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(egress): default the priority reserve and document each domain (#100426)

Julian Beza4fc07ecf198
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 6ef9921d8d84..c48f5b29e48d 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -601,7 +601,7 @@ PostHog can't overspend a budget it doesn't own, so honoring `429` / `Retry-Afte
**The exception is a credential PostHog owns and shares across processes** — today that's the PostHog GitHub App installation token (many PostHog subsystems draw from one per-installation budget at once).
There, reactive backoff isn't enough: without coordination, concurrent PostHog callers collectively blow past the shared limit before any `429` comes back.
-Those calls must route through [`posthog/egress/`](../../../posthog/egress/README.md) — a Redis-backed shared budget plus telemetry, gated by construction — never hand-rolled `requests`.
+Those calls must route through [`posthog/egress/`](../../../posthog/egress/README.md) — a Redis-backed shared budget plus telemetry, gated by construction — never hand-rolled `requests`. Invoke `/routing-outbound-api-calls` before adding such a call.
The [GitHub source](../../../products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py) is the reference: it keys the limiter on the **GitHub App installation id** (the budget owner in GitHub's own id space, not a PostHog DB row), and the customer-PAT path skips the limiter token-blind.
Raw calls to `api.github.com` are blocked by the `github-api-calls-go-through-egress` semgrep rule, so a GitHub-shaped source lands on the egress path by construction.
Deciding question is never "is this a warehouse source?" — it's **"who owns the token, and could concurrent PostHog processes trample each other on it?"**
diff --git a/.agents/skills/routing-outbound-api-calls/SKILL.md b/.agents/skills/routing-outbound-api-calls/SKILL.md
new file mode 100644
index 000000000000..f523482f2f96
--- /dev/null
+++ b/.agents/skills/routing-outbound-api-calls/SKILL.md
@@ -0,0 +1,104 @@
+---
+name: routing-outbound-api-calls
+description: >
+ Use before adding or changing Python code that calls a third-party HTTP API from PostHog (a vendor
+ REST call, a vendor SDK client, a scraping or enrichment service), and before adding or changing a
+ domain under posthog/egress/: its budget, priority lanes, identity, metrics, or rate-limit headers.
+ Routes the call to an existing egress domain, a new gated domain, a record-only domain, or no domain
+ at all, names the reference domain to copy, and lists the tests that catch a missing priority reserve.
+ Trigger terms: egress, outbound API, third-party API, vendor client, rate limit, 429, Retry-After,
+ budget, priority lane, BATCH, reserve, EgressClient, RecordedEgressClient, github_request.
+---
+
+# Routing outbound API calls
+
+`posthog/egress/` owns every outbound third-party API call that needs a shared budget or telemetry.
+[`posthog/egress/README.md`](../../../posthog/egress/README.md) is the reference for the mechanisms, and each domain's own `README.md` holds the facts about that API.
+This skill holds the procedure and the traps.
+
+## Route first
+
+| Situation | Route |
+| ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
+| A domain for the API exists (`ls posthog/egress/*/README.md`) | Call its `<domain>_request` helper or typed client. Read its README for identity and lanes. Never add a second client. |
+| New API, PostHog owns the credential, and the vendor publishes a request limit or bills per call | New gated domain: `EgressClient`, or `AsyncEgressClient` for an aiohttp client |
+| New API, PostHog owns the credential, and the vendor publishes no request limit that a rate budget can model | New record-only domain: `RecordedEgressClient` |
+| The customer owns the credential on their own vendor account, and no PostHog process shares it | No domain. Honor `429` and `Retry-After` at the caller. See "who owns the token" in `/implementing-warehouse-sources`. |
+| Throttling requests that reach PostHog's own API | `posthog/rate_limit.py`, not egress |
+| A budget that needs burst capacity, refunds, or a real per-caller `Retry-After` | `/using-redis-token-buckets` |
+| A secret-URL webhook (a Slack incoming webhook, an interactivity `response_url`) | Out of scope. The URL is the credential, so it must never become a metric label. |
+| A vendor calls PostHog (an inbound webhook) | `/adding-inbound-webhooks` |
+
+## Decide before you write code
+
+Write these four answers into the domain `README.md` first.
+Take each answer from the vendor's documentation or from production traffic, never from a sibling domain.
+
+1. **Identity.** The budget owner in the vendor's own id space: an installation, an account, a fleet. Never a PostHog row id. A secret identity goes through `scope_fingerprint` before it becomes a scope.
+2. **Budget.** A documented vendor limit means the budget stays under it. No documented limit means an operator ceiling on spend, read from settings. When the API already has a caller, check its peak requests per scope per minute and per hour before you pick numbers.
+3. **Lanes.** Keep the default reserve: `BATCH` is denied at 70% of a window, `NORMAL` at 90%. Pass `reserve={}` only when every caller runs on one lane, say why in the limiter docstring, and add the domain to `_FLAT_DOMAINS` in `posthog/egress/test/test_domains.py`. Give every caller an explicit lane: a person waiting gets `NORMAL`, background work gets `BATCH`. A call built from user-controlled input never runs `CRITICAL`, because `CRITICAL` is never shed.
+4. **Headers.** Parse only the rate-limit headers the vendor documents, and declare a gauge only for those. A header with an undocumented encoding (epoch or seconds) gets no gauge.
+
+## Source every vendor fact
+
+A limit, a cost, a quota, a header name, or a claim that a header is absent is a vendor fact.
+Each one goes into the domain `README.md` with its evidence under `## Sources`. `test_domains.py` fails a README without that section.
+
+- **Cite the vendor's own page.** A PR description, a sibling domain, a code comment, a blog post, or a search-result summary is not a source. Open the page it points at and cite that.
+- **Render docs that need JavaScript.** WebFetch returns an empty shell for a single-page docs site and can get a 429. Open the page in a headless browser (the Playwright MCP) or fetch the site's `llms-full.txt`. A docs site that renders nothing is not proof that the vendor documents nothing.
+- **Write "unverified" when no source loads.** Never turn an unchecked fact into a confident sentence.
+- **Check the gauges after the first deploy.** Query the domain's rate-limit gauges once the domain has traffic. An empty gauge means the headers do not reach PostHog, even when the docs say they do.
+- **Rule out your own code before you blame the vendor.** Before you write that a header does not arrive, confirm three things: the recorder passes a scope, the parser reads the documented name, and the process exports other gauges.
+
+## Build a new domain
+
+Work through "Adding a new egress domain" in the egress README.
+Copy the closest reference domain for the file layout:
+
+| Shape | Reference |
+| ------------------------------------ | -------------------------------- |
+| Sync, gated, with rate-limit headers | `posthog/egress/github/` |
+| Sync, gated, no rate-limit headers | `posthog/egress/firecrawl/` |
+| Record-only, secret identity | `posthog/egress/vapi/` |
+| Async (aiohttp) | `posthog/egress/harmonic/` |
+| Vendor SDK | `posthog/egress/slack/client.py` |
+
+- **Copy the layout, not the numbers.** Redo the four decisions above for the new API. A copy keeps the reference's settings defaults, lane defaults, and header names.
+- **Let the base client record.** The client sets `observability = <domain>_egress`. Do not add `record_<domain>_response` wrappers.
+- **Keep metric names explicit and stable.** Dashboards and alerts query them by name.
+- **Keep `posthog.models` imports out of the domain package.**
+- **The limiter never blocks.** The caller catches `<Domain>EgressBudgetExhausted` and backs off, defers, or degrades. A caller that folds exceptions into "not found" must catch it first.
+- **A caller that walks pages paces** with `pace_seconds` and `admission_interval_seconds` instead of getting denied.
+
+## Change an existing domain
+
+- Update the domain `README.md` in the same PR when its identity, budget, lanes, callers, or headers change.
+- Never rename a shipped metric or label.
+- A move between a flat and a laned policy changes production behavior. Compare the domain's peak traffic with the new thresholds and state the result in the PR.
+- A new caller of an existing domain passes its lane explicitly and goes into the domain README's callers.
+- A policy registered outside `posthog/egress/` gets the same default reserve. A single-lane throttle there passes `reserve={}`.
+
+## Tests
+
+Invoke `/writing-tests` first. In this package, these tests earn their place:
+
+- **Transport wiring.** Patch `requests.request` (or the aiohttp session), call the real `<domain>_request`, and assert the scope, the headers, and the recorded counter. Assert that a secret never reaches a label.
+- **Settings names.** Assert `resolve_policy(key).limits` under `override_settings`. The `getattr` defaults silently swallow a misspelled setting.
+- **Header parsing.** One parser case per documented header, plus garbage values.
+- **Lanes, only for a domain that overrides the reserve.** Use the real policy through `OutboundRateLimiter(LimitsBackend())` and a unique key.
+
+These do not:
+
+- **A lane claim proven with a patched gate.** A test that patches `consume_*_sync` to return `False` passes when the policy has no reserve at all.
+- **A per-domain copy of the default-ladder test.** `test_outbound_rate_limiter.py` covers the ladder, and `test_domains.py` pins the flat domains.
+
+## Traps this package already hit
+
+- **A fake gate.** `CRITICAL` plus a huge budget, or `_consume` that always returns `True`. Use `RecordedEgressClient` instead.
+- **A missing scope.** A scope of `None` or `""` skips the gate. A single-account domain passes a constant scope such as `"default"`, or every call goes through ungated.
+- **The base lane.** `EgressClient.request` defaults to `CRITICAL`. The `<domain>_request` helper sets its own sheddable default.
+- **Header names guessed from another vendor.** Firecrawl shipped gauges for GitHub-style `X-RateLimit-*` names that Firecrawl never documented, and they never recorded a value.
+- **A vendor fact copied from a PR description.** Open the vendor page, even when the page needs a browser to render.
+- **A caller from an unmerged PR documented as if it exists.**
+- **A domain added as a side effect of a product PR, with no README.** `test_domains.py` fails it. Write the README rather than skipping the test.
+- **Position words and hand-kept lists in docs** ("like the two above", "the second domain"). They break when the next domain lands.
diff --git a/.agents/skills/using-redis-token-buckets/SKILL.md b/.agents/skills/using-redis-token-buckets/SKILL.md
index e05f05e938d5..5cf1749285ae 100644
--- a/.agents/skills/using-redis-token-buckets/SKILL.md
+++ b/.agents/skills/using-redis-token-buckets/SKILL.md
@@ -18,7 +18,7 @@ description: 'Use when adding a bucket-like rate limit backed by Redis: a per-ca
## 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.
+- **Outbound third-party API calls**: use `posthog/egress/` and its `limits`-library sliding-window limiter (`posthog/egress/limiter/`), which carries priorities and degraded fallbacks. `/routing-outbound-api-calls` covers the route.
- **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`.
diff --git a/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml b/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml
index 8f348958e4f0..9dbcab438251 100644
--- a/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml
+++ b/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml
@@ -16,7 +16,7 @@ rules:
Why: a raw call bypasses the shared per-installation rate-limit budget and the
egress telemetry (request volume + `X-RateLimit-*` gauges), so it can burn a
- customer's GitHub budget invisibly. See `posthog/egress/README.md`.
+ customer's GitHub budget invisibly. See `posthog/egress/github/README.md`.
This rule only catches literal/f-string URLs; keep URLs inline at the call site.
Suppress a legitimate exception with
diff --git a/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml
index 0f30bfdbdd54..8a830c555abe 100644
--- a/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml
+++ b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml
@@ -6,7 +6,7 @@ rules:
Use `posthog.egress.slack.client.SlackWebClient` (or `SlackAsyncWebClient`) for
Slack SDK calls and `posthog.egress.slack.transport.slack_request` for direct HTTP.
Incoming webhooks and interactivity response URLs are outside this rule because their
- secret URL, not a workspace ID, owns the budget. See `posthog/egress/README.md`.
+ secret URL, not a workspace ID, owns the budget. See `posthog/egress/slack/README.md`.
The direct-HTTP half only catches literal/f-string URLs on the `requests` module, so
keep URLs inline at the call site. Any `WebClient` / `AsyncWebClient` construction is
diff --git a/AGENTS.md b/AGENTS.md
index d61944878763..9a3606360323 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -185,7 +185,7 @@ Each rule is tagged with what catches a violation.
- **Temporal activity payloads cap at ~2 MiB — pass large data by reference.** `[review]` Activity inputs and outputs cross a gRPC boundary the server rejects above that (`blobSizeLimitError`). As a field-level rule: if a field could exceed ~256 KB serialized (query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres or object storage from inside the activity and return only the row ID or S3 key. The workflow already has any ID created earlier in the run. Shuttling large data through the workflow produces `PayloadSizeError` (`TMPRL1103`) as soon as the data crosses the limit.
- **A Python `requests` call to GitHub or Slack under `common/`, `ee/`, `posthog/` or `products/` goes through `posthog/egress/`.** `[lint: github-api-calls-go-through-egress, slack-api-calls-go-through-egress]` Route it through the gated, recorded transport.
- **Every other call to those hosts is on review.** `[review]` The rules match an inline URL in a Python `requests` call inside those four directories. A URL bound to a variable first, another transport such as `httpx`, another language, or a caller under `tools/` all pass CI.
-- **Any other third-party API that needs rate-limiting or egress telemetry belongs there too.** `[review]` Add a `<domain>/` incarnation (GitHub is the reference). No semgrep rule covers a new domain, so a raw client for one reaches master unless a reader catches it. See [posthog/egress/README.md](posthog/egress/README.md).
+- **Any other third-party API that needs rate-limiting or egress telemetry belongs there too.** `[review]` Add a `<domain>/` incarnation (GitHub is the reference). No semgrep rule covers a new domain, so a raw client for one reaches master unless a reader catches it. `/routing-outbound-api-calls` decides the route and names the reference domain to copy.
- **Object storage is SeaweedFS — do not add new MinIO dependencies.** `[review]` Both S3-compatible stores are SeaweedFS: `objectstorage` (`:19000`, `OBJECT_STORAGE_*`) for general storage, `seaweedfs` (`:8333`, `SESSION_RECORDING_V2_S3_*`) for session replay v2. MinIO survives only as migration tooling in `docker-compose.hobby.yml` and `bin/upgrade-objectstorage`. Do not add compose services, scripts, tests or docs that stand up a `minio/minio` container. Talk to storage through the existing config and a standard S3 client, never a hardcoded endpoint. Note `objectstorage` registers credentials at runtime and returns `InvalidAccessKeyId` until that finishes, so wait for its readiness sentinel rather than the container start.
### Django admin
@@ -291,6 +291,7 @@ ALWAYS invoke the matching skill **first** — do not skip it, and do not attemp
- [`products/conversations/skills/organizing-conversations-code/SKILL.md`](products/conversations/skills/organizing-conversations-code/SKILL.md) — adding, moving, renaming, or reviewing files under `products/conversations/`
- `/integrating-with-posthog-ai` — making a product surface work with PostHog AI: injecting scene context or custom instructions, reacting to the agent's tool calls, or rendering your product's tool cards in a thread
- `/sending-notifications` — adding notification support
+- `/routing-outbound-api-calls` — adding or changing Python code that calls a third-party HTTP API, or changing any domain under `posthog/egress/` (budget, lanes, identity, metrics, headers)
- `/adding-activity-logging` — adding activity logging (the audit trail) to a model, writing or changing a `model_activity_signal` receiver or an activity describer, auditing which write paths of a model are logged, or debugging a change that is missing from the activity log
- `/writing-skills` — creating or updating skills in `.agents/skills/`
- `/editing-agents-md` — adding, editing or removing a rule in any `AGENTS.md` or `CLAUDE.md`, root or nested
diff --git a/posthog/cdp/services/icons.py b/posthog/cdp/services/icons.py
index 378145af2241..ba5f5137ca41 100644
--- a/posthog/cdp/services/icons.py
+++ b/posthog/cdp/services/icons.py
@@ -36,7 +36,8 @@ _DEFAULT_TEAM_HOURLY_BUDGET = 1_000
def _team_budget_policy(key: str) -> RatePolicy:
per_minute = int(getattr(settings, "CDP_ICONS_TEAM_PER_MINUTE_BUDGET", _DEFAULT_TEAM_PER_MINUTE_BUDGET))
hourly = int(getattr(settings, "CDP_ICONS_TEAM_HOURLY_BUDGET", _DEFAULT_TEAM_HOURLY_BUDGET))
- return RatePolicy(limits=((per_minute, 60.0), (hourly, 3600.0)), in_memory_divider=4)
+ # Flat: each team's budget has one caller on one lane, so no higher lane needs reserved headroom.
+ return RatePolicy(limits=((per_minute, 60.0), (hourly, 3600.0)), in_memory_divider=4, reserve={})
register_policy(_TEAM_BUDGET_DOMAIN, _team_budget_policy)
diff --git a/posthog/egress/AGENTS.md b/posthog/egress/AGENTS.md
index 1b1e7e33049f..293e53224d44 100644
--- a/posthog/egress/AGENTS.md
+++ b/posthog/egress/AGENTS.md
@@ -1,6 +1,8 @@
-# Outbound rate limiting & egress observability
+# Outbound egress: rate limiting, observability, transport
Read the README before changing metrics, limiter keys, or adding an egress domain here.
-Two things are easy to re-derive wrong: the identity model (key on the external budget owner — e.g. the GitHub App installation id — **never** a PostHog DB row id) and the deliberate PAT scope decision.
+Read a domain's own `README.md` before changing that domain, and invoke `/routing-outbound-api-calls` before adding or changing a domain.
+Two things are easy to re-derive wrong: the identity model (key on the external budget owner, for example the GitHub App installation id, and **never** a PostHog DB row id) and GitHub's deliberate PAT scope decision in `github/README.md`.
+A change to a domain's identity, budget, lanes, callers, or headers updates that domain's `README.md` in the same PR.
@README.md
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index e1f3b59335e4..74da549d5ef3 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -1,19 +1,20 @@
# Outbound egress: rate limiting, observability, transport
General-purpose controls for the calls PostHog makes _out_ to third-party APIs.
-GitHub was the first consumer and logo.dev (`logodev/`) is the second, but the package is built for more.
-A new outbound integration that needs rate-limiting or egress telemetry belongs here as a `<domain>/` incarnation (see [Adding a new egress domain](#adding-a-new-egress-domain)), never hand-rolled around `requests`.
+A new outbound integration that needs rate limiting or egress telemetry belongs here as a `<domain>/` package (see [Adding a new egress domain](#adding-a-new-egress-domain)), never hand-rolled around `requests`.
Three lanes, one per subpackage:
-- **`limiter/`** — shared, Redis-backed budgets so every worker process draws from one limit and PostHog stays inside an external API's rate limit, with priority lanes so bulk traffic can't starve critical traffic.
-- **`observability/`** — the metrics analog: request volume plus the API's own rate-limit headers, on one Prometheus metric set.
-- **`transport/`** — the HTTP client that composes the other two: one request that is gated _and_ recorded by construction, so no caller can bypass either.
+- **`limiter/`**: shared, Redis-backed budgets so every worker process draws from one limit and PostHog stays inside an external API's rate limit, with priority lanes so bulk traffic can't starve critical traffic.
+- **`observability/`**: the metrics analog, with request volume plus the API's own rate-limit headers, on one Prometheus metric set.
+- **`transport/`**: the HTTP client that composes the other two. Each request is gated _and_ recorded by construction, so no caller can bypass either.
-This is _outbound_ egress — what PostHog sends.
+This is _outbound_ egress: what PostHog sends.
It is unrelated to `posthog.rate_limit`, which throttles _inbound_ DRF requests from clients.
-All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`, `logodev/`, `firecrawl/`), supplying a budget policy, a metric set + parser, and a transport subclass.
-Adding a new outbound API is another `<domain>/` folder, not a change to the mechanisms.
+All three lanes are domain-free.
+Each third-party API is a domain under its own subpackage, and that subpackage's `README.md` holds the facts about the API: its identity, budget, lanes and callers, rate-limit headers, and auth.
+`github/` is the reference domain.
+Read a domain's `README.md` before changing that domain.
## Non-goals
@@ -42,26 +43,26 @@ Fix the request pattern first, then measure what is left.
### Using it
-A consumer identifies a budget with a limiter key shaped `{domain}:{scope}:{id}` — e.g. `github:installation:123`.
-Go through the facade, never the backing library:
+A consumer identifies a budget with a limiter key shaped `{domain}:{scope}:{id}`, for example `github:installation:123`.
+Go through the domain's gate, never the backing library:
```python
from posthog.egress.limiter.policies import Priority
from posthog.egress.github.limiter import consume_github_installation_sync
if not consume_github_installation_sync(installation_id, priority=Priority.BATCH, source="warehouse"):
- # Budget exhausted — back off and retry, defer, or drop. The limiter never blocks or sleeps.
+ # Budget exhausted: back off and retry, defer, or drop. The limiter never blocks or sleeps.
raise SomeRetryableError(...)
```
`acquire` (async) and `consume_sync` (sync, for callers outside an event loop) both return `True` if the call fits the shared budget and `False` if it would exceed it.
-They 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.
+They are **non-blocking**: the caller decides what to do on `False`.
+Each domain wraps the key construction in a thin gate like the GitHub helper above.
### 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:
+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)
@@ -76,159 +77,92 @@ A caller that keeps several calls in flight also asks `admission_interval_second
`pace_seconds` reads the window, so it cannot see calls the caller admitted but has not consumed yet; the interval comes from the policy alone and holds through that gap and through a store outage.
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.
+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.
-Each domain registers its policy with `register_policy(domain, policy)`, usually as a provider taking the full limiter key, so the budget is read at acquire time (settings + per-scope state) rather than frozen at import.
-GitHub meters its REST resources on **separate per-installation counters**, so it registers three domains — one per resource — and the transport routes each request to its meter by URL:
-
-- `github` — the `core` resource (5,000–15,000/hour), budgeted per **installation** and scaled to the installation's real tier: `api_request` persists each installation's last-observed core `X-RateLimit-Limit` (only trusted installation-token responses feed this), and the policy budgets 90% of it for the hour with a proportional per-minute smoothing cap (most installations sit on GitHub's 5,000/hour tier, not the 15,000 top tier). Unobserved installations fall back to the settings defaults (13,500/hour + 750/minute) until their first recorded response.
-- `github_search` — the `search` resource, a static 27/minute (under GitHub's real 30/min).
-- `github_code_search` — the `code_search` resource (`/search/code`), a static 8/minute (under GitHub's real 10/min).
-
-The two search budgets are static because GitHub's search rate limits are fixed regardless of the account's plan tier, so there is no tier to observe (unlike core).
-Budgets stay deliberately under the real ceiling so reactive backoff absorbs drift (clock skew, multi-process races, untracked PAT traffic on the same account).
-
-logo.dev (`logodev/`) meters per account, so a single `logodev` domain carries one instance-wide budget under a constant scope.
-Image CDN requests use `LOGO_DEV_PUBLISHABLE_KEY` (a `pk_` key) as a query parameter, while Search API requests use `LOGO_DEV_SECRET_KEY` (an `sk_` key) as a bearer token.
-`LOGO_DEV_TOKEN` is a deprecated compatibility fallback for image requests only and is never used to authenticate Search API requests.
-logo.dev publishes no rate-limit numbers, so the budgets are static operator ceilings read from settings at acquire time: `LOGODEV_EGRESS_PER_MINUTE_BUDGET` (default 300) smooths bursts and `LOGODEV_EGRESS_HOURLY_BUDGET` (default 5,000) caps total spend.
-Every logo.dev call runs on a sheddable lane — the icon id is user-controlled, so nothing in this domain runs `CRITICAL`.
-Icon bytes are never stored server-side (logo.dev licenses that separately), so steady-state traffic is deduped only by browser caching (`posthog/cdp/services/icons.py` sets `Cache-Control`) and tracks unique (user, icon) first views per day — raise the settings if that outgrows the defaults.
-
-Firecrawl (`firecrawl/`) meters per account and bills a credit per call, and an instance holds a single API key, so it follows the same shape: one `firecrawl` domain, one instance-wide budget under a constant scope.
-Firecrawl's per-plan limits are not discoverable from the running process, so the budgets are operator ceilings on spend read from settings at acquire time: `FIRECRAWL_EGRESS_PER_MINUTE_BUDGET` (default 60) smooths a burst of concurrent callers, and `FIRECRAWL_EGRESS_HOURLY_BUDGET` (default 1,000) caps what a runaway caller can spend before anyone notices.
-One scrape is one credit and one search is two credits per ten results, so those numbers cap a bill as much as a rate; they are sized for traffic of roughly one scrape per event a person triggers, and are meant to be raised in settings as that grows.
-Every Firecrawl call runs on a sheddable lane: what gets scraped is derived from user-supplied input and callers can do without the scrape, so nothing in this domain runs `CRITICAL`.
-`FIRECRAWL_API_KEY` authenticates every call as a bearer token; an instance without one makes no request at all (`FirecrawlNotConfigured`).
-
-Browserless (`browserless/`) meters **concurrent sessions**, not requests, and a session is held for the whole page load: a few seconds for a screenshot, tens of seconds for a Lighthouse audit.
-So its budget counts browser loads asked of one fleet, and the ceilings are small next to an API budget: `BROWSERLESS_EGRESS_PER_MINUTE_BUDGET` (default 120) and `BROWSERLESS_EGRESS_HOURLY_BUDGET` (default 2,000).
-Browserless publishes no rate-limit headers at all — its `X-Response-*` headers describe the page it fetched, not the API's budget — so, like logo.dev and Firecrawl, the budgets are static operator ceilings and the rate-limit gauges stay unset.
-
-The identity is the **fleet**: a hash of host and token together.
-Either alone is wrong. The same credential against a different host is a different set of workers, and a self-hosted fleet often carries no token, which would collapse every such deployment onto one budget if the token were the whole identity.
-The fleet is also what actually runs out: two callers pointed at one Browserless draw from one pool of workers whatever product they serve, so a narrower key would let each stay inside its own limit and still exhaust the fleet between them.
-
-This domain is where priority earns its keep, because its callers differ sharply in urgency.
-Heatmap screenshots run `NORMAL` — somebody is watching a spinner — while background consumers such as the Signals scout's Lighthouse audits run `BATCH` and are shed first, which is what leaves headroom for the render a person is waiting on.
-A denied call raises `BrowserlessEgressBudgetExhausted`; the heatmap caller maps it to its existing retryable error, under its own failure cause so a busy fleet is not read as a broken one.
-
-Harmonic (`harmonic/`) meters one account-wide rate limit, and an instance holds a single API key, so it uses one constant scope like the two above.
-The budget is a single per-second ceiling read from settings at acquire time: `HARMONIC_EGRESS_PER_SECOND_BUDGET` (default 15).
-Harmonic documents a per-second limit for most endpoints and answers 429 above it, reporting the current limit and remaining allowance in `X-Ratelimit-Limit-Second` and `X-Ratelimit-Remaining-Second` on every response.
-The default sits above that so the `BATCH` reserve floor lands the bulk lane near the documented rate, and it is tuned against the values this domain records from those headers.
-Harmonic is the first async domain: it subclasses `AsyncEgressClient` rather than `EgressClient`, because its client speaks `aiohttp`.
-Its lanes carry very different traffic, so the reserve floor matters: signup enrichment and the ICP re-enrichment sweep run `CRITICAL` inside a short Temporal activity budget, while the Salesforce enrichment sweep runs `BATCH` and yields to them.
+A budget is a `RatePolicy`: one or more `(count, period_seconds)` limits enforced _together_, so a policy can cap the hour and smooth per-minute bursts on the same key.
+Each domain registers its policy with `register_policy(domain, provider)`.
+A provider takes the full limiter key and runs at acquire time, so the budget follows settings changes and per-scope state rather than freezing at import.
+Most domains use `per_minute_and_hourly_policy`, which reads a per-minute and an hourly ceiling from settings.
+
+Where the provider publishes a limit, the budget stays under it, so the caller's reactive backoff absorbs drift (clock skew, multi-process races, traffic PostHog does not count).
+Where the provider publishes none, the budget is an operator ceiling on spend, meant to be raised in settings as real traffic grows.
### Priority lanes
Priority (`CRITICAL` / `NORMAL` / `BATCH`) controls how sheddable a call is when the budget gets tight.
-All priorities draw from the _same_ per-key counter — the lane only changes how much headroom must stay free for the call to be admitted (a _reserved floor_), so deferrable bulk traffic (`BATCH`) is denied before critical traffic as the budget fills, without ever splitting the budget into separate buckets.
-Admission tests `n + reserve` but only consumes `n`, so an empty reserve is bit-identical to pre-priority behavior.
-GitHub's reserve ladder is active: `BATCH` calls are denied once 70% of a window is consumed and `NORMAL` at 90%, while `CRITICAL` may use the full budget.
-Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override) — a shed sweep stops for the cycle and resumes on the next scheduled run.
+All priorities draw from the _same_ per-key counter.
+The lane only changes how much headroom must stay free for the call to be admitted (a _reserved floor_), so deferrable bulk traffic (`BATCH`) is denied before critical traffic as the budget fills, without ever splitting the budget into separate buckets.
+Admission tests `n + reserve` but only consumes `n`.
+
+Every policy gets `DEFAULT_RESERVE` unless it passes its own: `BATCH` calls are denied once 70% of a window is consumed and `NORMAL` at 90%, while `CRITICAL` may use the full budget.
+A policy passes `reserve={}` only when no higher-priority traffic exists to protect, and its limiter docstring says why.
+`test/test_domains.py` lists the flat domains, so a new flat policy needs a reviewed change to that list.
-The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
-An installation whose only consumer is a bulk one — a warehouse backfill of a repository nothing else touches — would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.
-So a non-`BATCH` `core` call writes a short-lived per-installation marker (`note_interactive_demand`), and the policy holds the full 70% floor only while that marker is present; without it `BATCH` falls back to a 10% floor — the same floor `NORMAL` keeps.
-Three details make that safe: the marker is written on the attempt rather than the outcome, so a _denied_ interactive call still counts; the floor matches `NORMAL`'s rather than dropping toward zero, so an unopposed backfill can never saturate the window past the point where the first interactive call would itself be denied, regardless of the marker it just wrote; and an unreachable cache reports demand as present, so a cache outage cannot hand the whole budget to bulk traffic.
-The two search resources keep the flat ladder — they are metered on their own counters, so core demand says nothing about them.
+A denied sheddable call raises the domain's `EgressBudgetExhausted` subclass.
+A denied `CRITICAL` call proceeds, and the API's own 429 is the backstop.
### Backend
-A sliding-window counter over Redis holds the shared budget across worker processes — O(1) memory per key, self-expiring, no background grooming.
+A sliding-window counter over Redis holds the shared budget across worker processes: O(1) memory per key, self-expiring, no background grooming.
When Redis is unavailable it degrades to a per-process in-memory counter, shrunk by `in_memory_divider` so N processes don't together allow N× the shared limit.
That fallback is best-effort: **the consumer's reactive backoff (e.g. honoring a 429) is the real backstop**, and the limiter is a proactive smoother on top.
All library and Redis specifics live in the backend module, so the facade and consumers stay backend-agnostic and the algorithm stays swappable.
## Egress observability
-Record every response through the domain's recorder (e.g. `record_github_api_response`) so request volume and the API's rate-limit headers land on one metric set, whichever subsystem made the call.
+Each domain constructs one `EgressObservability`, and the domain's transport records every request through it.
+Request volume and the API's rate-limit headers land on one metric set, whichever subsystem made the call.
-- **Counter** (`github_integration_api_requests_total`) — request volume, always recorded, including errors, rate-limited responses, and transport exceptions that raise before a response. Labeled `installation_id, method, endpoint, status_code, source`.
-- **Gauges** (`github_integration_api_rate_limit_{remaining,limit,reset_timestamp_seconds}`) — last-observed budget headroom parsed from the API's response headers (GitHub: `X-RateLimit-*`). Labeled `installation_id, resource`, with no `source`, because the budget is shared across sources.
+- **Counter** (for example `github_integration_api_requests_total`): request volume, always recorded, including errors, rate-limited responses, and transport exceptions that raise before a response. Labeled `<scope>, method, endpoint, status_code, source`.
+- **Gauges** (for example `github_integration_api_rate_limit_remaining`): last-observed budget headroom parsed from the API's response headers. Labeled `<scope>, resource`, with no `source`, because the budget is shared across sources. The gauges are optional: a domain declares only the ones its API reports, and parses only headers the API documents.
+- **Decisions** (`outbound_rate_limit_decisions_total`): one sample per limiter admission, labeled `domain, source, priority, granted`.
+Each domain keeps its own metric names, so existing dashboards stay valid.
The `source` label (e.g. `integration`, `visual_review`, `warehouse`) carries per-subsystem attribution.
-Endpoint labels are normalized to bound cardinality: owner/repo, numeric ids, commit SHAs, and free-form tails (file paths, compare refs) are templated out (`/repos/{owner}/{repo}/statuses/{sha}`), so raw-URL callers don't mint one label per commit.
+Endpoint labels are normalized to bound cardinality: numeric ids are templated out by default, and a domain with structured paths passes its own normalizer, so raw-URL callers don't mint one label per id.
## Transport
-`github_request` is the one way to call GitHub from anywhere — it gates on the shared per-installation budget and records telemetry by construction, so a caller physically can't forget either:
-
-```python
-from posthog.egress.github.transport import github_request
-from posthog.egress.limiter.policies import Priority
-
-resp = github_request(
- "GET",
- url,
- source="visual_review",
- headers={"Authorization": f"Bearer {token}"}, # caller owns auth; the client adds Accept + API version
- installation_id=installation_id, # budget owner; None = identity-blind (records volume only)
- priority=Priority.CRITICAL, # CRITICAL never blocks; sheddable lanes raise on denial
-)
-```
-
-It's **token-agnostic** (installation token, user token, PAT, or PostHog's shared token) and stateless.
-The generic `EgressClient` base owns the gate → request → record algorithm and the priority-based denial semantics (CRITICAL proceeds even when the budget is spent — GitHub's own 429 is the backstop; sheddable lanes raise `EgressBudgetExhausted`); `GitHubClient` fills the domain hooks.
-Response handling — what to do on a 403/429 — stays with the caller: `raise_if_github_rate_limited` / `GitHubRateLimitError` (GitHub's own 429, the reactive twin of our `EgressBudgetExhausted`) live in `github/transport.py` for callers that want to raise-and-retry.
-The model-coupled `GitHubIntegrationBase.api_request` layers the installation-token lifecycle (proactive refresh, 401 refresh-retry, rate-limit raising, per-instance `source` attribution) on top — hold an integration, call that; hold a bare token, call `github_request`.
-The `github-api-calls-go-through-egress` semgrep rule (`.semgrep/rules/devex/`) fails CI on a raw `requests` call that names `api.github.com` in the URL argument, so a new caller written that way lands on one of these two paths.
-The rule reads that argument only. A call that binds the URL to a variable first gets through, which is why `posthog/plugins/utils.py` still calls `requests.get` directly. Keep the URL inline at the call site.
+`transport/transport.py` holds three bases:
-Firecrawl callers go through `firecrawl/client.py` rather than `firecrawl_request` directly: `scrape(url, source=...)` returns a typed `FirecrawlScrape` (markdown, summary, plus the page title, description, status code and credits used) and raises `FirecrawlScrapeFailed` when Firecrawl answers with anything but a successful scrape, including the 200 responses that carry `success: false`.
-Only `POST /v2/scrape` is wired up, and the client reads `FIRECRAWL_API_KEY` from settings so the transport stays token-agnostic like the others.
+- **`EgressClient`**: gate, request, record, for a sync domain with a budget. A subclass sets `observability`, draws from its budget in `_consume`, and names its `EgressBudgetExhausted` subclass.
+- **`RecordedEgressClient`**: request and record with no gate, for an API that publishes no request limit a rate budget can model. `slack/` and `vapi/` use it.
+- **`AsyncEgressClient`**: the gated algorithm over aiohttp. `harmonic/` uses it.
-Slack Web API calls use `SlackWebClient` (and `SlackAsyncWebClient` where needed) from `slack/` so
-request volume, method, status, source, and workspace are recorded consistently. Slack applies Web API
-limits per method, workspace, and app, with additional special limits such as per-channel message
-posting. Installation age and Marketplace status can also change the limits for history methods.
-Slack does not return remaining-budget headers, so Slack egress records each HTTP attempt and the
-app-and-method-specific `Retry-After` from 429 responses. It does not proactively limit requests.
-Callers continue to own reactive retries.
+A domain exposes a `<domain>_request` helper over its client, and may add a typed client for the few endpoints its callers use (see `firecrawl/client.py`).
+A domain whose callers go through a vendor SDK hooks the SDK instead (see `slack/client.py`).
+Every client is token-agnostic: the caller passes its own credentials.
+Response handling, such as what to do on a 403 or 429, stays with the caller.
-Incoming webhooks and interactivity `response_url` calls are not Slack Web API calls. Their secret URL is
-the budget identity, and persisting or labeling by it would expose credentials. Keep their error handling
-with the caller rather than assigning them to a shared workspace bucket.
+Two semgrep rules in `.semgrep/rules/devex/` fail CI on a raw call that bypasses a domain: `github-api-calls-go-through-egress` (a `requests` call that names `api.github.com`) and `slack-api-calls-go-through-egress` (a `requests` call that names `slack.com/api`, or a bare `WebClient`).
+The `requests` half of each rule reads the URL argument only, so a call that binds the URL to a variable first gets through. Keep the URL inline at the call site.
+No rule covers the other domains.
## The one identity rule
-Everything keys on the **budget owner in the external API's own id space** — for GitHub the App **installation id**, because that is what GitHub meters.
+Everything keys on the **budget owner in the external API's own id space**: for GitHub the App **installation id**, because that is what GitHub meters.
It is **never** a PostHog DB row id (`Integration.id`).
Several PostHog integration rows can point at the same installation (multiple projects, one org), and GitHub gives that installation one shared budget: key a gauge by the row and one real budget splits into N flip-flopping series; key by the installation and you get one true series.
Per-caller attribution is the `source` label's job, not the identity's.
-> The cache-hit counter in `github_integration_base` is a separate concern (which rows are reading a warm cache) and legitimately keys by the integration row, not by the installation — it is not egress-budget telemetry. The caches it counts are installation-scoped, so a row can record a hit on an entry another row on the same installation filled.
-
-## Identity-blind callers and the PAT scope decision
-
-Some callers have no installation in scope.
-The important one is a warehouse source authenticated with a **personal access token (PAT)**: a customer's own token on the customer's own budget, disconnected from any PostHog installation (error tracking's public-repo path is the other).
-These record the counter only, under an empty `installation_id`, and skip both the limiter and the gauges.
-The counter still sums correctly, but identity-blind callers are **not distinguishable from one another** — every PAT lands on the same empty series, and writing headroom to a shared empty gauge would let unrelated tokens clobber each other.
-
-Scope line, as of the telemetry unification:
-
-- PAT request-**volume** telemetry is in scope and shipped (aggregate only).
-- PAT rate-limit **headroom** and PAT **limiting** are deferred — revisit.
-
-Both need the same missing piece: a per-token identity (a hash of the token) to key on.
-The headers are already on the response, so it needs no request restructuring — but a token-hash label is higher-cardinality than an installation, so it's a deliberate choice, not a default.
-`GithubEgressIdentity` is the seam where such a key would thread through.
+An identity that must not reach a metric label in plain form, such as a token, is hashed first (see `browserless/` and `vapi/`).
+A caller with no identity in scope passes no scope: it records the counter only and skips both the limiter and the gauges.
## Adding a new egress domain
-Add a `<domain>/` subpackage with three small adapters (see `github/`, or `firecrawl/` for a smaller one):
-
-- `limiter.py` — register a budget with `register_policy("<domain>", provider)` and a thin gate that builds the `{domain}:{scope}:{id}` key.
-- `observability.py` — an observability adapter (metric set, response parser, endpoint normalizer) and the recorders.
-- `transport.py` — an `EgressClient` subclass filling the domain hooks (headers, gate, recorders, normalizer, budget-exhausted error), exposed as a `<domain>_request` helper.
+Add a `<domain>/` subpackage and work through this list.
+The `/routing-outbound-api-calls` agent skill names the reference domain to copy and carries the decisions behind each step.
-A domain whose callers all hit the same few endpoints can add a fourth module, a typed client over the transport (see `firecrawl/client.py`), so call sites don't hand-build request bodies or re-parse the same response shape.
+1. **Choose the base.** `EgressClient` when the API publishes a limit or bills per call, `RecordedEgressClient` when only telemetry is useful, `AsyncEgressClient` for an aiohttp client.
+2. **Pick the identity** in the external API's id space (see [The one identity rule](#the-one-identity-rule)).
+3. **For a gated domain, add `limiter.py`.** Register a policy (usually `per_minute_and_hourly_policy`) and a thin gate that builds the `{domain}:{scope}:{id}` key. Keep the default reserve unless no higher lane exists; a flat policy needs a docstring reason and an entry in `test/test_domains.py`.
+4. **Add `observability.py`** with one `EgressObservability` and the domain's metric names. Declare a gauge and parse a header only when the API documents it.
+5. **Add `transport.py`** with the client subclass and a `<domain>_request` helper.
+6. **Add `README.md`** with the sections the other domains use: Identity, Budget, Lanes and callers, Rate-limit headers, Auth, Sources. Sources links the vendor page behind each limit, cost, and header claim. `test/test_domains.py` fails without the README or its Sources section.
+7. **Test the real policy** for any claim about which lane sheds first. A test that patches the gate cannot see a missing reserve.
-Keep the identity in the external API's id space, keep the subpackage free of `posthog.models` imports, and remember the limiter is non-blocking — the caller owns the back-off.
+Keep the subpackage free of `posthog.models` imports, and remember the limiter is non-blocking: the caller owns the back-off.
diff --git a/posthog/egress/browserless/README.md b/posthog/egress/browserless/README.md
new file mode 100644
index 000000000000..6b7bb2c61303
--- /dev/null
+++ b/posthog/egress/browserless/README.md
@@ -0,0 +1,41 @@
+# Browserless egress
+
+## Identity
+
+The **fleet**: a hash of host and token together, under the key `browserless:fleet:<hash>`.
+Either alone is wrong.
+The same credential against a different host is a different set of workers, and a self-hosted fleet often carries no token, which would collapse every such deployment onto one budget if the token were the whole identity.
+The fleet is also what actually runs out: two callers pointed at one Browserless draw from one pool of workers whatever product they serve, so a narrower key would let each stay inside its own limit and still exhaust the fleet between them.
+The hash keeps the token out of the metric label.
+
+## Budget
+
+Browserless meters **concurrent sessions**, not requests, and a session is held for the whole page load: a few seconds for a screenshot, tens of seconds for a Lighthouse audit.
+A load over the concurrency limit waits in a queue, and a load that finds the queue full gets a 429.
+So the budget counts browser loads asked of one fleet, and the ceilings are small next to an API budget:
+
+- `BROWSERLESS_EGRESS_PER_MINUTE_BUDGET` (default 120)
+- `BROWSERLESS_EGRESS_HOURLY_BUDGET` (default 2,000)
+
+## Lanes and callers
+
+The default reserve ladder applies, because callers differ sharply in urgency.
+Heatmap screenshots (`products/web_analytics/backend/tasks/heatmap_screenshot.py`) run `NORMAL`, because somebody is watching a spinner.
+A background consumer should run `BATCH`, so that it is shed first and leaves headroom for the render a person is waiting on.
+A denied call raises `BrowserlessEgressBudgetExhausted`; the heatmap caller maps it to its existing retryable error, under its own failure cause, so a busy fleet is not read as a broken one.
+
+## Rate-limit headers
+
+Browserless documents none, and a live response from the hosted fleet carries no `X-RateLimit-*` and no `Retry-After`.
+Its `X-Response-*` headers describe the page it fetched, not the API's budget, so the domain declares no gauges.
+The counter is `browserless_requests_total`, labeled `scope, method, endpoint, status_code, source`.
+
+## Auth
+
+The token stays in the URL's query string, because Browserless REST routes do not accept an `Authorization` header.
+`browserless_request` also takes the token separately, so the fleet can be fingerprinted without parsing the URL.
+
+## Sources
+
+- [Built-in queueing system](https://docs.browserless.io/enterprise/long-queues): the concurrency limit, the queue, and the 429 when the queue is full.
+- [#92939](https://github.com/PostHog/posthog/pull/92939): a live hosted-fleet response with no rate-limit headers.
diff --git a/posthog/egress/browserless/limiter.py b/posthog/egress/browserless/limiter.py
index 77839d934881..2773a0a23701 100644
--- a/posthog/egress/browserless/limiter.py
+++ b/posthog/egress/browserless/limiter.py
@@ -1,4 +1,4 @@
-"""Outbound Browserless budget, keyed by the fingerprint of the fleet's token.
+"""Outbound Browserless budget, keyed by the fleet a call competes for.
Browserless meters concurrent sessions rather than requests, and a session is held for the whole
page load: a few seconds for a screenshot, tens of seconds for a Lighthouse audit. So the budget
@@ -9,27 +9,25 @@ The fleet is the unit because that is what actually runs out. Two callers pointe
Browserless draw from one pool of workers whatever team or product they serve, so keying on
anything narrower would let them each stay inside their own limit and still exhaust the fleet
between them. Callers pointed at separate fleets fingerprint differently and never interfere.
-"""
-from django.conf import settings
+The default reserve ladder applies, because the callers differ sharply in urgency: a ``BATCH``
+background load is shed before a ``NORMAL`` render that somebody is waiting on.
+"""
from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+from posthog.egress.limiter.policies import Priority, per_minute_and_hourly_policy, register_policy
BROWSERLESS_DOMAIN = "browserless"
-
-def _browserless_policy(_key: str) -> RatePolicy:
- return RatePolicy(
- limits=(
- (int(getattr(settings, "BROWSERLESS_EGRESS_PER_MINUTE_BUDGET", 120)), 60.0),
- (int(getattr(settings, "BROWSERLESS_EGRESS_HOURLY_BUDGET", 2_000)), 3600.0),
- ),
- in_memory_divider=4,
- )
-
-
-register_policy(BROWSERLESS_DOMAIN, _browserless_policy)
+register_policy(
+ BROWSERLESS_DOMAIN,
+ per_minute_and_hourly_policy(
+ per_minute_setting="BROWSERLESS_EGRESS_PER_MINUTE_BUDGET",
+ per_minute_default=120,
+ hourly_setting="BROWSERLESS_EGRESS_HOURLY_BUDGET",
+ hourly_default=2_000,
+ ),
+)
def consume_browserless_sync(scope: str, *, priority: Priority, source: str) -> bool:
diff --git a/posthog/egress/browserless/observability.py b/posthog/egress/browserless/observability.py
index b674517fef16..a851bcd66551 100644
--- a/posthog/egress/browserless/observability.py
+++ b/posthog/egress/browserless/observability.py
@@ -2,78 +2,21 @@
Browserless returns no rate-limit headers. Its `X-Response-*` headers describe the page it
fetched, not the API's own budget, so there is nothing to read a remaining count or a reset time
-out of, and the snapshot below stays empty rather than inventing one. Volume, status, and latency
-are what this domain can honestly report; the gauges exist because the shared metric set declares
-them, and they simply stay unset. Verified against the hosted fleet, which returns a bare 200
-with no `X-RateLimit-*` and no `Retry-After`.
+out of, and this domain declares no gauges. Volume, status, and latency are what it can honestly
+report. Verified against the hosted fleet, which returns a bare 200 with no `X-RateLimit-*` and
+no `Retry-After`.
"""
-from collections.abc import Mapping
+from prometheus_client import Counter
-import requests
-from prometheus_client import Counter, Gauge
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
-from posthog.egress.browserless.limiter import BROWSERLESS_DOMAIN
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- register_egress_observability,
- unpack_requests_response,
-)
-
-_metrics = EgressMetrics(
- request_counter=Counter(
- "browserless_requests",
- "Outbound Browserless requests.",
- labelnames=["scope", "method", "endpoint", "status_code", "source"],
- ),
- remaining_gauge=Gauge(
- "browserless_rate_limit_remaining",
- "Unused: Browserless publishes no rate-limit headers.",
- labelnames=["scope", "resource"],
- ),
- limit_gauge=Gauge(
- "browserless_rate_limit_limit",
- "Unused: Browserless publishes no rate-limit headers.",
- labelnames=["scope", "resource"],
- ),
- reset_gauge=Gauge(
- "browserless_rate_limit_reset_at",
- "Unused: Browserless publishes no rate-limit headers.",
- labelnames=["scope", "resource"],
- ),
-)
-
-
-def _parse_browserless_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- return RateLimitSnapshot(resource="session")
-
-
-browserless_egress = EgressObservability(BROWSERLESS_DOMAIN, _metrics, _parse_browserless_rate_limit)
-register_egress_observability(browserless_egress)
-
-
-def record_browserless_response(
- response: requests.Response,
- *,
- source: str,
- scope: str,
- method: str,
- endpoint: str,
-) -> None:
- primitives = unpack_requests_response(response)
- browserless_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope=scope,
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
+browserless_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "browserless_requests",
+ "Outbound Browserless requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
)
-
-
-def record_browserless_exception(*, source: str, scope: str, method: str, endpoint: str, url: str) -> None:
- browserless_egress.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
+)
diff --git a/posthog/egress/browserless/transport.py b/posthog/egress/browserless/transport.py
index 18d3f2f3c1fc..cb45a79da152 100644
--- a/posthog/egress/browserless/transport.py
+++ b/posthog/egress/browserless/transport.py
@@ -1,14 +1,14 @@
"""Gated, recorded transport for calls to a Browserless fleet."""
-import hashlib
from typing import Any
from urllib.parse import urlsplit
import requests
from posthog.egress.browserless.limiter import consume_browserless_sync
-from posthog.egress.browserless.observability import record_browserless_exception, record_browserless_response
+from posthog.egress.browserless.observability import browserless_egress
from posthog.egress.limiter.policies import Priority
+from posthog.egress.observability.observability import scope_fingerprint
from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
@@ -30,36 +30,18 @@ def fleet_scope(url: str, token: str) -> str:
host = urlsplit(url).hostname or ""
if not host and not token:
return ""
- return hashlib.sha256(f"{host}|{token}".encode()).hexdigest()[:16]
+ return scope_fingerprint(host, token)
class BrowserlessClient(EgressClient):
+ observability = browserless_egress
+
def _standard_headers(self) -> dict[str, str]:
return {"Content-Type": "application/json"}
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return consume_browserless_sync(scope, priority=priority, source=source)
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_browserless_response(
- response,
- source=source,
- scope=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- )
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_browserless_exception(
- source=source,
- scope=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- url=url,
- )
-
def _budget_exhausted_error(self, scope: str) -> BrowserlessEgressBudgetExhausted:
return BrowserlessEgressBudgetExhausted("Browserless egress budget exhausted")
diff --git a/posthog/egress/firecrawl/README.md b/posthog/egress/firecrawl/README.md
new file mode 100644
index 000000000000..4452721a64ac
--- /dev/null
+++ b/posthog/egress/firecrawl/README.md
@@ -0,0 +1,50 @@
+# Firecrawl egress
+
+## Identity
+
+Firecrawl meters per account, and an instance holds a single API key.
+The whole instance draws from one budget under the key `firecrawl:account:default`.
+
+## Budget
+
+Firecrawl publishes per-minute limits by plan for `/scrape` and `/search`, but the running process cannot tell which plan its key is on, so the budget is an operator ceiling on spend, read from settings at acquire time:
+
+- `FIRECRAWL_EGRESS_PER_MINUTE_BUDGET` (default 60) smooths a burst of concurrent callers.
+- `FIRECRAWL_EGRESS_HOURLY_BUDGET` (default 1,000) caps what a runaway caller can spend before anyone notices.
+
+One scrape costs one credit, and one search costs two credits per ten results, so these numbers cap a bill as much as a rate.
+`search` reserves a second budget unit before the transport reserves its own, so one search draws two units.
+They are sized for roughly one scrape per event a person triggers, and are meant to be raised in settings as that grows.
+
+## Lanes and callers
+
+The default reserve ladder applies, and `firecrawl_request` defaults to `NORMAL`.
+Domain research for Tasks (`products/tasks/backend/facade/domain_research.py`) scrapes on `NORMAL`.
+The AI-enrichment label tools (`products/growth/backend/enrichment/tools.py`) search and scrape on `BATCH`.
+Nothing in this domain runs `CRITICAL`, because what gets scraped comes from user-supplied input and callers can do without the scrape.
+
+## Rate-limit headers
+
+Firecrawl documents no rate-limit status headers, so the domain declares no gauges.
+A 429 carries `Retry-After`, and the caller owns the retry.
+The counter is `firecrawl_api_requests_total`, labeled `account, method, endpoint, status_code, source`.
+
+## Auth
+
+`FIRECRAWL_API_KEY` authenticates every call as a bearer token.
+An instance without one makes no request at all: `scrape` and `search` raise `FirecrawlNotConfigured`.
+
+## Typed client
+
+Callers use `client.py` rather than `firecrawl_request`.
+`scrape(url, source=...)` returns a `FirecrawlScrape` (markdown, summary, page title, description, status code, credits used).
+It raises `FirecrawlScrapeFailed` when Firecrawl answers with anything but a successful scrape, including a 200 that carries `success: false`.
+`search(query, source=...)` returns a `FirecrawlSearch` of web results and raises `FirecrawlSearchFailed` on the same conditions.
+It rejects a `limit` above `MAX_SEARCH_LIMIT` or a query above `MAX_SEARCH_QUERY_CHARS` before any call.
+Only `POST /v2/scrape` and `POST /v2/search` are wired up.
+
+## Sources
+
+- [Rate limits](https://docs.firecrawl.dev/rate-limits): per-minute limits by plan for `/scrape` and `/search`.
+- [Errors](https://docs.firecrawl.dev/api-reference/errors): `Retry-After` on a 429, and no rate-limit status headers.
+- [Billing](https://docs.firecrawl.dev/billing): one credit per scrape, two credits per ten search results.
diff --git a/posthog/egress/firecrawl/limiter.py b/posthog/egress/firecrawl/limiter.py
index c537eba3a617..d9621f4a0fdb 100644
--- a/posthog/egress/firecrawl/limiter.py
+++ b/posthog/egress/firecrawl/limiter.py
@@ -11,46 +11,32 @@ Importing this module registers the policy as a side effect, so import it (direc
``consume_firecrawl_sync``) before using a ``firecrawl:...`` limiter key.
"""
-from django.conf import settings
-
from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+from posthog.egress.limiter.policies import Priority, per_minute_and_hourly_policy, register_policy
FIRECRAWL_DOMAIN = "firecrawl"
# One Firecrawl account per instance, so a constant id carries the instance-wide shared budget.
-_ACCOUNT_SCOPE_ID = "default"
-
-# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget fills,
-# then NORMAL. Nothing in this domain runs CRITICAL, because the scraped URL is derived from
-# user-supplied input and a never-shed lane would make the budget advisory.
-_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
+ACCOUNT_SCOPE_ID = "default"
# Operator ceilings on credit spend, not observed provider limits. Each scrape costs a credit, so
# the per-minute rate smooths a burst of concurrent sign-ups and the hourly rate caps what a runaway
-# caller can spend before someone notices.
-_DEFAULT_PER_MINUTE_BUDGET = 60
-_DEFAULT_HOURLY_BUDGET = 1_000
-
-
-# Registered as a provider so the budgets are read at acquire time, which means a settings override applies
-# without a process restart, matching the other egress domains.
-def _firecrawl_policy(key: str) -> RatePolicy:
- per_minute = int(getattr(settings, "FIRECRAWL_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))
- hourly = int(getattr(settings, "FIRECRAWL_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))
- return RatePolicy(
- limits=((per_minute, 60.0), (hourly, 3600.0)),
- in_memory_divider=4,
- reserve=_RESERVE,
- )
-
-
-register_policy(FIRECRAWL_DOMAIN, _firecrawl_policy)
+# caller can spend before someone notices. Nothing in this domain runs CRITICAL, because the scraped
+# URL is derived from user-supplied input and a never-shed lane would make the budget advisory.
+register_policy(
+ FIRECRAWL_DOMAIN,
+ per_minute_and_hourly_policy(
+ per_minute_setting="FIRECRAWL_EGRESS_PER_MINUTE_BUDGET",
+ per_minute_default=60,
+ hourly_setting="FIRECRAWL_EGRESS_HOURLY_BUDGET",
+ hourly_default=1_000,
+ ),
+)
def firecrawl_account_key() -> str:
"""Limiter key for the instance's single Firecrawl account, which is the unit Firecrawl meters."""
- return f"{FIRECRAWL_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"
+ return f"{FIRECRAWL_DOMAIN}:account:{ACCOUNT_SCOPE_ID}"
def consume_firecrawl_sync(n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:
diff --git a/posthog/egress/firecrawl/observability.py b/posthog/egress/firecrawl/observability.py
index 7e4b85932b6c..7cfc5c5f6eb2 100644
--- a/posthog/egress/firecrawl/observability.py
+++ b/posthog/egress/firecrawl/observability.py
@@ -1,107 +1,22 @@
"""Firecrawl egress telemetry.
-Every Firecrawl call funnels through these recorders so request volume lands on one metric set
-whichever subsystem made the call, attributed by the ``source`` label. Firecrawl meters each
-endpoint separately, so the gauges' ``resource`` is the endpoint the observed headers describe.
-"""
-
-from collections.abc import Mapping
-
-import requests
-from prometheus_client import Counter, Gauge
-
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- default_normalize_endpoint,
- register_egress_observability,
- unpack_requests_response,
-)
-
-FIRECRAWL_DOMAIN = "firecrawl"
-
-_metrics = EgressMetrics(
- request_counter=Counter(
- "firecrawl_api_requests",
- "Number of Firecrawl API requests made through the Firecrawl egress client.",
- labelnames=["account", "method", "endpoint", "status_code", "source"],
- ),
- remaining_gauge=Gauge(
- "firecrawl_api_rate_limit_remaining",
- "Most recently observed Firecrawl rate limit remaining count by endpoint.",
- labelnames=["account", "resource"],
- ),
- limit_gauge=Gauge(
- "firecrawl_api_rate_limit_limit",
- "Most recently observed Firecrawl rate limit by endpoint.",
- labelnames=["account", "resource"],
- ),
- reset_gauge=Gauge(
- "firecrawl_api_rate_limit_reset_timestamp_seconds",
- "Most recently observed Firecrawl rate limit reset timestamp by endpoint "
- "(unset: Firecrawl does not document the encoding of its reset header).",
- labelnames=["account", "resource"],
- ),
-)
-
-
-def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:
- if headers is None:
- return None
- value = headers.get(name)
- if value is None:
- return None
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
-
-
-def _parse_firecrawl_rate_limit(headers: Mapping[str, str] | None, url: str | None) -> RateLimitSnapshot:
- """Read Firecrawl's rate-limit headers when the response carries them. ``reset_at`` is left unset
- because Firecrawl does not document whether its reset header is an epoch or a number of seconds,
- and a gauge that could be either is worse than an unset one. ``resource`` comes from the request
- url, not a curated endpoint label, because Firecrawl meters each endpoint separately."""
- return RateLimitSnapshot(
- resource=default_normalize_endpoint(url),
- remaining=_float_header(headers, "X-RateLimit-Remaining"),
- limit=_float_header(headers, "X-RateLimit-Limit"),
- )
+Every Firecrawl call records through ``firecrawl_egress``, so request volume lands on one metric set
+whichever subsystem made the call, attributed by the ``source`` label.
+Firecrawl documents no rate-limit status headers, only ``Retry-After`` on a 429, so this domain
+declares no gauges.
+"""
-firecrawl_egress = EgressObservability(FIRECRAWL_DOMAIN, _metrics, _parse_firecrawl_rate_limit)
-register_egress_observability(firecrawl_egress)
+from prometheus_client import Counter
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
-def record_firecrawl_api_response(
- response: requests.Response,
- *,
- source: str,
- method: str | None = None,
- endpoint: str | None = None,
-) -> None:
- """Record one Firecrawl API response. The scope is always the instance's single account,
- because Firecrawl meters per API key and each instance holds exactly one."""
- primitives = unpack_requests_response(response)
- firecrawl_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope="default",
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
+firecrawl_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "firecrawl_api_requests",
+ "Number of Firecrawl API requests made through the Firecrawl egress client.",
+ labelnames=["account", "method", "endpoint", "status_code", "source"],
+ ),
)
-
-
-def record_firecrawl_api_exception(
- *,
- source: str,
- method: str,
- endpoint: str | None = None,
- url: str | None = None,
-) -> None:
- """Record a request that raised before a response (timeout, connection error)."""
- firecrawl_egress.record_exception(source=source, scope="default", method=method, endpoint=endpoint, url=url)
+)
diff --git a/posthog/egress/firecrawl/transport.py b/posthog/egress/firecrawl/transport.py
index ebd305140a40..b45c7dc7387c 100644
--- a/posthog/egress/firecrawl/transport.py
+++ b/posthog/egress/firecrawl/transport.py
@@ -10,14 +10,11 @@ from typing import Any
import requests
-from posthog.egress.firecrawl.limiter import consume_firecrawl_sync
-from posthog.egress.firecrawl.observability import record_firecrawl_api_exception, record_firecrawl_api_response
+from posthog.egress.firecrawl.limiter import ACCOUNT_SCOPE_ID, consume_firecrawl_sync
+from posthog.egress.firecrawl.observability import firecrawl_egress
from posthog.egress.limiter.policies import Priority
from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
-# The whole instance shares one Firecrawl account, so every call carries the same scope.
-_ACCOUNT_SCOPE = "default"
-
class FirecrawlEgressBudgetExhausted(EgressBudgetExhausted):
"""A sheddable (BATCH/NORMAL) Firecrawl call was shed by our egress limiter before it was sent.
@@ -28,20 +25,14 @@ class FirecrawlClient(EgressClient):
"""The Firecrawl incarnation of :class:`EgressClient`. Stateless, so one shared instance serves
every caller; wire it through :func:`firecrawl_request`."""
+ observability = firecrawl_egress
+
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json", "Content-Type": "application/json"}
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return consume_firecrawl_sync(priority=priority, source=source)
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_firecrawl_api_response(response, source=source, method=method, endpoint=endpoint)
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_firecrawl_api_exception(source=source, method=method, url=url, endpoint=endpoint)
-
def _budget_exhausted_error(self, scope: str) -> FirecrawlEgressBudgetExhausted:
return FirecrawlEgressBudgetExhausted("Firecrawl egress budget exhausted; degrading")
@@ -67,12 +58,13 @@ def firecrawl_request(
caller so far can do without the scrape, so Firecrawl traffic must not be able to consume the
whole budget the way a CRITICAL lane would.
"""
+ # The whole instance shares one Firecrawl account, so every call carries the same scope.
return _firecrawl_client.request(
method,
url,
source=source,
headers={"Authorization": f"Bearer {api_key}"},
- scope=_ACCOUNT_SCOPE,
+ scope=ACCOUNT_SCOPE_ID,
priority=priority,
endpoint=endpoint,
timeout=timeout,
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.md
new file mode 100644
index 000000000000..6a975f7c53b9
--- /dev/null
+++ b/posthog/egress/github/README.md
@@ -0,0 +1,88 @@
+# GitHub egress
+
+GitHub is the reference domain.
+Every GitHub API call in the codebase goes through it.
+
+## Identity
+
+The GitHub App **installation id**, because GitHub meters the rate limit per installation.
+Several PostHog integration rows can share one installation, and they all draw on its one budget.
+The limiter keys are `github:installation:<id>`, `github_search:installation:<id>`, and `github_code_search:installation:<id>`.
+
+## Budget
+
+GitHub meters its REST resources on separate per-installation counters, so this domain registers three limiter domains, and the transport routes each request to its meter by URL:
+
+- `github`: the `core` resource (5,000–15,000/hour), scaled to the installation's real tier. `api_request` persists each installation's last-observed core `X-RateLimit-Limit` (only trusted installation-token responses feed this), and the policy budgets 90% of it for the hour with a proportional per-minute smoothing cap. Unobserved installations fall back to `GITHUB_EGRESS_HOURLY_BUDGET` (13,500) and `GITHUB_EGRESS_PER_MINUTE_BUDGET` (750) until their first recorded response. Both settings are ceilings that tier scaling can only lower.
+- `github_search`: the `search` resource, a static 27/minute under GitHub's real 30/minute.
+- `github_code_search`: the `code_search` resource (`/search/code`), a static 8/minute under GitHub's real 10/minute.
+
+The two search budgets are static because GitHub's search limits do not depend on the plan tier, so there is no tier to observe.
+GraphQL routes to `core`. GitHub meters GraphQL by points, which a request counter cannot model, so charging it to `core` errs conservative.
+
+## Lanes and callers
+
+All three budgets use the default reserve ladder.
+Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override).
+A shed sweep stops for the cycle and resumes on the next scheduled run.
+A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.
+
+The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
+An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.
+So a non-`BATCH` `core` call writes a short-lived per-installation marker (`note_interactive_demand`), and the policy holds the full 70% floor only while that marker is present; without it `BATCH` falls back to a 10% floor, the same floor `NORMAL` keeps.
+Three details make that safe: the marker is written on the attempt rather than the outcome, so a _denied_ interactive call still counts; the floor matches `NORMAL`'s rather than dropping toward zero, so an unopposed backfill can never saturate the window past the point where the first interactive call would itself be denied, regardless of the marker it just wrote; and an unreachable cache reports demand as present, so a cache outage cannot hand the whole budget to bulk traffic.
+The two search resources keep the flat default ladder, because they are metered on their own counters and core demand says nothing about them.
+
+## Rate-limit headers
+
+`X-RateLimit-Remaining`, `X-RateLimit-Limit`, `X-RateLimit-Reset` and `X-RateLimit-Resource` feed the `github_integration_api_rate_limit_{remaining,limit,reset_timestamp_seconds}` gauges, labeled `installation_id, resource`.
+The counter is `github_integration_api_requests_total`, labeled `installation_id, method, endpoint, status_code, source`.
+Endpoint labels template out owner/repo, numeric ids, commit SHAs, and free-form tails (file paths, compare refs), so `/repos/{owner}/{repo}/statuses/{sha}` stays one series.
+
+## Auth
+
+`github_request` is token-agnostic (installation token, user token, PAT, or PostHog's shared token) and stateless:
+
+```python
+from posthog.egress.github.transport import github_request
+from posthog.egress.limiter.policies import Priority
+
+resp = github_request(
+ "GET",
+ url,
+ source="visual_review",
+ headers={"Authorization": f"Bearer {token}"}, # caller owns auth; the client adds Accept + API version
+ installation_id=installation_id, # budget owner; None = identity-blind (records volume only)
+ priority=Priority.CRITICAL, # CRITICAL never blocks; sheddable lanes raise on denial
+)
+```
+
+`raise_if_github_rate_limited` and `GitHubRateLimitError` (GitHub's own 429, the reactive twin of `GitHubEgressBudgetExhausted`) live in `transport.py` for callers that want to raise and retry.
+The model-coupled `GitHubIntegrationBase.api_request` layers the installation-token lifecycle (proactive refresh, 401 refresh-retry, rate-limit raising, per-instance `source` attribution) on top. Hold an integration, call that. Hold a bare token, call `github_request`.
+The `github-api-calls-go-through-egress` semgrep rule reads the URL argument only, which is why `posthog/plugins/utils.py` still calls `requests.get` directly with a URL it builds into a variable first.
+
+## Identity-blind callers and the PAT scope decision
+
+Some callers have no installation in scope.
+The important one is a warehouse source authenticated with a **personal access token (PAT)**: a customer's own token on the customer's own budget, disconnected from any PostHog installation (error tracking's public-repo path is the other).
+These record the counter only, under an empty `installation_id`, and skip both the limiter and the gauges.
+The counter still sums correctly, but identity-blind callers are **not distinguishable from one another**: every PAT lands on the same empty series, and writing headroom to a shared empty gauge would let unrelated tokens clobber each other.
+
+The scope line:
+
+- PAT request-**volume** telemetry is in scope and shipped (aggregate only).
+- PAT rate-limit **headroom** and PAT **limiting** are deferred, to revisit.
+
+Both need the same missing piece: a per-token identity (a hash of the token) to key on.
+The headers are already on the response, so it needs no request restructuring, but a token-hash label is higher-cardinality than an installation, so it's a deliberate choice, not a default.
+`GithubEgressIdentity` is the seam where such a key would thread through.
+
+## Caveats
+
+The cache-hit counter in `github_integration_base` is a separate concern (which rows are reading a warm cache) and legitimately keys by the integration row, not by the installation. It is not egress-budget telemetry.
+The caches it counts are installation-scoped, so a row can record a hit on an entry another row on the same installation filled.
+
+## Sources
+
+- [Rate limits for the REST API](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api): installation limits and the `x-ratelimit-*` headers.
+- [Search](https://docs.github.com/en/rest/search/search): the search and code search limits per minute.
diff --git a/posthog/egress/github/limiter.py b/posthog/egress/github/limiter.py
index fcc866f2840b..f651461ad0b6 100644
--- a/posthog/egress/github/limiter.py
+++ b/posthog/egress/github/limiter.py
@@ -28,7 +28,7 @@ if TYPE_CHECKING:
import requests
from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+from posthog.egress.limiter.policies import DEFAULT_RESERVE, Priority, RatePolicy, register_policy
GITHUB_DOMAIN = "github"
GITHUB_SEARCH_DOMAIN = "github_search"
@@ -68,14 +68,8 @@ _RESOURCE_DOMAINS: dict[GitHubRateResource, str] = {
GitHubRateResource.CODE_SEARCH: GITHUB_CODE_SEARCH_DOMAIN,
}
-# Reserved-floor ladder: BATCH calls are denied once 70% of a window is consumed, NORMAL at 90%,
-# CRITICAL can use the full budget. Active now that deferrable callers declare their lane
-# (code-workstreams polling and the job-logs worker at BATCH) — shedding them first is what keeps
-# headroom for user-facing traffic as an installation's budget fills.
-_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
-
-# Applied instead when an installation has served no recent interactive traffic. The BATCH floor
-# above keeps headroom for user-facing calls; on an installation whose only consumer is a bulk one
+# Applied instead of DEFAULT_RESERVE when an installation has served no recent interactive traffic.
+# The default BATCH floor keeps headroom for user-facing calls; on an installation whose only consumer is a bulk one
# — a warehouse backfill of a repository nothing else touches — it holds that headroom against
# contention which never arrives, and forfeits a third of the budget for the whole run. The hourly
# budget is what decides whether a large backfill finishes, so that third is the difference between
@@ -87,7 +81,7 @@ _RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
# point where that first interactive call would be admitted at all, regardless of the marker it
# just wrote. NORMAL's floor itself stays unchanged, because CRITICAL traffic arrives with no
# warning.
-_IDLE_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.10, Priority.NORMAL: 0.10}
+_IDLE_RESERVE: dict[Priority, float] = {**DEFAULT_RESERVE, Priority.BATCH: DEFAULT_RESERVE[Priority.NORMAL]}
# How long one interactive call holds the full reserve in place. Longer than a quiet gap in genuine
# interactive use, so the budget does not flap part-way through a backfill, and far shorter than a
@@ -281,7 +275,7 @@ def _github_policy(key: str) -> RatePolicy:
return RatePolicy(
limits=((per_minute, 60.0), (hourly, 3600.0)),
in_memory_divider=4,
- reserve=_RESERVE if has_interactive_demand(installation_id) else _IDLE_RESERVE,
+ reserve=DEFAULT_RESERVE if has_interactive_demand(installation_id) else _IDLE_RESERVE,
)
@@ -290,15 +284,9 @@ register_policy(GITHUB_DOMAIN, _github_policy)
# Static budgets, no observed-limit persistence: GitHub's search rate limits are fixed regardless
# of the account's plan tier (unlike core), so there is no tier to observe. Both sit just under
# GitHub's real per-installation ceilings (10/min and 30/min) so our reactive backoff absorbs
-# drift. Same reserve ladder as core so BATCH/NORMAL callers still shed first as the window fills.
-register_policy(
- GITHUB_CODE_SEARCH_DOMAIN,
- RatePolicy(limits=((8, 60.0),), in_memory_divider=4, reserve=_RESERVE),
-)
-register_policy(
- GITHUB_SEARCH_DOMAIN,
- RatePolicy(limits=((27, 60.0),), in_memory_divider=4, reserve=_RESERVE),
-)
+# drift. The default reserve ladder applies, so BATCH/NORMAL callers still shed first as the window fills.
+register_policy(GITHUB_CODE_SEARCH_DOMAIN, RatePolicy(limits=((8, 60.0),), in_memory_divider=4))
+register_policy(GITHUB_SEARCH_DOMAIN, RatePolicy(limits=((27, 60.0),), in_memory_divider=4))
def github_installation_key(
diff --git a/posthog/egress/github/observability.py b/posthog/egress/github/observability.py
index d6cfb156c1bb..550dab90167a 100644
--- a/posthog/egress/github/observability.py
+++ b/posthog/egress/github/observability.py
@@ -1,32 +1,25 @@
-"""GitHub egress telemetry — the first domain registered with the generic observability mechanism.
+"""GitHub egress telemetry on the generic observability mechanism.
-Every GitHub API client in the codebase funnels its responses through ``record_github_api_response``
-so request volume and GitHub's own ``X-RateLimit-*`` headers land on one metric set, regardless of
-which subsystem made the call (installation integration, warehouse source, Visual review,
-Conversations, ...). The ``source`` label keeps them apart on a single dashboard.
+Every GitHub API call in the codebase records through ``github_egress`` (via ``github_request``), so
+request volume and GitHub's own ``X-RateLimit-*`` headers land on one metric set, regardless of
+which subsystem made the call. The ``source`` label keeps them apart on a single dashboard.
-The metric names are kept stable (``github_integration_api_*``) so existing dashboards stay valid;
-the mechanism is the generic :class:`EgressObservability`, so a new outbound API is just another
-adapter module like this one.
+The metric names are kept stable (``github_integration_api_*``) so existing dashboards stay valid.
"""
import re
from collections.abc import Mapping
from urllib.parse import urlparse
-import requests
from prometheus_client import Counter, Gauge
from posthog.egress.observability.observability import (
EgressMetrics,
EgressObservability,
RateLimitSnapshot,
- register_egress_observability,
- unpack_requests_response,
+ float_header,
)
-GITHUB_DOMAIN = "github"
-
_metrics = EgressMetrics(
request_counter=Counter(
"github_integration_api_requests",
@@ -55,24 +48,12 @@ _metrics = EgressMetrics(
)
-def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:
- if headers is None:
- return None
- value = headers.get(name)
- if value is None:
- return None
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
-
-
def _parse_github_rate_limit(headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
return RateLimitSnapshot(
resource=headers.get("X-RateLimit-Resource", "unknown") if headers is not None else "unknown",
- remaining=_float_header(headers, "X-RateLimit-Remaining"),
- limit=_float_header(headers, "X-RateLimit-Limit"),
- reset_at=_float_header(headers, "X-RateLimit-Reset"),
+ remaining=float_header(headers, "X-RateLimit-Remaining"),
+ limit=float_header(headers, "X-RateLimit-Limit"),
+ reset_at=float_header(headers, "X-RateLimit-Reset"),
)
@@ -126,44 +107,4 @@ def _normalize_github_endpoint(url: str | None) -> str:
return "/" + "/".join(out)
-github_egress = EgressObservability(
- GITHUB_DOMAIN, _metrics, _parse_github_rate_limit, endpoint_normalizer=_normalize_github_endpoint
-)
-register_egress_observability(github_egress)
-
-
-def record_github_api_response(
- response: requests.Response,
- *,
- source: str,
- installation_id: str | None = None,
- method: str | None = None,
- endpoint: str | None = None,
-) -> None:
- """Record one GitHub API response. ``installation_id`` is the GitHub App installation — the shared
- rate-limit budget GitHub meters. Pass it when known so the rate-limit gauges are set; identity-blind
- callers (raw PATs) get request volume only. ``source`` attributes the call to a subsystem."""
- primitives = unpack_requests_response(response)
- github_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope=installation_id,
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
- )
-
-
-def record_github_api_exception(
- *,
- source: str,
- method: str,
- endpoint: str | None = None,
- url: str | None = None,
- installation_id: str | None = None,
-) -> None:
- """Record a request that raised before a response (timeout, connection error). Pass a curated
- ``endpoint`` or a raw ``url`` (normalised internally)."""
- github_egress.record_exception(source=source, scope=installation_id, method=method, endpoint=endpoint, url=url)
+github_egress = EgressObservability(_metrics, _parse_github_rate_limit, endpoint_normalizer=_normalize_github_endpoint)
diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.py
index db923ba94109..56e9b4cf51de 100644
--- a/posthog/egress/github/transport.py
+++ b/posthog/egress/github/transport.py
@@ -16,7 +16,7 @@ from typing import Any
import requests
from posthog.egress.github.limiter import classify_github_resource, consume_github_installation_sync
-from posthog.egress.github.observability import record_github_api_exception, record_github_api_response
+from posthog.egress.github.observability import github_egress
from posthog.egress.limiter.policies import Priority
from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
@@ -95,6 +95,8 @@ class GitHubClient(EgressClient):
"""The GitHub incarnation of :class:`EgressClient`. Stateless and token-agnostic, so one shared
instance serves every caller; wire it through :func:`github_request`."""
+ observability = github_egress
+
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}
@@ -103,14 +105,6 @@ class GitHubClient(EgressClient):
scope, resource=classify_github_resource(url), priority=priority, source=source
)
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_github_api_response(response, source=source, installation_id=scope, method=method, endpoint=endpoint)
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_github_api_exception(source=source, installation_id=scope, method=method, url=url, endpoint=endpoint)
-
def _budget_exhausted_error(self, scope: str) -> GitHubEgressBudgetExhausted:
return GitHubEgressBudgetExhausted(f"GitHub egress budget exhausted for installation {scope}; deferring")
diff --git a/posthog/egress/google_workspace/README.md b/posthog/egress/google_workspace/README.md
new file mode 100644
index 000000000000..3fea9f8fb8cb
--- /dev/null
+++ b/posthog/egress/google_workspace/README.md
@@ -0,0 +1,42 @@
+# Google Workspace egress
+
+## Identity
+
+The connected Google account's OAuth `sub`, under the key `google_workspace:account:<sub>`, because Gmail and Calendar meter quota per user per project.
+A caller with no account in scope, such as the Google OAuth diagnostics in `ee/api/google_oauth_diagnostics.py`, passes no scope and records volume only.
+
+## Budget
+
+Read from settings at acquire time:
+
+- `GOOGLE_WORKSPACE_EGRESS_PER_MINUTE_BUDGET` (default 250)
+- `GOOGLE_WORKSPACE_EGRESS_HOURLY_BUDGET` (default 10,000)
+
+[Gmail allows](https://developers.google.com/workspace/gmail/api/reference/quota) 6,000 quota units per user per minute, and `users.messages.get` costs 20 units, so 250 requests a minute stays under Google's limit even when every call is a message fetch.
+[Calendar allows](https://developers.google.com/workspace/calendar/api/guides/quota) 600 requests per user per minute.
+
+## Lanes and callers
+
+The policy is **flat** (`reserve={}`), and `google_workspace_request` defaults to `BATCH`.
+Every scoped caller is a background sync:
+
+- Gmail sync, `products/conversations/backend/services/gmail_sync.py`
+- Calendar sync, `products/customer_analytics/backend/logic/calendar_sync.py`
+
+No higher lane needs headroom, and the default ladder would deny the syncs at 70% of a budget that already sits close to Google's own limit.
+Add the ladder back if an interactive caller starts using this domain.
+
+## Rate-limit headers
+
+Google documents no rate-limit headers. [A quota error](https://developers.google.com/workspace/gmail/api/guides/handle-errors) is a 403 or 429 with a reason such as `rateLimitExceeded` in the JSON body, so the domain declares no gauges.
+The counter is `google_workspace_api_requests_total`, labeled `scope, method, endpoint, status_code, source`.
+
+## Auth
+
+The caller passes the account's OAuth access token, sent as a bearer token.
+
+## Sources
+
+- [Gmail usage limits](https://developers.google.com/workspace/gmail/api/reference/quota): quota units per user and per method.
+- [Calendar quotas](https://developers.google.com/workspace/calendar/api/guides/quota): requests per user per minute.
+- [Gmail errors](https://developers.google.com/workspace/gmail/api/guides/handle-errors): quota errors in the response body.
diff --git a/posthog/egress/google_workspace/limiter.py b/posthog/egress/google_workspace/limiter.py
index 24113438029f..c3f58e1a289a 100644
--- a/posthog/egress/google_workspace/limiter.py
+++ b/posthog/egress/google_workspace/limiter.py
@@ -1,22 +1,29 @@
-from django.conf import settings
+"""Google Workspace egress budget, keyed by the connected Google account.
-from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
-
-GOOGLE_WORKSPACE_DOMAIN = "google_workspace"
+Gmail and Calendar meter quota per user per project, so the scope is the account's OAuth ``sub``.
+Gmail allows 6,000 quota units per user per minute and ``users.messages.get`` costs 20, so the
+per-minute default of 250 stays under Google's limit even when every call is a message fetch.
+The policy is flat (``reserve={}``). Every scoped caller is a background sync that runs ``BATCH``,
+so no higher lane needs headroom, and the default ladder would deny the sync at 70% of a budget
+that already sits close to Google's own limit.
+"""
-def _google_workspace_policy(_key: str) -> RatePolicy:
- return RatePolicy(
- limits=(
- (int(getattr(settings, "GOOGLE_WORKSPACE_EGRESS_PER_MINUTE_BUDGET", 250)), 60.0),
- (int(getattr(settings, "GOOGLE_WORKSPACE_EGRESS_HOURLY_BUDGET", 10_000)), 3600.0),
- ),
- in_memory_divider=4,
- )
+from posthog.egress.limiter.outbound import get_outbound_rate_limiter
+from posthog.egress.limiter.policies import Priority, per_minute_and_hourly_policy, register_policy
+GOOGLE_WORKSPACE_DOMAIN = "google_workspace"
-register_policy(GOOGLE_WORKSPACE_DOMAIN, _google_workspace_policy)
+register_policy(
+ GOOGLE_WORKSPACE_DOMAIN,
+ per_minute_and_hourly_policy(
+ per_minute_setting="GOOGLE_WORKSPACE_EGRESS_PER_MINUTE_BUDGET",
+ per_minute_default=250,
+ hourly_setting="GOOGLE_WORKSPACE_EGRESS_HOURLY_BUDGET",
+ hourly_default=10_000,
+ reserve={},
+ ),
+)
def consume_google_workspace_sync(account_id: str, *, priority: Priority, source: str) -> bool:
diff --git a/posthog/egress/google_workspace/observability.py b/posthog/egress/google_workspace/observability.py
index 101712fac217..ad5988dd65d9 100644
--- a/posthog/egress/google_workspace/observability.py
+++ b/posthog/egress/google_workspace/observability.py
@@ -1,86 +1,19 @@
-from collections.abc import Mapping
+"""Google Workspace outbound request telemetry.
-import requests
-from prometheus_client import Counter, Gauge
+Google reports quota exhaustion in the error body, not in rate-limit headers, so this domain
+declares no gauges.
+"""
-from posthog.egress.google_workspace.limiter import GOOGLE_WORKSPACE_DOMAIN
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- register_egress_observability,
- unpack_requests_response,
-)
-
-_metrics = EgressMetrics(
- request_counter=Counter(
- "google_workspace_api_requests",
- "Outbound Google Workspace API requests.",
- labelnames=["scope", "method", "endpoint", "status_code", "source"],
- ),
- remaining_gauge=Gauge(
- "google_workspace_api_rate_limit_remaining",
- "Last observed Google Workspace API rate-limit remaining value.",
- labelnames=["scope", "resource"],
- ),
- limit_gauge=Gauge(
- "google_workspace_api_rate_limit_limit",
- "Last observed Google Workspace API rate-limit ceiling.",
- labelnames=["scope", "resource"],
- ),
- reset_gauge=Gauge(
- "google_workspace_api_rate_limit_reset_at",
- "Last observed Google Workspace API rate-limit reset timestamp.",
- labelnames=["scope", "resource"],
- ),
-)
-
-
-def _parse_google_workspace_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- return RateLimitSnapshot(resource="api")
+from prometheus_client import Counter
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
google_workspace_egress = EgressObservability(
- GOOGLE_WORKSPACE_DOMAIN,
- _metrics,
- _parse_google_workspace_rate_limit,
-)
-register_egress_observability(google_workspace_egress)
-
-
-def record_google_workspace_api_response(
- response: requests.Response,
- *,
- source: str,
- account_id: str,
- method: str,
- endpoint: str,
-) -> None:
- primitives = unpack_requests_response(response)
- google_workspace_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope=account_id,
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
- )
-
-
-def record_google_workspace_api_exception(
- *,
- source: str,
- account_id: str,
- method: str,
- endpoint: str,
- url: str,
-) -> None:
- google_workspace_egress.record_exception(
- source=source,
- scope=account_id,
- method=method,
- endpoint=endpoint,
- url=url,
+ EgressMetrics(
+ request_counter=Counter(
+ "google_workspace_api_requests",
+ "Outbound Google Workspace API requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
)
+)
diff --git a/posthog/egress/google_workspace/transport.py b/posthog/egress/google_workspace/transport.py
index 276cbc09883a..b9515234f1a6 100644
--- a/posthog/egress/google_workspace/transport.py
+++ b/posthog/egress/google_workspace/transport.py
@@ -3,10 +3,7 @@ from typing import Any
import requests
from posthog.egress.google_workspace.limiter import consume_google_workspace_sync
-from posthog.egress.google_workspace.observability import (
- record_google_workspace_api_exception,
- record_google_workspace_api_response,
-)
+from posthog.egress.google_workspace.observability import google_workspace_egress
from posthog.egress.limiter.policies import Priority
from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
@@ -16,46 +13,14 @@ class GoogleWorkspaceEgressBudgetExhausted(EgressBudgetExhausted):
class GoogleWorkspaceClient(EgressClient):
+ observability = google_workspace_egress
+
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json"}
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return consume_google_workspace_sync(scope, priority=priority, source=source)
- def _record_response(
- self,
- response: requests.Response,
- *,
- source: str,
- scope: str | None,
- method: str,
- endpoint: str | None,
- ) -> None:
- record_google_workspace_api_response(
- response,
- source=source,
- account_id=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- )
-
- def _record_exception(
- self,
- *,
- source: str,
- scope: str | None,
- method: str,
- url: str,
- endpoint: str | None,
- ) -> None:
- record_google_workspace_api_exception(
- source=source,
- account_id=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- url=url,
- )
-
def _budget_exhausted_error(self, scope: str) -> GoogleWorkspaceEgressBudgetExhausted:
return GoogleWorkspaceEgressBudgetExhausted("Google Workspace egress budget exhausted")
diff --git a/posthog/egress/harmonic/README.md b/posthog/egress/harmonic/README.md
new file mode 100644
index 000000000000..f68e1a57d8e6
--- /dev/null
+++ b/posthog/egress/harmonic/README.md
@@ -0,0 +1,44 @@
+# Harmonic egress
+
+## Identity
+
+Harmonic meters one account-wide rate limit, and an instance holds a single `HARMONIC_API_KEY`.
+Every call draws from one budget under the key `harmonic:account:default`.
+
+## Budget
+
+A single per-second ceiling read from settings at acquire time: `HARMONIC_EGRESS_PER_SECOND_BUDGET` (default 15).
+Harmonic documents a limit of 10 requests per second for most endpoints, with a 429 above it.
+Search agent and Scout task creation have lower limits of their own, and PostHog calls neither.
+The default sits above that on purpose. The `BATCH` reserve floors to 4 of 15 units, so the bulk lane is admitted up to 11 calls a second, next to the documented rate.
+
+## Lanes and callers
+
+The default reserve ladder applies, and it matters here, because the lanes carry very different traffic:
+
+- `CRITICAL`: signup enrichment and the ICP re-enrichment sweep, inside a short Temporal activity budget.
+- `BATCH`: the Salesforce enrichment sweep, which yields to them.
+
+The client is `ee/billing/salesforce_enrichment/harmonic_client.py`.
+The bulk sweep paces with `pace_seconds_harmonic` and `admission_interval_harmonic` rather than getting denied.
+A denied call raises `HarmonicEgressBudgetExhausted`. A caller that folds exceptions into an enrichment miss must catch it first, or a throttled lookup gets recorded as a company Harmonic does not know.
+
+## Rate-limit headers
+
+Harmonic documents `X-Ratelimit-Limit-Second` and `X-Ratelimit-Remaining-Second` on every response, and they feed the `harmonic_api_rate_limit_{limit,remaining}` gauges, with `account` as `resource`.
+Production has recorded no value on either gauge, although the recording path sets them for this scope and the worker exports gauges.
+Check a live response with the API key before you build a dashboard or tune the budget on them.
+Harmonic documents no reset header, so the domain declares no reset gauge.
+The counter is `harmonic_api_requests_total`.
+
+## Auth
+
+The caller sends the key in the `apikey` header, never as a URL query parameter, because a URL-borne key leaks into aiohttp exception telemetry.
+
+## Transport
+
+Harmonic is the async domain: it subclasses `AsyncEgressClient`, because its client speaks aiohttp, and the caller supplies its own `aiohttp.ClientSession`.
+
+## Sources
+
+- [API reference, rate limit](https://console.harmonic.ai/docs/api-reference/introduction#rate-limit): the per-second limit, the lower endpoint limits, and the headers. The page renders only with JavaScript, so open it in a browser.
diff --git a/posthog/egress/harmonic/limiter.py b/posthog/egress/harmonic/limiter.py
index b3b909db880e..fbc2d224dbf5 100644
--- a/posthog/egress/harmonic/limiter.py
+++ b/posthog/egress/harmonic/limiter.py
@@ -4,10 +4,10 @@ Harmonic bills one account-wide rate limit — there is one ``HARMONIC_API_KEY``
instance, not one per installation or team — so every call anywhere in the codebase draws from a
single shared budget under the constant key ``harmonic:account:default``.
-Harmonic documents a per-second limit for most endpoints and answers 429 above it, reporting the
-current limit and remaining allowance in ``X-Ratelimit-Limit-Second`` and
-``X-Ratelimit-Remaining-Second`` on every response. The budget is an operator ceiling tuned against
-the values this domain records from those headers.
+Harmonic's API reference documents a limit of 10 requests per second for most endpoints and answers
+429 above it. The default budget of 15 per second sits above
+that on purpose: the BATCH reserve floors to 4 of 15 units, so the bulk lane is admitted up to 11 calls a
+second, next to the documented rate.
Two very different consumers share this budget, so the priority lanes matter:
- CRITICAL (interactive): signup enrichment and the ICP re-enrichment sweep run inside a
@@ -27,28 +27,20 @@ from posthog.egress.limiter.policies import Priority, RatePolicy, register_polic
HARMONIC_DOMAIN = "harmonic"
# One account per instance — Harmonic meters usage account-wide, not per installation.
-_ACCOUNT_SCOPE_ID = "default"
-HARMONIC_ACCOUNT_KEY = f"{HARMONIC_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"
+ACCOUNT_SCOPE_ID = "default"
+HARMONIC_ACCOUNT_KEY = f"{HARMONIC_DOMAIN}:account:{ACCOUNT_SCOPE_ID}"
_DEFAULT_PER_SECOND_BUDGET = 15
HARMONIC_WINDOW_SECONDS = 1.0
-# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget
-# fills, then NORMAL, so the interactive lane (CRITICAL) can never be starved by the weekly bulk
-# enrichment job saturating the shared counter.
-_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
-
# Registered as a provider so the budget is read at acquire time — a settings override applies
-# without a process restart, matching the other egress domains.
+# without a process restart, matching the other egress domains. The default reserve ladder keeps the
+# interactive lane (CRITICAL) from being starved by the bulk enrichment job saturating the counter.
def _harmonic_policy(_key: str) -> RatePolicy:
per_second = int(getattr(settings, "HARMONIC_EGRESS_PER_SECOND_BUDGET", _DEFAULT_PER_SECOND_BUDGET))
- return RatePolicy(
- limits=((per_second, HARMONIC_WINDOW_SECONDS),),
- in_memory_divider=4,
- reserve=_RESERVE,
- )
+ return RatePolicy(limits=((per_second, HARMONIC_WINDOW_SECONDS),), in_memory_divider=4)
register_policy(HARMONIC_DOMAIN, _harmonic_policy)
diff --git a/posthog/egress/harmonic/observability.py b/posthog/egress/harmonic/observability.py
index 8c2cc3ea17ed..14c9e9b87d7a 100644
--- a/posthog/egress/harmonic/observability.py
+++ b/posthog/egress/harmonic/observability.py
@@ -1,22 +1,10 @@
"""Harmonic egress telemetry.
-Every Harmonic call funnels through these recorders so request volume and Harmonic's own
-rate-limit headers land on one metric set, attributed by the ``source`` label — the same generic
-:class:`EgressObservability` mechanism every other domain (github, logo.dev, Firecrawl, Vapi,
-Google Workspace, Slack) uses. Harmonic's client is aiohttp-based
-(``ee/billing/salesforce_enrichment/harmonic_client.py``), but ``record_response`` takes status
-code, headers and request method/url as plain primitives, so it's transport-agnostic — Harmonic's
-``HarmonicClient._record_response`` unpacks an ``aiohttp.ClientResponse`` itself and calls
-``record_harmonic_api_response(response.status, response.headers, ...)``.
-
-Harmonic bills one account-wide rate limit rather than a per-installation one, so ``_SCOPE`` (the
-metric scope label) and ``_RATE_LIMIT_RESOURCE`` (the rate-limit resource) are two distinct
-constants that happen to both be singletons for this domain today.
+Every Harmonic call records through ``harmonic_egress``, attributed by the ``source`` label.
Harmonic's API reference documents ``X-Ratelimit-Limit-Second`` and ``X-Ratelimit-Remaining-Second``
-on every response. The parser below reads those plus the GitHub-style ``X-RateLimit-*`` names, and
-returns None for anything absent or unparseable rather than raising: telemetry must never break the
-request it is recording.
+on every response, so the parser reads only those. It documents no reset header, so this domain
+declares no reset gauge. Production has recorded no value on either gauge yet; see the domain README.
"""
from collections.abc import Mapping
@@ -27,14 +15,9 @@ from posthog.egress.observability.observability import (
EgressMetrics,
EgressObservability,
RateLimitSnapshot,
- register_egress_observability,
+ float_header,
)
-HARMONIC_DOMAIN = "harmonic"
-
-# Harmonic bills one account-wide limit, not a per-installation one, so every call shares this scope.
-_SCOPE = "default"
-
# Harmonic rate-limits the whole account rather than per endpoint, so every observed header
# describes the same one resource.
_RATE_LIMIT_RESOURCE = "account"
@@ -55,60 +38,15 @@ _metrics = EgressMetrics(
"Most recently observed Harmonic rate limit.",
labelnames=["scope", "resource"],
),
- reset_gauge=Gauge(
- "harmonic_api_rate_limit_reset_timestamp_seconds",
- "Most recently observed Harmonic rate limit reset timestamp.",
- labelnames=["scope", "resource"],
- ),
)
-# Preferred first: the per-second variant matches the window this domain's policy actually gates.
-# Falls back to the GitHub-style name in case Harmonic serves only that one.
-_REMAINING_HEADERS = ("X-Ratelimit-Remaining-Second", "X-RateLimit-Remaining")
-_LIMIT_HEADERS = ("X-Ratelimit-Limit-Second", "X-RateLimit-Limit")
-_RESET_HEADERS = ("X-RateLimit-Reset",)
-
-
-def _first_float_header(headers: Mapping[str, str], names: tuple[str, ...]) -> float | None:
- for name in names:
- raw = headers.get(name)
- if raw is None:
- continue
- try:
- return float(raw)
- except (TypeError, ValueError):
- continue
- return None
-
def _parse_harmonic_rate_limit(headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- headers = headers or {}
return RateLimitSnapshot(
resource=_RATE_LIMIT_RESOURCE,
- remaining=_first_float_header(headers, _REMAINING_HEADERS),
- limit=_first_float_header(headers, _LIMIT_HEADERS),
- reset_at=_first_float_header(headers, _RESET_HEADERS),
+ remaining=float_header(headers, "X-Ratelimit-Remaining-Second"),
+ limit=float_header(headers, "X-Ratelimit-Limit-Second"),
)
-harmonic_egress = EgressObservability(HARMONIC_DOMAIN, _metrics, _parse_harmonic_rate_limit)
-register_egress_observability(harmonic_egress)
-
-
-def record_harmonic_api_response(
- status: int,
- headers: Mapping[str, str] | None,
- *,
- source: str,
- method: str,
- endpoint: str | None = None,
-) -> None:
- """Record one Harmonic API response. ``method``/``endpoint`` are the caller's curated labels —
- Harmonic's few endpoints (``/graphql``, ``/companies/{id}``, ``/enrichment_status``) are cheap
- to pass explicitly, so there is no URL-derived endpoint normaliser here."""
- harmonic_egress.record_response(status, headers, source=source, scope=_SCOPE, method=method, endpoint=endpoint)
-
-
-def record_harmonic_api_exception(*, source: str, method: str, endpoint: str | None = None) -> None:
- """Record a request that raised before a response (timeout, connection error)."""
- harmonic_egress.record_exception(source=source, scope=_SCOPE, method=method, endpoint=endpoint)
+harmonic_egress = EgressObservability(_metrics, _parse_harmonic_rate_limit)
diff --git a/posthog/egress/harmonic/transport.py b/posthog/egress/harmonic/transport.py
index afce382651e7..f9339db55d9c 100644
--- a/posthog/egress/harmonic/transport.py
+++ b/posthog/egress/harmonic/transport.py
@@ -1,23 +1,17 @@
"""Harmonic incarnation of the egress transport — async, since the Harmonic client is aiohttp-based
(``ee/billing/salesforce_enrichment/harmonic_client.py``). It subclasses
-:class:`posthog.egress.transport.transport.AsyncEgressClient`, the aiohttp counterpart to the
-``EgressClient`` base the sync domains (github, logo.dev, Firecrawl, Vapi) use.
+:class:`posthog.egress.transport.transport.AsyncEgressClient`.
"""
from typing import Any
import aiohttp
-from posthog.egress.harmonic.limiter import acquire_harmonic
-from posthog.egress.harmonic.observability import record_harmonic_api_exception, record_harmonic_api_response
+from posthog.egress.harmonic.limiter import ACCOUNT_SCOPE_ID, acquire_harmonic
+from posthog.egress.harmonic.observability import harmonic_egress
from posthog.egress.limiter.policies import Priority
from posthog.egress.transport.transport import AsyncEgressClient, EgressBudgetExhausted
-# Harmonic bills one account-wide budget, so every call carries the same scope. AsyncEgressClient
-# skips its gate entirely on a falsy scope, and Harmonic has no per-caller identity to gate on
-# instead, so this constant is what keeps every Harmonic call gated.
-_ACCOUNT_SCOPE = "default"
-
class HarmonicEgressBudgetExhausted(EgressBudgetExhausted):
"""A sheddable (BATCH/NORMAL) Harmonic call was shed by our egress limiter before it was ever
@@ -37,20 +31,14 @@ class HarmonicClient(AsyncEgressClient):
own ``aiohttp.ClientSession`` (``AsyncHarmonicClient`` already manages one via ``async with``,
matching aiohttp's recommended session-reuse pattern rather than one session per call)."""
+ observability = harmonic_egress
+
def _standard_headers(self) -> dict[str, str]:
return {"Content-Type": "application/json"}
async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return await acquire_harmonic(priority, source)
- def _record_response(
- self, response: aiohttp.ClientResponse, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_harmonic_api_response(response.status, response.headers, source=source, method=method, endpoint=endpoint)
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_harmonic_api_exception(source=source, method=method, endpoint=endpoint)
-
def _budget_exhausted_error(self, scope: str) -> HarmonicEgressBudgetExhausted:
return HarmonicEgressBudgetExhausted("Harmonic egress budget exhausted; degrading")
@@ -72,12 +60,15 @@ async def harmonic_request(
"""Make a gated, recorded Harmonic request on an existing session. ``source`` attributes the
call to a subsystem; callers own auth (the ``apikey`` header, never a URL query param — a
URL-borne key leaks into aiohttp exception telemetry)."""
+ # Harmonic bills one account-wide budget, so every call carries the same scope. AsyncEgressClient
+ # skips its gate entirely on a falsy scope, and Harmonic has no per-caller identity to gate on
+ # instead, so this constant is what keeps every Harmonic call gated.
return await _harmonic_client.request(
session,
method,
url,
source=source,
- scope=_ACCOUNT_SCOPE,
+ scope=ACCOUNT_SCOPE_ID,
priority=priority,
endpoint=endpoint,
headers=headers,
diff --git a/posthog/egress/limiter/policies.py b/posthog/egress/limiter/policies.py
index 85595c6cecb2..1813729b5905 100644
--- a/posthog/egress/limiter/policies.py
+++ b/posthog/egress/limiter/policies.py
@@ -12,9 +12,12 @@ backend swappable.
"""
from collections.abc import Callable, Mapping
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from enum import Enum
from math import floor
+from types import MappingProxyType
+
+from django.conf import settings
# (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.
@@ -32,6 +35,12 @@ class Priority(Enum):
BATCH = "batch" # deferrable bulk — yields the largest reserve, shed first
+# BATCH calls are denied once 70% of a window is consumed, NORMAL at 90%, and CRITICAL may use the
+# full budget. Every policy gets this ladder unless it passes its own, because a policy without a
+# reserve admits every lane to the full budget and makes the caller's priority meaningless.
+DEFAULT_RESERVE: Mapping[Priority, float] = MappingProxyType({Priority.BATCH: 0.30, Priority.NORMAL: 0.10})
+
+
@dataclass(frozen=True)
class RatePolicy:
"""A budget: one or more ``(count, period_seconds)`` limits enforced together.
@@ -42,15 +51,15 @@ class RatePolicy:
a 429) is the real backstop.
``reserve`` maps a :class:`Priority` to the fraction of each window's budget that must remain
- free for a call of that priority to be admitted. A priority absent from the map reserves nothing
- (0.0), so an empty ``reserve`` keeps every call critical-equivalent — exactly the pre-priority
- behavior. Fractions are validated to ``[0, 1)`` (1.0 would reserve the whole window and deny the
- priority forever).
+ free for a call of that priority to be admitted. It defaults to :data:`DEFAULT_RESERVE`. A
+ priority absent from the map reserves nothing (0.0), so ``reserve={}`` admits every lane to the
+ full budget. Pass it only for a domain with no higher-priority traffic to protect. Fractions are
+ validated to ``[0, 1)`` (1.0 would reserve the whole window and deny the priority forever).
"""
limits: tuple[RateLimit, ...]
in_memory_divider: int = 1
- reserve: Mapping[Priority, float] = field(default_factory=dict)
+ reserve: Mapping[Priority, float] = DEFAULT_RESERVE
def __post_init__(self) -> None:
# A policy with no limits would let every call through, defeating the point. Reject it at
@@ -67,14 +76,41 @@ class RatePolicy:
def reserve_amount(self, priority: Priority, count: int) -> int:
"""Units of a window of size ``count`` this priority must leave free: ``floor(fraction * count)``.
- floor (not round/ceil) so a 0 fraction reserves exactly 0, keeping the no-reserve path
- bit-identical to pre-priority behavior. Single source for both admission (backend) and
- validation (facade), so the two can't drift."""
+ floor (not round/ceil) so a 0 fraction reserves exactly 0 and a flat policy admits every lane
+ to the full window. Single source for both admission (backend) and validation (facade), so
+ the two can't drift."""
return floor(self.reserve_fraction(priority) * count)
PolicyProvider = Callable[[str], RatePolicy]
+
+def per_minute_and_hourly_policy(
+ *,
+ per_minute_setting: str,
+ per_minute_default: int,
+ hourly_setting: str,
+ hourly_default: int,
+ reserve: Mapping[Priority, float] = DEFAULT_RESERVE,
+) -> PolicyProvider:
+ """A provider for the common budget: a per-minute rate that smooths bursts and an hourly rate
+ that caps total spend, both read from settings on each acquire so an override applies without a
+ process restart. ``in_memory_divider`` is 4 because a Redis outage leaves each worker process
+ with its own counter."""
+
+ def provider(_key: str) -> RatePolicy:
+ return RatePolicy(
+ limits=(
+ (int(getattr(settings, per_minute_setting, per_minute_default)), 60.0),
+ (int(getattr(settings, hourly_setting, hourly_default)), 3600.0),
+ ),
+ in_memory_divider=4,
+ reserve=reserve,
+ )
+
+ return provider
+
+
_REGISTRY: dict[str, PolicyProvider] = {}
diff --git a/posthog/egress/logodev/README.md b/posthog/egress/logodev/README.md
new file mode 100644
index 000000000000..050b6c381b55
--- /dev/null
+++ b/posthog/egress/logodev/README.md
@@ -0,0 +1,42 @@
+# logo.dev egress
+
+## Identity
+
+logo.dev meters usage per account, and an instance configures one account.
+The whole instance draws from one budget under the key `logodev:account:default`.
+
+## Budget
+
+logo.dev limits requests per month by plan, not per minute or per hour, so the budget is an operator ceiling read from settings at acquire time:
+
+- `LOGODEV_EGRESS_PER_MINUTE_BUDGET` (default 300) smooths bursts, such as a catalog page fanning out cache misses.
+- `LOGODEV_EGRESS_HOURLY_BUDGET` (default 5,000) caps total spend.
+
+Icon bytes are never stored server-side, because logo.dev licenses that separately.
+Browser caching (`posthog/cdp/services/icons.py` sets `Cache-Control`) is the only dedupe, so steady-state traffic tracks unique (user, icon) first views per day.
+Raise the settings if that outgrows the defaults.
+
+## Lanes and callers
+
+The default reserve ladder applies.
+The CDP icon picker and MCP store icons (`posthog/cdp/services/icons.py`, source `cdp_icons`) call on the `NORMAL` lane.
+Nothing in this domain runs `CRITICAL`, because the icon id is user-controlled and a never-shed lane would make the budget advisory.
+A denied call raises `LogoDevEgressBudgetExhausted`, and the caller degrades to no icon.
+
+## Rate-limit headers
+
+logo.dev documents that it returns no `Retry-After`, `X-RateLimit-*`, or quota headers on any endpoint, so the domain declares no gauges.
+A request over the plan's limit gets a 429.
+The counter is `logodev_api_requests_total`, labeled `account, method, endpoint, status_code, source`.
+Image URLs collapse to the `/img/{domain}` endpoint label, so each brand does not mint its own series.
+
+## Auth
+
+- Image CDN requests use `LOGO_DEV_PUBLISHABLE_KEY` (a `pk_` key) as a query parameter.
+- Search API requests use `LOGO_DEV_SECRET_KEY` (an `sk_` key) as a bearer token.
+- `LOGO_DEV_TOKEN` is a deprecated fallback for image requests only, and never authenticates a Search API request.
+
+## Sources
+
+- [Rate limits](https://www.logo.dev/docs/platform/rate-limits): monthly limits by plan.
+- [Errors and status codes](https://www.logo.dev/docs/platform/errors): 429 on the plan limit, and no rate-limit headers.
diff --git a/posthog/egress/logodev/limiter.py b/posthog/egress/logodev/limiter.py
index f80994490185..dc9f286ee008 100644
--- a/posthog/egress/logodev/limiter.py
+++ b/posthog/egress/logodev/limiter.py
@@ -2,8 +2,8 @@
logo.dev meters usage per account, and each PostHog instance configures the image and Search API
credentials from that account, so the whole instance draws from a single shared budget under a
-constant scope. logo.dev publishes no hard rate-limit numbers, so the defaults are deliberately
-modest operator ceilings. Icon bytes are never stored server-side (logo.dev gates that behind a
+constant scope. logo.dev limits requests per month by plan, with no per-minute or hourly limit, so
+the defaults are deliberately modest operator ceilings. Icon bytes are never stored server-side (logo.dev gates that behind a
data-caching license), so upstream volume is deduped only per user, by the browser caching that
:mod:`posthog.cdp.services.icons` directs — steady-state traffic tracks unique (user, icon) first
views per day. Raise the settings below if that outgrows the defaults.
@@ -12,45 +12,32 @@ Importing this module registers the policy as a side effect — import it (direc
``consume_logodev_sync``) before using a ``logodev:...`` limiter key.
"""
-from django.conf import settings
-
from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+from posthog.egress.limiter.policies import Priority, per_minute_and_hourly_policy, register_policy
LOGODEV_DOMAIN = "logodev"
# One account per instance — the constant id for the instance-wide shared budget.
-_ACCOUNT_SCOPE_ID = "default"
-
-# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget
-# fills, then NORMAL. All icon traffic runs NORMAL — the icon id is user-controlled, so nothing in
-# this domain should run CRITICAL (a never-shed lane would make the budget advisory).
-_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
+ACCOUNT_SCOPE_ID = "default"
# Operator ceilings, not observed provider limits (logo.dev exposes none to observe). The per-minute
# rate smooths bursts (a catalog page fanning out cache misses), the hourly rate caps total spend.
-_DEFAULT_PER_MINUTE_BUDGET = 300
-_DEFAULT_HOURLY_BUDGET = 5_000
-
-
-# Registered as a provider so the budgets are read at acquire time — a settings override applies
-# without a process restart, matching the other egress domains.
-def _logodev_policy(key: str) -> RatePolicy:
- per_minute = int(getattr(settings, "LOGODEV_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))
- hourly = int(getattr(settings, "LOGODEV_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))
- return RatePolicy(
- limits=((per_minute, 60.0), (hourly, 3600.0)),
- in_memory_divider=4,
- reserve=_RESERVE,
- )
-
-
-register_policy(LOGODEV_DOMAIN, _logodev_policy)
+# All icon traffic runs NORMAL — the icon id is user-controlled, so nothing in this domain should run
+# CRITICAL (a never-shed lane would make the budget advisory).
+register_policy(
+ LOGODEV_DOMAIN,
+ per_minute_and_hourly_policy(
+ per_minute_setting="LOGODEV_EGRESS_PER_MINUTE_BUDGET",
+ per_minute_default=300,
+ hourly_setting="LOGODEV_EGRESS_HOURLY_BUDGET",
+ hourly_default=5_000,
+ ),
+)
def logodev_account_key() -> str:
"""Limiter key for the instance's single logo.dev account — the unit logo.dev meters."""
- return f"{LOGODEV_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"
+ return f"{LOGODEV_DOMAIN}:account:{ACCOUNT_SCOPE_ID}"
def consume_logodev_sync(n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:
diff --git a/posthog/egress/logodev/observability.py b/posthog/egress/logodev/observability.py
index 1e9931a1c851..5c25c6cc478a 100644
--- a/posthog/egress/logodev/observability.py
+++ b/posthog/egress/logodev/observability.py
@@ -1,27 +1,15 @@
"""logo.dev egress telemetry.
-Every logo.dev call funnels through these recorders so request volume lands on one metric set
+Every logo.dev call records through ``logodev_egress``, so request volume lands on one metric set
whichever subsystem made the call (CDP icon picker, MCP store icons, ...), attributed by the
-``source`` label. logo.dev reports no rate-limit response headers, so the parser returns an empty
-snapshot and the gauges stay unset — they exist because :class:`EgressMetrics` requires the full
-instrument set, and they start reporting the moment logo.dev grows the headers.
+``source`` label. logo.dev reports no rate-limit response headers, so this domain declares no gauges.
"""
-from collections.abc import Mapping
from urllib.parse import urlparse
-import requests
-from prometheus_client import Counter, Gauge
+from prometheus_client import Counter
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- register_egress_observability,
- unpack_requests_response,
-)
-
-LOGODEV_DOMAIN = "logodev"
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
_metrics = EgressMetrics(
request_counter=Counter(
@@ -29,28 +17,9 @@ _metrics = EgressMetrics(
"Number of logo.dev API requests made through the logo.dev egress client.",
labelnames=["account", "method", "endpoint", "status_code", "source"],
),
- remaining_gauge=Gauge(
- "logodev_api_rate_limit_remaining",
- "Most recently observed logo.dev rate limit remaining count (unset: logo.dev reports no rate-limit headers).",
- labelnames=["account", "resource"],
- ),
- limit_gauge=Gauge(
- "logodev_api_rate_limit_limit",
- "Most recently observed logo.dev rate limit (unset: logo.dev reports no rate-limit headers).",
- labelnames=["account", "resource"],
- ),
- reset_gauge=Gauge(
- "logodev_api_rate_limit_reset_timestamp_seconds",
- "Most recently observed logo.dev rate limit reset timestamp (unset: logo.dev reports no rate-limit headers).",
- labelnames=["account", "resource"],
- ),
)
-def _parse_logodev_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- return RateLimitSnapshot()
-
-
def _normalize_logodev_endpoint(url: str | None) -> str:
"""Collapse a logo.dev URL to a low-cardinality endpoint label. ``img.logo.dev/{brand-domain}``
would otherwise mint one label per brand, so the brand path is templated to ``/img/{domain}``;
@@ -64,40 +33,4 @@ def _normalize_logodev_endpoint(url: str | None) -> str:
return path or "/"
-logodev_egress = EgressObservability(
- LOGODEV_DOMAIN, _metrics, _parse_logodev_rate_limit, endpoint_normalizer=_normalize_logodev_endpoint
-)
-register_egress_observability(logodev_egress)
-
-
-def record_logodev_api_response(
- response: requests.Response,
- *,
- source: str,
- method: str | None = None,
- endpoint: str | None = None,
-) -> None:
- """Record one logo.dev API response. The scope is always the instance's single account —
- logo.dev meters per token and each instance holds exactly one."""
- primitives = unpack_requests_response(response)
- logodev_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope="default",
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
- )
-
-
-def record_logodev_api_exception(
- *,
- source: str,
- method: str,
- endpoint: str | None = None,
- url: str | None = None,
-) -> None:
- """Record a request that raised before a response (timeout, connection error)."""
- logodev_egress.record_exception(source=source, scope="default", method=method, endpoint=endpoint, url=url)
+logodev_egress = EgressObservability(_metrics, endpoint_normalizer=_normalize_logodev_endpoint)
diff --git a/posthog/egress/logodev/transport.py b/posthog/egress/logodev/transport.py
index 9edb7536068f..e6263283e332 100644
--- a/posthog/egress/logodev/transport.py
+++ b/posthog/egress/logodev/transport.py
@@ -11,13 +11,10 @@ from typing import Any
import requests
from posthog.egress.limiter.policies import Priority
-from posthog.egress.logodev.limiter import consume_logodev_sync
-from posthog.egress.logodev.observability import record_logodev_api_exception, record_logodev_api_response
+from posthog.egress.logodev.limiter import ACCOUNT_SCOPE_ID, consume_logodev_sync
+from posthog.egress.logodev.observability import logodev_egress
from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
-# The whole instance shares one logo.dev account, so every call carries the same scope.
-_ACCOUNT_SCOPE = "default"
-
class LogoDevEgressBudgetExhausted(EgressBudgetExhausted):
"""A sheddable (BATCH/NORMAL) logo.dev call was shed by our egress limiter before it was sent.
@@ -28,20 +25,11 @@ class LogoDevClient(EgressClient):
"""The logo.dev incarnation of :class:`EgressClient`. Stateless — one shared instance serves
every caller; wire it through :func:`logodev_request`."""
- def _standard_headers(self) -> dict[str, str]:
- return {}
+ observability = logodev_egress
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
return consume_logodev_sync(priority=priority, source=source)
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_logodev_api_response(response, source=source, method=method, endpoint=endpoint)
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_logodev_api_exception(source=source, method=method, url=url, endpoint=endpoint)
-
def _budget_exhausted_error(self, scope: str) -> LogoDevEgressBudgetExhausted:
return LogoDevEgressBudgetExhausted("logo.dev egress budget exhausted; degrading")
@@ -62,11 +50,12 @@ def logodev_request(
) -> requests.Response:
"""Make a gated, recorded logo.dev request. ``source`` attributes the call to a subsystem;
callers pass the authentication required by their selected logo.dev endpoint."""
+ # The whole instance shares one logo.dev account, so every call carries the same scope.
return _logodev_client.request(
method,
url,
source=source,
- scope=_ACCOUNT_SCOPE,
+ scope=ACCOUNT_SCOPE_ID,
priority=priority,
endpoint=endpoint,
timeout=timeout,
diff --git a/posthog/egress/observability/observability.py b/posthog/egress/observability/observability.py
index c57702f78a9d..136e9ba497b2 100644
--- a/posthog/egress/observability/observability.py
+++ b/posthog/egress/observability/observability.py
@@ -1,15 +1,15 @@
"""Generic outbound API egress observability — the metrics analog of the egress limiter.
-Mirrors the limiter's shape (:mod:`posthog.egress.limiter.outbound`): a domain-agnostic mechanism,
-with each third-party API registered as a *domain* that supplies its own metric set and a parser for
-that API's rate-limit response headers. A consumer records a response against a domain; the registered
-:class:`EgressObservability` does the rest.
+A domain-agnostic mechanism: each third-party API constructs one :class:`EgressObservability` with
+its own metric set and, when the API reports its budget, a parser for its rate-limit response headers.
+The domain's transport records every request through that instance.
Each domain keeps its own metric names (rather than one shared namespace) so existing dashboards stay
-valid and every API can name its metrics idiomatically — the reuse is in the recording mechanism, the
-endpoint-normalisation, and the registry, not in a single metric series.
+valid and every API can name its metrics idiomatically — the reuse is in the recording mechanism and
+the endpoint-normalisation, not in a single metric series.
"""
+import hashlib
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from urllib.parse import urlparse
@@ -17,8 +17,6 @@ from urllib.parse import urlparse
import requests
from prometheus_client import Counter, Gauge
-from posthog.dataclasses import frozen
-
@dataclass(frozen=True)
class RateLimitSnapshot:
@@ -39,12 +37,35 @@ class RateLimitSnapshot:
ResponseParser = Callable[[Mapping[str, str] | None, str | None], RateLimitSnapshot]
+def float_header(headers: Mapping[str, str] | None, name: str) -> float | None:
+ """A numeric header, or ``None`` when it is absent or unparseable. Telemetry must never break the
+ request it records, so a malformed value is dropped rather than raised."""
+ if headers is None:
+ return None
+ value = headers.get(name)
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def scope_fingerprint(*parts: str) -> str:
+ """A metric scope built from values that must not reach a label in plain form, such as a token.
+ The scope reaches Prometheus, and from there dashboards and alerts."""
+ return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]
+
+
@dataclass(frozen=True)
class EgressMetrics:
"""The Prometheus instruments one domain records on. The recorder fills labels positionally,
so a domain's metrics must declare them in this order: the counter as
``(<scope>, method, endpoint, status_code, source)`` and each gauge as ``(<scope>, resource)``.
+ The gauges are optional. A domain whose API reports no rate-limit headers declares none, because
+ a gauge that nothing can set only adds an empty series to every dashboard query.
+
``<scope>`` is the rate-limit budget owner in the *domain's own* id space — for GitHub the App
``installation_id`` (what GitHub actually meters), never a PostHog DB row id. Keeping the identity in
the external API's namespace is what lets one shared budget map to one series: several PostHog
@@ -57,9 +78,9 @@ class EgressMetrics:
value per source after that source goes quiet, misreporting remaining budget."""
request_counter: Counter
- remaining_gauge: Gauge
- limit_gauge: Gauge
- reset_gauge: Gauge
+ remaining_gauge: Gauge | None = None
+ limit_gauge: Gauge | None = None
+ reset_gauge: Gauge | None = None
def default_normalize_endpoint(url: str | None) -> str:
@@ -73,39 +94,9 @@ def default_normalize_endpoint(url: str | None) -> str:
return "/" + "/".join("{id}" if seg.isdigit() else seg for seg in path.split("/"))
-@frozen
-class ResponsePrimitives:
- """What :meth:`EgressObservability.record_response` needs, independent of the HTTP client that
- produced it. ``request_method`` and ``request_url`` come from the request, not the response."""
-
- status_code: int
- headers: Mapping[str, str] | None
- request_method: str | None
- request_url: str | None
-
-
-def unpack_requests_response(response: requests.Response) -> ResponsePrimitives:
- """Pull the primitives :meth:`EgressObservability.record_response` needs off a ``requests.Response``:
- status code, headers, and the prepared request's method/url. A response's ``.request`` (and its
- method/url) may be absent or non-string — a response built without a prepared request, or a test
- mock whose attributes are themselves Mocks — so this coerces to str-or-None/Mapping-or-None rather
- than raising: telemetry is best-effort, and a urlparse(Mock) blowing up here must not fail the
- actual outbound call."""
- headers = response.headers if isinstance(response.headers, Mapping) else None
- request = getattr(response, "request", None)
- req_method = getattr(request, "method", None)
- req_url = getattr(request, "url", None)
- return ResponsePrimitives(
- status_code=response.status_code,
- headers=headers,
- request_method=req_method if isinstance(req_method, str) else None,
- request_url=req_url if isinstance(req_url, str) else None,
- )
-
-
class EgressObservability:
- """One third-party API's egress telemetry: a metric set, a response parser, and an endpoint
- normaliser. Construct one per domain and register it; consumers record through it.
+ """One third-party API's egress telemetry: a metric set, an optional response parser, and an
+ endpoint normaliser. Construct one per domain; the domain's transport records through it.
``scope`` is the rate-limit budget owner in the domain's own id space (e.g. a GitHub App installation
id, which several PostHog integrations can share) — not a PostHog DB row id. The counter is always
@@ -115,12 +106,10 @@ class EgressObservability:
def __init__(
self,
- domain: str,
metrics: EgressMetrics,
- parser: ResponseParser,
+ parser: ResponseParser | None = None,
endpoint_normalizer: Callable[[str | None], str] = default_normalize_endpoint,
) -> None:
- self.domain = domain
self._metrics = metrics
self._parser = parser
self._normalize_endpoint = endpoint_normalizer
@@ -140,24 +129,54 @@ class EgressObservability:
"""``status_code``/``headers`` are the response's own; ``request_method``/``request_url`` are
the request's, used only as a fallback when the caller doesn't pass a curated ``method``/
``endpoint``. Callers unpack their transport's response type into these primitives (see
- :func:`unpack_requests_response` for the ``requests`` case) so this method stays
+ :meth:`record_requests_response` for the ``requests`` case) so this method stays
transport-agnostic — sync (``requests``) and async (``aiohttp``) domains share it alike."""
method_label = (method or request_method or "GET").upper()
endpoint_label = endpoint if endpoint is not None else self._normalize_endpoint(request_url)
self._metrics.request_counter.labels(scope or "", method_label, endpoint_label, str(status_code), source).inc()
- if scope is None:
+ if not scope or self._parser is None:
return
# Gauges are keyed by (scope, resource) only — the shared budget owner, no source. Every
# source sharing one budget updates one series; a per-source gauge would strand stale values.
snapshot = self._parser(headers, request_url)
- if snapshot.remaining is not None:
- self._metrics.remaining_gauge.labels(scope, snapshot.resource).set(snapshot.remaining)
- if snapshot.limit is not None:
- self._metrics.limit_gauge.labels(scope, snapshot.resource).set(snapshot.limit)
- if snapshot.reset_at is not None:
- self._metrics.reset_gauge.labels(scope, snapshot.resource).set(snapshot.reset_at)
+ for gauge, value in (
+ (self._metrics.remaining_gauge, snapshot.remaining),
+ (self._metrics.limit_gauge, snapshot.limit),
+ (self._metrics.reset_gauge, snapshot.reset_at),
+ ):
+ if gauge is not None and value is not None:
+ gauge.labels(scope, snapshot.resource).set(value)
+
+ def record_requests_response(
+ self,
+ response: requests.Response,
+ *,
+ source: str,
+ scope: str | None = None,
+ method: str | None = None,
+ endpoint: str | None = None,
+ ) -> None:
+ """:meth:`record_response` for a ``requests.Response``, the shape every sync domain holds.
+
+ A response's ``.request`` (and its method/url) may be absent or non-string — a response built
+ without a prepared request, or a test mock whose attributes are themselves Mocks — so this
+ coerces them to str-or-None rather than raising: telemetry is best-effort, and a
+ urlparse(Mock) blowing up here must not fail the actual outbound call."""
+ request = getattr(response, "request", None)
+ request_method = getattr(request, "method", None)
+ request_url = getattr(request, "url", None)
+ self.record_response(
+ response.status_code,
+ response.headers if isinstance(response.headers, Mapping) else None,
+ source=source,
+ scope=scope,
+ method=method,
+ endpoint=endpoint,
+ request_method=request_method if isinstance(request_method, str) else None,
+ request_url=request_url if isinstance(request_url, str) else None,
+ )
def record_exception(
self,
@@ -193,43 +212,3 @@ def record_outbound_decision(*, domain: str, source: str, priority: str, granted
"""Record one limiter decision. ``priority`` is the lane string (e.g. ``"batch"``); the caller
derives ``domain`` from the limiter key's first segment so this stays limiter-library-agnostic."""
outbound_rate_limit_decisions.labels(domain, source, priority, "true" if granted else "false").inc()
-
-
-_REGISTRY: dict[str, EgressObservability] = {}
-
-
-def register_egress_observability(observability: EgressObservability) -> None:
- _REGISTRY[observability.domain] = observability
-
-
-def resolve_egress_observability(domain: str) -> EgressObservability:
- obs = _REGISTRY.get(domain)
- if obs is None:
- raise ValueError(
- f"No egress observability registered for domain '{domain}'; "
- "register one with register_egress_observability() before recording against it"
- )
- return obs
-
-
-def record_outbound_api_response(
- response: requests.Response,
- *,
- domain: str,
- source: str,
- scope: str | None = None,
- method: str | None = None,
- endpoint: str | None = None,
-) -> None:
- """Domain-keyed convenience for generic callers that hold only a domain string."""
- primitives = unpack_requests_response(response)
- resolve_egress_observability(domain).record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope=scope,
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
- )
diff --git a/posthog/egress/slack/README.md b/posthog/egress/slack/README.md
new file mode 100644
index 000000000000..26a565f3c834
--- /dev/null
+++ b/posthog/egress/slack/README.md
@@ -0,0 +1,40 @@
+# Slack egress
+
+## Identity
+
+The Slack workspace id for Web API calls.
+The Retry-After gauge adds the app id to its `resource` label, because Slack applies a 429 to one app and one method.
+
+## Budget
+
+None: Slack calls are recorded, never gated (`RecordedEgressClient`).
+Slack applies Web API limits per method, workspace, and app, with special limits such as per-channel message posting.
+Installation age and Marketplace status also change the limits for history methods.
+With no single budget to draw from, a proactive limiter would guess, so callers keep owning reactive retries.
+
+## Lanes and callers
+
+No lanes, because nothing is gated.
+
+- Slack SDK calls use `SlackWebClient` or `SlackAsyncWebClient` from `client.py` and `async_client.py`. A retry handler records every HTTP attempt, including each retry.
+- Direct HTTP calls, such as file downloads in `posthog/temporal/ai/slack_app/attachments.py`, use `slack_request`.
+- The OAuth code exchange in `posthog/models/integration/oauth.py` records its response with `record_slack_api_response`.
+
+The `slack-api-calls-go-through-egress` semgrep rule fails CI on a bare `WebClient` or a raw `requests` call to `slack.com/api`.
+
+Incoming webhooks and interactivity `response_url` calls are not Web API calls.
+Their secret URL is the budget identity, and persisting or labeling by it would expose credentials, so their error handling stays with the caller.
+
+## Rate-limit headers
+
+Slack returns no remaining-budget headers.
+A 429's `Retry-After` sets `slack_api_rate_limit_reset_timestamp_seconds`, labeled `workspace_id` and `resource` as `<app_id>:<method>`.
+The counter is `slack_api_requests_total`, labeled `workspace_id, method, endpoint, status_code, source`.
+
+## Auth
+
+The caller passes its bot or user token.
+
+## Sources
+
+- [Web API rate limits](https://docs.slack.dev/apis/web-api/rate-limits): limits per method and workspace, the Marketplace change, and `Retry-After` on a 429.
diff --git a/posthog/egress/slack/async_client.py b/posthog/egress/slack/async_client.py
index 13dc7558feb9..c35c04f27e87 100644
--- a/posthog/egress/slack/async_client.py
+++ b/posthog/egress/slack/async_client.py
@@ -6,11 +6,7 @@ from slack_sdk.http_retry.response import HttpResponse
from slack_sdk.http_retry.state import RetryState
from slack_sdk.web.async_client import AsyncWebClient
-from posthog.egress.slack.observability import (
- record_slack_api_exception,
- record_slack_api_response,
- slack_endpoint_from_url,
-)
+from posthog.egress.slack.observability import record_slack_attempt
class SlackAsyncObservabilityHandler(AsyncRetryHandler):
@@ -28,23 +24,13 @@ class SlackAsyncObservabilityHandler(AsyncRetryHandler):
response: HttpResponse | None = None,
error: Exception | None = None,
) -> bool:
- endpoint = slack_endpoint_from_url(request.url)
- if response is not None:
- record_slack_api_response(
- response,
- source=self._source,
- workspace_id=self._workspace_id,
- app_id=self._app_id,
- method=request.method,
- endpoint=endpoint,
- )
- else:
- record_slack_api_exception(
- source=self._source,
- workspace_id=self._workspace_id,
- method=request.method,
- endpoint=endpoint,
- )
+ record_slack_attempt(
+ source=self._source,
+ workspace_id=self._workspace_id,
+ app_id=self._app_id,
+ request=request,
+ response=response,
+ )
return False
diff --git a/posthog/egress/slack/client.py b/posthog/egress/slack/client.py
index e0608776ed0a..033898cb7487 100644
--- a/posthog/egress/slack/client.py
+++ b/posthog/egress/slack/client.py
@@ -6,11 +6,7 @@ from slack_sdk.http_retry.request import HttpRequest
from slack_sdk.http_retry.response import HttpResponse
from slack_sdk.http_retry.state import RetryState
-from posthog.egress.slack.observability import (
- record_slack_api_exception,
- record_slack_api_response,
- slack_endpoint_from_url,
-)
+from posthog.egress.slack.observability import record_slack_attempt
class SlackObservabilityHandler(RetryHandler):
@@ -28,23 +24,13 @@ class SlackObservabilityHandler(RetryHandler):
response: HttpResponse | None = None,
error: Exception | None = None,
) -> bool:
- endpoint = slack_endpoint_from_url(request.url)
- if response is not None:
- record_slack_api_response(
- response,
- source=self._source,
- workspace_id=self._workspace_id,
- app_id=self._app_id,
- method=request.method,
- endpoint=endpoint,
- )
- else:
- record_slack_api_exception(
- source=self._source,
- workspace_id=self._workspace_id,
- method=request.method,
- endpoint=endpoint,
- )
+ record_slack_attempt(
+ source=self._source,
+ workspace_id=self._workspace_id,
+ app_id=self._app_id,
+ request=request,
+ response=response,
+ )
return False
diff --git a/posthog/egress/slack/observability.py b/posthog/egress/slack/observability.py
index 45a4feb6b41f..aca5f831cd4a 100644
--- a/posthog/egress/slack/observability.py
+++ b/posthog/egress/slack/observability.py
@@ -5,38 +5,27 @@ from urllib.parse import urlparse
import requests
from prometheus_client import Counter, Gauge
-
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- register_egress_observability,
+from slack_sdk.http_retry.request import HttpRequest
+from slack_sdk.http_retry.response import HttpResponse
+
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
+
+slack_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "slack_api_requests",
+ "Number of Slack API requests made through a Slack egress client.",
+ labelnames=["workspace_id", "method", "endpoint", "status_code", "source"],
+ ),
+ )
)
-SLACK_DOMAIN = "slack"
-
-
-_metrics = EgressMetrics(
- request_counter=Counter(
- "slack_api_requests",
- "Number of Slack API requests made through a Slack egress client.",
- labelnames=["workspace_id", "method", "endpoint", "status_code", "source"],
- ),
- remaining_gauge=Gauge(
- "slack_api_rate_limit_remaining",
- "Slack API rate limit remaining count when reported by Slack.",
- labelnames=["workspace_id", "resource"],
- ),
- limit_gauge=Gauge(
- "slack_api_rate_limit_limit",
- "Slack API rate limit when reported by Slack.",
- labelnames=["workspace_id", "resource"],
- ),
- reset_gauge=Gauge(
- "slack_api_rate_limit_reset_timestamp_seconds",
- "Slack API retry timestamp after a rate-limited response.",
- labelnames=["workspace_id", "resource"],
- ),
+# Slack returns no remaining-budget headers. Its only budget signal is the Retry-After on a 429,
+# which applies to one app and one Web API method, so the resource label carries both.
+_retry_at_gauge = Gauge(
+ "slack_api_rate_limit_reset_timestamp_seconds",
+ "Slack API retry timestamp after a rate-limited response.",
+ labelnames=["workspace_id", "resource"],
)
@@ -50,14 +39,6 @@ def _header(headers: Mapping[str, object], name: str) -> str | None:
return None
-def _parse_slack_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- return RateLimitSnapshot()
-
-
-slack_egress = EgressObservability(SLACK_DOMAIN, _metrics, _parse_slack_rate_limit)
-register_egress_observability(slack_egress)
-
-
def slack_endpoint_from_url(url: str) -> str:
parsed = urlparse(url)
if parsed.netloc == "files.slack.com" and parsed.path.startswith("/upload/v1/"):
@@ -92,8 +73,28 @@ def record_slack_api_response(
reset_at = time.time() + float(retry_after)
except ValueError:
return
- _metrics.reset_gauge.labels(normalized_workspace_id, f"{app_id}:{endpoint}").set(reset_at)
+ _retry_at_gauge.labels(normalized_workspace_id, f"{app_id}:{endpoint}").set(reset_at)
-def record_slack_api_exception(*, source: str, workspace_id: str | None, method: str, endpoint: str) -> None:
- slack_egress.record_exception(source=source, scope=workspace_id or None, method=method, endpoint=endpoint)
+def record_slack_attempt(
+ *,
+ source: str,
+ workspace_id: str | None,
+ app_id: str,
+ request: HttpRequest,
+ response: HttpResponse | None,
+) -> None:
+ """Record one Slack SDK attempt. The SDK calls its retry handlers once per HTTP attempt, with no
+ response when the attempt raised, so a retried call counts once per request it sent."""
+ endpoint = slack_endpoint_from_url(request.url)
+ if response is None:
+ slack_egress.record_exception(source=source, scope=workspace_id, method=request.method, endpoint=endpoint)
+ return
+ record_slack_api_response(
+ response,
+ source=source,
+ workspace_id=workspace_id,
+ app_id=app_id,
+ method=request.method,
+ endpoint=endpoint,
+ )
diff --git a/posthog/egress/slack/transport.py b/posthog/egress/slack/transport.py
index 443d45a26722..f223fef099b7 100644
--- a/posthog/egress/slack/transport.py
+++ b/posthog/egress/slack/transport.py
@@ -2,25 +2,22 @@ from typing import Any
import requests
-from posthog.egress.limiter.policies import Priority
-from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response
-from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
+from posthog.egress.slack.observability import record_slack_api_response, slack_egress
+from posthog.egress.transport.transport import RecordedEgressClient
-class SlackEgressBudgetExhausted(EgressBudgetExhausted):
- pass
+class SlackClient(RecordedEgressClient):
+ """Recorded, never gated. Slack applies its limits per method, workspace and app, and returns no
+ remaining-budget headers, so there is no single budget to draw from. Callers own reactive retries."""
+ observability = slack_egress
-class SlackClient(EgressClient):
def __init__(self, app_id: str) -> None:
self._app_id = app_id
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json"}
- def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
- return True
-
def _record_response(
self,
response: requests.Response,
@@ -39,25 +36,6 @@ class SlackClient(EgressClient):
endpoint=endpoint or "unknown",
)
- def _record_exception(
- self,
- *,
- source: str,
- scope: str | None,
- method: str,
- url: str,
- endpoint: str | None,
- ) -> None:
- record_slack_api_exception(
- source=source,
- workspace_id=scope,
- method=method,
- endpoint=endpoint or "unknown",
- )
-
- def _budget_exhausted_error(self, scope: str) -> SlackEgressBudgetExhausted:
- return SlackEgressBudgetExhausted(f"Slack egress budget exhausted for workspace {scope}")
-
def slack_request(
method: str,
diff --git a/posthog/egress/test/test_browserless_transport.py b/posthog/egress/test/test_browserless_transport.py
index 08452c37a177..48d0ce3c7ea3 100644
--- a/posthog/egress/test/test_browserless_transport.py
+++ b/posthog/egress/test/test_browserless_transport.py
@@ -5,6 +5,7 @@ from django.test import SimpleTestCase
import requests
from parameterized import parameterized
+from posthog.egress.browserless.observability import browserless_egress
from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted, browserless_request, fleet_scope
from posthog.egress.limiter.policies import Priority
@@ -49,7 +50,7 @@ class TestBrowserlessTransport(SimpleTestCase):
with (
patch("posthog.egress.browserless.transport.consume_browserless_sync", return_value=True) as consume,
patch("requests.request", return_value=_ok_response()) as request,
- patch("posthog.egress.browserless.transport.record_browserless_response") as record,
+ patch.object(browserless_egress, "record_requests_response") as record,
):
browserless_request(
"POST",
diff --git a/posthog/egress/test/test_domains.py b/posthog/egress/test/test_domains.py
new file mode 100644
index 000000000000..f49b2765934f
--- /dev/null
+++ b/posthog/egress/test/test_domains.py
@@ -0,0 +1,42 @@
+import importlib
+from pathlib import Path
+
+import posthog.egress
+from posthog.egress.limiter.policies import _REGISTRY, Priority, resolve_policy
+
+_EGRESS_ROOT = Path(posthog.egress.__file__).parent
+
+_FLAT_DOMAINS = {"google_workspace"}
+
+
+def _domain_dirs() -> list[Path]:
+ return sorted(path.parent for path in _EGRESS_ROOT.glob("*/transport.py") if path.parent.name != "transport")
+
+
+def _cites_sources(readme: Path) -> bool:
+ if not readme.is_file():
+ return False
+ _, _, sources = readme.read_text().partition("\n## Sources\n")
+ return "https://" in sources
+
+
+def test_every_domain_documents_itself_in_a_readme_with_sources() -> None:
+ missing = [domain.name for domain in _domain_dirs() if not _cites_sources(domain / "README.md")]
+ assert missing == []
+
+
+def test_only_reviewed_domains_run_a_flat_policy() -> None:
+ domain_names = {domain.name for domain in _domain_dirs()}
+ for domain in _domain_dirs():
+ if (domain / "limiter.py").is_file():
+ importlib.import_module(f"posthog.egress.{domain.name}.limiter")
+
+ # A domain registers under its directory name or a `<name>_` prefix (GitHub's search meters), which
+ # leaves out the flat policies that modules outside egress register in the same test run.
+ flat = {
+ name
+ for name in _REGISTRY
+ if any(name == domain or name.startswith(f"{domain}_") for domain in domain_names)
+ and resolve_policy(f"{name}:scope:1").reserve_fraction(Priority.BATCH) == 0.0
+ }
+ assert flat == _FLAT_DOMAINS
diff --git a/posthog/egress/test/test_firecrawl.py b/posthog/egress/test/test_firecrawl.py
index 62ba31e298a2..eb95d9f09126 100644
--- a/posthog/egress/test/test_firecrawl.py
+++ b/posthog/egress/test/test_firecrawl.py
@@ -8,8 +8,6 @@ from django.test import SimpleTestCase, override_settings
import requests
from parameterized import parameterized
-from prometheus_client import REGISTRY
-from requests.structures import CaseInsensitiveDict
from posthog.egress.firecrawl.client import (
MAX_SEARCH_LIMIT,
@@ -21,7 +19,6 @@ from posthog.egress.firecrawl.client import (
search,
)
from posthog.egress.firecrawl.limiter import consume_firecrawl_sync, firecrawl_account_key
-from posthog.egress.firecrawl.observability import record_firecrawl_api_response
from posthog.egress.firecrawl.transport import FirecrawlEgressBudgetExhausted
from posthog.egress.limiter.policies import Priority, resolve_policy
@@ -59,17 +56,6 @@ def _response(status: int, body: str) -> requests.Response:
return response
-def _response_with_rate_limit_headers(headers: dict[str, str], url: str) -> requests.Response:
- response = requests.models.Response()
- response.status_code = 200
- response.headers = CaseInsensitiveDict(headers)
- prepared = requests.models.PreparedRequest()
- prepared.method = "GET"
- prepared.url = url
- response.request = prepared
- return response
-
-
@contextmanager
def _firecrawl_answers(response: requests.Response) -> Iterator[tuple[MagicMock, MagicMock]]:
"""Yield the patched sender and limiter gate. The gate is patched in both the transport and the
@@ -152,30 +138,6 @@ class TestFirecrawlEgress(SimpleTestCase):
# misspelled setting and quietly pin the budget to the code default forever.
assert resolve_policy(firecrawl_account_key()).limits == ((7, 60.0), (11, 3600.0))
- def test_record_response_keys_the_rate_limit_gauges_by_the_request_url(self) -> None:
- # Firecrawl is the one domain whose gauge resource comes from the request url rather than a
- # curated endpoint label. Losing that wiring silently freezes every gauge under "unknown"
- # regardless of which endpoint was actually called.
- record_firecrawl_api_response(
- _response_with_rate_limit_headers(
- {"X-RateLimit-Remaining": "7", "X-RateLimit-Limit": "60"},
- "https://api.firecrawl.dev/v2/scrape",
- ),
- source="unit-test",
- )
- assert (
- REGISTRY.get_sample_value(
- "firecrawl_api_rate_limit_remaining", {"account": "default", "resource": "/v2/scrape"}
- )
- == 7
- )
- assert (
- REGISTRY.get_sample_value(
- "firecrawl_api_rate_limit_limit", {"account": "default", "resource": "/v2/scrape"}
- )
- == 60
- )
-
@override_settings(FIRECRAWL_API_KEY=_FAKE_API_KEY)
class TestFirecrawlSearchEgress(SimpleTestCase):
diff --git a/posthog/egress/test/test_github_limiter.py b/posthog/egress/test/test_github_limiter.py
index 3a053d540f31..1e1afc919fc1 100644
--- a/posthog/egress/test/test_github_limiter.py
+++ b/posthog/egress/test/test_github_limiter.py
@@ -11,7 +11,6 @@ from requests.structures import CaseInsensitiveDict
from posthog.egress.github.limiter import (
_IDLE_RESERVE,
- _RESERVE,
GitHubRateResource,
_interactive_last_written,
_interactive_memo,
@@ -29,7 +28,7 @@ from posthog.egress.github.limiter import (
observed_core_limit_cache_key,
remember_observed_core_limit,
)
-from posthog.egress.limiter.policies import Priority, resolve_policy
+from posthog.egress.limiter.policies import DEFAULT_RESERVE, Priority, resolve_policy
def _response(*, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
@@ -83,7 +82,7 @@ class TestGitHubTierBudgets(GitHubLimiterTestCase):
@parameterized.expand(
[
- ("interactive_demand_holds_the_full_reserve", True, _RESERVE),
+ ("interactive_demand_holds_the_full_reserve", True, DEFAULT_RESERVE),
("idle_installation_releases_it_to_batch", False, _IDLE_RESERVE),
]
)
diff --git a/posthog/egress/test/test_github_observability.py b/posthog/egress/test/test_github_observability.py
index c896c4f74f84..2fe0635f55d3 100644
--- a/posthog/egress/test/test_github_observability.py
+++ b/posthog/egress/test/test_github_observability.py
@@ -7,16 +7,8 @@ from parameterized import parameterized
from prometheus_client import REGISTRY
from requests.structures import CaseInsensitiveDict
-from posthog.egress.github.observability import (
- _normalize_github_endpoint,
- record_github_api_exception,
- record_github_api_response,
-)
-from posthog.egress.observability.observability import (
- default_normalize_endpoint,
- record_outbound_api_response,
- resolve_egress_observability,
-)
+from posthog.egress.github.observability import _normalize_github_endpoint, github_egress
+from posthog.egress.observability.observability import default_normalize_endpoint
_COUNTER = "github_integration_api_requests_total"
_REMAINING = "github_integration_api_rate_limit_remaining"
@@ -86,10 +78,10 @@ class TestGithubObservability(SimpleTestCase):
"source": "unit-known",
},
)
- record_github_api_response(
+ github_egress.record_requests_response(
_response(headers={"X-RateLimit-Remaining": "4321", "X-RateLimit-Resource": "core"}),
source="unit-known",
- installation_id="42",
+ scope="42",
)
after = REGISTRY.get_sample_value(
@@ -108,12 +100,14 @@ class TestGithubObservability(SimpleTestCase):
4321,
)
- def test_skips_gauges_when_identity_unknown(self) -> None:
+ @parameterized.expand([("no_scope", None), ("empty_scope", "")])
+ def test_skips_gauges_when_identity_unknown(self, name: str, scope: str | None) -> None:
# Identity-blind callers (raw-token sources) must not set the per-installation gauge — otherwise
# many installations alias onto the empty installation_id and the last write wins, misleadingly.
- record_github_api_response(
+ github_egress.record_requests_response(
_response(headers={"X-RateLimit-Remaining": "10", "X-RateLimit-Resource": "core"}),
- source="unit-blind",
+ source=f"unit-blind-{name}",
+ scope=scope,
)
self.assertIsNone(REGISTRY.get_sample_value(_REMAINING, {"installation_id": "", "resource": "core"}))
self.assertEqual(
@@ -124,44 +118,19 @@ class TestGithubObservability(SimpleTestCase):
"method": "GET",
"endpoint": "/repos/{owner}/{repo}/commits",
"status_code": "200",
- "source": "unit-blind",
+ "source": f"unit-blind-{name}",
},
),
1,
)
- def test_generic_resolver_routes_to_github(self) -> None:
- self.assertIs(resolve_egress_observability("github").domain, "github")
- record_outbound_api_response(
- _response(status=403, url="https://api.github.com/search/code"),
- domain="github",
- source="unit-generic",
- )
- self.assertEqual(
- REGISTRY.get_sample_value(
- _COUNTER,
- {
- "installation_id": "",
- "method": "GET",
- "endpoint": "/search/code",
- "status_code": "403",
- "source": "unit-generic",
- },
- ),
- 1,
- )
-
- def test_unregistered_domain_raises(self) -> None:
- with self.assertRaises(ValueError):
- resolve_egress_observability("definitely-not-registered")
-
def test_records_without_crashing_when_request_is_a_mock(self) -> None:
# A MagicMock response auto-vivifies .request.url / .request.method as Mocks (non-str);
# the recorder must coerce them to defaults, not raise urlparse(Mock) into the caller.
response = MagicMock()
response.status_code = 200
response.headers = CaseInsensitiveDict({})
- record_github_api_response(response, source="unit-mockreq")
+ github_egress.record_requests_response(response, source="unit-mockreq")
self.assertEqual(
REGISTRY.get_sample_value(
_COUNTER,
@@ -177,7 +146,7 @@ class TestGithubObservability(SimpleTestCase):
)
def test_exception_record_uppercases_method(self) -> None:
- record_github_api_exception(source="unit-exc", method="get", endpoint="/foo")
+ github_egress.record_exception(source="unit-exc", method="get", endpoint="/foo")
self.assertEqual(
REGISTRY.get_sample_value(
_COUNTER,
diff --git a/posthog/egress/test/test_github_transport.py b/posthog/egress/test/test_github_transport.py
index e4c0a7f16600..a6e7fb80d356 100644
--- a/posthog/egress/test/test_github_transport.py
+++ b/posthog/egress/test/test_github_transport.py
@@ -42,7 +42,6 @@ class TestGitHubTransport(SimpleTestCase):
with (
patch("posthog.egress.github.transport.consume_github_installation_sync") as consume,
patch("requests.request", return_value=_response()),
- patch("posthog.egress.github.transport.record_github_api_response"),
):
github_request("GET", "https://api.github.com/search/code?q=x", source="test", installation_id=None)
consume.assert_not_called()
diff --git a/posthog/egress/test/test_harmonic.py b/posthog/egress/test/test_harmonic.py
index 4f6167cef6d4..e52e5480a632 100644
--- a/posthog/egress/test/test_harmonic.py
+++ b/posthog/egress/test/test_harmonic.py
@@ -7,7 +7,7 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from posthog.egress.harmonic.limiter import HARMONIC_ACCOUNT_KEY, consume_harmonic
-from posthog.egress.harmonic.observability import _parse_harmonic_rate_limit
+from posthog.egress.harmonic.observability import _parse_harmonic_rate_limit, harmonic_egress
from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted, harmonic_request
from posthog.egress.limiter.backends import LimitsBackend
from posthog.egress.limiter.outbound import OutboundRateLimiter
@@ -66,25 +66,11 @@ class TestHarmonicRateLimitHeaderParser(SimpleTestCase):
("empty_headers", {}, RateLimitSnapshot(resource="account")),
(
"garbage_values",
- {"X-RateLimit-Remaining": "not-a-number", "X-RateLimit-Limit": "", "X-RateLimit-Reset": "soon"},
+ {"X-Ratelimit-Remaining-Second": "not-a-number", "X-Ratelimit-Limit-Second": ""},
RateLimitSnapshot(resource="account"),
),
(
- "standard_names",
- {"X-RateLimit-Remaining": "42", "X-RateLimit-Limit": "100", "X-RateLimit-Reset": "1700000000"},
- RateLimitSnapshot(resource="account", remaining=42.0, limit=100.0, reset_at=1700000000.0),
- ),
- (
- "second_variant_preferred_over_standard",
- {
- "X-Ratelimit-Remaining-Second": "5",
- "X-RateLimit-Remaining": "500",
- "X-Ratelimit-Limit-Second": "15",
- },
- RateLimitSnapshot(resource="account", remaining=5.0, limit=15.0),
- ),
- (
- "second_variant_alone",
+ "documented_names",
{"X-Ratelimit-Remaining-Second": "9", "X-Ratelimit-Limit-Second": "15"},
RateLimitSnapshot(resource="account", remaining=9.0, limit=15.0),
),
@@ -98,7 +84,7 @@ async def test_request_gates_before_sending_and_records_the_response() -> None:
session = _fake_session(status=201, headers={"X-Ratelimit-Remaining-Second": "9"})
with (
patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=True)) as acquire,
- patch("posthog.egress.harmonic.transport.record_harmonic_api_response") as record_response,
+ patch.object(harmonic_egress, "record_response") as record_response,
):
response = await harmonic_request(
session,
@@ -115,7 +101,7 @@ async def test_request_gates_before_sending_and_records_the_response() -> None:
session.request.assert_awaited_once()
assert session.request.call_args.kwargs["headers"]["apikey"] == "secret"
record_response.assert_called_once_with(
- 201, {"X-Ratelimit-Remaining-Second": "9"}, source="test", method="POST", endpoint="/graphql"
+ 201, {"X-Ratelimit-Remaining-Second": "9"}, source="test", scope="default", method="POST", endpoint="/graphql"
)
diff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.py
index 9ae63d0e1e15..99c19085f8ce 100644
--- a/posthog/egress/test/test_outbound_rate_limiter.py
+++ b/posthog/egress/test/test_outbound_rate_limiter.py
@@ -149,9 +149,6 @@ async def test_github_search_resource_meter_is_independent_of_core():
assert await limiter.acquire(core_key, 1, priority=Priority.CRITICAL) is True
-_RESERVE = {Priority.NORMAL: 0.1, Priority.BATCH: 0.3}
-
-
@pytest.mark.parametrize(
"priority,grantable",
[
@@ -165,7 +162,7 @@ _RESERVE = {Priority.NORMAL: 0.1, Priority.BATCH: 0.3}
async def test_reserved_floor_caps_each_priority(priority, grantable):
# The whole point of the lane: a lower priority is denied while headroom is still owed to higher
# ones, even though all three draw from the same counter.
- register_policy("test-reserve", RatePolicy(limits=((10, 3600.0),), reserve=_RESERVE))
+ register_policy("test-reserve", RatePolicy(limits=((10, 3600.0),)))
limiter = _fresh_limiter()
# Distinct scope per case — parametrize cases share one Redis-backed counter otherwise.
key = f"test-reserve:scope:{priority.value}"
@@ -186,12 +183,11 @@ async def test_batch_shed_before_critical_on_shared_counter():
@pytest.mark.parametrize("priority", [Priority.CRITICAL, Priority.NORMAL, Priority.BATCH])
-async def test_no_reserve_policy_is_priority_blind(priority):
- # An empty reserve must reproduce the pre-priority behavior for every lane — no headroom held back.
- register_policy("test-noreserve", RatePolicy(limits=((2, 3600.0),)))
+async def test_explicitly_flat_policy_is_priority_blind(priority):
+ register_policy("test-flat", RatePolicy(limits=((10, 3600.0),), reserve={}))
limiter = _fresh_limiter()
- key = f"test-noreserve:scope:{priority.value}"
- assert [await limiter.acquire(key, priority=priority) for _ in range(3)] == [True, True, False]
+ key = _unique_key("test-flat")
+ assert [await limiter.acquire(key, priority=priority) for _ in range(11)] == [True] * 10 + [False]
def test_reserve_inflated_weight_validation():
diff --git a/posthog/egress/test/test_slack_client.py b/posthog/egress/test/test_slack_client.py
index 7f1bd4ebc2a5..697f6784e985 100644
--- a/posthog/egress/test/test_slack_client.py
+++ b/posthog/egress/test/test_slack_client.py
@@ -80,7 +80,7 @@ async def test_async_slack_client_normalizes_external_upload_ticket() -> None:
)
response = HttpResponse(status_code=200, headers={}, body={})
- with patch("posthog.egress.slack.async_client.record_slack_api_response") as record_response:
+ with patch("posthog.egress.slack.observability.record_slack_api_response") as record_response:
assert await handler.can_retry_async(state=RetryState(), request=request, response=response) is False
assert record_response.call_args.kwargs["endpoint"] == "files.uploadExternal.data"
diff --git a/posthog/egress/test/test_vapi_transport.py b/posthog/egress/test/test_vapi_transport.py
index 5c867a53fad2..bc31ac194133 100644
--- a/posthog/egress/test/test_vapi_transport.py
+++ b/posthog/egress/test/test_vapi_transport.py
@@ -3,20 +3,31 @@ from unittest.mock import patch
from django.test import SimpleTestCase
import requests
+from prometheus_client import REGISTRY
+from posthog.egress.observability.observability import scope_fingerprint
from posthog.egress.vapi.transport import vapi_request
+def _request_count(scope: str, status_code: str = "201") -> float:
+ labels = {
+ "scope": scope,
+ "method": "POST",
+ "endpoint": "/call/web",
+ "status_code": status_code,
+ "source": "user_interviews",
+ }
+ return REGISTRY.get_sample_value("vapi_api_requests_total", labels) or 0
+
+
class TestVapiTransport(SimpleTestCase):
- def test_request_keeps_token_in_authorization_header_and_uses_fingerprint_scope(self) -> None:
+ def test_request_keeps_the_token_in_the_header_and_out_of_the_metric_scope(self) -> None:
response = requests.Response()
response.status_code = 201
+ fingerprint = scope_fingerprint("pk_test")
+ before = _request_count(fingerprint)
- with (
- patch("posthog.egress.vapi.transport.consume_vapi_api_sync", return_value=True) as consume,
- patch("requests.request", return_value=response) as request,
- patch("posthog.egress.vapi.transport.record_vapi_api_response"),
- ):
+ with patch("requests.request", return_value=response) as request:
vapi_request(
"POST",
"https://api.vapi.ai/call/web",
@@ -27,6 +38,21 @@ class TestVapiTransport(SimpleTestCase):
)
assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer pk_test"
- scope = consume.call_args.args[0]
- assert scope != "pk_test"
- assert len(scope) == 16
+ assert _request_count(fingerprint) == before + 1
+ assert _request_count("pk_test") == 0
+
+ def test_a_request_that_raises_is_recorded_and_re_raised(self) -> None:
+ fingerprint = scope_fingerprint("pk_test")
+ before = _request_count(fingerprint, "exception")
+
+ with patch("requests.request", side_effect=requests.ConnectionError("down")):
+ with self.assertRaises(requests.ConnectionError):
+ vapi_request(
+ "POST",
+ "https://api.vapi.ai/call/web",
+ api_token="pk_test",
+ source="user_interviews",
+ endpoint="/call/web",
+ )
+
+ assert _request_count(fingerprint, "exception") == before + 1
diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.py
index 183984ddc97a..62c5641fe433 100644
--- a/posthog/egress/transport/transport.py
+++ b/posthog/egress/transport/transport.py
@@ -3,14 +3,17 @@
An :class:`EgressClient` makes an outbound HTTP request that is *gated* (against the shared per-owner
budget) and *recorded* (request volume + the API's rate-limit headers) by construction, so no caller
can make a request that bypasses either. The gate→request→record algorithm and the priority-based
-denial semantics are domain-agnostic and live here; each third-party API subclasses and fills the
-domain hooks (standard headers, the limiter gate, the recorders, the endpoint normaliser, the
-budget-exhausted exception). GitHub is the first incarnation — see :mod:`posthog.egress.github.transport`.
-
-:class:`AsyncEgressClient` is the same algorithm for an aiohttp-based domain (Harmonic is the first —
-see :mod:`posthog.egress.harmonic.transport`): ``request``/``_consume`` are coroutines and the transport
-returns/catches aiohttp's types instead of ``requests``'. The two bases share the priority-based denial
-rule via :func:`_raise_if_denied` rather than each encoding it themselves.
+denial semantics are domain-agnostic and live here; each third-party API subclasses, points
+``observability`` at its metric set, and fills the gate hooks (the limiter draw and the
+budget-exhausted exception). See :mod:`posthog.egress.github.transport` for the reference domain.
+
+:class:`RecordedEgressClient` is the same transport without the gate, for an API PostHog observes but
+does not budget, because the API publishes no request limit that a rate budget can model.
+
+:class:`AsyncEgressClient` is the gated algorithm for an aiohttp-based domain (see
+:mod:`posthog.egress.harmonic.transport`): ``request``/``_consume`` are coroutines and the transport
+returns/catches aiohttp's types instead of ``requests``'. The sync and async bases share the
+priority-based denial rule via :func:`_raise_if_denied` rather than each encoding it themselves.
"""
from __future__ import annotations
@@ -27,6 +30,7 @@ if TYPE_CHECKING:
import aiohttp
from posthog.egress.limiter.policies import Priority
+from posthog.egress.observability.observability import EgressObservability
class EgressBudgetExhausted(Exception):
@@ -45,13 +49,25 @@ def _raise_if_denied(granted: bool, priority: Priority, make_error: Callable[[],
raise make_error()
-class EgressClient(ABC):
- """One outbound API's transport: gate → request → record, with priority-based denial semantics.
+class _EgressHooks:
+ """The hooks every transport shares, sync or async. Subclasses set ``observability``."""
- The algorithm is fixed here; subclasses supply the domain hooks. ``scope`` is the shared budget
- owner's id in the API's own namespace (e.g. a GitHub App installation id); ``None`` means the
- caller is identity-blind (a raw token with no shared budget), which skips the gate and records
- request volume only.
+ observability: EgressObservability
+
+ def _standard_headers(self) -> dict[str, str]:
+ """Default headers merged under the caller's (the caller's win) — e.g. Accept, API version."""
+ return {}
+
+ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
+ """Record a request that raised before returning a response (timeout, connection error)."""
+ self.observability.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
+
+
+class RecordedEgressClient(_EgressHooks):
+ """One outbound API's transport without a budget: request → record.
+
+ Subclasses set ``observability`` and may override the headers or the recorders. ``scope`` is the
+ metric identity in the API's own namespace; ``None`` records request volume without the gauges.
"""
def request(
@@ -62,14 +78,11 @@ class EgressClient(ABC):
source: str,
headers: dict[str, str] | None = None,
scope: str | None = None,
- priority: Priority = Priority.CRITICAL,
endpoint: str | None = None,
timeout: float | tuple[float, float] | None = None,
session: requests.Session | None = None,
**kwargs: Any,
) -> requests.Response:
- self._gate(scope, source, priority, url)
-
request_headers = {**self._standard_headers(), **(headers or {})}
sender = session or requests
try:
@@ -82,6 +95,51 @@ class EgressClient(ABC):
self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
return response
+ def _record_response(
+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
+ ) -> None:
+ """Record a returned response (volume + the API's rate-limit headers)."""
+ self.observability.record_requests_response(
+ response, source=source, scope=scope, method=method, endpoint=endpoint
+ )
+
+
+class EgressClient(RecordedEgressClient, ABC):
+ """One outbound API's transport: gate → request → record, with priority-based denial semantics.
+
+ The algorithm is fixed here; subclasses supply the gate hooks. ``scope`` is the shared budget
+ owner's id in the API's own namespace (e.g. a GitHub App installation id); ``None`` means the
+ caller is identity-blind (a raw token with no shared budget), which skips the gate and records
+ request volume only.
+ """
+
+ def request(
+ self,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ headers: dict[str, str] | None = None,
+ scope: str | None = None,
+ priority: Priority = Priority.CRITICAL,
+ endpoint: str | None = None,
+ timeout: float | tuple[float, float] | None = None,
+ session: requests.Session | None = None,
+ **kwargs: Any,
+ ) -> requests.Response:
+ self._gate(scope, source, priority, url)
+ return super().request(
+ method,
+ url,
+ source=source,
+ headers=headers,
+ scope=scope,
+ endpoint=endpoint,
+ timeout=timeout,
+ session=session,
+ **kwargs,
+ )
+
def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:
# Identity-blind callers have no shared budget to draw on — record volume only, never gate.
# An empty scope is no identity either: gating on it would key a phantom budget/metric series.
@@ -90,38 +148,24 @@ class EgressClient(ABC):
granted = self._consume(scope, priority, source, url)
_raise_if_denied(granted, priority, lambda: self._budget_exhausted_error(scope))
- # --- domain hooks -------------------------------------------------------------------------------
-
- @abstractmethod
- def _standard_headers(self) -> dict[str, str]:
- """Default headers merged under the caller's (the caller's win) — e.g. Accept, API version."""
+ # --- gate hooks ---------------------------------------------------------------------------------
@abstractmethod
def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
"""Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted.
``url`` lets a domain route the draw to the resource-specific meter GitHub bills the URL to."""
- @abstractmethod
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- """Record a returned response (volume + the API's rate-limit headers) via the domain's recorder."""
-
- @abstractmethod
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- """Record a request that raised before returning a response (timeout, connection error)."""
-
@abstractmethod
def _budget_exhausted_error(self, scope: str) -> EgressBudgetExhausted:
"""The domain-specific exception raised when a sheddable call is denied (a subclass of
:class:`EgressBudgetExhausted`)."""
-class AsyncEgressClient(ABC):
- """The aiohttp counterpart to :class:`EgressClient`, for a domain whose client is async (Harmonic
- is the first — see :mod:`posthog.egress.harmonic.transport`). Same gate → request → record
- algorithm, same domain hooks, and the same ``scope``/priority semantics; only the transport is
- async and speaks aiohttp's types instead of ``requests``'.
+class AsyncEgressClient(_EgressHooks, ABC):
+ """The aiohttp counterpart to :class:`EgressClient`, for a domain whose client is async (see
+ :mod:`posthog.egress.harmonic.transport`). Same gate → request → record algorithm, same hooks,
+ and the same ``scope``/priority semantics; only the transport is async and speaks aiohttp's types
+ instead of ``requests``'.
"""
async def request(
@@ -163,25 +207,19 @@ class AsyncEgressClient(ABC):
granted = await self._consume(scope, priority, source, url)
_raise_if_denied(granted, priority, lambda: self._budget_exhausted_error(scope))
- # --- domain hooks -------------------------------------------------------------------------------
-
- @abstractmethod
- def _standard_headers(self) -> dict[str, str]:
- """Default headers merged under the caller's (the caller's win) — e.g. Content-Type."""
-
- @abstractmethod
- async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
- """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted."""
-
- @abstractmethod
def _record_response(
self, response: aiohttp.ClientResponse, *, source: str, scope: str | None, method: str, endpoint: str | None
) -> None:
- """Record a returned response (volume + the API's rate-limit headers) via the domain's recorder."""
+ """Record a returned response (volume + the API's rate-limit headers)."""
+ self.observability.record_response(
+ response.status, response.headers, source=source, scope=scope, method=method, endpoint=endpoint
+ )
+
+ # --- gate hooks ---------------------------------------------------------------------------------
@abstractmethod
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- """Record a request that raised before returning a response (timeout, connection error)."""
+ async def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
+ """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted."""
@abstractmethod
def _budget_exhausted_error(self, scope: str) -> EgressBudgetExhausted:
diff --git a/posthog/egress/vapi/README.md b/posthog/egress/vapi/README.md
new file mode 100644
index 000000000000..da3f299cc55a
--- /dev/null
+++ b/posthog/egress/vapi/README.md
@@ -0,0 +1,31 @@
+# Vapi egress
+
+## Identity
+
+A 16-character SHA-256 fingerprint of the API token, so the token never reaches a metric label.
+
+## Budget
+
+None: Vapi calls are recorded, never gated (`RecordedEgressClient`).
+Vapi's docs state no REST request limit.
+The limit they describe is [concurrent call slots](https://docs.vapi.ai/calls/call-concurrency), which a request-rate budget cannot model.
+Add a gate only if Vapi publishes a request limit or starts billing per API call.
+
+## Lanes and callers
+
+No lanes, because nothing is gated.
+The user interviews web call creation (`products/user_interviews/backend/presentation/webhooks.py`) is the caller.
+It maps Vapi's own 429 to a retryable `VapiWebCallError`.
+
+## Rate-limit headers
+
+Vapi returns none, so the domain declares no gauges.
+The counter is `vapi_api_requests_total`, labeled `scope, method, endpoint, status_code, source`.
+
+## Auth
+
+`VAPI_PUBLIC_KEY`, sent as a bearer token.
+
+## Sources
+
+- [Call concurrency](https://docs.vapi.ai/calls/call-concurrency): concurrent call slots. Vapi's docs state no REST request limit.
diff --git a/posthog/egress/vapi/limiter.py b/posthog/egress/vapi/limiter.py
deleted file mode 100644
index 6a5191c41712..000000000000
--- a/posthog/egress/vapi/limiter.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""Outbound Vapi API budget keyed by the configured API token fingerprint."""
-
-from django.conf import settings
-
-from posthog.egress.limiter.outbound import get_outbound_rate_limiter
-from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
-
-VAPI_DOMAIN = "vapi"
-
-
-def _vapi_policy(_key: str) -> RatePolicy:
- return RatePolicy(
- limits=(
- (int(getattr(settings, "VAPI_EGRESS_PER_MINUTE_BUDGET", 10_000)), 60.0),
- (int(getattr(settings, "VAPI_EGRESS_HOURLY_BUDGET", 100_000)), 3600.0),
- ),
- in_memory_divider=4,
- )
-
-
-register_policy(VAPI_DOMAIN, _vapi_policy)
-
-
-def consume_vapi_api_sync(scope: str, *, priority: Priority, source: str) -> bool:
- return get_outbound_rate_limiter().consume_sync(
- f"{VAPI_DOMAIN}:api_key:{scope}",
- priority=priority,
- source=source,
- )
diff --git a/posthog/egress/vapi/observability.py b/posthog/egress/vapi/observability.py
index fb0ca86ec4d6..38aee66d4e98 100644
--- a/posthog/egress/vapi/observability.py
+++ b/posthog/egress/vapi/observability.py
@@ -1,71 +1,18 @@
-"""Vapi outbound API request telemetry."""
+"""Vapi outbound API request telemetry.
-from collections.abc import Mapping
+Vapi returns no rate-limit headers, so this domain declares no gauges.
+"""
-import requests
-from prometheus_client import Counter, Gauge
-
-from posthog.egress.observability.observability import (
- EgressMetrics,
- EgressObservability,
- RateLimitSnapshot,
- register_egress_observability,
- unpack_requests_response,
-)
-from posthog.egress.vapi.limiter import VAPI_DOMAIN
-
-_metrics = EgressMetrics(
- request_counter=Counter(
- "vapi_api_requests",
- "Outbound Vapi API requests.",
- labelnames=["scope", "method", "endpoint", "status_code", "source"],
- ),
- remaining_gauge=Gauge(
- "vapi_api_rate_limit_remaining",
- "Last observed Vapi API rate-limit remaining value.",
- labelnames=["scope", "resource"],
- ),
- limit_gauge=Gauge(
- "vapi_api_rate_limit_limit",
- "Last observed Vapi API rate-limit ceiling.",
- labelnames=["scope", "resource"],
- ),
- reset_gauge=Gauge(
- "vapi_api_rate_limit_reset_at",
- "Last observed Vapi API rate-limit reset timestamp.",
- labelnames=["scope", "resource"],
- ),
-)
-
-
-def _parse_vapi_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
- return RateLimitSnapshot(resource="api")
+from prometheus_client import Counter
+from posthog.egress.observability.observability import EgressMetrics, EgressObservability
-vapi_egress = EgressObservability(VAPI_DOMAIN, _metrics, _parse_vapi_rate_limit)
-register_egress_observability(vapi_egress)
-
-
-def record_vapi_api_response(
- response: requests.Response,
- *,
- source: str,
- scope: str,
- method: str,
- endpoint: str,
-) -> None:
- primitives = unpack_requests_response(response)
- vapi_egress.record_response(
- primitives.status_code,
- primitives.headers,
- source=source,
- scope=scope,
- method=method,
- endpoint=endpoint,
- request_method=primitives.request_method,
- request_url=primitives.request_url,
+vapi_egress = EgressObservability(
+ EgressMetrics(
+ request_counter=Counter(
+ "vapi_api_requests",
+ "Outbound Vapi API requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
)
-
-
-def record_vapi_api_exception(*, source: str, scope: str, method: str, endpoint: str, url: str) -> None:
- vapi_egress.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
+)
diff --git a/posthog/egress/vapi/transport.py b/posthog/egress/vapi/transport.py
index ae11a75ab23f..a14fa411c042 100644
--- a/posthog/egress/vapi/transport.py
+++ b/posthog/egress/vapi/transport.py
@@ -1,50 +1,25 @@
-"""Gated, recorded transport for calls to the Vapi API."""
+"""Recorded transport for calls to the Vapi API.
+
+Vapi documents no REST request limit. The limit it does enforce is concurrent call slots, which a
+request-rate budget cannot model, so these calls are recorded but not gated. The caller maps Vapi's
+own 429 to a retryable error.
+"""
-import hashlib
from typing import Any
import requests
-from posthog.egress.limiter.policies import Priority
-from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
-from posthog.egress.vapi.limiter import consume_vapi_api_sync
-from posthog.egress.vapi.observability import record_vapi_api_exception, record_vapi_api_response
-
+from posthog.egress.observability.observability import scope_fingerprint
+from posthog.egress.transport.transport import RecordedEgressClient
+from posthog.egress.vapi.observability import vapi_egress
-class VapiEgressBudgetExhausted(EgressBudgetExhausted):
- pass
+class VapiClient(RecordedEgressClient):
+ observability = vapi_egress
-class VapiClient(EgressClient):
def _standard_headers(self) -> dict[str, str]:
return {"Accept": "application/json", "Content-Type": "application/json"}
- def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
- return consume_vapi_api_sync(scope, priority=priority, source=source)
-
- def _record_response(
- self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
- ) -> None:
- record_vapi_api_response(
- response,
- source=source,
- scope=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- )
-
- def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
- record_vapi_api_exception(
- source=source,
- scope=scope or "",
- method=method,
- endpoint=endpoint or "unknown",
- url=url,
- )
-
- def _budget_exhausted_error(self, scope: str) -> VapiEgressBudgetExhausted:
- return VapiEgressBudgetExhausted("Vapi egress budget exhausted")
-
_vapi_client = VapiClient()
@@ -60,14 +35,12 @@ def vapi_request(
session: requests.Session | None = None,
**kwargs: Any,
) -> requests.Response:
- scope = hashlib.sha256(api_token.encode()).hexdigest()[:16]
return _vapi_client.request(
method,
url,
source=source,
headers={"Authorization": f"Bearer {api_token}"},
- scope=scope,
- priority=Priority.CRITICAL,
+ scope=scope_fingerprint(api_token),
endpoint=endpoint,
timeout=timeout,
session=session,
diff --git a/posthog/owners.yaml b/posthog/owners.yaml
index e0779a1f2f03..0387b1f0115f 100644
--- a/posthog/owners.yaml
+++ b/posthog/owners.yaml
@@ -9,6 +9,8 @@ rules:
owners: clickhouse
- match: '/data_freshness.py'
owners: team-platform-features
+ - match: '/egress/'
+ owners: team-devex
- match: '/email.py'
owners: team-platform-features
- match: '/heatmaps/'
diff --git a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
index 448501fd6617..568bc2ec728e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/person_property_update_consumer.py
@@ -108,7 +108,8 @@ def _current_rate() -> float:
def _rate_policy(_key: str) -> RatePolicy:
"""Resolve the live global budget. Registered as a provider so a constance change to the rate
takes effect without a restart (read on each acquire, not frozen at import)."""
- return RatePolicy(limits=((max(1, int(_current_rate())), 1.0),), in_memory_divider=_IN_MEMORY_DIVIDER)
+ # Flat: this consumer is the budget's only caller, so no higher lane needs reserved headroom.
+ return RatePolicy(limits=((max(1, int(_current_rate())), 1.0),), in_memory_divider=_IN_MEMORY_DIVIDER, reserve={})
register_policy(_RATE_DOMAIN, _rate_policy)