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.

fix(llm-gateway): include retry time in 429 rate limit error message (#82310)

Brittany Joiner5734f7ac5afa
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index b050bf50917b..cd57a9f1544f 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -211,6 +211,16 @@ async def resolve_plan_and_quota(
return plan_info, QuotaResourceStatus(limited=False)
+def _format_retry_delay(seconds: int) -> str:
+ if seconds < 60:
+ return f"{seconds} second{'s' if seconds != 1 else ''}"
+ if seconds < 3600:
+ minutes = (seconds + 59) // 60
+ return f"{minutes} minute{'s' if minutes != 1 else ''}"
+ hours = (seconds + 3599) // 3600
+ return f"{hours} hour{'s' if hours != 1 else ''}"
+
+
async def enforce_throttles(
request: Request,
user: Annotated[AuthenticatedUser, Depends(enforce_product_access)],
@@ -314,11 +324,18 @@ async def enforce_throttles(
message = (
f"Rate limit exceeded: {reason}" if reason and reason != "Rate limit exceeded" else "Rate limit exceeded"
)
+ # Surfaces like the Slack agent relay only error.message, so the retry
+ # time must live in the text, not just the Retry-After header. Skipped
+ # when retry_after is only a back-off hint (exhausted credits) — those
+ # details already carry their own next step.
+ if result.retry_after is not None and result.retry_after > 0 and result.retry_after_resets_limit:
+ message += f". Try again in about {_format_retry_delay(result.retry_after)}."
detail = {
"error": {
"message": message,
"type": "rate_limit_error",
"reason": reason,
+ **({"retry_after": result.retry_after} if result.retry_after is not None else {}),
**({"code": result.scope} if result.scope else {}),
}
}
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py b/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py
index 64eee2ea5256..bc09348855f4 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py
@@ -70,4 +70,7 @@ class BillableCreditThrottle(Throttle):
detail=_BUCKET_EXHAUSTED_DETAIL.get(config.credit_bucket, _DEFAULT_EXHAUSTED_DETAIL),
scope=self.scope,
retry_after=_RETRY_AFTER_SECONDS,
+ # Credits come back on top-up or billing rollover, not when the
+ # back-off above elapses.
+ retry_after_resets_limit=False,
)
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 0ac849400ce8..e4d85ad3e2fc 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
@@ -66,10 +66,12 @@ class CostThrottle(Throttle):
async def allow_request(self, context: ThrottleContext) -> ThrottleResult:
limit, window = self._get_limit_and_window(context)
if limit <= 0:
+ # A zero limit never refills, so the window is only a back-off hint.
return ThrottleResult.deny(
detail=self._get_limit_exceeded_detail(),
scope=self.scope,
retry_after=window,
+ retry_after_resets_limit=False,
)
limiter = self._get_limiter(context)
key = self._get_cache_key(context)
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
index 9b9275739133..1c50cfa47df1 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/denial_event.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/denial_event.py
@@ -34,6 +34,7 @@ class PosthogDenialCapturer:
"status_code": result.status_code,
"detail": result.detail,
"retry_after_seconds": result.retry_after,
+ "retry_after_resets_limit": result.retry_after_resets_limit,
"used_usd": result.used_usd,
"limit_usd": result.limit_usd,
"auth_method": auth_user.auth_method,
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 c53205b4b93e..f7c229be2d9c 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
@@ -62,6 +62,10 @@ class ThrottleResult:
retry_after: int | None = None
used_usd: float | None = None
limit_usd: float | None = None
+ # False when retry_after is only a client back-off hint (e.g. exhausted
+ # credits, zero limit) — retrying then won't succeed, so user-facing
+ # messages must not promise it will.
+ retry_after_resets_limit: bool = True
@classmethod
def allow(cls) -> ThrottleResult:
@@ -76,6 +80,7 @@ class ThrottleResult:
retry_after: int | None = None,
used_usd: float | None = None,
limit_usd: float | None = None,
+ retry_after_resets_limit: bool = True,
) -> ThrottleResult:
return cls(
allowed=False,
@@ -85,6 +90,7 @@ class ThrottleResult:
retry_after=retry_after,
used_usd=used_usd,
limit_usd=limit_usd,
+ retry_after_resets_limit=retry_after_resets_limit,
)
diff --git a/services/llm-gateway/tests/test_rate_limiting.py b/services/llm-gateway/tests/test_rate_limiting.py
index b39cd4a74cfd..e7d6f8238377 100644
--- a/services/llm-gateway/tests/test_rate_limiting.py
+++ b/services/llm-gateway/tests/test_rate_limiting.py
@@ -5,6 +5,7 @@ import pytest
from fakeredis import aioredis as fakeredis
from fastapi.testclient import TestClient
+from llm_gateway.dependencies import _format_retry_delay
from llm_gateway.rate_limiting.redis_limiter import RateLimiter
from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult
from llm_gateway.rate_limiting.token_bucket import TokenBucketLimiter
@@ -244,19 +245,79 @@ class TestRateLimitResponseHeaders:
assert response.status_code == 429
assert response.headers["retry-after"] == "3600"
- # The reason is repeated in the message (SDK error strings often
- # surface only error.message) and the throttle scope rides along as
- # a machine-readable code.
+ # The reason and retry time are repeated in the message (SDK error
+ # strings often surface only error.message) and the throttle scope
+ # and retry_after ride along machine-readable.
assert response.json() == {
"error": {
- "message": "Rate limit exceeded: Product rate limit exceeded",
+ "message": "Rate limit exceeded: Product rate limit exceeded. Try again in about 1 hour.",
"type": "rate_limit_error",
"reason": "Product rate limit exceeded",
+ "retry_after": 3600,
"code": "test_throttle",
}
}
+class TestBackoffOnlyRetryAfter:
+ def test_429_message_omits_retry_promise_when_retry_wont_reset_limit(self, mock_db_pool: MagicMock) -> None:
+ class CreditsExhaustedThrottle(Throttle):
+ scope = "billable_credits"
+
+ async def allow_request(self, context: ThrottleContext) -> ThrottleResult:
+ return ThrottleResult.deny(
+ detail="Your team has used its monthly PostHog AI credits.",
+ scope=self.scope,
+ retry_after=60,
+ retry_after_resets_limit=False,
+ )
+
+ conn = AsyncMock()
+ conn.fetchrow = AsyncMock(
+ return_value={
+ "id": "key_id",
+ "user_id": 1,
+ "scopes": ["llm_gateway:read"],
+ "current_team_id": 1,
+ "distinct_id": "test-distinct-id",
+ "is_staff": False,
+ }
+ )
+ mock_db_pool.acquire = AsyncMock(return_value=conn)
+
+ app = create_test_app(mock_db_pool, throttles=[CreditsExhaustedThrottle()])
+
+ with TestClient(app) as client:
+ body = {"model": "gpt-4", "messages": [{"role": "user", "content": "Hi"}]}
+ headers = {"Authorization": "Bearer phx_test_key"}
+ response = client.post("/v1/chat/completions", json=body, headers=headers)
+
+ assert response.status_code == 429
+ # The back-off hint still reaches machines via header and body,
+ # but the message must not promise that retrying will succeed.
+ assert response.headers["retry-after"] == "60"
+ error = response.json()["error"]
+ assert error["retry_after"] == 60
+ assert "Try again" not in error["message"]
+
+
+class TestFormatRetryDelay:
+ @pytest.mark.parametrize(
+ "seconds,expected",
+ [
+ pytest.param(1, "1 second", id="one_second"),
+ pytest.param(45, "45 seconds", id="seconds"),
+ pytest.param(60, "1 minute", id="one_minute"),
+ pytest.param(90, "2 minutes", id="minutes_round_up"),
+ pytest.param(3600, "1 hour", id="one_hour"),
+ pytest.param(3601, "2 hours", id="hours_round_up"),
+ pytest.param(86400, "24 hours", id="full_day"),
+ ],
+ )
+ def test_buckets_and_rounding(self, seconds: int, expected: str) -> None:
+ assert _format_retry_delay(seconds) == expected
+
+
class TestFreeTierModelGateErrorBody:
def test_gate_403_wire_body_carries_code_and_legacy_shim(
self, mock_db_pool: MagicMock, monkeypatch: pytest.MonkeyPatch