How to Implement a Task Queue
Build an in-process task queue: prioritise work, bound concurrency, retry with backoff, and survive a worker crash without losing tasks.
On this page
Introduction
A task queue accepts units of work, runs them with bounded concurrency, and retries the ones that fail. It decouples the arrival of work from its execution, so a burst is absorbed by the queue rather than spawning unbounded concurrent work. When the work must survive a process restart, the queue lives outside the process in a broker; when it does not, an in-process queue is simpler and has no external dependency.
This tutorial builds an in-process task queue: priorities, bounded concurrency, retry with backoff, and a dead-letter area for exhausted tasks. It covers when a durable queue is needed instead, and tests order, the concurrency cap, and retry behavior. The examples use an async queue, and the structure applies to a worker pool reading from a priority queue.
Define priorities and a stable order
If some tasks matter more, give them a higher priority so they are dequeued before lower-priority ones. Within a priority, keep a stable order, typically first-in-first-out, so the queue is deterministic and a test can assert the order. A priority queue ordered only by priority with no tie-break can reorder equal-priority tasks unpredictably, which makes behavior hard to reason about.
Do not overuse priorities. A few levels, such as high and default, cover most needs; a numeric priority on every task invites a maintenance problem where every producer picks a different value. If a task must not be starved by high-priority work, add aging or a separate queue so the low-priority work eventually runs.
interface Task {
id: string;
priority: number; // higher runs first
seq: number; // stable tie-break within a priority
run: () => Promise<void>;
attempts: number;
}
class TaskQueue {
private items: Task[] = [];
private running = 0;
constructor(private limit: number, private maxAttempts = 3) {}
push(task: Omit<Task, 'seq' | 'attempts'>) {
this.items.push({ ...task, seq: this.items.length, attempts: 0 });
this.items.sort((a, b) => b.priority - a.priority || a.seq - b.seq);
this.tick();
}
private tick() {
while (this.running < this.limit && this.items.length > 0) {
const task = this.items.shift()!;
this.running++;
task.run()
.catch(() => this.retry(task))
.finally(() => { this.running--; this.tick(); });
}
}
private retry(task: Task) {
task.attempts++;
if (task.attempts >= this.maxAttempts) return this.deadLetter(task);
const delay = Math.min(1000, 50 * 2 ** task.attempts) + Math.random() * 50;
setTimeout(() => { this.items.push(task); this.tick(); }, delay);
}
private deadLetter(task: Task) { /* record task.id with the failure reason */ }
}
Bound the concurrency and the queue
Run at most N tasks at once, chosen from the resource the tasks use, and bound the queue itself. An unbounded queue under a burst of submissions grows until memory is exhausted, so when it is full, apply backpressure: the submitter waits, or the queue rejects with a clear error. Bounding the concurrency protects the downstream; bounding the queue protects the process.
The two bounds serve different resources. The concurrency bound protects the thing the tasks call, such as a database or an API. The queue bound protects the memory of the process holding the pending tasks. Set both, and expose the queue depth and the running count as metrics, so saturation is visible before it becomes a failure.
Retry with backoff, then dead-letter
A failed task may succeed on a retry if the failure was transient, so retry it with exponential backoff and jitter, capped at a small number of attempts. The backoff spreads the retries so a downstream that failed does not get hammered by every task retrying at once. Cap the attempts, because a deterministic failure retries forever without making progress.
When a task exhausts its attempts, move it to a dead-letter area rather than dropping it. The dead-letter record carries the task’s identity, its payload if small, and the last failure reason, so an operator can inspect it, fix the cause, and replay it. A task that silently disappears on repeated failure is a data-loss bug that is hard to notice.
function backoffDelay(attempt, base = 50, cap = 5000) {
const exp = Math.min(cap, base * 2 ** attempt);
return Math.floor(exp / 2 + Math.random() * exp / 2); // full jitter
}
// on failure: attempts++ , if attempts < max -> setTimeout(retry, backoffDelay(attempts))
// else -> deadLetter(task)
Choose a durable queue when a crash must not lose work
An in-process queue loses its pending and in-flight tasks if the process crashes. That is acceptable for work the process can afford to repeat or lose. When the work must survive a restart, or must be processed by a different process, use a durable queue: a database table with a status column, or a message broker. The tasks are stored outside the process, so a crash resumes from the stored state.
A durable queue adds visibility and at-least-once delivery: a task may be processed more than once if a worker crashes after doing the work but before acknowledging, so the work must be idempotent or carry an idempotency key. An in-process queue with idempotent tasks can be simpler, but once durability or cross-process coordination is needed, the broker is the right tool.
Test order, cap, retry, and dead-letter
Test that a higher-priority task runs before a lower-priority one and that equal-priority tasks run in order. Test that the running count never exceeds N with more tasks than N. Test that a task failing twice and succeeding on the third is retried and completes, and that a task failing every time reaches the dead-letter after the cap. Test that the queue rejects or waits when full, applying backpressure.
node -e '
const q = new TaskQueue(2);
const order = [];
q.push({ priority: 0, run: async () => order.push("low") });
q.push({ priority: 10, run: async () => order.push("high") });
// assert order[0] === "high" and never more than 2 running
'
Common pitfalls
An unbounded queue that grows under a burst, no concurrency bound so a burst spawns unbounded work, a retry with no cap that loops forever on a deterministic failure, a task dropped on repeated failure with no dead-letter, and an in-process queue used where a crash must not lose work are the recurring mistakes. Bounded queues, a concurrency limit, capped backoff retries, a dead-letter area, and a durable queue when needed address them.
Conclusion
A task queue decouples work from its execution and controls the load. Prioritize with a stable tie-break, bound both the concurrency and the queue, retry with capped backoff, and dead-letter exhausted tasks, using a durable queue when a crash must not lose work. Self-check by asserting priority order, the concurrency cap, and the retry-then-dead-letter path. Then a burst is absorbed at a rate the system can take, and no failed task vanishes.
Sources: MDN: Microtasks and the event loop, Node.js: Escaping the async/await try/catch in worker queues, AWS: Dead-letter queues.
FAQ
- In-process queue or external broker?
- An in-process queue fits work the process can afford to lose on a crash and that does not need to survive a restart. For durable, cross-process work, use an external broker such as a durable database table or a message queue, so a crash does not lose the queue.
- What happens to a task that exhausts its retries?
- Move it to a dead-letter area: a separate list or table with the failure reason, so it is not silently dropped and can be inspected and replayed. A task that just disappears is a silent data loss.
Report a problem with this articleOpens a pre-filled issue on GitHub.