引言
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. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。
问题
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. 理解问题的全貌是设计正确方案的前提。
设计决策
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); }
}
实现
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;
}
测试边界
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. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。
常见陷阱
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. 避开这些陷阱可以减少生产事故。
结论
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. 按照本文的方法,你可以构建出既安全又高效的解决方案。
Sources: Exponential backoff, Stripe webhooks.