01C.4 Deadlocks, Livelock and Starvation

FoundationsLesson 4 of 720,114 words10 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

The worst concurrency bugs make no noise. A worker that never returns, a request that hangs at 0 % CPU, an agent run that sits for six hours with an empty log, a "fast" health check that cannot get a thread: nothing crashes, nothing raises, and the dashboards look calm until a customer complains. These are the three liveness failures: deadlock (everyone waits for someone else, forever), livelock (everyone is busy, nobody makes progress) and starvation (the system as a whole works, but one party never gets its turn). 01C.3 was about safety (the wrong answer); this lesson is about liveness (no answer at all). You will build each failure on purpose, using only the standard library, watch it happen under a timeout so your terminal never really hangs, learn the four conditions that make a deadlock possible, learn to find a stuck program from the outside and from the inside (including a wait-for-graph detector you write yourself), and learn the prevention toolbox: lock ordering, timeouts, hierarchies, and designs that need no locks at all. The last parts bring it back to AI services: LLM-client pools exhausted by nested calls, agents waiting on each other, and rate limiters stacked in the wrong order.

What you'll learn

  • What a deadlock is, with the one-lane-bridge analogy, and the four Coffman conditions (mutual exclusion, hold and wait, no preemption, circular wait) that must all hold, each paired with the prevention that breaks it
  • The difference between deadlock, livelock, starvation, a lost wake-up and plain slowness, and how to tell them apart from the outside (CPU use is the first clue)
  • Classic reproductions in running code: opposite lock order, a self-deadlock on a non-reentrant Lock, dining philosophers, a lost wake-up on a Condition
  • Deadlocks that are not "two locks": a full bounded queue, join() without task_done(), a thread pool whose tasks wait for tasks in the same pool, fork() with a held lock, multiprocessing.Queue and subprocess pipes, and the asyncio versions (tasks awaiting each other, a non-reentrant asyncio.Lock, a future nobody resolves)
  • How databases deadlock, how they detect and break it (PostgreSQL, MySQL/InnoDB, SQLite), and why you retry; and what is different when the deadlock spans machines
  • Detection: faulthandler.dump_traceback_later, py-spy dump, sys._current_frames, threading.enumerate, a heartbeat watchdog, and a wait-for-graph detector written in about 50 lines
  • Prevention: global lock ordering, acquire(timeout=), try-lock with jittered backoff, a lock hierarchy that raises on violation, one lock per invariant, never holding a lock across I/O or callbacks, and message-passing designs
  • Livelock: polite threads that retry in lockstep, and the randomized back-off that cures it
  • Starvation: writer starvation in naive read-write locks, unfair locks and barging, priority inversion (the Mars Pathfinder story told correctly), thread-pool starvation, event-loop starvation, a fast producer starving consumers, unbounded retry loops, FIFO versus unfair locks, fair semaphores and aging
  • AI-service cases: nested LLM calls exhausting a client pool, agent loops waiting on each other, tool calls that re-enter the agent, and semaphore versus rate-limiter ordering

What you don't need

  • An operating-systems course. Every term is explained in plain words first.
  • To have read the whole of 01C.3, but you should know what a Lock is for. 01C.3 §7.2 covers Lock and RLock basics; this lesson assumes them and shows what goes wrong.
  • Any LLM, API or provider. Every example is pure Python, and the "AI" examples use a fake model (asyncio.sleep).

Setup

No API key needed, nothing to install: every example uses only the standard library (threading, queue, concurrent.futures, multiprocessing, subprocess, asyncio, sqlite3, faulthandler). You need Python 3.11 or newer. Where a feature needs a newer version (asyncio.format_call_graph and the 3.14 introspection tools need 3.14; Queue.shutdown needs 3.13) the text says so. Inside a uv project from 01B.1 use uv run python file.py; otherwise python3 file.py works.

bash
python3 --version
# Is this a free-threaded build? (3.13+ only; True means the GIL is on, which is the normal case)
python3 -c "import sys; print(sys._is_gil_enabled())"

All Output: blocks in this lesson were produced on Python 3.14.6 (the normal build, GIL enabled) on macOS. Every deadlock demo is bounded by a timeout so the script ends by itself; each says what the unbounded version would do. Orderings and outcomes are deterministic because the demos force the unlucky schedule with a threading.Barrier instead of hoping for it. A few numbers (how often a lock hog wins, a faulthandler dump with paths and thread ids) depend on the machine and are labelled illustrative. Multi-process examples use if __name__ == "__main__":, which is mandatory on macOS and Windows.


What you must be able to do after this lesson#

  • Explain what a deadlock is and name the four Coffman conditions
  • Tell deadlock, livelock, starvation and slowness apart
  • Reproduce and fix an opposite-lock-order deadlock
  • Find a hung program with faulthandler or py-spy dump
  • Prevent deadlocks with lock ordering and acquire timeouts
  • Explain why holding a lock across I/O is dangerous

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The worker is hung, CPU is 0 %, nothing in the logs" Part 1 and Part 5
"Always take the locks in the same order" 2.1 and 6.2
"It deadlocks only under load" 3.2 and 9.1
"Our ThreadPoolExecutor is stuck" 3.2
"The child process hangs after fork" 3.3
"join() never returns" 3.1, 3.4
"asyncio can't deadlock, it's single-threaded" 3.5
"Postgres killed my transaction: deadlock detected" Part 4
"The CPU is at 100 % but nothing is happening" Part 7
"The health check times out while the workers are busy" 8.5
"Priority inversion (Mars Pathfinder)" 8.4
"Our agents wait on each other" 9.2

Part 1: What a deadlock is#

1.1 The one-lane bridge#

Two cars meet in the middle of a one-lane bridge, nose to nose. Each driver is waiting for the other to reverse. Neither will, because each is holding the bit of bridge they are on while waiting for the bit the other holds. No one is broken. Every driver is behaving reasonably. The system as a whole is stuck forever.

A deadlock is exactly that: a set of threads (or processes, tasks, transactions) in which each member holds something and waits for something held by another member, so none can ever proceed. The word "forever" matters: a deadlock does not clear up by itself. Only an outside force (a timeout, a database's deadlock detector, a human killing the process) breaks it.

Here is the smallest software version, drawn as a wait-for graph: circles are threads, boxes are locks, a solid arrow means "holds", a dotted arrow means "is waiting for".

flowchart LR
    TA(["Thread A"]) -- "holds" --> L1["cache lock"]
    TB(["Thread B"]) -- "holds" --> L2["budget lock"]
    TA -. "waits for" .-> L2
    TB -. "waits for" .-> L1

Follow the arrows: A holds cache and waits for budget; B holds budget and waits for cache. The path A → budget → B → cache → A is a closed loop. A cycle in the wait-for graph is a deadlock (when each lock has a single owner and each thread waits for one lock at a time, which is the case for ordinary locks). Part 5 turns that sentence into a working detector.

1.2 The four Coffman conditions#

In 1971 Coffman, Elphick and Shoshani published "System Deadlocks" (ACM Computing Surveys, vol. 3 no. 2, pp. 67-78), which stated the four conditions that must all hold at the same moment for a deadlock to be possible. They are now called the Coffman conditions:

# Condition Plain meaning Software example
1 Mutual exclusion A resource can be used by only one party at a time A Lock, a database row lock, a connection checked out of a pool, a file opened exclusively
2 Hold and wait A party holds one resource while waiting for another Thread takes the cache lock and, still holding it, asks for the budget lock
3 No preemption A resource cannot be taken away; only its holder can release it Python gives you no way to force a thread to drop a Lock (which is why the database case, where the engine rolls a transaction back, is the exception)
4 Circular wait There is a cycle: A waits for B, B waits for C, ..., Z waits for A The loop in the diagram above
flowchart TD
    S["Four conditions"] --> M["1. Mutual exclusion"]
    S --> H["2. Hold and wait"]
    S --> N["3. No preemption"]
    S --> C["4. Circular wait"]
    M --> D{"all four?"}
    H --> D
    N --> D
    C --> D
    D -- "yes" --> DL["Deadlock is possible"]
    D -- "no, break any one" --> OK["Deadlock is impossible"]

The power of this list is that it is a checklist for prevention: if you can make any one condition false, deadlock is impossible. Each prevention technique in Part 6 is "break condition N":

Break... By... Cost
Mutual exclusion Not sharing: give each thread its own copy (confinement), use immutable data, use lock-free structures or message passing Needs a redesign; not all resources can be duplicated (a physical GPU, a rate limit)
Hold and wait Take everything you need at once, or hold nothing while you wait (release before waiting, never hold a lock across I/O) Lower concurrency; you must know the full set up front
No preemption acquire(timeout=...): if you cannot get the second resource, release the first and start over; databases abort a victim transaction You must be able to roll back or retry; livelock risk (Part 7)
Circular wait A global lock order (always lock A before B) Needs discipline across the whole codebase; the cheapest and most common cure

1.3 Deadlock, livelock, starvation and their look-alikes#

When "it is stuck", you need to know which kind of stuck, because the cures differ. The first clue is CPU use (the same measurement you learned in 01C.1 §3.2):

Failure Everyone is... CPU while stuck Progress Clears by itself? Typical cause
Deadlock blocked, waiting for each other ~0 % none, for the involved parties Never Cycle of waits (Parts 1-6)
Livelock running, reacting to each other high none Only by luck Retry loops that mirror each other (Part 7)
Starvation some parties progress, one never does normal for others, yes; for the victim, none Maybe, when load drops Unfair scheduling or locking (Part 8)
Lost wake-up one thread waits for a signal already sent ~0 % none for that thread Never notify before wait (2.4)
Slow working, just a lot to do high or low steady Yes Not a bug; measure throughput
Blocked on I/O waiting for the network or disk ~0 % resumes when the I/O does Yes, if the I/O does No timeout on a call (01C.1 §4.2)

A rule of thumb for triage: 0 % CPU and no progress means "waiting on something" (deadlock, lost wake-up, a call without a timeout). High CPU and no progress means livelock or a runaway loop. Normal CPU and some requests never finishing means starvation or unfairness. The next sections make each of those concrete.


Part 2: Classic reproductions#

Every demo below forces the unlucky timing with a Barrier and uses acquire(timeout=...) so it ends. Remember what each timeout stands for: in production code that line would be a plain acquire() or with lock:, and the program would hang.

2.1 Opposite lock order: the classic#

An AI gateway keeps a prompt cache and a token budget, each with its own lock. One code path updates the cache and then charges the budget; another charges the budget and then writes the cache. Each path is individually correct. Together they are a deadlock waiting for the right moment.

python
# lock_order.py: the classic two-lock deadlock, made deterministic with a Barrier.
import threading

lock_cache = threading.Lock()   # protects the prompt cache
lock_budget = threading.Lock()  # protects the token budget
both_hold_one = threading.Barrier(2)
both_gave_up = threading.Barrier(2)   # keep holding until BOTH waits have timed out

def writer_a(report: list[str]) -> None:
    with lock_cache:                      # A takes cache first ...
        both_hold_one.wait()              # ... waits until B holds the other lock ...
        got = lock_budget.acquire(timeout=1.0)   # ... then wants budget
        report.append(f"A got budget: {got}")
        if got:
            lock_budget.release()
        both_gave_up.wait()

def writer_b(report: list[str]) -> None:
    with lock_budget:                     # B takes budget first (opposite order!)
        both_hold_one.wait()
        got = lock_cache.acquire(timeout=1.0)
        report.append(f"B got cache:  {got}")
        if got:
            lock_cache.release()
        both_gave_up.wait()

if __name__ == "__main__":
    report: list[str] = []
    ta = threading.Thread(target=writer_a, args=(report,), name="A")
    tb = threading.Thread(target=writer_b, args=(report,), name="B")
    ta.start(); tb.start()
    ta.join(); tb.join()
    for line in sorted(report):
        print(line)
    print("both timed out -> that was a real deadlock; with plain acquire() it would hang forever")
Output3 lines
A got budget: False
B got cache:  False
both timed out -> that was a real deadlock; with plain acquire() it would hang forever

Both threads reached their second acquire, found the lock held by the other, and gave up after one second. With a plain acquire() or with lock_budget: in that position, neither would ever return. The two Barriers in the code are the demonstration device: the first makes the unlucky interleaving certain; the second keeps each thread holding its lock until both have timed out (without it, the first timeout would release its lock and let the other thread through, which is what happens in real code when a timeout is the only thing breaking the cycle: the outcome becomes order-dependent).

Notice what the deadlock needed: two locks (mutual exclusion), each thread holding one while asking for another (hold and wait), no way to take a Lock from its owner (no preemption), and opposite acquisition orders (circular wait). Make the order the same in both functions and the cycle cannot form. That is 6.2.

2.2 The thread that waits for itself#

You do not need two threads. A non-reentrant lock deadlocks against its own owner:

python
# self_deadlock.py: a thread that waits for a lock it already holds.
import threading

lock = threading.Lock()

def refresh_cache() -> bool:
    with lock:                       # takes the lock ...
        return lookup_or_refill()

def lookup_or_refill() -> bool:
    # a helper that "also protects itself" with the same lock
    got = lock.acquire(timeout=0.5)  # plain acquire() here would hang forever
    if got:
        lock.release()
    return got

print("Lock    :", "re-acquired" if refresh_cache() else "TIMED OUT (self-deadlock)")

rlock = threading.RLock()

def refresh_cache_r() -> bool:
    with rlock:
        return lookup_or_refill_r()

def lookup_or_refill_r() -> bool:
    with rlock:                      # same thread: allowed, recursion level 2
        return True

print("RLock   :", "re-acquired" if refresh_cache_r() else "TIMED OUT")

# Sanity check on who may release a plain Lock: any thread.
lock2 = threading.Lock()
lock2.acquire()
t = threading.Thread(target=lock2.release)
t.start(); t.join()
print("Lock released by another thread:", not lock2.locked())
Output3 lines
Lock    : TIMED OUT (self-deadlock)
RLock   : re-acquired
Lock released by another thread: True

threading.Lock is not reentrant: the second acquire from the same thread blocks, because the lock is held, and the only thread that could release it is the one that is blocked. The Python docs describe RLock as the type that "may be acquired multiple times by the same thread", with an owner and a recursion level, and state that a reentrant lock "must be released by the thread that acquired it", whereas a plain Lock "can be called from any thread, not only the thread which has acquired the lock" (the last line of the output shows that too).

When is RLock the right answer? When a class has a public method that locks and then calls another public method that also locks (the pattern in the code above). The cleaner design is often to split each method into a public locking wrapper and a private _unlocked worker that assumes the lock is held; that makes the lock discipline explicit. 01C.3 §8.6 explains why reentrancy is a convenience, not a thread-safety guarantee. And RLock does not rescue you from the two-lock deadlock of 2.1; it only handles one thread re-entering one lock.

2.2b The thread that is interrupted by itself: signal handlers and finalizers#

A self-deadlock needs no second thread and no second function call in your own code. Python can run other code on your thread at almost any moment, in the middle of your critical section:

  • a signal handler (for example for SIGTERM, SIGUSR1 or a timer from signal.setitimer) runs on the main thread, between two bytecodes of whatever that thread was doing;
  • a __del__ method or a weakref callback runs on whichever thread happens to drop the last reference, including during garbage collection;
  • a logging call from either of those takes the logging module's own locks, which the interrupted code may already hold.

If the interrupted code holds a plain Lock and the handler takes the same lock, the thread waits for itself. It is one of the best-known Python-specific hangs, and it is intermittent: it needs the signal to land inside the critical section, so it passes every test and fails in production.

python
# signal_reentry.py: a signal handler that wants a lock its own thread already holds.
# POSIX only (signal.raise_signal with SIGUSR1). Bounded by a timeout so it ends.
import signal
import threading

lock = threading.Lock()
cache: dict[str, int] = {}

def on_signal(signum: int, frame) -> None:
    # Runs on the MAIN thread, between two bytecodes of whatever it was doing.
    got = lock.acquire(timeout=0.5)       # a plain acquire() here would hang the process forever
    print("handler got the lock:", got)
    if got:
        lock.release()

signal.signal(signal.SIGUSR1, on_signal)

with lock:                                # the main thread holds the lock ...
    cache["x"] = 1
    signal.raise_signal(signal.SIGUSR1)   # ... and a signal arrives on the same thread
    print("main thread resumed, still holding the lock:", lock.locked())
Output · POSIX; signal.raise_signal makes the unlucky timing deterministic2 lines
handler got the lock: False
main thread resumed, still holding the lock: True

With a plain acquire() the handler would never return and the main thread, which owns the lock, could never resume. The rules:

  1. Do not take locks in signal handlers or finalizers. Do the minimum: set a plain flag, or write a byte to a self-pipe (signal.set_wakeup_fd exists for this), or put() on a queue.SimpleQueue, whose C implementation the documentation calls reentrant and describes as appropriate for destructors such as __del__ and weakref callbacks (a CPython implementation detail). Let a normal thread do the real work.
  2. RLock helps only if the handler really is the same thread and the data is in a consistent state when the handler looks at it. Mid-update, it is not: you have traded a hang for a silent corruption.
  3. In asyncio, use loop.add_signal_handler, which runs the callback inside the event loop rather than at an arbitrary point, and keep the callback short.

01C.3 §7.5 shows the queue-and-owner-thread design that this rule leads to.

For an AI engineer: a SIGTERM handler that "gracefully flushes the batch" by taking the same lock the batching code holds is a classic way to make a service that will not shut down. Set a flag, let the worker finish its current item, and drain a queue.

2.3 Dining philosophers#

Dijkstra's dining philosophers (posed in 1965, retold by Hoare) is the textbook model of circular wait. Five philosophers sit round a table with five forks, one between each pair. To eat, a philosopher needs the fork on the left and the one on the right. If everyone picks up the left fork at the same moment, everyone holds one fork and waits for the one their neighbour holds: a five-party cycle.

In AI-service terms: five workers each need two of five shared resources (say, a GPU slot and a model-licence token, or two adjacent shard locks in a sharded cache) and each grabs "its own" first. The shape is identical.

python
# philosophers.py: dining philosophers, deadlocked and fixed.
import threading

N = 5

def dine(ordered: bool) -> list[str]:
    forks = [threading.Lock() for _ in range(N)]
    # Everyone sits down and picks up their first fork at the same moment.
    sat_down = threading.Barrier(N)
    gave_up = threading.Barrier(N)
    log: list[str] = []
    log_lock = threading.Lock()

    def philosopher(i: int) -> None:
        left, right = i, (i + 1) % N
        first, second = (min(left, right), max(left, right)) if ordered else (left, right)
        with forks[first]:
            if not ordered:
                sat_down.wait()                       # force the unlucky timing (everyone holds one fork)
            if forks[second].acquire(timeout=0.5):
                with log_lock:
                    log.append(f"philosopher {i} ate")
                forks[second].release()
            else:
                with log_lock:
                    log.append(f"philosopher {i} gave up (deadlock)")
            if not ordered:
                gave_up.wait()                        # hold the first fork until everyone has timed out

    threads = [threading.Thread(target=philosopher, args=(i,)) for i in range(N)]
    for t in threads: t.start()
    for t in threads: t.join()
    return sorted(log)

if __name__ == "__main__":
    print("naive (everyone takes left, then right):")
    for line in dine(ordered=False): print("  ", line)
    print("ordered (always take the lower-numbered fork first):")
    for line in dine(ordered=True): print("  ", line)
Output12 lines
naive (everyone takes left, then right):
   philosopher 0 gave up (deadlock)
   philosopher 1 gave up (deadlock)
   philosopher 2 gave up (deadlock)
   philosopher 3 gave up (deadlock)
   philosopher 4 gave up (deadlock)
ordered (always take the lower-numbered fork first):
   philosopher 0 ate
   philosopher 1 ate
   philosopher 2 ate
   philosopher 3 ate
   philosopher 4 ate

The fix in the second run is the resource hierarchy solution: number the forks and make everyone take the lower-numbered fork first. Philosopher 4 sits between fork 4 and fork 0 and therefore takes fork 0 first, which breaks the cycle: at least one philosopher can always get both forks. That single rule (impose a total order on the resources and acquire in ascending order) is the most important prevention technique in this lesson.

2.4 The lost wake-up#

Not every hang is a lock cycle. A lost wake-up is a thread waiting for a signal that has already been sent. Condition.notify() only wakes threads that are currently waiting; a notification with nobody waiting is forgotten.

python
# lost_wakeup.py: a Condition hang that is NOT a lock cycle: the notify happened before the wait.
import threading

cv = threading.Condition()
ready = False

def waiter_buggy() -> str:
    with cv:
        got = cv.wait(timeout=0.5)       # BUG: waits unconditionally
        return f"wait() returned {got}"

def waiter_correct() -> str:
    with cv:
        cv.wait_for(lambda: ready, timeout=0.5)   # checks the predicate first
        return f"wait_for() saw ready={ready}"

with cv:                                   # the producer is fast: it notifies first
    ready = True
    cv.notify_all()

print("buggy  :", waiter_buggy(), "(the wake-up was lost; a no-timeout wait() would hang forever)")
print("correct:", waiter_correct())
Output2 lines
buggy  : wait() returned False (the wake-up was lost; a no-timeout wait() would hang forever)
correct: wait_for() saw ready=True

The buggy waiter called wait() after the producer's notify_all(), so it sleeps until its timeout (a plain wait() would sleep forever, at ~0 % CPU). The correct pattern, from the official docs, is to check a predicate in a loop: wait_for(predicate) (or while not predicate(): cv.wait()) tests the shared state first and only sleeps if the condition is not yet true. The docs explain the loop is also needed because wait() "can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true". The signal is not the truth; the state is. 01C.3 §7.4 covers Condition in depth. An Event avoids this particular bug because it remembers that it was set.


Part 3: Deadlocks that are not "two locks"#

Deep-dive

Coffman's conditions say nothing about the word "lock". A resource is anything that is exclusive and that you wait for: a queue slot, a worker thread, a pipe buffer, a database row, a pool connection, a semaphore permit. The deadlocks below all follow the same recipe (exclusive resource, hold and wait, no preemption, circular wait) with a resource you may not think of as a lock.

3.1 Queues: a full queue, and a join() that never finishes#

A bounded queue.Queue(maxsize=N) is a pool of N slots. put() waits for a free slot; get() waits for an item. A pipeline of stages connected by bounded queues is a chain of waits, and a cycle in that chain is a deadlock. The simplest cycle is a stage that is both the only consumer and a producer of the same queue:

python
# queue_deadlocks.py: three ways a queue hangs a pipeline (each made safe with a timeout).
import queue
import threading

# 1. A stage that reads from and writes to the SAME bounded queue.
q: queue.Queue[int] = queue.Queue(maxsize=2)
q.put(1); q.put(2)                        # the queue is full

def stage() -> str:
    item = q.get()                        # takes one item ...
    try:
        q.put(item + 10)                  # ... puts one back: fine, there is room now
        q.put(item + 20, timeout=0.3)     # a SECOND put into a full queue nobody drains
    except queue.Full:
        return "stage blocked on put(): the queue is full and its only consumer is this very stage"
    return "no deadlock"

print("1.", stage())

# 2. join() waits for task_done(); a consumer that forgets (or crashes before) it.
jq: queue.Queue[str] = queue.Queue()
for name in ("a.pdf", "b.pdf", "c.pdf"):
    jq.put(name)

def forgetful_consumer() -> None:
    while True:
        jq.get()                          # BUG: no jq.task_done()

threading.Thread(target=forgetful_consumer, daemon=True).start()
joiner = threading.Thread(target=jq.join, daemon=True)
joiner.start()
joiner.join(timeout=0.5)
print("2. join() finished:", not joiner.is_alive(), "| unfinished_tasks =", jq.unfinished_tasks)

# 3. The same, with a consumer that crashes before task_done(): use try/finally.
cq: queue.Queue[str] = queue.Queue()
for name in ("a.pdf", "b.pdf", "c.pdf"):
    cq.put(name)

def careful_consumer() -> None:
    while True:
        item = cq.get()
        try:
            if item == "b.pdf":
                raise ValueError("corrupt PDF")
        except ValueError:
            pass
        finally:
            cq.task_done()                # always runs, so join() can finish

threading.Thread(target=careful_consumer, daemon=True).start()
cq.join()
print("3. join() finished with try/finally: unfinished_tasks =", cq.unfinished_tasks)
Output3 lines
1. stage blocked on put(): the queue is full and its only consumer is this very stage
2. join() finished: False | unfinished_tasks = 3
3. join() finished with try/finally: unfinished_tasks = 0

Read the three cases:

  1. The stage that feeds itself. The queue is full; the only thread that could make room is the one blocked on put(). This happens in real crawlers and agent loops: a worker pulls a URL, finds ten links, and pushes them back onto the same bounded queue. With a full queue every worker blocks on put() and nobody is left to get(). Fixes: use an unbounded queue for the feedback edge and bound the intake instead; push with put(timeout=...) or put_nowait and handle queue.Full (drop, spill to disk, or retry later); or use a separate queue for newly discovered work than for work in progress.
  2. join() without task_done(). Queue.join() "blocks until all items in the queue have been gotten and processed". An item counts as processed only when a consumer calls task_done() for it. The forgetful consumer drained the queue but never said so, so unfinished_tasks stays at 3 and join() waits forever. Calling task_done() more times than items raises ValueError, which at least fails loudly.
  3. The consumer that crashes before task_done(). An exception in the middle of processing skips the task_done() line and has the same effect as the forgetful consumer. Always put task_done() in a finally:. This is exactly the shape from 01B.4 §3.2, where asyncio.Queue has the same rule.

And a general rule about queues: every blocking put(), get() and join() in a long-lived service should have a timeout or a shutdown path. An unbounded wait is a deadlock you have not met yet. The backpressure logic of 01B.4 §3.3 (bounded queues) is correct; it just means you must make sure the cycle cannot close.

3.2 The pool that waits for itself#

ThreadPoolExecutor has a fixed number of worker threads. A task that submits another task to the same pool and then waits for its result holds a worker while waiting for a worker. Hold and wait, with the pool's workers as the exclusive resource. The official concurrent.futures documentation warns about exactly this ("Deadlocks can occur when the callable associated with a Future waits on the results of another Future") and shows a single-worker variant where a task submits to its own executor and calls .result().

Here is the realistic version: an "agent" task fans out sub-tasks onto the same pool.

python
# pool_deadlock.py: tasks that wait for other tasks submitted to the SAME pool.
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import threading

def leaf(n: int) -> int:
    return n * 2

def parent(pool: ThreadPoolExecutor, n: int, barrier: threading.Barrier, done: threading.Barrier) -> int | str:
    barrier.wait()                                  # make sure every worker is busy with a parent
    child = pool.submit(leaf, n)                    # queued behind the parents ...
    try:
        return child.result(timeout=1.0)            # ... and we block a worker waiting for it
    except TimeoutError:
        return "TIMEOUT"
    finally:
        done.wait()                                 # (demo only) all parents give up together

def run(workers: int, parents: int) -> str:
    barrier = threading.Barrier(parents)
    done = threading.Barrier(parents)
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futs = [pool.submit(parent, pool, i, barrier, done) for i in range(parents)]
        outcome = []
        for f in futs:
            try:
                outcome.append(f.result(timeout=5))
            except TimeoutError:
                outcome.append("TIMEOUT")
        return str(outcome)

print("2 workers, 2 parents  ->", run(2, 2))
print("3 workers, 2 parents  ->", run(3, 2))

# The fix by construction: two pools. Parents never share workers with leaves.
def run_two_pools() -> str:
    with ThreadPoolExecutor(max_workers=2, thread_name_prefix="parents") as outer, \
         ThreadPoolExecutor(max_workers=2, thread_name_prefix="leaves") as inner:
        def parent2(n: int) -> int:
            return inner.submit(leaf, n).result(timeout=5)
        return str([f.result() for f in [outer.submit(parent2, i) for i in range(4)]])

print("two pools, 4 parents  ->", run_two_pools())
Output3 lines
2 workers, 2 parents  -> ['TIMEOUT', 'TIMEOUT']
3 workers, 2 parents  -> [0, 2]
two pools, 4 parents  -> [0, 2, 4, 6]

With 2 workers and 2 parents, both workers are occupied by parents; each parent's child sits in the queue behind them; each parent waits for its child. With 3 workers there is one free worker to run the children, so everything finishes. That is the dangerous part: the code works in testing with a large pool and one request, and hangs in production when the pool is saturated. The probability of the deadlock rises with load. The third run shows the structural fix: parents and leaves use different pools, so a parent can never occupy the last worker a leaf needs.

Rules of thumb:

  • Never block a pool worker on a future from the same pool. If a task needs sub-results, either give sub-tasks their own pool, or do the sub-work inline in the same thread, or restructure so the parent returns and a callback (add_done_callback) continues the work.
  • Count the worst case. If one request can occupy P workers as parents, a pool of size P (or fewer, shared by concurrent requests) can deadlock. Size pools by the deepest nesting, not the average.
  • The default sizes are small on purpose. As of the Python 3.13 and 3.14 docs the default max_workers for ThreadPoolExecutor is min(32, (os.process_cpu_count() or 1) + 4); asyncio's default executor (used by asyncio.to_thread and loop.run_in_executor(None, ...)) is a ThreadPoolExecutor too. A deeply nested to_thread chain can therefore starve or deadlock the default executor.
  • Always wait with a timeout (future.result(timeout=...)). It converts a silent hang into a loud TimeoutError you can log and alert on.

The same structure appears in ProcessPoolExecutor (a worker process cannot wait for another task from the same pool) and in asyncio semaphores (9.1).

3.3 fork() with a held lock#

On Unix, os.fork() makes a copy of the whole process but only the calling thread survives in the child. A lock that another thread held at the moment of the fork is copied in its locked state, and the thread that would release it does not exist in the child. The child then deadlocks the first time it tries to take that lock. This is the best-known real-world cause of "my forked worker hangs at start-up": the lock is often hidden inside a library (a logging handler lock, a memory-allocator lock, an RNG lock, an HTTP connection pool).

text
 parent process                         child process (after fork)
 ----------------                       ---------------------------
 main thread  : calls fork()  ----->    main thread  : runs on
 worker thread: HOLDS lock              (worker thread does not exist)
                                        lock is copied as "locked"  --> nobody can ever release it
python
# fork_lock.py: fork() copies a lock that is held by a thread that does not exist in the child. POSIX only.
import os
import threading
import time
import warnings

lock = threading.Lock()
holding = threading.Event()
release = threading.Event()

def background_worker() -> None:
    with lock:                       # holds the lock while the main thread forks
        holding.set()
        release.wait()

threading.Thread(target=background_worker, daemon=True).start()
holding.wait()

r, w = os.pipe()
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    pid = os.fork()                  # Python 3.12+ warns here: the process has several threads
    if pid == 0:                     # ---- child ----
        got = lock.acquire(timeout=1.0)   # the owner thread was not copied: nobody will ever release it
        os.write(w, f"child: acquired={got}\n".encode())
        os._exit(0)
os.waitpid(pid, 0)
os.close(w)
print(os.read(r, 100).decode().strip())
print("parent warning categories:", sorted({c.category.__name__ for c in caught}))
release.set()
time.sleep(0.05)
print("parent: lock free again:", lock.acquire(timeout=1.0))
Output3 lines
child: acquired=False
parent warning categories: ['DeprecationWarning']
parent: lock free again: True

The child saw the lock held (acquired=False) although its owner was not copied. Python 3.12 added a DeprecationWarning that fires "if Python is able to detect that your process has multiple threads" when os.fork() is called, which is what the second output line shows. That warning is a direct signal that the situation above can occur.

What to do about it:

  • Do not use fork in a threaded program. multiprocessing offers three start methods: fork, spawn and forkserver. The 3.14 docs say fork "is no longer the default start method on any platform": on POSIX the default changed from fork to forkserver in Python 3.14, while spawn is the default on Windows and on macOS (since 3.8, because "the fork start method should be considered unsafe" there). Code that still needs fork must opt in with multiprocessing.get_context("fork"). Prefer spawn or forkserver for anything that touches threads, HTTP clients or loggers. More in 01C.7.
  • If you must fork, do it before you create threads, or re-initialize locks in the child with os.register_at_fork(...) (Python's own logging module does this for its handler locks).
  • Be suspicious of a worker that hangs only on Linux under fork and works on macOS or Windows: that is the signature.

3.4 Processes and pipes: join and wait in the wrong order#

Between processes the exclusive resource is the pipe buffer: a fixed-size kernel buffer (often 64 KiB on Linux, smaller on some systems). A writer blocks when it is full; a reader blocks when it is empty. If you wait for the writer to finish before you read, and the writer needs you to read before it can finish, that is a cycle.

Two documented cases, each shown with a timeout:

python
# mp_subprocess_hangs.py: two documented hangs between processes. Both are made safe with timeouts.
import multiprocessing as mp
import subprocess
import sys

def child_puts_big(q) -> None:
    q.put("x" * 5_000_000)          # far more than a pipe buffer holds

if __name__ == "__main__":
    # 1. join() before get() on a multiprocessing.Queue.
    q = mp.Queue()
    p = mp.Process(target=child_puts_big, args=(q,))
    p.start()
    p.join(timeout=1.0)
    print("1. child finished after join(timeout=1):", not p.is_alive())
    data = q.get()                  # the right order: drain first ...
    p.join()                        # ... then join
    print("   after draining the queue it exits with code", p.exitcode, "and got", len(data), "bytes")

    # 2. Popen.wait() with stdout=PIPE while the child writes more than the pipe holds.
    code = "import sys; sys.stdout.write('y' * 5_000_000)"
    proc = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE)
    try:
        proc.wait(timeout=1.0)
        print("2. wait() returned")
    except subprocess.TimeoutExpired:
        print("2. wait() timed out: child blocked writing to a full pipe nobody reads")
    out, _ = proc.communicate()     # communicate() reads while it waits
    print("   communicate() returned", len(out), "bytes, exit code", proc.returncode)
Output4 lines
1. child finished after join(timeout=1): False
   after draining the queue it exits with code 0 and got 5000000 bytes
2. wait() timed out: child blocked writing to a full pipe nobody reads
   communicate() returned 5000000 bytes, exit code 0
  1. multiprocessing.Queue and join(). The docs warn: if a child has put items on a queue, "that process will not terminate until all buffered items have been flushed to the pipe", so joining it before the queue is drained "may get a deadlock". The right order is drain first, join afterwards.
  2. subprocess.Popen.wait() with stdout=PIPE. The docs warn that wait() "will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that." In an AI service this is a Python process that shells out to ffmpeg, pdftotext or tesseract and captures its output: it works on the 1 KB test file and hangs on the 80 MB scan.

Both bugs are size-dependent: harmless with small data, fatal with big data. That makes them excellent candidates for "worked in the demo, hangs in production". Always use communicate() (or subprocess.run(..., capture_output=True, timeout=...)) rather than wait() plus pipes, and always give child processes a timeout.

3.5 Deadlocks in asyncio#

"asyncio is single-threaded, so it cannot deadlock" is false. A deadlock needs waiting, not threads, and await is waiting. With a single thread the failures are even simpler to cause, because there is only one thread to block.

python
# asyncio_deadlocks.py: deadlocks need no threads. Each case is bounded by wait_for so the script ends.
import asyncio
import os
import sys

async def two_tasks_wait_on_each_other() -> str:
    t1: asyncio.Task | None = None
    t2: asyncio.Task | None = None

    async def a() -> None:
        await asyncio.sleep(0)       # let both tasks exist
        await t2                     # A waits for B ...

    async def b() -> None:
        await asyncio.sleep(0)
        await t1                     # ... and B waits for A

    t1 = asyncio.create_task(a(), name="A")
    t2 = asyncio.create_task(b(), name="B")
    # asyncio.wait() with a timeout reports who is still pending and does NOT cancel anything.
    done, pending = await asyncio.wait({t1, t2}, timeout=0.3)
    if pending:
        # Do NOT call t1.cancel() here: on 3.14.6 cancelling a cycle of tasks recurses until
        # RecursionError, because each cancel() forwards to the task it is waiting on.
        # asyncio.format_call_graph(t1) would not help either: it recurses forever on a cycle (3.14.6).
        return "A and B await each other: nothing is runnable, nothing ever completes"
    return "finished"

async def self_deadlock_with_asyncio_lock() -> str:
    lock = asyncio.Lock()
    async def helper() -> None:
        async with lock:             # asyncio.Lock is NOT reentrant either
            pass
    async def caller() -> None:
        async with lock:
            await helper()
    try:
        await asyncio.wait_for(caller(), timeout=0.3)
    except TimeoutError:
        return "asyncio.Lock re-acquired by the same task: stuck"
    return "finished"

async def await_a_future_nobody_resolves() -> str:
    fut: asyncio.Future[str] = asyncio.get_running_loop().create_future()
    try:
        await asyncio.wait_for(fut, timeout=0.3)   # no one calls fut.set_result(...)
    except TimeoutError:
        return "future never resolved (the 'lost wake-up' of asyncio)"
    return "finished"

async def block_the_loop_waiting_for_the_loop() -> str:
    loop = asyncio.get_running_loop()
    async def inner() -> int:
        return 42
    # Sync code running ON the loop thread waits for a coroutine that needs the same loop thread to run.
    fut = asyncio.run_coroutine_threadsafe(inner(), loop)
    try:
        fut.result(timeout=0.3)                      # blocks the loop thread; inner() cannot start
    except TimeoutError:
        fut.cancel()
        return "run_coroutine_threadsafe(...).result() on the loop thread: the loop waited for itself"
    return "finished"

async def main() -> None:
    print("1.", await two_tasks_wait_on_each_other())
    print("2.", await self_deadlock_with_asyncio_lock())
    print("3.", await await_a_future_nobody_resolves())
    print("4.", await block_the_loop_waiting_for_the_loop())

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.run_until_complete(main())
    sys.stdout.flush()
    os._exit(0)   # skip asyncio.run()'s shutdown, which would cancel the cyclic tasks (see the warning above)
Output4 lines
1. A and B await each other: nothing is runnable, nothing ever completes
2. asyncio.Lock re-acquired by the same task: stuck
3. future never resolved (the 'lost wake-up' of asyncio)
4. run_coroutine_threadsafe(...).result() on the loop thread: the loop waited for itself
  1. Tasks awaiting each other. A awaits B, B awaits A. Neither is ever runnable again. (Awaiting a task that has already finished, or a task nobody else awaits, is fine; the cycle is what hurts.)
  2. A non-reentrant asyncio.Lock. The task holds the lock and calls a helper that takes the same lock. asyncio.Lock is not reentrant. The docs describe it as a mutex "for asyncio tasks" and it is also not thread-safe.
  3. A future nobody resolves. await fut where nobody calls set_result, set_exception or cancel. It is the asyncio flavour of the lost wake-up: the producer crashed, or took an error branch that forgot to resolve the future, or resolved a different future.
  4. The loop waiting for itself. Synchronous code running on the loop thread calls asyncio.run_coroutine_threadsafe(coro, loop).result(). The call parks the loop thread until the coroutine finishes, but the coroutine can only run on the loop thread. This one is easy to write by accident in a sync helper that "bridges" back into async code. It is a legitimate pattern only when called from a different thread. This is the deadlock version of the "blocking call inside the loop" from 01C.1 §4.5.

Two asyncio-specific points about surviving these:

  • Every await that can wait on something outside your control gets a timeout. async with asyncio.timeout(10): (3.11+) or asyncio.wait_for(...). Cancellation then unwinds the stuck task. See 01B.3 §3.5 and 01C.2 §6.1.
  • You cannot cancel your way out of case 1. On Python 3.14.6, calling cancel() on one of two tasks that await each other recurses until it raises RecursionError, because each cancel() forwards to the task it is waiting on. The same happens inside asyncio.run() shutdown, which cancels all remaining tasks. Treat a task cycle as a bug to prevent, not to clean up:
python
# cycle_cancel.py: what happens if you cancel a cycle of tasks (Python 3.14.6). Shown for information.
import asyncio, os, sys

async def main() -> None:
    t1 = t2 = None
    async def a():
        await asyncio.sleep(0); await t2
    async def b():
        await asyncio.sleep(0); await t1
    t1 = asyncio.create_task(a(), name="A")
    t2 = asyncio.create_task(b(), name="B")
    await asyncio.sleep(0.1)
    try:
        t1.cancel()
    except RecursionError as e:
        print("cancel() on a task cycle raised:", type(e).__name__)

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.run_until_complete(main())
    sys.stdout.flush(); os._exit(0)

Output (the demo exits with os._exit to skip the shutdown that would cancel the cycle again):

text
cancel() on a task cycle raised: RecursionError

3.6 The GIL does not prevent deadlocks#

A common misconception: "Python has a GIL, so only one thread runs at a time, so deadlocks are impossible." Every demo above ran on a normal GIL build and deadlocked. The Global Interpreter Lock serializes the execution of Python bytecode; it does not make your with lock_a: / with lock_b: sequence atomic, and it is released whenever a thread blocks on a lock, which is exactly when deadlocks happen. The GIL is also not a lock you can take, so it does not appear in your wait-for graph (01C.5 covers it fully).

On free-threaded builds (3.13t/3.14t, see 01C.5) nothing changes for your locks: the same ordering rules apply, and races that the GIL happened to hide (01C.3 §8.9) become more likely. If you add locks to fix those races, you also add edges to your lock-order graph.

3.7 Other waits that look like locks: join() while holding a lock, join cycles, dead holders#

Three more hangs are common enough to name. None of them involves two locks being taken in opposite orders.

python
# join_cases.py: waits that look like something else. Each is bounded by a timeout.
import threading

lock = threading.Lock()

def needs_lock() -> None:
    with lock:
        pass

# 1. join() while holding the lock the worker needs.
with lock:
    worker = threading.Thread(target=needs_lock)
    worker.start()
    worker.join(timeout=0.5)
    print("1. join with the lock held, finished:", not worker.is_alive())
worker.join()                               # lock released: the worker can now finish
print("   after releasing the lock, finished:", not worker.is_alive())

# 2. Two threads that join each other (a thread joining itself raises RuntimeError; a cycle just hangs).
threads: dict[str, threading.Thread] = {}
ready = threading.Barrier(3)
results: dict[str, bool] = {}
joined = threading.Barrier(2)               # neither thread exits before both have tried to join

def join_other_timed(me: str, other: str) -> None:
    ready.wait()
    threads[other].join(timeout=0.5)
    still_running = threads[other].is_alive()
    joined.wait()
    results[me] = still_running

threads["a"] = threading.Thread(target=join_other_timed, args=("a", "b"))
threads["b"] = threading.Thread(target=join_other_timed, args=("b", "a"))
for t in threads.values():
    t.start()
ready.wait()
for t in threads.values():
    t.join()
for me in sorted(results):
    print(f"2. {me} waited for the other; the other was still running:", results[me])

try:
    threading.current_thread().join()
except RuntimeError as exc:
    print("   self-join:", exc)

# 3. A holder that dies without releasing (no with / try-finally).
lock3 = threading.Lock()
def careless() -> None:
    lock3.acquire()
    raise ValueError("boom")                # lock3 is never released

threading.excepthook = lambda args: print("   holder died with", repr(args.exc_value))
t3 = threading.Thread(target=careless)
t3.start(); t3.join()
print("3. lock still held after its holder died:", lock3.locked())
print("   second acquire with timeout:", lock3.acquire(timeout=0.3))
Output8 lines
1. join with the lock held, finished: False
   after releasing the lock, finished: True
2. a waited for the other; the other was still running: True
2. b waited for the other; the other was still running: True
   self-join: cannot join current thread
   holder died with ValueError('boom')
3. lock still held after its holder died: True
   second acquire with timeout: False
  1. join() (or .result()) while holding a lock the other side needs. The joiner waits for the worker, the worker waits for the lock, the joiner holds it. The wait-for edges run through a thread instead of a second lock, which is why a lock-ordering review misses it. Rule: never call join(), result(), queue.get() or Event.wait() with a lock held (6.5).
  2. A join cycle. A thread that joins itself is caught: RuntimeError: cannot join current thread. Two threads that join each other, or a longer ring, are not caught and hang forever, exactly like the task cycle of 3.5. The demo uses join(timeout=...) so it ends, and a barrier so both joins really overlap.
  3. A holder that dies without releasing. A thread that calls acquire() without with or try/finally and then raises leaves the lock held for good. The demo's last two lines show the lock still locked after its owner is gone: Python does not release locks for dead threads. Always use with lock:.

Part 4: Databases and distributed systems#

Deep-dive

4.1 Database deadlocks#

Databases are full of locks (row locks, table locks, index locks), and transactions hold them until commit: textbook hold-and-wait. So databases deadlock all the time, and the good ones detect it and break it (they can, because a transaction can be rolled back: they break the "no preemption" condition). The classic pattern is two transactions updating the same two rows in opposite order:

sql
-- Transaction 1                          -- Transaction 2
BEGIN;                                    BEGIN;
UPDATE budgets SET tokens = tokens - 10
  WHERE tenant = 'acme';                  UPDATE budgets SET tokens = tokens - 5
                                            WHERE tenant = 'globex';
UPDATE budgets SET tokens = tokens + 10
  WHERE tenant = 'globex';  -- waits ...   UPDATE budgets SET tokens = tokens + 5
                                            WHERE tenant = 'acme';   -- waits ... DEADLOCK

How the three common engines handle it (as of November 2026; check the linked pages for your version):

Engine Detection What you see Source
PostgreSQL A waiting process waits deadlock_timeout (default 1 second) before running the (relatively expensive) deadlock check. If it finds a cycle it aborts one of the transactions; which one "is difficult to predict and should not be relied upon". SQLSTATE 40P01, condition name deadlock_detected (class 40, Transaction Rollback) Explicit locking, deadlock_timeout, error codes
MySQL / InnoDB Detection is on by default (innodb_deadlock_detect); it "tries to pick small transactions to roll back" (size = rows inserted/updated/deleted). On very busy systems detection itself can cost throughput, so some operators turn it off and rely on innodb_lock_wait_timeout. It cannot see deadlocks that involve LOCK TABLES or another storage engine's locks; those need the wait timeout. An error to the client that the transaction was rolled back; MySQL's text is "Deadlock found when trying to get lock; try restarting transaction" (error 1213, ER_LOCK_DEADLOCK, SQLSTATE 40001) InnoDB deadlock detection
SQLite Single writer. If waiting for a lock "could result in a deadlock", SQLite returns SQLITE_BUSY immediately, even when a busy timeout is set, instead of invoking the busy handler. sqlite3.OperationalError: database is locked sqlite3_busy_handler

PostgreSQL's own documentation gives the two defences, in this order: "The best defense against deadlocks is generally to avoid them by being certain that all applications using a database acquire locks on multiple objects in a consistent order." And if that is not feasible, "deadlocks can be handled on-the-fly by retrying transactions that abort due to deadlocks." Both are the same ideas as Part 6: lock ordering and retrying after a broken "no preemption".

What to set and what to write (PostgreSQL names as of November 2026, checked against the client settings and SELECT pages; MySQL names from its server reference). The MySQL deadlock error is 1213 (ER_LOCK_DEADLOCK, SQLSTATE 40001, "Deadlock found when trying to get lock; try restarting transaction").

Tool What it does Use it for
lock_timeout (PostgreSQL; default 0 = off) Aborts any statement that waits longer than the limit for a lock. Set per session or per transaction (SET LOCAL lock_timeout = '2s'); the docs advise against setting it in postgresql.conf because it affects every session Turning an unbounded lock wait into an error you can retry or report
statement_timeout (default 0) Aborts any statement that runs longer than the limit, waiting or not A ceiling on runaway queries; pointless to set lock_timeout at or above it
idle_in_transaction_session_timeout (default 0) Terminates a session that sits idle inside an open transaction too long The safety net for the "transaction held open during an LLM call" warning below: it kills the session and frees its locks
innodb_lock_wait_timeout (MySQL/InnoDB) How long a transaction waits for a row lock before giving up The only protection against deadlocks InnoDB cannot see (for example involving LOCK TABLES)
SELECT ... FOR UPDATE NOWAIT Errors immediately if a selected row cannot be locked "Try it, and tell the user it is busy"
SELECT ... FOR UPDATE SKIP LOCKED Silently skips rows that other transactions have locked. The docs call the resulting view inconsistent, "not suitable for general purpose work", but fine for "multiple consumers accessing a queue-like table" Job queues: each worker claims a different row and nobody waits
pg_advisory_lock(key) An application-defined lock held by the session. It is a lock like any other: take several in inconsistent order and they can deadlock Cross-process mutual exclusion on something that is not a row; apply the ordering rule of 6.2 to the keys

An illustrative job-claim query for an ingestion worker (not run: it needs a PostgreSQL server):

sql
-- Illustrative: each worker claims one pending document without waiting for the others.
BEGIN;
SELECT id, payload FROM ingest_jobs
 WHERE state = 'pending'
 ORDER BY id
 LIMIT 1
 FOR UPDATE SKIP LOCKED;
-- ... do the work, then:
UPDATE ingest_jobs SET state = 'done' WHERE id = :id;
COMMIT;

To find out who is blocking whom, ask PostgreSQL (illustrative; pg_blocking_pids() is documented on the system information functions page):

sql
-- Illustrative: every waiting backend, the backends that block it, and what each is doing.
SELECT waiting.pid                    AS waiting_pid,
       waiting.query                  AS waiting_query,
       pg_blocking_pids(waiting.pid)  AS blocked_by,
       now() - waiting.query_start    AS waiting_for
  FROM pg_stat_activity AS waiting
 WHERE cardinality(pg_blocking_pids(waiting.pid)) > 0;

Join the blocked_by pids back to pg_stat_activity to see their queries, and look for a state of idle in transaction: that is the usual culprit. pg_locks shows the individual locks, and log_lock_waits logs waits longer than deadlock_timeout.

You can watch SQLite's refusal to deadlock with two connections that both hold a read lock and both want to write:

python
# sqlite_busy.py: two connections each hold a read lock and want to write. SQLite refuses to deadlock.
import os
import sqlite3
import tempfile

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "jobs.db")
    setup = sqlite3.connect(path)
    setup.execute("CREATE TABLE jobs (id INTEGER PRIMARY KEY, state TEXT)")
    setup.execute("INSERT INTO jobs (state) VALUES ('queued')")
    setup.commit(); setup.close()

    # isolation_level=None: we send BEGIN ourselves. timeout=5 asks SQLite to wait up to 5 s on contention.
    a = sqlite3.connect(path, timeout=5, isolation_level=None)
    b = sqlite3.connect(path, timeout=5, isolation_level=None)

    a.execute("BEGIN"); a.execute("SELECT * FROM jobs").fetchall()   # A: shared (read) lock
    b.execute("BEGIN"); b.execute("SELECT * FROM jobs").fetchall()   # B: shared (read) lock

    a.execute("UPDATE jobs SET state = 'A'")   # A takes the RESERVED lock: readers may still read
    print("A: UPDATE accepted (A now holds the RESERVED write lock)")
    try:
        b.execute("UPDATE jobs SET state = 'B'")   # B also wants to write: it already holds a read lock, so waiting could deadlock
    except sqlite3.OperationalError as e:
        print("B failed immediately:", e)       # despite timeout=5: SQLite does not wait here
    b.execute("ROLLBACK")
    a.execute("COMMIT")
    print("A committed; row =", a.execute("SELECT state FROM jobs").fetchone()[0])
    a.close(); b.close()
Output3 lines
A: UPDATE accepted (A now holds the RESERVED write lock)
B failed immediately: database is locked
A committed; row = A

Connection A got the write lock first. Connection B, which already held a read lock, would have to wait for A, but A cannot commit while B's read lock exists: a two-party cycle. SQLite saw that and failed B immediately, despite timeout=5. The cure is also the textbook one: acquire the strongest lock you will need at the start (BEGIN IMMEDIATE for a transaction that will write) so you wait once, at the front door, instead of upgrading half-way through.

The application's side of a database deadlock is retry the whole transaction. The aborted transaction was rolled back, so nothing is half-done, but the database will not retry for you:

python
# db_retry.py: retry a whole transaction when the database picks it as the deadlock victim.
# A stand-in exception is used so the demo needs no database driver.
import random
import time

class DeadlockDetected(Exception):
    """Stands for psycopg.errors.DeadlockDetected (SQLSTATE 40P01) or MySQL error 1213."""

def run_transaction(attempt_log: list[str], fail_times: int):
    state = {"calls": 0}
    def transaction() -> str:
        state["calls"] += 1
        attempt_log.append(f"attempt {state['calls']}: BEGIN ... UPDATE ... UPDATE")
        if state["calls"] <= fail_times:
            raise DeadlockDetected("deadlock detected")     # the DB already rolled the transaction back
        return "COMMIT"
    return transaction

def with_deadlock_retry(tx, attempts: int = 5, base: float = 0.01, seed: int = 7) -> str:
    rng = random.Random(seed)
    for attempt in range(1, attempts + 1):
        try:
            return tx()                                      # the WHOLE transaction is the unit of retry
        except DeadlockDetected:
            if attempt == attempts:
                raise
            time.sleep(rng.uniform(0, base * 2 ** attempt))  # jittered exponential back-off
    raise AssertionError("unreachable")

log: list[str] = []
print("result:", with_deadlock_retry(run_transaction(log, fail_times=2)))
print("\n".join(log))
Output4 lines
result: COMMIT
attempt 1: BEGIN ... UPDATE ... UPDATE
attempt 2: BEGIN ... UPDATE ... UPDATE
attempt 3: BEGIN ... UPDATE ... UPDATE

Retry only when the transaction is idempotent in effect (it was rolled back, so re-running the same statements is safe) and keep side effects outside it: if the transaction body also sent an email or called an LLM API, the retry sends it twice (01B.9 Part 3 on idempotency). Add jitter (01B.9 §4.2) so the two victims do not collide again in lockstep (Part 7). The SQL-level lost-update and locking choices are in 01C.3 §5.2.

4.2 Distributed deadlocks#

When the exclusive resources live on different machines (a distributed lock in Redis, a lease in etcd, a row lock in each of two databases, an "agent A is waiting for agent B's tool server" chain), the wait-for graph is spread across machines and no one has the whole graph. Single-process detectors (Part 5) cannot see the cycle. Real systems use a small set of answers:

Approach How it works Trade-off
Timeouts and leases Every lock has a time-to-live; if the holder does not renew, the lock expires Simple and universal. A holder that is merely slow loses the lock while still working (needs fencing tokens to be safe)
Global ordering All services lock resources in one agreed order (for example by resource id) Free at run time; needs a shared convention and discipline
A coordinator A single transaction manager or lock service owns the graph and can run detection A single point of failure and of contention
Avoid distributed locks Use idempotent operations, optimistic concurrency, queues and sagas (compensating actions) instead More design work; usually the best answer
Probe-based detection Services forward "probe" messages along wait edges; a probe that returns to its sender proves a cycle (Chandy-Misra-Haas) Research-grade; rare in application code

The practical advice for an AI engineer: never let two services wait on each other synchronously (service A calls B while holding its own resource, and B calls A), put a deadline on every cross-service call (the 01B.9 §2.4 and 11C.3 §5.1 deadline propagation), and prefer designs where a stuck peer produces a timeout instead of a lock held forever. The same advice applies to agents that call other agents (9.2).


Part 5: Finding a deadlock#

A deadlocked service gives you very little: no exception, no log line (the thread that would log is the one that is stuck), no CPU. Detection is therefore a skill of its own. The approach, in the order you will reach for it:

  1. Is it a deadlock at all? Check CPU (1.3). 0 % CPU and a request that never finishes points to waiting. High CPU points to livelock or a runaway loop.
  2. Where is every thread parked? A stack dump of all threads answers this immediately. Almost every deadlock is obvious from a stack dump: you see N threads in acquire() / get() / result() / join(), at lines that tell you what each wants.
  3. Who holds what? Python's Lock does not record its owner, so you must reason from the stacks (which thread is inside the with lock_a: block), or add instrumentation (5.6).
  4. Make it self-reporting so next time you do not need to be there: a watchdog (5.5) and a dump signal (5.2).

5.1 Stack dumps from outside, from inside, and on a timer#

Tool Where it runs Needs the program's cooperation? Needs code change? Notes
faulthandler.dump_traceback_later(timeout) inside, on a watchdog thread yes: armed at start-up one line Stdlib. Works even when every Python thread is blocked, because the dump is written by a C-level watchdog thread
faulthandler.register(signal.SIGUSR1) inside, on a signal armed at start-up one line Stdlib, Unix only. kill -USR1 <pid> dumps all threads on demand
py-spy dump --pid <pid> outside, a separate process no none Third-party. Reads the target's memory. Usually needs root (macOS always; Linux unless ptrace_scope allows it); in Docker needs SYS_PTRACE
py-spy dump --native / pystack remote <pid> (Bloomberg's pystack) / gdb with CPython's py-bt outside no none Third-party (gdb is a system debugger). Also show the C frames, which you need when a thread is stuck inside an extension module rather than in Python code
sys._current_frames() inside yes a diagnostic endpoint or thread Stdlib. Source of a "dump threads" admin endpoint
python -m pdb -p <pid> (3.14+) outside, attaches a debugger no none Stdlib; for a process blocked in a system call it only takes effect once the process reaches the next bytecode or receives a signal
python -m asyncio ps / pstree <pid> (3.14+) outside no none Stdlib; asyncio tasks only (5.7)

5.2 faulthandler: the built-in dump#

faulthandler is in the standard library, writes from C (so it works when Python code cannot run) and has two features that matter here. dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False) arms a watchdog thread that dumps every thread's traceback after timeout seconds, "or every timeout seconds if repeat is True"; with exit=True it then calls _exit(1) (the docs note that file buffers are not flushed). register(signum) installs a signal handler that dumps all threads on demand (not available on Windows).

python
# faulthandler_demo.py: arm a watchdog that dumps every thread's stack if the program is still running in 1 s.
import faulthandler
import sys
import threading
import time

lock_a, lock_b = threading.Lock(), threading.Lock()
step = threading.Barrier(2)

def one() -> None:
    with lock_a:
        step.wait()
        lock_b.acquire()          # never succeeds

def two() -> None:
    with lock_b:
        step.wait()
        lock_a.acquire()          # never succeeds

faulthandler.dump_traceback_later(1.0, exit=True, file=sys.stderr)   # watchdog thread; exit=True ends the process
for fn in (one, two):
    threading.Thread(target=fn, name=fn.__name__, daemon=True).start()
time.sleep(10)                    # the dump (and exit) happens long before this ends
Example output · illustrative11 lines
Timeout (0:00:01)!
Thread 0x000000016e237000 [two] (most recent call first):
  File "/work/faulthandler_demo.py", line 18 in two
  File ".../lib/python3.14/threading.py", line 1024 in run
  ...
Thread 0x000000016d22b000 [one] (most recent call first):
  File "/work/faulthandler_demo.py", line 13 in one
  File ".../lib/python3.14/threading.py", line 1024 in run
  ...
Thread 0x00000001ff73d300 (most recent call first):
  File "/work/faulthandler_demo.py", line 23 in <module>

Read it like this: threads one and two are both stopped on their second acquire (lines 13 and 18, the lines that call lock_b.acquire() and lock_a.acquire()); the main thread is in time.sleep. Two threads parked on lock lines, while each is inside a with for the other lock: the classic cycle. You read the lock names from the source at those line numbers.

For a production service, three habits cost almost nothing:

python
# at process start-up (for example in your app factory)
import faulthandler
import signal

faulthandler.enable()                                   # dump on SIGSEGV/SIGFPE/SIGABRT/SIGBUS/SIGILL
if hasattr(signal, "SIGUSR1"):                          # not on Windows
    faulthandler.register(signal.SIGUSR1, all_threads=True)   # `kill -USR1 <pid>` dumps all threads, process keeps running

or simply run with python -X faulthandler app.py / PYTHONFAULTHANDLER=1, which enables the crash handler. Send the dump to a file that survives the container (file=open(path, "w"); the docs say the file object must stay open).

5.3 py-spy dump: from outside, no code change#

When the process is already hung and you did not arm anything, a sampling profiler that can read another process's memory saves you. py-spy (third-party; install it separately and check PyPI for the current version, as of November 2026) prints the Python stack of every thread:

bash
py-spy dump --pid 12345            # all threads; add --locals to show local variables
# macOS always needs root: sudo py-spy dump --pid 12345
# Linux: root, or lower the ptrace restriction, or start the app under py-spy
# Docker: start the container with --cap-add SYS_PTRACE (the container otherwise denies process_vm_readv)
Example output · illustrative14 lines
Process 12345: python3 gateway.py
Python v3.14.6 (/usr/local/bin/python3.14)

Thread 0x7F2A1C000700 (idle): "MainThread"
    wait (threading.py:359)
    result (concurrent/futures/_base.py:451)
    handle_request (gateway/agents.py:88)
Thread 0x7F2A0B7FE700 (idle): "ThreadPoolExecutor-0_0"
    result (concurrent/futures/_base.py:451)
    run_subtasks (gateway/agents.py:61)
    ...
Thread 0x7F2A0AFFD700 (idle): "ThreadPoolExecutor-0_1"
    result (concurrent/futures/_base.py:451)
    run_subtasks (gateway/agents.py:61)

Two pool workers parked in Future.result inside the same function run_subtasks is the signature of 3.2. (idle means the thread is not consuming CPU; a thread stuck in a C call with the GIL released also shows as idle.) This is the process you would run in an incident. Keep it in your image or runbook. Python 3.14's own python -m pdb -p <pid> can attach a debugger to a running process too.

5.4 From inside: sys._current_frames() and threading.enumerate()#

threading.enumerate() lists live Thread objects; sys._current_frames() returns "a dictionary mapping each thread's identifier to the topmost stack frame currently active in that thread". Joining the two gives you a dump function you can expose on an admin endpoint or call from a watchdog. The underscore says it is a diagnostic helper, not a stable application API.

python
# thread_dump.py: a poor man's py-spy dump, from inside the process: sys._current_frames().
import sys
import threading
import traceback

lock = threading.Lock()
lock.acquire()                                  # held forever by the main thread

def stuck_on_lock() -> None:
    lock.acquire()

def stuck_on_queue_get() -> None:
    import queue
    queue.Queue().get()

def dump_threads() -> list[str]:
    names = {t.ident: t.name for t in threading.enumerate()}
    lines = []
    for ident, frame in sorted(sys._current_frames().items(), key=lambda kv: names.get(kv[0], "")):
        stack = traceback.extract_stack(frame)
        if names.get(ident) == "MainThread":
            continue
        mine = [f for f in stack if f.filename == __file__]   # skip frames inside the stdlib
        top = mine[-1]
        lines.append(f"{names.get(ident, '?'):<12} waiting in {top.name}() at line {top.lineno}: {top.line}")
    return lines

if __name__ == "__main__":
    for name, fn in (("lock-waiter", stuck_on_lock), ("queue-waiter", stuck_on_queue_get)):
        threading.Thread(target=fn, name=name, daemon=True).start()
    import time; time.sleep(0.2)                # let both threads reach their wait
    print(f"{len(threading.enumerate())} threads alive")
    for line in dump_threads():
        print(line)
Output3 lines
3 threads alive
lock-waiter  waiting in stuck_on_lock() at line 10: lock.acquire()
queue-waiter waiting in stuck_on_queue_get() at line 14: queue.Queue().get()

The three threads are the main thread plus the two parked ones. The helper skips frames inside the standard library (threading.py, queue.py) to show your line: that is where you look for the lock or call. traceback.extract_stack(frame) gives file, line, function and source text for each frame.

5.5 A heartbeat watchdog#

The most robust production pattern is a watchdog: something that expects regular proof of life and acts when it stops. The thing it guards sends a "heartbeat" (updates a timestamp) after each unit of work; a separate thread wakes up several times per interval and checks the age of the last beat. If the heartbeat is stale, the watchdog dumps the stacks (and, depending on policy, logs, alerts or exits so the orchestrator restarts the process).

python
# watchdog.py: a heartbeat watchdog thread that dumps where every thread is stuck, then lets the process decide.
import sys
import threading
import time
import traceback

class Watchdog(threading.Thread):
    def __init__(self, stale_after: float, on_stall) -> None:
        super().__init__(name="watchdog", daemon=True)
        self.stale_after = stale_after
        self.on_stall = on_stall
        self._last = time.monotonic()

    def beat(self) -> None:                      # call this from the code you are guarding
        self._last = time.monotonic()

    def run(self) -> None:
        while True:
            time.sleep(self.stale_after / 4)
            if time.monotonic() - self._last > self.stale_after:
                self.on_stall(self.snapshot())
                return

    @staticmethod
    def snapshot() -> list[str]:
        names = {t.ident: t.name for t in threading.enumerate()}
        out = []
        for ident, frame in sys._current_frames().items():
            if names.get(ident) == "watchdog":
                continue
            mine = [f for f in traceback.extract_stack(frame) if f.filename == __file__]
            if mine:
                out.append(f"{names.get(ident, '?')}: {mine[-1].name}() line {mine[-1].lineno}: {mine[-1].line}")
        return sorted(out)

stalled = threading.Event()

def report(lines: list[str]) -> None:
    print("STALL detected; thread positions:")
    for line in lines:
        print("  ", line)
    stalled.set()

lock = threading.Lock()
lock.acquire()

def worker() -> None:
    # The lock is never released: this is the hang.
    lock.acquire()

if __name__ == "__main__":
    dog = Watchdog(stale_after=0.4, on_stall=report)
    dog.start()
    threading.Thread(target=worker, name="worker", daemon=True).start()
    for _ in range(3):                           # healthy phase: heartbeats arrive
        dog.beat(); time.sleep(0.1)
    # The main loop "hangs": no more beats arrive.
    stalled.wait(timeout=5)
Output3 lines
STALL detected; thread positions:
   MainThread: <module>() line 58: stalled.wait(timeout=5)
   worker: worker() line 49: lock.acquire()

Three design points:

  • The watchdog must never need a lock the guarded code might hold. It reads one float and uses time.monotonic(), which is not affected by clock changes. A watchdog that takes the application lock is subject to the same deadlock.
  • A healthy-looking process can be useless. A liveness probe that only checks "the HTTP server answers" passes while every worker is deadlocked. Make the heartbeat come from the work itself (a worker finishing a job), not from a side thread that always runs.
  • When the watchdog fires, dump first, restart second. A restart without the dump destroys the evidence.

In Kubernetes or similar platforms the same idea is the liveness probe, backed by an endpoint that reads the last-progress timestamp. The metrics side of it (queue depth, oldest in-flight job age) belongs in your monitoring (11A.2): "age of the oldest in-flight job" is the single best alert for deadlocks and starvation alike.

5.6 A wait-for graph detector in about 50 lines#

Java's jstack prints "Found one Java-level deadlock" because the JVM knows who owns every monitor. Python's Lock is anonymous, but you can add the missing knowledge in the places that matter: wrap your important locks in a class that records who owns it and who is waiting. Then a wait-for graph is easy to build, and a cycle in it is a deadlock.

The data: owners[lock] = thread (set when acquired) and waiting[thread] = lock (set while blocked). The thread-to-thread edge is: T waits for lock L, L is owned by U, so T → U. Because each thread waits for at most one lock at a time, following the edges from any thread either ends (no cycle from here) or comes back to a visited node (cycle).

python
# wait_for_graph.py: a deadlock detector built from a wait-for graph, standard library only.
import threading
from typing import Optional

class TrackedLock:
    """A Lock that records its owner and who is waiting for it."""
    registry_lock = threading.Lock()
    owners: dict["TrackedLock", int] = {}            # lock -> owning thread ident
    waiting: dict[int, "TrackedLock"] = {}           # thread ident -> lock it waits for

    def __init__(self, name: str) -> None:
        self.name = name
        self._lock = threading.Lock()

    def acquire(self, timeout: float = -1) -> bool:
        me = threading.get_ident()
        with TrackedLock.registry_lock:
            TrackedLock.waiting[me] = self           # edge: me -> this lock
        ok = self._lock.acquire(timeout=timeout)
        with TrackedLock.registry_lock:
            del TrackedLock.waiting[me]
            if ok:
                TrackedLock.owners[self] = me        # edge: this lock -> me
        return ok

    def release(self) -> None:
        with TrackedLock.registry_lock:
            TrackedLock.owners.pop(self, None)
        self._lock.release()

    __enter__ = lambda self: (self.acquire(), self)[1]
    __exit__ = lambda self, *exc: self.release()

def find_deadlock(names: dict[int, str]) -> Optional[list[str]]:
    """Return a cycle of thread names if one exists, else None."""
    with TrackedLock.registry_lock:
        # thread -> thread edge: T waits for lock L, L is owned by U  =>  T -> U
        edges = {t: TrackedLock.owners[l] for t, l in TrackedLock.waiting.items() if l in TrackedLock.owners}
        lock_of = {t: l.name for t, l in TrackedLock.waiting.items()}
    for start in edges:
        seen, node = [], start
        while node in edges and node not in seen:    # each thread waits for at most one lock: follow the chain
            seen.append(node)
            node = edges[node]
        if node in seen:                             # we came back: a cycle
            cycle = seen[seen.index(node):]
            return [f"{names[t]} waits for {lock_of[t]} held by {names[edges[t]]}" for t in cycle]
    return None

if __name__ == "__main__":
    a, b = TrackedLock("cache"), TrackedLock("budget")
    step = threading.Barrier(3)
    release_all = threading.Event()

    def worker(first: TrackedLock, second: TrackedLock) -> None:
        with first:
            step.wait()
            if second.acquire(timeout=3):
                second.release()

    t1 = threading.Thread(target=worker, args=(a, b), name="worker-1")
    t2 = threading.Thread(target=worker, args=(b, a), name="worker-2")
    t1.start(); t2.start()
    step.wait()                                      # main joins: both workers now hold one lock
    import time; time.sleep(0.2)                     # give both time to start waiting
    names = {t1.ident: t1.name, t2.ident: t2.name}
    cycle = find_deadlock(names)
    print("deadlock found:" if cycle else "no deadlock")
    for line in cycle or []:
        print("  ", line)
    t1.join(); t2.join()                             # the 3 s acquire timeouts end the demo
    print("after timeouts:", find_deadlock(names))
Output4 lines
deadlock found:
   worker-1 waits for budget held by worker-2
   worker-2 waits for cache held by worker-1
after timeouts: None

The cycle is printed in terms you can act on: which thread waits for which lock and who holds it. The last line shows that after the 3 s timeouts expire the cycle disappears (the waiters left the waiting map).

How to use this idea in a real code base:

  • Use one wrapper class for the few shared locks that matter (not for every lock in the process; the registry lock adds overhead and its own contention).
  • Run find_deadlock from the watchdog thread and log the cycle.
  • Lock-order validators exist in other runtimes: the Linux kernel's "lockdep" and ThreadSanitizer's lock-order-inversion report both record the order in which locks are taken and flag any pair taken in both orders, even if no deadlock happened on that run. That is much better than waiting for the unlucky schedule, and you build a tiny version in 6.4.
  • This detector only sees locks that go through the wrapper. A thread blocked in queue.get() or future.result() is waiting too, but not for a tracked lock; you would extend waiting to those, or rely on stack dumps.

5.7 asyncio introspection tools#

For asyncio programs you want the tasks and who awaits whom, not the OS threads (they are all the same one thread). Python 3.14 added two tools.

In-process: asyncio.format_call_graph(future=None, /, *, depth=1, limit=None) returns a string describing the await chain of a task, and asyncio.print_call_graph(...) prints it; capture_call_graph returns a data structure. All were added in 3.14. Here is one for a task blocked on an Event:

python
# asyncio_graph.py (Python 3.14+): ask asyncio who is waiting for whom.
import asyncio

async def worker(gate: asyncio.Event) -> None:
    await gate.wait()

async def main() -> None:
    gate = asyncio.Event()
    t = asyncio.create_task(worker(gate), name="worker-1")
    await asyncio.sleep(0)                      # let it start and block
    print(asyncio.format_call_graph(t))         # a string; print_call_graph() prints it
    gate.set()
    await t

asyncio.run(main())
Example output · illustrative4 lines
* Task(name='worker-1', id=0x107fd05f0)
  + Call stack:
  |   File '.../lib/python3.14/asyncio/locks.py', line 213, in async Event.wait()
  |   File '/work/asyncio_graph.py', line 5, in async worker()

From outside, on a running process (3.14+): python -m asyncio ps PID prints a flat table of tasks and who awaits them, and python -m asyncio pstree PID prints the await tree. The 3.14 documentation says these read the target "without executing any code in it", may need permission to inspect another process, and that pstree reports an error instead of a tree when the await graph contains a cycle (naming the cycle, for example Task-2 → Task-3 → Task-2), while ps still lists every task. That is the right behaviour for diagnosing 3.5 case 1. (The in-process format_call_graph recursed without bound on a cycle in the test described in 3.5; prefer the CLI tools when you suspect one.) Both are 3.14+ features: on 3.11 to 3.13, use asyncio.all_tasks() plus task.get_stack() and repr(task) (a pending task's repr shows wait_for=<...>), and enable debug mode (01C.2 §8.1).


Part 6: Prevention#

Detection tells you a deadlock happened; prevention makes it impossible. Use the Coffman table from 1.2: pick the cheapest condition to break. In practice engineers reach for these, in this order:

Order Technique Breaks Use when
1 Avoid taking two locks at once (restructure so each critical section needs one) hold and wait Always the first question. Often the answer is "copy the data out under lock A, release, then take lock B"
2 Global lock ordering circular wait You really need two locks together and you control all the code that takes them
3 Message passing / one owner thread mutual exclusion State can be owned by one thread or task and others send it requests (01C.3 §7.5)
4 Timeouts + back-off (try-lock) no preemption You cannot control lock order (callbacks, plugins, third-party code), or the locks are external (DB rows, distributed locks)
5 No lock held across I/O or foreign callbacks hold and wait Always, as a coding rule
6 A checked hierarchy circular wait (enforced) A large codebase where "remember the order" will not survive turnover
7 Detection + recovery (watchdog, DB victim abort, restart) (cleans up after) The last line of defence, never the first

6.1 One lock per invariant, and the fewest locks possible#

A lock protects an invariant (a statement that must always be true: "tokens_used equals the sum of the per-request counts"). Give each independent invariant its own lock, and do not take two unless one operation really spans two invariants. Too few locks (one global lock) kills concurrency but cannot deadlock against itself; too many locks, taken in varying combinations, creates the orders that deadlock. The sweet spot is a small number of locks, each with a short, written description of what it protects and a rule about what may be called while it is held (preferably: nothing that takes another lock).

6.2 Global lock ordering#

Give every lock a rank, and always acquire in ascending rank. When the locks are instances of the same class (two accounts in a transfer, two tenants' budgets, two shards), use a stable key such as an id or a creation counter, never id(obj) unless objects live as long as the lock (ids can be reused after an object is freed, and are not stable across processes).

The three techniques of this part are in one runnable file; section 1 is the ordering rule:

python
# prevention.py: three ways to stop the two-lock deadlock: global ordering, timeout + backoff, and a checked hierarchy.
import random
import threading
import time
from contextlib import contextmanager

# ---------- 1. Global lock ordering: transfer tokens between tenant budgets ----------
class Budget:
    _next_rank = 0
    def __init__(self, name: str, tokens: int) -> None:
        self.name, self.tokens = name, tokens
        self.lock = threading.Lock()
        self.rank = Budget._next_rank          # a stable, unique order for every lock
        Budget._next_rank += 1

def transfer(src: Budget, dst: Budget, amount: int) -> None:
    first, second = sorted((src, dst), key=lambda b: b.rank)   # ALWAYS lock the lower rank first
    with first.lock, second.lock:
        if src.tokens >= amount:
            src.tokens -= amount
            dst.tokens += amount

def hammer(budgets: list[Budget], n: int, seed: int) -> None:
    rng = random.Random(seed)
    for _ in range(n):
        a, b = rng.sample(budgets, 2)
        transfer(a, b, rng.randint(1, 5))

budgets = [Budget(f"tenant-{i}", 1000) for i in range(4)]
threads = [threading.Thread(target=hammer, args=(budgets, 20_000, s)) for s in range(8)]
for t in threads: t.start()
for t in threads: t.join()
print("1. ordered transfers finished; total tokens =", sum(b.tokens for b in budgets), "(started with 4000)")

# ---------- 2. Try-lock with timeout, release everything, back off with jitter, retry ----------
def acquire_both(l1: threading.Lock, l2: threading.Lock, rng: random.Random, attempts: int = 50) -> int:
    for attempt in range(1, attempts + 1):
        l1.acquire()
        if l2.acquire(timeout=0.01):
            return attempt                     # holding both
        l1.release()                           # give up EVERYTHING we hold ...
        time.sleep(rng.uniform(0, 0.005) * attempt)   # ... and wait a random, growing time
    raise TimeoutError("could not take both locks")

x, y = threading.Lock(), threading.Lock()
done = []
def worker(first, second, seed):
    got = acquire_both(first, second, random.Random(seed))
    time.sleep(0.02)                           # do the work while holding both
    second.release(); first.release()
    done.append(True)

ts = [threading.Thread(target=worker, args=(x, y, 1)), threading.Thread(target=worker, args=(y, x, 2))]
for t in ts: t.start()
for t in ts: t.join()
print("2. opposite-order threads with try-lock + jittered backoff both finished:", len(done) == 2)

# ---------- 3. A lock hierarchy that raises if you break it ----------
_held = threading.local()

@contextmanager
def ranked(rank: int, name: str, lock: threading.Lock):
    stack = getattr(_held, "stack", [])
    if stack and stack[-1][0] >= rank:
        raise RuntimeError(f"lock order violation: taking {name} (rank {rank}) while holding {stack[-1][1]} (rank {stack[-1][0]})")
    with lock:
        _held.stack = stack + [(rank, name)]
        try:
            yield
        finally:
            _held.stack = stack

cache_l, budget_l = threading.Lock(), threading.Lock()
with ranked(10, "cache", cache_l), ranked(20, "budget", budget_l):
    print("3. cache -> budget is allowed")
try:
    with ranked(20, "budget", budget_l), ranked(10, "cache", cache_l):
        pass
except RuntimeError as e:
    print("   ", e)
Output4 lines
1. ordered transfers finished; total tokens = 4000 (started with 4000)
2. opposite-order threads with try-lock + jittered backoff both finished: True
3. cache -> budget is allowed
    lock order violation: taking cache (rank 10) while holding budget (rank 20)
  1. Eight threads made 160,000 random transfers between four tenant budgets with the ordering rule and finished, with the total unchanged. Remove the sorted(...) line (always lock src then dst) and this program would deadlock quickly: transfer a → b in one thread and b → a in another is the opposite-order pattern of 2.1.
  2. The same fix is what databases recommend (PostgreSQL: "acquire locks on multiple objects in a consistent order") and what SELECT ... FOR UPDATE ... ORDER BY id gives you for several rows.

Rules to make ordering work in practice:

  • Write the order down where the next engineer will see it (a comment on the lock definition, a module docstring).
  • Order by a key, not by call site. "Always sorted(..., key=...)" in one helper function (lock_both(a, b)), so call sites cannot get it wrong.
  • Locks of different kinds get a documented total order across the program (for example: registry_lock < tenant_lock < cache_lock).
  • A callback invoked while holding a lock can acquire a lock that is lower in the order than the one you hold, which breaks the rule invisibly (6.5).

6.3 acquire(timeout=...) and try-lock with back-off#

When you cannot guarantee an order, break no preemption yourself: take the first lock, try the second with a timeout (or non-blocking), and if it fails release everything you hold and try again later. Lock.acquire(blocking=True, timeout=-1) returns True if the lock was taken and False on timeout; per the docs, it is forbidden to give a timeout when blocking=False. Python's with lock: syntax has no timeout form, so write a small helper (a contextmanager) or call acquire explicitly in a try/finally.

Section 2 of prevention.py above does it: each thread takes its first lock, acquire(timeout=0.01) on the second, and on failure releases the first, sleeps a random, growing time (jittered back-off) and starts over. Both opposite-order threads finish. Three details matter:

  • Release everything before retrying. Holding the first lock while sleeping keeps the cycle alive.
  • Jitter. Without randomness, two threads that failed together retry together and fail together: that is the livelock of Part 7.
  • Bound the attempts and raise a clear error (TimeoutError, with the lock names in the message). A timeout that only logs and retries forever is an infinite loop with extra steps.

Timeouts turn a silent hang into a loud, attributable failure, which is worth the code even when ordering already protects you. Put a timeout on every wait that depends on another party: lock.acquire(timeout=), queue.get(timeout=), future.result(timeout=), thread.join(timeout=), Condition.wait_for(..., timeout=), asyncio.timeout(), HTTP client timeouts (01B.9 §2.1). The total budget approach is in 01B.9 §2.4.

6.4 A lock hierarchy that raises on violation#

Convention fails when teams grow. Make the order machine-checked: give each lock a rank and record, per thread, the ranks currently held; if code tries to take a lock whose rank is not higher than the one it holds, raise immediately, on every run, even if no other thread is around to deadlock with. Section 3 of prevention.py shows a ~15-line version with threading.local:

  • Taking cache (rank 10) then budget (rank 20) is allowed.
  • Taking budget then cache raises RuntimeError: lock order violation: taking cache (rank 10) while holding budget (rank 20).

This converts an intermittent production hang into a deterministic test failure the first time the offending code path is exercised, which is the best trade there is. Run it in tests and in staging; in production you may keep it on if the overhead is acceptable. (The Linux kernel does the same thing with its "lockdep" validator, and the same idea exists in many languages' lock libraries.)

6.5 Never hold a lock across I/O or foreign code#

Two sub-rules that remove most real-world deadlocks and stalls at once:

  1. Do not hold a lock while doing I/O (network calls, disk, a database query, an LLM call). I/O has unbounded duration, so you convert a "microsecond" lock into a "whatever the provider takes" lock, and everyone queues behind it. It also hides lock dependencies (the I/O library may take its own locks).
  2. Do not call code you do not control while holding a lock (callbacks, event handlers, __del__, logging handlers, user-supplied functions, Future done-callbacks). You cannot know which locks that code takes, so you cannot know the order. __del__ and weakref callbacks are the extreme case: they can run on your thread in the middle of your critical section (2.2b).

The standard cure for both is copy-then-release: take the lock, copy what you need, release, then act on the copy.

python
# copy_then_release.py: snapshot under the lock, call out with the lock released.
import threading
from typing import Callable

class EventBus:
    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._handlers: list[Callable[[str], None]] = []

    def subscribe(self, handler: Callable[[str], None]) -> None:
        with self._lock:
            self._handlers.append(handler)

    def publish(self, event: str) -> None:
        with self._lock:
            handlers = list(self._handlers)   # a snapshot: cheap, and the lock is held for microseconds
        for handler in handlers:              # foreign code runs with NO lock held
            handler(event)                    # a handler may now call subscribe() or publish() safely

bus = EventBus()
bus.subscribe(lambda e: bus.subscribe(lambda e2: None))   # re-entrancy that would deadlock a lock-held publish()
bus.publish("started")
print("handlers after publish:", len(bus._handlers))
Output1 line
handlers after publish: 2

Holding self._lock while looping and calling handlers would deadlock (a Lock is not reentrant) the moment a handler subscribes. The price of copy-then-release is that a handler may run slightly after another thread unsubscribed it; for most systems that is acceptable and should be documented. 01C.3 §7.7 lists lock-hygiene rules from the race side; they are the same rules.

6.6 Design away the lock#

The most robust cure is a design where the conditions cannot hold:

  • Confinement: each thread or task owns its data; nothing is shared. No lock, no deadlock.
  • One owner, many clients: a single thread owns the shared structure and everyone else sends it messages through a queue.Queue (01C.3 §7.5). Be careful about request/response over queues: if the owner calls a client and the client calls the owner synchronously, that is a wait cycle again.
  • Immutability and publish-by-assignment: readers see a complete, never-modified snapshot, and a writer swaps in a new one (01C.3 §7.6).
  • Optimistic concurrency: do not hold anything while working; check a version number at the end and retry on conflict (databases: a version column).
  • asyncio single-flight: many callers wait on one future for the same key rather than each taking a lock (01C.3 §4.2).

6.7 A prevention checklist for code review#

  1. Does any function take more than one lock? Where is the order written down?
  2. Is any lock held across I/O, an LLM call, sleep, .result(), .join(), queue.get() or a callback?
  3. Does any task submitted to a pool wait for another task in the same pool?
  4. Does every blocking wait have a timeout and a defined failure path?
  5. Does every task_done() live in a finally? Is there a shutdown path (Queue.shutdown, sentinels) for every consumer?
  6. After fork(): are threads started before the fork? Is the start method spawn/forkserver?
  7. Is a Lock re-entered anywhere (a public method calling another public method)?
  8. For asyncio: is any await waiting on something that only a later line of the same task would produce?
  9. Is there a watchdog or "oldest in-flight job" metric, so the next hang is found in minutes?
  10. Is join() or result() ever called with a lock held (3.7)?
  11. What releases this lock if its holder is killed or raises? Is there a with or finally, and for cross-process locks, a lease or a kernel-released lock?
  12. Does any signal handler, __del__ or weakref callback take a lock (2.2b)?

Part 7: Livelock#

Deep-dive

7.1 Busy, polite and going nowhere#

Two people meet head-on in a corridor. Each steps aside to let the other pass: both to their left. Now they block each other again. Both step to the right. Blocked again. They are both moving, both being polite, and neither makes progress. That is livelock: the parties are not blocked (so CPU is busy and the threads are running, not waiting), but their reactions to each other keep undoing the progress.

The difference from deadlock, in one line: deadlock is stillness; livelock is motion without progress. The cause is almost always a mirror-image retry policy: "if I cannot get it, back off and try again" applied identically by every party, at the same moments.

7.2 Reproduce it#

Part 1 is a deterministic corridor simulation (no threads), so you can see the symmetry. Part 2 uses real locks: each thread takes its own lock, tries the other without waiting, and on failure releases and retries immediately. A Barrier makes the worst-case timing happen every round (without it, real schedules usually desynchronize by luck within a few rounds, which is why livelock is rarer in the wild than deadlock, and harder to reproduce). Then the same code with random back-off:

python
# livelock.py: threads that are busy, polite and getting nowhere. Part 1 is a deterministic simulation, part 2 uses real locks.
import random
import threading

# ---------- 1. Two people in a corridor, one step per tick ----------
def corridor(strategy: str, ticks: int = 8, seed: int = 0) -> str:
    rng = random.Random(seed)
    side = {"Ana": "left", "Ben": "left"}          # both start on the left and block each other
    for tick in range(1, ticks + 1):
        if side["Ana"] != side["Ben"]:
            return f"passed at tick {tick}"
        for who in side:                            # both notice the clash and politely step aside
            if strategy == "polite":
                side[who] = "right" if side[who] == "left" else "left"      # both always flip
            else:
                side[who] = rng.choice(["left", "right"])                    # randomized
    return f"still stuck after {ticks} ticks"

print("polite, always flip :", corridor("polite"))
print("random side         :", corridor("random"))

# ---------- 2. Real locks: grab one, try the other, release and retry immediately ----------
def run(jitter: bool, rounds: int = 200) -> str:
    a, b = threading.Lock(), threading.Lock()
    lockstep = threading.Barrier(2)                 # makes the worst-case timing happen every round
    results: dict[str, int] = {}

    def worker(name: str, first: threading.Lock, second: threading.Lock) -> None:
        rng = random.Random(name)
        for attempt in range(1, rounds + 1):
            with first:
                if not jitter:
                    lockstep.wait()                 # both hold one lock at the same moment ...
                if second.acquire(blocking=False):  # ... try the other without waiting
                    second.release()
                    results[name] = attempt
                    return
            # polite: back off by... doing nothing at all, then go again immediately
            if jitter:
                threading.Event().wait(rng.uniform(0, 0.001))     # random pause breaks the symmetry
        results[name] = -1

    t1 = threading.Thread(target=worker, args=("T1", a, b))
    t2 = threading.Thread(target=worker, args=("T2", b, a))
    t1.start(); t2.start(); t1.join(); t2.join()
    ok = all(v > 0 for v in results.values())
    return f"both finished: {ok}" if ok else f"gave up after {rounds} rounds each (CPU busy, zero progress)"

print("locks, lockstep retries :", run(jitter=False))
print("locks, random back-off  :", run(jitter=True))
Output4 lines
polite, always flip : still stuck after 8 ticks
random side         : passed at tick 3
locks, lockstep retries : gave up after 200 rounds each (CPU busy, zero progress)
locks, random back-off  : both finished: True
  • With "always flip" both people are stuck for the whole run; with a random choice per tick they pass in the third tick (the seed is fixed, so this is repeatable).
  • With lockstep retries both threads spend 200 rounds each taking a lock, failing to get the second, giving up the first and trying again: lots of CPU, no progress. With a random pause (0 to 1 ms) the symmetry breaks and both finish.

7.3 Where livelock appears in real systems#

Where What mirrors Symptom Cure
Try-lock + immediate retry (the demo above) Two threads release and re-acquire in lockstep Both threads at 100 % CPU, throughput zero Random back-off; tie-break by a rank (6.2)
Optimistic transaction retry Two transactions conflict, both abort and restart at once, conflict again Rising retry counters, no commits Jittered exponential back-off (01B.9 §4.2), bounded attempts
Retry storms across services Every client retries a failing dependency on the same fixed schedule The recovering service is hit by a synchronized wave each interval and falls over again Jitter, circuit breakers, retry budgets (01B.9 §1.3, 11C.3 Part 3)
Leader election flapping Two nodes each step down when they see the other claim leadership, then both claim again Leadership oscillates Randomized election timeouts (the technique Raft uses), lease durations longer than timeouts
Failover ping-pong A health checker moves traffic from A to B because A is "slow"; the extra load makes B slow; it moves back Traffic oscillates between replicas Hysteresis (different thresholds to switch away and back), minimum dwell time
Agent loops A planner agent asks a critic agent for review; the critic's answer triggers a re-plan; the re-plan triggers a review... Many tool and token calls, no final answer A step budget and a progress check (8.1 §1.4, 9.2)

Livelock-like behaviour is also what Ethernet's original collision protocol (CSMA/CD) solves with randomized exponential back-off: after a collision, each station waits a random number of slot times before retrying, and the range doubles with each further collision. The same idea is behind every retry policy in this course.

7.4 The cures#

  1. Randomize (jitter): add randomness to the wait so identical parties desynchronize. Cheap, universal, and what the demo used.
  2. Break the symmetry deterministically: give the parties a rank (a thread id, a node id, a tenant id) and let the lower rank win ties. This is the same trick as lock ordering.
  3. Bound the attempts: a retry loop with no maximum is a livelock waiting for the right conditions. After N tries, fail loudly or escalate.
  4. Add a coordinator: a single arbiter that grants resources removes the need for the parties to negotiate.
  5. Back off exponentially: doubling the wait lowers the collision probability each round, so conflicts resolve themselves under load instead of amplifying it.
  6. Measure progress, not activity: alert on "units of work completed per minute", not on CPU or request counts. A livelocked service has plenty of both.

Part 8: Starvation#

Deep-dive

8.1 What starvation is#

Starvation means a thread, task, request or tenant is ready to run but is never given the resource, while the rest of the system keeps working. The system as a whole is healthy (throughput looks fine), which is exactly why starvation is hard to notice: it is a property of one party's experience. A deadlock stops everyone involved; starvation stops one victim.

There is no cycle in the wait-for graph. The cause is a scheduling or locking policy that is allowed to pick someone else forever. The standard remedy is fairness: a guarantee that every waiter eventually gets a turn (strong fairness is usually "FIFO or bounded bypass": nobody is overtaken more than N times). Fairness is not free: strict FIFO hand-off costs throughput, because the next thread must be woken and scheduled before it can take the lock, while an unfair lock lets the currently running thread continue immediately. That is the reason most locks are unfair by default.

Cause of starvation Mechanism Section
Naive reader-writer lock A continuous stream of readers means the lock is never free of readers, so the writer waits forever 8.2
Unfair locks and barging A thread that releases and immediately re-acquires wins every race against the sleeping waiters 8.3
Priority inversion A high-priority task waits for a low-priority one that is itself starved by medium-priority tasks 8.4
Strict priority queues New urgent work keeps arriving, so low-priority work never runs 8.8
Shared pool full of slow jobs A quick request waits behind long jobs in the same worker pool 8.5
One task hogging an event loop A coroutine that never yields keeps everyone else off the loop 8.6
Fast producer, no backpressure The producer never suspends, so consumers never run 8.7
A noisy tenant in one FIFO queue One tenant's bulk jobs are all ahead of everyone else's 8.8

8.2 Writer starvation in read-write locks#

A read-write lock lets many readers hold the lock together, or exactly one writer hold it alone. It is a good fit for read-mostly data: a model-routing table, a prompt-template registry, a feature-flag store. The standard library has no read-write lock, so people write one. The obvious implementation has a flaw: it lets a reader in whenever no writer is inside. If readers overlap continuously (each new reader arrives before the previous one leaves), there is never a moment with zero readers, and a waiting writer is starved.

This experiment builds both versions. A new reader arrives every 10 ms and each read lasts 50 ms, so about five readers hold the lock at any moment. A writer arrives after 100 ms and waits up to 1 s.

python
# rw_starvation.py: writer starvation in a naive read-write lock, and the writer-preferring fix.
import threading
import time

class NaiveRWLock:
    """Many readers OR one writer. Readers get in whenever no writer is *inside*."""
    def __init__(self) -> None:
        self._cv = threading.Condition()
        self._readers = 0
        self._writer = False

    def acquire_read(self) -> None:
        with self._cv:
            self._cv.wait_for(lambda: not self._writer)
            self._readers += 1

    def release_read(self) -> None:
        with self._cv:
            self._readers -= 1
            self._cv.notify_all()

    def acquire_write(self, timeout: float | None = None) -> bool:
        with self._cv:
            if not self._cv.wait_for(lambda: not self._writer and self._readers == 0, timeout):
                return False
            self._writer = True
            return True

    def release_write(self) -> None:
        with self._cv:
            self._writer = False
            self._cv.notify_all()

class WriterPreferringRWLock(NaiveRWLock):
    """New readers wait while any writer is waiting, so a writer is never overtaken forever."""
    def __init__(self) -> None:
        super().__init__()
        self._writers_waiting = 0

    def acquire_read(self) -> None:
        with self._cv:
            self._cv.wait_for(lambda: not self._writer and self._writers_waiting == 0)
            self._readers += 1

    def acquire_write(self, timeout: float | None = None) -> bool:
        with self._cv:
            self._writers_waiting += 1
            try:
                if not self._cv.wait_for(lambda: not self._writer and self._readers == 0, timeout):
                    return False
                self._writer = True
                return True
            finally:
                self._writers_waiting -= 1
                self._cv.notify_all()        # readers blocked on us may proceed if we gave up

def experiment(lock: NaiveRWLock) -> str:
    stop = threading.Event()
    reads_done = 0
    count_lock = threading.Lock()

    def reader() -> None:
        nonlocal reads_done
        lock.acquire_read()
        time.sleep(0.05)                      # a 50 ms read (say, scanning a cache)
        lock.release_read()
        with count_lock:
            reads_done += 1

    def reader_stream() -> None:              # a new reader every 10 ms: at least 4-5 overlap at any moment
        threads = []
        while not stop.is_set():
            t = threading.Thread(target=reader); t.start(); threads.append(t)
            time.sleep(0.01)
        for t in threads: t.join()

    stream = threading.Thread(target=reader_stream); stream.start()
    time.sleep(0.1)                           # the read traffic is flowing
    t0 = time.perf_counter()
    got = lock.acquire_write(timeout=1.0)     # the writer arrives
    waited = time.perf_counter() - t0
    if got:
        lock.release_write()
    stop.set(); stream.join()
    return f"writer acquired: {got}, readers kept flowing meanwhile: {reads_done > 5}, writer in within 0.2 s: {got and waited < 0.2}"

print("naive RW lock            :", experiment(NaiveRWLock()))
print("writer-preferring RW lock:", experiment(WriterPreferringRWLock()))
Output2 lines
naive RW lock            : writer acquired: False, readers kept flowing meanwhile: True, writer in within 0.2 s: False
writer-preferring RW lock: writer acquired: True, readers kept flowing meanwhile: True, writer in within 0.2 s: True

The naive lock never let the writer in during a full second, while readers were being served the whole time (the typical starvation shape: the system is busy and healthy, and the victim is stuck). The writer-preferring variant counts waiting writers and makes new readers wait while any writer is waiting. Existing readers finish (50 ms), the writer enters, then readers resume.

Trade-offs of the three policies:

Policy Readers Writers Risk
Reader-preferring (naive) Never wait for a waiting writer; maximal read throughput Can starve Writer starvation
Writer-preferring New readers wait behind a waiting writer Served as soon as current readers drain Frequent writers can starve readers
Fair (FIFO-ordered) Served in arrival order, runs of consecutive readers share the lock Served in arrival order Lower peak throughput; more code

8.3 Unfair locks and barging#

Which waiting thread gets a threading.Lock when it is released? The official documentation is blunt: "which one of the waiting threads proceeds is not defined, and may vary across implementations". It says the same about semaphores ("The order in which threads are awoken should not be relied on"). No FIFO guarantee exists. Worse, a thread that releases and immediately re-acquires can win again before any waiter has even been scheduled; the sleeping waiter wakes up, finds the lock taken, and goes back to sleep. This is barging.

asyncio is different: the docs state that "Acquiring a lock is fair: the coroutine that proceeds will be the first coroutine that started waiting on the lock". The semaphore page makes no such promise, so do not assume it for asyncio.Semaphore. Here are the three behaviours side by side, with a FIFO ticket lock for threads (each arriving thread takes a ticket number and waits until "now serving" reaches it):

python
# fairness.py: who gets the lock next? asyncio.Lock is FIFO; threading.Lock promises nothing; a ticket lock is FIFO.
import asyncio
import threading
import time

# ---------- 1. asyncio.Lock hands over in arrival order ----------
async def asyncio_order() -> list[int]:
    lock = asyncio.Lock()
    order: list[int] = []
    async def job(i: int) -> None:
        async with lock:
            order.append(i)
            await asyncio.sleep(0)
    async with lock:                                   # hold it while five tasks queue up
        tasks = [asyncio.create_task(job(i)) for i in range(5)]
        await asyncio.sleep(0.01)
    await asyncio.gather(*tasks)
    return order

print("1. asyncio.Lock acquisition order:", asyncio.run(asyncio_order()))

# ---------- 2. A FIFO (ticket) lock for threads ----------
class TicketLock:
    """Threads get the lock strictly in the order they asked for it."""
    def __init__(self) -> None:
        self._cv = threading.Condition()
        self._next_ticket = 0
        self._now_serving = 0

    def acquire(self) -> None:
        with self._cv:
            my = self._next_ticket
            self._next_ticket += 1
            self._cv.wait_for(lambda: self._now_serving == my)

    def release(self) -> None:
        with self._cv:
            self._now_serving += 1
            self._cv.notify_all()

    def waiting(self) -> int:
        with self._cv:
            return self._next_ticket - self._now_serving

def ticket_order() -> list[int]:
    lock = TicketLock()
    order: list[int] = []
    lock.acquire()                                     # main holds it
    threads = []
    for i in range(5):
        def job(i: int = i) -> None:
            lock.acquire(); order.append(i); lock.release()
        t = threading.Thread(target=job); t.start(); threads.append(t)
        while lock.waiting() < i + 2:                  # wait until thread i is really queued
            time.sleep(0.001)
    lock.release()
    for t in threads: t.join()
    return order

print("2. TicketLock acquisition order  :", ticket_order())

# ---------- 3. threading.Lock: no promise. A thread that re-takes the lock at once can barge ahead ----------
def barging(seconds: float = 0.5) -> tuple[int, int]:
    lock = threading.Lock()
    stop = threading.Event()
    counts = {"hog": 0, "polite": 0}
    def hog() -> None:
        while not stop.is_set():
            with lock:
                counts["hog"] += 1                     # takes, works a little, releases, and immediately takes again
    def polite() -> None:
        while not stop.is_set():
            with lock:
                counts["polite"] += 1
            time.sleep(0)                              # yields once between turns
    ts = [threading.Thread(target=hog), threading.Thread(target=polite)]
    for t in ts: t.start()
    time.sleep(seconds); stop.set()
    for t in ts: t.join()
    return counts["hog"], counts["polite"]

hog, polite = barging()
print(f"3. hog acquired {hog:,} times, polite acquired {polite:,} times")
Output2 lines
1. asyncio.Lock acquisition order: [0, 1, 2, 3, 4]
2. TicketLock acquisition order  : [0, 1, 2, 3, 4]

The first two lines are deterministic: both locks hand over in arrival order. The third line of the program depends on the machine, so it gets the exact label:

Example output · illustrative1 line
3. hog acquired 6,401,365 times, polite acquired 1,191 times

Your counts will differ; on the machine used for this lesson the ratio was thousands to one in every run. The "hog" thread holds the lock for a nanosecond, releases, and takes it again before the other thread, which yields after each turn, gets scheduled. Both threads are always "ready"; in the run above the polite one got about 0.02 % of the turns. Nothing is deadlocked, nothing is broken, and the polite thread is for practical purposes starved.

When does this matter in a Python service?

  • A background loop that holds a shared lock in a tight cycle (a metrics flusher, a cache sweeper, a log writer) can starve request threads that need the same lock. The cure is to hold the lock for less (copy-then-release, 6.5), to sleep between turns, or to use a fair lock.
  • A fair lock is a convenience, not a free lunch. The ticket lock above is correct and simple but slower under contention (every release wakes all waiters via notify_all to find the one with the right ticket; a production version would give each waiter its own wake-up primitive). Use fairness where starvation is possible and costly, and unfair locks where critical sections are tiny and contention is low.
  • For asyncio you get FIFO locks for free, and waiters are woken in order, which is also why a slow holder makes everyone in line wait (head-of-line blocking). It is cured by shorter critical sections, not by a different lock. (The classic lock convoy is a different effect: see the Terms table.)

8.4 Priority inversion, and the Mars Pathfinder reset#

Priority inversion is when a high-priority task is delayed by a lower-priority one. The simple case is unavoidable and harmless: a low task holds a lock, the high task needs it, so the high task waits for the low task to finish its short critical section (bounded inversion). The dangerous case is unbounded inversion, which needs three tasks:

  1. L (low priority) takes a mutex and starts working in its critical section.
  2. H (high priority) becomes ready, wants the same mutex, and blocks. Only L can release it.
  3. M (medium priority, needing no lock at all) becomes ready. The scheduler runs the highest-priority ready task: M beats L. L is preempted inside its critical section and cannot run again until M finishes.

So H is effectively waiting for M, a task with lower priority than H and no relationship to the lock, for as long as M wants to run. The scheduler did exactly what it was told; the priority ordering was inverted by the lock.

Mars Pathfinder (July 1997). The spacecraft began resetting its computer repeatedly soon after landing. The mission's own post-mortem account (mirrored on the University of North Carolina site) explains it this way: the third-highest-priority bus-distribution task (bc_dist) needed a mutex that guarded shared communications state inside the vxWorks select() mechanism, a mutex that the low-priority meteorological data task (ASI/MET) held while it sent data through the pipe-based inter-task communication. Several medium-priority tasks (for instance communications) pre-empted the meteorological task while it held the mutex. The bus scheduler (bc_sched, the highest-priority task) then found that bc_dist had not finished its cycle, which was a hard deadline, "declared the error that initiated the reset" and the computer rebooted. Note that the reset came from a deadline check: the bus scheduler, running at the start of each cycle, found that the distribution task had not finished and treated that as a fault. Detecting lack of progress and resetting is what a watchdog does, and the system behaved as designed. The fix was to turn on priority inheritance for that mutex (the team changed a global variable in the vxWorks selectLib so that the mutex was created with the inheritance option), and the account states that this "corrected the problem". With priority inheritance, a low-priority task that holds a lock temporarily inherits the priority of the highest-priority task waiting for it, so M can no longer preempt it and it finishes its critical section quickly.

Here is the same story as a tick-by-tick simulation, so you can see the inversion in the schedule. One CPU, three tasks, one mutex. L runs, H arrives at tick 1 and blocks on L's mutex, M arrives at tick 2. Each letter is one tick of CPU:

python
# priority_inversion.py: a one-CPU, tick-by-tick scheduler simulation of priority inversion and priority inheritance.
# Deterministic: no threads, no clocks. Higher number = higher priority.
from dataclasses import dataclass, field

@dataclass
class Task:
    name: str
    prio: int
    arrives: int
    ops: list[str]                     # "work" = one tick of CPU; "lock"/"unlock" take no time
    pc: int = 0
    done_at: int | None = None
    blocked_on_mutex: bool = False
    eff_prio: int = field(init=False)
    def __post_init__(self) -> None:
        self.eff_prio = self.prio

def simulate(inheritance: bool) -> str:
    L = Task("L (low: weather data)", 1, 0, ["lock"] + ["work"] * 5 + ["unlock"])
    M = Task("M (medium: comms)",     2, 2, ["work"] * 8)
    H = Task("H (high: bus manager)", 3, 1, ["lock", "work", "unlock"])
    tasks = [L, M, H]
    owner: Task | None = None
    timeline: list[str] = []
    for tick in range(40):
        # zero-time ops first: lock / unlock
        for t in tasks:
            while t.done_at is None and t.arrives <= tick and t.pc < len(t.ops) and not t.blocked_on_mutex:
                op = t.ops[t.pc]
                if op == "lock":
                    if owner is None:
                        owner = t; t.pc += 1
                    else:
                        t.blocked_on_mutex = True
                        if inheritance and owner.eff_prio < t.eff_prio:
                            owner.eff_prio = t.eff_prio        # the owner inherits the waiter's priority
                elif op == "unlock":
                    owner = None; t.pc += 1; t.eff_prio = t.prio
                    for w in tasks:
                        if w.blocked_on_mutex:
                            w.blocked_on_mutex = False         # waiter retries the lock
                else:
                    break
            if t.pc == len(t.ops) and t.done_at is None and t.arrives <= tick:
                t.done_at = tick
        runnable = [t for t in tasks if t.arrives <= tick and t.done_at is None and not t.blocked_on_mutex]
        if not runnable:
            if all(t.done_at is not None for t in tasks): break
            timeline.append("."); continue
        run = max(runnable, key=lambda t: t.eff_prio)
        run.pc += 1                                            # one tick of "work"
        timeline.append(run.name[0])
        if run.pc == len(run.ops):
            run.done_at = tick + 1
    return f"{''.join(timeline)}   H finished at tick {H.done_at}"

print("no inheritance  :", simulate(False))
print("with inheritance:", simulate(True))
Output2 lines
no inheritance  : LLMMMMMMMMLLLH   H finished at tick 14
with inheritance: LLLLLHMMMMMMMM   H finished at tick 6

Without inheritance the timeline is LL (L works, H blocks at tick 1), then MMMMMMMM (M, which does not need the lock, preempts L and runs all eight of its ticks), then LLL (L finally finishes its critical section) and only then H: H completes at tick 14. With inheritance, L is boosted to H's priority when H blocks, runs straight through its critical section (LLLLL), and H finishes at tick 6; M runs afterwards.

Does Python have this problem?

  • The standard threading module exposes no thread priorities, so you cannot recreate Pathfinder with plain Threads; CPython's own locks do not implement priority inheritance, and the OS scheduler's priority is not under your control from Python.
  • But the pattern is everywhere in AI services, because priority is a business concept, not a scheduler setting: an interactive chat request (high priority) waits for a slot in an LLM client pool that is held by slow batch-embedding jobs (low priority); the chat is stuck behind work that the business considers less important, and medium-priority traffic (other chats) keeps flowing. Cures mirror priority inheritance: reserve capacity for the high-priority class (separate pools or semaphores), cap the low-priority class (so it can never take all slots), preempt (cancel or checkpoint batch work when interactive demand arrives), and keep critical sections short.
  • Real-time systems and databases (priority ceilings, SCHED_FIFO, priority-inheritance mutexes in POSIX via PTHREAD_PRIO_INHERIT) address it at the OS level. If you run Python on such a system, the C-level lock you are waiting on may or may not carry inheritance; check.

8.5 Thread-pool starvation#

A pool has a fixed number of workers. If every worker is busy with a slow job, a quick job submitted later waits in the queue, even though it would take microseconds. This is how a health check, a metrics endpoint or a cancel request gets stuck behind 60-second LLM calls, and a platform kills a healthy-but-busy pod because "the health check timed out".

python
# pool_starvation.py: a quick task waits behind slow ones in a shared pool; a separate pool fixes it. Ordering only.
from concurrent.futures import ThreadPoolExecutor
import threading

def experiment(separate_pools: bool) -> str:
    slow_gate = threading.Event()
    started = threading.Barrier(3)               # 2 slow jobs + the main thread
    bulk = ThreadPoolExecutor(max_workers=2, thread_name_prefix="bulk")
    health = ThreadPoolExecutor(max_workers=1, thread_name_prefix="health") if separate_pools else bulk
    def slow_job() -> None:
        started.wait()
        slow_gate.wait()                         # stands for a 60 s LLM call
    for _ in range(2):
        bulk.submit(slow_job)
    started.wait()                               # both workers are now busy
    health_check = health.submit(lambda: "ok")
    try:
        result = health_check.result(timeout=0.3)
    except TimeoutError:
        result = "NOT SERVED within 0.3 s (queued behind the slow jobs)"
    slow_gate.set()
    bulk.shutdown(); 
    if health is not bulk:
        health.shutdown()
    return result

print("one shared pool   :", experiment(False))
print("separate pools    :", experiment(True))
Output2 lines
one shared pool   : NOT SERVED within 0.3 s (queued behind the slow jobs)
separate pools    : ok

The quick job could not run because both workers sat in "LLM calls" (an Event.wait() standing in for them). The second run uses a separate small pool for the quick job; it ran at once. This is the bulkhead pattern, named after the watertight compartments of a ship: one flooded compartment does not sink the ship (01B.9 §6.2, 11C.3 §4.1).

A subtle variant sits inside asyncio: its default executor (the thread pool behind asyncio.to_thread(...) and loop.run_in_executor(None, ...)) is also used by the event loop for things like name resolution (loop.getaddrinfo). If your own to_thread jobs fill that executor with slow work, new network connections stall on DNS lookups even though the loop itself is idle. Give heavy to_thread work its own executor (loop.run_in_executor(my_pool, ...)), or limit how many such jobs run at once with a semaphore.

8.6 Event-loop starvation#

All coroutines on one event loop share one thread. A task that does not yield starves every other task on that loop, including heartbeats, timeouts and cancellations (and, as 01C.1 §4.5 showed, it can blow your health check). 01C.2 §4.5 covers loop fairness in depth. Here is the ordering, in miniature:

python
# loop_starvation.py: starving other tasks on ONE event loop. Everything printed is an ordering, so it is deterministic.
import asyncio

async def heartbeat(log: list[str]) -> None:
    for i in range(3):
        log.append(f"beat {i}")
        await asyncio.sleep(0)               # a real suspension: lets the loop run others

async def greedy(log: list[str], with_yield: bool) -> None:
    for i in range(3):
        log.append(f"chunk {i}")             # a slice of CPU work
        if with_yield:
            await asyncio.sleep(0)           # hand the loop back between slices

async def scenario(with_yield: bool) -> list[str]:
    log: list[str] = []
    await asyncio.gather(greedy(log, with_yield), heartbeat(log))
    return log

print("greedy never yields :", asyncio.run(scenario(False)))
print("greedy yields       :", asyncio.run(scenario(True)))

# ---------- 'await' alone does not yield: awaiting something that is already ready never suspends ----------
async def producer(q: asyncio.Queue[int], log: list[str]) -> None:
    for i in range(4):
        await q.put(i)                       # unbounded queue: put() completes at once, NO suspension
    log.append("producer finished")

async def consumer(q: asyncio.Queue[int], log: list[str]) -> None:
    for _ in range(4):
        log.append(f"consumed {await q.get()}")

async def pipeline(bounded: bool) -> list[str]:
    q: asyncio.Queue[int] = asyncio.Queue(maxsize=1 if bounded else 0)
    log: list[str] = []
    await asyncio.gather(producer(q, log), consumer(q, log))
    return log

print("unbounded queue:", asyncio.run(pipeline(False)))
print("bounded queue  :", asyncio.run(pipeline(True)))
Output4 lines
greedy never yields : ['chunk 0', 'chunk 1', 'chunk 2', 'beat 0', 'beat 1', 'beat 2']
greedy yields       : ['chunk 0', 'beat 0', 'chunk 1', 'beat 1', 'chunk 2', 'beat 2']
unbounded queue: ['producer finished', 'consumed 0', 'consumed 1', 'consumed 2', 'consumed 3']
bounded queue  : ['consumed 0', 'consumed 1', 'consumed 2', 'producer finished', 'consumed 3']

The first two lines show the cause. A coroutine that does all its CPU slices without ever awaiting something that suspends runs to completion before the loop even looks at the heartbeat task. When it inserts await asyncio.sleep(0) between slices (a real suspension point that hands control back to the loop for one iteration), the two interleave. For a real CPU-heavy chunk that cannot be sliced, run it off the loop: await asyncio.to_thread(...) (if it releases the GIL) or a process pool (01C.1 Part 3).

8.7 Unbounded retries and fast producers#

The second half of loop_starvation.py (from 8.6) is the lesson that await does not mean "yield". await q.put(i) on an unbounded asyncio.Queue completes at once (there is always room), so the awaiting coroutine never suspends. The producer's loop ran all four iterations before the consumer got a single turn: output line 3 shows producer finished first. With a bounded queue (maxsize=1) put() really does wait when the queue is full, and the consumer interleaves (line 4). This is a quiet way to starve consumers and to let the queue (memory) grow without bound, and a reason to bound queues, which is the backpressure rule of 01B.4 §3.3. The same applies to a for loop calling a non-blocking put_nowait in a thread that never sleeps.

Unbounded retry loops starve others in three ways:

  1. They hold a scarce slot while sleeping. async with semaphore: for attempt in range(10): ...; await asyncio.sleep(backoff) keeps a concurrency slot occupied during every back-off, so a flaky request uses a slot for minutes while healthy requests queue. Release the slot before sleeping and re-acquire after, or retry outside the semaphore (see 9.3).
  2. They amplify load on a struggling dependency, which slows everyone else down (retry storm, Part 7).
  3. They spin. A loop like while not ready(): pass or while True: try: acquire_nowait() except: continue consumes CPU and, on a GIL build, competes for the interpreter with the very thread that would make it ready.

The shared cure: bound attempts and total time, back off with jitter, and never hold a shared resource while waiting.

8.8 Fairness tools: fair queues, fair semaphores and aging#

Per-tenant fair queueing. A FIFO queue is fair to jobs, not to tenants. When one tenant submits 8 jobs (a bulk re-embedding) just before two others submit 2 each, FIFO makes the small tenants wait for all 8. Round-robin across tenants (one job per tenant per round) bounds how long any tenant waits by the number of tenants, not by the size of the largest backlog:

python
# fair_tenants.py: one noisy tenant starves the others in a FIFO queue; per-tenant round-robin fixes it.
from collections import deque

def fifo_order(jobs: list[tuple[str, int]]) -> list[str]:
    return [f"{t}{n}" for t, n in jobs]

def round_robin_order(jobs: list[tuple[str, int]]) -> list[str]:
    queues: dict[str, deque[int]] = {}
    for t, n in jobs:
        queues.setdefault(t, deque()).append(n)
    out: list[str] = []
    while any(queues.values()):
        for t in list(queues):                    # one job per tenant per round
            if queues[t]:
                out.append(f"{t}{queues[t].popleft()}")
    return out

# tenant "big" submits 8 jobs first (a bulk re-embedding), then "acme" and "globex" each submit 2.
jobs = [("big", i) for i in range(8)] + [("acme", i) for i in range(2)] + [("globex", i) for i in range(2)]
fifo = fifo_order(jobs)
rr = round_robin_order(jobs)
print("FIFO        :", fifo)
print("round-robin :", rr)
print("position of acme0 / globex0 in FIFO       :", fifo.index("acme0") + 1, "/", fifo.index("globex0") + 1)
print("position of acme0 / globex0 in round-robin:", rr.index("acme0") + 1, "/", rr.index("globex0") + 1)
Output4 lines
FIFO        : ['big0', 'big1', 'big2', 'big3', 'big4', 'big5', 'big6', 'big7', 'acme0', 'acme1', 'globex0', 'globex1']
round-robin : ['big0', 'acme0', 'globex0', 'big1', 'acme1', 'globex1', 'big2', 'big3', 'big4', 'big5', 'big6', 'big7']
position of acme0 / globex0 in FIFO       : 9 / 11
position of acme0 / globex0 in round-robin: 2 / 3

acme's first job moves from position 9 to position 2, and globex's from 11 to 3. The big tenant's work is not lost, only interleaved. This is the idea behind weighted fair queueing in networks and tenant fairness in LLM gateways (11C.3 §7.3). Weighted variants give a paying tier more turns per round.

Aging. A strict priority queue can starve low-priority work indefinitely, if urgent work keeps arriving faster than it is served. Aging gradually raises the priority of a waiting item, in proportion to how long it has waited, so every item eventually becomes the most urgent:

python
# aging.py: a priority queue that starves low-priority jobs, and aging that fixes it. Deterministic simulation.
import heapq

BASE = {"batch": 9.0, "chat": 1.0}     # lower number = more urgent

def serve(aging: float, steps: int = 40) -> str:
    """One job is served per step. Two NEW urgent 'chat' jobs arrive per step (faster than we serve);
    one 'batch' job has been waiting since step 0. Effective priority = base - aging * time_waited."""
    waiting: list[tuple[str, int, int]] = [("batch", 0, 0)]        # (kind, arrival_step, sequence number)
    seq = 1
    for step in range(1, steps + 1):
        for _ in range(2):
            waiting.append(("chat", step, seq)); seq += 1
        # Re-score every waiting job from its base priority and how long it has waited, then serve the best.
        scored = [(BASE[kind] - aging * (step - arrived), s, kind, arrived) for kind, arrived, s in waiting]
        best = heapq.nsmallest(1, scored)[0]
        waiting.remove((best[2], best[3], best[1]))
        if best[2] == "batch":
            return f"batch job served at step {step}"
    return f"batch job still waiting after {steps} steps ({len(waiting)} jobs queued, backlog growing)"

print("strict priority :", serve(aging=0.0))
print("with aging 0.5  :", serve(aging=0.5))
Output2 lines
strict priority : batch job still waiting after 40 steps (41 jobs queued, backlog growing)
with aging 0.5  : batch job served at step 31

With strict priority the batch job was still waiting after 40 steps behind a growing backlog; with aging (priority improves by 0.5 for each step waited) it is served at step 31, still after the chats that had waited longest, but not never. Aging is how operating-system schedulers avoid starving low-priority processes. Tune the rate: too fast and priorities mean nothing; too slow and the wait is long.

Fair semaphores. threading.Semaphore promises no wake-up order. To get FIFO fairness, queue waiters explicitly: each waiter gets its own Event (or asyncio.Future) appended to a deque, and release() hands the permit to the head of the deque rather than incrementing a shared counter. A permit given directly to the head cannot be stolen (no barging). For most services the right move is not a cleverer semaphore but separate limits per class (bulkheads, 8.5) so classes cannot starve each other.

8.9 Measuring starvation#

You cannot see starvation in averages. Use:

  • Wait time, not just run time, as a metric: time from enqueue to start, per queue, per tenant, per priority class. Watch p99 and max, not the mean.
  • Age of the oldest waiting item (a gauge). A rising oldest-age with steady throughput is the starvation signature; with zero throughput it is deadlock.
  • Per-class throughput. If class A completes 1,000 jobs/min and class B completes 0, you have your answer.
  • In-flight count versus capacity (Little's law, 01C.1 §3.5): if every slot is permanently occupied and the queue is growing, you are saturated, and who gets the slots is a fairness question.
  • Event-loop lag: a heartbeat task measuring how late it runs (01C.1 §4.5).

Part 9: AI-service cases#

The patterns above show up in AI engineering in a handful of recurring forms. All demos use a fake model (asyncio.sleep) so they cost nothing and finish by themselves.

9.1 Nested LLM calls and the exhausted client pool#

You cap concurrent model calls with a semaphore (the right move: 01B.4 Part 1, 03.9 §4.2). Then someone writes an agent that takes a slot for the whole agent run and, inside it, makes sub-calls that need more slots. With two slots and two agents:

python
# nested_llm_calls.py: an agent holds an LLM-client slot while its sub-agents wait for one. Fake model: asyncio.sleep.
import asyncio

async def fake_llm(prompt: str) -> str:
    await asyncio.sleep(0.01)
    return f"answer({prompt})"

async def run(design: str) -> str:
    slots = asyncio.Semaphore(2)                  # "at most 2 LLM calls in flight"

    async def call_llm(prompt: str) -> str:
        async with slots:
            return await fake_llm(prompt)

    async def agent_bad(name: str) -> str:
        async with slots:                         # BUG: holds a slot for the whole agent ...
            await fake_llm(f"{name}: plan")
            subs = await asyncio.gather(*(call_llm(f"{name}.sub{i}") for i in range(2)))   # ... then needs more
            return f"{name} done with {len(subs)} sub-results"

    async def agent_good(name: str) -> str:
        plan = await call_llm(f"{name}: plan")    # a slot is held only for the duration of one model call
        subs = await asyncio.gather(*(call_llm(f"{name}.sub{i}") for i in range(2)))
        return f"{name} done with {len(subs)} sub-results"

    agent = agent_bad if design == "bad" else agent_good
    try:
        results = await asyncio.wait_for(asyncio.gather(agent("A"), agent("B")), timeout=1.0)
        return "; ".join(results)
    except TimeoutError:
        return "TIMEOUT: both agents hold a slot and wait for another one (hold-and-wait)"

print("slot held across sub-calls:", asyncio.run(run("bad")))
print("slot held per model call  :", asyncio.run(run("good")))
Output2 lines
slot held across sub-calls: TIMEOUT: both agents hold a slot and wait for another one (hold-and-wait)
slot held per model call  : A done with 2 sub-results; B done with 2 sub-results

In the bad design, agent A holds slot 1 and agent B holds slot 2; each now asks for a third and fourth slot for its sub-calls. Nothing is free and nothing will be freed: the semaphore is a pool of exclusive resources, and this is hold-and-wait with permits instead of locks. It is the same bug as the thread-pool deadlock (3.2), and it appears in the same way: fine in tests (one agent), a hang in production under load. The fix is to hold a slot only for the duration of one model call (acquire at the leaf, never at the orchestrating layer), which is exactly call_llm in the good design. If an orchestration layer must be limited too, give it a separate semaphore: an agent-count limit and a model-call limit are different resources, and as long as you always take them in the same order (agent slot, then call slot, never the reverse) there is no cycle.

9.2 Agents that wait on each other#

Multi-agent systems (08D.3) add message dependencies between components. The same three failure modes appear: deadlock (A waits for B's reply while B waits for A's), livelock (A hands the task to B, who hands it back, with no progress) and starvation (one busy agent's inbox is never drained). That course's section on conflicts, shared state, deadlocks and loops is the design view; this is the mechanism:

python
# agents_deadlock.py: agents that handle one request at a time and ask each other for help.
# Fake model work only (asyncio.sleep). Scenario 1 and 2: hold-and-wait and its fix. Scenario 3: a call loop.
import asyncio

class Agent:
    def __init__(self, name: str) -> None:
        self.name = name
        self.busy = asyncio.Lock()                # one request at a time (shared scratchpad / single context)

    async def answer(self, question: str) -> str:          # a leaf request: needs our busy-lock briefly
        async with self.busy:
            await asyncio.sleep(0.01)                      # "thinking"
            return f"[{self.name}] answered '{question}'"

    async def solve(self, peer: "Agent", hold_while_delegating: bool) -> str:
        async with self.busy:
            await asyncio.sleep(0.01)                      # our own thinking, under our lock
            if hold_while_delegating:
                helped = await peer.answer("sub-question") # hold and wait: we still own our busy-lock
                return f"[{self.name}] used ({helped})"
        helped = await peer.answer("sub-question")         # fix: our lock is released before we wait
        return f"[{self.name}] used ({helped})"

async def two_users(hold: bool) -> str:
    a, b = Agent("A"), Agent("B")
    try:
        results = await asyncio.wait_for(
            asyncio.gather(a.solve(b, hold), b.solve(a, hold)), timeout=0.5)
        return " | ".join(results)
    except TimeoutError:
        return "TIMEOUT: each agent holds its own lock and waits for the other's"

async def ask(agent: str, peers: dict[str, str], chain: tuple[str, ...] = ()) -> str:
    """Each agent delegates to its peer. The chain guard refuses a request that already passed through us."""
    if agent in chain:
        return f"[{agent}] refuses (chain {' -> '.join(chain)} would loop)"
    await asyncio.sleep(0)
    return f"[{agent}] used ({await ask(peers[agent], peers, chain + (agent,))})"

print("1. delegating while holding own lock:", asyncio.run(two_users(True)))
print("2. delegating with no lock held     :", asyncio.run(two_users(False)))
print("3. A asks B, B asks A               :", asyncio.run(ask("A", {"A": "B", "B": "A"})))
Output3 lines
1. delegating while holding own lock: TIMEOUT: each agent holds its own lock and waits for the other's
2. delegating with no lock held     : [A] used ([B] answered 'sub-question') | [B] used ([A] answered 'sub-question')
3. A asks B, B asks A               : [A] used ([B] used ([A] refuses (chain A -> B would loop)))
  1. Each agent processes one request at a time (a lock around its scratchpad), and while holding its own lock delegates a sub-question to the other agent, which needs its lock. Two simultaneous users, one per agent, produce the cross-wait. It is the two-lock deadlock of 2.1 with agents as the locks.
  2. The fix: do not hold your own lock while waiting for someone else. Do your own thinking under the lock, release it, then delegate.
  3. A single request that bounces A → B → A is not a lock problem at all but a loop. A call-chain guard (pass the list of agents already visited, refuse to re-enter) ends it deterministically. Combine it with a maximum depth and the step budgets of 08A.2, so a missing guard costs a bounded amount of money instead of an unbounded one.

General rules for agent graphs: (a) every cross-agent wait has a timeout and a defined fallback (return partial results, escalate to a human); (b) prefer asynchronous hand-offs (fire a task to a queue and continue) over blocking request-response between agents; (c) keep the agent call graph a DAG where you can (a planner may call workers, workers may not call the planner); (d) never let one agent's inbox be unbounded or unfair.

9.3 Semaphore and rate limiter: which comes first?#

An LLM client usually needs two limiters: a concurrency cap (a semaphore) and a rate limit (a token bucket: requests per minute, tokens per minute; 01B.4 Part 4). They are different resources, and the order in which you acquire them matters, not for deadlock but for starvation and idle capacity:

python
# ordering_sketch.py: two ways to combine a concurrency cap and a rate limiter.
# `limiter.wait()` stands for "wait until the token bucket allows one more request".
import asyncio
from typing import Awaitable, Callable

async def slot_then_rate(sem: asyncio.Semaphore, limiter, call: Callable[[], Awaitable[str]]) -> str:
    async with sem:                      # takes a scarce concurrency slot ...
        await limiter.wait()             # ... then may sit idle waiting for a rate-limit token
        return await call()

async def rate_then_slot(sem: asyncio.Semaphore, limiter, call: Callable[[], Awaitable[str]]) -> str:
    await limiter.wait()                 # wait for the token while holding nothing ...
    async with sem:                      # ... then take a slot only when the request can start now
        return await call()

In slot_then_rate, a task that holds one of N slots spends its time waiting for a token while the slot is idle. If the rate limit is the bottleneck, all N slots end up held by tasks waiting for tokens, so effective concurrency is held artificially low, and anything else that needs a slot but not a token (a cheap local-model call or a cached lookup sharing the semaphore) is starved by tasks that cannot even start. rate_then_slot waits for the token first, holding nothing, then takes a slot only when the request is ready to go. The general rule: acquire the limit you may wait longest on first, while holding nothing, and acquire the limit you hold longest last. Never hold a scarce resource while waiting for a different one. If the two orders are mixed in different code paths (some callers acquire slot-then-rate, others rate-then-slot), you also have the opposite-order pattern of 2.1, and a real cycle appears if the limiter's refill depends on work that itself needs a slot (for example a limiter that learns its quota from a response header, fetched through the same semaphore). Pick one order for the whole codebase and encapsulate it in one async with limits: helper.

9.4 Other AI-shaped hangs#

  • A tool that calls the agent that called it. The tool handler blocks on a lock or a thread that the agent loop already holds. Treat tool execution as foreign code: never call it while holding an agent lock (6.5), and give every tool call a timeout (08A.6).
  • Single-flight cache that waits for itself. A "compute once, everyone else waits" cache where the computation (an embedding or a summary) itself looks up the same key: the first caller waits for its own future (01C.3 §4.2, 01C.3 §6.2 show the pattern; add a timeout and a recursion check).
  • Streaming response, client gone. A producer writes tokens into a bounded queue; the consumer (the HTTP response) has disconnected and stopped reading; the producer blocks on put() forever, holding an LLM-client slot and a connection. Always cancel the producer when the consumer goes away (11C.3 §5.2).
  • Training/inference data loaders. A worker process blocked on a full multiprocessing.Queue while the parent has stopped consuming (an exception in the training loop) leaves orphaned workers; same family as 3.4.

Reference

Symptoms you will actually see, how to confirm each, and the fix. Use the CPU-first triage of 1.3 to find the right row.

# Symptom Cause How to confirm Fix
1 Worker hangs, CPU ~0 %, nothing in logs; shows up under load only Opposite lock order (2.1) Stack dump: two threads parked on acquire lines, each inside the other's with Global lock order (6.2); timeouts (6.3)
2 A thread hangs the first time a helper is called Non-reentrant Lock taken twice by one thread (2.2) Dump shows the thread parked in acquire under a with on the same lock Split public/private methods; RLock only if needed
3 A consumer thread sleeps forever though work was sent Lost wake-up (2.4) Dump shows Condition.wait with no timeout; predicate already true wait_for(predicate) in a loop; use Event for one-shot signals
4 Pipeline stops; queue sizes at their maximum Stage feeding its own bounded queue (3.1) Dump: all workers in put; queue at maxsize Unbounded feedback edge, put(timeout), separate queues
5 queue.join() never returns A consumer skipped task_done() (crash or forgot) q.unfinished_tasks stays above zero with empty queue task_done() in finally; Queue.shutdown() (3.13+)
6 ThreadPoolExecutor stuck at 100 % of workers busy, 0 % CPU Tasks waiting on futures from the same pool (3.2) Dump: all workers in Future.result Separate pools, inline sub-work, timeouts on result()
7 Forked worker hangs at start-up on Linux only fork() copied a lock held by another thread (3.3) DeprecationWarning about multi-threaded fork; child parked in acquire spawn/forkserver; fork before threads; os.register_at_fork
8 A process never exits after join() multiprocessing.Queue not drained (3.4) Child alive at join(timeout); large items in the queue get() before join(); use a Manager queue or sentinel
9 Subprocess call hangs on big output only wait() with stdout=PIPE Child writes more than the pipe buffer communicate() or subprocess.run(..., capture_output=True, timeout=...)
10 asyncio service stops responding, all tasks "pending" Task cycle, non-reentrant asyncio.Lock, unresolved future, or .result() on the loop thread (3.5) python -m asyncio ps/pstree PID (3.14+); asyncio.all_tasks() Timeouts on every await; fix the cycle; never block the loop thread
11 database is locked / deadlock detected Two transactions lock rows in opposite order, or a lock upgrade (4.1) DB logs (log_lock_waits, InnoDB status) Same lock order, BEGIN IMMEDIATE, short transactions, retry the whole transaction
12 Both threads at 100 % CPU, no progress Livelock: lockstep retry (7.2) High CPU plus zero completed work per minute Jitter, tie-breaker, bounded attempts
13 Writers or rare operations never run Reader-preferring read-write lock (8.2) Writer wait time grows while readers flow Writer-preferring or fair lock; immutable snapshot
14 One thread gets almost every turn of a lock Barging on an unfair lock (8.3) Per-thread acquisition counts hugely uneven Shorter critical sections; ticket (FIFO) lock
15 Interactive requests slow while batch jobs run Priority inversion through a shared pool (8.4) Chat wait time rises with batch load Reserved capacity, separate pools, cap low priority
16 Health check times out though workers are fine Quick work queued behind slow work in one pool (8.5) Queue wait time of the probe job Bulkhead: separate pool for control-plane work
17 Network calls stall while the loop is idle asyncio default executor full of slow to_thread jobs, starving DNS lookups (8.5) Executor queue growing; getaddrinfo slow Dedicated executor for heavy jobs; limit with a semaphore
18 Heartbeats late, tasks starved on one loop A coroutine that never suspends (8.6) Loop-lag metric; debug-mode slow-callback log await between slices, to_thread or a process pool
19 Consumers idle, queue growing, producer finishes first await put() on an unbounded queue never suspends (8.7) Memory grows; consumption starts late Bounded queue; backpressure
20 Small tenants wait while one tenant's bulk job runs One FIFO queue (8.8) Per-tenant wait time Round-robin or weighted fair queueing
21 All agents "busy", none progressing, model-call slots all taken Slot held across nested calls (9.1) Semaphore at zero; dumps show agents awaiting sub-calls Acquire at the leaf only; separate limits
22 Agents pass a task back and forth, bills rise Call loop (9.2) Repeating agent names in traces Chain guard, depth cap, step budget
23 Throughput capped though the provider has headroom Concurrency slots held while waiting for rate-limit tokens (9.3) In-flight count at cap, requests per second below the limit Rate limit first, slot second

A last note on method. Liveness bugs are intermittent and load-dependent, so the best investment is instrumentation you can read after the fact: a watchdog that dumps stacks (5.5), a faulthandler signal (5.2), and an "age of the oldest in-flight job" metric (8.9). They turn a once-a-month mystery into a stack trace.


Common misconceptions#

Misconception Reality
"The GIL means Python can't deadlock" The GIL serializes bytecode, not your lock sequences. Every demo here deadlocked on a normal GIL build (3.6)
"asyncio is single-threaded, so no deadlocks" await is waiting. Task cycles, non-reentrant asyncio.Lock, unresolved futures and .result() on the loop thread all hang (3.5)
"If it passes tests, the lock order is fine" A deadlock needs one unlucky interleaving; code with inconsistent order is wrong on every run and hangs on some (1.2)
"RLock fixes deadlocks" It fixes a thread re-entering one lock. It does nothing for two threads and two locks (2.2)
"A timeout fixes the deadlock" A timeout turns a hang into an error. The cycle still exists; you must still fix the order or the design (6.3)
"Bigger thread pool = no more pool deadlocks" It only raises the load at which they occur. Never wait on a same-pool future (3.2)
"Livelock is just a slow deadlock" Opposite behaviour: CPU is busy, state keeps changing, and nothing completes (Part 7)
"Starvation means the system is overloaded" The system can be healthy overall. Starvation is unfairness, visible in per-party wait time, not in averages (8.1)
"threading.Lock is FIFO" The docs promise no order; barging is real (8.3). asyncio.Lock is documented as fair
"await always lets other tasks run" Awaiting something already ready (an unbounded put) never suspends (8.7)
"Priority inversion only matters on spacecraft" Priority is a business concept: chat versus batch sharing a pool inverts exactly as L, M and H do (8.4)
"Databases handle deadlocks, so I needn't" They abort one victim; you must retry the whole transaction, without double side effects (4.1)

Key takeaways#

  • A deadlock needs all four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait. Break any one and it is impossible; each prevention technique is "break condition N".
  • Deadlocks need no "lock" in the narrow sense: full bounded queues, join() without task_done(), same-pool futures, pipe buffers, held semaphore permits and asyncio waits all qualify.
  • Triage by CPU: 0 % and no progress is a wait (deadlock, lost wake-up, missing timeout); high CPU and no progress is livelock; normal CPU with one victim is starvation.
  • Always lock in one global order; never take two locks if you can restructure so you need one; never hold a lock across I/O, an LLM call or foreign code; use copy-then-release.
  • Put a timeout on every wait that depends on another party, and handle the failure. Timeouts turn silent hangs into attributable errors.
  • Make the next hang self-reporting: faulthandler (dump_traceback_later, register), a heartbeat watchdog, py-spy dump, and, on 3.14, python -m asyncio ps/pstree. A wait-for graph with a cycle search is a ~60-line detector for your key locks.
  • Do not use fork with threads; spawn or forkserver are the safe defaults (POSIX default became forkserver in 3.14). Drain queues before join(), use communicate() with pipes.
  • Livelock is cured by jitter, rank tie-breakers, bounded attempts and exponential back-off. Starvation is cured by fairness: writer preference, FIFO or ticket locks, aging, per-class pools, round-robin across tenants.
  • Priority inversion (Mars Pathfinder) is a low-priority holder starved by medium-priority work while a high-priority task waits. Cure: priority inheritance, or, in services, reserved capacity and separate pools.
  • For AI services: hold an LLM-client slot only for the duration of one model call, never across a nested agent run; give agent graphs timeouts, chain guards and budgets; acquire the rate limit before the concurrency slot.

Terms introduced in this lesson#

Term Meaning
Deadlock A state where each member of a set of parties holds something and waits for something held by another member, so none can proceed
Livelock Parties keep reacting to each other and consuming CPU, but make no progress
Starvation A ready party is repeatedly passed over and never gets the resource, while others progress
Liveness failure A failure to make progress (deadlock, livelock, starvation), as opposed to a safety failure such as a wrong result
Coffman conditions The four conditions that must all hold for a deadlock: mutual exclusion, hold and wait, no preemption, circular wait
Hold and wait Holding one resource while waiting for another
Circular wait A cycle of parties each waiting for a resource held by the next
Wait-for graph A graph with an edge from A to B when A waits for something B holds; a cycle means deadlock (for single-unit resources)
Lock ordering Always acquiring locks in one global order so that circular wait cannot form
Lock hierarchy Ranked locks where acquiring a lock of equal or lower rank than one already held is an error
Reentrant lock (RLock) A lock that its owner can acquire again without blocking; released once per acquire
Self-deadlock A thread waiting for a non-reentrant lock it already holds
Lost wake-up Waiting for a notification that was already sent and forgotten
Try-lock / timed acquire Attempting to take a lock without waiting indefinitely (acquire(blocking=False) or acquire(timeout=...))
Dining philosophers The classic model of circular wait: five diners need two shared forks each
Watchdog A separate thread or process that expects regular heartbeats and acts when they stop
Heartbeat A regular proof-of-life signal from the code being guarded
Barging A running thread re-acquiring a lock ahead of threads already waiting for it
Ticket lock A FIFO lock: each arriving thread takes a number and waits until its number is served
Fair lock A lock that guarantees waiters are served in a defined order (usually arrival order)
Reader-writer lock A lock allowing many concurrent readers or one exclusive writer
Writer starvation A writer repeatedly overtaken by new readers and never admitted
Priority inversion A high-priority task delayed by a lower-priority one holding a needed resource
Priority inheritance A lock holder temporarily taking the priority of the highest-priority waiter, to finish quickly
Aging Raising the effective priority of an item the longer it waits, to prevent starvation
Bulkhead Separate resource pools for separate workloads so one cannot exhaust the other
Fair queueing / round-robin Serving one job per tenant or class per round instead of in global arrival order
Head-of-line blocking Many waiters queued behind one slow holder of a fair lock or resource; plain queueing delay
Lock convoy A throughput collapse where threads keep queueing on a hot lock and every release forces a hand-off and a context switch; related to the GIL convoy effect in 01C.5 §3.4
Deadlock victim The transaction a database aborts to break a deadlock

Exercises#

  1. Coffman audit. For each prevention technique below, say which of the four conditions it breaks: (a) global lock ordering; (b) acquire(timeout=...) with release-and-retry; (c) a single owner thread receiving messages; (d) taking all needed locks together in one operation; (e) a database aborting a victim transaction.
  2. Fix the transfer. Two threads transfer money between accounts a and b in opposite directions, each locking src then dst. Write the fixed transfer using lock ordering by account id, run 20,000 transfers each way, and check that both threads finish and the total is unchanged.
  3. Predict, then run. Without running it, say what each of the four lines A-D prints in the script of the solution (it uses RLock, Lock.acquire(blocking=False), a timed second acquire and an invalid combination).
  4. A loud lock. Write a locked(lock, name, timeout) context manager that raises a TimeoutError naming the lock instead of hanging, and show it catching a self-deadlock.
  5. Fix the pool. Take the nested-submit deadlock of 3.2 and fix it without a second pool.
  6. Clean shutdown. Rewrite a three-consumer queue pipeline to stop with Queue.shutdown() (Python 3.13+) instead of sentinels, with task_done() in a finally and join() returning.
  7. Three-way cycle. Construct a deterministic deadlock of three threads (T0 holds X wants Y, T1 holds Y wants Z, T2 holds Z wants X) and print what each thread holds and wanted.
  8. A task awaits itself. What does await asyncio.current_task() do inside a task on your Python version?
  9. Why jitter? Fifty clients fail at the same instant and retry after a fixed 500 ms, or after a uniform random delay in [0, 500 ms]. Count the largest number of retries that land in one 10 ms window in each case.
  10. Weighted fairness. Extend round-robin so that a pro tenant (weight 2) gets two jobs per round and a free tenant (weight 1) one. Show the order for 4 free jobs and 6 pro jobs.
  11. Triage. Classify each and name the first thing to measure. (a) The process is at 0 % CPU and no job has completed for 20 minutes. (b) Two worker processes are at 100 % CPU and the completed-jobs counter is flat. (c) Latency is fine on average but one tenant's p99 wait is 40 minutes. (d) The child process started with fork hangs on its first logging call. (e) queue.join() returns never; the queue is empty.
  12. Limits helper. Write an async with limits(...) helper that acquires the rate-limit token first and the concurrency slot second (9.3), with a fake limiter, and print the order of events for two calls.
  13. Dump to a file. Use faulthandler.dump_traceback_later to write a dump to a file after 0.3 s while one extra thread is blocked, and count the threads in the file.
Solution

1. (a) Circular wait. (b) No preemption (you voluntarily give back what you hold). (c) Mutual exclusion on the shared state (only the owner touches it, so no lock is shared). (d) Hold and wait (nothing is held while waiting; you either get everything or nothing). (e) No preemption (the database takes away the victim's locks by rolling it back).

2. Ordering by account id, so transfer(a, b) and transfer(b, a) both lock account 1 first:

python
# ex2_transfer.py: fix an opposite-order transfer by ordering the locks by account id.
import threading

class Account:
    def __init__(self, ident: int, balance: int) -> None:
        self.ident, self.balance = ident, balance
        self.lock = threading.Lock()

def transfer(src: Account, dst: Account, amount: int) -> None:
    first, second = (src, dst) if src.ident < dst.ident else (dst, src)   # lower id first, always
    with first.lock, second.lock:
        src.balance -= amount
        dst.balance += amount

a, b = Account(1, 100), Account(2, 100)
def worker(x: Account, y: Account) -> None:
    for _ in range(20_000):
        transfer(x, y, 1)

ts = [threading.Thread(target=worker, args=(a, b)), threading.Thread(target=worker, args=(b, a))]
for t in ts: t.start()
for t in ts: t.join(timeout=10)
print("finished:", not any(t.is_alive() for t in ts), "| total =", a.balance + b.balance)
Output1 line
finished: True | total = 200

3. A prints True (the same thread may re-enter an RLock; _is_owned is a private helper used only to peek). B prints False (non-blocking try on a held Lock returns immediately). C prints False after 0.2 s (timed try expires). D raises ValueError ("can't specify a timeout for a non-blocking call"); that is the documented rule that a timeout is forbidden with blocking=False.

python
# ex3_predict.py: predict what each line prints, then run it.
import threading

lock = threading.Lock()
rlock = threading.RLock()

with rlock:
    with rlock:
        print("A: RLock twice ->", rlock._is_owned())     # _is_owned is a private helper, used here only to peek

with lock:
    print("B: Lock, non-blocking second try ->", lock.acquire(blocking=False))

with lock:
    print("C: Lock, 0.2 s timeout second try ->", lock.acquire(timeout=0.2))

try:
    lock.acquire(blocking=False, timeout=1)
except ValueError as e:
    print("D:", e)
Output4 lines
A: RLock twice -> True
B: Lock, non-blocking second try -> False
C: Lock, 0.2 s timeout second try -> False
D: can't specify a timeout for a non-blocking call

4.

python
# ex4_timeout_lock.py: a `with`-compatible lock helper that fails loudly instead of hanging.
import threading
from contextlib import contextmanager

@contextmanager
def locked(lock: threading.Lock, name: str, timeout: float = 5.0):
    if not lock.acquire(timeout=timeout):
        raise TimeoutError(f"could not acquire {name!r} within {timeout} s (possible deadlock)")
    try:
        yield
    finally:
        lock.release()

budget = threading.Lock()
with locked(budget, "budget"):
    try:
        with locked(budget, "budget", timeout=0.2):      # same thread again: would hang with a plain `with`
            pass
    except TimeoutError as e:
        print("TimeoutError:", e)
Output1 line
TimeoutError: could not acquire 'budget' within 0.2 s (possible deadlock)

5. Do the sub-work inline: the parent computes the leaf results itself instead of waiting for another worker, so there is nothing to wait for and two workers suffice for any number of parents. (Another valid fix is a second pool.)

python
# ex5_pool_fix.py: the nested-submit deadlock, fixed by doing the sub-work inline (no second wait on the pool).
from concurrent.futures import ThreadPoolExecutor

def leaf(n: int) -> int:
    return n * 2

def parent(n: int) -> int:
    return sum(leaf(n + i) for i in range(3))     # sub-work done in this very thread: nothing to wait for

with ThreadPoolExecutor(max_workers=2) as pool:   # 2 workers is enough now, however many parents there are
    print(list(pool.map(parent, range(6))))
Output1 line
[6, 12, 18, 24, 30, 36]

6. q.shutdown() stops new puts; consumers drain what is left, then get() raises queue.ShutDown and they return. task_done() in finally lets join() finish:

python
# ex6_shutdown.py (Python 3.13+): stop consumers cleanly with Queue.shutdown() instead of one sentinel each.
import queue
import threading

q: queue.Queue[int] = queue.Queue()
results: list[int] = []
lock = threading.Lock()

def consumer() -> None:
    while True:
        try:
            item = q.get()
        except queue.ShutDown:                    # raised once the queue is shut down AND empty
            return
        try:
            with lock:
                results.append(item * item)
        finally:
            q.task_done()                         # always, even if processing failed

workers = [threading.Thread(target=consumer) for _ in range(3)]
for w in workers: w.start()
for i in range(10):
    q.put(i)
q.shutdown()                                      # no more puts; consumers drain what is left, then exit
q.join()                                          # returns: every item got its task_done()
for w in workers: w.join(timeout=5)
print("sorted results:", sorted(results), "| workers alive:", sum(w.is_alive() for w in workers))
Output1 line
sorted results: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] | workers alive: 0

7. Each thread takes its first lock, meets a barrier so that all three hold one lock, then tries its second with a timeout; the three timeouts form the cycle X to Y to Z to X:

python
# ex7_three_cycle.py: a three-thread cycle, found by reading who holds what.
import threading

locks = {name: threading.Lock() for name in "XYZ"}
step = threading.Barrier(3)
results: dict[str, str] = {}

def worker(name: str, first: str, second: str) -> None:
    with locks[first]:
        step.wait()
        ok = locks[second].acquire(timeout=0.5)
        results[name] = f"holds {first}, wanted {second}: {'got it' if ok else 'blocked'}"
        if ok:
            locks[second].release()
        step.wait()                               # all three give up together (demo only)

ts = [threading.Thread(target=worker, args=(f"T{i}", a, b))
      for i, (a, b) in enumerate([("X", "Y"), ("Y", "Z"), ("Z", "X")])]
for t in ts: t.start()
for t in ts: t.join()
for name in sorted(results): print(name, results[name])
Output3 lines
T0 holds X, wanted Y: blocked
T1 holds Y, wanted Z: blocked
T2 holds Z, wanted X: blocked

8. On Python 3.14.6 the task raises immediately instead of hanging:

python
# ex8_self_await.py: what happens if a task awaits itself?
import asyncio

async def main() -> None:
    async def selfish() -> None:
        await asyncio.current_task()          # waits for itself
    try:
        await asyncio.wait_for(asyncio.create_task(selfish()), timeout=0.5)
    except RuntimeError as e:
        print("RuntimeError:", str(e).split(":")[0])   # the full message also shows the task repr, with paths
    except TimeoutError:
        print("TimeoutError: it just hangs")

asyncio.run(main())
Output1 line
RuntimeError: Task cannot await on itself

asyncio checks the trivial self-cycle but not longer cycles, which is why 3.5 case 1 hangs silently. (This check is observed behaviour of the version tested here.)

9. With a fixed delay all 50 clients retry in the same window; with full jitter the load is spread. The exact jittered figure depends on the seed (fixed to 1 here):

python
# ex9_jitter.py: 50 clients fail at the same instant. How synchronized is the retry wave?
import random

def worst_bucket(delays: list[float], bucket: float = 0.01) -> int:
    counts: dict[int, int] = {}
    for d in delays:
        counts[int(d / bucket)] = counts.get(int(d / bucket), 0) + 1
    return max(counts.values())

rng = random.Random(1)
clients = 50
fixed = [0.5] * clients                                   # everybody retries after exactly 500 ms
jittered = [rng.uniform(0, 0.5) for _ in range(clients)]  # "full jitter": uniform in [0, 500 ms]
print("fixed delay   : most clients in one 10 ms window =", worst_bucket(fixed))
print("full jitter   : most clients in one 10 ms window =", worst_bucket(jittered))
Output2 lines
fixed delay   : most clients in one 10 ms window = 50
full jitter   : most clients in one 10 ms window = 5

10. Give each tenant weight pops per round:

python
# ex10_weighted.py: weighted round-robin across tenants (a tenant with weight 2 gets two jobs per round).
from collections import deque

def weighted_round_robin(jobs: dict[str, list[str]], weights: dict[str, int]) -> list[str]:
    queues = {t: deque(js) for t, js in jobs.items()}
    out: list[str] = []
    while any(queues.values()):
        for t in queues:
            for _ in range(weights.get(t, 1)):
                if queues[t]:
                    out.append(queues[t].popleft())
    return out

jobs = {"free": [f"free{i}" for i in range(4)], "pro": [f"pro{i}" for i in range(6)]}
print(weighted_round_robin(jobs, {"free": 1, "pro": 2}))
Output1 line
['free0', 'pro0', 'pro1', 'free1', 'pro2', 'pro3', 'free2', 'pro4', 'pro5', 'free3']

11. (a) Deadlock or missing timeout (0 % CPU, no progress): take a stack dump (py-spy dump, faulthandler). (b) Livelock or a runaway loop (high CPU, no progress): measure completed work per minute and look at the retry counters. (c) Starvation: per-tenant wait-time percentiles and the age of the oldest waiting job. (d) Lock held by another thread at the moment of fork: look for the multi-thread DeprecationWarning; switch to spawn or forkserver. (e) A missing task_done() (or a consumer crash): check q.unfinished_tasks; put task_done() in finally.

12.

python
# ex12_limits.py: one helper that always takes the rate-limit token first and the concurrency slot second.
import asyncio
from contextlib import asynccontextmanager

class TokenBucket:                                        # a fake limiter: grants one token every 10 ms
    def __init__(self, log: list[str]) -> None:
        self.log = log
    async def wait(self) -> None:
        await asyncio.sleep(0.01)
        self.log.append("token")

@asynccontextmanager
async def limits(bucket: TokenBucket, sem: asyncio.Semaphore, log: list[str]):
    await bucket.wait()               # 1) wait for the rate limit while holding NOTHING
    async with sem:                   # 2) then take a slot only for the call itself
        log.append("slot")
        yield

async def main() -> None:
    log: list[str] = []
    bucket, sem = TokenBucket(log), asyncio.Semaphore(1)
    async def call(i: int) -> None:
        async with limits(bucket, sem, log):
            log.append(f"call {i}")
    await asyncio.gather(*(call(i) for i in range(2)))
    print(log)

asyncio.run(main())
Output1 line
['token', 'slot', 'call 0', 'token', 'slot', 'call 1']

The token wait happens while holding nothing; the slot is taken only for the call itself. (The fake limiter does not ration; a real token bucket would space the tokens.)

13.

python
# ex13_dump_file.py: arm faulthandler's watchdog to write to a file, then count how many threads it listed.
import faulthandler
import os
import tempfile
import threading
import time

lock = threading.Lock()
lock.acquire()
threading.Thread(target=lock.acquire, name="stuck", daemon=True).start()

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "dump.txt")
    with open(path, "w") as f:                       # the file must stay open until the dump is written
        faulthandler.dump_traceback_later(0.3, file=f)
        time.sleep(0.8)
        faulthandler.cancel_dump_traceback_later()
    text = open(path).read()
    print("thread blocks in the dump:", text.count("Thread 0x"), "| mentions 'stuck':", "[stuck]" in text)
Output1 line
thread blocks in the dump: 2 | mentions 'stuck': True

Two thread blocks: the main thread and the blocked stuck thread. In production, write the dump to a file or stderr that your platform captures, since the process may not live long afterwards.


Where you'll use this in the AI path#

This lesson Where it comes back
Bounded concurrency, semaphores, queues, shutdown 01B.4 (patterns that must not close a wait cycle), 03.9 §4.2 and §4.6 (semaphore and connection pool)
Timeouts, deadlines and jittered retries 01B.9 §2.1, §2.4, §4.2
Bulkheads, tenant fairness, deadline propagation, cancellation 11C.3 §4.1, §7.3, §5.1, §5.2
Agent loops, budgets and multi-agent hangs 08A.2 §1.4, 08D.3 §3.5
"Age of the oldest in-flight job", alerts on stalls 11A.2 metrics, SLOs and alerting
Races that locks introduce or fix; thread-safe design 01C.3
The event loop, cancellation and loop fairness 01C.2
The GIL and free-threaded builds 01C.5
fork, start methods and cross-process locks 01C.7

Check yourself#

  1. State the four Coffman conditions and say which one a global lock order removes.
  2. Why is a deadlock typically intermittent even though the code is wrong on every run?
  3. A thread calls a method that takes self._lock, and that method calls another method that takes self._lock. What happens with a Lock? With an RLock? Which design is usually better?
  4. A ThreadPoolExecutor(max_workers=4) hangs under load. Each task submits a sub-task to the same pool and calls .result(). Why does it work with one request but not with six?
  5. What does Queue.join() wait for, and what three mistakes make it hang?
  6. Why is fork() in a multi-threaded process dangerous, and what changed about the default start method in Python 3.14?
  7. Name two ways an asyncio program can deadlock with only one thread.
  8. How do PostgreSQL, InnoDB and SQLite each deal with a deadlock, and what must the application do?
  9. A service is at 0 % CPU and not completing work. List three ways to find where every thread is stuck, one of them requiring no code change.
  10. What is the difference between livelock and a spin lock, and what is the standard cure for livelock?
  11. A naive read-write lock never admits a writer. Why, and how does a writer-preferring lock fix it? What is its own risk?
  12. What is priority inversion, and why did the Mars Pathfinder computer reset? What was the fix?
  13. Why can a threading.Lock starve a thread even though no one holds it for long, and what does asyncio.Lock guarantee instead?
  14. An agent holds a concurrency slot while it runs its sub-calls. Why can two such agents deadlock with a limit of two slots, and what is the structural fix?

Further resources#


← 01C.3: Race Conditions and Thread Safety | Module 01C overview | 01C.5: The Global Interpreter Lock (GIL) →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close