Ch.61: Message Queue System Design: Why Jobs Come Back
Outline
- 0:00 The thumbnail is finished. The job returns.
- 0:41 Follow one job through the service
- 1:13 What the producer and worker need
- 1:58 Storage capacity is not processing capacity
- 2:45 Save before saying accepted
- 3:39 Find a candidate, then check its state
- 4:29 Receive changes the delivery state
- 5:14 Nobody receives the reply
- 5:41 The first worker wakes up late
- 6:47 Successful delete can mean less than expected
- 7:32 Protect the thumbnail where it is written
- 8:19 A deadline trades duplicates for recovery time
- 9:15 No jobs returned does not mean no jobs remain
- 10:03 One customer's slow work fills the workers
- 10:59 Keep the job that will not finish
- 11:45 Replay the intention, not a new side effect
- 12:13 Recover without inventing a fresh queue
- 13:06 Return to the same complete map
- 13:57 Watch the work, not just the empty space
Transcript
0:00 Imagine a photo site putting expensive thumbnail jobs in a message queue. The queue retains work so background workers can resize pictures after the web request returns. A worker finishes a thumbnail, then another worker receives that same job. That duplicate work costs processing time. Why is the queue offering it again? We'll design the queue behind that question: how it accepts jobs, lends them to workers, and records completion when machines or replies disappear. So the queue stores work, while the resized picture lives somewhere else.
0:30 Finishing that picture doesn't automatically tell the queue anything. Exactly. The awkward gap between those two facts is where a lot of apparently finished jobs come back. First, follow the thumbnail job on this complete map. A producer sends a job through an authorized entry point into durable message storage. Workers ask for work through the delivery path. Their thumbnails go to a separate destination. Each delivery gets a receipt identifying that attempt; the worker returns it when finishing.
1:00 Recovery finds abandoned deliveries and retains repeatedly troublesome jobs. We'll return to this same map. To start, decide what the producer and worker can actually ask this service to do. Before choosing storage, state the functional requirements for that submitted thumbnail. Accept it or refuse clearly, retain accepted work for the agreed lifetime, and let workers receive eligible jobs. Workers need to poll for jobs and acknowledge a finished delivery. Some jobs also need more processing time.
1:30 Then let a worker extend its current delivery. If that delivery expires without completion, make the retained job eligible again. And if a job keeps returning, keep it inspectable rather than letting it circulate forever. That's different from promising every job eventually succeeds. Right. We're building a competing-consumer work queue, where workers share jobs. We aren't broadcasting every event to every application or keeping a permanent replay log. Next, set our non-functional requirements: durable acceptance across an individual process failure, resource limits, separation between customers' work, and a way to see how long work waits.
2:07 Let's say our fictional workload averages 1,000 jobs each second, each carrying 1,024 bytes. Keep 1 day of retained messages. That payload alone is about 88 billion bytes a day, before indexes or replicas. Capacity planning needs room beyond a normal day. And 2 seconds of processing per job means about 2000 occupied worker slots at that average rate. More queue storage doesn't add those workers. Yeah. We've made more room for waiting, not more workers. I'd refuse new acceptance at a known storage limit.
2:41 Accepted means retained, not guaranteed to finish on time. Now make acceptance concrete. Put the job key, payload, a hash of its contents, and ready state in one durable transaction. Only one creation for that queue and job key can commit. Save it before saying accepted. Suppose that commit succeeds but the success reply is lost. The producer can't tell whether the queue kept the job. Does it send another one? It retries the same logical job key. The committed record remembers both that key and its content hash for the agreed retry window, so the service recognizes the request.
3:18 A changed payload under that key is a conflict. Otherwise a producer could reuse one identity for two different jobs, and deduplication would conceal the mistake. Our thumbnail key includes its requested size and the source photo's version. The queue's retry window is finite; we don't promise to remember every identity forever. Once jobs are retained, workers need an efficient way to find ready ones. Route an incoming job and its retries to the same partition. Index when those stored jobs can next be delivered.
3:49 Think of a partition as a group of message records under one storage authority. Does that index decide whether the worker owns a job? No. It proposes a candidate. The durable message record still decides whether a claim can advance. A stale hint must not authorize an extra delivery. Suppose the index loses the hint for our job. Its stored record is still there. Look through the persisted eligible times in limited batches to rebuild that entry. That's how retained work gets found again. Right, losing the shortcut shouldn't mean losing the job.
4:22 Recovery may take longer, but accepted work mustn't disappear because an in-memory entry vanished. With our thumbnail found, claim it atomically: ready becomes delivery 6, with a deadline. 6 is a generation, a number that changes on each new delivery. The delivery number, then. The thumbnail still keeps the same permanent job identifier? Yes. Its receipt identifies that job and this attempt, so only the current attempt can finish or extend its delivery. Got it. Two workers can find the same candidate, but the stored claim settles who gets this delivery. A cache that eventually catches up can't make that decision safely.
5:01 Amazon's managed queue service, SQS, permits duplicates on standard queues, even while a received message is temporarily hidden. Our serialized claims still don't guarantee that only one worker runs the job. But imagine a valid claim that produces no useful work. The queue records a delivery, sends its reply, and the connection breaks before the worker receives it. The job remains retained, temporarily hidden from ordinary delivery. When its deadline expires, another poll can claim it. We spend recovery time without losing the payload.
5:32 So an unanswered receive leaves uncertainty about an issued attempt. What if the worker received the job and then paused? Next, picture this: worker A receives our thumbnail job at 0 on this timeline. Its receipt expires 30 seconds later. Then A pauses for longer than that. At 31 seconds, worker B receives a new delivery of the same job. At 32, A resumes, still holding its original receipt. Both processes can now compute. The deadline changed the queue's permission to redeliver; it did not reach into A's machine and stop its code.
6:07 Hold on. A common mistake is treating this like a lock. Think of two copies of one work order: an expired stamp won't erase either sheet. Which receipt can now finish the queue's current delivery? Only B's current receipt under our chosen state machine. Finishing compares the receipt's generation and live deadline with the authoritative record before changing it. A's old receipt fails that comparison. We can prevent stale queue completion while A is still doing outside work. Those are separate protections.
6:38 Hold that distinction. Replacing the receipt fixes which attempt can change queue state. It hasn't yet made a second thumbnail computation harmless. Before fixing that outside work, one vendor detail matters. Our strict receipt comparison is a proposed design choice, not a claim about SQS's implementation. My first thought was that an old SQS receipt always gets rejected. Does its documented delete operation actually promise that? No. AWS says an old handle can receive a successful response without deleting the message. Its standard queues can also rarely deliver a message after deletion.
7:12 Then a success-shaped response isn't a universal proof of removal. We need the precise API contract, not the reassuring name of its operation. The official source links are in the description. In our design, retain enough completion state to answer repeated acknowledgments consistently within the supported retry window. Now consider both workers reaching the thumbnail destination. Use the same job identity for a conditional create of the result, not a fresh key per delivery. Oh, right. The first valid result creates the output.
7:44 A repeated request finds that result already present and can finish without making another logical thumbnail entry. It may still waste computation. And the key must include the photo version and resize settings, so a genuinely different thumbnail isn't mistaken for a duplicate. Yeah, I'd accept repeat computation before I'd silently overwrite a newer photo's result. What if the destination performs an action we can't make idempotent? Then we cannot promise that action happens exactly once. Idempotent means a repeat is harmless; the queue alone cannot give an unrelated destination that property.
8:18 With the thumbnail protected at its destination, the delivery deadline still affects cost. A short one can repeat slow jobs; a long one hides abandoned work for longer. I'd use a reasonable initial interval and let active workers request extensions. Google's subscriber guide describes the same short-versus-long deadline tradeoff. But an extension reply can disappear too. The worker doesn't know if that extension took effect. Is sending another extension request enough evidence to keep going? For instance, take an alternative version of A's timeline.
8:50 Before 30 seconds, A requests a deadline at 1 minute for its current receipt. If the reply disappears, repeat that exact end time. Confirmation establishes the new deadline; an expired or replaced attempt cannot revive itself. I didn't realize how different that is from adding time on every retry. Until confirmation, I'd rely on the old deadline and expect possible redelivery. Now inspect that backlog: it can look empty while workers are busy. A poll asks for currently available deliveries, not a certificate that every accepted job finished.
9:25 Or the request may have checked only part of the service. AWS documents short polling that samples servers and can miss work elsewhere. Long polling waits and searches more broadly, reducing empty responses. In our router, notifications wake waiting polls, which recheck durable state before claiming anything. So a wakeup is a hint too. I'd bound each caller's waiting connections; otherwise the supposedly empty queue could exhaust resources just answering people asking for work. Yep. Keep available and in-flight work separate on the dashboard.
9:56 A smaller visible backlog could mean progress, or simply more jobs temporarily held by workers. Next, imagine our thumbnail belongs to a quiet customer. Another customer fills the shared workers with a long run of big image jobs. Our one little job keeps waiting. AWS's fair-queue account watches current deliveries by customer, not just backlog. How can we let our quiet customer's thumbnail through when a worker asks again? Limit current claims in our partition. When a slot opens, give that polling worker our waiting job before the dominating customer's next one.
10:32 If nobody else waits, let the busy customer use spare capacity. Oh, so we don't leave a worker idle just to make customers' counts look equal. Our thumbnail gets a turn while the big-image sender keeps using spare capacity. Large pictures still take longer. Production monitoring should guide worker scaling when sustained demand requires it. A queue can absorb a finite burst; it cannot process an infinite backlog by being patient. But a fair queue still needs to handle jobs that keep returning. Apply a delivery-count policy and retain it for inspection.
11:05 This failed-work area is commonly called a dead-letter queue. A finished thumbnail may simply have lost its acknowledgment. How does the queue tell that apart from failed processing? It can't. Count delivery attempts and put unresolved work into the record's retained-failure state. An inspectable failed-work view doesn't require an atomic move between two unrelated databases. Now other jobs can proceed while an operator investigates. But putting the message aside doesn't undo a thumbnail that one of its workers already wrote. And retained doesn't mean permanent.
11:37 Define the inspection and retention policy explicitly, alert on exhausted work, and don't let storage cleanup silently become the success metric. Once the cause is repaired, an operator can replay this retained job. A fresh receipt identifies the next attempt. An operator might say, 'The bug is fixed. Why not give this replay a fresh result key?' That new key would bypass duplicate protection. Keep the destination identity unless a different result is intended, and preserve enough history to explain earlier deliveries.
12:07 Leaving the dead-letter view still doesn't prove the outside action succeeded. Now switch from an operator replay to the queue process crashing. On our original timeline, B has the current delivery. The replacement starts with empty memory. Where does it recover that state? Read the stored row for our thumbnail. B's current delivery is still recorded, including when it expires. Rebuild eligible hints in small pages. Resetting that row to ready would send it out again because a server rebooted. And storage failover must preserve that claimed row, rather than restore its earlier ready state.
12:42 We require that guarantee from the record store; we aren't designing a new consensus algorithm here. If we lose the storage authority needed for a safe write, stop taking new work. Keeping the entry point responsive isn't worth acknowledging jobs we might forget. Yeah. The producer can retry an explicit refusal. We accept that interruption rather than silently weaken what earlier success replies meant. Now return to our original architecture map. The producer's acceptance ends at durable message state.
13:12 The worker's delivery has a receipt and deadline. Its thumbnail is written outside the queue. The router and eligible-work index find candidates, while conditional state changes control deliveries. Extensions buy time, expiry restores eligibility, and unresolved jobs remain inspectable. Customer scheduling protects access to workers. Recovery reconstructs hints without forgetting claims. Every route serves a stated requirement, but none can read an outside worker's mind. Our opening thumbnail can therefore exist while its job returns.
13:41 If completion never reached the queue, redelivery is how it avoids assuming the work disappeared successfully. The receipt keeps an old delivery from finishing a newer one. The stable destination key makes a repeat harmless. We needed both boundaries to answer that opening question. Finally, for debugging, watch the age of the oldest available job, active deliveries, expiry activity and exhausted work separately. Each describes a different place the job might be waiting. If available work falls but thumbnails aren't appearing, which of those would you check first?
14:13 Active deliveries and the actual completed results. The jobs may all be out with workers while no pictures are appearing. I care more about that complete path than a reassuring queue-depth number. And when work returns, we can explain whether it was an unanswered request, an expired delivery or an unresolved effect, instead of treating every duplicate as a mysterious queue bug. Thanks for listening to Learning Podcasts.