Library/Coding patterns that get asked/Building a small system

A work queue that survives failures

105 min6 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Hand out tasks oldest first with a deque or a heap, and let only the worker that holds a task finish it
  • Put a failed task back in its original place, count its attempts, and send it to a dead-letter queue at the limit
  • Turn a reservation into a lease that ends by itself, with a clock you pass in, a heap of deadlines and a cooldown counted from the failure
  • Hold a task until the tasks it depends on are done, and take its dependents down with it when one dies
  • Answer the follow-ups: late acks and work that runs twice, heartbeats, fencing tokens, a queue that crashes, and priorities
Part 1 of 6about 15 min
A queue and its holders

A work queue that survives failures

OpenAI software engineer candidates report a fault-tolerant work queue as their coding question (3 reports). Two of them name the parts they had to build: enqueue, reserve, fail and a dead-letter queue, with unit tests that all had to pass (2 reports). It starts like this:

Build WorkQueue. enqueue(task_id) adds a task. reserve(worker) hands that worker the oldest waiting task and hides it from every other worker, or returns None when nothing is waiting. ack(worker, task_id) marks the task done and returns True, but only for the worker that holds it.

CallReturns
enqueue("a"), then enqueue("b")
reserve("w1")"a"
reserve("w2")"b"
ack("w2", "a")False, because w1 holds a
ack("w1", "a")True, and a is done
reserve("w1")None, because w2 still holds b

Then the interviewer adds failure. fail gives a task back, and after too many failures the task goes to a dead-letter queue. Next comes time: a reservation that ends by itself when a worker goes quiet, and a cooldown before a failed task runs again. In two reports, the second part added dependencies between tasks (2 reports).

You don't write it yet. The lesson first teaches the pieces one at a time: a line in order, a reservation only its holder can finish, retries and a dead-letter queue, leases on a clock you control, and tasks that wait on other tasks. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.

This lesson builds on three earlier ones: heaps for the next task and the next deadline, the caches lesson's clock that you pass in, and Kahn's algorithm from the topological sort lesson, which comes back when tasks wait on other tasks.

A queue hands out the oldest task first

A queue is a line at a counter. New tasks join at the back, and work is taken from the front. So the task that has waited longest goes first. That rule is called FIFO, for first in, first out.

Python's collections.deque is built for this. append adds at the back and popleft takes from the front, and both cost O(1).

from collections import deque

line = deque()
line.append("a")
line.append("b")
line.append("c")
print(line.popleft())
print(line)
a
deque(['b', 'c'])
The line after three enqueues, front on the left
line
abc

reserve takes a, the task that has waited longest. A new task joins after c.

A plain list works too, but list.pop(0) moves every item behind the first one up a place, so it costs O(n). On a queue of a million tasks, that's a million moves for every reserve. Use a deque, or a heap when the order needs more than arrival time. You'll need the heap in part 2.

One more rule from the problem: a reserve on an empty queue returns None. It doesn't raise. Workers ask for work all the time, and "nothing to do" is a normal answer.

The function replay in the editor runs a list of queue operations on a deque. Write the loop body, so each reserve records the task it took, or None.

A reservation hides a task, and only its holder can finish it

Why not pop the task and forget about it? Because workers crash. If the queue forgets a task the moment a worker takes it, a crash loses that task for good.

So reserve doesn't delete. It moves the task from waiting to reserved and writes down who holds it. The task is hidden from every other worker, but the queue still knows about it. Later the holder sends an ack, short for acknowledgment: the work is done, and the queue can mark it finished.

That needs two dicts:

DictMapsExample
statustask id to its state{"a": "reserved", "b": "waiting"}
holdera reserved task to its worker{"a": "w1"}

An ack counts only when it comes from the holder. Any other ack returns False and changes nothing:

  • another worker's ack, because it never had the task
  • a second ack from the holder, because the task is already done
  • an ack for an id the queue never saw

Why False and not an exception? In a real system, acks arrive late, twice, or from a worker that lost its task. Those are normal events. A boolean lets the worker log it and move on.

Predict

w1 reserves a. Then w2 calls ack("w2", "a"). What should happen?

Pick an answer above to see the rest

Name the states before you write the class

Every task in the queue is in one of four states, and it moves between them on four events:

The four states of a task, and the events that move it
reserveackfailfail-lastwaitingreserveddonedead
  • waiting: in the line, ready to be handed out.
  • reserved: a worker holds it.
  • done: the holder acked it. Nothing moves it again.
  • dead: it failed too many times and sits in the dead-letter queue. Nothing moves it again either, until a person sends it back.

Say these out loud at the start of the interview. They answer most edge cases before you write any code. Can you ack a waiting task? No, only a reserved one. Can a done task fail? No. Can a task be reserved twice at once? No, a reserve needs a waiting task.

The candidate who failed this round missed one rule, the place a failed task goes back to (1 report). A state table turns the edge cases into a list you can check, instead of something you remember under time pressure.

A table also makes a good test plan. Every arrow in the figure is a test that the move works. Every missing arrow is a test that the move is refused.

The function next_state in the editor answers one question: from this state, on this event, where does a task go? Write it as a lookup in a dict of the four allowed moves.

Part 1 done
Part 2 of 6about 22 min
Failures and retries

A worker can crash after the work and before the ack

Here is the failure that shapes everything in this part. Worker w1 reserves a task that charges a customer $30. It charges the card. Then, before it can send the ack, its machine restarts.

The queue sees a reserved task and a worker that went quiet. It can't tell which of these happened:

  • w1 crashed before it charged the card.
  • w1 charged the card, then crashed before the ack.

The safe choice is to run the task again. A lost task is a bug nobody sees. So a queue that retries delivers each task at least once, and sometimes more than once.

That moves part of the job to the worker. Amazon's SQS guide says it directly: design your applications to be idempotent, so that handling the same message twice does no harm. An operation is idempotent when doing it twice leaves the same result as doing it once.

The usual way is an idempotency key. The task id travels with the work, and whatever applies the result remembers the ids it has applied. A second copy of the same id is skipped.

Predict

Deliveries: (pay-1, 30), (pay-2, 50), (pay-1, 30). pay-1 was delivered twice. What total should the worker apply?

Pick an answer above to see the rest

A failed task goes back in its original place

When a task fails, it goes back to waiting. But where in the line?

One candidate's report gives the rule: a task put back in the queue keeps the place of its original enqueue time. That candidate missed it, the unit tests didn't all pass, and the round was lost (1 report).

a, b and c were enqueued in that order. w2 holds b, and a fails.
right
ac
wrong
ca

a was enqueued before c, so it goes back ahead of c. Appended at the back, it would wait behind newer work.

A deque can only add at its two ends, so it can't do this. Appending sends a to the back. Adding at the front looks right with one failure and breaks with two. If a and b both fail, with b first, then a must still go before b.

The fix is to stop thinking of the line as arrival order. Give each task a number when it's first enqueued: 0, 1, 2, and so on. Keep the waiting tasks in a heap keyed by that number. A heap always gives you its smallest item, so the oldest waiting task comes out first. Putting a task back is one push with the number it already has.

A heap push and pop each cost O(log n), and the smallest item is heap[0]. If heaps are new to you, the heaps lesson builds one from a plain list.

ReadyLine in the editor is the waiting line inside the work queue, kept as a heap of (enqueue number, task id). Its enqueue and take work. Write put_back, which puts a failed task back by its original enqueue number.

Count the failures, and stop at max_attempts

A task that fails every time would bounce between waiting and reserved forever. A bad input, such as a corrupt file, never gets better on a retry. So the queue counts each task's failed attempts and gives up at a limit, max_attempts.

Say exactly what the limit means before you code it. In the practice problem, max_attempts=3 means a task may be tried three times. The third failure is the last, so it sends the task to the dead-letter queue.

FailureCountWith max_attempts=3
first1back to waiting
second2back to waiting
third3dead

The test is failures >= max_attempts. With >, the task gets a fourth try. That off-by-one is easy to write and easy to miss, because every test where the task succeeds still passes.

Two more details:

  • Each task has its own count. A dict from task id to failures does it.
  • max_attempts below 1 makes no sense, since a task must be tried at least once. Raise ValueError in the constructor.

The dead-letter queue, or DLQ, is just a list of the dead task ids, in the order they died. The task isn't deleted. It's set aside, so a person can look at why it failed.

Predict

max_attempts=2. Task a fails, task b fails, then task a fails again. Which tasks are dead?

Pick an answer above to see the rest

The dead-letter queue holds tasks for a person to fix

A task lands in the dead-letter queue because it failed every attempt. Most of the time that means a bug or bad data, not bad luck. So the dead-letter queue is a to-do list for a person.

What happens next, in a real system:

  1. An alert fires when the dead-letter queue grows. Nobody reads a list they don't know about.
  2. Someone looks at the dead tasks, and the error each one raised, and finds the cause.
  3. They fix the bug, and redrive the tasks: send them back to the queue with fresh attempts.

A redrive must reset the failure count. A task that comes back with 3 failures and max_attempts=3 dies on its very next failure, with no real retry.

Leave the tasks that weren't fixed where they are, in their order. They are still a record of what went wrong.

There's a classic Python bug waiting in this code. If you loop over a list and remove items from it in the same loop, the loop skips the item after each one you remove. Here's why: after a remove, every later item moves up one place, and the loop's position moves on past the item that just slid into the empty spot. Build a new list instead, and assign it back with dead[:] = ..., so the caller's list changes too.

Predict

dead is [a, b, c, d]. You loop over it and remove each task in {b, c}. What is left?

Pick an answer above to see the rest

Find the bug: a retry that goes to the back

Here is levels 1 and 2 of the work queue, as many candidates first write it. Enqueue, reserve and the holder check all work. The dead-letter queue works too.

The bug is the one from the report: a failed task goes behind tasks that were enqueued after it (1 report). In the example, a, b and c are enqueued, w1 takes a, w2 takes b, and a fails. The next reserve should give a. This code gives c.

It's an easy bug to write, because it feels natural. The task is being enqueued again, so it gets the next number, like any new task. But a retry isn't a new task. Its place in line was decided when it first arrived.

In the editor, WorkQueue hands out c before the failed a. Run it, find the line in fail that gives a its new place, and fix it.

Watch · 6 min

From his Cambridge distributed systems course. From 4:25 a like is counted twice: the acknowledgment is lost, so the client sends the update again. From 8:09 the fix is an idempotent update, like adding to a set instead of adding 1 to a counter. A task that runs again after a crash before its ack needs the same property.

Distributed Systems 5.1: Replication · Martin Kleppmann · Oct 2020YouTube
Part 2 done
Part 3 of 6about 24 min
Leases and time

Pass the clock in, so a test can move time

Part 3 brings time into the queue. Before you write any of it, decide where the time comes from.

If the class calls time.monotonic() itself, a test of a 30-second timeout has to sleep for 30 seconds. Tests get slow, and a busy machine makes them flaky. So pass a clock in: a function that returns the current time. Production passes time.monotonic. A test passes a fake clock and sets the time by hand.

class FakeClock:
    def __init__(self):
        self.now = 0

    def __call__(self):
        return self.now


clock = FakeClock()
print(clock())
clock.now = 12
print(clock())
0
12

The practice problem's WorkQueue(..., clock=time.monotonic) works this way, and every test in it moves the clock by hand. Use time.monotonic, not time.time, for the real clock: the wall clock can jump backward when the machine syncs its time, and a lease must never get longer by accident.

Now the first rule with time in it. A reservation made at time t, with a timeout of 10, is held while t <= now < t + 10. The start is in and the end is out. So at exactly t + 10 it's over.

w1 reserves a at 0, with a visibility timeout of 10Interactive
0123456789101112
w1 holds a
● the start is in. ○ the end is out.
0 <= 10 < 10 is false, so at 10 it's gone.

Slide now. At 9 w1 still holds a. At 10 it doesn't. A timeout of None never ends, which is the queue of part 1.

The function lease_live in the editor answers whether a reservation is still held at now. Write it with the half-open rule, and let a timeout of None mean forever.

A visibility timeout turns a reservation into a lease

Part 2 had a hole. A worker that crashes never calls fail, so its task stays reserved forever. Nobody else can take it.

A prep guide's page on OpenAI mentions a queue with visibility timeouts (1 source). That's the fix, and it's how Amazon SQS works. A reserved task is hidden, or invisible, for a fixed time. If the worker doesn't ack before the time is up, the task becomes visible again, and another worker can take it.

So a reservation is really a lease: a hold on the task that ends by itself at a deadline, reserved_at + visibility_timeout. When the deadline passes:

  • the holder no longer holds the task, so its ack or fail returns False
  • the task goes back to waiting, in its original place
  • the timeout counts as a failed attempt, so a task that keeps timing out reaches the dead-letter queue

That last point matters. A task that crashes its worker every time, say one that runs out of memory, never calls fail. Without counting timeouts, it would loop forever.

When several leases have ended, handle them in deadline order. The order decides which task dies first, so it decides the order of dead_letters().

Predict

The leases are a until 12, b until 10 and c until 30. At time 12, which leases have ended, in order?

Pick an answer above to see the rest

Check the leases on every call, not on a timer

When does the queue notice that a lease ended? The first idea is a background thread that wakes up every second. That brings threads and locks into a 60-minute interview, and it still notices up to a second late.

There's a simpler way. The queue only has to be right when someone asks it something. So every public method starts by bringing the leases up to date with the clock: end every lease whose deadline has passed, then answer. This is lazy expiry. Nothing happens between calls, and nothing needs to.

The rule is every public method, with no exceptions. reserve must check, or it hides a task that's free again. status must check, or it reports a dead lease as reserved. And ack must check, or a worker whose lease ended can still finish a task another worker may be running.

That last one is the bug in the editor. w1 reserves a at 0, with a timeout of 10. Nobody calls reserve after that. At 12, w1 sends its ack. The lease is still in self.leases, because only reserve cleans them up, so the ack wins.

Why does a late ack matter if the work got done? Because the queue has already decided the work wasn't done. In a real system, another worker could have the task by now, and both would write a result. The queue has to give one answer about who holds a task, and the clock decides it.

In the editor, WorkQueue lets w1's late ack count. It keeps waiting as a plain list, as the early steps did, to stay short, so leave that alone: the bug is in the leases. Find the method that reads the leases without bringing them up to date first, and fix it.

A heap of deadlines finds the next lease to end

Checking the leases on every call is only cheap if each check is cheap. Scanning every lease costs O(n) per call, and a queue with 100,000 tasks in flight answers thousands of calls a second.

A heap of deadlines fixes that. Push (deadline, lease number, task id) when a task is reserved. The lease that ends soonest is always heap[0], so a check looks at one entry, and pops only the leases that really ended.

There's a catch. A heap can't remove an entry from the middle. When w1 acks a before its deadline, a's entry stays in the heap. Later, a might even be reserved again, with a new entry. When the old entry reaches the top, it must not end the new lease.

The fix is a lease number. Every reservation gets a new number from a counter, and the queue remembers the live number for each reserved task. When an entry is popped, it counts only if its number is still the task's live number. Otherwise it's stale, and you drop it. This is the lazy delete from the heaps lesson.

The deadline heap at 12. a now holds lease 2.
heap entries
deadlineleasetask1100a2121b3152a

Entry 1 is stale: a's live lease is 2, not 0, so it's dropped. Entry 2 ends b's lease now. Entry 3 is a's live lease and stays.

Use the number, not the worker's name. The same worker can lose a lease and reserve the same task again, and its name alone would make the old entry look live.

The function pop_ended in the editor gets the deadline heap and current, each reserved task's live lease number. Write it, so it pops every entry that is due and skips the stale ones.

A cooldown counts from the failure

One candidate's report adds a cooldown: a task waits a while after it's preempted before it can run again, and you work out from the preempt timestamp when the cooldown ends (1 report). The practice problem gives each task a cooldown and applies it after every failure, from fail or from a timeout.

The rule: a task that fails at time t is ready again at t + cooldown.

a, with cooldown 5, reserved at 0 and failed at 3
0 + 5, the wrong rule
reserved
cooling ready at 8
038
seconds

Count from the failure, not from the reservation. Counted from the reserve at 0, a would be ready at 5, while it has only cooled for 2.

For a timeout, the failure time is the deadline, not the moment the queue notices. With lazy expiry the queue might notice at 12 a lease that ended at 10. The task failed at 10, so with cooldown 4 it's ready at 14.

The cooling tasks need their own heap, keyed by ready_at, because they become ready in that order. When a task's cooldown ends, it moves to the ready heap, keyed by its enqueue number again. Two heaps, two orders: when a task can go, and which task goes first.

The function release in the editor moves cooled tasks from the cooling heap to the ready heap. Write it, so every task whose ready_at has come moves over, keyed by its enqueue number.

Watch · 4 min

From 4:01 a failure detector is a timeout: no answer in time, so the node must have crashed. From 5:10 why that can be wrong, since the message or its answer may be lost or delayed, or the node only slow. A lease that runs out makes the same guess about a worker, which is how a slow worker can still finish a task someone else now holds.

Distributed Systems 2.4: Fault tolerance · Martin Kleppmann · Oct 2020YouTube
Part 3 done
Part 4 of 6about 14 min
Tasks that wait on others

A task can wait for other tasks to finish

In two reports, the second part of the round added dependencies between tasks (2 reports). One candidate solved part one and then ran out of time debugging part two (1 report). So plan this part before you need it.

Here's a running example: a pipeline for an uploaded photo.

Each arrow runs from a task to a task that waits on it
fetchparsethumbindex

index can't run until both parse and thumb are done. "Done" means acked. A dependency that is only reserved, or one that failed and is waiting to retry, still blocks.

Don't check every task's dependencies on every reserve. Keep two things instead, as Kahn's algorithm does in the topological sort lesson:

  • blocked: for each task, how many of its dependencies aren't done yet
  • dependents: for each task, the tasks that wait on it

When a task is acked, go through its dependents and lower each count by one. A task whose count reaches 0 is free, and it joins the ready heap with its own enqueue number. So once it's free, it takes its place among the waiting tasks by when it was enqueued, not by when it was freed.

Predict

fetch is acked, and then parse. thumb is still reserved. What is index's count?

Pick an answer above to see the rest

When a task dies, the tasks that wait on it die too

Say parse fails every attempt and goes to the dead-letter queue. It will never be done. So index, which waits on it, can never run. If the queue leaves index waiting, it waits forever, and nothing tells anyone.

The practice problem's rule: when a task dies, every task that depends on it, directly or through others, dies with it. They go into the dead-letter queue right after it, in enqueue order. That's a design choice, and it's the one to say out loud: a task that can never run should show up where people look.

To find them, walk the dependents map from the dead task. Keep a stack of tasks to visit and a set of tasks found. Pop a task, and for each task that waits on it, add it to the set and push it on the stack, unless it's already in the set. The set does two jobs. It lists each task once, though index can be reached from both parse and thumb. And it guarantees the walk stops.

Sort what you found by enqueue order at the end. The walk finds tasks in whatever order the map lists them, and the dead-letter queue needs an order you can test.

parse dies. Who goes with it?
fetchdoneparsedeadthumbindexpublish

thumb is fine: it waits only on fetch, which is done. index and publish both go.

The function doomed in the editor lists every task below a dead one. The stack and the set are set up for you. Fill in the loop that walks the dependents map.

Every dependency must already exist, so there's never a cycle

What should enqueue("index", depends_on=["parse", "thumb"]) do if thumb was never enqueued? You could wait for thumb to show up. But then a typo in an id makes index wait forever, with no error.

The practice problem raises ValueError instead. Every dependency must already be in the queue.

That rule has a bonus. A task can only depend on tasks enqueued before it. So the dependencies all point back in time, and a cycle, where a waits on b and b waits on a, can't happen. You never need cycle detection. Say that in the interview: it's the kind of reasoning that shows you see the whole design.

The other half of the rule is easy to get wrong: a call that raises must store nothing. Check every argument first, then change the state. If the code stores the task and then finds the bad dependency, half a task stays behind. Its id is in status, so a corrected retry of the same enqueue raises "already enqueued".

The order inside enqueue:

  1. Raise if the id was seen before.
  2. Raise if any dependency is unknown.
  3. If a dependency is already dead, the new task is dead at once, since it can never run.
  4. Otherwise store it as waiting, count its open dependencies, and register it with each one.

Step 3 is the practice problem's last rule, and it follows from the cascade: a task that joins after its dependency died would have died with it.

In the editor, WorkQueue has an enqueue that stores a task and its open dependencies. Write the checks at its top, so a bad call raises ValueError before anything is stored.

Part 4 done
Part 5 of 6about 13 min
The worked example

A worked example: clarify, then name the state

Here is the full problem, solved the way you'd do it in the room. Spend the first minutes asking, and say the answer you'll assume if the interviewer shrugs:

  • What does a reserve return when nothing is ready? None.
  • Who may ack or fail a task? Only its holder, and only while the lease is live. Others get False.
  • Where does a failed task go? Back in its original place.
  • What does max_attempts=3 mean? Three tries. The third failure is the last.
  • Does a timeout count as a failure? Yes, at its deadline.
  • Time? An injected clock.
  • One thread? Yes for now. A lock is a follow-up.

Then name the state, one field per job:

FieldHoldsWhy
orderid to enqueue numbera task's place, forever
stateid to waiting, reserved, done or deadstatus and every check
failuresid to failed attemptsthe dead-letter limit
holderid to (worker, lease number)who may ack, and which heap entry is live
readyheap of (order, id)which task goes next
coolingheap of (ready_at, order, id)when a failed task may go again
leasesheap of (deadline, lease number, id)which lease ends next
deadlist of idsdead_letters()

The heart of the class is one private method that every public method calls first. It ends every lease whose deadline has passed, calling the failure handler at the deadline. Then it moves every cooled task to ready. The order of those two steps matters. A lease that ends at 10, with no cooldown, makes its task ready at 10. If you release the cooling tasks first, that task waits until the next call.

WorkQueue in the editor is the timed part of the queue: three heaps, the holders, and _failed, which starts a task's cooldown. Write _tick, the method every public call runs first.

Trace the reported trap, then write the test that catches it

One candidate lost the round on one rule, with the tests in front of them (1 report). So when you finish a level, trace it by hand with a small case, out loud, before you run anything.

Here's the trace for the retry rule. Three tasks, two workers:

StepCallWaiting, in orderReserved
1enqueue a, b, ca, b, c
2reserve("w1") gives ab, ca by w1
3reserve("w2") gives bca by w1, b by w2
4fail("w1", "a")a, cb by w2
5reserve("w3") gives ac

Step 4 is the trap. A version that appends a gets c at step 5.

Then turn the trace into a test. A good test for this rule needs a task enqueued after the failed one to still be waiting. With only a and b, there's nothing for a to wrongly fall behind, and the broken version passes. This is the habit that proves a test: break the code on purpose and check that the test fails. The practice problem's tests were checked this way, against fourteen broken versions.

Predict

A test enqueues a and b, reserves both, fails a, and checks that the next reserve gives a. Does it catch a queue that puts a failed task at the back?

Pick an answer above to see the rest

Test it against a slow version that is too simple to be wrong

The fast queue has three heaps, lease numbers and stale entries. Each is a place for a bug. A good way to test it is to compare it with a brute-force version: the same rules, written as plainly as possible, with no attempt at speed.

The brute-force queue keeps one list of tasks in enqueue order, each a dict with its state, its ready_at and its dependencies. A reserve scans the list from the start and takes the first task that is waiting, has cooled down, and has every dependency done. There's no heap to get out of order and no stale entry to skip.

In the editor, write brute_reserve, the slow reserve over a plain list of task dicts in enqueue order. It takes the first task that may go now and marks it reserved.

Drive both queues with the same random calls, and compare after every call

Once the slow queue has all its methods, run it and the fast one with the same random run of calls, with a fake clock that moves forward a random amount between calls, and compare what both return after every call. That tries orders nobody would write by hand, such as a lease that ends on the tick a dependency is acked.

Keep the numbers small: a handful of tasks, two or three workers, max_attempts of 2, a timeout of a few ticks. Small numbers make the edges come up often. Fix the random seed, so a failure comes back when you rerun it.

In an interview you won't have time to write it all. Saying you'd do it, and why, still counts.

Part 5 done
Part 6 of 6about 17 min
Follow-ups

What interviewers ask next

Once the levels pass, expect questions about the real system behind the class. The reports name the parts and the second-part dependencies. The questions below are the ones the design itself raises, so be ready for them:

  • How long should a lease be? And what about a task that takes longer?
  • A worker's lease ran out, but it's still running. What stops it from writing a stale result?
  • What if the queue itself crashes?
  • What about priorities?
  • Many workers on many threads? Put one lock around each public method. Every call reads and writes the same heaps, so it's all or nothing. A lock per task doesn't help, because reserve has to look at all of them.

Start with the lease length. Too short, and slow tasks time out while they're still working, so they run twice and use up attempts they never failed. Too long, and a crashed worker's task sits hidden for that long before anyone retries it.

The way out is a heartbeat. Set a short timeout, and let a worker that's still busy extend its lease every so often. Amazon's SQS guide recommends this for long jobs: a heartbeat that keeps extending the visibility timeout until the work is done. A crashed worker stops sending heartbeats, so its lease ends soon after the crash.

Two rules keep heartbeats safe. Only the holder can extend. And a lease that has already ended can't be brought back, because by then the task may belong to someone else.

The batch inference lesson shows the same leases and heartbeats in a system design, with a worker that dies partway through a long job.

The function extend in the editor is a heartbeat. Write it, so the holder of a live lease moves its deadline to now + timeout, and every other call returns False.

A fencing token stops a worker whose lease ran out

Here's the follow-up that catches most candidates. w1 reserves a. Its machine freezes for 40 seconds, longer than the lease. The lease ends, and w2 takes a and writes its result. Then w1 wakes up and, not knowing any time passed, writes its own result over w2's.

The queue refused w1's ack, but the ack comes after the write. The queue can't stop a write to some other system. That system has to stop it.

The fix is a fencing token. The lease number already grows with every reservation, so hand it to the worker with the task. The worker sends it with every write. The store where results go remembers the highest token it has seen for each key and refuses a write with a lower one. w2's lease is newer, so its token is higher, and w1's late write loses.

Predict

The store has seen token 2 for key a. Then a write with token 1 arrives, and then one with token 2 again. What does the store accept?

Pick an answer above to see the rest

If the queue itself crashes, rebuild it from a log

Your queue lives in memory. If its process dies, every task in it is gone, and that's worse than any one worker crashing.

The usual answer is a log: before the queue changes anything, it appends a line describing the change to a file, and flushes it to disk. Enqueue, reserve, ack and fail each write one line. After a crash, the new process reads the log from the start and applies each line in order, which rebuilds the state.

One choice to make on purpose: what about tasks that were reserved when the queue crashed? Their leases lived in memory, and the clock has moved on since. The safe choice is to treat every one of them as waiting again. If the worker was still running, it'll do the work a second time, which is fine, because the work is idempotent. If the worker died with the queue, the task would otherwise be lost.

A log grows forever. So every so often, the queue writes a snapshot of its whole state and starts a new log after it. A restart reads the newest snapshot, then only the log since it.

Real systems often hand this whole problem to a database or a message broker. Saying so is fine. But know what they do underneath, because "it's in the database" invites the next question: what happens to a reserved task when the database fails over?

The function replay in the editor rebuilds each task's state from the log. Write it, so it applies every event in order and then sends every task still reserved back to waiting.

Priorities go in front of the enqueue number

"Some tasks are urgent. How would you add priorities?" This one is quick if you built the ready heap on a key.

The heap already orders by a tuple: (enqueue number, task id). Put the priority in front: (-priority, enqueue number, task id). Python compares tuples one item at a time, so the priority decides first, and the enqueue number breaks ties. The minus sign makes a higher priority come out first from a min-heap.

Then say what it costs. A low-priority task can wait forever while urgent tasks keep coming. That's called starvation. The usual fix is aging: a task's priority rises the longer it waits. And a retried task keeps its priority and its enqueue number, for the same reason it kept its place in part 2.

Predict

Waiting: a with priority 1, b with priority 5, c with priority 5, enqueued in that order. Which goes first?

Pick an answer above to see the rest

Practice

Sources (3)
  1. Amazon SQS visibility timeout · Amazon SQS Developer Guide (undated page, read 2026-11-06) · Nov 6, 2026
    “Implement a heartbeat mechanism to periodically extend the visibility timeout, ensuring the message remains invisible until processing is complete.”
  2. Amazon SQS at-least-once delivery · Amazon SQS Developer Guide (undated page, read 2026-11-06) · Nov 6, 2026
    “Design your applications to be idempotent (they should not be affected adversely when processing the same message more than once).”
  3. heapq: Heap queue algorithm · Python 3.12 documentation · Oct 26, 2026
    “Removing the entry or changing its priority is more difficult because it would break the heap structure invariants.”