Async Work and Long-Running Tasks

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.

Wait for the job, or hand it off

2

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

The Request That Waits

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.

Say it aloud

L equals lambda times W.

L
L the average number of requests inside at once, so the number of busy slots.
λ
lambda the arrival rate: requests per second.
×
times multiply.
W
W the seconds each request holds its slot.
In plain words

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 numbers

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.

Find the endpoint that eats 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.

600 s

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.

The failure, as symptom, measurement and fix

  1. Symptom: the p99 latency of a fast endpoint climbs while its own traffic is flat.
  2. Measure: busy slots and slot hold time per endpoint, not request count.
  3. Fix: do not run the slow part inside the request. Hand it off and answer at once.
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.

The road

  1. Producer, broker, worker: the three parts of a queue, and when a job can be lost.
  2. The visibility timeout: the timer that guards each claim, and the duplicate it causes.
  3. Sizing the worker pool: Little's law again, and how close to full a pool can run.
  4. Telling the client it is done: polling, webhooks and the job state machine.
  5. Retries, backoff and dead letters: retry without a storm, and stop the jobs that never succeed.
  6. Idempotency: make a second run harmless.
  7. Priorities and fairness: who waits when the pool is busy.
  8. Scheduled work on a fleet: one cron entry, ten replicas, one run.
  9. The assembled pipeline: kill a worker and watch the job survive.
  10. Field guide: the numbers, the checklist and the core code.
Uploads are 1% of requests. Profile lookups slow down whenever uploads rise. What is the best explanation?

Chapter 1

Producer, Broker, Worker

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.

  1. The producer (the upload handler) writes a message: a small record that describes the job. It takes about 5 ms.
  2. The broker stores the message on disk until a worker claims it. Amazon SQS, RabbitMQ and Redis can all play this part.
  3. A worker asks the broker for a message, does the 600 s of work, then tells the broker it is done.

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.

DeliveryThe worker deletes the messageIf the worker crashes mid-job
At most once (ack early)when it claims it, before the workThe job is gone. No error, no retry.
At least once (ack late)after the work succeedsThe message comes back, and another worker runs it.

Crash the worker mid-job

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.

The failure, as symptom, measurement and fix

  1. Symptom: a few users say their video never finished, and the logs show no error.
  2. Measure: jobs created per day minus jobs finished or failed per day. It should be zero.
  3. Fix: acknowledge after the work. Then handle the duplicates that this choice allows (Chapters 2 and 6).
A worker deletes each message as soon as it receives it, then transcodes. The process is killed mid-job. What happens?

Chapter 2

The Visibility Timeout

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.

Say it aloud

n equals the ceiling of D over V.

n
n how many workers start this one job before the first finishes.
⌈ ⌉
the ceiling of round up to the next whole number.
D
D how long one run of the job takes, in seconds.
V
V the visibility timeout, in seconds. If V is at least D, n is 1.
In plain words

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 numbers

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.

Set the timer against the job

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.

300 s
600 s

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)

The failure, as symptom, measurement and fix

  1. Symptom: output files written twice, compute bills up, no errors.
  2. Measure: how often a message is received more than once, next to the job's p99 duration.
  3. Fix: a heartbeat, or V above the p99. Chapter 6 makes the rare duplicate harmless.
The visibility timeout is 300 s and a job takes 900 s, with no heartbeat. How many workers start this job?

Chapter 3

Sizing the Worker Pool

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).

Say it aloud

rho equals lambda times W, over c.

ρ
rho busy share: the share of time each worker is busy, from 0 to 1.
λ
lambda jobs arriving per second.
W
W the average seconds one job takes to run.
c
c the number of workers in the pool.
In plain words

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 numbers

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.

Run the pool hotter

Three curves, three pool sizes, all with 30 s jobs. Drag the busy share and read the wait on each curve.

0.80

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.

The failure, as symptom, measurement and fix

  1. Symptom: jobs finish in seconds at night and in tens of minutes at midday.
  2. Measure: the age of the oldest message in the queue (SQS reports it as ApproximateAgeOfOldestMessage).
  3. Fix: size for the peak, scale on queue depth before the wait breaches, and let a worker finish its claimed job before you remove it.
100 jobs arrive per second and each takes 30 s on average. What happens with exactly 3,000 workers?

Chapter 4

Telling the Client It Is Done

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.

Say it aloud

q equals N over T.

q
q status requests per second.
N
N jobs being watched right now.
T
T the poll interval: seconds between two polls of one job.
In plain words

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 numbers

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.

Ask, wait, or be told

Blue is status traffic. Green is the news: jobs that finish each second. Pick a channel, and for polling, drag the interval.

2 s

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.

The state every channel reads

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.

The failure, as symptom, measurement and fix

  1. Symptom: the status endpoint is the busiest route, and a job shows running after it was done.
  2. Measure: status requests per finished job, and state changes that move out of a final state.
  3. Fix: push with a poll fallback, and write every state change as a compare-and-swap.
2,000 jobs are watched and clients poll every 4 s. About 50 jobs finish per second. How many status requests arrive per second?

Chapter 5

Retries, Backoff and Dead Letters

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.

Say it aloud

d-k equals b times 2 to the k minus 1.

dk
d-k the wait, in seconds, before retry number k.
b
b the base wait: the wait before the first retry. Here 1 s.
2k−1
2 to the k minus 1 doubles once per earlier retry: 1, 2, 4, 8, and so on.
In plain words

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 numbers

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.

Say it aloud

d-k equals a random number between zero and b times 2 to the k minus 1.

dk
d-k this worker's own wait before retry k.
random( , )
a random number between every value in the range is equally likely, drawn fresh by each worker.
0
zero the shortest possible wait.
b × 2k−1
b times 2 to the k minus 1 the longest wait: the plain backoff from the first equation.
In plain words

Each worker computes the backoff cap, then rolls its own d-k inside it.

With numbers

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.

Break up the retry storm

Each bar counts retries that hit storage in one 100 ms slice. Switch jitter on and off, and drag how many workers failed together.

1,000

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.

Jobs that will never succeed

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.

FailureRetry?Why
Timeout, connection resetYes, with jitterThe same call will likely work soon.
HTTP 503 or 429Yes, with jitterThe service says: try later.
HTTP 400, corrupt inputNo, to the DLQ nowThe 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.

The failure, as symptom, measurement and fix

  1. Symptom: a ten second outage turns into a ten minute one, with load spikes at 1, 3 and 7 s.
  2. Measure: requests per 10 ms to the dependency during recovery, and DLQ arrivals per hour.
  3. Fix: full jitter, an attempt cap with a DLQ, an alarm on the DLQ, and a breaker on the dependency.
1,000 workers fail at once and use backoff with base 1 s but no jitter. What does the storage service see?

Chapter 6

Idempotency

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.

Say it aloud

K equals lambda times w.

K
K the keys held in the dedup store at any moment.
λ
lambda new jobs per second, each with one key.
w
w the dedup window: seconds each key is kept.
In plain words

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.

With numbers

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.

Catch the late duplicate

The yellow band is the window that remembers the key. The marker is the duplicate. Drag both.

3,600 s
2,100 s

100 new jobs per second, 100 bytes per stored key. Illustrative.

Some effects are idempotent by nature, and some are not.

EffectSafe to repeat?Why
SET status = 'done'YesIt sets a fixed value.
SET credits = credits - 1NoTwo runs remove two credits.
Send "your video is ready"NoThe 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.

The failure, as symptom, measurement and fix

  1. Symptom: a user gets two emails, or two charges, for one upload.
  2. Measure: side effects per job ID. Any count above one is a bug.
  3. Fix: an idempotency key at the API, a status check and fixed output path in the worker, a flag per unsafe effect.
Duplicates can arrive up to 2,100 s after the original. Keys are kept for 1,800 s. What happens to a duplicate at 2,000 s?

Chapter 7

Priorities and Fairness

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.

  1. One FIFO line: first in, first out, for everyone.
  2. Hard split: reserve some workers for pro jobs only.
  3. Strict priority: a free worker always takes a waiting pro job first.

Choose who waits

Bars show the average wait before a worker starts the job. Pick a policy, then drag the pro share of traffic.

10%

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:

PolicyPro waitsFree waits
One FIFO line8.3 s8.3 s
Hard split, 3 pro and 17 free workers8.9 s29.5 s
Strict priority0.9 s9.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.

The failure, as symptom, measurement and fix

  1. Symptom: free-tier jobs sit for hours during a pro surge.
  2. Measure: wait time per tier and per customer, at the p99, not the average.
  3. Fix: priority with aging or a weighted floor, and round robin by customer inside a tier.
Strict priority cut pro waits from 8.3 s to 0.9 s with no new workers. What happened to the average wait over all jobs?

Chapter 8

Scheduled Work on a Fleet

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.

Say it aloud

T-lock must be greater than D-ninety-nine plus m.

Tlock
T-lock the lock's time to live, in seconds.
>
must be greater than a rule, not a calculation.
D99
D-ninety-nine the task duration that 99 runs in 100 finish within.
m
m the margin for clock differences between machines, pauses and slow starts.
In plain words

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 numbers

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.

Hand the lock to one replica

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.

30 s
45 s

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.

The failure, as symptom, measurement and fix

  1. Symptom: one scheduled email arrives twice, now and then.
  2. Measure: runs per schedule slot, logged with the replica name.
  3. Fix: a lock with a TTL above p99 plus margin, a heartbeat that extends it for long tasks, and a task that is idempotent anyway.
A lock with a 30 s TTL guards a task whose p99 is 45 s. What can happen?

Chapter 9

The Assembled Pipeline

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.

Kill a worker and keep the job

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.

0.35 / s

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.

You kill a busy worker. A few demo seconds later another worker finishes the same job. Which two mechanisms did that?

Chapter 10

Field Guide

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.

Terms and numbers

TermMeaningThis lesson's number
Little's lawbusy = arrival rate × time held2/s × 600 s = 1,200 slots
202 Acceptedtaken, not finishedupload holds a slot 0.055 s
Ack latedelete the message after success50 lost jobs a day saved
Visibility timeouthow long a claim hides a messageabove the 900 s p99, or a heartbeat
Heartbeatextend the claim while aliveevery 60 s, to 180 s
Busy sharework in progress / workers3,000 / 3,750 = 0.8
Poll loadwatched jobs / interval3,000 / 2 s = 1,500 per second
Full jitterrandom wait up to the backoffabout 10 per 10 ms, not 1,000
Dead-letter queuewhere capped-out jobs goafter 5 attempts
Dedup windowhow long a key is kept3,600 s, 360,000 keys, 36 MB
Lock TTLlifetime of a singleton lock120 s for a 45 s p99 task

Checklist

  1. Does any request do work longer than about a second? Queue it and answer 202.
  2. Acknowledge after the work, never before.
  3. Set each queue's visibility timeout from its slowest job's p99, or heartbeat.
  4. Size the pool from peak lambda times average W, and scale on queue age.
  5. Push status when you can; keep a status endpoint as the fallback.
  6. Retry only retryable errors, with full jitter, a cap and a DLQ with an alarm.
  7. Make the handler idempotent: a status check, a fixed output path, a flag per unsafe effect.
  8. Use priority with aging, and round robin by customer.
  9. Guard scheduled tasks with a lock whose TTL beats p99 plus margin.

The core loop

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

Where it sits

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.

Keep going

The one habit. When a spec says "processing" or "generating", ask how long the work takes. If it does not fit inside a request, everything in this lesson is what correct means.

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.

Sources

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).

Async Work and Long-Running Tasks
Scaling Reads · Scaling Writes · Realtime Updates · Back to Gleams