At-Least-Once Webhook Delivery That Survives a Redis Wipe: PostgreSQL, BullMQ and the Outbox Sweeper
KestrelMQ commits every delivery to PostgreSQL before queueing it, and an outbox sweeper re-enqueues anything Redis loses. Reproduce the recovery yourself with five commands, and see exactly how idempotency keys, job IDs and replays fit together.
Most queue-backed systems have the same hole: the database commit and the queue push are two writes to two stores. Crash in between, or lose Redis, and an accepted event silently never gets delivered.
KestrelMQ treats PostgreSQL as the source of truth and the queue as a disposable accelerator. Every delivery is committed as a PENDING row first, and an outbox sweeper re-enqueues any row that has no job. You can break Redis on purpose and watch it recover.
Prove it: wipe Redis and watch the delivery land
This runs against the Docker quickstart with the integration and routing rule from the 3-minute walkthrough ($KMQ is your API URL, $KMQ_API_KEY a workspace API key).
# 1. Stop the worker so the job just sits in the queue.
docker compose --profile full stop worker
# 2. Ingest an event. It is committed to PostgreSQL as a PENDING delivery.
curl -s -X POST "$KMQ/v1/events" \
-H "Authorization: Bearer $KMQ_API_KEY" \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: outbox-demo-1' \
-d '{"event":"order.paid","payload":{"orderId":"ord_9001","amount":149.99}}' \
| jq '{eventId, deliveryIds}'
# 3. Simulate Redis losing its data: the BullMQ job is gone, the row is not.
docker compose exec redis redis-cli FLUSHALL
# 4. Bring the worker back.
docker compose --profile full start worker
# 5. Poll. The status stays PENDING until the sweeper's next tick, then flips.
watch -n 5 "curl -s '$KMQ/v1/deliveries?limit=1' -H 'Authorization: Bearer $KMQ_API_KEY' | jq '.data[0] | {id, status, attemptCount}'"Expected: PENDING with attemptCount: 0 right after step 4, then DELIVERED within about 30 to 90 seconds. The sweeper runs every 60 seconds and only touches rows older than 30 seconds, so the wait is the point: nothing was re-queued by hand, and the delivery was never lost.
Two notes on what you just exercised:
- With Redis completely down,
POST /v1/eventsfails fast, because the workspace rate limiter lives in Redis. The recovery path covers the narrower and nastier cases: Redis restarts without persistence, an eviction, an operatorFLUSHALL, or a crash between the commit and the enqueue. - If the crash happens after the commit but before the enqueue finishes, the API call itself may return an error even though the delivery rows are durable. Retry with the same
Idempotency-Key: the unique constraint in PostgreSQL finds the existing event and returns it, so you get no duplicate fan-out.
The pipeline
ingest -> PostgreSQL txn (event + delivery rows, PENDING) -> BullMQ job -> worker attempt
ok -> DELIVERED
transient -> RETRYING (backoff) -> worker attempt ...
fatal/exhausted -> FAILED -> deliveries-dlq -> replay (manual)
sweeper: PENDING older than 30s -> re-enqueue (idempotent)Step 1: commit first, queue second
On POST /v1/events, KestrelMQ validates the payload against the workspace's event schema, evaluates routing rules, and writes the event plus one delivery row per matching route in a single transaction. Each delivery starts as PENDING (or SCHEDULED when deliverAt is set). Only after the commit does it enqueue:
const { event, deliveries } = await prisma.$transaction(async (tx) => {
const event = await tx.event.create({ data: { workspaceId, eventName, payload } });
const deliveries = await Promise.all(
routes.map((route) =>
tx.delivery.create({ data: { eventId: event.id, routeId: route.id, status: "PENDING" } }),
),
);
return { event, deliveries };
});
// After commit. If this throws or the process dies, the rows above are still durable
// and the outbox sweeper will enqueue them.
await deliveriesQueue.addBulk(
deliveries.map((d) => ({
name: "deliver",
data: { deliveryId: d.id, workspaceId, eventId: event.id },
opts: { jobId: d.id, attempts: d.maxAttempts, backoff: { type: "kestrel-exponential" } },
})),
);Step 2: BullMQ executes the attempts
Workers consume the deliveries queue: load the delivery, decrypt integration credentials in memory, render the template, sign the request and call the target with a 10-second timeout through the SSRF-pinned client (see SSRF protection). Every attempt is recorded in delivery_attempts. Transient failures (429, 5xx, network errors, timeouts) retry; any other 4xx and configuration errors are fatal and go straight to FAILED.
Step 3: the outbox sweeper closes the gap
The sweeper is a repeatable job (outbox-sweeper-cron, every 60 seconds) on its own outbox-sweeper queue. It treats the deliveries table as an outbox:
const stale = await prisma.delivery.findMany({
where: { status: "PENDING", createdAt: { lt: new Date(Date.now() - 30_000) } },
orderBy: { createdAt: "asc" },
take: 200, // batch size per tick
});
await deliveriesQueue.addBulk(
stale.map((d) => ({ name: "deliver", data: { deliveryId: d.id /* ... */ }, opts: { jobId: d.id } })),
);Because jobId equals the delivery ID, BullMQ drops the add when a job for that delivery already exists, so the sweeper can be aggressive without creating duplicate work. SCHEDULED and PAUSED deliveries are deliberately not swept, and RETRYING deliveries are owned by BullMQ's delayed jobs.
How the idempotency pieces fit together
There are four different IDs doing four different jobs:
| Layer | Mechanism | Effect |
|---|---|---|
| Client to API | Idempotency-Key header (or idempotencyKey field) | A repeat within 24 hours returns 200 with the original event instead of 202; backed by a PostgreSQL unique constraint, so it survives a Redis flush |
| API and sweeper to queue | BullMQ jobId = delivery.id | Enqueueing the same delivery twice is a no-op |
| Replay | New job ${delivery.id}-replay-<uuid> | Removes the old job, resets the row to PENDING, and sets attempts to attemptCount + maxAttempts for a fresh budget |
| KestrelMQ to receiver | X-KestrelMQ-Delivery-Id header | Stable across retries and replays; deduplicate on this |
The replay gets a new job ID because BullMQ ignores an add whose ID already exists: reusing jobId = delivery.id would be silently dropped. The delivery ID itself never changes, so receivers still deduplicate correctly.
The retry flow
Transient failures retry with exponential backoff and ±10% jitter. The full curve is 10s, 1m, 5m, 30m, 2h; with the default budget of five attempts, the first four tiers are used (scale them with BACKOFF_SCALE_FACTOR).
| Attempt | Delay before next try | Status on failure |
|---|---|---|
| 1 (initial) | 10s | RETRYING |
| 2 | 1m | RETRYING |
| 3 | 5m | RETRYING |
| 4 | 30m | RETRYING |
| 5 | exhausted | FAILED + deliveries-dlq |
A failed delivery can be replayed with POST /v1/deliveries/:id/replay, or by an agent through the MCP replay_delivery tool.
Why the guarantee is "at least once"
Consider a receiver that processes the webhook and then takes 11 seconds to respond. KestrelMQ's 10-second timeout fires, the attempt is recorded as failed, and a retry follows. The receiver sees the event twice: the sender cannot distinguish "never arrived" from "arrived but the ack was lost". So:
- Verify the HMAC signature on every request (zero-downtime secret rotation).
- Deduplicate on
X-KestrelMQ-Delivery-Idbefore side effects.X-KestrelMQ-Event-Idis shared by every delivery fanned out from one event. - Respond
2xxquickly and process asynchronously.
Next step
Run the five commands above on a local stack and watch a wiped queue heal itself. Every attempt, status code and nextRetryAt is visible through GET /v1/deliveries/:id or the MCP inspect_delivery tool. Then harden the receiving side with the signature verification guide.
FAQ
Does KestrelMQ provide exactly-once webhook delivery?
No. KestrelMQ guarantees at-least-once delivery. Consumers may occasionally receive the same event twice, for example after a timeout where the request actually succeeded, so receivers should deduplicate on X-KestrelMQ-Delivery-Id.
What happens if Redis loses a queued job?
Every delivery is first persisted in PostgreSQL. A repeatable outbox sweeper job (every 60 seconds) re-enqueues PENDING deliveries older than 30 seconds, using the delivery ID as the BullMQ job ID so jobs that still exist are ignored. A crash or Redis data loss between the commit and the enqueue does not lose deliveries.
What is the default retry schedule?
Five total attempts. Delays follow a 10 second, 1 minute, 5 minute, 30 minute (then 2 hour) curve with plus or minus 10 percent jitter, so the four retries between five attempts use the first four tiers. After exhaustion the delivery becomes FAILED and a job is added to the deliveries-dlq queue.
How do idempotency keys, job IDs and replays fit together?
The Idempotency-Key header deduplicates events at ingestion (200 instead of 202 on a repeat within 24 hours, backed by a unique constraint in PostgreSQL). The BullMQ job ID equals the delivery ID, so enqueueing the same delivery twice is a no-op. A replay removes the old job and enqueues a new one with the ID delivery-ID-replay-UUID and a fresh retry budget.
Run guaranteed webhook delivery on your own infrastructure
KestrelMQ is MIT-licensed and boots with a single Docker Compose file. Follow the quickstart or start in the hosted dashboard.