Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
8c20b55
feat(proxy): push-based OTLP billable-request metering for enterprise…
yassin-berriai Jun 29, 2026
fb1c18b
fix(proxy): align billable-request metering with the global collector
yassin-berriai Jul 7, 2026
87adc8f
fix(proxy): wrap enterprise billing import in try-except per code-qua…
yassin-berriai Jul 7, 2026
dd263fd
chore: satisfy strict lint gates in billing modules
yassin-berriai Jul 7, 2026
6484270
fix(proxy): bill provider passthrough, search, and rag routes
yassin-berriai Jul 7, 2026
3f76aca
fix(proxy): bill MCP and A2A requests by protocol transport routes only
yassin-berriai Jul 8, 2026
6f12dda
fix(proxy): harden billable-request classification and recorder lifec…
yassin-berriai Jul 9, 2026
b64f299
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
yassin-berriai Jul 9, 2026
291cfbf
chore(ui): regenerate eslint metrics after staging merge
yassin-berriai Jul 9, 2026
b25c2d2
docs(proxy): state the lower-bound billing contract in middleware com…
yassin-berriai Jul 9, 2026
3271c0f
fix(proxy): bill mcp-rest tool calls and bare a2a agent invokes
yassin-berriai Jul 9, 2026
2e50567
fix(proxy): flush billable-request counts on proxy shutdown
yassin-berriai Jul 9, 2026
382d11b
fix(proxy): stop billing bare a2a task RPCs and close the shutdown race
yassin-berriai Jul 9, 2026
f0b217f
test(proxy): stub the OTLP exporter in the recorder-build test
yassin-berriai Jul 9, 2026
4f7f706
fix(helm): truncate the helm.sh/chart label to 63 bytes
yassin-berriai Jul 9, 2026
1b91dd4
feat(proxy): accept inline PEM for the billing-metrics mTLS credentials
yassin-berriai Jul 9, 2026
91f5e26
feat(helm): add first-class billingMetrics values to the componentize…
yassin-berriai Jul 9, 2026
1023072
feat(terraform): billing-metrics variables for the aws and gcp templates
yassin-berriai Jul 9, 2026
f77c13e
feat(helm): add billingMetrics values to the classic chart
yassin-berriai Jul 9, 2026
a5b0f7c
test(helm): pin that the migrations job never mounts the billing cert
yassin-berriai Jul 9, 2026
37c6bad
fix(helm): meter the backend too, it serves the MCP transport
yassin-berriai Jul 9, 2026
269ee7e
fix(proxy): never log billing credential values when they fail to res…
yassin-berriai Jul 9, 2026
baba77b
Revert "fix(helm): truncate the helm.sh/chart label to 63 bytes"
yassin-berriai Jul 9, 2026
533b62c
feat(helm): default billingMetrics.secretName to the conventional name
yassin-berriai Jul 9, 2026
f80510e
feat(proxy): log once when billing metrics are actually enabled
yassin-berriai Jul 9, 2026
726eb1d
fix(terraform): fail the plan on a partial billing-metrics config
yassin-berriai Jul 9, 2026
5933294
docs(terraform): record why the billing guard sits on the gateway res…
yassin-berriai Jul 9, 2026
534ddfd
fix(terraform): guard the backend against a partial billing config too
yassin-berriai Jul 9, 2026
c109489
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
yassin-berriai Jul 15, 2026
c6bb384
docs(team): document mcp_rpm_limit in update_team docstring
yassin-berriai Jul 15, 2026
6d0a044
chore(ui): regenerate schema.d.ts for update_team docstring change
yassin-berriai Jul 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
194 changes: 194 additions & 0 deletions litellm/proxy/enterprise_billing/billing_metrics.py
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)))
Comment thread
yassin-berriai marked this conversation as resolved.
Resolved

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: 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 service.instance.id resource attribute, such as an instance identifier combined with the PID or a UUID generated when the provider is built.



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

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.

Zero export interval accepted

Medium Severity

The _export_interval_ms function allows zero or negative values for LITELLM_BILLING_METRICS_EXPORT_INTERVAL_MS. This can cause the PeriodicExportingMetricReader to export metrics continuously or excessively, leading to unnecessary CPU contention and system load.

Fix in Cursor Fix in Web

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),
Comment thread
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
175 changes: 175 additions & 0 deletions litellm/proxy/middleware/billable_request_metrics_middleware.py
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)
Comment thread
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)

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: Non-inference passthrough requests are billed

_PASSTHROUGH_PREFIXES includes broad provider prefixes such as /openai, and this branch records any successful POST below them. An authenticated caller can repeatedly send successful non-inference passthrough requests like POST /openai/v1/assistants or thread/resource creation calls and have them counted as billable LLM requests even though they are not inference calls; classify passthroughs by known inference subpaths instead of the provider prefix alone.

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.

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/"):
Comment thread
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")
Comment thread
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
Comment thread
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
Comment thread
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)
Comment thread
yassin-berriai marked this conversation as resolved.
Resolved
Loading
Loading