: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llm-gateway): give PostHog staff unlimited usage (#70073)
Tom Owers140c72fbf48e
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex 09d223304d41..c87ef56798be 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -165,6 +165,13 @@ class Settings(BaseSettings):# Combined with the team multiplier by taking the larger of the two.staff_rate_limit_multiplier: int = 10+ # When true, PostHog staff (authenticated is_staff) bypass the per-user+ # burst/sustained cost caps entirely, on every product. Spend is still+ # recorded for observability — only enforcement and the reported usage+ # status treat staff as unlimited. Set false to fall back to the+ # elevated-but-finite `staff_rate_limit_multiplier` cap.+ staff_unlimited_usage: bool = True+product_cost_limits: dict[str, ProductCostLimit] = DEFAULT_PRODUCT_COST_LIMITSuser_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITSdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.pyindex 6657d835b435..3a8913f8c48c 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@@ -16,7 +16,13 @@ from llm_gateway.config import (if TYPE_CHECKING:from llm_gateway.config import UserCostLimitfrom llm_gateway.rate_limiting.redis_limiter import CostRateLimiter-from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult, get_rate_limit_multiplier+from llm_gateway.rate_limiting.throttles import (+ Throttle,+ ThrottleContext,+ ThrottleResult,+ get_rate_limit_multiplier,+ is_usage_unlimited,+)from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT, get_billing_period_number, is_pro_planlogger = structlog.get_logger(__name__)@@ -257,12 +263,30 @@ class _UserCostThrottleBase(CostThrottle):async def allow_request(self, context: ThrottleContext) -> ThrottleResult:if not context.end_user_id:return ThrottleResult.allow()+ if is_usage_unlimited(context.user):+ return ThrottleResult.allow()settings = get_settings()if settings.user_cost_limits_disabled:await super().allow_request(context)return ThrottleResult.allow()return await super().allow_request(context)+ async def get_status(self, context: ThrottleContext) -> CostStatus:+ if is_usage_unlimited(context.user):+ # Staff have no per-user cap: report an effectively unlimited budget+ # so the usage endpoint computes 0% used and never flags the user as+ # rate limited. `float("inf")` never crosses the wire — only+ # `used_percent`/`exceeded` are serialized to the client.+ _, window = self._get_limit_and_window(context)+ return CostStatus(+ used_usd=0.0,+ limit_usd=float("inf"),+ remaining_usd=float("inf"),+ resets_in_seconds=window,+ exceeded=False,+ )+ return await super().get_status(context)+async def record_cost(self, context: ThrottleContext, cost: float) -> None:if not context.end_user_id:returndiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.pyindex 8d88b6b08ca2..6620d455bcf7 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py@@ -31,6 +31,14 @@ def get_rate_limit_multiplier(user: AuthenticatedUser) -> int:return max(get_team_multiplier(user.team_id), get_staff_multiplier(user))+def is_usage_unlimited(user: AuthenticatedUser) -> bool:+ """PostHog staff have no per-user cost cap — the burst/sustained throttles+ neither deny their requests nor report them as rate limited. Spend is still+ recorded for observability; only enforcement is skipped. Gated by a setting+ so it can be switched off without a redeploy. Non-staff users are unaffected."""+ return user.is_staff and get_settings().staff_unlimited_usage++@dataclassclass ThrottleContext:user: AuthenticatedUserdiff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex 52feb5c4fb0f..430223da9e44 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -2,6 +2,7 @@ import pytestfrom llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.config import get_settings+from llm_gateway.rate_limiting.cost_throttles import CostThrottlefrom llm_gateway.rate_limiting.throttles import ThrottleContext@@ -39,6 +40,13 @@ def make_context()+async def recorded_cost(throttle: CostThrottle, context: ThrottleContext) -> float:+ """Cost the underlying limiter has actually accumulated for this context, read+ straight from the limiter rather than through get_status (which reports staff as+ unlimited). Lets a test prove spend was recorded even when enforcement is bypassed."""+ return await throttle._get_limiter(context).get_current(throttle._get_cache_key(context))++class TestProductCostLimitConfig:def test_default_product_cost_limits(self) -> None:get_settings.cache_clear()@@ -564,6 +572,106 @@ class TestUserCostDisabledFlag:get_settings.cache_clear()+class TestStaffUnlimitedUsage:+ @pytest.mark.asyncio+ async def test_staff_allowed_over_burst_limit(self) -> None:+ # staff_unlimited_usage defaults to True.+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(user=make_user(is_staff=True), product="posthog_code")++ await throttle.record_cost(context, 100_000.0)+ # Observability guarantee: staff spend is still recorded even though the+ # request is allowed. Fails if record_cost starts skipping staff.+ assert await recorded_cost(throttle, context) == 100_000.0+ result = await throttle.allow_request(context)+ assert result.allowed is True+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_staff_allowed_over_sustained_limit(self) -> None:+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle++ throttle = UserCostSustainedThrottle(redis=None)+ context = make_context(user=make_user(is_staff=True), product="posthog_code")++ await throttle.record_cost(context, 100_000.0)+ result = await throttle.allow_request(context)+ assert result.allowed is True+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_staff_status_reports_unlimited(self) -> None:+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(user=make_user(is_staff=True), product="posthog_code")++ await throttle.record_cost(context, 100_000.0)+ # Spend is recorded on the limiter even though the reported status hides it+ # behind an unlimited budget — the observability guarantee this PR promises.+ assert await recorded_cost(throttle, context) == 100_000.0+ status = await throttle.get_status(context)+ assert status.used_usd == 0.0+ assert status.exceeded is False+ assert status.limit_usd == float("inf")+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_free_plan_staff_still_unlimited(self) -> None:+ # The case that bit staff before: a staff member on the free plan was+ # pinned to the (multiplied) free-plan cap rather than treated as unlimited.+ from datetime import UTC, datetime, timedelta++ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle++ throttle = UserCostSustainedThrottle(redis=None)+ context = make_context(+ user=make_user(is_staff=True),+ product="posthog_code",+ plan_key="posthog-code-free-20260301",+ seat_created_at=(datetime.now(tz=UTC) - timedelta(days=5)).isoformat(),+ )++ await throttle.record_cost(context, 100_000.0)+ assert (await throttle.allow_request(context)).allowed is True+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_non_staff_still_enforced(self) -> None:+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(user=make_user(is_staff=False), product="posthog_code")++ await throttle.record_cost(context, 500.0)+ result = await throttle.allow_request(context)+ assert result.allowed is False+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_staff_enforced_when_setting_disabled(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_UNLIMITED_USAGE", "false")+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ # With the bypass off, staff fall back to the multiplied finite cap+ # ($500 burst * 10 staff multiplier = $5000).+ context = make_context(user=make_user(is_staff=True), product="posthog_code")++ await throttle.record_cost(context, 5_000.0)+ result = await throttle.allow_request(context)+ assert result.allowed is False+ get_settings.cache_clear()++class TestRetryAfterHeader:@pytest.mark.asyncioasync def test_retry_after_returns_full_window_without_redis(self) -> None:diff --git a/services/llm-gateway/tests/test_throttles.py b/services/llm-gateway/tests/test_throttles.pyindex 7d2a84ee20d3..c2ead6ca8c81 100644--- a/services/llm-gateway/tests/test_throttles.py+++ b/services/llm-gateway/tests/test_throttles.py@@ -17,6 +17,7 @@ from llm_gateway.rate_limiting.throttles import (get_rate_limit_multiplier,get_staff_multiplier,get_team_multiplier,+ is_usage_unlimited,)@@ -235,3 +236,22 @@ class TestGetRateLimitMultiplier:get_settings.cache_clear()assert get_rate_limit_multiplier(make_user(team_id=99, is_staff=False)) == 1get_settings.cache_clear()+++class TestIsUsageUnlimited:+ def test_false_for_non_staff_user(self) -> None:+ get_settings.cache_clear()+ assert is_usage_unlimited(make_user(is_staff=False)) is False+ get_settings.cache_clear()++ def test_true_for_staff_user_by_default(self) -> None:+ # staff_unlimited_usage defaults to True.+ get_settings.cache_clear()+ assert is_usage_unlimited(make_user(is_staff=True)) is True+ get_settings.cache_clear()++ def test_false_for_staff_when_disabled(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_UNLIMITED_USAGE", "false")+ get_settings.cache_clear()+ assert is_usage_unlimited(make_user(is_staff=True)) is False+ get_settings.cache_clear()