Building a Webhook Delivery System That Actually Retries
Pranav Patel
Co-founder·11 min read
On this page

How Reloop delivers webhooks: idempotent events, per-endpoint filters and rate limits, HMAC-SHA256 signatures, SSRF protection with DNS pinning, a 7-attempt retry schedule over 17 hours, auto-disable and manual replays.
A webhook system is only as good as what it does when your endpoint is down. Reloop's webhook system delivers every event at least once: it stores the event, creates one delivery per subscribed endpoint, signs the body with HMAC-SHA256, and POSTs it from a BullMQ worker. If the endpoint fails, the delivery is retried up to 7 times over about 17 hours. Endpoints that keep failing are disabled instead of hammered, and any delivery can be replayed by hand.
This post walks through how that works in the Reloop codebase, with the numbers taken straight from the code. (The code is public because we open-sourced the whole stack.)
The flow
1Something happens (email delivered, contact created, domain verified, …)2 │3 ▼ NATS event4workflow service — dispatcher (queue group "webhook-dispatcher")5 │ 1. insert webhook_event (idempotent)6 │ 2. find active endpoints subscribed to this event type7 │ 3. per endpoint: filters → rate limit → insert webhook_delivery8 │ 4. enqueue BullMQ job (jobId = deliveryId)9 ▼10BullMQ "webhook-delivery-queue" (concurrency 10)11 │ sign → SSRF-checked, DNS-pinned HTTPS POST → record result12 ├── 2xx → success, reset consecutive failures13 ├── error / non-2xx → retry on fixed schedule14 └── last attempt → failed, maybe auto-disable endpointThree tables carry the state:
webhook_eventwebhook_deliverywebhook1. Events are idempotent
The same real-world event can show up more than once. KumoMTA (the MTA at the heart of our delivery pipeline) can log twice, a NATS message can be redelivered, a service can restart mid-handler. If each of those created a new webhook, customers would see duplicate email.delivered calls.
So every dispatch carries a stable key. For delivery events it's built from the organization, event type, email ID, KumoMTA record type and record ID:
const sourceKey = `${orgId}:${webhookType}:${email.id}:${event.type}:${event.id}`;The dispatcher looks the key up before inserting, and the unique constraint on idempotency_key catches the race where two replicas insert at once:
1// apps/backend/workflow/src/lib/webhook-dispatcher.ts (simplified)2const existing = await db.query.webhookEvent.findFirst({3 where: eq(schema.webhookEvent.idempotencyKey, idempotencyKey),4});5if (existing) return { eventId: existing.id, deliveryCount: 0 };6
7try {8 await db.insert(schema.webhookEvent).values({ id: eventId, idempotencyKey, ... });9} catch {10 // unique violation: a concurrent insert won, reuse it11}On top of that, the dispatcher subscribes in the NATS queue group webhook-dispatcher, so only one workflow replica handles each event in the first place.
2. Fan-out with per-endpoint settings
For each active endpoint subscribed to the event type, the dispatcher applies that endpoint's settings before creating a delivery.
maxRetriesrateLimitEnabledtruemaxRequestsPerMinutefilteringOptions.matchConditionsdata field equals the valuefilteringOptions.excludeFieldsdataRate limits delay, they don't drop
The outbound limit is a fixed one-minute window in Redis. When an endpoint is over its cap, the delivery isn't discarded. Its first attempt is delayed until the window resets:
1// apps/backend/workflow/src/lib/webhook-dispatcher.ts (simplified)2const bucket = Math.floor(Date.now() / 60_000);3const key = `reloop:webhook-out:${hook.id}:${bucket}`;4const count = await redis.increment(key);5if (count === 1) await redis.expire(key, 65);6
7if (isWebhookRateLimited(count, hook.maxRequestsPerMinute)) {8 delayMs = rateLimitDelayMs(await redis.ttl(key)); // at least 1 s9}If Redis is unavailable, the check fails open and the delivery goes out. Losing a rate limit for a minute is better than losing events.
Filters
Filtering is shallow on purpose. A customer who only wants bounces (say, to mirror our bounce processing into their own database) can set:
1{2 "filteringOptions": {3 "matchConditions": { "status": "bounced" },4 "excludeFields": ["subject"]5 }6}The excluded fields are removed from the stored delivery payload too, not just the outgoing request, so sensitive fields never sit in our delivery logs.
3. Signing
Every POST is signed with the endpoint's secret (whsec_…, stored encrypted and decrypted only inside the worker). The signed string is the Unix timestamp, a dot, and the exact raw body:
1export function signWebhookBody(secret: string, rawBody: string, ts: number) {2 return createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");3}The request carries three headers:
Reloop-Idwhev_01h… (same as the body's id)Reloop-Timestamp1753185600Reloop-Signaturet=1753185600,v1=5257a8…Two details matter here:
- The body is serialized once. The worker builds the envelope, calls
JSON.stringifyonce, signs that string and sends that same string. Re-serializing between signing and sending is the classic way to ship signatures that never verify. - Customers can't override the security headers. Endpoints can add custom headers, but names like
Reloop-Signature,Content-Type,HostandAuthorizationare reserved and silently dropped.
On the receiving side, verify against the raw body, use a constant-time compare, and reject timestamps older than five minutes to block replays. The full snippet is in the webhook verification docs.
4. Sending without becoming an SSRF proxy
A webhook URL is user input that makes our servers send HTTP requests. Without care, someone could point it at http://169.254.169.254/ or an internal service and use us to reach it.
The HTTP client in packages/webhook-delivery does three things:
- HTTPS only in production.
- Resolve, then validate. The hostname is resolved, and every address is checked against private ranges (
10/8,172.16/12,192.168/16, loopback, IPv6 ULA) and always-blocked ranges (link-local169.254/16, CGNAT100.64/10, multicast,0.0.0.0). - Pin the IP. The request connects to the exact IP that passed validation, while still sending the original hostname for TLS SNI and the
Hostheader. This closes the DNS-rebinding gap where a hostname resolves to a public IP during the check and a private one during the request.
1// packages/webhook-delivery/src/http-client.ts (simplified)2lib.request({3 hostname: resolved.pinnedIp,4 servername: parsed.hostname, // TLS SNI5 headers: { ...headers, Host: parsed.host },6 lookup: (_h, _o, cb) => cb(null, resolved.pinnedIp, resolved.family),7 timeout: 10_000,8});Requests time out after 10 seconds, and stored response bodies are truncated at 8,192 characters.
5. Retries on a fixed schedule
We tried exponential backoff first. It's fine for jobs, but bad for humans debugging webhooks: "when is the next try?" shouldn't need a calculator. So retries follow a fixed, documented schedule, implemented as a custom BullMQ backoff:
1export const WEBHOOK_RETRY_DELAYS_MS = [2 5_000, // before attempt 23 5 * 60_000, // before attempt 34 30 * 60_000, // before attempt 45 2 * 60 * 60_000, // before attempt 56 5 * 60 * 60_000, // before attempt 67 10 * 60 * 60_000 // before attempt 78] as const;The early retries catch blips like a deploy or a cold start. The late ones cover a real outage that someone has to wake up and fix.
Any network error, timeout or non-2xx response counts as a failure. Each attempt writes the response status, a truncated body, the duration and the next retry time to webhook_delivery, so the dashboard can show exactly what happened.
The BullMQ job ID is the delivery ID. Enqueueing the same delivery twice is a no-op, so a restart in the middle of the fan-out can't create duplicate jobs.
6. Auto-disable broken endpoints
An endpoint that's been deleted or misconfigured will fail forever. Retrying every event 7 times against it wastes work and floods the delivery log.
After each terminal outcome (success, or failure on the last attempt) the worker updates the endpoint's counters in one statement:
1// apps/backend/workflow/src/handlers/webhook-delivery.handler.ts (simplified)2consecutiveFailures: succeeded3 ? 04 : sql`${schema.webhook.consecutiveFailures} + 1`,When consecutiveFailures reaches 10 (WEBHOOK_DISABLE_AFTER_CONSECUTIVE_FAILURES), the endpoint is marked failed and stops receiving new deliveries. One success in between resets the counter, so a flaky endpoint stays enabled. Re-enable it from the dashboard once it's fixed.
7. Replays
Sometimes you want an event again: you fixed a bug in your handler, or you restored a database. Replay creates a new delivery row linked to the original and enqueues it with the endpoint's current maxRetries. The original delivery's history is never changed, which keeps the audit trail honest.
Replays are refused while the endpoint is disabled, failed or paused, with a why explaining which.
What we'd tell anyone building this
FAQ
At least once. Events are deduplicated at the source, but a delivery can
still be retried after your server processed it and failed to respond in
time. Use the Reloop-Id header to make your handler idempotent.
Yes. Any non-2xx response is retried on the schedule. Only SSRF-blocked or non-HTTPS URLs fail immediately. Return 2xx as soon as you've stored the event, and do slow work asynchronously.
Yes. Set maxRetries on the endpoint to anything from 1 to 7. Only the
first rows of the schedule apply.
Email lifecycle (email.sent, email.delivered, email.bounced,
email.complained, email.opened, email.clicked, email.received
and more), plus domain, API key and contact events. See
event types. email.received is what lets
an AI agent read and reply to email.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


