An upload API answers in 200 ms. The transcode behind it takes 600 s. If the request waits, 2 uploads a second hold 1,200 workers of a 50 worker pool. Hand the job to a queue and they hold 0.11.
Pick how the handler treats the upload, then drag the upload rate. Watch who holds the 50 slots. Then we build it piece by piece: the queue, the claim timer, the pool, the status channel, retries, idempotency, priorities and cron.
You need to know that an HTTP request expects an answer in under a second and that a database stores rows you can update. We build the rest from zero.
Toy numbers are labelled. Facts about real systems come from the Amazon SQS, Celery, Redis and Temporal documentation, each linked where it is used.
Illustrative service: 200 fast requests a second that each hold a slot for 0.2 s, plus uploads. The slot counts come from Little's law (Chapter 0), so they are averages.
Chapter 0
Count how many workers a slow request holds, and see why ten minutes of work cannot live inside one HTTP request
A user drops a video on an upload page. The API answers in 200 ms with a video ID. Then the file must become three resolutions and a thumbnail. That work is transcoding, and on this service it takes about 600 seconds. Can one HTTP request hold both numbers?
The API runs a worker pool: a fixed number of slots, here 50, that each serve one request at a time. A slot is busy from the moment a request arrives until its response leaves. So the question becomes: how many slots are busy at once?
Call the number of requests that arrive each second λ (lambda). Call the time each request holds a slot W, in seconds. Call the average number of busy slots L.
L equals lambda times W.
Multiply how many requests arrive each second, lambda, by how long each one stays, W. The product L is how many are inside at the same time. This is Little's law. It holds for any system whose line does not grow forever.
With made-up numbers: fast requests arrive at lambda = 200 per second and stay W = 0.2 s, so L = 40 of the 50 slots. Uploads that wait for the transcode arrive at 2 per second and stay 600 s, so L = 1,200. They are 1% of the requests and need 24 times the pool.
The top bar splits the requests by endpoint. The bottom bar splits the busy slots. Drag how long an upload holds its slot.
Illustrative traffic: profile 150 per second at 0.15 s, search 50 per second at 0.35 s, upload 2 per second. Pool of 50 slots.
The slots are shared by every endpoint. When uploads hold them all, a profile lookup that needs 15 ms waits behind a ten minute transcode. Nothing in the profile code changed, so nobody looks at uploads.
It gets worse. The load balancer closes an idle connection long before 600 s. An AWS Application Load Balancer, for example, defaults to a 60 second idle timeout. The client sees an error and retries, and the retry holds a second slot for the same video.
pythondef handle_upload(request): video_id = save_to_storage(request.files["video"].read()) # about 50 ms enqueue_job("transcode", video_id=video_id) # about 5 ms: hands off, does not wait return {"video_id": video_id, "status": "queued"}, 202
The status code is 202 Accepted: the server took the request but has not finished the work. The handler now holds a slot for 0.055 s, so uploads hold 2 × 0.055 = 0.11 slots on average.
Chapter 1
Open up the hand-off, and choose when the broker forgets a message so that a crash never loses a job
The upload handler called enqueue_job and returned. Where did the job go? A task queue has three parts, and each part hands the job to the next.
Now a worker crashes in the middle of a job. What happens to the message? That depends on when the worker acknowledges it, that is, tells the broker to delete it.
| Delivery | The worker deletes the message | If the worker crashes mid-job |
|---|---|---|
| At most once (ack early) | when it claims it, before the work | The job is gone. No error, no retry. |
| At least once (ack late) | after the work succeeds | The message comes back, and another worker runs it. |
Pick when the worker acknowledges. Press Run a job, then press Crash while the bar fills.
A toy on a compressed clock. The message comes back after the broker's timeout, which Chapter 2 explains.
Put a number on it. Say a platform runs 500,000 transcodes a day, and 0.01% of them meet a worker crash: an out-of-memory kill, a deploy, a lost machine. With ack early, 500,000 × 0.0001 = 50 videos a day vanish without a trace. With ack late, the same 50 come back and finish.
pythondef worker_loop(broker): msg = broker.receive() # msg.body: {"job_id": "job_8f2a", "video_id": "vid_5591", "attempt": 0} transcode(msg.body["video_id"]) # a crash here leaves the message with the broker broker.delete(msg) # ack late: delete only after success
Defaults matter here. In Celery, the setting task_acks_late is disabled by default, so a worker acknowledges a task before it runs it. A long job that must not be lost needs that setting turned on.
Chapter 2
Watch a timer that is shorter than the job hand the same video to a second worker, and fix it with a heartbeat
With ack late, how does the broker decide that a worker has died? It uses a timer. When a worker receives a message, the broker hides it from everyone else for a fixed window, the visibility timeout. If the worker deletes the message in time, the job is done. If the window runs out first, the message becomes visible again and the next worker that asks gets it.
In Amazon SQS this window defaults to 30 seconds, and a worker can change it with ChangeMessageVisibility. Now say someone copies a 300 s timeout from a faster job type, and the transcode takes 600 s.
Call the job's duration D and the visibility timeout V, both in seconds. Each time the window expires before the first worker finishes, one more worker starts the same job. Call the number of copies that start n.
n equals the ceiling of D over V.
Divide the job's duration D by the timeout V and round up. A new copy starts at every multiple of V that comes before D. That count is n.
With D = 600 s and V = 300 s, n = 2: worker B starts at 300 s and runs until 900 s. Its whole 600 s is wasted. A 900 s p99 job gives n = 3 copies.
Each lane is one worker. Yellow ticks are the moments the window expires. Drag the timeout below the job and watch copies appear. Then turn on the heartbeat.
The heartbeat extends the claim to 180 s from now, every 60 s. Durations are illustrative.
Price it. Say 1% of 500,000 daily jobs hit this bug. That is 5,000 extra copies a day, each running 600 s: 5,000 × 600 = 3,000,000 worker-seconds, or 833 worker-hours a day. At a made-up $0.04 per worker-hour, about $33 a day and $1,000 a month, for work done twice.
One fix sets V above the worst case, say 1,200 s for a 900 s p99. But then a worker that crashes at 10 s leaves its job hidden for 20 minutes. The better fix is a heartbeat: while it works, the worker extends its claim every 60 s to 180 s from now. A slow job never loses its claim. A dead worker stops beating, and the broker frees its job within 120 to 180 s. The SQS guide recommends this pattern and caps the total at 12 hours from the first receive.
pythondef process(msg, sqs, queue_url): last = time.time() for chunk in encode_chunks(msg.body["video_id"]): process_chunk(chunk) if time.time() - last > 60: # heartbeat every 60 s sqs.change_message_visibility(QueueUrl=queue_url, ReceiptHandle=msg.receipt_handle, VisibilityTimeout=180) last = time.time() sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg.receipt_handle)
Chapter 3
Use Little's law to count the workers, then see how a pool's size decides how close to full it can run
The queue now carries many job types: 5 s thumbnails, 15 s previews, 600 s transcodes. Measured over the whole mix, say 100 jobs arrive each second and the average job takes 30 s. Little's law from Chapter 0 gives the jobs in progress: L = 100 × 30 = 3,000. With one job per worker, 3,000 workers are busy on average.
So is 3,000 workers enough? Only if work arrives like a metronome. Call the number of workers c. Call the share of time each worker is busy its busy share, ρ (rho).
rho equals lambda times W, over c.
Lambda times W is the work in progress. Divide it by the c workers you have. If rho reaches 1, the line of waiting jobs grows without end.
With lambda = 100 per second, W = 30 s and c = 3,750 workers, rho = 3,000 / 3,750 = 0.8. Each worker idles one fifth of the time.
How long does a job wait for a free worker at rho = 0.8? That depends on c. Jobs arrive at random, so sometimes several come at once. One worker has nobody to cover a burst. A thousand workers almost always have one free. The device computes the average wait with the Erlang C formula, the standard model for c workers and random arrivals.
Three curves, three pool sizes, all with 30 s jobs. Drag the busy share and read the wait on each curve.
Random arrivals and random job lengths (the M/M/c model). Real job lengths are burstier, so treat these waits as a lower bound.
At rho = 0.8, one worker makes a job wait 120 s, ten workers 6.1 s, a hundred workers 0.03 s. With 3,750 workers the wait is near zero. A big pool can run hot. A small pool needs headroom.
The real danger is the peak. Say daytime traffic runs 1.8 times the daily average. Then lambda = 180, L = 5,400, and 3,750 workers give rho = 1.44. The pool finishes 3,750 / 30 = 125 jobs a second while 180 arrive. The backlog grows by 55 jobs every second. An autoscaler whose new workers take 90 s to boot adds 55 × 90 = 4,950 jobs to the backlog before help arrives.
ApproximateAgeOfOldestMessage).Chapter 4
Price polling against the rate of real news, pick a push channel, and guard the job's state with compare-and-swap
The client got a 202 and a job ID. Its progress bar is still spinning. How does it learn that the job finished? The obvious answer is to ask: call GET /jobs/{id} every few seconds. This is polling.
Call the number of jobs that clients are watching N and the time between two polls T, in seconds. Call the requests per second that reach the status endpoint q.
q equals N over T.
Each of the N watched jobs sends one poll every T seconds. Divide N by T to get q. The average client learns of the finish T/2 seconds late.
With N = 3,000 jobs in progress (Chapter 3) and T = 2 s, q = 1,500 requests per second. Only 100 jobs finish each second, so 14 of every 15 polls hear "still running". The average delay is 1 s.
Blue is status traffic. Green is the news: jobs that finish each second. Pick a channel, and for polling, drag the interval.
3,000 watched jobs, 100 finishing per second. The long poll holds each request up to 25 s and checks every 0.5 s. Illustrative.
Push flips who starts the call. With a webhook, the client registers a URL and the worker calls it once when the job ends: 100 calls a second, with no delay. A browser tab has no public URL, so it holds a WebSocket instead; Realtime Updates builds that connection tier. A webhook call can fail too, so it needs retries, and the status endpoint stays as the fallback.
Every channel reads one row per job. Its state moves through a few values: queued, running, retrying, then done or failed. Nothing leaves a final state. Chapter 2's duplicate puts two workers on one job. A compare-and-swap update lets only one of them win: the write succeeds only if the row still holds the state the worker expects.
sqlUPDATE jobs SET status = 'running', worker_id = $1, started_at = now() WHERE id = $2 AND status IN ('queued', 'retrying'); -- 1 row changed: you own the job. 0 rows: someone else does, so stop now.
running after it was done.Chapter 5
Space retries out so a recovering service survives them, add randomness to break the herd, and park the jobs that never succeed
Every transcode ends by writing to object storage. Storage goes down for ten seconds, and 1,000 workers fail at the same instant. When should each one try again?
Exponential backoff waits longer after each failure. Call the first wait b, in seconds, and the attempt number k. Call the wait before retry k dk.
d-k equals b times 2 to the k minus 1.
Wait b before the first retry. Double the wait d-k after every failure. A short blip costs one short wait, and a long outage is not hammered.
With b = 1 s, the waits are 1, 2, 4, 8 and 16 s. The retries fire at 1, 3, 7, 15 and 31 s after the first failure.
Backoff alone has a flaw. All 1,000 workers failed together and use the same formula. So all 1,000 retry at 1 s, at 3 s and at 7 s, and each spike can knock storage down again. This is a thundering herd. The fix is full jitter: draw each wait at random between zero and the backoff value.
d-k equals a random number between zero and b times 2 to the k minus 1.
Each worker computes the backoff cap, then rolls its own d-k inside it.
For the first retry the cap is 1 s, or 100 windows of 10 ms. So 1,000 workers / 100 windows = about 10 retries per window, not 1,000 at once.
Each bar counts retries that hit storage in one 100 ms slice. Switch jitter on and off, and drag how many workers failed together.
Four retries each, base 1 s, one fixed random seed. Full jitter as described by Marc Brooker in the AWS Architecture Blog post "Exponential Backoff and Jitter" (2015).
A Temporal activity retries by default after 1 s, doubles each time, caps the wait at 100 s, and never stops trying.
Backoff assumes the failure will pass. A corrupt video fails on every try: it is a poison pill. If poison pills are 0.1% of 100 jobs a second, 0.1 arrive each second, and 8,640 a day join a queue they never leave. So cap the attempts, say at 5, then move the job to a dead-letter queue (DLQ), where a person reads it. In SQS the cap is the maxReceiveCount of a redrive policy.
| Failure | Retry? | Why |
|---|---|---|
| Timeout, connection reset | Yes, with jitter | The same call will likely work soon. |
| HTTP 503 or 429 | Yes, with jitter | The service says: try later. |
| HTTP 400, corrupt input | No, to the DLQ now | The same request fails the same way. |
When a dependency is clearly down, a circuit breaker stops calling it: after 5 failures in a row, it fails calls at once for 30 s, then lets one probe through.
Chapter 6
Make a second run of the same job change nothing, and size the window that catches a repeated request
Duplicates come from three places: a client that retries after a 504, a visibility timeout that expires, a retry after a failure. No broker can promise each job runs exactly once when the job has a side effect. A worker can always crash after the work and before its acknowledgement. What we can build is effectively once: delivery at least once, plus a handler where a second run has the same effect as one. That property is idempotency.
pythondef process_transcode(msg, db, storage): job = db.get_job(msg.body["job_id"]) if job.status == "done": return # a duplicate: do nothing path = f"transcoded/{job.id}/out.mp4" # keyed by the job, not the attempt storage.write(path, transcode(job.video_id)) # a racing copy overwrites the same file db.mark_done(job.id)
A client retry needs a guard one step earlier, before a job exists. The client sends an idempotency key, one per upload, in a header. The API stores each key with its first response. A repeat gets the stored response and no new job. How long must the store keep each key?
Call the arrival rate of new jobs λ and the time a key is kept, the dedup window, w. Call the number of keys stored at once K.
K equals lambda times w.
This is Little's law with keys in place of requests. Keys arrive at lambda and each stays w seconds, so K are stored. Pick w first: it must outlast the latest legal duplicate.
A redelivered duplicate can arrive up to the 1,200 s timeout plus the 900 s p99 job: 2,100 s. Round up to w = 3,600 s. With lambda = 100 per second, K = 360,000 keys. At 100 bytes each, that is 36 MB.
The yellow band is the window that remembers the key. The marker is the duplicate. Drag both.
100 new jobs per second, 100 bytes per stored key. Illustrative.
Some effects are idempotent by nature, and some are not.
| Effect | Safe to repeat? | Why |
|---|---|---|
SET status = 'done' | Yes | It sets a fixed value. |
SET credits = credits - 1 | No | Two runs remove two credits. |
| Send "your video is ready" | No | The user gets two emails. |
An unsafe effect gets its own flag, flipped by compare-and-swap before the effect fires. Only the caller that changes one row sends the email.
sqlUPDATE jobs SET notified = true WHERE id = $1 AND notified = false; -- 1 row changed: send the email. 0 rows: it was sent already.
Chapter 7
Split one busy pool between paying and free jobs, and compare one line, a hard split and strict priority
A paying customer's job waits behind a flood of free jobs. Should it? Take a small pool so the waits are visible: 20 workers, jobs of 30 s, 0.6 jobs arriving per second. Then rho = 0.6 × 30 / 20 = 0.9. One job in ten is from the pro tier.
There are three common policies.
Bars show the average wait before a worker starts the job. Pick a policy, then drag the pro share of traffic.
M/M/c model, 20 workers, 30 s jobs, 0.6 jobs per second. The hard split reserves the pro load rounded up, plus one. Strict priority does not stop a running job.
At 10% pro, the numbers from the model:
| Policy | Pro waits | Free waits |
|---|---|---|
| One FIFO line | 8.3 s | 8.3 s |
| Hard split, 3 pro and 17 free workers | 8.9 s | 29.5 s |
| Strict priority | 0.9 s | 9.1 s |
The hard split makes both tiers worse here. Small pools waste capacity, because a pro worker idles while free jobs wait. Strict priority keeps the shared pool and moves pro to the front: pro drops ninefold, free rises only from 8.3 to 9.1 s. The average over all jobs stays 8.3 s. Policy moves waiting around. It does not remove it.
Strict priority has one danger. Drag the pro share up: free jobs wait longer and longer, and if pro work alone fills the pool, free jobs never start. That is starvation. Two fixes bound it.
The same problem exists inside one tier. One customer submits 500 jobs; nine others submit one each. In one FIFO line, a single job can wait behind all 500. With round robin by customer, the worker takes one job from each customer in turn. Each single job then has at most 9 jobs ahead.
Chapter 8
Turn one cron entry on ten replicas into one run with a lock, and size the lock's lifetime from the task's worst case
Some work starts from the clock: "every five minutes, find jobs stuck in running and requeue them." The API runs 10 replicas, and each runs the same scheduler. At 10:05, ten copies of the task start. If the task sends emails, every user gets ten.
The fix is a distributed lock: a key that only one holder can own. With Redis, a replica runs SET lock:requeue <token> NX EX 120. NX sets the key only if it does not exist, and EX makes it expire after 120 s. One replica gets OK and runs the task. The other nine get nothing and skip.
The expiry frees the lock if its holder crashes. But it brings back Chapter 2's bug. Call the lock's lifetime, its TTL, Tlock. Call the task's p99 duration D99 and a safety margin m.
T-lock must be greater than D-ninety-nine plus m.
Take the task's worst normal duration, D-ninety-nine, add a margin m, and set the lock's T-lock above the sum. Otherwise the lock expires while the task still runs, and the next replica to ask gets it.
With D-ninety-nine = 45 s, a TTL of 30 s fails: a replica that asks at 35 s gets the lock and starts a second run. A TTL of 120 s gives a 75 s margin.
Ten replicas ask for the lock at slightly different moments. The yellow bar is the lock's life. Drag the TTL below the task and watch a second run start.
The ten ask times spread over 0 to 40 s stand for slow starts and pauses. Illustrative.
Two details from the Redis docs. Store a random token as the value. Delete the lock only if the value still matches, so a slow holder cannot free a lock that another replica now owns. And the Redis docs prefer the Redlock algorithm to this single-key pattern when you need stronger guarantees. One more trap: if the holder deletes the lock when it finishes, a replica that asks late still runs the task for the same slot. Put the slot in the key (lock:requeue:10:05) and let it expire.
A task that touches every row needs spreading. "Rebuild every user's feed once a day" for 10,000,000 users, started at midnight, floods the pool. Split users into 1,440 buckets by user ID, one per minute: 6,944 users per minute, about 115.7 per second all day.
Chapter 9
Run the whole system on a fast clock, kill a worker mid-job, and watch the job survive
Here is every part in one place. The producer enqueues a job and answers 202. The broker hides each claimed message behind a visibility timeout. Four workers claim, heartbeat and finish. A finished job is checked against its state, so a duplicate changes nothing.
Press Play. Upload jobs or let them arrive. Kill a busy worker and watch its job come back after the timeout. Then switch the heartbeat off and watch duplicates appear.
A compressed demo clock: jobs take 4 to 6 demo seconds, the visibility timeout is 3, and a killed worker reboots after 4. The ratios matter, not the values.
Read the counters like an incident review.
A kill with the heartbeat on costs one timeout of delay and one rerun. The heartbeat off costs a copy of most jobs. With both a correct timer and an idempotent finish, failures cost compute and never cost correctness.
Chapter 10
Keep the terms, the numbers, the checklist and the core loop in one place
Work that outlives a request goes to a queue. The request answers 202. A worker claims the job behind a timer and extends the claim while it works. It retries with jitter, parks what never succeeds, and finishes so that a second run does no harm.
| Term | Meaning | This lesson's number |
|---|---|---|
| Little's law | busy = arrival rate × time held | 2/s × 600 s = 1,200 slots |
| 202 Accepted | taken, not finished | upload holds a slot 0.055 s |
| Ack late | delete the message after success | 50 lost jobs a day saved |
| Visibility timeout | how long a claim hides a message | above the 900 s p99, or a heartbeat |
| Heartbeat | extend the claim while alive | every 60 s, to 180 s |
| Busy share | work in progress / workers | 3,000 / 3,750 = 0.8 |
| Poll load | watched jobs / interval | 3,000 / 2 s = 1,500 per second |
| Full jitter | random wait up to the backoff | about 10 per 10 ms, not 1,000 |
| Dead-letter queue | where capped-out jobs go | after 5 attempts |
| Dedup window | how long a key is kept | 3,600 s, 360,000 keys, 36 MB |
| Lock TTL | lifetime of a singleton lock | 120 s for a 45 s p99 task |
pythonimport random, time RETRYABLE = (TimeoutError, ConnectionError) def work_one(broker, db, max_attempts=5, base=1.0): msg = broker.receive(visibility_timeout=180) if msg is None: return job_id, attempt = msg.body["job_id"], msg.body["attempt"] if not db.claim(job_id): # compare-and-swap: queued -> running broker.delete(msg); return # done already, or someone else owns it try: run_with_heartbeat(job_id, msg, broker, every=60, extend_to=180) db.finish(job_id) # running -> done except RETRYABLE: if attempt + 1 >= max_attempts: broker.dead_letter(msg); db.fail(job_id) else: db.set_status(job_id, "retrying") broker.retry_after(msg, random.uniform(0, base * 2 ** attempt)) # full jitter return except Exception: broker.dead_letter(msg); db.fail(job_id); return # not retryable broker.delete(msg) # ack late
A raw broker gives you delivery and the timeout; you build the rest. A task framework such as Celery adds retries, schedules and result storage as settings. A workflow engine such as Temporal saves each step's progress and retries activities by policy. Each layer moves these decisions. None removes them: you still pick timeouts and still need idempotent steps.
Now press Present or Teach. Explain from memory Little's law on a shared pool, the timeout duplicate, and the layers that make a duplicate harmless. Then go back to the hero, switch to Wait for it, and say how many slots one upload a minute takes.
An Engineermaxxing lesson; all toy numbers are labelled. Facts about real systems: the Amazon SQS Developer Guide on visibility timeout and dead-letter queues; the Celery configuration reference; the Redis SET command; Temporal retry policies; the Application Load Balancer attributes; Marc Brooker, Exponential Backoff and Jitter (2015).