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(billing): invalidate gateway quota cache (#72348)

Jonathan Mieloo74d6b6a85a5f
diff --git a/ee/api/quota_limits.py b/ee/api/quota_limits.py
index 25a3b810fac2..1cd8c4df4d72 100644
--- a/ee/api/quota_limits.py
+++ b/ee/api/quota_limits.py
@@ -20,7 +20,7 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.constants import AvailableFeature
-from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
+from ee.billing.quota_limiting import QuotaResource, get_fresh_team_limited_resources
class QuotaResourceLimitSerializer(serializers.Serializer):
@@ -91,15 +91,14 @@ class QuotaLimitsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
org_usage = self.team.organization.usage or {}
+ # Fresh read on purpose: the gateway re-caches this answer for minutes, so serving
+ # the 30s per-worker memo here would re-poison a just-invalidated gateway entry.
+ limited_resources = get_fresh_team_limited_resources(self.team.api_token)
limited = {}
for resource in QuotaResource:
summary = org_usage.get(resource.value) or {}
limited[resource.value] = {
- "limited": is_team_limited(
- self.team.api_token,
- resource,
- QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
- ),
+ "limited": limited_resources[resource],
"usage": _resource_usage(summary),
"limit": summary.get("limit"),
}
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 5bac20480482..5cc78cbcc7fa 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -227,6 +227,22 @@ def is_team_limited(team_api_token: str, resource: QuotaResource, cache_key: Quo
return team_api_token in limited_team_attributes
+def get_fresh_team_limited_resources(team_api_token: str) -> dict[QuotaResource, bool]:
+ """Uncached limited-state for one team across every resource, one Redis round trip.
+
+ `is_team_limited` reads a fleet-wide list memoized per worker for 30 seconds, which
+ is fine for callers that re-check constantly — but consumers that cache the answer
+ downstream for minutes (the LLM gateway) would re-cache a just-lifted limit as still
+ limited. This reads the zset scores directly instead.
+ """
+ now_ts = timezone.now().timestamp()
+ pipe = get_client().pipeline()
+ for resource in QuotaResource:
+ pipe.zscore(f"{QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY.value}{resource.value}", team_api_token)
+ scores = pipe.execute()
+ return {resource: score is not None and score >= now_ts for resource, score in zip(QuotaResource, scores)}
+
+
def dispatch_recordings_remote_config_sync(team_ids: Iterable[int]) -> None:
"""
Triggers a `RemoteConfig` rebuild for each team after its recordings quota-limit state
@@ -625,6 +641,31 @@ def org_quota_limited_until(
}
+def invalidate_llm_gateway_quota_cache(team_ids: Iterable[int]) -> None:
+ """Evict the LLM gateway's per-team quota entries so a raised billing limit
+ takes effect immediately instead of after the gateway's five-minute cache TTL.
+
+ The gateway caches in its own Redis (`settings.LLM_GATEWAY_REDIS_URL`, not the
+ central instance) and key shapes mirror `llm_gateway/services/quota_resolver.py`.
+ Best-effort by design: the gateway TTL already bounds staleness, so a failure
+ here must not fail the billing update that just committed.
+ """
+ cache_keys = [
+ key
+ for team_id in team_ids
+ for key in (
+ f"quota:code_usage_billing:team:{team_id}",
+ *(f"quota:{resource.value}:team:{team_id}" for resource in QuotaResource),
+ )
+ ]
+ if not cache_keys:
+ return
+ try:
+ get_client(settings.LLM_GATEWAY_REDIS_URL).delete(*cache_keys)
+ except Exception as e:
+ capture_exception(e)
+
+
def update_org_billing_quotas(organization: Organization):
"""
This method is basically update_all_orgs_billing_quotas but for a single org. It's called more often
@@ -688,6 +729,8 @@ def update_org_billing_quotas(organization: Organization):
if recordings_transitioned_team_ids:
dispatch_recordings_remote_config_sync(recordings_transitioned_team_ids)
+ invalidate_llm_gateway_quota_cache(teams_by_token.values())
+
def set_org_usage_summary(
organization: Organization,
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index eb533075a998..a2b315c2e3f7 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -976,6 +976,30 @@ class TestQuotaLimiting(BaseTest):
# reset for subsequent tests
self.organization.never_drop_data = False
+ def test_update_org_billing_quotas_invalidates_llm_gateway_quota_cache(self) -> None:
+ gateway_redis_url = "redis://llm-gateway-redis-test/"
+ cache_keys = [
+ f"quota:posthog_code_credits:team:{self.team.id}",
+ f"quota:ai_credits:team:{self.team.id}",
+ f"quota:code_usage_billing:team:{self.team.id}",
+ ]
+ with self.settings(LLM_GATEWAY_REDIS_URL=gateway_redis_url):
+ gateway_redis = get_client(gateway_redis_url)
+ gateway_redis.mset(dict.fromkeys(cache_keys, "stale"))
+ # Seed the central Redis too: eviction must target the gateway's own
+ # instance, not the default client (which would silently no-op in prod).
+ self.redis_client.mset(dict.fromkeys(cache_keys, "central"))
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+
+ update_org_billing_quotas(self.organization)
+
+ assert gateway_redis.mget(cache_keys) == [None] * len(cache_keys)
+ assert self.redis_client.mget(cache_keys) == [b"central"] * len(cache_keys)
+ self.redis_client.delete(*cache_keys)
+
def test_update_org_billing_quotas(self):
with freeze_time("2021-01-01T12:59:59Z"):
other_team = create_team(organization=self.organization)
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 89633b859fa1..dc0eab9d6f98 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -479,6 +479,10 @@ if get_from_env("POSTHOG_REPLAY_VISION_REDIS_HOST", ""):
os.getenv("POSTHOG_REPLAY_VISION_REDIS_PORT", "6379"),
)
+# The LLM gateway caches per-team quota state in its own Redis (llm_gateway/services/quota_resolver.py).
+# The central-Redis default only suits single-Redis setups; cloud must point this at the gateway's instance.
+LLM_GATEWAY_REDIS_URL = os.getenv("LLM_GATEWAY_REDIS_URL", REDIS_URL)
+
if not REDIS_URL:
raise ImproperlyConfigured(
"Env var REDIS_URL or POSTHOG_REDIS_HOST is absolutely required to run this software.\n"