Skip to content

feat(hybridcloud): Emit webhook mailbox depth and oldest-pending-age metrics - #121506

Merged
vaind merged 5 commits into
masterfrom
ivandlugos/inc-2420-emit-mailbox-depth-and-oldest-pending-age-metrics
Aug 7, 2026
Merged

vaind merged 5 commits into
masterfrom
ivandlugos/inc-2420-emit-mailbox-depth-and-oldest-pending-age-metrics

Conversation

@vaind

@vaind vaind commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Webhook forwarding had no backlog telemetry. A growing mailbox was neither measurable nor alertable — during INC-2324 the backlog had to be sized with ad-hoc Redash SQL and a raw Postgres row estimate. This is the prerequisite for the forwarding SLO/alerting work in INC-2421 as well as a tool to measure impact of other work being done to improve webhook delivery performance.

Every row in hybridcloud_webhookpayload is a webhook we still owe a cell, so the backlog is the whole table. Metrics are split into two tasks by cost, because the monitor has to keep working during exactly the backlog it exists to report on.

Both tasks live in a new src/sentry/hybridcloud/tasks/webhook_backlog_metrics.py. They share no code path with delivery — only the model — so deliver_webhooks.py is byte-identical to master and this diff is purely additive.

Metric names below omit their common hybridcloud.webhookpayload. prefix.

Cheap tier — record_webhook_backlog_metrics, every 60s

Neither query aggregates the table, so this tier stays roughly three orders of magnitude cheaper than the one below it and keeps reporting however deep the backlog gets.

metric source cost mid-backlog meaning
backlog.pending_count_estimate pg_class.reltuples no scan backlog size
backlog.oldest_pending_age_seconds ORDER BY id LIMIT 1 827 buffers / 11.8 ms age of the oldest undelivered payload

The estimate is emitted even at zero, so a drained backlog is distinguishable from a task that has stopped reporting. The age is omitted when nothing is pending — zero would read as "caught up" rather than "nothing to catch up on".

reltuples is autovacuum-maintained and therefore approximate; measured mid-backlog it landed 0.13% below an exact count(*). That is comfortably good enough for the growth trend it feeds, and mailbox.pending_count carries the exact value.

The age lookup is not constant-cost, which I originally assumed it was. ORDER BY id LIMIT 1 walks the primary key past whatever dead index entries delivery has left at the head, so its cost follows vacuum lag — 827 buffers rather than the handful I expected. It is still ~1000x cheaper than the aggregate and self-heals as the scan marks dead entries killed, but since nothing in the design bounds it, it runs under a 5s statement_timeout. On timeout the size estimate is still reported, because it needs no scan at all.

Aggregate tier — record_mailbox_depth_metrics, every 5 minutes

Delivery is ordered within a mailbox, so one deep mailbox stalls everything behind it while the totals still look healthy. max_depth is what makes that visible, and establishing it requires aggregating every row.

metric tags meaning
mailbox.pending_count provider exact backlog per provider — a count of payloads
mailbox.active_count provider number of distinct mailboxes with any backlog for that provider, not a payload count — easy to misread next to pending_count above it. pending_count / active_count is the average backlog depth per active mailbox
mailbox.max_depth provider deepest single mailbox — the head-of-line signal
mailbox.oldest_pending_age_seconds provider oldest undelivered payload per provider

Bounded by a 30s statement_timeout set with SET LOCAL, so it cannot leak into other work on the connection. On timeout the task emits mailbox.aggregate_failed and returns: a pathological table costs us the breakdown, not a pinned control replica, and the cheap tier keeps reporting throughout.

Measurements

EXPLAIN (ANALYZE, BUFFERS) against the live table via the read replica, taken while the table was carrying a deep backlog — the state these metrics exist to report on, and the one where the query choice actually matters:

query plan buffers exec of which JIT
GROUP BY provider, mailbox_name + MIN(date_added) (shipped) Parallel Seq Scan 897,195 1,312 ms 625 ms
GROUP BY mailbox_name + MIN(id) Parallel Index Only Scan, Heap Fetches: 893,706 1,000,278 1,225 ms 18 ms
GROUP BY provider + COUNT(*) Parallel Index Only Scan (provider_idx) 394,645 720 ms 16 ms

An earlier revision grouped by mailbox_name and recovered the provider from the mailbox name prefix, to keep the aggregate index-only. Production shows that plan reports Heap Fetches: 893,706 against ~897k total heap pages — this table's insert/delete churn keeps the visibility map permanently stale, so the index-only scan visits the heap anyway. It touches more buffers than the sequential scan and leads by 7% on wall clock, all of which is JIT overhead on the other query; net of JIT it is the slower of the two.

Since the index-only plan bought nothing, the aggregate groups by the real provider column. That removes the prefix derivation, a second id-based lookup, the assumption that id order matches date_added order, and the race where a head row is delivered between the two queries — MIN(date_added) now falls out of the same aggregate.

webhookpayload_provider_idx does not help the two-column group-by (confirmed Parallel Seq Scan): no index covers provider and mailbox_name together. It would serve a provider-only count, but that is one of the four provider-tagged metrics, so splitting it out would mean a second scan and two tagging paths.

Verifying the cheap tier's plan is what turned up the caveat above: Limit -> Index Scan using hybridcloud_webhookpayload_pkey, 827 buffers, 11.8 ms. The plan is right, the cost was not what I claimed.

Fixes INC-2420

…metrics

Webhook forwarding backlog had no telemetry, so a growing mailbox was neither
measurable nor alertable — during INC-2324 the backlog had to be sized with ad-hoc
Redash SQL and a raw Postgres row estimate.

Adds a control-silo task emitting per-provider gauges for backlog size, mailbox
count, deepest mailbox, and oldest undelivered payload age. It runs on its own
60s schedule rather than inside schedule_webhook_delivery so that aggregating a
deep backlog can never delay the delivery it measures.

The aggregate groups by mailbox_name and touches only id, which keeps it an
index-only scan of webhookpayload_mailbox_id_idx. Measured over 500k rows: 5,160
buffers / 107ms, against 125,000 buffers / 2.7s for the equivalent query that
also selects provider and date_added. Provider is recovered from the mailbox
name prefix, and oldest age from a primary-key lookup of each provider's head
row, so neither forces a heap fetch.

Refs INC-2420
@vaind
vaind requested review from a team as code owners August 7, 2026 08:48
@linear-code

linear-code Bot commented Aug 7, 2026

Copy link
Copy Markdown

INC-2420

@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Aug 7, 2026
…ate tiers

Production EXPLAIN on the live table (2.6M rows, 7GB heap, mid-backlog) contradicted
the assumption the first pass was built on. The mailbox_name index-only scan reported
Heap Fetches: 893,706 — not zero. The visibility map is permanently stale under this
table's insert/delete churn, so the plan still visits nearly every heap page. It
touched more buffers than the plain sequential scan it was chosen over (1,000,278 vs
897,195) and won by 7% on wall clock, all of which was JIT overhead on the other side.

Since the index-only plan bought nothing, group by the real provider column. That
drops the mailbox-name prefix derivation, the follow-up id lookup, the assumption that
ids order the same as date_added, and the race where a head row is delivered between
the two queries. MIN(date_added) now comes from the same aggregate.

Splitting the task follows from the same measurement: every variant scans the whole
table, so cost tracks the backlog. The two signals worth paging on do not need a scan
at all — size from the planner row estimate, age from the single lowest-id row — so
they stay at 60s and cannot degrade. The per-provider aggregate that needs the scan
moves to 5 minutes under a 30s statement timeout, losing the breakdown rather than
pinning a control replica if the table ever gets pathological.

Refs INC-2420
@vaind
vaind force-pushed the ivandlugos/inc-2420-emit-mailbox-depth-and-oldest-pending-age-metrics branch from 05bb9e6 to eac54e7 Compare August 7, 2026 09:29
Production EXPLAIN shows the oldest-payload lookup reads ~830 buffers, not the
handful I assumed. ORDER BY id LIMIT 1 walks the primary key past whatever dead index
entries delivery has left at the head, so its cost tracks vacuum lag rather than
staying constant. It is still ~1000x cheaper than the per-mailbox aggregate and ran
in 11.8ms mid-backlog, so the tiering holds — but nothing in the design bounds it,
so it now runs under a 5s statement timeout like the aggregate does. On timeout the
size estimate, which needs no scan at all, is still reported.

Also records the measured accuracy of the reltuples estimate: 2,626,000 against an
exact 2,629,316, or 0.13% low mid-backlog.

Refs INC-2420
vaind added 2 commits August 7, 2026 11:53
The two metrics tasks share no code path with delivery — only the model — so they
were sitting in deliver_webhooks.py purely because that is where the first draft
grew. Splitting them out leaves deliver_webhooks.py byte-identical to master and
gives the observation code its own module and test file.

Task names change with the module. Nothing has been deployed under the old names,
so there is no registered-name migration to worry about.

Refs INC-2420
The two log keys still read deliver_webhook.*, which was correct when this code
lived in that module and is misleading now that it does not.

Fold the oldest-per-provider conditional into the same min() idiom the rest of the
accumulation loop uses, and pull the repeated metric names in the tests into
constants so the assertions stop wrapping across four lines each.

Refs INC-2420
@vaind
vaind merged commit 695b098 into master Aug 7, 2026
87 of 90 checks passed
@vaind
vaind deleted the ivandlugos/inc-2420-emit-mailbox-depth-and-oldest-pending-age-metrics branch August 7, 2026 12:05
vaind added a commit that referenced this pull request Aug 10, 2026
## Problem

The mailbox gauges from #121506 report the backlog per provider — who
sent the queued webhooks, not what they are. Sizing a parser-side drop
needs the latter.

#121434 dropped 13.6M unconsumed `check_suite` deliveries a day. The
follow-up it names — dropping `check_run.completed` payloads that
reference no pull request based in their own repo, the largest remaining
line at 12.1M/day — has an inflow number
(`github.webhook.forwarded_event`) and a latency number
(`delivery_time_ms{github_event_and_action}`), but nothing that says
what is actually *sitting* in the mailboxes. That is the
INC-2324/INC-2421 question, and today it is only answerable per
provider.

## Changes

`hybridcloud.webhookpayload.mailbox.pending_count` gains an `event_type`
tag.

GitHub mailboxes already carry the answer.
`GithubRequestParser.get_mailbox_identifier` appends the event type to
the mailbox name so deliveries of different types don't queue behind
each other (`GithubEnterpriseRequestParser` inherits it), and the
aggregate already groups by `mailbox_name`. So this is a re-key of rows
that are in memory either way — **no extra query, no change to the
statement-timeout envelope**.

Two things the derivation has to get right:

- A delivery that arrives with no `X-GitHub-Event` header mailboxes
*without* the suffix, leaving a bucket number where this reads. Tagging
that verbatim would put unbounded ints in a tag, so only names in
`CELL_PROCESSED_GITHUB_EVENTS` are trusted; anything else is `unknown`.
- `none` (provider doesn't mailbox by event type) is kept distinct from
`unknown` (it does, but this mailbox has none to read). Conflating them
would hide the header-less deliveries.

It reads the `provider` column rather than the mailbox prefix, so legacy
rows predating that column report `none` even when they are GitHub
mailboxes. Those are draining out, and deriving a provider two different
ways is worse than under-reporting them.

## Why only `pending_count`

Every emission is host-tagged by the Datadog backend, so each tag value
costs a series per worker that runs the task. Tagging all four gauges
would take this from `4 × 7 providers` to `4 × 25` combinations;
confining it to `pending_count` makes that `3 × 7 + 25`.

The other three read fine per provider:

- `max_depth` — GitHub mailboxes are per-event-type by construction, so
this is *already* one event type's mailbox. The tag would only name
which one, and `pending_count` names it.
- `active_count` — a routing/fan-out signal, not a composition one.
- `oldest_pending_age_seconds` — a single stalled event type does hide
inside the provider-wide age. That is an alerting concern for INC-2421
and a one-line addition if that work wants it; not worth paying for
speculatively.

Kept the full 9-event set rather than a hardcoded high-volume subset
with an `other` bucket. That would be cheaper, but the list would go
stale silently and hide the next `check_suite` — the exact thing this
exists to catch. The 9 are bounded and grow only when someone adds a
`GithubWebhookType`.

## Compatibility

Summing `pending_count` over `event_type` reproduces the provider-only
value, so anything built on the existing series keeps working. No
in-repo consumers reference these metric names.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants