1 min read·Run it here

Design a Job Queue

A small in-memory queue with generated IDs, claim/complete status transitions, retry budget, and priority with FIFO tie-breaking.

Pattern
FIFO queue -> status map -> retries
Time
O(n) claim
Space
O(n)

This is a product-platform classic: a small queue starts as FIFO, then turns into state transitions and retry policy.

The recipe

Say before you type: "The queue holds IDs. The map owns job state."

Use two structures:

private jobs = new Map<string, Job>();
private queue: string[] = [];

enqueue() creates an ID, stores the job as queued, and pushes the ID. claim() removes an ID from the waiting queue, marks that job running, increments attempts, and returns a copy of the job.

State transitions

Think in legal transitions:

queued -> running -> done
queued -> running -> queued
queued -> running -> failed

complete(id) only works on running. fail(id) only works on running. Both return true when they acted and false when they refused — so fail on the attempt that exhausts the retries still returns true: it did act, it just moved the job to failed instead of back to queued.

Priority

When priority arrives, you do not have to rewrite everything. Scan the queued IDs and pick the highest priority. If priority ties, choose the lower insertion sequence.

That makes the rule explicit: priority first, FIFO second.