Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

perf(prometheus): render /metrics off the event loop and coalesce concurrent scrapes (#37702)

devin-ai-integration[bot]3d3946059da1
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index 6df04ff622d..76066f4a305 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -4067,9 +4067,10 @@ class PrometheusLogger(CustomLogger):
require_auth (bool, optional): Whether to require authentication for the metrics endpoint.
Defaults to False.
"""
- from prometheus_client import make_asgi_app
+ from prometheus_client import REGISTRY
from litellm._logging import verbose_proxy_logger
+ from litellm.integrations.prometheus_metrics_endpoint import make_metrics_asgi_app
from litellm.proxy.proxy_server import app
# Create metrics ASGI app
@@ -4078,9 +4079,9 @@ class PrometheusLogger(CustomLogger):
registry: Final = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
- metrics_app = make_asgi_app(registry)
+ metrics_app = make_metrics_asgi_app(registry)
else:
- metrics_app = make_asgi_app()
+ metrics_app = make_metrics_asgi_app(REGISTRY)
# Mount the metrics app to the app
app.mount("/metrics", metrics_app)
diff --git a/litellm/integrations/prometheus_metrics_endpoint.py b/litellm/integrations/prometheus_metrics_endpoint.py
new file mode 100644
index 00000000000..b41cc13a04f
--- /dev/null
+++ b/litellm/integrations/prometheus_metrics_endpoint.py
@@ -0,0 +1,100 @@
+"""ASGI app for `/metrics` that keeps registry rendering off the event loop.
+
+``prometheus_client.make_asgi_app`` collects and serializes the whole registry
+inline in the coroutine, so a large scrape (tens of MB on high cardinality
+deployments) blocks every other request on the loop for its whole duration. This
+app renders in a worker thread instead, shares one render across concurrent
+scrapes that want the same output, and streams the payload back in chunks.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import gzip
+from collections.abc import Callable, Iterator, Mapping
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Final
+
+from prometheus_client import CollectorRegistry
+from prometheus_client.exposition import choose_encoder, gzip_accepted
+from starlette.requests import Request
+from starlette.responses import StreamingResponse
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+RESPONSE_CHUNK_SIZE_BYTES: Final = 64 * 1024
+
+_GZIP_HEADERS: Final = MappingProxyType({"Content-Encoding": "gzip"})
+
+
+@dataclass(frozen=True, slots=True)
+class ScrapeRequest:
+ """What a scrape asks for, normalized so that header spellings sharing an output share a render."""
+
+ encoder: Callable[[CollectorRegistry], bytes]
+ content_type: str
+ gzipped: bool
+ metric_names: tuple[str, ...]
+
+
+def parse_scrape_request(accept: str, accept_encoding: str, metric_names: tuple[str, ...]) -> ScrapeRequest:
+ encoder, content_type = choose_encoder(accept)
+ return ScrapeRequest(
+ encoder=encoder,
+ content_type=content_type,
+ gzipped=gzip_accepted(accept_encoding),
+ metric_names=metric_names,
+ )
+
+
+def render_scrape(registry: CollectorRegistry, request: ScrapeRequest) -> bytes:
+ rendered: Final = request.encoder(
+ registry.restricted_registry(request.metric_names) if request.metric_names else registry # pyright: ignore[reportArgumentType] # RestrictedRegistry is registry-shaped but not a subclass
+ )
+ return gzip.compress(rendered) if request.gzipped else rendered
+
+
+class CoalescedScrapeRenderer:
+ """Renders the registry in a worker thread, sharing one render per distinct output across concurrent scrapes."""
+
+ def __init__(self, registry: CollectorRegistry) -> None:
+ self._registry = registry
+ self._inflight: Mapping[ScrapeRequest, asyncio.Task[bytes]] = MappingProxyType({})
+
+ def _forget(self, finished: asyncio.Task[bytes]) -> None:
+ self._inflight = MappingProxyType({key: task for key, task in self._inflight.items() if task is not finished})
+
+ async def render(self, request: ScrapeRequest) -> bytes:
+ inflight: Final = self._inflight.get(request)
+ if inflight is not None:
+ return await asyncio.shield(inflight)
+
+ task: Final = asyncio.create_task(asyncio.to_thread(render_scrape, self._registry, request))
+ self._inflight = MappingProxyType({**self._inflight, request: task})
+ task.add_done_callback(self._forget)
+ return await asyncio.shield(task)
+
+
+def _chunks(body: bytes) -> Iterator[bytes]:
+ return (body[start : start + RESPONSE_CHUNK_SIZE_BYTES] for start in range(0, len(body), RESPONSE_CHUNK_SIZE_BYTES))
+
+
+def make_metrics_asgi_app(registry: CollectorRegistry) -> ASGIApp:
+ renderer: Final = CoalescedScrapeRenderer(registry)
+
+ async def metrics_app(scope: Scope, receive: Receive, send: Send) -> None:
+ request: Final = Request(scope, receive)
+ scrape: Final = parse_scrape_request(
+ accept=request.headers.get("accept", ""),
+ accept_encoding=request.headers.get("accept-encoding", ""),
+ metric_names=tuple(request.query_params.getlist("name[]")),
+ )
+ body: Final = await renderer.render(scrape)
+ response: Final = StreamingResponse(
+ _chunks(body),
+ media_type=scrape.content_type,
+ headers=_GZIP_HEADERS if scrape.gzipped else None,
+ )
+ await response(scope, receive, send)
+
+ return metrics_app
diff --git a/tests/test_litellm/integrations/test_prometheus_metrics_endpoint.py b/tests/test_litellm/integrations/test_prometheus_metrics_endpoint.py
new file mode 100644
index 00000000000..f0e6495ba22
--- /dev/null
+++ b/tests/test_litellm/integrations/test_prometheus_metrics_endpoint.py
@@ -0,0 +1,276 @@
+"""The /metrics app must render off the event loop, coalesce concurrent scrapes and stream chunks."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Final
+
+import httpx
+import pytest
+from prometheus_client import CollectorRegistry, Gauge
+from prometheus_client.metrics_core import GaugeMetricFamily
+from prometheus_client.registry import Collector
+
+from litellm.integrations.prometheus_metrics_endpoint import (
+ RESPONSE_CHUNK_SIZE_BYTES,
+ make_metrics_asgi_app,
+)
+
+_GATE_TIMEOUT_SECONDS: Final = 10.0
+_SECOND_SCRAPE_SETTLE_SECONDS: Final = 0.2
+
+
+class _SlowCollector(Collector):
+ """Blocking collector standing in for a large registry render."""
+
+ def __init__(self, block_seconds: float, sample_count: int = 1) -> None:
+ self.block_seconds = block_seconds
+ self.sample_count = sample_count
+ self.collect_calls = 0
+
+ def collect(self) -> Iterator[GaugeMetricFamily]:
+ self.collect_calls += 1
+ time.sleep(self.block_seconds)
+ family: Final = GaugeMetricFamily("slow_metric", "slow", labels=("idx",))
+ for idx in range(self.sample_count):
+ family.add_metric((str(idx),), 1.0)
+ yield family
+
+
+def _client(registry: CollectorRegistry) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=make_metrics_asgi_app(registry)),
+ base_url="http://metrics.test",
+ )
+
+
+def _registry_with(collector: Collector) -> CollectorRegistry:
+ registry: Final = CollectorRegistry()
+ registry.register(collector)
+ return registry
+
+
+async def _scrape(client: httpx.AsyncClient, headers: Mapping[str, str] | None = None) -> httpx.Response:
+ return await client.get("/metrics", headers=headers)
+
+
+async def test_render_does_not_block_the_event_loop():
+ ticks: Final[list[float]] = [] # mutable-ok: records loop wakeups while the scrape is in flight
+
+ async def ticker() -> None:
+ while True:
+ await asyncio.sleep(0.01)
+ ticks.append(time.monotonic())
+
+ ticker_task: Final = asyncio.create_task(ticker())
+ async with _client(_registry_with(_SlowCollector(block_seconds=0.5))) as client:
+ try:
+ response: Final = await _scrape(client)
+ finally:
+ ticker_task.cancel()
+
+ assert b"slow_metric" in response.content
+ assert len(ticks) > 5, "event loop was blocked while the registry was rendered"
+
+
+async def test_concurrent_identical_scrapes_share_one_render():
+ collector: Final = _SlowCollector(block_seconds=0.2)
+ async with _client(_registry_with(collector)) as client:
+ responses: Final[Sequence[httpx.Response]] = await asyncio.gather(*(_scrape(client) for _ in range(5)))
+
+ assert collector.collect_calls == 1
+ for response in responses:
+ assert b"slow_metric" in response.content
+
+
+async def test_sequential_scrapes_are_rendered_fresh():
+ collector: Final = _SlowCollector(block_seconds=0.0)
+ async with _client(_registry_with(collector)) as client:
+ await _scrape(client)
+ await _scrape(client)
+
+ assert collector.collect_calls == 2
+
+
+async def test_gzip_is_used_when_the_scraper_accepts_it():
+ registry: Final = CollectorRegistry()
+ Gauge("plain_metric", "plain", registry=registry).set(1)
+
+ async with _client(registry) as client:
+ compressed: Final = await _scrape(client, headers={"accept-encoding": "gzip"})
+ plain: Final = await _scrape(client, headers={"accept-encoding": "identity"})
+
+ assert compressed.headers["content-encoding"] == "gzip"
+ assert "content-encoding" not in plain.headers
+ assert compressed.content == plain.content
+ assert b"plain_metric" in plain.content
+
+
+async def test_name_filter_restricts_the_rendered_registry():
+ registry: Final = CollectorRegistry()
+ Gauge("wanted_metric", "wanted", registry=registry).set(1)
+ Gauge("other_metric", "other", registry=registry).set(1)
+
+ async with _client(registry) as client:
+ response: Final = await client.get("/metrics", params={"name[]": "wanted_metric"})
+
+ assert b"wanted_metric" in response.content
+ assert b"other_metric" not in response.content
+
+
+async def test_large_payload_is_streamed_in_chunks():
+ registry: Final = _registry_with(_SlowCollector(block_seconds=0.0, sample_count=5000))
+ chunk_sizes: Final[list[int]] = [] # mutable-ok: records the ASGI body parts the app emitted
+
+ async def send(message: Mapping[str, object]) -> None:
+ if message["type"] == "http.response.body":
+ body = message["body"]
+ assert isinstance(body, bytes)
+ chunk_sizes.append(len(body))
+
+ incoming: Final = iter(({"type": "http.request", "body": b"", "more_body": False},))
+
+ async def receive() -> Mapping[str, object]:
+ request: Final = next(incoming, None)
+ if request is not None:
+ return request
+ await asyncio.Event().wait()
+ return {"type": "http.disconnect"}
+
+ app: Final = make_metrics_asgi_app(registry)
+ await app(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/metrics",
+ "headers": (),
+ "query_string": b"",
+ },
+ receive,
+ send,
+ )
+
+ assert sum(chunk_sizes) > RESPONSE_CHUNK_SIZE_BYTES
+ assert len(chunk_sizes) > 2
+ assert max(chunk_sizes) <= RESPONSE_CHUNK_SIZE_BYTES
+
+
+class _GatedCollector(Collector):
+ """Blocking collector that parks in the worker thread until the test releases it."""
+
+ def __init__(self) -> None:
+ self.started = threading.Event()
+ self.release = threading.Event()
+ self._lock = threading.Lock()
+ self.collect_calls = 0
+
+ def collect(self) -> Iterator[GaugeMetricFamily]:
+ with self._lock:
+ self.collect_calls += 1
+ self.started.set()
+ self.release.wait(timeout=_GATE_TIMEOUT_SECONDS)
+ family: Final = GaugeMetricFamily("gated_metric", "gated")
+ family.add_metric((), 1.0)
+ yield family
+
+
+async def _scrape_pair_concurrently(
+ registry: CollectorRegistry, collector: _GatedCollector, headers: Sequence[Mapping[str, str]]
+) -> Sequence[httpx.Response]:
+ """Issue the second scrape only once the first one's render is parked inside the worker thread."""
+ async with _client(registry) as client:
+ try:
+ first: Final = asyncio.create_task(_scrape(client, headers=headers[0]))
+ assert await asyncio.to_thread(collector.started.wait, _GATE_TIMEOUT_SECONDS), "first render never started"
+ second: Final = asyncio.create_task(_scrape(client, headers=headers[1]))
+ await asyncio.sleep(_SECOND_SCRAPE_SETTLE_SECONDS)
+ collector.release.set()
+ return await asyncio.gather(first, second)
+ finally:
+ collector.release.set()
+
+
[email protected]("reverse", (False, True), ids=("as-listed", "reversed"))
+ "spellings",
+ (
+ ({"accept-encoding": "gzip"}, {"accept-encoding": "gzip, deflate"}),
+ ({"accept": "*/*"}, {"accept": "text/plain;version=0.0.4;q=0.5,*/*;q=0.1"}),
+ ),
+ ids=("accept-encoding", "accept"),
+)
+async def test_header_spellings_with_the_same_output_share_one_render(
+ spellings: Sequence[Mapping[str, str]], reverse: bool
+):
+ collector: Final = _GatedCollector()
+ ordered: Final = tuple(reversed(spellings)) if reverse else spellings
+
+ responses: Final = await _scrape_pair_concurrently(_registry_with(collector), collector, ordered)
+
+ assert collector.collect_calls == 1, "the second scrape rendered the registry again instead of joining the first"
+ for response in responses:
+ assert b"gated_metric" in response.content
+
+
+async def test_different_output_formats_are_rendered_separately():
+ collector: Final = _GatedCollector()
+
+ responses: Final = await _scrape_pair_concurrently(
+ _registry_with(collector),
+ collector,
+ ({"accept": "text/plain"}, {"accept": "application/openmetrics-text"}),
+ )
+
+ assert collector.collect_calls == 2, "scrapes wanting different exposition formats must not share a render"
+ assert responses[0].headers["content-type"] != responses[1].headers["content-type"]
+
+
+async def test_concurrent_gzip_and_plain_scrapes_each_get_their_own_encoding():
+ collector: Final = _GatedCollector()
+
+ responses: Final = await _scrape_pair_concurrently(
+ _registry_with(collector),
+ collector,
+ ({"accept-encoding": "gzip"}, {"accept-encoding": "identity"}),
+ )
+
+ assert collector.collect_calls == 2, "scrapes wanting different content encodings must not share a render"
+ assert responses[0].headers["content-encoding"] == "gzip"
+ assert "content-encoding" not in responses[1].headers
+ for response in responses:
+ assert b"gated_metric" in response.content
+
+
+async def test_a_finishing_render_does_not_evict_another_that_is_still_in_flight():
+ collector: Final = _GatedCollector()
+ async with _client(_registry_with(collector)) as client:
+ try:
+ parked: Final = asyncio.create_task(_scrape(client))
+ assert await asyncio.to_thread(collector.started.wait, _GATE_TIMEOUT_SECONDS), "first render never started"
+
+ unrelated: Final = await client.get("/metrics", params={"name[]": "no_such_metric"})
+ assert unrelated.status_code == 200
+
+ joiner: Final = asyncio.create_task(_scrape(client))
+ await asyncio.sleep(_SECOND_SCRAPE_SETTLE_SECONDS)
+ collector.release.set()
+ responses: Final = await asyncio.gather(parked, joiner)
+ finally:
+ collector.release.set()
+
+ assert collector.collect_calls == 1, "an unrelated render finishing evicted the render still in flight"
+ for response in responses:
+ assert b"gated_metric" in response.content