fix(api): acknowledge Linear webhooks before fanning them out
Problem
Sentry API-18, Failed to acquire permit to connect, on the Linear webhook route. It survived #7114, which fixed the scheduled jobs stacking; this is the ingest path itself.
The route fanned out inline: Promise.all over every integration_connection for the delivering Linear organization, each one doing its own recordWebhookDelivery, task-status and task lookups, an assignee join, a Linear API call and a task upsert, plus an automation event.
Measured on a copy of production for this change:
- one Linear organization is connected to 17 Superset organizations (
maxoverintegration_connectionsgrouped byexternal_org_id), so a single delivery issued ~100 neon-http queries, ~40 concurrently; - 1,344 Linear organizations have at least one active connection; 317 have disconnected all of theirs.
From the earlier investigation on the same data: a bulk edit produced 3,501 deliveries in 8 minutes (~15k route invocations in 10 minutes), route p50 0.9s, p95 15.7s, max 33s — against Linear's 5 second timeout, after which it retries at 1 minute / 1 hour / 6 hours and may disable the webhook outright.
Root cause
Two things compounding, and only one of them is the fan-out being wide.
neon-http sends one HTTPS request per query. A query whose connection misses the proxy's idle pool has to open a compute connection, and that needs a permit from a per-compute semaphore — permits=100, timeout=10ms. Promise.all over 17 connections asks for 17 connections at the same instant, every one of them a pool miss. That is what exhausts the permits.
The obvious fix — bound the fan-out concurrency — was not available, because the route was holding Linear's response open the whole time and p95 was already three times Linear's timeout. Serializing would have traded 500s for dropped deliveries.
So the ordering had to change before the concurrency could.
Fix
The route accepts and does not work.
webhook/route.ts verifies the delivery, checks somebody is still subscribed, records the delivery once — identity in ingest.webhook_events, body in ingest.webhook_payloads, one round trip — and publishes a pointer to QStash. Two indexed queries and a publish. This is the ack-then-process shape the api already runs for Slack events and Microsoft Teams notifications, both of which have the same kind of clock over them.
jobs/process-delivery/route.ts does the work QStash hands back, with no clock over it. It walks the connections one at a time, so they reuse one pooled connection rather than asking for seventeen at once. Each connection is caught individually and the loop runs to the end, so one organization's broken token cannot cost the other sixteen their delivery.
The queue message is a pointer (webhookEventId, receivedAt, deliveryId), not the body, so no oversized issue description can outgrow a QStash message limit and turn into a webhook Linear disables. The consumer reads the body back in the same round trip as the delivery's status: exactness comes from the event row's own received_at, and the day is passed as constant bounds so the planner prunes webhook_payloads to the single partition the body is in.
Per-connection webhook_events rows are unchanged, ids included (deliveryIds.ts reproduces the existing format exactly, so no in-flight row is orphaned). They are what makes a retry cheap: only the organizations that have not finished do any work the second time.
The ordering is the contract. Nothing is acknowledged before it is durable, and nothing is acknowledged that has not been queued — a delivery recorded but not queued answers 500 so Linear retries it, because a row nothing will ever pick up is a webhook lost in silence.
What happens on a cold start
Nothing is lost, and this is the reason the work goes to QStash rather than after() / waitUntil. The handoff between accepting a delivery and processing it is a durable row plus a queued message, both outside the process. No in-memory queue, no timer, no post-response continuation. An instance that is recycled, killed or cold the moment after it answers Linear is carrying no state that mattered. A cold start is also now strictly cheaper on the request path than it was: module init, two indexed queries and a publish, where it used to be module init and the entire fan-out.
What happens on a duplicate delivery
recordWebhookDelivery dedupes on (provider, event_id) as it always has, and the route queues nothing whose row is not pending — a redelivery of something already carried through is a single query and a 200.
There is deliberately no QStash deduplicationId, despite the shape fitting. QStash keeps deduplication ids for 90 days, so once a message had exhausted its retries the same id would silently swallow Linear's 1-hour and 6-hour redeliveries of that event: accepted, not enqueued, 200. The delivery's own row dedupes instead and has the right lifetime, since recordWebhookDelivery reopens a failed row so a redelivery is queued again. A duplicate that does get through costs one query in the consumer, which returns early on an already-processed row.
What happens if the deferred work fails
- A connection fails. The other connections still run. The consumer marks the delivery
failedand answers 500, so QStash retries; the per-connection rows mean only the unfinished organizations repeat any work. - QStash exhausts its 3 retries. The message lands in QStash's DLQ and the row stays
failedwith the per-connection errors on it. Linear's own 1-hour and 6-hour redeliveries then reopen the row and queue it again — which works only because there is no deduplication id. - Both give up.
jobs/sweep-abandonedpicks the delivery back up an hour after it arrived and hands it to QStash again — see below. After five attempts it is markedabandonedand left alone, durable and queryable with the reason on the row. - The body is gone (its partition is dropped at 7 days, well before the row's 30): the consumer marks it
failedand answers 200 rather than retrying something no retry can recover.
Deliberately not in this change
- No Cloudflare Queues. This is the api-only step: the split between accepting a delivery and processing it, with an idempotent consumer, is the part the ratified plan needs either way. When the queue arrives it replaces
enqueueLinearDeliveryand calls the sameprocessDelivery. - No new env vars —
QSTASH_TOKEN/QSTASH_URLare already required by the api's env schema and used by the other job routes. The sweep does need a QStash schedule created, which is the one thing outside the repo; see Before this works on a schedule. - No retry loop anywhere around the failing query.
- GitHub's route is untouched, though it shows the same permit errors at lower volume. It already records once per delivery; it does not fan out per connection, so it is a different fix.
- The per-connection rows still each store a copy of the body. That predates this change (17 copies per delivery); the accepted delivery now adds an 18th. Storing it once is worth doing and belongs with the plan's "bodies stored once", not here.
- Deliveries nobody subscribes to are still dropped without a record, exactly as before — the one 200 that persists nothing, and it carries no work to lose. 317 Linear organizations have disconnected everything, and recording them would start writing rows and queueing work for traffic no measurement here can see.
The sweep
jobs/sweep-abandoned re-queues deliveries that were accepted but never carried through, and gives up on the ones that have had enough.
It reads a time band, not a status. The obvious query — Linear rows that are pending or failed — I measured on production-shaped data before writing it:
| access path | cost | grows with |
|---|---|---|
(provider, status) | 48.7s, 130k rows, 311k buffers dirtied | the pending/failed backlog |
(provider, event_id) prefix | one entry per delivery in retention — millions | all deliveries ever |
bitmap AND of both | 293ms, but walks 222k index entries | the backlog |
band of received_at | 539ms, 22.7k rows, sorts in memory | 15 minutes of ingest, nothing else |
A job that costs more than its cadence is precisely what #7114 had to stop happening, so the first one is not an option. The partial index that would make a status query cheap needs an ACCESS EXCLUSIVE lock on a 137M-row, 101 GB table on the hottest write path — the same index #7114 declined for the same reason — so this PR does not add one either. Only the band has a cost that does not move when the backlog does.
The band is read inside AS MATERIALIZED deliberately. Without the fence the planner has three ways to answer this and chooses between them on how the bounds are written and that day's statistics — one of the three being the 48.7s scan. The fence makes received_at the only usable predicate, so the cost is the band, permanently.
Sixty minutes is the abandonment age. Longer than the consumer's own maxDuration = 300, so nothing merely slow is swept; past QStash's three retries; and level with Linear's second redelivery, so Linear's own retry gets first attempt and this sits behind it. Far inside the seven days webhook_payloads keeps a body, so anything swept can still be read.
Fifteen minutes is the band, because that is what the measurement allows: an hour is 89.4k rows, 4.9s, and spills to disk. That makes this a rolling backstop rather than a catch-up — a delivery is examined while it sits in the band and never again — so the band has to stay wider than the cadence. At every 5 minutes each delivery passes under three runs and two can be missed before anything goes unexamined; a longer outage leaves its deliveries to Linear's redeliveries.
Bounds. singleFlight (the advisory lock from #7114) keeps one run at a time, and the run is held across its publishes so the route is one connection. At most 500 rows are read and 50 re-queued per run; the rest wait. A run also stops after three consecutive publish failures — a failure here is not row-specific, so 50 doomed publishes at two attempts each can outrun maxDuration and kill the run before the write-back commits, leaving deliveries that were published uncounted and published again next run.
Both write-backs are fenced on the state the row was read in, not just its id. A consumer re-queued by an earlier run can still be mid-flight — it has up to its own 300s ceiling — and commit while the sweep is working. So the abandonment update carries the status and attempt-count conditions it selected on: writing abandoned over a consumer's completed result would record the opposite of what happened, and since abandoned is a state the consumer refuses, it would also buy a duplicate fan-out from the next redelivery.
The attempt-count update needed more than that same status fence. The consumer increments retry_count when it marks a delivery failed, and a consumer started by the first publish of a run can finish before the last publish returns — failed is inside the status fence, so both increments would land and one re-queue would spend two of the delivery's five attempts. That makes the give-up fire early during exactly the incident the attempts exist for, which is a delivery-loss direction. It is therefore fenced on the count the row was read at as well, grouped by that value so it stays one statement per distinct count.
Ordering: publish, then count. A publish that failed does not spend one of the delivery's five. The opposite ordering is cheaper to write and loses deliveries, and a duplicate costs one query per already-finished connection.
That ordering has a cost, and it is worth naming rather than leaving implied. The band is read ORDER BY received_at with a ceiling of 50 re-queues, and a failed publish deliberately leaves the row untouched — so a partial but persistent publish failure starves the tail of the band: the same oldest rows sit at the head across all three runs a delivery gets, and rows behind them age out of the band unexamined. This is distinct from the outage case above, and it is not covered by "leaves its deliveries to Linear's own redeliveries" being about downtime.
It is accepted rather than fixed, for three reasons. The message is a fixed-shape pointer, so there is no row-specific reason for a publish to fail — 50 consecutive failures means QStash is unreachable, refusing or rate-limiting, and in that state no row can be re-queued whichever ones are picked, so the blocking loses nothing that was not already lost. The deliveries are not lost meanwhile: Linear's redeliveries at 1 minute, 1 hour and 6 hours reopen the row through recordWebhookDelivery, and the band sits at 60–75 minutes, so a starved delivery still has the 6-hour attempt ahead of it. And the obvious fix — a persisted recovery cursor — is worse in the case it is meant to help: the band's starvation is self-limiting at fifteen minutes, where a cursor parked on a row that keeps failing blocks everything behind it indefinitely unless it is aged, at which point it is the band again with durable state added to a route whose entire cost argument is that it holds none.
What would change that: a publish failure that is persistent and row-specific — a delivery id shape QStash rejects, a per-row quota. If one appears, this ordering is the first thing to revisit, and the cheap answer is to rotate the offset within the band rather than to persist a cursor.
Giving up. Five attempts — counting every attempt the row has had, including the consumer's own failures and reopenings by Linear redeliveries — and then the row is set to abandoned, a status neither the sweep's query nor the consumer will act on. A poison delivery stops within a few sweeps and stays visible with the reason on it, instead of being swept forever.
Not re-queueing a fragment. Delivery rows and per-connection rows share this table, and re-queueing a per-connection row would fan out part of a delivery. The delivery row's event_id now carries a delivery:h: / delivery:c: marker: the prefix is what the query matches on, and the letter records whether Linear sent a delivery header — which cannot be recovered from the id, and which the consumer needs, because a delivery with no header derives its automation-event dedup key differently. planSweep refuses anything that is not a delivery row rather than guessing, and per-connection ids are untouched.
Before this works on a schedule
One thing outside the repo: a QStash schedule has to be created for POST /api/integrations/linear/jobs/sweep-abandoned, every 5 minutes. Schedules for this app live in the Upstash console, not in this repository — there is no vercel.json crons block and no schedule manifest to add to — which is why the earlier revision of this PR avoided adding a route that nothing would call.
Until that schedule exists the route is inert: it verifies QStash signatures like every other job route, so it cannot be triggered by anything else, and nothing else calls it. Everything else in this PR works without it; what is missing without it is only the backstop, and the failure it backstops needs QStash to have exhausted its retries and Linear to have exhausted its own.
Immediate follow-up
Three findings from the bot review; each is answered in its thread.
Fixed — the body lookup matched nothing (critical). The consumer looked the body up by the timestamp carried through the queue. received_at is a Postgres timestamp keeping microseconds and arrives here as a JavaScript Date, which keeps milliseconds, so the lookup asked for …01.812 where the row holds …01.812344. Every delivery would have been marked failed with "payload missing" and none of the fan-out would have run — the feature would have been broken outright, not degraded. Checked against a copy of production: the old condition matches 0 rows for a real delivery, the new one matches 1. Exactness now comes from p.received_at = e.received_at; only the day is constant, and EXPLAIN confirms pruning to one partition is intact. partitionDay holds the reasoning and is tested at both midnight edges.
Fixed — the publish was unbounded against Linear's clock. The QStash client defaults to retries: 5 with backoff: (n) => Math.exp(n) * 50, about 4.3s of sleeping before it throws, inside a five-second budget, on the path whose only job is to answer fast. The client now uses retry: { retries: 1, backoff: () => 150 }. There is no signal or publish timeout to pass — the SDK's timeout bounds QStash's call to the destination — and racing a timer would leave the publish running with an unknowable outcome, which is the one thing this path cannot have. A fast 500 is strictly better than a slow one: the row is already durable and Linear's redelivery re-queues it.
Not taken — an atomic pending → processing claim per connection. The race is real but pre-existing and unchanged here: the route already read a pending row and acted on it without claiming it, and this PR moves that code rather than widening the window. A lease would also need a reaper for rows abandoned by a killed function, and claim semantics belong in the queued-ingest consumer, decided once for every provider.
The decline rests entirely on the side effects being idempotent, so here is that claim in full rather than as an assertion — it is what a future reviewer needs to re-check, and it is exactly what stops holding if someone adds a fourth writer to this path.
processForConnection has three side effects, and each is idempotent for a different reason:
- The task mirror (
processIssueEvent,tasks). The upsert carriessetWhere: tasks.externalUpdatedAt IS NULL OR tasks.externalUpdatedAt < excluded.external_updated_at. Two racing deliveries for one issue both write, and Postgres discards the one carrying the olderupdatedAt— the decision is made by the conditional write, not by the read above it, which is why the read going stale is harmless. Equal timestamps — the same delivery processed twice — also lose, so a duplicate is a no-op rather than a rewrite. - The automation event (
ingestAutomationEvent→recordAutomationEvent). Deduped on(integration_connection_id, provider, external_event_id), whereexternal_event_idis the delivery id: Linear'slinear-deliveryheader, which is stable across its retries, or${type}:${data.id}:${webhookTimestamp}when there is none. A second run inserts nothing and dispatches nothing. - The branch-name fetch (
fetchIssueBranchName). A read against Linear's API. A duplicate costs one wasted API call.
So the worst a duplicate fan-out does is spend a Linear API call and two no-op writes. That is the whole basis of the decline, and it is also why the sweep can re-queue a delivery without knowing whether a consumer is still on it.
What would break it. Any new writer on this path that is not conditional on the delivery's own ordering or deduped on its id — an append rather than an upsert (a comment mirror, an audit row, an outbound notification), a counter increment, a write keyed on something other than the delivery. retry_count is already such a counter and is already approximate for this reason. Adding one of those makes the claim false and makes the lease necessary, and the give-away is that it will not have a setWhere or a unique index behind it.
Verification
bunx biome check apps/api/src/app/api/integrations/linear
Checked 20 files in 13ms. No fixes applied.
bunx tsc --noEmit in apps/api — clean, no output.
bun test src in apps/api (whole app, not just the touched directory):
69 pass
0 fail
124 expect() calls
Ran 69 tests across 9 files. [90.00ms]
bun test in packages/db, which this branch also touches:
13 pass
0 fail
30 expect() calls
Ran 13 tests across 1 file. [45.00ms]
The sweep's rules are in planSweep, a pure function, so they are pinned without a database: it never re-queues a per-connection row or a row recorded before this format existed, it gives up at the fifth attempt but not the fourth, the per-run ceiling never crowds out marking a poison delivery abandoned, and a delivery that arrived without a header is re-queued as having none rather than as the string "null". deliveryIds pins the marker itself — that a per-connection id can never be read as a delivery row, and that re-deriving the header from a swept row reproduces the original per-connection ids exactly.
The sweep's query was run against a copy of production with its real bind parameters, and the plan checked (CTE Scan on band, fence intact). The two fenced write-backs were run against Postgres on a temp table rather than argued — each is UPDATE 1, not 2:
id | status | retry_count | outcome
----+-----------+-------------+------------------------------
1 | abandoned | 5 | ok: abandoned
2 | processed | 5 | ok: consumer result survived
3 | pending | 5 | ok: counted once
4 | failed | 5 | ok: no double count
``` The new tests were written before the code. `deliveryIds.test.ts` pins the dedup keys — an empty delivery header is not an id, bulk edits in the same millisecond do not collide, the per-connection format is byte-identical to the one rows were already recorded under, and a connection row can never collide with the delivery row. `route.test.ts` pins the acceptance contract: no acknowledgement of a delivery it could not record, none of a delivery it could not queue, nothing recorded for a delivery nobody subscribes to, and nothing recorded for a malformed body.
The consumer's payload read was checked against a copy of production rather than reasoned about, for a real delivery — the condition this PR started with against the one it ships:
stored | as_a_js_date | old_exact_match_rows | fixed_match_rows
2026-09-08 01:53:31.335643 | 2026-09-08 01:53:31.335 | 0 | 1
and that the day bounds still prune to one partition:
Nested Loop Left Join
Join Filter: (p.received_at = e.received_at)
-> Index Scan using webhook_events_pkey on webhook_events e
-> Index Scan using webhook_payloads_20260908_pkey on webhook_payloads_20260908 p
Index Cond: ((webhook_event_id = ...) AND (received_at >= '2026-09-08 00:00:00')
AND (received_at < '2026-09-09 00:00:00'))
The fan-out width and subscriber counts quoted above are from the same database, queried directly.
Not verified end to end against live Linear traffic: QStash cannot reach a local api, so the queued half needs either a QStash dev server via `QSTASH_URL` or the deploy. Worth watching API-18 and the route's p95 after it lands.
Refs API-18
https://claude.ai/code/session_01RSwhAUCDyim8EcDyyRW5Hn
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
* **New Features**
* Linear webhook deliveries are processed asynchronously for more reliable handling.
* Events are delivered to active connections, including issue updates and automation events.
* Abandoned deliveries can be re-queued automatically, while exhausted attempts are marked accordingly.
* Duplicate deliveries are detected and prevented from being processed multiple times.
* Connection-specific results and processing statuses are tracked.
* **Bug Fixes**
* Failed deliveries can be retried instead of being silently acknowledged.
* Invalid requests are rejected, while completed deliveries are safely acknowledged.
* Delivery payloads are matched reliably across timestamp precision and day boundaries.
* Deliveries without active subscribers are acknowledged without unnecessary processing.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->