← Back to Node.js, page 10

nodejs-0200 · Hard senior

How would you design a reliable webhook delivery system in Node.js, covering signing, retries, idempotency, ordering and what the receiver must do?

Write events to a durable store, deliver them from a queue with workers, sign each request (HMAC over a timestamp and the body), and retry with exponential backoff and jitter until a limit, then park them in a dead letter list. Delivery is at least once, so every event has an id that the receiver uses to deduplicate. Receivers verify the signature with a constant-time comparison, check the timestamp, answer quickly with 2xx and process in the background.

Full answer

Sender side

  1. Durable first: save the event (id, type, payload, endpoint, status) in the database in the same transaction as the business change (the outbox pattern). A separate worker reads the outbox and enqueues delivery jobs (BullMQ, SQS). This avoids losing events when the process crashes.
  2. Delivery worker: POST with a short timeout (5 to 10 seconds), headers for event id, timestamp and signature. Success means a 2xx status. Treat 5xx, 429 and network errors as retryable. 4xx (except 408 and 429) is usually permanent, but many senders retry a few times anyway.
  3. Retries: exponential backoff with jitter (for example 1 minute, 5 minutes, 30 minutes, 2 hours, up to a day or more). After the maximum attempts, move to a dead letter state, alert the customer, and offer manual replay. Disable endpoints that fail for days.
  4. Security: sign with HMAC-SHA256 using a per-endpoint secret over timestamp + '.' + raw body. Allow secret rotation (two valid secrets). Block requests to private IP ranges to prevent SSRF, use HTTPS only, and do not follow redirects blindly.
  5. Fairness: one slow customer must not block others. Use a queue per endpoint or per customer, concurrency limits and rate limits.
  6. Ordering: at-least-once delivery with retries does not keep order. Give each event a sequence number or timestamp and tell receivers to treat events as hints, or fetch the current resource state from your API.
  7. Observability: a delivery log with attempts, status codes and latency, and a replay button.

Receiver side

  • Read the raw body (before JSON parsing), verify the signature with crypto.timingSafeEqual, reject old timestamps (for example older than 5 minutes) to stop replays, answer 2xx fast, enqueue the work, and deduplicate by event id (a unique key in the database).
javascript
const crypto = require('node:crypto');

const sign = (secret, timestamp, body) => crypto.createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');

function verify({ secret, header, body, now, toleranceSeconds = 300 }) {
  const [t, v1] = header.split(',').map((part) => part.split('=')[1]);
  if (Math.abs(now - Number(t)) > toleranceSeconds) return 'rejected: timestamp too old';
  const expected = Buffer.from(sign(secret, t, body), 'hex');
  const received = Buffer.from(v1, 'hex');
  return expected.length === received.length && crypto.timingSafeEqual(expected, received) ? 'accepted' : 'rejected: bad signature';
}

// Backoff with full jitter. The random function is injected, so the output is stable.
const delaySeconds = (attempt, random = Math.random, base = 60, cap = 6 * 3600) => Math.floor(random() * Math.min(cap, base * 2 ** (attempt - 1)));

const secret = 'whsec_demo_secret';
const event = { id: 'evt_1001', type: 'course.completed', data: { student: 'Asha' } };
const body = JSON.stringify(event);
const t = 1_800_000_000;
const header = `t=${t},v1=${sign(secret, t, body)}`;

console.log('valid delivery        :', verify({ secret, header, body, now: t + 5 }));
console.log('tampered body         :', verify({ secret, header, body: body.replace('Asha', 'Ravi'), now: t + 5 }));
console.log('wrong secret          :', verify({ secret: 'other', header, body, now: t + 5 }));
console.log('replay after 10 min   :', verify({ secret, header, body, now: t + 600 }));
console.log('max backoff per attempt (seconds):', [1, 2, 3, 4, 5, 6, 7, 8].map((n) => delaySeconds(n, () => 0.999999)).join(', '));
console.log('with random = 0.5     :', [1, 2, 3, 4, 5].map((n) => delaySeconds(n, () => 0.5)).join(', '));

// The receiver deduplicates by event id.
const processed = new Set();
const receive = (evt) => (processed.has(evt.id) ? 'duplicate ignored' : (processed.add(evt.id), 'processed'));
console.log('same event delivered twice:', receive(event), '|', receive(event));

The signing, verification, replay window and backoff numbers are run here. The queue, the outbox table and the network delivery are described in the text and were not built or run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid delivery : accepted tampered body : rejected: bad signature wrong secret : rejected: bad signature replay after 10 min : rejected: timestamp too old max backoff per attempt (seconds): 59, 119, 239, 479, 959, 1919, 3839, 7679 with random = 0.5 : 30, 60, 120, 240, 480 same event delivered twice: processed | duplicate ignored

Key points

  • Store events durably (outbox) and deliver from a queue.
  • Sign timestamp plus raw body with HMAC and compare in constant time.
  • Retry with backoff and jitter, then dead letter and replay.
  • Delivery is at least once and unordered, so receivers must deduplicate.
  • Isolate customers and protect against SSRF.

Common mistakes

  • Verifying the signature over parsed JSON instead of the raw body.
  • Comparing signatures with === (timing leak).
  • Doing slow work before answering 2xx, so the sender retries.
  • Retrying immediately and flooding a failing endpoint.
  • Assuming events arrive once and in order.

Follow-ups

  • How would you rotate a signing secret without downtime?
  • How do you prevent SSRF in a webhook sender?
  • What would a replay endpoint need to be safe?

Tips

  • Cover sender and receiver separately.
  • Say 'at least once, so deduplicate'.
  • Mention outbox, signing, backoff and dead letters.