Webhook deliveries fail all the time: the customer’s server is down for maintenance, their database locks up, or they rate-limit you. Without a webhook retry system, those events are simply gone. This tutorial builds one in Node.js with BullMQ and Redis: deliveries are queued, failed ones retry with exponential backoff and jitter, and permanent failures land in a dead-letter list you can replay.
Quick answer: Do not send webhooks inside the request that triggers them. Add each delivery to a BullMQ queue, let a worker POST it, and when the POST fails BullMQ schedules a retry with a delay that doubles each time. After the last attempt, copy the job to a dead-letter list.
- Install
bullmq,ioredis,axiosandexpress, and start Redis. - Create a queue with
attemptsand an exponentialbackoff. - Write a worker that POSTs each payload and throws on any non-2xx response.
- Register a custom backoff strategy with jitter and a maximum delay.
- Push jobs that fail every attempt to a dead-letter list, and send a stable event ID so receivers can skip duplicates.
In this guide
- Before You Start
- What You Will Build
- Why a Simple Retry Loop Fails
- Step 1: Set Up the Project
- Step 2: Create the Webhook Queue
- Step 3: Write the Worker with a Custom Backoff
- Step 4: Build the Express Server and a Flaky Test Receiver
- Test It: Watch the Retries Back Off
- Step 5: Store Permanent Failures in a Dead-Letter List
- Prevent Duplicate Deliveries with an Event ID
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps

Before You Start
- Node.js 18 or newer (a current LTS release is best).
- A running Redis server. On a Mac,
brew install redisand thenbrew services start redisis the easiest route. With Docker:docker run -d --name redis-webhooks -p 127.0.0.1:6379:6379 redis. - Two terminal windows: one for the server, one for curl. The tutorial takes about 30 minutes.
- Test URLs only. The demo sender will POST to any URL you give it, so do not expose it to the internet as written.
What You Will Build
.env– the port and Redis connection settings.queue.js– the Redis connection and thewebhookQueuewith default retry settings.worker.js– sends each webhook, applies the custom backoff and writes permanent failures to a dead-letter list.server.js– an API to queue webhooks, plus a mock receiver that fails 80% of the time.
Why a Simple Retry Loop Fails
The usual first attempt is a try/catch that retries three times, one second apart. That is useless when the customer’s API is down for ten minutes: all three retries fail within three seconds. Worse, when their server comes back, every sender’s backlog of instant retries hits it at once, like a self-inflicted denial-of-service attack.
The fix is an asynchronous queue:
- When an event happens, push it to the queue and immediately return 202 Accepted.
- A background worker makes the actual HTTP POST.
- If the POST fails, the worker schedules a retry with exponential backoff, for example after 1, 2, 4 and 8 seconds.
This tutorial uses Redis and BullMQ for the queue. Your API stays fast, and jobs survive a restart of your own server because they live in Redis.
Step 1: Set Up the Project
You need Express for the test server, Axios to send the webhooks, BullMQ for the queue and dotenv for settings. Run this in your terminal:
mkdir webhook-retry-system
cd webhook-retry-system
npm init -y
npm install express bullmq ioredis axios dotenvNext, create a .env file in the project folder with the port and the Redis connection settings:
PORT=3000
REDIS_HOST=127.0.0.1
REDIS_PORT=6379Step 2: Create the Webhook Queue
Keeping the queue configuration separate from the Express routes keeps both files short. Create a file named queue.js. It sets up the Redis connection and exports the queue:
const { Queue } = require('bullmq');
const IORedis = require('ioredis');
require('dotenv').config();
const connection = new IORedis({
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || 6379,
maxRetriesPerRequest: null,
});
const webhookQueue = new Queue('webhookQueue', {
connection,
defaultJobOptions: {
attempts: 5,
backoff: {
type: 'exponential',
delay: 2000, // Initial delay of 2 seconds
},
removeOnComplete: true,
removeOnFail: false,
},
});
module.exports = { webhookQueue, connection };These defaults tell BullMQ to try each job up to 5 times with exponential backoff starting at 2,000 ms. After a failure BullMQ waits 2 seconds before the first retry, 4 seconds before the second, 8 seconds before the third, and so on. removeOnFail: false keeps permanently failed jobs in Redis so you can inspect them. The server in Step 4 overrides the backoff for each job with the custom strategy from Step 3.
Step 3: Write the Worker with a Custom Backoff
The built-in backoff is fine for many cases, but two extra rules help in production:
- A maximum delay, here 1 hour, so retries do not stretch out over days.
- Jitter, a small random amount added to each delay, so hundreds of failed jobs do not all retry in the same millisecond (the “thundering herd” problem).
Create a file named worker.js. It registers the custom backoff strategy and sends each webhook:
const { Worker } = require('bullmq');
const axios = require('axios');
const { connection } = require('./queue');
const customBackoffStrategy = (attemptsMade, type, err, job) => {
if (type !== 'customExponential') {
return 1000;
}
const initialDelay = 1000; // 1 second
const maxDelay = 3600000; // 1 hour
// Calculate delay: initialDelay * 2^(attemptsMade - 1)
let delay = initialDelay * Math.pow(2, attemptsMade - 1);
// Add some jitter (randomness between 0 and 500ms) to avoid synchronized retries
const jitter = Math.floor(Math.random() * 500);
delay = Math.min(delay + jitter, maxDelay);
return delay;
};
const worker = new Worker('webhookQueue', async (job) => {
const { url, payload, headers } = job.data;
console.log(`[Job ${job.id}] Attempting to send webhook to ${url} (Attempt ${job.attemptsMade + 1})`);
await axios.post(url, payload, {
headers: {
'Content-Type': 'application/json',
'X-Webhook-Event-Id': job.id, // Same ID on every retry, so the receiver can deduplicate
...headers,
},
timeout: 5000, // Timeout after 5 seconds
});
console.log(`[Job ${job.id}] Webhook delivered successfully!`);
}, {
connection,
settings: {
// BullMQ calls this single function with the backoff type set on the job
backoffStrategy: customBackoffStrategy,
},
});
worker.on('failed', (job, err) => {
if (job.attemptsMade >= job.opts.attempts) {
console.error(`[Job ${job.id}] Permanently failed after ${job.attemptsMade} attempts. Error: ${err.message}`);
} else {
console.warn(`[Job ${job.id}] Failed attempt. Retrying in background... Error: ${err.message}`);
}
});
worker.on('error', (err) => {
console.error('Worker error:', err.message);
});
module.exports = worker;Axios throws for any non-2xx response, and BullMQ treats a thrown error as a failed attempt. It then calls the backoff strategy with the job’s backoff type (customExponential), gets the next delay with jitter added, and schedules the job to run again. Every attempt carries the same X-Webhook-Event-Id header, so the receiver can recognise a repeat.
Step 4: Build the Express Server and a Flaky Test Receiver
Now you need an endpoint that accepts webhook requests and puts them on the queue. To test retries without waiting for a real server to crash, the same app also has a mock receiver that fails at random.
Create a file named server.js. It loads the worker, so one process runs both the API and the background sender:
const express = require('express');
const { webhookQueue } = require('./queue');
require('./worker'); // Start the worker background process
const app = express();
app.use(express.json());
// Endpoint to enqueue a new webhook dispatch
app.post('/api/send-webhook', async (req, res) => {
const { url, payload } = req.body || {};
if (!url || !payload) {
return res.status(400).json({ error: 'Missing url or payload' });
}
try {
const job = await webhookQueue.add('sendWebhook', { url, payload }, {
attempts: 5,
backoff: { type: 'customExponential' },
});
return res.status(202).json({
message: 'Webhook accepted and queued',
jobId: job.id
});
} catch (error) {
console.error('Failed to queue webhook job:', error);
return res.status(500).json({ error: 'Internal server error' });
}
});
// A mock endpoint that fails 80% of the time to test our retry system
app.post('/mock-receiver', (req, res) => {
const shouldFail = Math.random() < 0.8;
if (shouldFail) {
console.log('--- Mock Receiver: Simulating 500 Internal Server Error ---');
return res.status(500).json({ error: 'Simulated failure' });
}
console.log('--- Mock Receiver: Success! 200 OK received ---');
return res.status(200).json({ received: true });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});The server has two endpoints:
POST /api/send-webhookis what your app calls to send a webhook. It takes the target URL and payload, adds them to BullMQ and returns 202 Accepted straight away.POST /mock-receiversimulates a flaky third-party API that fails 80% of the time, so you can watch retries happen.
Keep /api/send-webhook internal. As written it will POST to any URL the caller supplies, so in a real system look the destination up from your own subscription records instead of accepting it in the request.
Test It: Watch the Retries Back Off
Start the server in your first terminal:
node server.jsYou should see Server running on port 3000. In a second terminal, queue a webhook that targets the flaky mock receiver:
curl -X POST http://localhost:3000/api/send-webhook -H "Content-Type: application/json" -d '{"url": "http://localhost:3000/mock-receiver", "payload": {"event": "order.created", "id": 99283}}'curl returns straight away with {"message":"Webhook accepted and queued","jobId":"1"} (the job ID increases with each test). The server terminal then shows the attempts. Here is an example; your attempt numbers will differ because the receiver fails at random:
Server running on port 3000
[Job 1] Attempting to send webhook to http://localhost:3000/mock-receiver (Attempt 1)
--- Mock Receiver: Simulating 500 Internal Server Error ---
[Job 1] Failed attempt. Retrying in background... Error: Request failed with status code 500
[Job 1] Attempting to send webhook to http://localhost:3000/mock-receiver (Attempt 2)
--- Mock Receiver: Simulating 500 Internal Server Error ---
[Job 1] Failed attempt. Retrying in background... Error: Request failed with status code 500
[Job 1] Attempting to send webhook to http://localhost:3000/mock-receiver (Attempt 3)
--- Mock Receiver: Simulating 500 Internal Server Error ---
[Job 1] Failed attempt. Retrying in background... Error: Request failed with status code 500
[Job 1] Attempting to send webhook to http://localhost:3000/mock-receiver (Attempt 4)
--- Mock Receiver: Success! 200 OK received ---
[Job 1] Webhook delivered successfully!Watch the pauses between attempts. They roughly double after each failure (about 1, 2, then 4 seconds, plus jitter), which gives a recovering server room to breathe. If all 5 attempts fail, you will see Permanently failed after 5 attempts instead; send the curl command again to try another job.
Step 5: Store Permanent Failures in a Dead-Letter List
When all 5 attempts fail, BullMQ moves the job to its failed set. Because removeOnFail is false it stays in Redis, but nothing looks at it unless you do. In production you want a dead-letter queue (DLQ), a separate place for permanent failures, so you can review or replay them later.
Add this code to the bottom of worker.js, after the worker is created. It listens for failed jobs and pushes the final failures to a Redis list:
const IORedis = require('ioredis');
const dlqConnection = new IORedis({
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || 6379
});
worker.on('failed', async (job, err) => {
if (job.attemptsMade >= job.opts.attempts) {
const deadPayload = {
jobId: job.id,
url: job.data.url,
payload: job.data.payload,
failedAt: new Date().toISOString(),
error: err.message,
};
try {
// Push the failed payload to a Redis list named 'webhook:dlq'
await dlqConnection.rpush('webhook:dlq', JSON.stringify(deadPayload));
console.error(`[DLQ] Job ${job.id} moved to Dead Letter Queue.`);
} catch (dlqError) {
console.error(`[DLQ] Could not store job ${job.id}:`, dlqError.message);
}
}
});Send a few test webhooks until one fails all 5 attempts, then read the list from your terminal:
redis-cli lrange webhook:dlq 0 -1If Redis runs in Docker, put docker exec redis-webhooks in front of the command. Each entry is the JSON object the code stored: job ID, URL, payload, time of failure and the last error. When the customer fixes their server, a small script or admin page can read this list and queue the payloads again.
Prevent Duplicate Deliveries with an Event ID
Sometimes the receiving server processes your webhook but times out before sending its 200 OK. Your worker then retries, and the receiver gets the same event twice. That is why the worker sends the BullMQ job ID as X-Webhook-Event-Id, and it stays the same across retries. The receiver should store each ID, for example in Redis, and skip any ID it has already processed.
Receivers also need to know the webhook really came from you. Sign each payload with a shared secret and send the signature in a header; the tutorial on how to verify webhook signatures with HMAC in Node.js shows both sides of that check.
If It Still Doesn’t Work
ECONNREFUSED 127.0.0.1:6379: Redis is not running. Start it withbrew services start redisordocker start redis-webhooks.- A job is tried only once: it was added without
attempts. Passattemptswhen you add the job, as the server does. - Every retry waits exactly 1 second: the job’s backoff type does not match. The server adds jobs with
backoff: { type: 'customExponential' }, which must match the name the strategy checks; any other type falls back to 1,000 ms. - curl returns 400
Missing url or payload: the body was not parsed. Keep the-H "Content-Type: application/json"header in the curl command. EADDRINUSEon port 3000: another process already uses the port. Stop it or changePORTin.env.- Nothing appears in
webhook:dlq: no job has failed all 5 attempts yet. With an 80% failure rate, roughly one test in three ends in the dead-letter list.
Frequently Asked Questions
Why not just use setTimeout for retries?
Because a pending setTimeout disappears if your Node.js process crashes or restarts. With BullMQ, scheduled retries live in Redis, outside your process, so they survive an app crash or a deploy. Enable Redis persistence (AOF) if they also need to survive a Redis restart.
How many times should I retry a webhook?
Enough attempts to outlast a realistic outage, which usually means hours rather than seconds. The demo values are short so you can watch them: 5 attempts doubling from 1 second cover only about 15 seconds. Starting at 30 seconds with 10 attempts and the 1-hour cap spreads retries over roughly three hours.
How do I handle rate limits on the receiver’s end?
Treat a 429 Too Many Requests response as a signal to slow down. Read the Retry-After header and use it as the next delay instead of your own backoff. For heavy outgoing traffic, see the guide on how to handle external API rate limits with BullMQ and Redis.
Should I encrypt webhook payloads stored in Redis?
Yes, if they contain sensitive data such as personal details or payment information. Encrypt the payload before you add it to the queue, and decrypt it inside the worker right before sending. Anyone with access to Redis can otherwise read every queued and dead-lettered payload.
Next Steps
You now have a webhook sender that retries with backoff and jitter, caps the delay and keeps permanent failures for replay. Raise the initial delay and attempt count for production, add signing, and replace the open url field with your own subscription lookup. To test against a real receiver on your laptop, expose it with the guide to testing webhooks locally with Cloudflare Tunnels.

