Repository navigation
feat(proxy): push-based OTLP billable-request metering for enterprise deployments #31592
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 5 commits
8c20b55
fb1c18b
87adc8f
dd263fd
6484270
3f76aca
6f12dda
b64f299
291cfbf
b25c2d2
3271c0f
2e50567
382d11b
f0b217f
4f7f706
1b91dd4
91f5e26
1023072
f77c13e
a5b0f7c
37c6bad
269ee7e
baba77b
533b62c
f80510e
726eb1d
5933294
534ddfd
c109489
c6bb384
6d0a044
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| """ | ||
| Push-based OTLP metering for enterprise litellm deployments. | ||
|
|
||
| Owns a dedicated OpenTelemetry meter provider and an OTLP/HTTP exporter | ||
| authenticated to our global collector with a TLS client certificate. The | ||
| collector front end terminates mutual TLS: the client certificate presented | ||
| here is validated against our CA at the edge, and the verified subject is | ||
| what identifies the deployment. It is intentionally isolated from the global | ||
| meter provider so the customer's own OTEL metrics are untouched and ours | ||
| never leak into their backend. | ||
|
|
||
| The deployment's identity rides on the TLS client certificate, not on the | ||
| payload; the secret license key is never sent as an attribute or header. | ||
| """ | ||
|
|
||
| import os | ||
| from dataclasses import dataclass | ||
| from typing import TYPE_CHECKING, Optional, Union | ||
|
|
||
| from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter | ||
| from opentelemetry.metrics import Counter | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader | ||
| from opentelemetry.sdk.resources import Resource | ||
|
|
||
| from litellm._logging import verbose_proxy_logger | ||
| from litellm.proxy.middleware.billable_request_metrics_middleware import ( | ||
| BillableCategory, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from litellm.proxy._types import EnterpriseLicenseData | ||
|
|
||
| ENDPOINT_ENV = "LITELLM_BILLING_METRICS_ENDPOINT" | ||
| CLIENT_CERT_ENV = "LITELLM_BILLING_METRICS_CLIENT_CERT" | ||
| CLIENT_KEY_ENV = "LITELLM_BILLING_METRICS_CLIENT_KEY" | ||
| CA_CERT_ENV = "LITELLM_BILLING_METRICS_CA_CERT" | ||
| EXPORT_INTERVAL_ENV = "LITELLM_BILLING_METRICS_EXPORT_INTERVAL_MS" | ||
| DEFAULT_EXPORT_INTERVAL_MS = 60_000 | ||
| _METRICS_PATH = "/v1/metrics" | ||
|
|
||
| METRIC_NAME = "litellm.enterprise.billable_requests" | ||
| METER_NAME = "litellm.enterprise.billing" | ||
|
|
||
| AttributeValue = Union[str, int] | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class BillingMetricsConfig: | ||
| endpoint: str | ||
| client_cert_path: str | ||
| client_key_path: str | ||
| ca_cert_path: Optional[str] | ||
| export_interval_ms: int | ||
| litellm_version: str | ||
| license_id: Optional[str] | ||
|
|
||
|
|
||
| def _metrics_endpoint(endpoint: str) -> str: | ||
| """The OTLP/HTTP metric exporter wants the full URL including the signal path.""" | ||
| trimmed = endpoint.rstrip("/") | ||
| return trimmed if trimmed.endswith(_METRICS_PATH) else f"{trimmed}{_METRICS_PATH}" | ||
|
|
||
|
|
||
| def _resource_attributes(config: BillingMetricsConfig) -> dict[str, AttributeValue]: | ||
| base: dict[str, AttributeValue] = { | ||
| "service.name": "litellm-proxy", | ||
| "litellm.version": config.litellm_version, | ||
| } | ||
| license_attr: dict[str, AttributeValue] = {"litellm.license.id": config.license_id} if config.license_id else {} | ||
| return {**base, **license_attr} | ||
|
|
||
|
|
||
| def _billable_attributes( | ||
| category: BillableCategory, route: str, status_code: int, model_id: Optional[str] | ||
| ) -> dict[str, AttributeValue]: | ||
| base: dict[str, AttributeValue] = { | ||
| "litellm.endpoint.category": category.value, | ||
| "http.route": route, | ||
| "http.response.status_code": status_code, | ||
| } | ||
| model_attr: dict[str, AttributeValue] = {"litellm.model_id": model_id} if model_id else {} | ||
| return {**base, **model_attr} | ||
|
|
||
|
|
||
| def build_mtls_meter_provider(config: BillingMetricsConfig) -> MeterProvider: | ||
| """OTLP/HTTP exporter presenting a TLS client certificate. | ||
|
|
||
| The collector's load balancer terminates mutual TLS and validates the client | ||
| certificate against our CA. Server verification uses the system trust store | ||
| (the collector presents a public web-PKI certificate); ca_cert_path overrides | ||
| it only for private/test collectors. | ||
| """ | ||
| exporter = OTLPMetricExporter( | ||
| endpoint=_metrics_endpoint(config.endpoint), | ||
| # None -> exporter falls back to the system trust store. | ||
| certificate_file=config.ca_cert_path, | ||
| client_certificate_file=config.client_cert_path, | ||
| client_key_file=config.client_key_path, | ||
| ) | ||
| reader = PeriodicExportingMetricReader(exporter, export_interval_millis=config.export_interval_ms) | ||
| return MeterProvider(metric_readers=[reader], resource=Resource.create(_resource_attributes(config))) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: Replicas export conflicting cumulative counters Every process exports this cumulative counter with the same resource attributes, meter name, and dimensions. In deployments with multiple workers or replicas, independent writers can overlap under one OTLP stream identity; receivers may deduplicate overlapping streams, so some billable requests can be dropped. Add a stable, process-unique |
||
|
|
||
|
|
||
| class BillingMetricsRecorder: | ||
| """Increments one OTLP counter per billable request. The meter provider is injected (see the factory).""" | ||
|
|
||
| def __init__(self, provider: MeterProvider) -> None: | ||
| self._provider = provider | ||
| self._counter: Counter = provider.get_meter(METER_NAME).create_counter( | ||
| name=METRIC_NAME, | ||
| unit="{request}", | ||
| description="Count of 2xx HTTP requests to billable LLM/MCP/A2A endpoints", | ||
| ) | ||
|
|
||
| def record(self, *, category: BillableCategory, route: str, status_code: int, model_id: Optional[str]) -> None: | ||
| self._counter.add(1, _billable_attributes(category, route, status_code, model_id)) | ||
|
|
||
|
|
||
| def _export_interval_ms() -> int: | ||
| raw = os.getenv(EXPORT_INTERVAL_ENV) | ||
| if raw is None: | ||
| return DEFAULT_EXPORT_INTERVAL_MS | ||
| try: | ||
| return int(raw) | ||
| except ValueError: | ||
| verbose_proxy_logger.warning( | ||
| "Invalid %s=%r, falling back to %d ms", EXPORT_INTERVAL_ENV, raw, DEFAULT_EXPORT_INTERVAL_MS | ||
| ) | ||
| return DEFAULT_EXPORT_INTERVAL_MS | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Zero export interval acceptedMedium Severity The Reviewed by Cursor Bugbot for commit 6d0a044. Configure here. |
||
|
|
||
|
|
||
| def load_billing_metrics_config( | ||
| *, license_data: Optional["EnterpriseLicenseData"], litellm_version: str | ||
| ) -> Optional[BillingMetricsConfig]: | ||
| endpoint = os.getenv(ENDPOINT_ENV) | ||
| client_cert = os.getenv(CLIENT_CERT_ENV) | ||
| client_key = os.getenv(CLIENT_KEY_ENV) | ||
| # Optional: only for private/test collectors whose server cert is not on the | ||
| # public web PKI. The production collector needs no CA override. | ||
| ca_cert = os.getenv(CA_CERT_ENV) | ||
|
|
||
| missing = [ | ||
| name | ||
| for name, value in ( | ||
| (ENDPOINT_ENV, endpoint), | ||
| (CLIENT_CERT_ENV, client_cert), | ||
| (CLIENT_KEY_ENV, client_key), | ||
| ) | ||
| if not value | ||
| ] | ||
| if endpoint is None or client_cert is None or client_key is None: | ||
| verbose_proxy_logger.warning( | ||
| "Enterprise billing metrics disabled: licensed deployment missing config (%s)", | ||
| ", ".join(missing), | ||
| ) | ||
| return None | ||
|
|
||
| required_paths = [client_cert, client_key] + ([ca_cert] if ca_cert else []) | ||
| unreadable = [path for path in required_paths if not os.path.isfile(path)] | ||
| if unreadable: | ||
| verbose_proxy_logger.warning( | ||
| "Enterprise billing metrics disabled: certificate file(s) not found: %s", | ||
| ", ".join(unreadable), | ||
|
veria-ai[bot] marked this conversation as resolved.
Resolved
|
||
| ) | ||
| return None | ||
|
|
||
| return BillingMetricsConfig( | ||
| endpoint=endpoint, | ||
| client_cert_path=client_cert, | ||
| client_key_path=client_key, | ||
| ca_cert_path=ca_cert, | ||
| export_interval_ms=_export_interval_ms(), | ||
| litellm_version=litellm_version, | ||
| license_id=(license_data or {}).get("user_id"), | ||
| ) | ||
|
|
||
|
|
||
| def build_billing_metrics_recorder( | ||
| *, premium: bool, license_data: Optional["EnterpriseLicenseData"], litellm_version: str | ||
| ) -> Optional[BillingMetricsRecorder]: | ||
| """Build the recorder, or None when the deployment is not licensed or metering is unconfigured.""" | ||
| if not premium: | ||
| return None | ||
|
|
||
| config = load_billing_metrics_config(license_data=license_data, litellm_version=litellm_version) | ||
| if config is None: | ||
| return None | ||
|
|
||
| try: | ||
| return BillingMetricsRecorder(build_mtls_meter_provider(config)) | ||
| except Exception as exc: # noqa: BLE001 -- metering must never break proxy startup | ||
| verbose_proxy_logger.warning("Enterprise billing metrics disabled: failed to initialize exporter: %s", exc) | ||
| return None | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| """ | ||
| Counts billable HTTP requests on enterprise deployments. | ||
|
|
||
| A billable request is an inbound request to an LLM inference, MCP, or A2A | ||
| endpoint that returns a 2xx status. The actual export happens in an injected | ||
| recorder (see litellm.proxy.enterprise_billing.billing_metrics); when no | ||
| recorder is injected (non-enterprise, or metering misconfigured) this | ||
| middleware is a transparent pass-through. | ||
| """ | ||
|
|
||
| from enum import Enum | ||
| from typing import Callable, Optional, Protocol, Sequence, runtime_checkable | ||
|
|
||
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
|
|
||
| from litellm.proxy._types import LiteLLMRoutes | ||
|
|
||
|
|
||
| class BillableCategory(str, Enum): | ||
| LLM = "llm" | ||
| MCP = "mcp" | ||
| A2A = "a2a" | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class BillingRecorder(Protocol): | ||
| def record(self, *, category: BillableCategory, route: str, status_code: int, model_id: Optional[str]) -> None: ... | ||
|
|
||
|
|
||
| _MODEL_ID_HEADER = b"x-litellm-model-id" | ||
|
|
||
| # Ordered: a longer suffix that shares an ending with a shorter one must come | ||
| # first, e.g. "/chat/completions" before "/completions". This is the inference | ||
| # surface that writes a SpendLogs row on success -- the same population the | ||
| # admin UI usage page counts -- so the collector and the UI report the same | ||
| # number. LLM routes are POST-only inference calls; GET reads on the same | ||
| # resources (list/status/content) are not billable and are excluded by the | ||
| # method gate in classify_billable_request. | ||
| _LLM_ROUTE_SUFFIXES: tuple[str, ...] = ( | ||
| "/chat/completions", | ||
| "/completions", | ||
| "/embeddings", | ||
| "/responses", | ||
| "/rerank", | ||
| "/moderations", | ||
| "/images/generations", | ||
| "/images/edits", | ||
| "/images/variations", | ||
| "/audio/transcriptions", | ||
| "/audio/translations", | ||
| "/audio/speech", | ||
| "/messages", # Anthropic /v1/messages (count_tokens does not end with /messages) | ||
| "/videos", # create; GET list is excluded by the POST gate | ||
| "/remix", # /v1/videos/{id}/remix | ||
| "/ocr", | ||
| "/search", # /v1/search and /v1/vector_stores/{id}/search | ||
| "/rag/query", | ||
| "/rag/ingest", | ||
| ":generateContent", # Gemini-native /v1beta/models/{model}:generateContent | ||
| ":streamGenerateContent", | ||
| ) | ||
|
|
||
| # Provider passthrough prefixes (e.g. /bedrock/..., /vertex-ai/...) carry real | ||
| # inference calls that write SpendLogs rows, so they bill. Anchored to the | ||
| # routes enum so new providers are picked up without touching this module. | ||
| # /langfuse forwards observability traffic, not inference: it writes no | ||
| # SpendLogs row and must not bill. | ||
| _NON_BILLABLE_PASSTHROUGH_PREFIXES = frozenset({"/langfuse"}) | ||
| _PASSTHROUGH_PREFIXES: tuple[str, ...] = tuple( | ||
| prefix | ||
| for prefix in LiteLLMRoutes.mapped_pass_through_routes.value | ||
| if prefix not in _NON_BILLABLE_PASSTHROUGH_PREFIXES | ||
| ) | ||
|
|
||
|
|
||
| def _classify_llm_route(path: str) -> Optional[str]: | ||
| suffix_match = next((suffix for suffix in _LLM_ROUTE_SUFFIXES if path == suffix or path.endswith(suffix)), None) | ||
|
yassin-berriai marked this conversation as resolved.
Resolved
|
||
| if suffix_match is not None: | ||
| return suffix_match | ||
| # Deep passthrough paths only: the bare prefix itself is not an inference call. | ||
| return next((prefix for prefix in _PASSTHROUGH_PREFIXES if path.startswith(f"{prefix}/")), None) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: Non-inference passthrough requests are billed
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Checked this against what the proxy actually records, and prefix-based passthrough billing is deliberate; the metering unit here is requests the deployment itself counts as successful on its usage dashboard, not inference calls specifically. pass_through_async_success_handler (litellm/proxy/pass_through_endpoints/success_handler.py) dispatches success handlers for every successful passthrough call: when no provider-specific handler recognizes the subpath it falls back to StandardPassThroughResponseObject and still writes the SpendLogs row; only /langfuse (already excluded from billing) and AssemblyAI non-POST reads opt out. Verified on a live proxy: a 200 POST /openai/v1/assistants wrote a pass_through_endpoint success row in LiteLLM_SpendLogs and counts toward the dashboard successful requests exactly like a chat completion, so excluding it from the exported count would make enterprise metering drift below the number the customer sees on their own usage page, which is the parity invariant this feature is built around. The remaining asymmetry runs the safe direction only: non-POST passthrough calls (GET and DELETE reads) can write SpendLogs rows but never bill because of the POST gate, so any classifier-vs-dashboard mismatch is an undercount |
||
|
|
||
|
|
||
| def classify_billable_request(path: str, method: str = "POST") -> Optional[tuple[BillableCategory, str]]: | ||
| """Map a request path to its (category, normalized route), or None if not billable.""" | ||
| normalized = path.rstrip("/") or "/" | ||
|
|
||
| if normalized == "/mcp" or normalized.startswith("/mcp/"): | ||
| return (BillableCategory.MCP, "/mcp") | ||
| if normalized == "/v1/mcp" or normalized.startswith("/v1/mcp/"): | ||
|
veria-ai[bot] marked this conversation as resolved.
Resolved
|
||
| return (BillableCategory.MCP, "/v1/mcp") | ||
| if normalized == "/v1/a2a" or normalized.startswith("/v1/a2a/"): | ||
| return (BillableCategory.A2A, "/v1/a2a") | ||
| if normalized == "/a2a" or normalized.startswith("/a2a/"): | ||
| return (BillableCategory.A2A, "/a2a") | ||
|
yassin-berriai marked this conversation as resolved.
Resolved
|
||
|
|
||
| # Inference calls are POSTs; GETs on these paths are reads (list videos, | ||
| # fetch a response object), which write no SpendLogs row and must not bill. | ||
| if method.upper() != "POST": | ||
| return None | ||
|
|
||
| llm_route = _classify_llm_route(normalized) | ||
| if llm_route is not None: | ||
| return (BillableCategory.LLM, llm_route) | ||
| return None | ||
|
yassin-berriai marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def _extract_model_id(headers: Sequence[tuple[bytes, bytes]]) -> Optional[str]: | ||
| return next( | ||
| (value.decode("latin-1") for name, value in headers if name.lower() == _MODEL_ID_HEADER and value), | ||
| None, | ||
| ) | ||
|
|
||
|
|
||
| class BillableRequestMetricsMiddleware: | ||
| """ | ||
| Pure ASGI middleware that records one billable request per 2xx response to a | ||
| billable endpoint. Modeled on InFlightRequestsMiddleware: it wraps `send`, | ||
| reads the final status and the x-litellm-model-id header off the | ||
| `http.response.start` message, and never blocks or fails the request path. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| app: ASGIApp, | ||
| recorder: Optional[BillingRecorder] = None, | ||
| recorder_factory: Optional[Callable[[], Optional[BillingRecorder]]] = None, | ||
| ) -> None: | ||
| self.app = app | ||
| self.recorder = recorder | ||
| # The factory defers recorder construction to the first request, AFTER the | ||
| # startup event has loaded the YAML config's environment_variables (license | ||
| # and cert env vars). Building at import time captured recorder=None for | ||
| # deployments configured that way. Resolved exactly once; the result | ||
| # (including None) is cached. | ||
| self._recorder_factory = recorder_factory | ||
| self._resolved = recorder_factory is None | ||
|
|
||
| def _resolve_recorder(self) -> Optional[BillingRecorder]: | ||
| if not self._resolved: | ||
| factory = self._recorder_factory | ||
| self.recorder = factory() if factory is not None else self.recorder | ||
| self._resolved = True | ||
| return self.recorder | ||
|
yassin-berriai marked this conversation as resolved.
Resolved
|
||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| recorder = self._resolve_recorder() | ||
| if recorder is None: | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| classification = classify_billable_request(scope.get("path", ""), scope.get("method", "POST")) | ||
| if classification is None: | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| category, route = classification | ||
| status_code = 0 | ||
| model_id: Optional[str] = None | ||
|
|
||
| async def send_wrapper(message: Message) -> None: | ||
| nonlocal status_code, model_id | ||
| if message["type"] == "http.response.start": | ||
| status_code = message["status"] | ||
| model_id = _extract_model_id(message.get("headers", [])) | ||
| await send(message) | ||
|
|
||
| await self.app(scope, receive, send_wrapper) | ||
|
|
||
| if 200 <= status_code < 300: | ||
| recorder.record(category=category, route=route, status_code=status_code, model_id=model_id) | ||
|
yassin-berriai marked this conversation as resolved.
Resolved
|
||


Uh oh!
There was an error while loading. Please reload this page.