: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(egress): tell a caller how long to wait for outbound budget (#88249)
Tom Owers77d9cc6a8bdb
diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 12d12b399905..095ab15bade3 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -35,6 +35,26 @@ if not consume_github_installation_sync(installation_id, priority=Priority.BATCHThey are **non-blocking** — the caller decides what to do on `False`.The GitHub helpers wrap the key construction; other domains expose their own thin gate the same way.+### Pacing (for callers that can wait)++Getting denied is recoverable but wasteful: the caller learns nothing about _when_ the budget frees, so it backs off blind, and the budget it already spent stays spent.+A caller that can wait — a bulk import walking pages, not a request serving a person — should instead ask how long to wait and not get denied at all:++```python+pace = get_outbound_rate_limiter().pace_seconds(key, priority=Priority.BATCH)+if pace > 0:+ ... # the caller owns the wait; the limiter never sleeps+```++`pace_seconds` returns **0 while a window still holds more than half of that priority's allowance**, so a short run is never slowed for a budget it cannot dent.+Below that it spreads the allowance that is left over the time left in the window, which is the interval that keeps the caller admitted instead of shed.+It reads the same reserved floors admission does, so a `BATCH` caller paces off the share it may actually take, not the whole window.++Two things it is not.+It is **advisory** — `acquire`/`consume_sync` remain the only authority on whether a call is admitted, so a bug here cannot over-admit.+And it is not a wait-for-reset: these are sliding windows, which free continuously, so waiting for a reset would idle for a whole window to get budget that was arriving all along.+A store failure answers 0 rather than raising, because pacing sits in front of every gated call and the in-memory fallback's headroom is one process's, not the shared budget's.+### Budgets (policies)A budget is a `RatePolicy`: one or more `(count, period_seconds)` limits enforced _together_, so you can cap the hour and smooth per-minute bursts on the same key.diff --git a/posthog/egress/limiter/backends.py b/posthog/egress/limiter/backends.pyindex 01b1e2c00aca..457327af5173 100644--- a/posthog/egress/limiter/backends.py+++ b/posthog/egress/limiter/backends.py@@ -10,6 +10,7 @@ offloads the blocking call via ``asyncio.to_thread`` rather than pulling in ``listorage, which requires a separate ``coredis`` client and would bypass our configured client."""+import timeimport asyncioimport threading@@ -35,6 +36,13 @@ _PLACEHOLDER_URI = "redis://outbound-rate-limiter"# (or be wiped by a reset() of) anything else that might use the limits library's default "LIMITS"._KEY_PREFIX = "outbound_rate_limit"+# While a window still holds more than this share of a priority's allowance, `pace_seconds` returns+# zero. A short run spends too little of the budget to exhaust it, so slowing it would buy nothing+# and cost latency on every small job. Under the share, the remaining allowance is close enough to+# the floor that spending it at full speed would exhaust the window and get the caller shed for the+# rest of it.+_PACE_HEADROOM_FRACTION = 0.5+def _items(limits: tuple[RateLimit, ...]) -> list[RateLimitItemPerSecond]:# limits models a window as amount-per-(multiples seconds); our periods are already seconds.@@ -71,6 +79,33 @@ def _check(return all(limiter.hit(item, key, cost=n) for item in items)+def _window_wait(+ limiter: SlidingWindowCounterRateLimiter,+ item: RateLimitItemPerSecond,+ key: str,+ count: int,+ reserve: int,+ now: float,+) -> float:+ """Seconds this window wants between calls so its allowance lasts until the window rolls.++ The budget is a sliding window, so it frees continuously rather than at a reset. A caller that+ waits for a reset would idle for a whole window; the useful wait is the interval that spreads+ the allowance that is left over the time that is left.+ """+ stats = limiter.get_window_stats(item, key)+ # The reserved floor is headroom this priority may not take, so it is not part of the allowance+ # being spread. Ignoring it would pace as if the whole window were available and still leave the+ # caller shed at the floor.+ usable = max(0, stats.remaining - reserve)+ if usable > (count - reserve) * _PACE_HEADROOM_FRACTION:+ return 0.0+ seconds_left = max(0.0, stats.reset_time - now)+ if usable == 0:+ return seconds_left+ return seconds_left / usable++class LimitsBackend:"""Sliding-window-counter rate limiting over Redis with an in-memory fallback.@@ -98,6 +133,23 @@ class LimitsBackend:shrunk = self._shrunk(policy)return _check(self._memory_limiter(), _items(shrunk), key, n, _reserves(policy, priority, shrunk))+ def pace_seconds(self, key: str, policy: RatePolicy, priority: Priority) -> float:+ limits = policy.limits+ try:+ limiter = self._redis_limiter()+ now = time.time()+ waits = [+ _window_wait(limiter, item, key, count, reserve, now)+ for item, (count, _), reserve in zip(_items(limits), limits, _reserves(policy, priority, limits))+ ]+ except _REDIS_ERRORS:+ # The in-memory fallback counts one process, so its headroom is not the shared budget's+ # and a wait derived from it would be a guess. Zero leaves the gate and the caller's own+ # backoff behaving exactly as they do without pacing.+ return 0.0+ # The tightest window governs: waiting the shortest interval would exhaust every other one.+ return max(waits, default=0.0)+@staticmethoddef _shrunk(policy: RatePolicy) -> tuple[RateLimit, ...]:divider = max(1, policy.in_memory_divider)diff --git a/posthog/egress/limiter/outbound.py b/posthog/egress/limiter/outbound.pyindex dc8aad1e1c9d..328f4a0940b3 100644--- a/posthog/egress/limiter/outbound.py+++ b/posthog/egress/limiter/outbound.py@@ -59,6 +59,20 @@ class OutboundRateLimiter:record_outbound_decision(domain=_domain_of(key), source=source, priority=priority.value, granted=granted)return granted+ def pace_seconds(self, key: str, *, priority: Priority = Priority.NORMAL) -> float:+ """Seconds to wait before the next call on ``key`` so it does not exhaust the budget.++ Advisory, and non-blocking like the rest of this facade: ``acquire`` and ``consume_sync``+ stay the authority on whether a call is admitted, and the caller owns the wait. Zero means+ the budget holds enough headroom that the call does not need to wait, which is the answer+ for any run short enough never to spend its share.++ A caller that cannot wait can ignore this. A caller that can, such as a bulk import walking+ pages, turns a budget it would otherwise exhaust (and then be shed from for the rest of the+ window) into a steady drip that stays admitted.+ """+ return self._backend.pace_seconds(key, resolve_policy(key), priority)+_limiter: OutboundRateLimiter | None = None_limiter_lock = threading.Lock()diff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.pyindex b2221e9be014..09f69aeb1b39 100644--- a/posthog/egress/test/test_outbound_rate_limiter.py+++ b/posthog/egress/test/test_outbound_rate_limiter.py@@ -1,3 +1,5 @@+import uuid+import pytestimport posthog.egress.limiter.backends as backends_module@@ -27,6 +29,12 @@ def _fresh_limiter() -> OutboundRateLimiter:return OutboundRateLimiter(LimitsBackend())+def _unique_key(domain: str) -> str:+ # The pacing tests read how full a window is, so they need a window nothing else has spent.+ # Redis holds the counters for the length of the window, which outlives the test run.+ return f"{domain}:scope:{uuid.uuid4().hex}"++@pytest.mark.parametrize("domain,limits,n,expected",[@@ -202,3 +210,80 @@ def test_policy_rejects_out_of_range_reserve(bad_fraction):# A fraction outside [0, 1) is a config error: 1.0 reserves the whole window and denies forever.with pytest.raises(ValueError):RatePolicy(limits=((10, 3600.0),), reserve={Priority.BATCH: bad_fraction})+++ "hits,expect_paced",+ [+ # 6 of 10 left. A run this short cannot exhaust the window, so pacing it would add latency+ # to every small job and prevent nothing.+ (4, False),+ # 4 of 10 left. Spending the rest at full speed empties the window, after which the caller+ # is shed for the remainder of it.+ (6, True),+ (10, True),+ ],+)+def test_pacing_starts_only_once_headroom_is_scarce(hits, expect_paced):+ # Both ways of breaking the threshold are silent. Stuck on, every short run through every egress+ # domain is slowed for a budget it never dents. Stuck off, a long run still empties its window+ # and is shed, which is the condition pacing exists to avoid.+ register_policy("test-pace-threshold", RatePolicy(limits=((10, 3600.0),)))+ limiter = _fresh_limiter()+ key = _unique_key("test-pace-threshold")+ for _ in range(hits):+ limiter.consume_sync(key)++ assert (limiter.pace_seconds(key) > 0.0) is expect_paced+++def test_pacing_excludes_the_priority_reserve_from_the_allowance():+ # The reserved floor is headroom a BATCH caller may never take. Spreading raw `remaining`+ # instead would drip at the rate of a window this caller does not own, so it would still be shed+ # at the floor: a wait that looks right and prevents nothing.+ register_policy("test-pace-reserve", RatePolicy(limits=((10, 3600.0),), reserve={Priority.BATCH: 0.3}))+ limiter = _fresh_limiter()+ key = _unique_key("test-pace-reserve")+ for _ in range(4):+ limiter.consume_sync(key, priority=Priority.CRITICAL)++ # 6 units are left. CRITICAL may take all 6, which is above its share. BATCH may take 3 of them,+ # which is below its own, so only BATCH waits.+ assert limiter.pace_seconds(key, priority=Priority.CRITICAL) == 0.0+ assert limiter.pace_seconds(key, priority=Priority.BATCH) > 0.0+++ "limits",+ [+ ((100, 60.0), (10, 3600.0)),+ ((10, 3600.0), (100, 60.0)),+ ],+)+def test_pacing_follows_the_tightest_window(limits):+ # Taking the shortest interval, or reading only the first limit, paces to a window that is not+ # the binding one and empties the one that is. Both orderings are covered because an index bug+ # passes under one of them.+ register_policy("test-pace-tightest", RatePolicy(limits=limits))+ limiter = _fresh_limiter()+ key = _unique_key("test-pace-tightest")+ for _ in range(6):+ limiter.consume_sync(key)++ # The minute window is barely touched. The hourly one is down to 4 of 10 and governs.+ assert limiter.pace_seconds(key) > 0.0+++def test_pace_seconds_answers_zero_when_the_store_is_unavailable(monkeypatch):+ # Pacing sits in front of every gated call, so a Redis blip must not raise into the caller. The+ # in-memory fallback counts one process, so its headroom is not the shared budget's and a wait+ # derived from it would be a guess. Not pacing is the honest answer.+ register_policy("test-pace-store-down", RatePolicy(limits=((10, 3600.0),)))++ def _boom(*_args, **_kwargs):+ raise ConnectionError("redis down")++ monkeypatch.setattr(backends_module, "get_client", _boom)+ limiter = _fresh_limiter()++ assert limiter.pace_seconds(_unique_key("test-pace-store-down")) == 0.0