: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(rate-limiting): add shared outbound API egress limiter (#66064)
Julian Bez752e6c25f0a2
diff --git a/posthog/rate_limiting/__init__.py b/posthog/rate_limiting/__init__.pynew file mode 100644index 000000000000..e31df3a0822d--- /dev/null+++ b/posthog/rate_limiting/__init__.py@@ -0,0 +1,20 @@+"""General-purpose outbound API egress rate limiting.++Shared, Redis-backed budgets for calls leaving PostHog to third-party APIs, so every worker+process draws from one limit. Consumers go through ``OutboundRateLimiter`` with a key like+``"github:installation:123"``; per-target budgets are declared as ``RatePolicy`` objects and+registered by each consumer's adapter (see ``posthog.rate_limiting.github``).++Distinct from ``posthog.rate_limit`` (inbound DRF request throttling) — this limits what we+send out, not what clients send us.+"""++from posthog.rate_limiting.outbound import OutboundRateLimiter, get_outbound_rate_limiter+from posthog.rate_limiting.policies import RatePolicy, register_policy++__all__ = [+ "OutboundRateLimiter",+ "get_outbound_rate_limiter",+ "RatePolicy",+ "register_policy",+]diff --git a/posthog/rate_limiting/backends.py b/posthog/rate_limiting/backends.pynew file mode 100644index 000000000000..03de6e5c198e--- /dev/null+++ b/posthog/rate_limiting/backends.py@@ -0,0 +1,99 @@+"""``limits``-backed implementation of the outbound limiter.++All limiter-library and Redis specifics live here so the facade and consumers stay+backend-agnostic — swap the library by replacing this module. A sliding-window-counter over Redis+holds the shared budget across worker processes: O(1) memory per key, self-expiring (no background+threads, nothing to groom). An in-memory counter is the degraded fallback when Redis is down.++``limits`` builds its storage from our shared sync ``posthog.redis`` client; the async ``acquire``+offloads the blocking call via ``asyncio.to_thread`` rather than pulling in ``limits``' async+storage, which requires a separate ``coredis`` client and would bypass our configured client.+"""++import asyncio+import threading++import structlog+import redis.exceptions+from limits import RateLimitItemPerSecond+from limits.storage import MemoryStorage, RedisStorage+from limits.strategies import SlidingWindowCounterRateLimiter++from posthog.rate_limiting.policies import RateLimit, RatePolicy+from posthog.redis import get_client++logger = structlog.get_logger(__name__)++# Transport failures we degrade to the in-memory fallback on; anything else (config/programming+# errors) propagates rather than being silently mislabeled as a Redis outage.+_REDIS_ERRORS = (redis.exceptions.RedisError, ConnectionError, TimeoutError, OSError)++# The connection_pool is what's actually used; this URI only has to parse as a redis URI.+_PLACEHOLDER_URI = "redis://outbound-rate-limiter"++# Namespace our keys in the shared Redis db so they're self-documenting and can't collide with+# (or be wiped by a reset() of) anything else that might use the limits library's default "LIMITS".+_KEY_PREFIX = "outbound_rate_limit"+++def _items(limits: tuple[RateLimit, ...]) -> list[RateLimitItemPerSecond]:+ # limits models a window as amount-per-(multiples seconds); our periods are already seconds.+ return [RateLimitItemPerSecond(count, int(period_seconds)) for count, period_seconds in limits]+++def _check(limiter: SlidingWindowCounterRateLimiter, items: list[RateLimitItemPerSecond], key: str, n: int) -> bool:+ # Allowed only if every window has room; consume from all. Best-effort, not atomic across windows:+ # testing all first avoids the deterministic partial-consume (hit window A, then deny window B), but+ # a concurrent caller landing between test and hit can still leave one window consumed on a denied+ # call. The drift is deny-biased (we err toward denying, never over-allowing the shared budget) and+ # bounded by headroom plus the consumer's reactive backoff — fine for egress; cross-window atomicity+ # (a custom multi-window Lua) isn't worth it at v1.+ if not all(limiter.test(item, key, cost=n) for item in items):+ return False+ return all(limiter.hit(item, key, cost=n) for item in items)+++class LimitsBackend:+ """Sliding-window-counter rate limiting over Redis with an in-memory fallback.++ One limiter instance is built lazily and reused for all keys — ``limits`` namespaces state in+ Redis by the key passed to ``hit``/``test``, so there are no per-key objects or background work.+ """++ def __init__(self) -> None:+ self._redis: SlidingWindowCounterRateLimiter | None = None+ self._memory: SlidingWindowCounterRateLimiter | None = None+ self._lock = threading.Lock()++ async def acquire(self, key: str, policy: RatePolicy, n: int) -> bool:+ # Offload the blocking Redis call so the event loop isn't held.+ return await asyncio.to_thread(self.consume_sync, key, policy, n)++ def consume_sync(self, key: str, policy: RatePolicy, n: int) -> bool:+ try:+ return _check(self._redis_limiter(), _items(policy.limits), key, n)+ except _REDIS_ERRORS:+ logger.warning("outbound_rate_limit_redis_unavailable", key=key, fallback="in_memory")+ return _check(self._memory_limiter(), _items(self._shrunk(policy)), key, n)++ @staticmethod+ def _shrunk(policy: RatePolicy) -> tuple[RateLimit, ...]:+ divider = max(1, policy.in_memory_divider)+ return tuple((max(1, count // divider), period) for count, period in policy.limits)++ def _redis_limiter(self) -> SlidingWindowCounterRateLimiter:+ if self._redis is None:+ with self._lock:+ if self._redis is None:+ storage = RedisStorage(+ _PLACEHOLDER_URI, connection_pool=get_client().connection_pool, key_prefix=_KEY_PREFIX+ )+ self._redis = SlidingWindowCounterRateLimiter(storage)+ return self._redis++ def _memory_limiter(self) -> SlidingWindowCounterRateLimiter:+ if self._memory is None:+ with self._lock:+ if self._memory is None:+ self._memory = SlidingWindowCounterRateLimiter(MemoryStorage())+ return self._memorydiff --git a/posthog/rate_limiting/github.py b/posthog/rate_limiting/github.pynew file mode 100644index 000000000000..892633cf3385--- /dev/null+++ b/posthog/rate_limiting/github.py@@ -0,0 +1,61 @@+"""GitHub egress — the first consumer of the outbound rate limiter.++A GitHub App installation gets 15,000 REST requests/hour, shared across every PostHog+consumer of that installation (warehouse sources, Tasks, Code, Conversations, Visual+review). This module registers that budget as a policy keyed per installation and exposes+a thin gate other GitHub call sites can adopt one line at a time.++Importing this module registers the policy as a side effect — import it (directly or via+``acquire_github_installation``) before using a ``github:...`` limiter key.+"""++from django.conf import settings++from posthog.rate_limiting.outbound import get_outbound_rate_limiter+from posthog.rate_limiting.policies import RatePolicy, register_policy++GITHUB_DOMAIN = "github"++# Default under GitHub's real 15k/hr ceiling so the reactive backoff (GitHubRateLimitError in+# posthog/models/integration.py) absorbs drift between our local count and GitHub's actual+# counter — clock skew, multi-process races, and untracked PAT traffic on the same account.+_DEFAULT_HOURLY_BUDGET = 13_500++# A per-minute smoothing cap layered on top of the hourly budget. High enough that a normal+# failed run (a handful of jobs) never touches it, low enough that no single consumer can drain+# the shared hourly budget in seconds and that we stay clear of GitHub's secondary (per-minute+# abuse) limits. Under sustained pressure a flood drains at ~this rate, leaving budget for+# co-tenant consumers each minute (~hourly/30 — the hour can't empty faster than ~half an hour).+_DEFAULT_PER_MINUTE_BUDGET = 450+++def _hourly_budget() -> int:+ return int(getattr(settings, "GITHUB_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))+++def _per_minute_budget() -> int:+ return int(getattr(settings, "GITHUB_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))+++# Both rates are enforced together — the per-minute rate smooths bursts, the hourly rate caps total+# spend. Registered as a provider so the budgets are read from settings at acquire time, not frozen+# at import (lets deploy-time config and test overrides take effect).+def _github_policy() -> RatePolicy:+ return RatePolicy(+ limits=((_per_minute_budget(), 60.0), (_hourly_budget(), 3600.0)),+ in_memory_divider=4,+ )+++register_policy(GITHUB_DOMAIN, _github_policy)+++def github_installation_key(installation_id: str | int) -> str:+ """Limiter key for one GitHub App installation — the unit GitHub's budget is scoped to."""+ return f"{GITHUB_DOMAIN}:installation:{installation_id}"+++async def acquire_github_installation(installation_id: str | int, n: int = 1) -> bool:+ """Reserve ``n`` requests against an installation's hourly GitHub budget. Returns False when+ the budget is exhausted — back off and retry rather than calling GitHub."""+ return await get_outbound_rate_limiter().acquire(github_installation_key(installation_id), n)diff --git a/posthog/rate_limiting/outbound.py b/posthog/rate_limiting/outbound.pynew file mode 100644index 000000000000..0f6b78e945ce--- /dev/null+++ b/posthog/rate_limiting/outbound.py@@ -0,0 +1,53 @@+"""The outbound egress rate limiter facade.++This is the only surface consumers should touch. Call ``acquire`` (async) or ``consume_sync``+with a limiter key whose domain has a registered ``RatePolicy``; it returns True if the call fits+the shared budget, False if it would exceed it. Both are non-blocking — the caller decides what to+do on False (back off and retry, defer, or drop). Consumers depend on this facade, never on the+backing library, so the algorithm/backend stays swappable.+"""++import threading++from posthog.rate_limiting.backends import LimitsBackend+from posthog.rate_limiting.policies import RatePolicy, resolve_policy+++def _validate(n: int, policy: RatePolicy) -> None:+ if n < 1:+ raise ValueError(f"rate limiter weight must be >= 1, got {n}")+ smallest = min(count for count, _ in policy.limits)+ if n > smallest:+ # limits treats a weight larger than the limit as permanently unsatisfiable, so the caller+ # would back off forever rather than ever be granted. Fail loudly instead of silently.+ raise ValueError(f"weight {n} exceeds the tightest configured limit ({smallest}); it can never be granted")+++class OutboundRateLimiter:+ def __init__(self, backend: LimitsBackend | None = None) -> None:+ self._backend = backend or LimitsBackend()++ async def acquire(self, key: str, n: int = 1) -> bool:+ """Reserve ``n`` units against ``key``'s budget. Returns False if it would exceed it."""+ policy = resolve_policy(key)+ _validate(n, policy)+ return await self._backend.acquire(key, policy, n)++ def consume_sync(self, key: str, n: int = 1) -> bool:+ """Non-blocking sync variant for callers outside an event loop."""+ policy = resolve_policy(key)+ _validate(n, policy)+ return self._backend.consume_sync(key, policy, n)+++_limiter: OutboundRateLimiter | None = None+_limiter_lock = threading.Lock()+++def get_outbound_rate_limiter() -> OutboundRateLimiter:+ global _limiter+ if _limiter is None:+ with _limiter_lock:+ if _limiter is None:+ _limiter = OutboundRateLimiter()+ return _limiterdiff --git a/posthog/rate_limiting/policies.py b/posthog/rate_limiting/policies.pynew file mode 100644index 000000000000..9a212b633883--- /dev/null+++ b/posthog/rate_limiting/policies.py@@ -0,0 +1,65 @@+"""Outbound egress rate policies and their registry.++A *policy* is a budget for calls leaving PostHog to a third-party API. Consumers identify a+budget with a limiter key shaped ``"{domain}:{scope}:{id}"`` (e.g. ``"github:installation:123"``);+the facade resolves the key to a policy by its ``domain`` (the first segment).++Policies are registered as *providers* — a zero-arg callable returning a ``RatePolicy`` — so a+budget sourced from Django settings is read at resolve time, not frozen at import. Pass a plain+``RatePolicy`` for a static budget. This module is backend-agnostic (no Redis, no limiter library),+which keeps the limiter backend swappable.+"""++from collections.abc import Callable+from dataclasses import dataclass++# (count, period_seconds) — one rate constraint. A policy may carry several; they are all enforced+# together, so you can cap the hour AND smooth per-minute bursts on the same key.+RateLimit = tuple[int, float]+++@dataclass(frozen=True)+class RatePolicy:+ """A budget: one or more ``(count, period_seconds)`` limits enforced together.++ ``in_memory_divider`` shrinks the per-process fallback budget used when Redis is unavailable:+ each process would otherwise get the full budget, so N processes together would allow N× the+ shared limit. The fallback is best-effort only — the consumer's reactive backoff (e.g. honoring+ a 429) is the real backstop.+ """++ limits: tuple[RateLimit, ...]+ in_memory_divider: int = 1++ def __post_init__(self) -> None:+ # A policy with no limits would let every call through, defeating the point. Reject it at+ # definition time rather than surfacing an opaque "min() arg is empty" deep in the facade.+ if not self.limits:+ raise ValueError("RatePolicy.limits must declare at least one (count, period_seconds) limit")+++PolicyProvider = Callable[[], RatePolicy]++_REGISTRY: dict[str, PolicyProvider] = {}+++def register_policy(domain: str, policy: RatePolicy | PolicyProvider) -> None:+ """Register the budget for a key domain. Pass a ``RatePolicy`` for a static budget, or a+ zero-arg callable to resolve it lazily (e.g. from settings) on each acquire."""+ if isinstance(policy, RatePolicy):+ _REGISTRY[domain] = lambda: policy+ else:+ _REGISTRY[domain] = policy+++def resolve_policy(key: str) -> RatePolicy:+ domain, sep, _rest = key.partition(":")+ if not sep or not domain:+ raise ValueError(f"Malformed limiter key '{key}'; expected '{{domain}}:{{scope}}:{{id}}'")+ provider = _REGISTRY.get(domain)+ if provider is None:+ raise ValueError(+ f"No outbound rate policy registered for domain '{domain}' (key '{key}'); "+ "register one with register_policy() before using this key"+ )+ return provider()diff --git a/posthog/rate_limiting/test/test_outbound_rate_limiter.py b/posthog/rate_limiting/test/test_outbound_rate_limiter.pynew file mode 100644index 000000000000..c09a8bfc15f6--- /dev/null+++ b/posthog/rate_limiting/test/test_outbound_rate_limiter.py@@ -0,0 +1,113 @@+import pytest++import posthog.rate_limiting.backends as backends_module+import posthog.rate_limiting.outbound as outbound_module+import posthog.rate_limiting.policies as policies_module+from posthog.rate_limiting import OutboundRateLimiter, RatePolicy, register_policy+from posthog.rate_limiting.backends import LimitsBackend+from posthog.rate_limiting.github import acquire_github_installation, github_installation_key+from posthog.rate_limiting.policies import resolve_policy++[email protected](autouse=True)+def _reset_limiter_state():+ # Tests register throwaway domains and the GitHub-adapter test goes through the process singleton;+ # restore the registry and drop the singleton so tests stay isolated (and the import-time GitHub+ # policy survives).+ saved = dict(policies_module._REGISTRY)+ outbound_module._limiter = None+ yield+ policies_module._REGISTRY.clear()+ policies_module._REGISTRY.update(saved)+ outbound_module._limiter = None+++def _fresh_limiter() -> OutboundRateLimiter:+ # Fresh backend per test so in-memory fallback state never leaks budget across tests.+ return OutboundRateLimiter(LimitsBackend())+++ "domain,limits,n,expected",+ [+ ("test-enforce-single", ((2, 3600.0),), 1, [True, True, False]),+ ("test-enforce-weighted", ((4, 3600.0),), 2, [True, True, False]),+ # Both orderings of a two-rate policy must enforce the binding window, whichever it is —+ # guards that every rate is checked, not just items[0].+ ("test-enforce-multirate", ((2, 60.0), (100, 3600.0)), 1, [True, True, False]),+ ("test-enforce-multirate-rev", ((100, 60.0), (2, 3600.0)), 1, [True, True, False]),+ ],+)+async def test_budget_denies_once_exhausted(domain, limits, n, expected):+ # Guards seconds->window conversion and the weight passthrough: a broken item build would+ # enforce the wrong window, and a dropped weight would let n>1 burst free.+ register_policy(domain, RatePolicy(limits=limits))+ limiter = _fresh_limiter()+ key = f"{domain}:scope:1"+ assert [await limiter.acquire(key, n) for _ in expected] == expected+++def test_consume_sync_enforces_budget():+ # The sync path is a distinct code path from async acquire and a real entry point — keep it+ # covered so a regression in get_client wiring or test/hit ordering is caught.+ register_policy("test-sync", RatePolicy(limits=((2, 3600.0),)))+ limiter = _fresh_limiter()+ assert [limiter.consume_sync("test-sync:scope:1") for _ in range(3)] == [True, True, False]+++async def test_unique_keys_do_not_share_budget():+ # Per-key isolation: exhausting one installation's budget must not deny another, or the shared+ # GitHub budget would be enforced globally instead of per installation.+ register_policy("test-isolation", RatePolicy(limits=((1, 3600.0),)))+ limiter = _fresh_limiter()+ assert await limiter.acquire("test-isolation:scope:A", 1) is True+ assert await limiter.acquire("test-isolation:scope:A", 1) is False+ assert await limiter.acquire("test-isolation:scope:B", 1) is True+++def test_policy_rejects_empty_limits():+ # A limit-less policy would let every call through; it must fail at definition time rather than+ # surfacing an opaque min() error on first acquire.+ with pytest.raises(ValueError):+ RatePolicy(limits=())++[email protected]("bad_key", ["totally-unregistered:scope:1", "nocolon"])+def test_resolve_policy_rejects_bad_keys(bad_key):+ # Fail-closed: an unregistered domain or a malformed (colon-less) key must raise rather than+ # silently egress unlimited or resolve the whole string as a domain.+ with pytest.raises(ValueError):+ resolve_policy(bad_key)+++async def test_falls_back_to_in_memory_when_redis_unavailable(monkeypatch):+ # Redis down must still enforce (shrunk by in_memory_divider), never allow unlimited egress.+ # Regression: an except branch that returns True instead of falling back to the local counter.+ register_policy("test-fallback", RatePolicy(limits=((4, 3600.0),), in_memory_divider=2))++ def _boom(*_args, **_kwargs):+ raise ConnectionError("redis down")++ monkeypatch.setattr(backends_module, "get_client", _boom)+ limiter = _fresh_limiter()+ key = "test-fallback:scope:1"+ # divider 2 -> effective in-memory limit of 2 -> third call denied+ assert [await limiter.acquire(key, 1) for _ in range(3)] == [True, True, False]+++def test_weight_validation():+ # n<1 must raise, and n above the tightest limit must raise rather than spin forever (limits+ # treats a weight larger than the limit as permanently unsatisfiable).+ register_policy("test-weight", RatePolicy(limits=((3, 3600.0),)))+ limiter = _fresh_limiter()+ with pytest.raises(ValueError):+ limiter.consume_sync("test-weight:scope:1", 0)+ with pytest.raises(ValueError):+ limiter.consume_sync("test-weight:scope:1", 5)+++async def test_github_adapter_registers_policy_and_keys_per_installation():+ # Importing the adapter must register the GitHub budget (else this raises) and key per+ # installation so distinct installations draw on independent budgets.+ assert github_installation_key(1) != github_installation_key(2)+ assert await acquire_github_installation(987654321, 1) is Truediff --git a/pyproject.toml b/pyproject.tomlindex 9b82644a3e6f..2d9f99ca207e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -198,6 +198,7 @@ dependencies = ["scrubadub~=2.0.1","braintrust-core>=0.0.59,<1","wrapt==1.17.3",+ "limits==5.8.0",][dependency-groups]diff --git a/uv.lock b/uv.lockindex 98250eaf2778..e422e61583d8 100644--- a/uv.lock+++ b/uv.lock@@ -3938,6 +3938,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3b/e4/b2f4ca7965ca373b491cdb4bc25cdb30c1649ca81a8782056a83850292a9/librt-0.11.0-cp313-cp313-win_arm64.whl", hash = "sha256:96f044bb325fd9cf1a723015638c219e9143f0dfbc0ca54c565df2b7fc748b44", size = 103448, upload-time = "2026-05-10T18:16:29.066Z" },]+[[package]]+name = "limits"+version = "5.8.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "deprecated" },+ { name = "packaging" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/71/69/826a5d1f45426c68d8f6539f8d275c0e4fcaa57f0c017ec3100986558a41/limits-5.8.0.tar.gz", hash = "sha256:c9e0d74aed837e8f6f50d1fcebcf5fd8130957287206bc3799adaee5092655da", size = 226104, upload-time = "2026-02-05T07:17:35.859Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b9/98/cb5ca20618d205a09d5bec7591fbc4130369c7e6308d9a676a28ff3ab22c/limits-5.8.0-py3-none-any.whl", hash = "sha256:ae1b008a43eb43073c3c579398bd4eb4c795de60952532dc24720ab45e1ac6b8", size = 60954, upload-time = "2026-02-05T07:17:34.425Z" },+]+[[package]]name = "linkedin-api-client"version = "0.3.0"@@ -5602,6 +5616,7 @@ dependencies = [{ name = "langchain-openai" },{ name = "langgraph" },{ name = "langgraph-checkpoint" },+ { name = "limits" },{ name = "linkedin-api-client" },{ name = "lxml" },{ name = "lzstring" },@@ -5876,6 +5891,7 @@ requires-dist = [{ name = "langchain-openai", specifier = "~=0.3.35" },{ name = "langgraph", specifier = "==0.4.10" },{ name = "langgraph-checkpoint", specifier = "==4.1.1" },+ { name = "limits", specifier = "==5.8.0" },{ name = "linkedin-api-client", specifier = "~=0.3.0" },{ name = "lxml", specifier = "==6.0.2" },{ name = "lzstring", specifier = "==1.0.4" },