: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(provisioning): add redis token bucket primitive and fail open on cache outages (#83934)
Rafael Audibert1081196ff09a
diff --git a/.agents/skills/using-redis-token-buckets/SKILL.md b/.agents/skills/using-redis-token-buckets/SKILL.mdnew file mode 100644index 000000000000..ff455b899647--- /dev/null+++ b/.agents/skills/using-redis-token-buckets/SKILL.md@@ -0,0 +1,67 @@+---+name: using-redis-token-buckets+description: 'Use when adding a bucket-like rate limit backed by Redis: a per-caller budget with burst capacity and continuous refill, a refund path for requests that did no work, or a limit whose Retry-After must be a real wait rather than a window edge. `posthog/token_bucket.py` provides an atomic Lua token bucket (`consume`, `refund`, `peek`) over `posthog.redis.get_client()`. Choose it over DRF `SimpleRateThrottle`/fixed-window cache counters when boundary bursts, top-of-window lockouts, or charge-then-refund semantics matter. Trigger terms: token bucket, rate limit, burst, refill, quota, Retry-After, fixed window, throttle.'+---++# Using Redis token buckets++`posthog/token_bucket.py` is the repo's primitive for bucket-like limits in Redis. A bucket holds up to `burst` tokens and refills continuously at `per_hour / 3600` tokens per second. Every operation is atomic (a server-side Lua script), so concurrent web workers cannot double-spend a token.++## Use this skill when++- Adding a rate limit where callers legitimately burst but must be capped on sustained rate+- A limit needs a **refund** path: charge on entry, give the token back when the request provably did no work+- `Retry-After` must be the real per-caller wait for the next token, not "seconds until the top of the hour"+- Replacing a fixed-window cache counter that suffers 2x boundary bursts or full-window lockouts+- Exposing `RateLimit-Limit/Remaining/Reset` headers or a quota introspection endpoint (use `peek`)++## When NOT to use it++- **Per-IP or per-user request throttling on ordinary DRF endpoints**: subclass the existing throttles in `posthog/rate_limit.py` (`IPThrottle`, `UserRateThrottle`, `PersonalApiKeyRateThrottle`). They integrate with DRF's lifecycle and the `RATE_LIMIT_ENABLED` instance setting.+- **Outbound third-party API calls**: use `posthog/egress/` and its `limits`-library sliding-window limiter (`posthog/egress/limiter/`), which carries priorities and degraded fallbacks.+- **Hard quotas that must survive a Redis flush**: a bucket is best-effort (eviction or failover hands the caller a fresh budget). Pair it with a durable Postgres count for the few operations where that matters, and treat the bucket as the fast path.+- **Concurrency caps** (how many at once, not how often): see the sorted-set gate in `posthog/clickhouse/client/limit.py`.++## `limits` (vendored library) vs this module++The repo also vendors the [`limits`](https://limits.readthedocs.io/) library (used by `posthog/egress/limiter/backends.py`). Pick by the semantics you need, not by familiarity:++- **Use `limits`** when a plain window answers the question "no more than N per window" and nothing ever needs to be un-counted. Its `MovingWindowRateLimiter`/`SlidingWindowCounterRateLimiter` strategies avoid fixed-window boundary bursts, its `RedisStorage` runs its own Lua so hits are atomic, and `test()`/`get_window_stats()` cover peeking and remaining/reset. For outbound third-party calls specifically, don't use it directly; go through `posthog/egress/`, which wraps it with priorities and a degraded in-memory fallback.+- **Use this module** when you need what `limits` cannot express: a token bucket (independent burst capacity and refill rate), a **refund** path (its API is `hit`/`test`/`get_window_stats`/`clear`; there is no way to give a hit back), a `Retry-After` that is the wait for the next token rather than the window edge, or variable per-request cost.++A custom script is the de-facto token-bucket implementation on stock Redis (no native rate-limit command; the redis-cell module is not deployed), and `limits` runs its own Lua anyway, so neither choice avoids Lua.++## The API++```python+from posthog.token_bucket import Budget, BucketDecision, BucketUnavailable, consume, peek, refund++BUDGET = Budget(burst=30, per_hour=120) # capacity 30, refills one token every 30s++decision = consume(f"myfeature_rate:{team_id}", BUDGET)+match decision:+ case BucketUnavailable():+ ... # Redis can't answer: usually fail open; fall through to a durable check if you have one+ case BucketDecision(allowed=False):+ raise Throttled(wait=decision.retry_after) # whole seconds, safe for a Retry-After header+ case BucketDecision():+ ... # proceed; decision.remaining / .limit / .reset back RateLimit-* headers++# The request turned out to do no work (validation error, capability refusal):+refund(f"myfeature_rate:{team_id}", BUDGET)++# Introspection without charging (headers on reads, a /limits endpoint):+peek(f"myfeature_rate:{team_id}", BUDGET)+```++Semantics worth knowing:++- `consume` charges and answers in one atomic step. `cost` above `burst` is a programmer error (`ValueError`), not a denial.+- `refund` is capped at capacity and treats a missing key as an already-full bucket. Refund only what you charged; refunding on outcomes the caller controls (e.g. their own 4xxs they can trigger for free) is fine, refunding on outcomes an attacker controls to spin the bucket is not.+- `peek` is a plain read plus local refill math, so it can lose a sub-second race to a concurrent charge. Never gate anything on `peek`; gate on `consume`.+- Keys are fully caller-constructed. Prefix them (`<feature>_rate:`), include every identity the budget is scoped to, and never include secrets. The bucket self-expires once it would be full again, so idle keys clean themselves up.+- Nothing raises on Redis failure: every operation returns `BucketUnavailable` and the **caller** decides fail-open vs fall-through. Do not swallow it silently; log or count it so an outage is visible.++## Testing++Under `settings.TEST`, `posthog.redis.get_client()` returns fakeredis, which executes the Lua scripts (via lupa). Control time with `freeze_time` (the script's clock is passed in from Python), reset between tests with `posthog.redis.TEST_clear_clients()` + `posthog.token_bucket.TEST_reset_scripts()`, and see `posthog/test/test_token_bucket.py` for the pattern.diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.pyindex 126a8f020332..69884288a8ad 100644--- a/ee/api/agentic_provisioning/throttling.py+++ b/ee/api/agentic_provisioning/throttling.py@@ -34,6 +34,8 @@ from django.core.cache import cachefrom django.http import HttpRequestimport structlog+from django_redis.exceptions import ConnectionInterrupted+from redis.exceptions import RedisErrorfrom rest_framework.request import Requestfrom rest_framework.throttling import BaseThrottlefrom rest_framework.views import APIView@@ -78,11 +80,22 @@ def _fixed_window_count(cache_key: str, window_seconds: int) -> int:try:cache.add(cache_key, 0, timeout=window_seconds)return cache.incr(cache_key)- except (ValueError, ConnectionError, TimeoutError) as e:+ except ValueError as e:+ # incr raises ValueError when the key expired between add and incr.+ logger.warning("provisioning_rate_limit_cache_error", cache_key=cache_key, error=str(e))+ try:+ # cache.add preserves any counter a concurrent request already initialized,+ # so a transient cache error doesn't reset the window for a caller at the limit.+ cache.add(cache_key, 1, timeout=window_seconds)+ except (RedisError, ConnectionInterrupted):+ pass+ return 1+ except (RedisError, ConnectionInterrupted) as e:+ # Redis is unreachable (its errors subclass RedisError/Exception, not the+ # builtin ConnectionError/TimeoutError). Fail open without touching the+ # cache again: a second cache call would raise the same way and turn every+ # provisioning request into a 500 for as long as Redis is down.logger.warning("provisioning_rate_limit_cache_error", cache_key=cache_key, error=str(e))- # cache.add preserves any counter a concurrent request already initialized,- # so a transient cache error doesn't reset the window for a caller at the limit.- cache.add(cache_key, 1, timeout=window_seconds)return 1diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.pyindex 7a41e3c1e263..649ad18ce8d2 100644--- a/ee/api/agentic_provisioning/views/base.py+++ b/ee/api/agentic_provisioning/views/base.py@@ -67,8 +67,11 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):)# Provisioning throttles keyed on something DRF has by the time it calls- # check_throttles (the partner on request.auth, a URL kwarg). Additive to- # DEFAULT_THROTTLE_CLASSES, which still guards these endpoints per IP.+ # check_throttles (the partner on request.auth, a URL kwarg). These are the+ # only limits that reliably apply here: DEFAULT_THROTTLE_CLASSES is a no-op+ # unless the RATE_LIMIT_ENABLED instance setting is on, and even then it+ # skips authenticated requests that carry no personal API key, which is+ # every bearer-authenticated provisioning call.# Flows whose key only appears mid-handler (token exchange, account# request partner quota, wizard runs) call the throttling helpers instead.partner_throttle_classes: ClassVar[list[type[BaseThrottle]]] = []diff --git a/ee/partners/stripe/api/provisioning/throttling.py b/ee/partners/stripe/api/provisioning/throttling.pyindex e0b49090e0ea..175f84c5231f 100644--- a/ee/partners/stripe/api/provisioning/throttling.py+++ b/ee/partners/stripe/api/provisioning/throttling.py@@ -15,6 +15,8 @@ from typing import ClassVarfrom django.core.cache import cacheimport structlog+from django_redis.exceptions import ConnectionInterrupted+from redis.exceptions import RedisErrorfrom rest_framework.request import Requestfrom rest_framework.throttling import BaseThrottlefrom rest_framework.views import APIView@@ -54,11 +56,22 @@ class StripeFixedWindowThrottle(BaseThrottle):try:cache.add(cache_key, 0, timeout=RATE_LIMIT_WINDOW_SECONDS)self.count = cache.incr(cache_key)- except (ValueError, ConnectionError, TimeoutError) as e:+ except ValueError as e:+ # incr raises ValueError when the key expired between add and incr.+ logger.warning("stripe_provisioning_rate_limit_cache_error", endpoint=self.endpoint, error=str(e))+ try:+ # cache.add preserves any counter a concurrent request already initialized,+ # so a transient cache error doesn't reset the window when at the limit.+ cache.add(cache_key, 1, timeout=RATE_LIMIT_WINDOW_SECONDS)+ except (RedisError, ConnectionInterrupted):+ pass+ self.count = 1+ except (RedisError, ConnectionInterrupted) as e:+ # Redis is unreachable (its errors subclass RedisError/Exception, not the+ # builtin ConnectionError/TimeoutError). Fail open without touching the+ # cache again: a second cache call would raise the same way and turn every+ # provisioning request into a 500 for as long as Redis is down.logger.warning("stripe_provisioning_rate_limit_cache_error", endpoint=self.endpoint, error=str(e))- # cache.add preserves any counter a concurrent request already initialized,- # so a transient cache error doesn't reset the window when at the limit.- cache.add(cache_key, 1, timeout=RATE_LIMIT_WINDOW_SECONDS)self.count = 1return self.count <= self.limitdiff --git a/posthog/test/test_token_bucket.py b/posthog/test/test_token_bucket.pynew file mode 100644index 000000000000..ff7a8d644ec1--- /dev/null+++ b/posthog/test/test_token_bucket.py@@ -0,0 +1,104 @@+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized+from redis.exceptions import ConnectionError as RedisConnectionError++from posthog.redis import TEST_clear_clients+from posthog.token_bucket import BucketDecision, BucketUnavailable, Budget, TEST_reset_scripts, consume, peek, refund++# 1 token per second, so refill math reads directly in seconds.+ONE_PER_SECOND = Budget(burst=10, per_hour=3600)+++class TestTokenBucket(SimpleTestCase):+ def setUp(self) -> None:+ TEST_clear_clients()+ TEST_reset_scripts()+ self.addCleanup(TEST_clear_clients)+ self.addCleanup(TEST_reset_scripts)++ def test_burst_then_deny_with_accurate_retry_after(self) -> None:+ with freeze_time("2026-01-01 00:00:00"):+ for _ in range(ONE_PER_SECOND.burst):+ decision = consume("bucket:burst", ONE_PER_SECOND)+ assert isinstance(decision, BucketDecision)+ assert decision.allowed++ denied = consume("bucket:burst", ONE_PER_SECOND)+ assert isinstance(denied, BucketDecision)+ assert not denied.allowed+ assert denied.remaining == 0+ assert denied.retry_after == 1+ assert denied.reset == ONE_PER_SECOND.burst++ def test_continuous_refill_and_burst_cap(self) -> None:+ with freeze_time("2026-01-01 00:00:00") as frozen:+ for _ in range(ONE_PER_SECOND.burst):+ consume("bucket:refill", ONE_PER_SECOND)++ frozen.tick(5)+ decision = consume("bucket:refill", ONE_PER_SECOND)+ assert isinstance(decision, BucketDecision)+ assert decision.allowed+ assert decision.remaining == 4++ # A long idle refills to capacity, never beyond it.+ frozen.tick(100_000)+ decision = consume("bucket:refill", ONE_PER_SECOND)+ assert isinstance(decision, BucketDecision)+ assert decision.remaining == ONE_PER_SECOND.burst - 1++ def test_refund_returns_tokens_capped_at_capacity(self) -> None:+ with freeze_time("2026-01-01 00:00:00"):+ for _ in range(3):+ consume("bucket:refund", ONE_PER_SECOND)+ assert refund("bucket:refund", ONE_PER_SECOND) == 8+ assert refund("bucket:refund", ONE_PER_SECOND, cost=100) == ONE_PER_SECOND.burst+ # A missing key is a full bucket; nothing to give back.+ assert refund("bucket:never-charged", ONE_PER_SECOND) == ONE_PER_SECOND.burst++ def test_peek_reads_without_charging(self) -> None:+ with freeze_time("2026-01-01 00:00:00"):+ fresh = peek("bucket:peek", ONE_PER_SECOND)+ assert isinstance(fresh, BucketDecision)+ assert fresh.allowed+ assert fresh.remaining == ONE_PER_SECOND.burst++ consume("bucket:peek", ONE_PER_SECOND)+ first, second = (peek("bucket:peek", ONE_PER_SECOND) for _ in range(2))+ assert isinstance(first, BucketDecision) and isinstance(second, BucketDecision)+ assert first.remaining == second.remaining == ONE_PER_SECOND.burst - 1++ def test_redis_error_returns_unavailable_instead_of_raising(self) -> None:+ broken = MagicMock()+ broken.register_script.return_value.side_effect = RedisConnectionError("down")+ broken.hmget.side_effect = RedisConnectionError("down")+ TEST_reset_scripts()+ with patch("posthog.token_bucket.get_client", return_value=broken):+ assert isinstance(consume("bucket:down", ONE_PER_SECOND), BucketUnavailable)+ assert isinstance(refund("bucket:down", ONE_PER_SECOND), BucketUnavailable)+ assert isinstance(peek("bucket:down", ONE_PER_SECOND), BucketUnavailable)+ TEST_reset_scripts()++ @parameterized.expand(+ [+ ("zero_cost", 0),+ ("cost_above_burst", 11),+ ]+ )+ def test_invalid_cost_is_a_programmer_error(self, _name: str, cost: int) -> None:+ with self.assertRaises(ValueError):+ consume("bucket:invalid", ONE_PER_SECOND, cost=cost)++ @parameterized.expand(+ [+ ("zero_burst", 0, 60),+ ("zero_rate", 10, 0),+ ]+ )+ def test_invalid_budget_is_a_programmer_error(self, _name: str, burst: int, per_hour: int) -> None:+ with self.assertRaises(ValueError):+ Budget(burst=burst, per_hour=per_hour)diff --git a/posthog/token_bucket.py b/posthog/token_bucket.pynew file mode 100644index 000000000000..38c0d880dff7--- /dev/null+++ b/posthog/token_bucket.py@@ -0,0 +1,218 @@+"""Redis-backed token bucket for rate limiting.++A bucket holds up to ``burst`` tokens and refills continuously at+``per_hour / 3600`` tokens per second. Continuous refill is what a fixed+window cannot give: no 2x burst across a window boundary, no lockout until+the top of the hour, and ``retry_after`` is the real per-caller wait for the+next token rather than the time to the window edge.++Custom Lua rather than the vendored ``limits`` library because ``limits``+offers only window strategies (fixed/moving/sliding) with no token bucket and+no way to refund a charge, and stock Redis has no native rate-limit command.+The check-refill-and-charge sequence must be atomic across concurrent web+workers, which is exactly what a server-side script provides; ``limits``+ships its own Lua for the same reason.++Callers decide what happens when Redis can't answer: every operation returns+``BucketUnavailable`` instead of raising, so an endpoint can fail open (most+should) or fall through to a durable check without this module choosing for+them. Deliberately metric-free; counters belong with the consumer that knows+the endpoint and tier being limited.+"""++from __future__ import annotations++import math+import time++import structlog+from redis.commands.core import Script+from redis.exceptions import RedisError++from posthog.dataclasses import frozen+from posthog.redis import get_client++logger = structlog.get_logger(__name__)+++@frozen+class Budget:+ # Capacity: the most tokens the bucket can hold, so the biggest burst a caller gets.+ burst: int+ # Refill rate, as tokens per hour.+ per_hour: int++ def __post_init__(self) -> None:+ if self.burst < 1:+ raise ValueError(f"burst must be >= 1, got {self.burst}")+ if self.per_hour < 1:+ raise ValueError(f"per_hour must be >= 1, got {self.per_hour}")++ @property+ def refill_per_second(self) -> float:+ return self.per_hour / 3600.0+++@frozen+class BucketDecision:+ allowed: bool+ # Whole tokens currently available. ``limit`` is the capacity (``burst``),+ # matching RateLimit-Limit/Remaining header semantics for token buckets.+ remaining: int+ limit: int+ # Seconds until the next token exists (0 when allowed). Whole seconds,+ # rounded up, so a Retry-After header never tells a caller to retry early.+ retry_after: int+ # Seconds until the bucket is full again.+ reset: int+++@frozen+class BucketUnavailable:+ """Redis could not answer. The caller chooses fail-open or a durable fallback."""++ error: str+++# KEYS[1] bucket hash. ARGV: capacity, refill_per_sec, cost, now_ms.+# Returns {allowed, remaining_floor, retry_after_ms, reset_ms}.+_CONSUME_LUA = """+local capacity = tonumber(ARGV[1])+local refill_per_sec = tonumber(ARGV[2])+local cost = tonumber(ARGV[3])+local now_ms = tonumber(ARGV[4])++local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')+local tokens = tonumber(state[1])+local ts = tonumber(state[2])+if tokens == nil or ts == nil then+ tokens = capacity+ ts = now_ms+end++-- Clamp a backwards clock (web workers supply now_ms and may disagree by a+-- little) so a skewed worker can neither mint free tokens nor wipe accrual.+if now_ms < ts then+ now_ms = ts+end+tokens = math.min(capacity, tokens + ((now_ms - ts) / 1000.0) * refill_per_sec)++local allowed = 0+if tokens >= cost then+ tokens = tokens - cost+ allowed = 1+end++redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now_ms)+-- Self-expire once the bucket would be full anyway, so idle keys don't accumulate.+redis.call('PEXPIRE', KEYS[1], math.ceil((capacity / refill_per_sec) * 1000) + 60000)++local retry_after_ms = 0+if allowed == 0 then+ retry_after_ms = math.ceil(((cost - tokens) / refill_per_sec) * 1000)+end+local reset_ms = math.ceil(((capacity - tokens) / refill_per_sec) * 1000)+return {allowed, math.floor(tokens), retry_after_ms, reset_ms}+"""++# KEYS[1] bucket hash. ARGV: capacity, cost.+# A missing key means the bucket is already full, so there is nothing to give back.+_REFUND_LUA = """+local capacity = tonumber(ARGV[1])+local cost = tonumber(ARGV[2])+local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens'))+if tokens == nil then+ return capacity+end+tokens = math.min(capacity, tokens + cost)+redis.call('HSET', KEYS[1], 'tokens', tokens)+return math.floor(tokens)+"""+++@frozen+class _Scripts:+ consume: Script+ refund: Script+++_registered_scripts: _Scripts | None = None+++def _scripts() -> _Scripts:+ global _registered_scripts+ if _registered_scripts is None:+ client = get_client()+ _registered_scripts = _Scripts(+ consume=client.register_script(_CONSUME_LUA),+ refund=client.register_script(_REFUND_LUA),+ )+ return _registered_scripts+++def consume(key: str, budget: Budget, cost: int = 1) -> BucketDecision | BucketUnavailable:+ """Atomically refill the bucket and take ``cost`` tokens if available."""+ if cost < 1 or cost > budget.burst:+ raise ValueError(f"cost must be between 1 and burst ({budget.burst}), got {cost}")+ consume_script = _scripts().consume+ try:+ allowed, remaining, retry_after_ms, reset_ms = consume_script(+ keys=[key],+ args=[budget.burst, budget.refill_per_second, cost, int(time.time() * 1000)],+ )+ except RedisError as e:+ logger.warning("token_bucket_unavailable", key=key, operation="consume", error=str(e))+ return BucketUnavailable(error=str(e))+ return BucketDecision(+ allowed=bool(allowed),+ remaining=int(remaining),+ limit=budget.burst,+ retry_after=math.ceil(retry_after_ms / 1000),+ reset=math.ceil(reset_ms / 1000),+ )+++def refund(key: str, budget: Budget, cost: int = 1) -> int | BucketUnavailable:+ """Give ``cost`` tokens back, capped at capacity. Returns the new whole-token count."""+ if cost < 1:+ raise ValueError(f"cost must be >= 1, got {cost}")+ refund_script = _scripts().refund+ try:+ return int(refund_script(keys=[key], args=[budget.burst, cost]))+ except RedisError as e:+ logger.warning("token_bucket_unavailable", key=key, operation="refund", error=str(e))+ return BucketUnavailable(error=str(e))+++def peek(key: str, budget: Budget) -> BucketDecision | BucketUnavailable:+ """Read the bucket without charging it.++ A plain read plus local refill math instead of a third script: peek backs+ introspection and response headers, where losing a sub-second race to a+ concurrent charge changes nothing a caller may rely on.+ """+ try:+ tokens_raw, ts_raw = get_client().hmget(key, "tokens", "ts")+ except RedisError as e:+ logger.warning("token_bucket_unavailable", key=key, operation="peek", error=str(e))+ return BucketUnavailable(error=str(e))++ if tokens_raw is None or ts_raw is None:+ tokens = float(budget.burst)+ else:+ elapsed = max(0.0, time.time() - float(ts_raw) / 1000)+ tokens = min(float(budget.burst), float(tokens_raw) + elapsed * budget.refill_per_second)++ return BucketDecision(+ allowed=tokens >= 1,+ remaining=math.floor(tokens),+ limit=budget.burst,+ retry_after=0 if tokens >= 1 else math.ceil((1 - tokens) / budget.refill_per_second),+ reset=math.ceil((budget.burst - tokens) / budget.refill_per_second),+ )+++def TEST_reset_scripts() -> None:+ """Drop cached script bindings so tests that swap the redis client re-register."""+ global _registered_scripts+ _registered_scripts = None