Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llm-gateway): capture rate limit denial events to PostHog (#58664)

Peter Kirkhame94d3fc1279b
diff --git a/services/llm-gateway/src/llm_gateway/auth/models.py b/services/llm-gateway/src/llm_gateway/auth/models.py
index 1e732d470019..5bcad3e287cd 100644
--- a/services/llm-gateway/src/llm_gateway/auth/models.py
+++ b/services/llm-gateway/src/llm_gateway/auth/models.py
@@ -13,6 +13,14 @@ class AuthenticatedUser:
application_id: str | None = None
+def resolve_distinct_id(auth_user: AuthenticatedUser, end_user_id: str | None) -> str:
+ # OAuth tokens identify the human; everything else prefers end_user_id so
+ # events land on the customer-facing person profile.
+ if auth_user.auth_method == "oauth_access_token":
+ return auth_user.distinct_id
+ return end_user_id or auth_user.distinct_id
+
+
def has_required_scope(scopes: list[str], required: str = "llm_gateway:read", *, allow_wildcard: bool = False) -> bool:
if not scopes:
return False
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index f43fbf08e2af..8959a076544a 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -8,6 +8,7 @@ from uuid import UUID, uuid4, uuid5
import structlog
from posthoganalytics import Posthog
+from llm_gateway.auth.models import resolve_distinct_id
from llm_gateway.callbacks.base import InstrumentedCallback
from llm_gateway.request_context import (
get_auth_user,
@@ -118,10 +119,10 @@ class PostHogCallback(InstrumentedCallback):
# Anthropic's metadata.user_id is co-opted as a trace id by Claude Code
# (see _normalize_trace_id), and Claude Code sends a JSON blob there.
trace_id = _normalize_trace_id(metadata.get("user_id"))
- if auth_user and auth_user.auth_method == "oauth_access_token":
- distinct_id = auth_user.distinct_id
+ if auth_user is None:
+ distinct_id = end_user_id or str(uuid4())
else:
- distinct_id = end_user_id or (auth_user.distinct_id if auth_user else str(uuid4()))
+ distinct_id = resolve_distinct_id(auth_user, end_user_id)
team_id = auth_user.team_id if auth_user and auth_user.team_id else None
logger.debug(
@@ -204,10 +205,10 @@ class PostHogCallback(InstrumentedCallback):
# Anthropic's metadata.user_id is co-opted as a trace id by Claude Code
# (see _normalize_trace_id), and Claude Code sends a JSON blob there.
trace_id = _normalize_trace_id(metadata.get("user_id"))
- if auth_user and auth_user.auth_method == "oauth_access_token":
- distinct_id = auth_user.distinct_id
+ if auth_user is None:
+ distinct_id = end_user_id or str(uuid4())
else:
- distinct_id = end_user_id or (auth_user.distinct_id if auth_user else str(uuid4()))
+ distinct_id = resolve_distinct_id(auth_user, end_user_id)
team_id = auth_user.team_id if auth_user and auth_user.team_id else None
logger.debug(
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index c67dace427d3..42d84eff1110 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -31,6 +31,7 @@ from llm_gateway.rate_limiting.cost_throttles import (
UserCostBurstThrottle,
UserCostSustainedThrottle,
)
+from llm_gateway.rate_limiting.denial_event import PosthogDenialCapturer
from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.request_context import RequestContext, set_request_context
from llm_gateway.services.plan_resolver import PlanResolver
@@ -138,14 +139,21 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
logger.info("Redis connected")
product_throttle = ProductCostThrottle(redis=app.state.redis)
+ denial_capturer: PosthogDenialCapturer | None = None
+ if settings.posthog_project_token:
+ denial_capturer = PosthogDenialCapturer(
+ api_key=settings.posthog_project_token,
+ host=settings.posthog_host,
+ )
app.state.throttle_runner = ThrottleRunner(
throttles=[
product_throttle,
UserCostBurstThrottle(redis=app.state.redis),
UserCostSustainedThrottle(redis=app.state.redis),
- ]
+ ],
+ denial_capturer=denial_capturer,
)
- logger.info("Throttle runner initialized")
+ logger.info("Throttle runner initialized", denial_capture_enabled=denial_capturer is not None)
app.state.cost_gauge_task = asyncio.create_task(publish_product_cost_gauges_loop(product_throttle))
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
index c926e368fd9d..2cbc5ada5ccd 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
@@ -106,6 +106,8 @@ class CostThrottle(Throttle):
detail=self._get_limit_exceeded_detail(),
scope=self.scope,
retry_after=retry_after,
+ used_usd=current,
+ limit_usd=limit,
)
return ThrottleResult.allow()
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/denial_event.py b/services/llm-gateway/src/llm_gateway/rate_limiting/denial_event.py
new file mode 100644
index 000000000000..9b9275739133
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/denial_event.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+import asyncio
+from functools import partial
+from typing import Any, Protocol
+
+import structlog
+from posthoganalytics import Posthog
+
+from llm_gateway.auth.models import resolve_distinct_id
+from llm_gateway.rate_limiting.throttles import ThrottleContext, ThrottleResult
+
+logger = structlog.get_logger(__name__)
+
+DENIAL_EVENT_NAME = "llm_gateway_rate_limit_denied"
+
+
+class DenialCapturer(Protocol):
+ def __call__(self, context: ThrottleContext, result: ThrottleResult, scope: str, /) -> None: ...
+
+
+class PosthogDenialCapturer:
+ def __init__(self, api_key: str, host: str) -> None:
+ self._api_key = api_key
+ self._host = host
+
+ def __call__(self, context: ThrottleContext, result: ThrottleResult, scope: str) -> None:
+ auth_user = context.user
+ distinct_id = resolve_distinct_id(auth_user, context.end_user_id)
+
+ properties: dict[str, Any] = {
+ "product": context.product,
+ "scope": scope,
+ "status_code": result.status_code,
+ "detail": result.detail,
+ "retry_after_seconds": result.retry_after,
+ "used_usd": result.used_usd,
+ "limit_usd": result.limit_usd,
+ "auth_method": auth_user.auth_method,
+ "application_id": auth_user.application_id,
+ "gateway_user_id": auth_user.user_id,
+ }
+ if auth_user.team_id is not None:
+ properties["team_id"] = auth_user.team_id
+
+ capture_kwargs: dict[str, Any] = {
+ "distinct_id": distinct_id,
+ "event": DENIAL_EVENT_NAME,
+ "properties": properties,
+ }
+ if auth_user.team_id is not None:
+ capture_kwargs["groups"] = {"project": auth_user.team_id}
+
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # No running loop (e.g. called from sync test); fire inline.
+ self._capture_sync(**capture_kwargs)
+ return
+ loop.run_in_executor(None, partial(self._capture_sync, **capture_kwargs))
+
+ def _capture_sync(self, **capture_kwargs: Any) -> None:
+ client: Any | None = None
+ try:
+ client = Posthog(
+ self._api_key,
+ host=self._host,
+ sync_mode=True,
+ enable_local_evaluation=False,
+ )
+ client.capture(**capture_kwargs)
+ except Exception:
+ logger.exception("denial_event_capture_failed")
+ finally:
+ if client is not None:
+ client.shutdown()
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/runner.py b/services/llm-gateway/src/llm_gateway/rate_limiting/runner.py
index 0d3a16d90fb3..79d7ddbd5a0f 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/runner.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/runner.py
@@ -5,14 +5,16 @@ import asyncio
import structlog
from llm_gateway.metrics.prometheus import RATE_LIMIT_EXCEEDED
+from llm_gateway.rate_limiting.denial_event import DenialCapturer
from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult
logger = structlog.get_logger(__name__)
class ThrottleRunner:
- def __init__(self, throttles: list[Throttle]):
+ def __init__(self, throttles: list[Throttle], denial_capturer: DenialCapturer | None = None):
self._throttles = throttles
+ self._denial_capturer = denial_capturer
@property
def throttles(self) -> list[Throttle]:
@@ -33,6 +35,12 @@ class ThrottleRunner:
scope=scope,
status_code=result.status_code,
)
+ if self._denial_capturer is not None:
+ try:
+ self._denial_capturer(context, result, scope)
+ except Exception:
+ # Capture failures must never break the throttle path.
+ logger.exception("denial_capturer_failed", scope=scope, product=context.product)
return result
return ThrottleResult.allow()
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
index 6cd2d0b82cc5..aff139e2e529 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
@@ -32,6 +32,8 @@ class ThrottleResult:
detail: str = "Rate limit exceeded"
scope: str | None = None
retry_after: int | None = None
+ used_usd: float | None = None
+ limit_usd: float | None = None
@classmethod
def allow(cls) -> ThrottleResult:
@@ -44,8 +46,18 @@ class ThrottleResult:
detail: str = "Rate limit exceeded",
scope: str | None = None,
retry_after: int | None = None,
+ used_usd: float | None = None,
+ limit_usd: float | None = None,
) -> ThrottleResult:
- return cls(allowed=False, status_code=status_code, detail=detail, scope=scope, retry_after=retry_after)
+ return cls(
+ allowed=False,
+ status_code=status_code,
+ detail=detail,
+ scope=scope,
+ retry_after=retry_after,
+ used_usd=used_usd,
+ limit_usd=limit_usd,
+ )
class Throttle(ABC):
diff --git a/services/llm-gateway/tests/test_denial_event.py b/services/llm-gateway/tests/test_denial_event.py
new file mode 100644
index 000000000000..b77a53e1f772
--- /dev/null
+++ b/services/llm-gateway/tests/test_denial_event.py
@@ -0,0 +1,277 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from llm_gateway.auth.models import AuthenticatedUser
+from llm_gateway.rate_limiting.denial_event import DENIAL_EVENT_NAME, PosthogDenialCapturer
+from llm_gateway.rate_limiting.runner import ThrottleRunner
+from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult
+
+
+def _user(
+ user_id: int = 42,
+ team_id: int | None = 7,
+ auth_method: str = "personal_api_key",
+ distinct_id: str | None = None,
+ application_id: str | None = "app-1",
+) -> AuthenticatedUser:
+ return AuthenticatedUser(
+ user_id=user_id,
+ team_id=team_id,
+ auth_method=auth_method,
+ distinct_id=distinct_id or f"distinct-{user_id}",
+ scopes=["llm_gateway:read"],
+ application_id=application_id,
+ )
+
+
+def _context(user: AuthenticatedUser | None = None, end_user_id: str | None = None) -> ThrottleContext:
+ return ThrottleContext(user=user or _user(), product="posthog_code", end_user_id=end_user_id)
+
+
+class _DeniedThrottle(Throttle):
+ scope = "user_cost_burst"
+
+ def __init__(self, result: ThrottleResult):
+ self._result = result
+
+ async def allow_request(self, context: ThrottleContext) -> ThrottleResult:
+ return self._result
+
+
+class TestRunnerCallsCapturer:
+ @pytest.mark.asyncio
+ async def test_capturer_called_on_denial(self) -> None:
+ captured: list[tuple[ThrottleContext, ThrottleResult, str]] = []
+
+ def capturer(ctx: ThrottleContext, result: ThrottleResult, scope: str) -> None:
+ captured.append((ctx, result, scope))
+
+ runner = ThrottleRunner(
+ throttles=[
+ _DeniedThrottle(
+ ThrottleResult.deny(
+ scope="user_cost_burst",
+ retry_after=120,
+ used_usd=12.5,
+ limit_usd=10.0,
+ )
+ )
+ ],
+ denial_capturer=capturer,
+ )
+ await runner.check(_context())
+
+ assert len(captured) == 1
+ _, result, scope = captured[0]
+ assert scope == "user_cost_burst"
+ assert result.used_usd == 12.5
+ assert result.limit_usd == 10.0
+
+ @pytest.mark.asyncio
+ async def test_capturer_not_called_when_allowed(self) -> None:
+ calls = 0
+
+ def capturer(ctx: ThrottleContext, result: ThrottleResult, scope: str) -> None:
+ nonlocal calls
+ calls += 1
+
+ class AllowAll(Throttle):
+ scope = "always_allow"
+
+ async def allow_request(self, context: ThrottleContext) -> ThrottleResult:
+ return ThrottleResult.allow()
+
+ runner = ThrottleRunner(throttles=[AllowAll()], denial_capturer=capturer)
+ await runner.check(_context())
+
+ assert calls == 0
+
+ @pytest.mark.asyncio
+ async def test_capturer_exception_does_not_break_throttling(self) -> None:
+ def broken(ctx: ThrottleContext, result: ThrottleResult, scope: str) -> None:
+ raise RuntimeError("boom")
+
+ runner = ThrottleRunner(
+ throttles=[_DeniedThrottle(ThrottleResult.deny(scope="user_cost_burst", retry_after=1))],
+ denial_capturer=broken,
+ )
+ # Should still surface the denial result, not raise.
+ result = await runner.check(_context())
+ assert result.allowed is False
+
+
+class TestPosthogDenialCapturer:
+ @pytest.fixture
+ def capturer(self) -> PosthogDenialCapturer:
+ return PosthogDenialCapturer(api_key="phc_test", host="https://us.i.posthog.com")
+
+ @pytest.mark.parametrize(
+ (
+ "user",
+ "end_user_id",
+ "result",
+ "scope",
+ "expected_distinct_id",
+ "expected_properties",
+ "expected_absent_properties",
+ "expected_groups",
+ ),
+ [
+ pytest.param(
+ _user(user_id=42, team_id=7, auth_method="personal_api_key"),
+ "end-user-123",
+ ThrottleResult.deny(
+ scope="user_cost_burst",
+ retry_after=60,
+ used_usd=15.25,
+ limit_usd=10.0,
+ ),
+ "user_cost_burst",
+ "end-user-123",
+ {
+ "retry_after_seconds": 60,
+ "used_usd": 15.25,
+ "limit_usd": 10.0,
+ "team_id": 7,
+ "auth_method": "personal_api_key",
+ "gateway_user_id": 42,
+ "application_id": "app-1",
+ },
+ [],
+ {"project": 7},
+ id="personal-api-key-prefers-end-user-id",
+ ),
+ pytest.param(
+ _user(user_id=1, auth_method="oauth_access_token", distinct_id="oauth-distinct"),
+ "ignored",
+ ThrottleResult.deny(scope="user_cost_sustained", retry_after=10),
+ "user_cost_sustained",
+ "oauth-distinct",
+ {
+ "retry_after_seconds": 10,
+ "team_id": 7,
+ "auth_method": "oauth_access_token",
+ "gateway_user_id": 1,
+ "application_id": "app-1",
+ },
+ [],
+ {"project": 7},
+ id="oauth-uses-auth-distinct-id",
+ ),
+ pytest.param(
+ _user(team_id=None),
+ None,
+ ThrottleResult.deny(scope="user_cost_burst", retry_after=5),
+ "user_cost_burst",
+ "distinct-42",
+ {
+ "retry_after_seconds": 5,
+ "auth_method": "personal_api_key",
+ "gateway_user_id": 42,
+ "application_id": "app-1",
+ },
+ ["team_id"],
+ None,
+ id="no-team-id-omits-groups",
+ ),
+ ],
+ )
+ def test_event_payload(
+ self,
+ capturer: PosthogDenialCapturer,
+ user: AuthenticatedUser,
+ end_user_id: str | None,
+ result: ThrottleResult,
+ scope: str,
+ expected_distinct_id: str,
+ expected_properties: dict[str, Any],
+ expected_absent_properties: list[str],
+ expected_groups: dict[str, int] | None,
+ ) -> None:
+ recorded: dict[str, Any] = {}
+
+ def fake_sync(**kwargs: Any) -> None:
+ recorded.update(kwargs)
+
+ with patch.object(capturer, "_capture_sync", side_effect=fake_sync):
+ capturer(
+ _context(user=user, end_user_id=end_user_id),
+ result,
+ scope=scope,
+ )
+
+ assert recorded["event"] == DENIAL_EVENT_NAME
+ assert recorded["distinct_id"] == expected_distinct_id
+ props = recorded["properties"]
+ assert props["product"] == "posthog_code"
+ assert props["scope"] == scope
+ for key, value in expected_properties.items():
+ assert props[key] == value
+ for key in expected_absent_properties:
+ assert key not in props
+ if expected_groups is None:
+ assert "groups" not in recorded
+ else:
+ assert recorded["groups"] == expected_groups
+
+ @pytest.mark.asyncio
+ async def test_call_dispatches_to_executor_inside_event_loop(self, capturer: PosthogDenialCapturer) -> None:
+ loop = asyncio.get_running_loop()
+ recorded: dict[str, Any] = {}
+
+ def fake_sync(**kwargs: Any) -> None:
+ recorded.update(kwargs)
+
+ original_run_in_executor = loop.run_in_executor
+ executor_calls: list[tuple[Any, Any, tuple[Any, ...], Any]] = []
+
+ def tracking_run_in_executor(executor: Any, func: Any, *args: Any) -> Any:
+ fut = original_run_in_executor(executor, func, *args)
+ executor_calls.append((executor, func, args, fut))
+ return fut
+
+ user = _user(user_id=42, team_id=7, auth_method="personal_api_key")
+ result = ThrottleResult.deny(
+ scope="user_cost_burst",
+ retry_after=60,
+ used_usd=15.25,
+ limit_usd=10.0,
+ )
+
+ with (
+ patch.object(capturer, "_capture_sync", side_effect=fake_sync),
+ patch.object(loop, "run_in_executor", side_effect=tracking_run_in_executor),
+ ):
+ capturer(
+ _context(user=user, end_user_id="end-user-123"),
+ result,
+ "user_cost_burst",
+ )
+ assert len(executor_calls) == 1
+ await executor_calls[0][3]
+
+ executor, _, _, _ = executor_calls[0]
+ assert executor is None
+ assert recorded["event"] == DENIAL_EVENT_NAME
+ assert recorded["distinct_id"] == "end-user-123"
+ assert recorded["properties"]["used_usd"] == 15.25
+ assert recorded["properties"]["limit_usd"] == 10.0
+ assert recorded["groups"] == {"project": 7}
+
+ def test_capture_sync_swallows_posthog_failures(self, capturer: PosthogDenialCapturer) -> None:
+ broken_client = MagicMock()
+ broken_client.capture.side_effect = RuntimeError("network down")
+ with patch("llm_gateway.rate_limiting.denial_event.Posthog", return_value=broken_client):
+ # Must not raise.
+ capturer._capture_sync(distinct_id="d", event=DENIAL_EVENT_NAME, properties={})
+ broken_client.shutdown.assert_called_once()
+
+ def test_capture_sync_swallows_posthog_constructor_failures(self, capturer: PosthogDenialCapturer) -> None:
+ with patch("llm_gateway.rate_limiting.denial_event.Posthog", side_effect=RuntimeError("bad host")):
+ # Must not raise.
+ capturer._capture_sync(distinct_id="d", event=DENIAL_EVENT_NAME, properties={})