In distributed systems and event-driven architectures, network partitions, transient downstream slowdowns, and container restarts are operational constants, not edge cases. Yet many teams still rely on naive retry loops: catch a 5xx, sleep for a fixed interval, and retry until a static counter runs out.
At scale, simplistic retry logic does more than drop events; it can turn a partial failure into a cascading outage. Synchronized retries hammer a recovering service, short provider retry windows expire before your system is back, and abrupt pod terminations leave “zombie” jobs stranded in flight.
This guide treats retries, backoff, and queue mechanics as first-class architectural primitives and covers three patterns for production-grade delivery systems:
- Bridging provider-specific retry ceilings: reconciling short upstream retry windows (Slack, PagerDuty, GitHub, Shopify) with a durable replay queue.
- Leased worker heartbeats and stalled-delivery recovery: eliminating zombie jobs and duplicate processing during Kubernetes rolling deploys.
- Latency-driven adaptive backoff: using
p95andp99response-time percentiles to slow delivery before outright5xxfailures appear.
Note on provider numbers: The limits quoted below were checked against vendor documentation in December 2026. Providers change these values, so confirm them before you size your own retention and reconciliation windows.
1. Handling Provider-Specific Retry Ceilings
When you receive webhooks, your ingestion layer is at the mercy of the sender’s retry policy. Each provider enforces its own response deadline, retry schedule, and rules for disabling a failing subscription. The differences are large enough to shape your architecture.
The Asymmetry of Upstream Retry Schedules
| Provider | Response deadline | Retry behavior | After exhaustion / disablement |
|---|---|---|---|
| Slack Events API | 3 seconds (any HTTP 2xx) | 3 retries: nearly immediately, after about 1 minute, and after about 5 minutes. Optional Delayed Events adds hourly retries for up to 24 hours. | Slack’s docs offer no way to resend an event. If more than 95% of delivery attempts fail within 60 minutes, Slack temporarily disables the app’s event subscriptions (the docs exempt apps receiving fewer than 1,000 events per hour). |
| PagerDuty Webhooks (V3) | 5 seconds (16 seconds for webhooks from Custom Incident Actions) | Retries for up to 48 hours on timeouts, connection failures, 5xx, and 429. Any other 4xx is treated as permanent and not retried. | 3 consecutive dropped webhooks disable the subscription for 24 hours, and queued webhooks are discarded. Ordering is guaranteed per subscription and incident, so a retrying webhook holds later ones for the same incident behind it. |
| Stripe (live mode) | Not covered here | Exponential backoff for up to 3 days. Test mode retries three times over a few hours. | Stripe emails you if an endpoint has returned no 2xx for multiple days and states when it will be disabled automatically. Missed events can be retried from the Dashboard or listed via the API (events from the last 30 days). |
| Shopify | 5 seconds | 19 retries over 48 hours. | After 19 consecutive failures the webhook subscription is automatically deleted. |
| GitHub | 10 seconds (GitHub.com) | No automatic redelivery. | Failed deliveries are recorded as failures. You redeliver manually or via the REST API, and only deliveries from the past 3 days are eligible. |
The Six-Minute Cliff
Slack’s default schedule illustrates a classic trap. If your database goes down for a 10-minute maintenance window, the three retries are spent in roughly six minutes, and those deliveries are gone unless you enabled Delayed Events (which also has a default two-hour cutoff for late events). If the failure rate crosses the 95% threshold, Slack may also disable your event subscriptions.
PagerDuty has the opposite problem. Its 48-hour retry window is generous, but ordering is enforced per subscription and incident. Suppose an incident.triggered delivery times out because your handler spent 6 seconds querying an internal CMDB against a 5-second deadline. Later webhooks for the same incident (incident.acknowledged, incident.resolved) wait behind it. A short outage on your side can also produce three consecutive drops and a 24-hour subscription disablement.
GitHub shows a third failure mode: with no automatic retries, an outage means missed events until you notice and redeliver them within the 3-day window.
Architectural Pattern: Acknowledge-First Durable Replay
To bridge short-retry providers and fragile downstream processors, separate ingestion from execution.
[Slack / PagerDuty / GitHub / Shopify] │ (HTTP POST, 3–10 s response deadline) ▼ ┌─────────────────────────────────────────┐ │ Stateless Ingestion Edge │ │ 1. Verify HMAC signature on raw body │ │ 2. Persist raw payload + headers │ │ 3. Return 2xx (202 Accepted) fast │ └──────────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────────┐ │ Durable Event Log / Replay Queue │ │ (Kafka / SQS / Postgres / Redis Streams)│ └──────────────────┬──────────────────────┘ │ ┌───────────┴───────────┐ ▼ ▼ [Primary Worker Pool] [Dead-Letter / Replay Store] (multi-day backoff) (retention you choose + replay API) Step 1: Fast-Path Verification and Persistence
The public endpoint should contain no business logic. Its responsibilities are:
- Cryptographic verification. Verify the signature over the raw request body before parsing it, using a constant-time comparison. Slack signs with HMAC-SHA256 (
X-Slack-Signature, withX-Slack-Request-Timestamp, and you should reject deliveries older than 5 minutes). PagerDuty signs with HMAC-SHA256 inX-PagerDuty-Signature; the header can hold several comma-separatedv1=entries while a secret is being rotated, so accept a match on any of them. Stripe uses theStripe-Signatureheader. - Idempotency key extraction. Capture the provider’s delivery identifier before parsing the domain payload:
event_idfor Slack,X-Webhook-Idfor PagerDuty (repeated across retries of the same webhook),X-GitHub-Deliveryfor GitHub, and the eventidfor Stripe. - Durable write and a fast
2xx. Persist the raw body, headers, and arrival time to an append-only store (Kafka, SQS, or a Postgres outbox table), then return202 Accepted. Aim for tens of milliseconds, well inside every provider’s deadline.
Choose status codes deliberately, because they can change provider behavior. Return 4xx only for requests you never want to see again, such as bad signatures. PagerDuty treats non-429 4xx responses as permanent, while a 5xx for a forged request would invite 48 hours of retries. For Slack, you can respond with a non-200 status and the X-Slack-No-Retry: 1 header to ask Slack not to resend that event.
Because delivery is at-least-once everywhere, the ingestion edge must also deduplicate on those identifiers, and your retention for processed IDs should exceed the provider’s longest retry window (more than 48 hours for PagerDuty, more than 3 days for Stripe).
Step 2: Internal Long-Tail Backoff and Replay
Once an event is in your durable queue, you control the retry lifecycle. Instead of Slack’s six-minute window, you can run a multi-day schedule, for example exponential backoff with jitter spanning 72 hours, and move exhausted messages to a Dead-Letter Queue (DLQ). Pick the DLQ retention to match how long you need to replay. On SQS, for instance, queue retention is bounded (up to 14 days), whereas a Kafka topic or Postgres table can retain longer.
After an outage, run a controlled replay: drain the DLQ back into the primary topic at a rate-limited pace so downstream services are not hit by the whole backlog at once.
Reconciliation is still required. If the network between the provider and your edge fails, even an acknowledge-first design can miss events. Pair the queue with a periodic reconciliation worker that polls the provider’s API for state whenever you detect an ingestion gap, a subscription warning, or a disablement. PagerDuty explicitly does not resend webhooks it discarded after a disablement, and Slack’s docs offer no way to browse or resend past deliveries. GitHub (REST API) and Stripe (List Events API) both let you enumerate missed deliveries or events.
2. Leased Worker Heartbeats and Stalled Delivery Recovery
In Kubernetes, worker pods are ephemeral. Autoscalers remove idle replicas, rolling deployments replace pods many times a day, and spot capacity can be reclaimed on short notice: AWS gives a two-minute interruption notice, while Azure Spot VMs and Google Cloud Spot VMs give roughly 30 seconds (best effort).
If a worker pulls a message and is then killed mid-delivery (SIGKILL, or an OOMKilled container), the job ends up in one of two bad states: lost (if it was acknowledged on pull) or stuck as a zombie (if it was marked IN_PROGRESS with no expiry).
Fixed Visibility Timeouts Force a Trade-Off
Amazon SQS hides a received message from other consumers for the visibility timeout (30 seconds by default, up to 12 hours). If the consumer deletes the message in time, processing succeeded; if it crashes, the message reappears afterwards. A fixed value forces a trade-off when job durations vary:
- Too short (for example 30 s): a legitimately slow job outlives the timeout, a second worker picks it up, and you get concurrent duplicate execution.
- Too long (for example 15 min): a pod that is
OOMKilledtwo seconds into a job leaves it stalled for almost 15 minutes, which breaks real-time latency goals.
SQS’s own documentation recommends a heartbeat: periodically extend the visibility timeout with ChangeMessageVisibility while work is in progress. Note that the 12-hour maximum is measured from first receipt and extending does not reset it. The pattern below applies the same idea to a database-backed queue and adds fencing.
Short Leases, Heartbeats, and Fencing Tokens
Instead of reserving a job for its worst-case runtime, a worker takes a short lease (say 15 seconds) and a background heartbeat extends it every ~5 seconds (a common rule of thumb is a heartbeat interval of about one third of the lease). A monotonically increasing fencing token protects against stale workers.
1. Lease Acquisition
-- Atomic lease acquisition in PostgreSQL (SKIP LOCKED pattern) WITH next_job AS ( SELECT job_id FROM delivery_jobs WHERE status IN ('PENDING', 'IN_FLIGHT') AND next_run_at <= NOW() AND (lease_expires_at IS NULL OR lease_expires_at < NOW()) ORDER BY next_run_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED ) UPDATE delivery_jobs d SET status = 'IN_FLIGHT', worker_id = :worker_uuid, lease_expires_at = NOW() + INTERVAL '15 seconds', attempt_count = d.attempt_count + 1, fencing_token = d.fencing_token + 1, updated_at = NOW() FROM next_job WHERE d.job_id = next_job.job_id RETURNING d.*; 2. Fencing Against Split-Brain Workers
Imagine a worker hits a long GC pause or network stall. Its lease expires at second 15, a healthy worker claims the job at second 16 (fencing token 2), and the stalled worker wakes at second 18 still believing it owns the job (token 1). Every renewal and every final state commit must therefore check the token:
-- Conditional heartbeat (affects 0 rows if the lease was taken over) UPDATE delivery_jobs SET lease_expires_at = NOW() + INTERVAL '15 seconds', updated_at = NOW() WHERE job_id = :job_id AND worker_id = :worker_uuid AND fencing_token = :current_token AND status = 'IN_FLIGHT'; If the update affects zero rows, the heartbeat loop should cancel the local execution context (calling the cancel function from context.WithCancel in Go, or AbortController.abort() in Node.js) so in-flight work stops as early as possible. Apply the same WHERE ... fencing_token = :current_token guard when writing the final DELIVERED or FAILED state.
An honest limitation: a fencing token only protects resources that check it. The database row in the example does, but a third-party webhook receiver does not. A stale worker may therefore still complete an outbound HTTP call. Treat delivery as at-least-once, and send a stable idempotency key (for example the job ID) on every attempt so receivers can deduplicate.
3. Graceful Shutdown During Rolling Deploys
Heartbeats handle ungraceful deaths (SIGKILL, OOMKilled), which cannot be trapped. Planned terminations send SIGTERM first, so cooperate with Kubernetes:
- Set
terminationGracePeriodSecondsexplicitly (the default is 30 seconds; for example use60) so slow deliveries have headroom beforeSIGKILL. - Handle
SIGTERMimmediately by stopping new polls. - Drain, then release. Wait for active deliveries for a bounded time (for example 45 seconds, leaving margin inside a 60-second grace period). For anything unfinished, perform a voluntary lease release (
SET status = 'PENDING', lease_expires_at = NULL) so another pod picks it up immediately. Consider not counting that release as a failed attempt.
3. Adaptive Backoff Based on Latency Percentiles (p95/p99), Not Just Status Codes
Classic exponential backoff reacts to a binary signal: 200 means healthy, while 502, 503, 504, or a timeout triggers a backoff step. Real services rarely fail that cleanly. They go through gray failures, where the system is degraded but not reporting itself as down, as described in the “Gray Failure” research from Microsoft Research. Typical symptoms include:
- Connection pools saturate and request durations climb from tens of milliseconds to seconds.
- GC pauses or CPU throttling push tail latency (
p99) toward the client’s read timeout. - Workers keep dispatching at full concurrency because most requests still return
200, and this can push a struggling receiver into collapse.
Tail Latency as an Early-Warning Signal
Averages hide degradation: an endpoint can hold a 120ms median while its p99 spikes into the multi-second range. Tracking rolling p95 and p99 latency per destination gives you an early indicator of saturation before 5xx errors appear. You can feed that signal into both the retry scheduler and the outbound dispatcher.
A Latency-Aware Backoff Formula
Standard exponential backoff with full jitter:
Tbase(n)=min(Tmax, Tinitial⋅2n),Tsleep=Uniform(0, Tbase(n))T_{\text{base}}(n) = \min\left(T_{\max},\; T_{\text{initial}} \cdot 2^{n}\right), \qquad T_{\text{sleep}} = \text{Uniform}\left(0,\; T_{\text{base}}(n)\right)Tbase(n)=min(Tmax,Tinitial⋅2n),Tsleep=Uniform(0,Tbase(n))
Add a latency degradation multiplier α\alphaα, computed from a rolling window (for example, the last 60 seconds or 500 requests) of per-destination latencies versus a healthy baseline:
R95=Lp95,currentLp95,baseline,R99=Lp99,currentLp99,baselineR_{95} = \frac{L_{p95,\text{current}}}{L_{p95,\text{baseline}}}, \qquad R_{99} = \frac{L_{p99,\text{current}}}{L_{p99,\text{baseline}}}R95=Lp95,baselineLp95,current,R99=Lp99,baselineLp99,current
α=clamp(1.0+w1⋅max(0,R95−θ95)+w2⋅max(0,R99−θ99), 1.0, αmax)\alpha = \text{clamp}\left( 1.0 + w_1 \cdot \max(0, R_{95} - \theta_{95}) + w_2 \cdot \max(0, R_{99} - \theta_{99}),\; 1.0,\; \alpha_{\max} \right)α=clamp(1.0+w1⋅max(0,R95−θ95)+w2⋅max(0,R99−θ99),1.0,αmax)
Where θ95\theta_{95}θ95 and θ99\theta_{99}θ99 are tolerance thresholds (for example 1.51.51.5 and 2.02.02.0), w1w_1w1 and w2w_2w2 are sensitivity weights (for example 0.50.50.5 and 0.750.750.75), and αmax\alpha_{\max}αmax caps the multiplier (for example 8.08.08.0). The adaptive ceiling becomes:
Tadaptive(n)=min(Tmax, α⋅Tinitial⋅2n)T_{\text{adaptive}}(n) = \min\left(T_{\max},\; \alpha \cdot T_{\text{initial}} \cdot 2^{n}\right)Tadaptive(n)=min(Tmax,α⋅Tinitial⋅2n)
The thresholds, weights, and cap are tuning parameters, not universal constants. Start with the illustrative values above and calibrate them against your own destinations.
How It Behaves
Assume Lp95,baseline=200msL_{p95,\text{baseline}} = 200\text{ms}Lp95,baseline=200ms, Lp99,baseline=400msL_{p99,\text{baseline}} = 400\text{ms}Lp99,baseline=400ms, Tinitial=2sT_{\text{initial}} = 2\text{s}Tinitial=2s, θ95=1.5\theta_{95} = 1.5θ95=1.5, and θ99=2.0\theta_{99} = 2.0θ99=2.0:
- Normal operation (Lp95=220msL_{p95} = 220\text{ms}Lp95=220ms, Lp99=450msL_{p99} = 450\text{ms}Lp99=450ms): R95=1.10R_{95} = 1.10R95=1.10 and R99=1.125R_{99} = 1.125R99=1.125 are both under their thresholds, so α=1.0\alpha = 1.0α=1.0 and retries follow the normal curve (ceilings of
2s,4s,8s, ...). - Gray failure (Lp95=600msL_{p95} = 600\text{ms}Lp95=600ms, Lp99=2,400msL_{p99} = 2{,}400\text{ms}Lp99=2,400ms): even if most requests still return
200, a status-code-only breaker sees nothing wrong. Here R95=3.0R_{95} = 3.0R95=3.0 and R99=6.0R_{99} = 6.0R99=6.0, so α=1.0+0.5(3.0−1.5)+0.75(6.0−2.0)=4.75\alpha = 1.0 + 0.5(3.0-1.5) + 0.75(6.0-2.0) = 4.75α=1.0+0.5(3.0−1.5)+0.75(6.0−2.0)=4.75. At n=1n = 1n=1 the ceiling stretches from4sto19s. - Severe degradation (Lp99≥5,000msL_{p99} \ge 5{,}000\text{ms}Lp99≥5,000ms): R99≥12.5R_{99} \ge 12.5R99≥12.5, which by itself pushes α\alphaα past the cap, so α=αmax=8.0\alpha = \alpha_{\max} = 8.0α=αmax=8.0. Pair this with a per-destination adaptive concurrency limiter (for example AIMD, additive increase and multiplicative decrease) that shrinks in-flight requests to a small number of probes until latency recovers.
Reference Implementation (TypeScript)
This sketch combines a sliding-window percentile tracker, latency-scaled backoff, full jitter, and Retry-After handling.
interface AdaptiveBackoffConfig { windowSize: number; // e.g. 500 samples minSamples: number; // e.g. 20 baselineP95Ms: number; baselineP99Ms: number; thresholdP95: number; // e.g. 1.5 thresholdP99: number; // e.g. 2.0 weightP95: number; // e.g. 0.5 weightP99: number; // e.g. 0.75 maxMultiplier: number; // e.g. 8.0 } export class AdaptiveBackoffScheduler { private samples: number[] = []; constructor(private readonly config: AdaptiveBackoffConfig) {} /** Record a response duration in ms. Record timeouts too (see best practices). */ public recordLatency(durationMs: number): void { this.samples.push(durationMs); if (this.samples.length > this.config.windowSize) this.samples.shift(); } private percentile(sorted: number[], p: number): number { if (sorted.length === 0) return 0; const idx = Math.ceil((p / 100) * sorted.length) - 1; return sorted[Math.max(0, Math.min(idx, sorted.length - 1))]; } /** Latency degradation multiplier (alpha) from rolling p95/p99. */ public computeMultiplier(): number { const c = this.config; if (this.samples.length < c.minSamples) return 1.0; // avoid reacting to noise const sorted = [...this.samples].sort((a, b) => a - b); const r95 = this.percentile(sorted, 95) / c.baselineP95Ms; const r99 = this.percentile(sorted, 99) / c.baselineP99Ms; const alpha = 1.0 + c.weightP95 * Math.max(0, r95 - c.thresholdP95) + c.weightP99 * Math.max(0, r99 - c.thresholdP99); return Math.min(c.maxMultiplier, Math.max(1.0, alpha)); } /** * Next retry delay in ms: adaptive exponential cap, full jitter, * with an explicit Retry-After (in seconds) acting as a hard floor. */ public nextDelayMs( attempt: number, initialDelayMs = 1000, maxDelayMs = 300_000, retryAfterSeconds?: number ): number { const alpha = this.computeMultiplier(); const cap = Math.min(maxDelayMs, alpha * initialDelayMs * 2 ** attempt); const jittered = Math.floor(Math.random() * cap); if (retryAfterSeconds !== undefined && retryAfterSeconds > 0) { return Math.max(jittered, retryAfterSeconds * 1000); } return jittered; } } Two caveats on the sketch. With only 20 samples, the computed p99 is effectively the maximum, so raise minSamples if single outliers cause false alarms. And Retry-After may be either a number of seconds or an HTTP date, so a production version should parse both.
Best Practices for Multi-Tenant Queues
- Isolate metrics per destination. Never compute one global
p99across all consumers. A single slow customer endpoint should only slow its own partition, which prevents noisy-neighbor head-of-line blocking. - Learn baselines per destination. A fixed
baselineP95Msfails when one endpoint normally answers in40msand another in600ms. Maintain an exponentially weighted moving average (EWMA) of healthyp95/p99values per destination. - Count timeouts as slow samples. Record a timed-out request at its timeout value (or higher). Otherwise dropped connections never enter the window and your percentiles look better exactly when the receiver is unresponsive.
- Honor
Retry-After. When a downstream returns429or503withRetry-After, treat it as a hard floor under your jittered delay. - Use retry budgets and circuit breakers. Cap retries as a fraction of traffic per destination so retries cannot multiply load during an outage, and open a breaker when a destination stays unhealthy.
- Make attempts observable. Emit per-destination metrics (attempt counts,
alpha, concurrency limit, queue age) so operators can see why a delivery is being delayed.
Summary Checklist for Resilient Queue & Retry Engineering
- Decouple ingestion from execution. Verify the signature, persist the raw event, and return
2xximmediately, so Slack’s 3-second deadline, PagerDuty’s 5-second deadline, and similar limits stop being your problem. - Design for the provider’s retry ceiling. Plan for Slack’s roughly six-minute window, PagerDuty’s 3-drop disablement, and GitHub’s lack of retries, and add reconciliation against provider APIs.
- Deduplicate and be idempotent. Delivery is at-least-once everywhere, so key on
event_id,X-Webhook-Id, orX-GitHub-Delivery, and send idempotency keys on your own outbound deliveries. - Replace fixed lock timeouts with short leases. Combine heartbeats, fencing tokens, and
SIGTERMlease-release hooks, and remember fencing only protects resources that check the token. - React to tail latency, not just errors. Drive backoff multipliers and per-destination concurrency limits from rolling
p95/p99ratios so gray failures don’t escalate into full outages.
Originally published at https://instawebhook.com/blog/mastering-retries-backoff-queue-mechanics-architecture-for-resilient-event-deliv