Lesson 204 of 296
Background jobs: queues, retries, dead-letter and outbox
What you will learn
- Why some work should not run inside a request
- Queues, producers and workers
- Retries with exponential backoff and jitter
- Dead-letter queues
- Delivery guarantees
- The dual-write problem and the transactional outbox pattern
- Scheduled jobs
On this page
Why background jobs?
Some work is slow or unreliable: sending emails, generating PDFs, resizing images, calling third-party APIs, importing a large CSV. Doing it inside the HTTP request makes the user wait, risks timeouts, and if the third party is down, the whole request fails.
Instead: the request puts a job on a queue and responds quickly (often 202 Accepted with a job ID). Separate worker processes take jobs from the queue and do the work.
Client → API: POST /reports → API adds job to queue → 202 Accepted { jobId }
↓
Worker takes job → builds report → saves to S3 → marks job done
Client → GET /reports/jobs/{jobId} → { status: "done", url }Benefits: fast responses, retries when something fails, smoothing traffic spikes (the queue absorbs bursts; workers process at their own pace), and scaling workers separately from the API.
Tools
| Tool | Notes |
|---|---|
| BullMQ | Popular Node.js queue on Redis: retries, delays, priorities, scheduled and repeatable jobs, rate limiting. NestJS has a module for it |
| AWS SQS | Managed queue service (Lesson 256) |
| RabbitMQ | A message broker with flexible routing |
| Kafka | A distributed log for very high-volume event streaming (Lesson 236) |
| pg-boss, Graphile Worker | Queues stored in PostgreSQL: one less system to run |
A BullMQ example:
import { Queue, Worker } from "bullmq";
const connection = { host: "localhost", port: 6379 };
type WelcomeEmailJob = { userId: string; email: string };
export const emailQueue = new Queue<WelcomeEmailJob>("emails", { connection });
export async function enqueueWelcomeEmail(userId: string, email: string) {
await emailQueue.add("welcome", { userId, email }, {
jobId: `welcome-${userId}`,
attempts: 5,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: 1000,
removeOnFail: false
});
}
declare function sendEmail(to: string, template: string): Promise<void>;
export function startEmailWorker() {
return new Worker<WelcomeEmailJob>(
"emails",
async (job) => {
await sendEmail(job.data.email, "welcome");
},
{ connection, concurrency: 10 }
);
}jobIdmakes enqueueing idempotent: adding the same welcome job twice does not create two jobs.attemptsandbackoffretry failures: 2 s, 4 s, 8 s, 16 s...concurrency: 10lets one worker process run 10 jobs at the same time (useful for I/O-bound work).
Retries with exponential backoff and jitter
When a call fails because of a temporary problem (timeout, 503, rate limit), retry, but:
- Exponential backoff: wait longer each time (1 s, 2 s, 4 s, 8 s...), so a struggling service gets time to recover.
- Jitter: add randomness to each wait. Without it, thousands of clients that failed together retry at exactly the same moments, hitting the service in waves (the thundering herd).
- Limit the number of attempts.
- Retry only retryable errors: timeouts, 429, 502, 503, 504. Do not retry 400 or 422: the same input fails the same way.
- Retried operations must be idempotent (Lesson 195).
export function backoffDelay(attempt: number, baseMs = 500, maxMs = 30_000, random: () => number = Math.random): number {
const exponential = Math.min(maxMs, baseMs * 2 ** attempt);
return Math.round(random() * exponential);
}
type RetryOptions = {
attempts?: number;
isRetryable?: (err: unknown) => boolean;
sleep?: (ms: number) => Promise<void>;
};
export async function retry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
const {
attempts = 5,
isRetryable = () => true,
sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
} = options;
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt++) {
try {
return await fn();
} catch (err) {
lastError = err;
if (!isRetryable(err) || attempt === attempts - 1) break;
await sleep(backoffDelay(attempt));
}
}
throw lastError;
}This "full jitter" approach picks a random delay between 0 and the exponential cap, a strategy described by AWS. Note the separate RetryOptions type: without it, TypeScript infers the default () => true as a function that can only return true, and callers could not pass a rule that returns false. Passing sleep in also makes the function easy to test without real waiting.
Dead-letter queues
A job that fails every attempt (a bug, bad data, a permanently invalid email address) must not retry forever or be silently lost. It is moved to a dead-letter queue (DLQ): a separate place for failed messages. Then:
- Alert when the DLQ is not empty.
- Inspect, fix the bug or data, and redrive (re-queue) the messages.
A "poison message" that crashes the worker every time is exactly what a DLQ catches.
Delivery guarantees
| Guarantee | Meaning | Reality |
|---|---|---|
| At most once | May be lost, never duplicated | Simple, rarely acceptable |
| At least once | Never lost, may be duplicated | What most queues give you (SQS standard, BullMQ, RabbitMQ with acknowledgements) |
| Exactly once | Never lost, never duplicated | Very hard across systems; in practice: at-least-once delivery + idempotent consumers = exactly-once effect |
Duplicates happen because a worker can finish the work but crash before acknowledging it; the queue then delivers it again. So consumers must be idempotent (Lesson 195).
The dual-write problem
A common bug:
await db.order.create(order); step 1: saved
await queue.publish("OrderPlaced"); step 2: the process crashes hereThe order exists but no event was published, so no confirmation email, no stock update. Reversing the steps is not better (an event for an order that was never saved). You cannot have a transaction across a database and a message broker. This is the dual-write problem.
The transactional outbox pattern
- In the same database transaction as the business change, insert the event into an outbox table:
BEGIN;
INSERT INTO orders (...) VALUES (...);
INSERT INTO outbox (id, type, payload, created_at) VALUES (uuid, 'OrderPlaced', '{...}', now());
COMMIT;Both are saved, or neither is.
- A separate relay process reads unpublished outbox rows, publishes them to the queue, and marks them as sent (or a change data capture tool such as Debezium reads the database log and publishes them).
- If the relay crashes after publishing but before marking a row as sent, the event is published again: at-least-once again, so consumers stay idempotent.
The outbox pattern is a favourite senior interview topic because it shows you understand failure between systems.
Scheduled jobs
Recurring work (nightly reports, cleaning expired sessions, sending reminders) uses cron-style schedules: BullMQ repeatable jobs, a cloud scheduler (EventBridge Scheduler, Lesson 256) or Kubernetes CronJobs. With several app instances, make sure the job runs once, not once per instance (use the queue's scheduler or a lock).
How to say it in an interview
"Slow or unreliable work like emails, PDFs and third-party calls goes to a queue: the API enqueues a job and returns 202, and separate workers process it, which gives fast responses, retries, load smoothing and independent scaling. I retry only transient errors, with exponential backoff and jitter and a maximum number of attempts, and failed jobs go to a dead-letter queue with alerts and redrive. Most queues are at-least-once, so consumers are idempotent. To avoid the dual-write problem between the database and the broker, I use the transactional outbox: write the event in the same transaction and let a relay or change data capture publish it."
Key words
| Word | Meaning |
|---|---|
| Queue | A list of jobs or messages waiting to be processed |
| Worker | A process that takes jobs from a queue and runs them |
| Exponential backoff | Waiting longer between each retry |
| Jitter | Random variation in retry delays |
| Thundering herd | Many clients retrying at the same moment |
| Dead-letter queue | Where messages go after failing every retry |
| At-least-once | Messages may be delivered more than once |
| Dual-write problem | Updating two systems without a shared transaction |
| Transactional outbox | Saving events in the same DB transaction, publishing them later |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.