← Back to Node.js, page 8

nodejs-0147 · Hard senior

How do you design reliable background jobs: idempotency, retries, dead letters and graceful worker shutdown?

Queues give at-least-once delivery, so a job can run twice. Make each job idempotent (a job id or an idempotency record), retry transient errors with exponential backoff and jitter, stop retrying permanent errors, move jobs that run out of attempts to a dead letter queue for inspection, and shut workers down gracefully by letting the active job finish before the process exits.

Full answer

Delivery guarantees

  • Exactly-once processing across a network is not realistic. Queues choose at-least-once: a job is retried if a worker crashes or its lock expires (stalled job). So side effects (send an email, charge a card) must be safe to repeat.

Idempotency patterns

  • Deterministic job id: queue.add(name, data, { jobId: 'invoice-42' }). Adding the same id again is ignored while the job exists, which de-duplicates producers.
  • Processor side: record completed work in the database with a unique key (job id or business id) and skip if present. Use the same key as the idempotency key for payment APIs.
  • Make the effect itself idempotent: UPSERT, set state rather than increment.

Retries

  • Retry transient failures (timeouts, 429, 503) with exponential backoff and jitter, and a limited number of attempts.
  • Do not retry permanent failures (validation error, 404 for the target). In BullMQ throw UnrecoverableError to fail at once.
  • Respect external rate limits with queue rate limiting, and use timeouts inside the processor so a job cannot hang forever.

Dead letters

  • A job that has used all attempts goes to the failed set. Copy it (with the error and data) to a dead letter queue or an alert, so people can inspect, fix and replay it. Do not drop failures silently.

Graceful shutdown

  • On SIGTERM: stop taking new jobs and wait for active ones (worker.close() waits unless forced), then close the queue and Redis connections. Set the container's stop timeout longer than your longest job, or split long jobs into steps.
  • If a worker is killed, the lock expires and another worker picks the job up, which is why idempotency is needed.

Observability: log job id, attempt number and duration, and alert on failed counts, queue age and retry rates.

javascript
const { Queue, Worker, QueueEvents, UnrecoverableError } = require('bullmq');
const { setTimeout: sleep } = require('node:timers/promises');

const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const connection = { host: url.hostname, port: Number(url.port) };
const suffix = process.pid;

async function main() {
  const queue = new Queue(`work-${suffix}`, { connection });
  const dead = new Queue(`dead-${suffix}`, { connection });
  const events = new QueueEvents(`work-${suffix}`, { connection });
  await events.waitUntilReady();

  const charged = new Set();                       // our idempotency record
  let sideEffects = 0;
  const processor = async (job) => {
    if (job.name === 'charge') {
      if (charged.has(job.data.invoice)) return 'skipped (already charged)';
      sideEffects++;
      charged.add(job.data.invoice);
      await sleep(150);                            // a slow job, still running during shutdown
      return 'charged';
    }
    if (job.name === 'always-fails') throw new Error('upstream is down');
    if (job.name === 'bad-input') throw new UnrecoverableError('invalid card number');
  };
  const worker = new Worker(`work-${suffix}`, processor, { connection });

  // Jobs that used all their attempts, or failed with a permanent error, are copied to the dead letter queue.
  const toDeadLetter = async (job, err) => {
    const finished = err.name === 'UnrecoverableError' || job.attemptsMade >= (job.opts.attempts || 1);
    if (job && finished) await dead.add('dead', { original: job.name, error: err.message, attempts: job.attemptsMade });
  };
  worker.on('failed', toDeadLetter);

  // 1. Same jobId twice: only one job exists, so the invoice is charged once.
  const first = await queue.add('charge', { invoice: 'inv-42' }, { jobId: 'invoice-42' });
  await queue.add('charge', { invoice: 'inv-42' }, { jobId: 'invoice-42' });
  const counts = await queue.getJobCounts('waiting', 'active');
  console.log('1. jobs for jobId invoice-42 (queued twice):', counts.waiting + counts.active);

  // 2. Graceful shutdown while the job is active: close() waits for it.
  await sleep(50);
  console.log('2. state before close:', await first.getState());
  await worker.close();
  console.log('   state after close  :', await first.getState(), '| charges made:', sideEffects);

  // 3. A second worker: retries then dead letter, and an unrecoverable error.
  const worker2 = new Worker(`work-${suffix}`, processor, { connection });
  worker2.on('failed', toDeadLetter);
  const retry = await queue.add('always-fails', {}, { attempts: 3, backoff: { type: 'fixed', delay: 10 } });
  const bad = await queue.add('bad-input', {}, { attempts: 5 });
  await Promise.all([retry.waitUntilFinished(events).catch(() => {}), bad.waitUntilFinished(events).catch(() => {})]);
  await sleep(100);
  const deadJobs = (await dead.getJobs(['waiting'])).map((j) => `${j.data.original}: ${j.data.attempts} attempt(s), "${j.data.error}"`).sort();
  console.log('3. dead letter queue:', deadJobs.join(' | '));

  await worker2.close(); await events.close();
  await queue.obliterate({ force: true }); await dead.obliterate({ force: true });
  await queue.close(); await dead.close();
}
main();

The script shows de-duplication by jobId, a worker that finishes its active job during close(), and two kinds of failure that end in a dead letter queue: retries that run out, and an error that is not retried. It needs a running Redis server. Install first with npm install bullmq (run here with bullmq 6.7.12). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. jobs for jobId invoice-42 (queued twice): 1 2. state before close: active state after close : completed | charges made: 1 3. dead letter queue: always-fails: 3 attempt(s), "upstream is down" | bad-input: 1 attempt(s), "invalid card number"

Key points

  • Delivery is at least once, so side effects must be idempotent.
  • A deterministic jobId de-duplicates producers.
  • Retry transient errors with backoff; fail permanent ones at once.
  • Send exhausted jobs to a dead letter queue, not the void.
  • On shutdown let the active job finish before exiting.

Common mistakes

  • Assuming a job runs exactly once and charging twice.
  • Retrying permanent errors until attempts run out.
  • Dropping failed jobs with no record.
  • Stopping the process while a job is running, with no graceful close.
  • Using the same retry delay for all clients, which causes retry storms.

Follow-ups

  • How do you replay jobs from a dead letter queue safely?
  • What is a stalled job in BullMQ?
  • How does an idempotency key work with a payment provider?

Tips

  • Say 'at least once, so idempotent'.
  • Describe retries, dead letters and shutdown in that order.
  • Mention a deterministic job id.