How to Build a Job Queue with Backoff and Dead Letters
Design a durable job queue with atomic claiming, exponential backoff with jitter, maximum attempts, and a dead-letter path that keeps failures inspectable.
On this page
Introduction
A job queue decouples work that must happen from the request that triggers it. An HTTP handler enqueues a job and returns quickly; a pool of workers picks up jobs and does the slow, retryable, or rate-limited work — sending email, generating a report, syncing a third party. The value comes from the properties of the queue: durability so a crash does not lose work, retries with backoff so transient failures recover, and a dead-letter path so permanent failures are visible instead of silent.
This tutorial builds a durable job queue with TypeScript and SQL. It covers the job lifecycle, atomic claiming with a visibility timeout, exponential backoff with jitter, retry caps and dead-lettering, crash recovery, monitoring, and the tests that prove a job is processed exactly once and dead-lettered after the cap. The patterns map directly to SQS, Redis-backed queues, and Postgres-as-a-queue designs.
Model the job lifecycle
Give every job an explicit state machine. A job is pending when it is ready to run, running when a worker holds a lease on it, and terminal when it has succeeded or been dead-lettered. Alongside the state, store the attempt count, the scheduled run time, a lease expiry, and the last error. The attempt count is what makes retries bounded; without it, a permanently failing job retries forever and pins a worker.
The queue is the set of pending jobs ordered by their scheduled run time, not by insertion time, because backoff moves a retried job into the future. Terminal jobs leave the queue and, on failure, enter the dead-letter store. Model the lifecycle so the happy path, the retry path, and the give-up path are all representable without special cases in the worker.
Enqueue atomically
Enqueue the job in the same transaction as the state change that justifies it. If an order is created and the confirmation email is enqueued as a separate operation, a crash between them either sends no email or sends two. The transactional outbox pattern fixes this: write the job row in the same database transaction as the business row, then a separate process publishes pending jobs to the queue. For a queue that lives in the same database, the insert itself is the outbox.
-- Jobs table: the queue is a query over this table ordered by run_at.
CREATE TABLE jobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
kind text NOT NULL,
payload jsonb NOT NULL,
state text NOT NULL DEFAULT 'pending', -- pending|running|succeeded|dead
attempts integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL DEFAULT 5,
run_at timestamptz NOT NULL DEFAULT now(),
locked_until timestamptz,
locked_by text,
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX jobs_ready_idx ON jobs (run_at) WHERE state = 'pending';
Claim jobs atomically
A worker must claim a job in one operation so two workers cannot pick up the same row. The classic race is select-then-update: two workers both SELECT the same pending job and both process it. Avoid it with a single atomic statement that selects and marks the row in one step. In PostgreSQL, SELECT ... FOR UPDATE SKIP LOCKED lets a worker take the next unlocked job and lets other workers skip it immediately instead of blocking.
-- Claim one job atomically: lock the row, mark it running, set a lease.
UPDATE jobs
SET state = 'running',
attempts = attempts + 1,
locked_by = $1,
locked_until = now() + interval '60 seconds'
WHERE id = (
SELECT id FROM jobs
WHERE state = 'pending' AND run_at <= now()
ORDER BY run_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, kind, payload, attempts;
The locked_until value is the visibility timeout: the worker holds the job until it finishes or the lease expires. A long job must renew the lease periodically, or set it generously from the start. When the lease expires, the job is eligible again, which is how a crashed worker’s job is reclaimed.
Retry with exponential backoff and jitter
On a transient failure, reschedule rather than fail. Exponential backoff grows the delay with each attempt — base * 2^attempt — so a struggling dependency gets breathing room instead of a hammering. Pure exponential backoff is a trap under fleet-wide failure: every worker that failed at the same instant retries at the same later instant, re-creating the burst. Add jitter.
/** Full jitter: delay is uniform in [0, min(cap, base * 2^attempt)]. */
function nextDelayMs(attempt: number, base = 1_000, cap = 300_000): number {
const exponential = Math.min(cap, base * 2 ** attempt);
return Math.floor(Math.random() * exponential);
}
/** Schedule the retry without losing the attempt count. */
function backoffUpdate(attempt: number): { delayMs: number; retryAt: Date } {
const delayMs = nextDelayMs(attempt);
return { delayMs, retryAt: new Date(Date.now() + delayMs) };
}
On failure, set state = 'pending', run_at = now() + delay, and keep the incremented attempt count. Distinguish transient errors (timeouts, connection resets, 5xx, 429 with a Retry-After) from permanent ones (validation errors, 4xx, a malformed payload). Retry the transient, and dead-letter the permanent immediately; a validation bug that retries five times only delays the inevitable failure and wastes worker capacity.
Dead-letter after the attempt cap
When a job reaches max_attempts, stop retrying and move it to a dead-letter state, preserving the payload and the last error. Dead-lettering is not deletion: the record stays so an operator can inspect why it failed, fix the root cause, and requeue it. Alert when the dead-letter count crosses a threshold or grows at a sustained rate, because that is a real bug or a dependency that will not recover.
async function onFailure(job: Job, err: Error): Promise<void> {
if (isPermanent(err) || job.attempts >= job.maxAttempts) {
await db.markDead(job.id, err.message); // preserves attempts and last_error
await metrics.increment('jobs.dead', { kind: job.kind });
return;
}
const { retryAt } = backoffUpdate(job.attempts);
await db.reschedule(job.id, retryAt, err.message);
}
Provide a requeue operation that resets attempts to zero and moves a dead job back to pending, so recovering a batch after a fix is one command. Without it, dead-lettered jobs accumulate and nobody dares touch them.
Recover from crashes and stuck jobs
A worker that crashes mid-job never reschedules it, so the job sits in running until its lease expires. A sweeper must return expired leases to pending so another worker can try. Run the sweeper periodically (every few seconds), and make it safe under concurrency by updating only rows whose lease has actually expired.
-- Reclaim jobs whose worker died: the lease expired while still running.
UPDATE jobs
SET state = 'pending', locked_by = NULL, locked_until = NULL,
last_error = COALESCE(last_error, 'lease_expired')
WHERE state = 'running' AND locked_until < now();
Make the handler idempotent, because at-least-once delivery means a job can run twice: once before a crash and once after the lease expires. Write idempotency keys or guard on the terminal state so a re-run is a no-op. Never assume exactly-once execution from the queue; guarantee it with an idempotency check in the handler.
Monitor queue depth and age
The two metrics that matter are ready depth and the age of the oldest ready job. Depth tells you whether the workers are keeping up; age tells you whether the queue is actually draining, because a deep queue that drains in seconds is fine but one job that has waited an hour is a user-visible delay. Alert on oldest-ready age crossing an SLO, on dead-letter growth, and on the rate of lease expirations, which correlates with worker crashes. Emit per-kind depth so a single hot job type does not hide behind a healthy aggregate.
Testing retries and dead letters
Test the failure behavior, not only the success path. Assert that a job that throws once is rescheduled with a positive future run_at and its attempt count incremented, that a job that keeps failing is dead-lettered exactly at max_attempts, and that a lease-expired job is reclaimed. Use a fake clock so the backoff test does not sleep.
test('retries with backoff and dead-letters at the cap', async () => {
const clock = fakeClock();
await queue.enqueue({ kind: 'email', payload: {}, maxAttempts: 3 });
const alwaysFails = async () => { throw new Error('transient'); };
// Attempt 1 -> pending again, run_at in the future.
const first = await worker.runOnce(alwaysFails, clock.now());
expect(first.state).toBe('pending');
expect(first.attempts).toBe(1);
expect(first.runAt.getTime()).toBeGreaterThan(clock.now().getTime());
// Advance past each delay and fail until the cap.
for (let i = 2; i <= 3; i++) {
clock.advance(clock.msUntil(first.runAt));
await worker.runOnce(alwaysFails, clock.now());
}
const final = await queue.get(first.id);
expect(final.state).toBe('dead'); // exactly at max_attempts, not before
expect(final.attempts).toBe(3);
});
Add a concurrency test: enqueue one job, start several workers, and assert the handler ran once (plus any deliberate duplicate from a lease expiry). Assert the dead-letter record keeps the last error and the attempt count so it can be debugged.
Common pitfalls
- Select-then-update claiming. Two workers process the same job; use an atomic claim.
- No visibility timeout. A crashed worker locks a job forever, or two workers race.
- Retries without jitter. Synchronized retry storms re-overwhelm a recovering dependency.
- Unbounded retries. A permanently failing job pins a worker forever.
- Dead-letter deletes the payload. The failure history you need to debug is gone.
- Assuming exactly-once. At-least-once means the handler must be idempotent.
- No stuck-job sweeper. Lease-expired jobs never return to the ready set.
- No oldest-age metric. Queue depth alone hides a job that has waited for an hour.
Conclusion
A durable job queue is a state machine with an atomic claim, a bounded retry policy with jittered backoff, a dead-letter terminal state, and a sweeper that reclaims expired leases. Enqueue in the same transaction as the business change, claim with a lock that other workers can skip, retry transient errors with full jitter and no cap on total time but a hard cap on attempts, and preserve failed jobs for inspection. Make the handler idempotent, monitor depth and oldest age, and test the retry-to-dead-letter path with a fake clock. Do this and the queue turns unreliable work into a system that degrades predictably, retries honestly, and never loses a job.
Sources: AWS: Exponential Backoff and Jitter, AWS SQS: Dead-letter queues, BullMQ documentation.
FAQ
- Why is jitter necessary if I already use exponential backoff?
- Pure exponential backoff makes every failed worker retry at the same instant, producing synchronized bursts that re-overwhelm a recovering dependency. Jitter adds randomness to the delay so retries spread out. Full jitter, choosing a delay uniformly between zero and the exponential cap, is simple and avoids the thundering herd.
- When should a job go to the dead-letter queue?
- After a fixed maximum attempt count, when the error is permanent (a validation failure or a 4xx), or when the job exceeds a maximum age. Dead-lettering preserves the payload and the error history for inspection instead of dropping the job, and it lets you alert on a growing dead-letter depth as a signal of a real bug.
- What is a visibility timeout and why does it matter?
- When a worker claims a job it gets a lease for a fixed time. If the worker crashes, the lease expires and the job becomes visible again for another worker. Without it, a crashed worker leaves the job locked forever, or two workers process it at once. Set the lease longer than the expected processing time and renew it for long jobs.
Report a problem with this articleOpens a pre-filled issue on GitHub.