Skip to content

[Draft] [serve] Prometheus metrics for AutoscalingConfig - #56851

Open
arcyleung wants to merge 2 commits into
ray-project:masterfrom
arcyleung:prometheus-metrics
Open

arcyleung wants to merge 2 commits into
ray-project:masterfrom
arcyleung:prometheus-metrics

Conversation

@arcyleung

@arcyleung arcyleung commented Sep 23, 2025 •

Copy link
Copy Markdown
Contributor

Implementation of AutoscalingConfig prometheus_custom_metrics:
image

Why are these changes needed?

Support collection of Prometheus exporter metrics at each replica, and report them to the controller, if the serve config AutoscalingConfig specifies.

Related issue number

Checks


Note

Adds optional per-replica Prometheus metric collection for autoscaling, refactors Prometheus helpers into a shared module, and updates proto/config/constants/replica logic and tests.

  • Serve autoscaling (backend):
    • Enable collecting custom Prometheus metrics per replica when AutoscalingConfig.prometheus_metrics is set; fetched at RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST and merged into autoscaling reports.
    • Extend replica metrics manager to asynchronously fetch/filter metrics by replica label and include alongside ongoing-requests/custom metrics.
  • Config/Proto:
    • Add prometheus_metrics to AutoscalingConfig (Python) and new proto messages PrometheusCustomMetrics/PrometheusMetric; map list ↔ proto on (de)serialization.
    • Update JSON surfaces and defaults accordingly.
  • Constants:
    • Introduce RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST env var for exporter host.
  • Prometheus utilities:
    • New python/ray/_private/prometheus_utils.py with fetch/parse/filter helpers and async fetch; remove duplicated logic from test_utils and update imports across tests/benchmarks.
  • Tests/BUILD:
    • Add test_prometheus_autoscaling_metrics.py; adjust existing tests and BUILD to include env and new imports; minor test stability tweaks.

Written by Cursor Bugbot for commit 02a540c. This will update automatically on new commits. Configure here.

@arcyleung
arcyleung requested a review from a team as a code owner September 23, 2025 21:40
@arcyleung arcyleung changed the title [serve] Prometheus metrics [serve] Prometheus metrics for AutoscalingConfig Sep 23, 2025

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for collecting Prometheus metrics for autoscaling decisions in Ray Serve. The changes include updates to the configuration and protobuf definitions, and new logic in the replica to fetch metrics from a Prometheus endpoint. While the feature is a valuable addition, I've found a few critical issues in the implementation. The logic for fetching metrics is incorrect for labeled metrics (like histograms), which will lead to unexpected behavior. There's also a potential TypeError if Prometheus metrics are not configured. Additionally, the tests for this new feature could be strengthened to catch these kinds of issues. My review includes specific suggestions to address these points.

Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment on lines +22 to +42
def check_autoscaling_metrics_include_prometheus(
client, deployment_id: DeploymentID, expected_metrics: List[str]
) -> bool:
"""Check that autoscaling metrics include the expected prometheus metrics."""

try:
metrics = get_autoscaling_metrics_from_controller(client, deployment_id)
# The metrics should include both ongoing requests and prometheus custom metrics
if not metrics:
print("No metrics returned from controller!")
return False

# For prometheus custom metrics, we expect the keys to be present in the dict
for expected_metric in expected_metrics:
if expected_metric not in metrics:
print(f"Expected metric {expected_metric} not found")
return False
return True
except Exception as e:
print(f"Error checking metrics: {e}")
return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The test helper check_autoscaling_metrics_include_prometheus and the associated tests are not strong enough. They only check for the presence of the metric key in the results, not the correctness of its value. Because the implementation falls back to 0.0 on any error (including metric not found), the tests will pass even if the metric fetching logic is broken.

To make the tests more robust, they should be updated to:

  1. Use a simple, predictable metric for testing (e.g., a gauge that you can set manually).
  2. Assert that the fetched metric value is correct, not just that the key exists.

This will help catch bugs like the incorrect handling of histogram metrics.

cursor[bot]

This comment was marked as outdated.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation community-contribution Contributed by the community labels Sep 24, 2025
cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Sep 25, 2025
cursor[bot]

This comment was marked as outdated.

Comment thread python/ray/serve/config.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Outdated
for metric_name in prometheus_metrics:
if metric_name in metric_samples_by_name:
# Get the latest sample for this metric
samples = metric_samples_by_name[metric_name]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we handle counters, gauges, and histogram metrics?

@arcyleung arcyleung Oct 1, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we let the autoscaling policy handle the raw Prometheus metrics? Or you mean we need to deserialize them back into each class found in metrics.py (Counter, Gauge, Histogram)?

Otherwise, the only processing I do in _fetch_prometheus_metrics is filter metric Samples with the matching replica_id.

@arcyleung
arcyleung requested a review from a team as a code owner October 1, 2025 02:05
cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

Comment thread python/ray/_common/prometheus_utils.py Outdated
@@ -0,0 +1,266 @@
"""Utilities for fetching and parsing Prometheus metrics.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assuming this is used by libraries? If so lets move it to _common folder.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a problem with importing aiohttp outside ray serve, it appears to be blacklisted in the installation script in /ray/ci/env/check_minimal_install.py

@arcyleung
arcyleung requested a review from edoakes as a code owner October 2, 2025 14:20
Comment thread python/ray/serve/config.py Outdated

# Prometheus metrics which will be collected at each replica, which will be available in the custom AutoscalingPolicy function
# List of metric_names
prometheus_metrics: Optional[List[str]] = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i believe it would be better if we can make it a field and provide description.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread python/ray/serve/_private/constants.py Resolved
Comment thread python/ray/serve/_private/replica.py Outdated
if self._autoscaling_config and self.should_collect_ongoing_requests():
self.start_metrics_pusher()
if self._autoscaling_config:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UNL

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines +318 to +326
if self._autoscaling_config.prometheus_metrics:
self._prometheus_metrics_enabled = True
self._prometheus_queries = autoscaling_config.prometheus_metrics
self.start_metrics_pusher()
return

elif self.should_collect_ongoing_requests():
self.start_metrics_pusher()
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function is anyway ending here, we can just put one if condition for the

if self._autoscaling_config.prometheus_metrics:
                self._prometheus_metrics_enabled = True
                self._prometheus_queries = autoscaling_config.prometheus_metrics

and then we should start the metrics pusher and return

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines +318 to +326
if self._autoscaling_config.prometheus_metrics:
self._prometheus_metrics_enabled = True
self._prometheus_queries = autoscaling_config.prometheus_metrics
self.start_metrics_pusher()
return

elif self.should_collect_ongoing_requests():
self.start_metrics_pusher()
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if self._autoscaling_config.prometheus_metrics:
self._prometheus_metrics_enabled = True
self._prometheus_queries = autoscaling_config.prometheus_metrics
self.start_metrics_pusher()
return
elif self.should_collect_ongoing_requests():
self.start_metrics_pusher()
return
if self._autoscaling_config.prometheus_metrics:
self._prometheus_metrics_enabled = True
self._prometheus_queries = autoscaling_config.prometheus_metrics
self.start_metrics_pusher()
return

@arcyleung arcyleung Oct 17, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pusher should only be started only if there's either prometheus_metrics or should_collect_ongoing_requests, otherwise each replica just pushes empty metrics and wastes compute. See #56005 (comment)

Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/serve/_private/replica.py Outdated
prom_addr = RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST
logger.debug(f"Fetching metrics from prometheus exporter at {prom_addr}")

metrics_text = await fetch_prometheus_metrics_async(

@harshit-anyscale harshit-anyscale Oct 7, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there any prometheus API which can return us the exact metrics we are looking for? IIUC, this will fetch all prom metrics in our memory, and then we will find the metrics which are helpful to us.

@arcyleung arcyleung Oct 9, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my first implementation it will query the Prometheus Server which supported PromQL filtering. However as you say this current implementation will get everything from Prometheus Exporter. As Abrar suggested I will switch back to the first original implementation.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

cursor[bot]

This comment was marked as outdated.

Comment thread python/ray/serve/tests/BUILD.bazel Outdated
"RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE": "0",
"RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S": "0.5",
"RAY_SERVE_RECORD_AUTOSCALING_STATS_TIMEOUT_S": "3",
"RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST": "http://localhost:9090",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Double HTTP prefix in Prometheus URL construction

The environment variable RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST is set to "http://localhost:9090" in the test configuration, but the fetch_from_prom_server function in prometheus_utils.py already prepends "http://" to the address parameter when constructing the URL. This results in a malformed URL like "http://http://localhost:9090/api/v1/query" with a double HTTP prefix, which will cause Prometheus queries to fail. The environment variable should be set to just "localhost:9090" without the protocol prefix.

Fix in Cursor Fix in Web

Comment thread README.rst Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/_private/test_utils.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@arcyleung

Copy link
Copy Markdown
Contributor Author

Update (agent pass)

Pushed tip b28a362 on arcyleung:prometheus-metrics with:

  • Node-local Prometheus query cache/dedup (in-process + on-disk TTL + file lock) so co-located replicas do not N× hit the same host/query
  • Host scheme normalization (fixes double http://); empty default host with explicit error when prometheus_metrics set without env
  • Controller probe uses RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST (no hardcoded localhost:9090)
  • Unified set_autoscaling_config so missing Prom host does not skip other metrics collection
  • Tests assert metric values, not only key presence; added test_prometheus_query_cache.py
  • Local multi-node docker harness under python/ray/serve/tests/multi_node_prometheus/

Note on full rebase onto latest master: a clean replay onto current ray-project/ray master exists locally (prometheus-metrics-rebased, git merge-base --is-ancestor upstream/master HEAD passes) but force-pushing that history is blocked by the PAT lacking the workflow scope (new upstream file .github/workflows/notify-slack-on-label.yml). Re-push of the full rebased history needs a token with workflow (or SSH key on the account).

Cursor/Gemini comment themes addressed on tip are documented in the agent review notes (DI handler, double URL prefix, hardcoded host, value extraction, early-return metrics, etc.).

@arcyleung
arcyleung force-pushed the prometheus-metrics branch from b28a362 to 1c4e48e Compare July 3, 2026 00:25
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch 2 times, most recently from d7c2dc5 to eff744f Compare July 3, 2026 01:11
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch from eff744f to a01e551 Compare July 3, 2026 01:17
Comment thread python/ray/_common/prometheus_utils.py Resolved
Comment thread python/ray/_common/prometheus_utils.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch from a01e551 to dbe2074 Compare July 3, 2026 01:23
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch from dbe2074 to 1a24c41 Compare July 3, 2026 01:42
Comment thread python/ray/_common/prometheus_utils.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch 3 times, most recently from 3367542 to 09270c7 Compare July 3, 2026 02:11

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 09270c7. Configure here.

Comment thread python/ray/serve/_private/constants.py Resolved
@arcyleung
arcyleung force-pushed the prometheus-metrics branch from 09270c7 to 2f3889c Compare July 3, 2026 03:43
Arthur Leung added 2 commits July 3, 2026 19:34
Add AutoscalingConfig.prometheus_metrics and replica-side PromQL collection
with a node-local TTL cache so co-located replicas sharing host/query do not
N× hit Prometheus. Configured expressions are queried as-is. Prometheus JSON
status=error raises instead of being treated as empty samples.

Signed-off-by: Arthur Leung <[email protected]>
Core unit coverage: value extraction, co-located cache dedup, Prom error
status handling, zero-TTL, and replica fetch path with co-located ids.

Signed-off-by: Arthur Leung <[email protected]>
@arcyleung

Copy link
Copy Markdown
Contributor Author

Review disposition (rebased tip)

Human review threads (abrarsheikh / jjyao / harshit) are addressed on the current tip or declined with rationale:

  • Done: prometheus_metrics Field+description; PromQL utils in ray._common.prometheus_utils; unified set_autoscaling_config (start/stop pusher); empty host errors; default 10s timeout; co-located node-local cache; queries as-is (no forced replica= rewrite).
  • Declined rename to prometheus_custom_metrics — keep shorter public name; list values are PromQL/names (see field description).
  • Histogram/counters: use PromQL in the list (e.g. histogram_quantile(...)); we extract instant vector/scalar samples as floats.

Also on tip: raise on Prometheus JSON status=error (do not cache as empty); removed unused Serve-side TTL constant (env still honored in _common).

Rebased onto latest ray-project/ray master; tip will be the SHA on this branch after push.

@arcyleung
arcyleung force-pushed the prometheus-metrics branch from 2f3889c to 193d82a Compare July 3, 2026 23:34

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community docs An issue or change related to documentation go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants