How to Build a Webhook Retry System
Deliver webhooks with exponential backoff, jitter, dead-letter queues, and idempotency to handle endpoint failures without losing events.
On this page
Introduction
Webhooks deliver events to external systems, but those systems go down, return 500, or time out. A retry system ensures the event is eventually delivered without flooding the endpoint or losing the event. The key ingredients are persistence, exponential backoff with jitter, a dead-letter queue for permanent failures, and idempotency for safe redelivery. This guide builds a retry system that handles all four.
The problem
If you fire and forget, a failed delivery loses the event. If you retry immediately in a loop, you flood a struggling endpoint. If you retry without a cap, a permanently failing endpoint accumulates retries forever. If you redeliver without idempotency, the receiver processes the event twice. A real system needs a persistent queue, a backoff schedule, a circuit breaker, and a deduplication key.
Design decisions
Each webhook delivery is a row in a table with the event payload, endpoint URL, status, attempt count, and next retry time. A worker polls for deliveries due for retry and sends them. The backoff is exponential with jitter: next retry is base times two to the attempt power, plus a random fraction. On a 5xx or network error, the delivery is rescheduled. On a 4xx, it is moved to the dead-letter queue immediately. After max attempts, it is moved to the DLQ and an alert fires.
async processDelivery(d) {
try {
const res = await fetch(d.url, { method: 'POST', body: JSON.stringify(d.payload), headers: { 'X-Event-ID': d.id } });
if (res.status >= 500) throw new Error('server error');
if (res.status >= 400) return moveToDLQ(d, res.status);
await markDelivered(d);
} catch (e) { await scheduleRetry(d); }
}
Implementation
The retry schedule uses exponential backoff with a cap and jitter. The base interval is one second, the cap is one hour, and the jitter is up to twenty percent. The worker runs on a timer, queries for deliveries where next retry time is in the past, and processes them in batches with a concurrency limit. The dead-letter queue is a separate table or topic; deliveries there are available for manual replay or inspection. An alert fires when the DLQ depth exceeds a threshold.
function nextRetry(attempt) {
const base = 1000;
const cap = 3600000;
const exp = Math.min(cap, base * 2 ** attempt);
const jitter = exp * 0.2 * Math.random();
return Date.now() + exp + jitter;
}
Testing the boundary
Test that a 500 response schedules a retry with increasing delays. Test that a 400 response moves the delivery to the DLQ without retry. Test that after max attempts the delivery goes to the DLQ. Test that delivering the same event ID twice to a receiver that deduplicates results in one processing. Test that the worker respects the concurrency limit.
Common pitfalls
Avoid retrying 4xx errors; they are permanent. Avoid fixed retry intervals; they cause retry storms when many deliveries fail simultaneously. Avoid unbounded attempts; they fill the queue with hopeless retries. Avoid delivering without an event ID; the receiver cannot deduplicate. Avoid blocking the event producer on delivery; use an async queue so the producer is never blocked.
Operational considerations
Use exponential backoff with full jitter for retry delays: compute base * 2^attempt and then pick a uniform random value between zero and that ceiling. Full jitter spreads retries across the full window and avoids the thundering-herd pattern where every retrying webhook hits a recovering endpoint at the same deterministic instant. A base of one second and a cap of one hour covers most recovery windows; tune the cap to the endpoint’s expected recovery time, not to a generic best practice. Always persist the next attempt time, not just an attempt count, so a worker restart does not lose the schedule.
Move an event to a dead-letter queue after the maximum retry count, not after a maximum elapsed time. A max-attempts rule is deterministic and testable; a max-elapsed rule depends on wall-clock gaps between attempts that vary with backoff. The dead-letter entry stores the original payload, the endpoint URL, the attempt history with response codes and bodies, and the final error. A dashboard over the dead-letter queue surfaces endpoints that are consistently failing, which is usually a configuration problem on the receiver side, not a transient network issue.
Every webhook payload must carry an event ID and be signed with an HMAC of the payload body using a shared secret. The receiver checks the signature before any processing, so a forged webhook from a network attacker is rejected at the boundary. The receiver also deduplicates by event ID, because at-least-once delivery means the same event may arrive twice during a retry or a worker failover. Document that your delivery is at-least-once, not exactly-once, because receivers who assume exactly-once will skip deduplication and corrupt their state on a redelivery.
Monitor the delivery success rate per endpoint, the retry attempt distribution, and the dead-letter queue depth. A rising retry count on one endpoint often means the endpoint is slow, not down; a circuit breaker that pauses delivery to that endpoint for a minute after repeated 5xx responses lets it recover without generating a backlog of retries. Alert on dead-letter growth, not on individual retries, because retries are normal and dead-letters are the signal that an event needs human attention.
Conclusion
A webhook retry system needs persistence, exponential backoff with jitter, a dead-letter queue, and idempotency. Store every delivery, retry only on 5xx and network errors, cap the attempts, and include an event ID for deduplication. Test the retry schedule, the DLQ, and idempotency. The result is reliable delivery without flooding or losing events. Never retry on 4xx responses, because a 4xx indicates a permanent problem with the payload or the endpoint that retrying the same request will not fix.
Sources: Exponential backoff, Stripe webhooks.
FAQ
- Should I retry on 4xx errors?
- No. A 4xx indicates a permanent problem with the request; retrying will not help and wastes resources. Retry only on 5xx and network errors.
- How much jitter should I add?
- Add up to twenty percent of the backoff interval to spread retries and avoid synchronized retry storms.
- How do I ensure idempotency?
- Include a unique event ID in the webhook payload and header; the receiver should deduplicate by event ID.
Report a problem with this articleOpens a pre-filled issue on GitHub.