01C.3 Race Conditions and Thread Safety
Every concurrency bug you will meet in production has the same shape: two things that were supposed to happen one after the other happened at the same time, or in the wrong order, and nobody noticed until the data was wrong. The server double-charged an invoice, two users saw each other's chat history, the cache fetched the same document five times, the daily token budget was overspent by 30 percent. None of these crash. They produce plausible wrong answers, rarely, and never when you are watching. This lesson gives you a precise mental model of race conditions: what they are, the three different things people mean by the word, how to reproduce them deterministically (so you can prove a bug and prove a fix), why Python's GIL does less for you than you think, and how races appear in threads, in asyncio, in processes, in databases and in LLM services. Then it turns to the positive side, thread safety: the toolbox of fixes (confinement, immutability, message passing, locks, atomic database statements), what the standard library does and does not make safe for you, how to design a class that is safe to share, how free-threaded Python changes the picture, and how to test for a bug that only happens one run in a thousand.
Lesson 01B.4 already showed the practical asyncio tools (Lock, Condition, Event, single-flight) and one forced-interleaving thread demo. This lesson does not repeat them. It owns the theory and the whole-picture catalogue: when a race exists, in which runtime, and which fix is right.
What you'll learn
- The vocabulary, precisely: race condition, data race, check-then-act, read-modify-write, TOCTOU, critical section, atomic operation, invariant, visibility, heisenbug
- What
counter += 1really compiles to (withdis), and an exhaustive enumeration of every way two threads can interleave it, so you can see the probability of a lost update rather than guess at it - Why the GIL does not make your code thread-safe, which single operations CPython does document as atomic, and why that list is an implementation detail
- Honest reproduction: why a plain integer
+=did not lose updates in the experiment on Python 3.14.6 here, and which shapes of code do lose updates (a Python function call in the window, even a trivial one, or a Python__add__) - Races on files (TOCTOU), in
asyncio(await points), between processes (multiprocessing.Value), and in databases (lost update, guardedUPDATE, version columns) - AI-service races: a shared token budget, cache stampedes, duplicate tool calls, global conversation state that leaks between users, and results handed from worker threads to an event loop
- The fix toolbox and how to choose: confinement, immutability, message passing,
Lock,RLock,Semaphore,Event,Condition,Barrier,queue.Queue, atomic database statements, compare-and-swap - Thread safety as a design property: the five levels, what the standard library guarantees (
queue,logging,random,sqlite3,decimal,functools,collections), composition traps,threading.localvscontextvars, lazy singletons and double-checked locking, reentrancy - What free-threaded CPython (3.13t/3.14t) changes, and the tools that exist for it
- How to test for races: forced interleavings, an exhaustive schedule explorer, stress tests with
sys.setswitchinterval, and a review checklist
What you don't need
- Any knowledge of operating-system internals. Where a concept comes from there (mutexes, atomic instructions), you get a plain-English version first.
- Lessons 01C.1 and 01C.2 are helpful companions (what concurrency is, how the event loop schedules tasks) but every example here is self-contained. If you have not met
async/await, read 01B.3 before Part 4. - Deadlocks and starvation. Those are the other way locks go wrong and have their own lesson, 01C.4. This lesson tells you to use locks; that one tells you what they cost.
- The GIL's internals. 01C.5 owns them; this lesson uses only the consequences.
Setup
No API key needed, nothing to install, no network. Every example uses the Python standard library. You need Python 3.11 or newer. The outputs in this lesson were produced on Python 3.14.6 (the default, GIL-enabled build) on macOS. Two honest caveats apply to everything below:
- Anything involving real threads racing is machine-dependent, so those outputs are labelled illustrative or print only facts that cannot vary ("some updates were lost", not "47,213 were lost").
- These outputs come from a normal GIL build, not a free-threaded one. Statements about free-threaded behaviour come from the official documentation and are marked as such.
python3 --version
python3 -c "import sys; print(getattr(sys, '_is_gil_enabled', lambda: True)())" # 3.13+; older versions always have a GILThe free-threading checks need Python 3.13 or newer (sys._is_gil_enabled() appeared in 3.13, and the sys.flags.thread_inherit_context flag in 3.14). The scripts below use getattr(...) fallbacks so the rest of the lesson runs on 3.11+.
Create a scratch folder and run each snippet with python3 file.py (macOS/Linux/WSL) or py file.py (Windows PowerShell). Scripts that start threads or processes use an if __name__ == "__main__": guard, which matters for multiprocessing on macOS and Windows.
What you must be able to do after this lesson#
- Define race condition, data race, check-then-act and critical section
- Explain why counter += 1 can lose updates
- Explain why the GIL does not make your code thread-safe
- Spot a race at an await point in asyncio
- Fix a race with a Lock, a queue or an atomic database statement
- Choose between confinement, immutability and locking
- Test code for races with forced interleavings and stress tests
Why this matters for an AI engineer#
An AI service is concurrent by construction: a web server handles many requests at once, each fanning out to many slow model calls, with caches, budgets, rate limiters, conversation stores and job queues shared between them. Races are therefore not exotic; they are the default failure mode of state shared between in-flight requests, and they hide behind the fact that the model call itself is slow and non-deterministic, so "the answer looked a bit odd" is an ordinary Tuesday.
| You'll hear... | You'll understand it after... |
|---|---|
| "It only fails in production, and only sometimes." | 1.5 Heisenbugs, Part 9 testing for races |
"But Python has the GIL, so counter += 1 is safe." |
2.1 what += compiles to, 2.4 what the GIL does not do |
| "Which dict and list operations are atomic?" | 2.5 atomic operations |
| "We spent 30% more tokens than the daily cap." | 4.1 await-point races, 6.1 a shared token budget |
| "Two users saw each other's conversation." | 6.4 global conversation state, 8.5 threading.local vs contextvars |
| "The refund email went out three times." | 6.3 duplicate tool calls, 5.3 idempotency keys |
| "The cache fetched the same embedding ten times." | 4.2 the async cache, 8.7 lazy singletons |
"Is logging / random / sqlite3 thread-safe?" |
8.3 the standard library table |
| "Thread-safe means I can share it freely, right?" | 8.1 the five levels, 8.4 composition traps |
| "What changes with free-threaded Python?" | 8.9 free-threaded CPython |
| "How do I prove this race is fixed?" | 9.2 an exhaustive schedule explorer, 9.3 stress tests |
Part 1: What a race condition is#
1.1 The shared whiteboard#
Two colleagues share one whiteboard that holds the number of open support tickets: 12. A new ticket arrives for each of them at the same moment. Each walks to the board, reads 12, walks back to their desk, adds one in their head (13), returns to the board and writes 13. The board now says 13. Two tickets arrived; the board counts one. Neither colleague made a mistake in isolation. The bug lives in the gap between reading and writing, during which the other person acted on the same stale number.
That is the whole idea of a race condition: the correctness of the result depends on the relative timing of operations that the programmer assumed were ordered or exclusive, and the timing is not controlled. Fixing it always means one of two things: make the gap disappear (the read and the write become one indivisible step) or make everyone else wait outside the gap (mutual exclusion), or remove the shared board (give each person their own tally and add them up at the end).
1.2 Three words that are often confused#
People use "race condition" for at least three distinct problems. Telling them apart tells you which fix applies.
| Term | Plain meaning | Example | Typical fix |
|---|---|---|---|
| Data race | Two threads access the same memory location at the same time, at least one is a write, and there is no synchronization. A precise, low-level term from C, C++ and Java memory models. | Two threads write the same int field with no lock |
Synchronization (lock, atomic), or do not share |
| Race condition | The program's logic is wrong for some timing. It can exist with no data race at all, and a data race can exist without it mattering. | Two requests each check "is the last seat free?" then each book it, using perfectly synchronized individual operations | Make the whole logical operation atomic |
| Check-then-act (also TOCTOU, "time of check to time of use") | A decision is made from a check, and by the time you act the check is stale. The most common real race condition. | if not path.exists(): path.write_text(...) |
Make check and act one step: open(path, "x"), a lock around both, a guarded UPDATE |
| Read-modify-write (also lost update) | Read a value, compute a new one from it, write it back; another writer's change in between is overwritten. | counter += 1, balance = balance - amount, budget.tokens -= n |
Make the three steps atomic, or let the database do the arithmetic |
1.3 Shared, mutable, concurrent: the three ingredients#
A race needs all three of these. Remove any one and the bug cannot exist:
| Ingredient | Remove it by... | Example |
|---|---|---|
| Shared: more than one thread/task/process can reach the same state | Confinement: keep state local to one owner | Each worker keeps its own tally and returns it |
| Mutable: the state changes after it is shared | Immutability: build a new value instead of changing the old one | A frozen config object swapped by one assignment |
| Concurrent: the accesses can overlap in time | Serialization: one owner, or locks, or a queue | One writer thread reads a queue |
This table is the backbone of Part 7. Always ask in this order: can I stop sharing it? can I stop mutating it? only then: how do I serialize access to it?
1.4 Races exist at every layer#
The same shape repeats at every scale; only the tools change.
| Layer | What is shared | Example | Part |
|---|---|---|---|
| Threads | Memory in one process | Two worker threads update one dict | 2, 3 |
asyncio tasks |
Memory in one thread, interleaved at await |
Two tasks spend the same token budget | 4 |
| Processes | Shared memory, files, sockets | Four workers bump one multiprocessing.Value |
5.1 |
| Files | The filesystem | Two jobs both decide to create job.lock |
3.3 |
| Databases | Rows | Two requests read used=0, each writes its own total |
5.2 |
| Distributed systems | A cache key, a queue, an API with side effects | A retried request creates two invoices | 5.3 |
1.5 Why races hide: heisenbugs#
A heisenbug is a bug that disappears or changes when you try to observe it (a pun on Heisenberg). Races are the classic case, for four reasons:
- The window is tiny. The gap between a read and a write may be a few nanoseconds; the scheduler lands in it once in a million runs.
- Adding a
printor a debugger changes the timing. Printing takes a lock and does I/O; the thread yields; the bug vanishes. - Your laptop is not production. Fewer cores, less load, a different Python version, a different scheduler: the same code that never fails locally fails daily on a busy 32-core server.
- Absence of failure is not evidence of correctness. A race you have not triggered is still there. In 2.3 you will see a read-modify-write that never failed in 9.6 million attempts on one Python version, and the fix is still required.
Because of 4, this lesson keeps returning to two techniques that make races reproducible: forcing the bad interleaving (a Barrier or Event placed in the window, 3.1) and enumerating all interleavings (2.2, 9.2). A race you can reproduce on demand is a race you can fix with confidence.
1.6 Visibility and ordering#
Races are not only about interleaving. A second question is visibility: will thread B ever see what thread A wrote, and in what order? On real hardware and in compilers, writes can be buffered, cached per core, or reordered, so in languages with an explicit memory model (Java, C++, Go) a plain shared flag is not guaranteed to be seen at all without synchronization. CPython hides most of this on today's builds, but the guarantee you should rely on is the one the documentation gives for synchronization objects: releasing a lock or setting an Event makes earlier writes visible to the thread that acquires or waits.
The classic case is the stop flag:
stop = False
def worker():
while not stop: # fragile: relies on the flag write becoming visible
do_work()It usually works in CPython, but nothing in the language promises it, and it gives you no way to wait for the flag. The right tool is threading.Event:
import threading
stop = threading.Event()
def worker():
while not stop.is_set():
do_work()
# or: stop.wait(timeout=1.0) to sleep until told to stop
# elsewhere: stop.set()Do not rely on the accidental visibility of plain variables; the free-threaded build (8.9) removes some of that accidental safety.
Part 2: The lost update, anatomy and exhaustive proof#
Deep-dive
2.1 What counter += 1 really does#
In source code, counter += 1 looks like one step. It is not. Python's dis module shows the bytecode the interpreter actually runs:
# e01_dis.py
import dis
counter = 0
def bump() -> None:
global counter
counter += 1
dis.dis(bump)Output (Python 3.14.6; opcode names and numbers differ between Python versions):
6 RESUME 0
8 LOAD_GLOBAL 0 (counter)
LOAD_SMALL_INT 1
BINARY_OP 13 (+=)
STORE_GLOBAL 0 (counter)
LOAD_CONST 1 (None)
RETURN_VALUEThree instructions do the real work: LOAD_GLOBAL (read the shared value onto the interpreter's private stack), BINARY_OP (add one, on that private copy) and STORE_GLOBAL (write the result back). That is a read-modify-write in three steps, and the middle value lives in the thread's own stack, invisible to everyone else. Between the load and the store, the shared variable can be changed by another thread, and the store will then overwrite that change with a number computed from stale data.
sequenceDiagram
participant A as Thread A
participant S as Shared counter
participant B as Thread B
A->>S: load (reads 0)
B->>S: load (reads 0)
A->>A: add 1 (local result 1)
B->>B: add 1 (local result 1)
A->>S: store 1
B->>S: store 1
Note over S: Two increments, final value 1The same applies to self.count += 1, d[key] += 1, total = total + x, lst[i] = lst[i] + 1 and every x op= y on shared state. The statement form is irrelevant; what matters is whether the new value depends on the old value and there is a gap between reading one and writing the other.
2.2 Every possible interleaving: twenty schedules, eighteen wrong#
Instead of hoping a race shows up, we can enumerate it. Model each thread as three steps (load, add, store). A schedule is an order in which the six steps of two threads can run, keeping each thread's own steps in order. Run all of them:
# e02_interleavings.py: enumerate EVERY way two threads can interleave
# the three steps of `counter += 1` (load, add, store).
from collections import Counter
from itertools import combinations
STEPS = ("load", "add", "store")
def run(schedule: tuple[str, ...]) -> int:
"""schedule is a sequence like ('A','B','A',...): who moves next."""
shared = 0
local = {"A": None, "B": None} # each thread's private 'stack'
pc = {"A": 0, "B": 0}
for who in schedule:
step = STEPS[pc[who]]
pc[who] += 1
if step == "load":
local[who] = shared
elif step == "add":
local[who] = local[who] + 1
else:
shared = local[who]
return shared
def all_schedules():
# choose which 3 of the 6 time slots belong to thread A
for a_slots in combinations(range(6), 3):
yield tuple("A" if i in a_slots else "B" for i in range(6))
results = Counter()
examples = {}
for s in all_schedules():
r = run(s)
results[r] += 1
examples.setdefault(r, "".join(s))
total = sum(results.values())
print(f"{total} possible interleavings")
for value in sorted(results):
print(f"final counter == {value}: {results[value]} interleavings, e.g. {examples[value]}")20 possible interleavings
final counter == 1: 18 interleavings, e.g. AABABB
final counter == 2: 2 interleavings, e.g. AAABBBRead the second line carefully: if the scheduler chose uniformly among interleavings, 18 of 20 (90%) would lose an update. The only two correct schedules are the ones where one thread finishes all three steps before the other starts (AAABBB, BBBAAA): that is, the ones where the operation behaved as if it were atomic. Any overlap of the two load-to-store windows loses an update, because both threads then compute from the same stale value. Real schedulers are not uniform (threads run for long stretches without switching, so the "serial" schedules are far more likely than 2 in 20), which is exactly why the bug is rare rather than absent.
It gets worse with more threads. The same enumeration for any number of threads (each thread is still load, add, store; this version generates the schedules recursively):
# e02b: same with N threads x 3 steps, count schedules by outcome (multinomial)
from collections import Counter
from math import factorial
def schedules(counts):
if sum(counts) == 0:
yield ()
return
for i, c in enumerate(counts):
if c:
nxt = list(counts); nxt[i] -= 1
for rest in schedules(tuple(nxt)):
yield (i,) + rest
def run(schedule, n):
shared = 0
local = [0]*n
pc = [0]*n
for t in schedule:
s = pc[t]; pc[t] += 1
if s == 0: local[t] = shared
elif s == 1: local[t] += 1
else: shared = local[t]
return shared
for n in (2, 3):
res = Counter(run(s, n) for s in schedules((3,)*n))
print(n, "threads:", sum(res.values()), "interleavings;", dict(sorted(res.items())))2 threads: 20 interleavings; {1: 18, 2: 2}
3 threads: 1680 interleavings; {1: 1404, 2: 270, 3: 6}With three threads, only 6 of 1,680 schedules (the six fully serial orders) are fully correct. Each extra thread multiplies the wrong schedules; correct behaviour is a vanishing fraction of the possibilities, so correctness has to come from construction (making the steps atomic), never from luck.
2.3 Real threads: an honest experiment#
Now run it for real. Four threads each add one, 200,000 times, to a shared global and to an attribute on a shared object. Correct total: 800,000.
# e03_stress.py: lost updates with real threads. Counts are machine-dependent.
import sys
import threading
N_THREADS = 4
PER_THREAD = 200_000
counter = 0
def bump_global() -> None:
global counter
for _ in range(PER_THREAD):
counter += 1
class Box:
n = 0
def bump_attr(box: Box) -> None:
for _ in range(PER_THREAD):
box.n += 1
def run(label: str, interval: float | None) -> None:
global counter
if interval is not None:
sys.setswitchinterval(interval)
counter = 0
box = Box()
ts = [threading.Thread(target=bump_global) for _ in range(N_THREADS)]
for t in ts: t.start()
for t in ts: t.join()
ts = [threading.Thread(target=bump_attr, args=(box,)) for _ in range(N_THREADS)]
for t in ts: t.start()
for t in ts: t.join()
expected = N_THREADS * PER_THREAD
print(f"{label:22s} global lost={expected - counter:>7} attr lost={expected - box.n:>7}")
if __name__ == "__main__":
gil = getattr(sys, "_is_gil_enabled", lambda: True)() # attribute exists on 3.13+
print(sys.version.split()[0], "GIL enabled:", gil)
for _ in range(3):
run("default (5 ms)", None)
for _ in range(3):
run("switchinterval 1e-6", 1e-6)3.14.6 GIL enabled: True
default (5 ms) global lost= 0 attr lost= 0
default (5 ms) global lost= 0 attr lost= 0
default (5 ms) global lost= 0 attr lost= 0
switchinterval 1e-6 global lost= 0 attr lost= 0
switchinterval 1e-6 global lost= 0 attr lost= 0
switchinterval 1e-6 global lost= 0 attr lost= 0That is the real result on Python 3.14.6 on one machine: zero lost updates in 9.6 million attempts, even with the thread-switch interval shrunk by a factor of 5,000. If you stopped here you would conclude += on an integer is safe. It is not, and understanding why the experiment "passed" is one of the most useful things in this lesson.
CPython only considers handing the GIL to another thread at certain points in the bytecode (as I understand CPython's design: roughly on entering a Python function and on loop back-edges, where it checks an internal "eval breaker" flag; 01C.5 explains the mechanism). The three instructions of counter += 1 on an int contain no such point, so on this build, for this loop, the read-modify-write happens to be uninterruptible. That is an accident of the current implementation, not a language guarantee: which instructions are checked has changed between CPython versions, and (from reports I did not re-verify on older versions) a loop like this was commonly observed to lose updates on older releases. Do not build on it. Now change the shape of the code so that something that can yield sits inside the window:
# e04_when_it_loses.py: which read-modify-write shapes lose updates on this build?
import sys
import threading
N_THREADS = 4
PER_THREAD = 100_000
INTERVAL = float(sys.argv[1]) if len(sys.argv) > 1 else 0.005 # CPython default
sys.setswitchinterval(INTERVAL)
def delta() -> int: # a Python-level function call inside the window
return 1
class Money:
"""int-like value whose __add__ is Python code."""
def __init__(self, v: int) -> None:
self.v = v
def __add__(self, other: int) -> "Money":
return Money(self.v + other)
state = {"plain": 0, "call": 0, "dunder": Money(0), "dictkey": {"k": 0}, "locked": 0}
lock = threading.Lock()
def plain() -> None:
for _ in range(PER_THREAD):
state["plain"] += 1
def call() -> None:
for _ in range(PER_THREAD):
state["call"] = state["call"] + delta()
def dunder() -> None:
for _ in range(PER_THREAD):
state["dunder"] = state["dunder"] + 1
def dictkey() -> None:
for _ in range(PER_THREAD):
d = state["dictkey"]
d["k"] = d["k"] + delta()
def locked() -> None:
for _ in range(PER_THREAD):
with lock:
state["locked"] = state["locked"] + delta()
def hammer(fn) -> None:
ts = [threading.Thread(target=fn) for _ in range(N_THREADS)]
for t in ts: t.start()
for t in ts: t.join()
if __name__ == "__main__":
expected = N_THREADS * PER_THREAD
gil = getattr(sys, "_is_gil_enabled", lambda: True)() # attribute exists on 3.13+
print(sys.version.split()[0], "GIL enabled:", gil, "switch interval:", INTERVAL)
for name, fn in [("plain", plain), ("call", call), ("dunder", dunder),
("dictkey", dictkey), ("locked", locked)]:
hammer(fn)
v = state[name]
if isinstance(v, Money): v = v.v
if isinstance(v, dict): v = v["k"]
print(f"{name:8s} {'LOST UPDATES' if v != expected else 'exact'}")Run it as python3 e04_when_it_loses.py 0.005 and again with 1e-6. Example output (illustrative — your exact output will differ; the pattern is what to notice):
3.14.6 GIL enabled: True switch interval: 0.005
plain exact
call exact
dunder LOST UPDATES
dictkey exact
locked exact
3.14.6 GIL enabled: True switch interval: 1e-06
plain exact
call LOST UPDATES
dunder LOST UPDATES
dictkey LOST UPDATES
locked exact(In repeated runs on the machine that produced this output the 1e-6 runs lost roughly half of all updates in call, dunder and dictkey, every time. At the default interval the dunder shape lost updates in some runs and stayed exact in others; plain was exact in every run at both settings. The counts vary; the pattern did not.)
What this teaches:
- A race can be real and invisible.
plainnever failed;dunder, where the window contains a Python function call, failed even at the default setting, though only some of the time (a bug that fails a few runs in a hundred is an easy one; real ones fail one in a million). The window is whatever the interpreter might switch inside, not what the source looks like.plainis also a dict update (state["plain"] += 1) and stayed exact.dictkeylost updates only because it callsdelta()between the read and the write. So what matters is whether anything in the window can offer a thread switch (a Python call, a Python__add__), not which container you use.
lockedwas exact every time. The fix does not depend on guessing which shapes lose updates; it makes all of them safe.- Shrinking the switch interval is a test technique.
sys.setswitchinterval(1e-6)asks the interpreter to offer a switch far more often, which turns a one-in-a-million schedule into a frequent one. 9.3 uses it deliberately. - Free-threaded builds change everything here. Without the GIL, two threads execute bytecode truly in parallel, so even the
plainshape becomes a real race (the official documentation lists read-modify-write as not atomic; see 8.9). These outputs do not come from that build. - Cross-link: 01C.5 §2.1 explains the eval-breaker check points (calls and backward jumps) that decide which of these shapes the experiment lets through; the forced, deterministic lost update is in 3.1.
2.4 What the GIL does and does not do#
The GIL is a lock inside CPython that lets only one thread run Python bytecode at a time (01B.4 §8.1 gives the two-minute version; 01C.5 owns the details). What it does protect is the interpreter's own consistency: two threads appending to the same list will not corrupt the list's internal array, because one append runs start to finish. What it does not protect is your program's logic:
| The GIL gives you | The GIL does not give you |
|---|---|
| A single operation on a built-in type runs without another thread running Python code in the middle, as long as it calls back into no Python code (the FAQ's wording; see 2.5) | Atomicity of sequences of instructions (x = x + 1, check-then-act, "read the list then use what you read") |
| Memory safety of built-in containers during single operations | Any ordering guarantee between threads |
| A fairly simple mental model for many one-line operations | A guarantee that the model survives: C extensions can release it, and Python 3.13+ can run without it |
| Freedom from data races inside the interpreter | Freedom from race conditions in your logic |
2.5 Which operations are atomic (and why you should not rely on it)#
The official Python FAQ ("What kinds of global value mutation are thread-safe?") states the GIL-era position. It says Python offers to switch threads only between bytecode instructions, that "each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program", and that operations on shared built-in variables "that 'look atomic' really are". Its list (L, L1, L2 are lists, D, D1, D2 are dicts, x, y objects, i, j ints):
| Atomic, per the FAQ | Not atomic, per the FAQ |
|---|---|
L.append(x) |
i = i+1 |
L1.extend(L2) |
L.append(L[-1]) |
x = L[i] |
L[i] = L[j] |
x = L.pop() |
D[x] = D[x] + 1 |
L1[i:j] = L2 |
|
L.sort() |
|
x = y |
|
x.field = y |
|
D[x] = y |
|
D1.update(D2) |
|
D.keys() |
The FAQ adds a caveat that matters in practice: operations that replace other objects "may invoke those other objects' __del__() method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex!"
Read the right-hand column. The pattern: one operation on one container is atomic; two operations (a read then a write, even of the same container) are not. L.append(L[-1]) reads L[-1] and then appends: two steps. D[x] = D[x] + 1 reads then writes: two steps. This is exactly the lost-update shape of 2.1, written with a container instead of an integer.
Four further facts to hold on to:
- Atomic only while no Python code runs.
D[x] = yis atomic forstrorintkeys. Ifxhas a Python-level__hash__or__eq__, or replacing a value triggers a Python__del__, other threads can run in the middle, because that callback is Python bytecode. Thedunderrow in 2.3 is the same effect. - It is an implementation detail of the GIL build. The FAQ section is written for the GIL; it says nothing about free-threaded builds. The free-threading HOWTO says the free-threaded build "aims to provide similar thread-safety behavior at the Python level" and that built-in types such as
dict,listandsetuse internal locks, but it explicitly recommends usingthreading.Lockor other synchronization primitives "instead of relying on the internal locks of built-in types, when possible." - The newer documentation is more precise. The Python 3.14 documentation has a dedicated Thread Safety Guarantees page for the free-threaded build with five levels (incompatible, compatible, safe on distinct objects, safe on shared objects, atomic) and per-method detail for
list,dict,set,bytearrayandmemoryview. Its recurring theme is the same: single operations such aslst.append(x),d[key] = vors.add(x)are safe, but read-modify-write (lst[i] = lst[i] + 1) and check-then-act (if lst: lst.pop(),if elem in s: s.remove(elem)) are not, and iteration is never atomic: to iterate a container others may change, iterate over a copy (for item in lst.copy():). - Atomic is not the same as correct.
D[k] = vbeing atomic does not makeif k not in D: D[k] = compute()correct (it computes twice; see 3.1).
What this means for an AI engineer: you may legitimately use one-liners like results.append(item) from many threads (it is the one shared write each worker needs; 7.1 uses it), but treat "atomic" as a documented property of a single call, not a licence to leave multi-step logic unprotected.
Part 3: Check-then-act and TOCTOU#
The lost update of Part 2 needs an arithmetic operation. Many real races need nothing but a decision: "if it is not there, create it", "if there is stock, sell it", "if the file does not exist, take the lock". The decision is based on a check, and the check can be out of date by the time you act.
3.1 Force the bad schedule with a Barrier#
Here is the situation behind half the "why did it load the model twice?" bugs. A registry hands out expensive objects (an embedding model, a client pool). Two threads ask for the same name at the same moment. Because a real race is rare, the demo places a threading.Barrier(2) between the check and the act: both threads must finish their check before either may continue. That does not create a bug that was not there; it forces the one bad schedule to happen every time, so we can see the effect and later prove a fix.
# e05_check_then_act.py: a check-then-act race on a dict, forced into the
# bad interleaving with a Barrier so the result is deterministic.
import threading
registry: dict[str, int] = {}
created: list[str] = [] # which thread actually created the entry
barrier = threading.Barrier(2) # both threads finish their CHECK before either ACTS
def get_or_create_racy(name: str, who: str) -> int:
if name not in registry: # CHECK
barrier.wait() # (test hook: force the bad schedule)
registry[name] = len(created) + 1 # ACT, based on a stale check (the "expensive load")
created.append(who)
return registry[name]
def get_or_create_safe(name: str, who: str, lock: threading.Lock) -> int:
with lock: # check and act are ONE critical section
if name not in registry:
registry[name] = len(created) + 1
created.append(who)
return registry[name]
def main() -> None:
results: dict[str, int] = {}
def worker(who: str) -> None:
results[who] = get_or_create_racy("embedding-model", who)
ts = [threading.Thread(target=worker, args=(w,)) for w in ("A", "B")]
for t in ts: t.start()
for t in ts: t.join()
print("racy: the model was loaded", len(created), "times")
# the safe version needs no barrier: only one thread can ever pass the check
registry.clear(); created.clear()
lock = threading.Lock()
results.clear()
def worker2(who: str) -> None:
results[who] = get_or_create_safe("embedding-model", who, lock)
ts = [threading.Thread(target=worker2, args=(w,)) for w in ("A", "B")]
for t in ts: t.start()
for t in ts: t.join()
print("safe: the model was loaded", len(created), "time")
if __name__ == "__main__":
main()racy: the model was loaded 2 times
safe: the model was loaded 1 timeThe "racy" function is not wrong in a single-threaded program, and each of its individual operations (in, []=, append) is atomic. It is wrong because the pair (not in, then assign) is not atomic. The safe version wraps check and act in one with lock: block, so a second thread cannot enter until the first has finished, and then it sees the entry and skips. Notice that the safe version needs no barrier to be correct: correctness comes from the lock, and the barrier is purely a testing device.
Three alternatives to an explicit lock, in order of preference when they apply:
| Technique | How | Caveat |
|---|---|---|
| One atomic call | registry.setdefault(name, value) checks and inserts in a single call (documented as safe on single items in the free-threading docs) |
The value argument is computed before the call, so setdefault(name, load_model()) always loads. It is atomic insertion, not lazy creation |
| Try, and handle the failure (EAFP: "easier to ask forgiveness than permission") | try: open(path, "x") ... except FileExistsError: |
Works when the operation itself is atomic and reports "already exists" |
| Let a lock own the pair | with lock: around check and act |
Keep the section short; do not hold it across slow I/O (7.7) |
3.2 The shape to look for in code review#
Search for this pattern: a condition on shared state, then, below it, a change to that same state, with anything in between that can pause the thread or task (a function call, I/O, an await, a lock being released).
if <state says X>: # check
...anything that can pause...
<change state> # act (assumes X is still true)Common disguises: if key not in cache: cache[key] = compute(); if not job.is_running: job.start(); if len(pool) < max: pool.append(new_conn()); if balance >= amount: balance -= amount; if not os.path.exists(p): os.makedirs(p).
3.3 Files: TOCTOU and the atomic alternatives#
The filesystem is shared by every process on the machine, so file races cross thread and process boundaries and are also a security concern. The official os.access documentation warns that using access() to check permissions before opening "creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it", and recommends EAFP: just try to open it and handle the error. The same applies to exists(), isfile(), mkdir after exists, and any "check then create/write/delete" sequence.
The atomic building blocks Python gives you:
| Need | Racy | Atomic |
|---|---|---|
| Create a file only if absent (a lock file, a claim) | if not p.exists(): p.write_text(...) |
open(p, "x") ("exclusive creation": fails with FileExistsError; it maps to the OS's create-new-only flag) |
| Create a directory if absent | if not d.exists(): d.mkdir() |
d.mkdir(exist_ok=True) or catch FileExistsError |
| Replace a file so readers never see half a write | write directly into the final path | write a temp file in the same directory, flush and fsync, then os.replace(tmp, final). The os.rename/os.replace documentation says that when it succeeds "the renaming will be an atomic operation (this is a POSIX requirement)"; it may fail across different filesystems, which is why the temp file lives beside the target. Two extra details: on Windows os.replace raises PermissionError if a reader still has the target open, and for crash durability on POSIX you would also fsync the containing directory |
| Delete if present | if p.exists(): p.unlink() |
p.unlink(missing_ok=True) |
# e05b_toctou_files.py: check-then-create on a file, and the atomic alternative.
import os
import tempfile
import threading
from pathlib import Path
def demo(tmp: Path) -> None:
target = tmp / "job.lock"
both_checked = threading.Barrier(2)
winners: list[str] = []
def racy(who: str) -> None:
if not target.exists(): # CHECK
both_checked.wait() # test hook: force the bad schedule
target.write_text(who) # ACT (overwrites silently)
winners.append(who) # both believe they own the lock
ts = [threading.Thread(target=racy, args=(w,)) for w in ("A", "B")]
for t in ts: t.start()
for t in ts: t.join()
print("check-then-create: owners claimed:", sorted(winners))
target.unlink()
winners.clear()
def atomic(who: str) -> None:
try:
with open(target, "x") as f: # 'x' = O_CREAT | O_EXCL: create or fail, atomically
f.write(who)
except FileExistsError:
return # somebody else won; that is a normal outcome
winners.append(who)
ts = [threading.Thread(target=atomic, args=(w,)) for w in ("A", "B")]
for t in ts: t.start()
for t in ts: t.join()
print("open(..., 'x'): owners claimed:", len(winners))
# atomic replace: readers see the old file or the new file, never a half-written one
cfg = tmp / "config.json"
cfg.write_text('{"version": 1}')
fd, tmp_name = tempfile.mkstemp(dir=tmp, suffix=".tmp") # same directory = same filesystem
with os.fdopen(fd, "w") as f:
f.write('{"version": 2}')
f.flush()
os.fsync(f.fileno())
os.replace(tmp_name, cfg) # atomic when it succeeds (POSIX requirement)
print("after replace:", cfg.read_text())
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as d:
demo(Path(d))check-then-create: owners claimed: ['A', 'B']
open(..., 'x'): owners claimed: 1
after replace: {"version": 2}Both threads passed the exists() check and both "won" the lock; with open(..., "x") exactly one did, and the loser got a normal, handleable exception. The os.replace pattern is how you should write any file that a concurrent reader (another process, a hot-reloading server) might open at any moment: a config file, an index manifest, a cache entry.
Part 4: Races in asyncio#
A common belief says "asyncio is single-threaded, so it has no races." The first half is true and the second half is false. Single-threaded means the event loop never runs two tasks simultaneously, so there are no data races in the C sense and plain counter += 1 with no await inside is safe. But the loop does interleave tasks, and it does so at await points that actually suspend. Any invariant that is broken across an await can be observed by another task. That is a race condition, and 01B.4 already warned about it in the context of one demo (01B.4 §7.2). This part gives the general rule and the cases that matter in AI services.
4.1 No await, no race; await in the window, race#
The rule: in asyncio, tasks can only be interleaved at suspension points (await) (and at the other suspension points: async with, async for, yield inside an async generator). So a critical section is safe, without any lock, if it contains no suspension point. It is vulnerable if it contains one.
flowchart LR
subgraph before ["Task A and Task B on one event loop"]
A1["A: check budget (100 >= 60)"] --> A2["A: await provider call"]
B1["B: check budget (100 >= 60)"] --> B2["B: await provider call"]
A2 --> A3["A: deduct 60"]
B2 --> B3["B: deduct 60"]
end
A1 -. "loop switches to B at the await" .-> B1The practical consequence for an AI service: the slow part of nearly every request is an await (the model call), and the check ("do we have budget?", "is this in the cache?") usually comes before it and the update ("deduct", "store") after it. That puts the whole model call inside the race window, which is as wide as a window can be.
The script below shows three things: the check-await-act race on a token budget, the safe rule "no await means no race", and an async cache that fetches the same key five times.
# e06_asyncio_races.py: races in asyncio exist, and need an await in the window.
import asyncio
# ---- 1. check-then-await-then-act: a shared token budget -------------------
class Budget:
def __init__(self, tokens: int) -> None:
self.tokens = tokens
async def spend_racy(self, n: int) -> bool:
if self.tokens >= n: # CHECK
await asyncio.sleep(0) # e.g. awaiting the provider call
self.tokens -= n # ACT on a stale check
return True
return False
class SafeBudget(Budget):
def __init__(self, tokens: int) -> None:
super().__init__(tokens)
self._lock = asyncio.Lock()
async def spend(self, n: int, fail: bool = False) -> bool:
async with self._lock: # reserve under the lock ...
if self.tokens < n:
return False
self.tokens -= n # ... deduct BEFORE the slow await
try:
await asyncio.sleep(0) # the slow call happens outside the lock
if fail:
raise RuntimeError("provider error")
except BaseException: # CancelledError is a BaseException: `except Exception` would miss it
await self.refund(n) # nothing was spent: give the reservation back
raise
return True
async def refund(self, n: int) -> None: # if the call fails, give it back
async with self._lock:
self.tokens += n
async def budget_demo() -> None:
b = Budget(100)
ok = await asyncio.gather(*(b.spend_racy(60) for _ in range(3)))
print(f"racy: approved {sum(ok)} x 60 tokens from a budget of 100; left={b.tokens}")
sb = SafeBudget(100)
ok = await asyncio.gather(*(sb.spend(60) for _ in range(3)))
print(f"safe: approved {sum(ok)} x 60 tokens from a budget of 100; left={sb.tokens}")
sf = SafeBudget(100)
res = await asyncio.gather(sf.spend(60, fail=True), return_exceptions=True)
print(f"fails: {res[0]!r}; left={sf.tokens} (the reservation was refunded)")
# ---- 2. no await in the window = no race (single-threaded interleaving only
# happens at await points) -------------------------------------------
async def no_await_demo() -> None:
counter = 0
async def bump() -> None:
nonlocal counter
for _ in range(1000):
counter += 1 # read-modify-write with NO await inside
await asyncio.sleep(0)
await asyncio.gather(*(bump() for _ in range(10)))
print("no await inside the window: counter =", counter)
# ---- 3. a cache with an await between check and store ----------------------
calls = 0
async def fetch(key: str) -> str:
global calls
calls += 1
await asyncio.sleep(0.01)
return key.upper()
async def cache_demo() -> None:
global calls
cache: dict[str, str] = {}
async def get_naive(key: str) -> str:
if key not in cache:
cache[key] = await fetch(key)
return cache[key]
await asyncio.gather(*(get_naive("doc-1") for _ in range(5)))
print("naive cache: provider calls for one key =", calls)
calls = 0
cache.clear()
inflight: dict[str, asyncio.Task[str]] = {}
async def get_single_flight(key: str) -> str:
if key in cache:
return cache[key]
task = inflight.get(key)
if task is None: # no await between this check and the store below
task = asyncio.create_task(fetch(key))
inflight[key] = task
try:
value = await task
finally:
inflight.pop(key, None)
cache[key] = value
return value
await asyncio.gather(*(get_single_flight("doc-1") for _ in range(5)))
print("single-flight: provider calls for one key =", calls)
async def main() -> None:
await budget_demo()
await no_await_demo()
await cache_demo()
asyncio.run(main())racy: approved 3 x 60 tokens from a budget of 100; left=-80
safe: approved 1 x 60 tokens from a budget of 100; left=40
fails: RuntimeError('provider error'); left=100 (the reservation was refunded)
no await inside the window: counter = 10000
naive cache: provider calls for one key = 5
single-flight: provider calls for one key = 1Walk through each part.
The budget. Three tasks each want 60 tokens from a budget of 100. In the racy version all three check (100 ≥ 60 is true three times), all three await, and all three deduct: the budget ends at -80. The safe version uses the reserve before the slow await pattern: take the lock, check and deduct in one critical section with no await inside it, release, and only then do the slow call. If the call fails or the task is cancelled, the except BaseException branch calls refund() and re-raises (the fails: line shows the budget restored to 100); without it the tokens would stay reserved forever. This is the same reserve/settle shape as a database "hold" on a credit card, and Part 6 builds a production-grade thread version.
No await in the window. Ten tasks each do a thousand read-modify-writes with no await between them, and the answer is exactly 10,000. This is not luck: nothing can interrupt the loop between the read and the write. It is the reason many small asyncio programs work without a single lock. It is also why adding a harmless-looking await logger.info(...), await cache.get(...) or await asyncio.sleep(0) inside a read-modify-write can introduce a bug in code that was correct a minute ago.
4.2 The async cache and single-flight#
The third demo in the script is the most common asyncio race in AI code. get_naive does if key not in cache: cache[key] = await fetch(key). Five tasks ask for doc-1 together: all five check an empty cache, all five start a provider call, and the provider is billed five times (naive cache: provider calls for one key = 5). A lock around the whole get would be correct but would serialize all keys, so a slow fetch for one document blocks every other document. The fix that scales is single-flight: remember the in-flight task per key, so later callers wait for the same call. get_single_flight above does it in a few lines, and its crucial property is the comment: no await sits between "is there an in-flight task for this key?" and "register mine", so that check-then-act is atomic by construction.
01B.4 §7.1 builds the production version (with asyncio.shield so one caller's cancellation does not cancel the shared call) and 11B.3 §7.6 applies it to an LLM response cache. Treat this section as the reason those exist.
4.3 Crossing the thread boundary#
Real AI services mix both worlds: an asyncio server that calls a synchronous SDK through asyncio.to_thread, or a worker thread that wants to push a result into an asyncio.Queue. Event-loop objects are not thread-safe; the documentation says "almost all asyncio objects are not thread safe" and tells you to use loop.call_soon_threadsafe() to schedule a callback from another OS thread and asyncio.run_coroutine_threadsafe() to run a coroutine from another thread and get a concurrent.futures.Future back.
# e17_cross_thread.py: handing results from a worker thread to the event loop safely.
import asyncio
import threading
import time
def blocking_sdk_call(n: int) -> str:
time.sleep(0.01) # a sync-only SDK
return f"result-{n}"
async def main() -> None:
loop = asyncio.get_running_loop()
queue: asyncio.Queue[str] = asyncio.Queue()
def worker(n: int) -> None: # runs in an OS thread
result = blocking_sdk_call(n)
# WRONG: queue.put_nowait(result) (asyncio.Queue is not thread-safe)
loop.call_soon_threadsafe(queue.put_nowait, result) # RIGHT: hop onto the loop's thread
ts = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in ts: t.start()
got = sorted([await queue.get() for _ in range(3)])
for t in ts: t.join()
print("received on the loop thread:", got)
# the other direction: a thread submits a coroutine and waits for its result
async def lookup(key: str) -> str:
await asyncio.sleep(0)
return key.upper()
out: list[str] = []
def thread_calls_coroutine() -> None:
out.append(asyncio.run_coroutine_threadsafe(lookup("doc-7"), loop).result())
t = threading.Thread(target=thread_calls_coroutine); t.start()
while t.is_alive():
await asyncio.sleep(0.001) # keep the loop running so the coroutine can execute
t.join()
print("run_coroutine_threadsafe returned:", out[0])
asyncio.run(main())received on the loop thread: ['result-0', 'result-1', 'result-2']
run_coroutine_threadsafe returned: DOC-7Calling queue.put_nowait(result) directly from the worker thread would be a race against the loop's own bookkeeping (and, in debug mode, the loop calls it triggers, call_soon and call_at, raise RuntimeError when invoked from the wrong thread; with no waiting getter you may get silent corruption instead). call_soon_threadsafe is the one doorway: it puts the callable on the loop's ready queue under the loop's own thread-safe mechanism, so put_nowait then runs on the loop thread. The reverse direction (a thread calling a coroutine) goes through run_coroutine_threadsafe(...).result(). Never call .result() on that future from the loop's own thread: it blocks the loop that must run the coroutine, which is a deadlock (01C.4).
4.4 Two traps: loop-bound primitives and cancellation#
Two asyncio failures appear in real AI services and test suites and have nothing to do with await ordering.
Trap 1: primitives bind to a loop. An asyncio.Lock, Semaphore or Queue created at import time (module level) binds to the first event loop that actually has to wait on it. Reuse it from a second asyncio.run() (a second test, a notebook re-run, a reloader) and it raises. The script contends the lock in two successive runs:
# f_loop_bound.py: an asyncio primitive created at import time binds to the first loop that has to wait on it.
import asyncio
lock = asyncio.Lock() # created at import time, outside any running loop
async def contend() -> None:
async def hold() -> None:
async with lock:
await asyncio.sleep(0.01)
# two tasks: the second has to WAIT, which is when the lock binds to this loop
await asyncio.gather(hold(), hold())
asyncio.run(contend())
print("first asyncio.run: ok")
try:
asyncio.run(contend()) # a NEW event loop (as in a second test, or a notebook re-run)
except RuntimeError as exc:
print("second asyncio.run: RuntimeError:", str(exc).split(">", 1)[1].strip())first asyncio.run: ok
second asyncio.run: RuntimeError: is bound to a different event loopTrap 2: cancellation inside a critical section. A timeout (asyncio.timeout()), a client disconnect or a TaskGroup sibling failing cancels a task by raising asyncio.CancelledError at its current await. If that happens between "reserve" and "settle", the reservation leaks unless you restore it:
# f_cancel.py: a cancelled task between reserve and settle leaks state unless a finally restores it.
import asyncio
class Budget:
def __init__(self, tokens: int) -> None:
self.free = tokens
async def call_leaky(self, n: int) -> None:
self.free -= n # reserve
await asyncio.sleep(10) # slow model call; cancelled by the timeout below
# (settle step never reached)
async def call_safe(self, n: int) -> None:
self.free -= n # reserve
try:
await asyncio.sleep(10)
except BaseException: # CancelledError is a BaseException, not an Exception
self.free += n # give the reservation back
raise
async def main() -> None:
for name in ("call_leaky", "call_safe"):
b = Budget(100)
try:
async with asyncio.timeout(0.01):
await getattr(b, name)(60)
except TimeoutError:
pass
print(f"{name}: free tokens after a timeout = {b.free}")
asyncio.run(main())call_leaky: free tokens after a timeout = 40
call_safe: free tokens after a timeout = 100CancelledError is a BaseException, so except Exception would not catch it; use try/finally or except BaseException: ...; raise. The rules: create asyncio primitives inside the running loop (in main() or a FastAPI lifespan), and always restore invariants in a finally, because timeouts and cancellations are the normal failure mode of model calls.
Part 5: Races beyond one process#
Deep-dive
5.1 Between processes#
Processes do not share memory by default, so a plain Python variable cannot race across them. The moment you share memory on purpose, the races return with no GIL to help at all (each process has its own GIL and they run in parallel). multiprocessing.Value is the smallest example, and the documentation warns about exactly the Part 2 shape: "Operations like += which involve a read and write are not atomic. So if, for instance, you want to atomically increment a shared value it is insufficient to just do counter.value += 1". By default Value carries a recursive lock (lock=True) that you take explicitly with get_lock().
# e08_processes.py: shared multiprocessing.Value with and without its lock.
import multiprocessing as mp
N_PROCS = 4
PER_PROC = 50_000
def bump_unlocked(counter) -> None:
for _ in range(PER_PROC):
counter.value += 1 # read-modify-write: NOT atomic across processes
def bump_locked(counter) -> None:
for _ in range(PER_PROC):
with counter.get_lock(): # the Value's own recursive lock
counter.value += 1
def run(target) -> int:
counter = mp.Value("i", 0) # lock=True by default
procs = [mp.Process(target=target, args=(counter,)) for _ in range(N_PROCS)]
for p in procs: p.start()
for p in procs: p.join()
return counter.value
if __name__ == "__main__":
expected = N_PROCS * PER_PROC
print("start method:", mp.get_start_method())
u = run(bump_unlocked)
l = run(bump_locked)
print("unlocked:", "LOST UPDATES" if u != expected else "exact (got lucky)")
print("locked: ", "exact" if l == expected else f"unexpected {l}")start method: spawn
unlocked: LOST UPDATES
locked: exactNotes:
- The lock must be taken by you:
Valuewithlock=Trueonly provides a lock;counter.value += 1does not acquire it. This is a classic surprise. - Locks cannot be passed to just any child: with
spawnandforkserverthey must be passed as arguments to the child (ascounteris here, with its embedded lock), not captured from a global. - The default start method changed in Python 3.14: on POSIX it is now
forkserverrather thanfork; macOS and Windows already defaulted tospawn. The documentation notes that forking a multithreaded process is problematic, which is the heart of 01C.4's fork-with-held-locks hazard. - For the full treatment of shared memory (
shared_memory,mmap, cleanup, crash safety) see 01C.7. The rule to carry from here: shared memory has no thread-safety for free. Every writer needs a lock or a single-writer protocol.
5.2 In the database: lost updates and the fixes#
Databases are the most important place for races in real products, because every web request is a concurrent actor and the database is the shared state. The classic is the same read-modify-write: an application reads a row, computes a new value in Python, writes it back. Two requests doing this concurrently lose one update.
The script below uses sqlite3 with two connections that are interleaved by hand (so the output is deterministic) to show four approaches to a per-user token quota:
# e07_db_lost_update.py: lost update, atomic UPDATE and optimistic locking (sqlite3).
# Two "request handlers" are interleaved by hand so the output is deterministic.
import sqlite3
import tempfile
from pathlib import Path
def connect(path: Path) -> sqlite3.Connection:
con = sqlite3.connect(path, timeout=5, isolation_level=None) # autocommit; we control it
con.execute("PRAGMA busy_timeout = 5000")
return con
def setup(path: Path) -> None:
con = connect(path)
con.execute("CREATE TABLE IF NOT EXISTS quota (user TEXT PRIMARY KEY, used INTEGER, version INTEGER)")
con.execute("DELETE FROM quota")
con.execute("INSERT INTO quota VALUES ('ana', 0, 0)")
con.close()
def used(path: Path) -> int:
con = connect(path)
(n,) = con.execute("SELECT used FROM quota WHERE user='ana'").fetchone()
con.close()
return n
def lost_update(path: Path) -> None:
"""read in Python, add in Python, write back: the classic ORM mistake."""
setup(path)
a, b = connect(path), connect(path)
(ra,) = a.execute("SELECT used FROM quota WHERE user='ana'").fetchone() # A reads 0
(rb,) = b.execute("SELECT used FROM quota WHERE user='ana'").fetchone() # B reads 0
a.execute("UPDATE quota SET used=? WHERE user='ana'", (ra + 100,)) # A writes 100
b.execute("UPDATE quota SET used=? WHERE user='ana'", (rb + 250,)) # B writes 250 (A lost)
a.close(); b.close()
print("read-modify-write in Python: used =", used(path), "(expected 350)")
def atomic_update(path: Path) -> None:
"""let the database do the arithmetic inside one statement."""
setup(path)
a, b = connect(path), connect(path)
a.execute("UPDATE quota SET used = used + ? WHERE user='ana'", (100,))
b.execute("UPDATE quota SET used = used + ? WHERE user='ana'", (250,))
a.close(); b.close()
print("atomic UPDATE ... used = used + ?: used =", used(path))
def conditional_update(path: Path) -> None:
"""a check that is part of the statement: spend only if enough is left."""
setup(path)
con = connect(path)
limit = 300
results = []
for amount in (100, 250, 150):
cur = con.execute(
"UPDATE quota SET used = used + ? WHERE user='ana' AND used + ? <= ?",
(amount, amount, limit),
)
results.append(cur.rowcount == 1) # rowcount 0 means the guard refused it
con.close()
print("guarded UPDATE accepted:", results, "-> used =", used(path))
def optimistic(path: Path) -> None:
"""compare-and-swap with a version column; the loser retries."""
setup(path)
a, b = connect(path), connect(path)
ra = a.execute("SELECT used, version FROM quota WHERE user='ana'").fetchone()
rb = b.execute("SELECT used, version FROM quota WHERE user='ana'").fetchone()
cur = a.execute("UPDATE quota SET used=?, version=version+1 WHERE user='ana' AND version=?",
(ra[0] + 100, ra[1]))
print("A CAS succeeded:", cur.rowcount == 1)
cur = b.execute("UPDATE quota SET used=?, version=version+1 WHERE user='ana' AND version=?",
(rb[0] + 250, rb[1]))
print("B CAS succeeded:", cur.rowcount == 1, "(stale version -> zero rows updated)")
if cur.rowcount == 0: # retry: re-read, recompute, try again
rb = b.execute("SELECT used, version FROM quota WHERE user='ana'").fetchone()
cur = b.execute("UPDATE quota SET used=?, version=version+1 WHERE user='ana' AND version=?",
(rb[0] + 250, rb[1]))
print("B retry succeeded:", cur.rowcount == 1)
a.close(); b.close()
print("after optimistic retry: used =", used(path))
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "quota.db"
lost_update(p)
atomic_update(p)
conditional_update(p)
optimistic(p)read-modify-write in Python: used = 250 (expected 350)
atomic UPDATE ... used = used + ?: used = 350
guarded UPDATE accepted: [True, False, True] -> used = 250
A CAS succeeded: True
B CAS succeeded: False (stale version -> zero rows updated)
B retry succeeded: True
after optimistic retry: used = 350| Approach | What it does | When to use it |
|---|---|---|
| Read-modify-write in Python | SELECT used, add in Python, UPDATE used = ? |
Never for contended counters: it lost 100 of the 350 here |
| Atomic statement | UPDATE quota SET used = used + ? |
Counters and balances. The database applies it to the current row value under its own locking |
| Guarded update | UPDATE ... SET used = used + ? WHERE used + ? <= ?, then check rowcount |
Limits and budgets: the check and the act are one statement, so the check cannot go stale. rowcount == 0 means "refused" |
| Optimistic locking (compare-and-swap) | UPDATE ... WHERE version = ? and bump the version; zero rows updated means someone else changed it, so re-read and retry |
Larger records edited through a form or an agent where you cannot express the change as one SQL expression |
The version-column technique is compare-and-swap (CAS) in database clothing: "set this to the new value only if it still has the value I read". CPU instructions, Redis (WATCH/MULTI or a Lua script for version checks; SET ... NX is the related conditional set, "set only if absent", which suits claims and locks rather than version checks), DynamoDB conditional writes and HTTP If-Match/ETag headers all offer the same primitive. Its cost is that losers must retry, so bound the retries and add jitter, exactly as in 01B.9.
5.2b Transactions do not fix a stale read#
"I wrapped it in a transaction" is the most common wrong answer to a lost update. A transaction groups statements so they commit or roll back together; it does not make a value you read earlier fresh. Under the default isolation of many databases (PostgreSQL's is READ COMMITTED) a BEGIN; SELECT used ...; (compute in Python) UPDATE ... SET used = ?; COMMIT sequence loses updates exactly like the autocommit version. What fixes it is making the read itself take a lock, or letting the database detect the conflict.
The script below uses sqlite3 (stdlib) with hand-interleaved handlers, so the output is deterministic. SQLite has a single writer and is stricter than PostgreSQL, so it refuses some of these sequences with database is locked instead of silently losing the update; that is still a failure you must handle.
# f_txn.py: "I used a transaction" does not fix a read-modify-write (sqlite3, hand-interleaved).
import sqlite3
import tempfile
from pathlib import Path
def connect(path: Path) -> sqlite3.Connection:
# isolation_level=None: no hidden transactions; we write BEGIN/COMMIT ourselves.
return sqlite3.connect(path, timeout=0.05, isolation_level=None)
def setup(path: Path) -> None:
con = connect(path)
con.execute("DROP TABLE IF EXISTS quota")
con.execute("CREATE TABLE quota (user TEXT PRIMARY KEY, used INTEGER)")
con.execute("INSERT INTO quota VALUES ('ana', 0)")
con.close()
def used(path: Path) -> int:
con = connect(path)
(n,) = con.execute("SELECT used FROM quota WHERE user='ana'").fetchone()
con.close()
return n
def stale_read(path: Path) -> None:
"""the read happens BEFORE the transaction; the transaction only wraps the write."""
setup(path)
a, b = connect(path), connect(path)
(ra,) = a.execute("SELECT used FROM quota WHERE user='ana'").fetchone()
(rb,) = b.execute("SELECT used FROM quota WHERE user='ana'").fetchone()
for con, new in ((a, ra + 100), (b, rb + 250)):
con.execute("BEGIN")
con.execute("UPDATE quota SET used=? WHERE user='ana'", (new,))
con.execute("COMMIT") # each write is atomic; the stale read is not fixed
a.close(); b.close()
print("transaction around the write only: used =", used(path), "(expected 350)")
def deferred(path: Path) -> None:
"""BEGIN (deferred) ... SELECT ... UPDATE ... COMMIT, two handlers overlapping."""
setup(path)
a, b = connect(path), connect(path)
a.execute("BEGIN"); b.execute("BEGIN")
(ra,) = a.execute("SELECT used FROM quota WHERE user='ana'").fetchone() # A reads 0
(rb,) = b.execute("SELECT used FROM quota WHERE user='ana'").fetchone() # B reads 0
try:
a.execute("UPDATE quota SET used=? WHERE user='ana'", (ra + 100,))
a.execute("COMMIT")
b.execute("UPDATE quota SET used=? WHERE user='ana'", (rb + 250,))
b.execute("COMMIT")
except sqlite3.OperationalError as exc:
print("deferred transactions: OperationalError:", exc)
finally:
for c in (a, b):
try: c.execute("ROLLBACK")
except sqlite3.OperationalError: pass
c.close()
print("deferred transactions: used =", used(path), "(expected 350)")
def immediate(path: Path) -> None:
"""BEGIN IMMEDIATE takes the write lock BEFORE the read, so writers queue up."""
setup(path)
a, b = connect(path), connect(path)
a.execute("BEGIN IMMEDIATE")
(ra,) = a.execute("SELECT used FROM quota WHERE user='ana'").fetchone()
try:
b.execute("BEGIN IMMEDIATE") # A holds the write lock: B must wait
except sqlite3.OperationalError as exc:
print("B while A is in its transaction:", exc)
a.execute("UPDATE quota SET used=? WHERE user='ana'", (ra + 100,))
a.execute("COMMIT")
b.execute("BEGIN IMMEDIATE") # B retries after A committed
(rb,) = b.execute("SELECT used FROM quota WHERE user='ana'").fetchone() # fresh read: 100
b.execute("UPDATE quota SET used=? WHERE user='ana'", (rb + 250,))
b.execute("COMMIT")
a.close(); b.close()
print("BEGIN IMMEDIATE: used =", used(path), "(expected 350)")
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as d:
stale_read(Path(d) / "q.db")
deferred(Path(d) / "q.db")
immediate(Path(d) / "q.db")transaction around the write only: used = 250 (expected 350)
deferred transactions: OperationalError: database is locked
deferred transactions: used = 0 (expected 350)
B while A is in its transaction: database is locked
BEGIN IMMEDIATE: used = 350 (expected 350)Read it in order:
- A transaction around only the write still lost 100: each write was atomic, but the reads happened earlier and went stale.
- Deferred transactions (
BEGIN, the default kind) read first and ask for the write lock later. Both handlers hold a read lock, so A'sCOMMITcannot get exclusive access while B still reads: the work fails (database is locked) and, with nothing retried, no update happened at all. SQLite turned a silent lost update into a loud failure; you need a retry. BEGIN IMMEDIATEtakes the write lock at the start, before the read, so a second writer waits (here it is tolddatabase is lockedat once because the timeout is tiny, and retries after A commits). B's retry reads the fresh value, 100, and the total is correct. The general rule is lock at the read.
The same idea in a client/server database, as an illustrative sketch (not run here; PostgreSQL needs a server):
-- Pessimistic: lock the row at the read, so the second transaction waits for the first
BEGIN;
SELECT used FROM quota WHERE user_id = 'ana' FOR UPDATE; -- row lock until COMMIT
UPDATE quota SET used = used + 250 WHERE user_id = 'ana';
COMMIT;
-- Claim "run this key once" without a race: the unique index decides
INSERT INTO processed_events (event_id) VALUES ('evt_42') ON CONFLICT DO NOTHING;
-- rows affected = 1: you own it; 0: someone else already didThe alternatives are a stricter isolation level (SERIALIZABLE), where the database aborts one transaction with a serialization failure and your code must retry it, or the optimistic version column above. What each level guarantees differs by engine and version: read the PostgreSQL transaction isolation and explicit locking chapters (or your own database's) before relying on one.
5.3 Caches, double-submits and idempotency keys#
Distributed races are the same race with a network in the window. Three recur in AI products:
- Cache stampede: many requests miss the same cold key and each recomputes. Fixes: single-flight in-process (4.2) and a short-lived "someone is computing" marker across processes. 11B.3 §7.6 owns the LLM-specific treatment.
- Double-submit: a user double-clicks "Generate report", or a mobile client retries after a timeout, and two jobs run. Fix: the client sends a unique idempotency key per intended operation, and the server stores it with a unique constraint so the second arrival is recognized and returns the first result instead of acting again. 01B.9 §3.3 builds this.
- Lost update on shared documents: two agents or users edit the same record. Fix: version columns or ETags (above).
The unifying advice: anything an unreliable network might deliver twice must be safe to receive twice. A lock inside one process cannot protect you across two server replicas, so for cross-process correctness prefer database constraints and atomic statements over in-memory locks; they are the one mechanism every replica already shares.
Part 6: AI-service race gallery#
Reference
Four races that appear in real LLM products. Each has a deliberately small, runnable, no-network model of the bug and its fix; the model call is replaced by an await asyncio.sleep(0) or a thread barrier.
6.1 A shared token budget#
The scenario: a service must not spend more than a daily token budget, but many requests run at once and each model call takes seconds. The race: check the budget, call the model, add the spend afterwards. Meanwhile twenty other requests did the same check. 4.1 showed the asyncio version. Here is a thread-safe class with a pattern worth copying: reserve before the call, settle after it, release on failure.
# e16b_token_budget.py: a thread-safe token budget with reserve / settle / release.
import threading
class TokenBudget:
"""Thread-safe daily budget. reserve() before the call, settle() after it."""
def __init__(self, limit: int) -> None:
self._lock = threading.Lock()
self._limit = limit
self._reserved = 0
self._spent = 0
def reserve(self, estimate: int) -> bool:
with self._lock:
if self._spent + self._reserved + estimate > self._limit:
return False
self._reserved += estimate
return True
def settle(self, estimate: int, actual: int) -> None:
with self._lock:
self._reserved -= estimate # release the reservation ...
self._spent += actual # ... and record what really happened
def release(self, estimate: int) -> None:
with self._lock:
self._reserved -= estimate # the call failed: nothing was spent
def snapshot(self) -> tuple[int, int]: # one lock acquisition = a consistent pair
with self._lock:
return self._spent, self._reserved
def budget_demo() -> None:
budget = TokenBudget(limit=10_000)
accepted = 0
count_lock = threading.Lock()
def request(i: int) -> None:
nonlocal accepted
if not budget.reserve(1_000):
return
try:
if i % 5 == 0:
raise TimeoutError("provider timeout") # every fifth call fails
except BaseException:
budget.release(1_000) # give the reservation back, or it leaks forever
return # (a real handler would re-raise or report)
with count_lock:
accepted += 1
budget.settle(1_000, 800) # the model used fewer tokens than estimated
ts = [threading.Thread(target=request, args=(i,)) for i in range(25)]
for t in ts: t.start()
for t in ts: t.join()
spent, reserved = budget.snapshot()
print("budget: spent never above the limit:", spent <= 10_000)
print("budget: nothing left reserved:", reserved == 0)
print("budget: spent matches what was accepted:", spent == accepted * 800)
if __name__ == "__main__":
budget_demo()budget: spent never above the limit: True
budget: nothing left reserved: True
budget: spent matches what was accepted: TrueEvery fifth call fails in the demo; release is what keeps reserved at zero afterwards. Without it each timeout would leave 1,000 tokens reserved forever and the budget would slowly strangle the service. Catch BaseException (not just Exception) so a cancelled call releases too (4.4). Its essential design points:
- One lock, held only for arithmetic:
reserve,settleandsnapshotnever do I/O while holding it. reserve(estimate)checksspent + reserved + estimate <= limitand records the reservation in one critical section, so two callers can never both claim the last tokens.settle(estimate, actual)releases the reservation and records the real number, which is usually lower than the estimate (providers report actual usage after the call).release(estimate)is the failure path: it hands the reservation back with nothing spent.snapshot()returns both numbers under a single lock acquisition, because readingspentandreservedwith two separate property reads could show an inconsistent pair.
The same shape protects dollar budgets, per-tenant quotas, rate-limit counters and "at most N running jobs" limits. It is also why a Semaphore (7.3) is the right tool for concurrency limits and a reserve/settle budget is the right tool for quantity limits (01B.4 Part 4 distinguishes concurrency from rate).
6.2 The cache stampede#
Covered in 4.2 (asyncio) and 7.8 (threads). The summary: the race is "check cache, miss, compute, store", the damage is cost (N provider calls instead of one) rather than wrong data, and the fix is to coalesce callers per key.
6.3 Duplicate tool calls#
An agent's tool call can be issued more than once for three reasons that all look like races: a retry layer re-sends after a timeout that the server actually completed; the agent's loop proposes the same action twice in one turn; and two workers consume the same queue message (at-least-once delivery). If the tool has a side effect ("send the refund email", "create the Jira ticket", "charge the card"), the result is a duplicate side effect. The cure is idempotency: give each intended action a key and make "run this key at most once" atomic.
The Once class in the script below does the in-process version: claim the key under a lock before doing the work, and release the claim if the work fails so a retry can run:
# e16_ai_cases.py: two AI-service races with fakes (no network, no provider).
import asyncio
import threading
# ---- A. module-level "current conversation": cross-talk between requests -------
current_history: list[str] = [] # BUG: global, shared by every request
async def handle_global(user: str, question: str) -> list[str]:
current_history.clear() # "start a conversation"
current_history.append(f"{user}: {question}")
await asyncio.sleep(0) # the model call (any await)
return list(current_history) # what the prompt would contain
async def handle_scoped(user: str, question: str) -> list[str]:
history = [f"{user}: {question}"] # local to this request: confinement
await asyncio.sleep(0)
return history
async def conversation_demo() -> None:
a, b = await asyncio.gather(handle_global("ana", "refund?"), handle_global("bo", "invoice?"))
print("global state: ana's prompt =", a)
print(" bo's prompt =", b)
a, b = await asyncio.gather(handle_scoped("ana", "refund?"), handle_scoped("bo", "invoice?"))
print("request-local: ana's prompt =", a)
print(" bo's prompt =", b)
# ---- B. duplicate tool calls: the same side effect fired twice -------------------
sent_emails: list[str] = []
def send_refund_email_naive(order_id: str) -> None:
sent_emails.append(order_id)
class Once:
"""Run each key's side effect at most once, even under concurrent retries."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._done: set[str] = set()
def run(self, key: str, fn, *args) -> bool:
with self._lock: # claim the key BEFORE doing the work
if key in self._done:
return False
self._done.add(key)
try:
fn(*args)
except Exception:
with self._lock:
self._done.discard(key) # failed: allow a retry
raise
return True
def tool_demo() -> None:
barrier = threading.Barrier(3)
def agent_retry(_: int) -> None: # the agent loop, a retry layer and a webhook all fire it
barrier.wait()
send_refund_email_naive("order-991")
ts = [threading.Thread(target=agent_retry, args=(i,)) for i in range(3)]
for t in ts: t.start()
for t in ts: t.join()
print("naive tool: emails sent for one refund =", len(sent_emails))
sent_emails.clear()
once = Once()
barrier = threading.Barrier(3)
def agent_retry_safe(_: int) -> None:
barrier.wait()
once.run("refund:order-991", send_refund_email_naive, "order-991")
ts = [threading.Thread(target=agent_retry_safe, args=(i,)) for i in range(3)]
for t in ts: t.start()
for t in ts: t.join()
print("idempotent tool: emails sent for one refund =", len(sent_emails))
if __name__ == "__main__":
asyncio.run(conversation_demo())
tool_demo()global state: ana's prompt = ['bo: invoice?']
bo's prompt = ['bo: invoice?']
request-local: ana's prompt = ['ana: refund?']
bo's prompt = ['bo: invoice?']
naive tool: emails sent for one refund = 3
idempotent tool: emails sent for one refund = 1The three agent retries fired the naive tool three times and the Once wrapper once. Two honest limits of this code: it is in-process (two server replicas would each send one email, so production needs the key stored in a database with a unique constraint, 5.3), and it does not distinguish "in progress" from "done" for callers that arrive while the first is still running (they return False immediately; a production version would let them wait for or fetch the first result). 08A.2 §4.1 shows how an agent loop runs parallel tool calls with a bound; this section is the reason tool design in Module 08A insists on idempotent tools.
6.4 Global conversation state in a web service#
The most embarrassing race in a chat product is cross-talk: user A's request is answered with user B's history. It happens when a web service keeps "the current conversation" in a module-level variable or a class attribute shared by every request, which works perfectly in a single-user test. The first half of the script in 6.3 reproduces it: two concurrent requests both clear and fill the same global list, the model "call" is an await, and each request then reads what the last writer left. Output: ana's prompt = ['bo: invoice?']. Ana's question was replaced by Bo's, and the service would send Bo's text to the model and Ana's answer to Ana, a privacy incident, not just a bug.
The fix is confinement: state belongs to the request, passed as arguments or kept in a local variable (handle_scoped), never in a global. Where you genuinely need "ambient" per-request data (a request id, the current user for logging) use contextvars (8.5), not a global and not threading.local. In FastAPI, app.state is shared by all requests, so only put things there that are read-only or internally thread/task-safe (an HTTP client, a settings object, a model handle), never per-user mutable data. 11C.1 §5.1 makes the same point at deployment scale: keep replicas stateless and put shared state in a store.
Part 7: The fix toolbox#
7.0 Choose the cheapest fix that works#
Locks are what everyone reaches for first, and they are the last resort in this list, because every lock adds contention, a place to forget to unlock, and the possibility of deadlock (01C.4). Work down the diagram from the top:
flowchart TD
Q1{"Does the data have to be shared at all?"}
Q1 -->|"No"| C["Confine it: local variables, one task or thread owns it, merge results at the end"]
Q1 -->|"Yes"| Q2{"Does it change after creation?"}
Q2 -->|"No"| I["Make it immutable: frozen dataclass, tuple, str. Publish by one assignment"]
Q2 -->|"Yes"| Q3{"Can one owner serialize all changes?"}
Q3 -->|"Yes"| M["Message passing: queue.Queue to an owner thread, asyncio.Queue to an owner task"]
Q3 -->|"No"| Q4{"Is the state in a database or cache?"}
Q4 -->|"Yes"| D["Atomic statement, guarded UPDATE, version column, INCR, SET NX, idempotency key"]
Q4 -->|"No"| L["Lock around the whole invariant: Lock, RLock, asyncio.Lock. Keep the section tiny"]The first four fixes are shown side by side in one script: eight threads each add 1 five thousand times to a shared total (correct: 40,000).
# e09_fixes.py: the fix toolbox on one running example, a shared usage ledger.
import queue
import threading
from collections import defaultdict
from dataclasses import dataclass
N_THREADS = 8
PER_THREAD = 5_000
def hammer(fn, *args) -> None:
ts = [threading.Thread(target=fn, args=args) for _ in range(N_THREADS)]
for t in ts: t.start()
for t in ts: t.join()
# --- Fix 1: confinement/merge: each thread owns its own tally, merge at the end
def confinement() -> int:
tallies: list[int] = []
def work() -> None:
local = 0 # no sharing at all while counting
for _ in range(PER_THREAD):
local += 1
tallies.append(local) # list.append is atomic: one shared write per thread
hammer(work)
return sum(tallies)
# --- Fix 2: a lock around the whole read-modify-write
class LockedCounter:
def __init__(self) -> None:
self._lock = threading.Lock()
self._n = 0
def incr(self, by: int = 1) -> int:
with self._lock:
self._n += by
return self._n
@property
def value(self) -> int:
with self._lock:
return self._n
def locking() -> int:
c = LockedCounter()
def work() -> None:
for _ in range(PER_THREAD):
c.incr()
hammer(work)
return c.value
# --- Fix 3: message passing: ONE owner thread mutates; everyone else sends messages
def owner_thread() -> int:
q: queue.Queue[int | None] = queue.Queue()
total = 0
def owner() -> None:
nonlocal total
while (msg := q.get()) is not None: # None is the stop sentinel
total += msg # only this thread ever touches `total`
o = threading.Thread(target=owner)
o.start()
def work() -> None:
for _ in range(PER_THREAD):
q.put(1)
hammer(work)
q.put(None)
o.join()
return total
# --- Fix 4: immutability: build a new value, publish it with ONE reference assignment
@dataclass(frozen=True)
class Config:
model: str
timeout: float
current = Config("small", 10.0)
def reload_config(model: str, timeout: float) -> None:
global current
current = Config(model, timeout) # readers see the old or the new, never a mix
if __name__ == "__main__":
expected = N_THREADS * PER_THREAD
for name, fn in [("confinement", confinement), ("lock", locking), ("owner thread", owner_thread)]:
print(f"{name:13s} {fn()} (expected {expected})")
reload_config("large", 30.0)
print(current)confinement 40000 (expected 40000)
lock 40000 (expected 40000)
owner thread 40000 (expected 40000)
Config(model='large', timeout=30.0)7.1 Confinement: the fix that needs no lock#
Confinement means each thread or task works on private data and only the results meet at the end. In the script, each worker counts into a local variable (no sharing, no lock, no contention) and performs one shared write, tallies.append(local), which is atomic. Compare the cost: with a lock, 40,000 acquire/release pairs; with confinement, 8.
In real code the cleanest confinement is to let the executor return values instead of appending to a shared list at all: with ThreadPoolExecutor() as pool: results = list(pool.map(work, items)) (or pool.submit(...) and future.result()). Each call returns its value to the parent through a Future; the futures machinery is the confinement, and there is no shared results list to protect.
This is the shape of every good parallel data job: map privately, reduce once. An embedding job gives each worker its own batch and its own output list, and the parent concatenates. A web request keeps its conversation in local variables (6.4). Confinement is also how ProcessPoolExecutor works: arguments are copied in, results copied out, nothing shared.
7.2 Lock and RLock: mutual exclusion#
A lock (mutex) lets one thread at a time into a critical section; others wait. In Python it is threading.Lock, used as a context manager so it is released even if the code inside raises:
# lock_pattern.py: the shape of every correct lock use
import threading
class Ledger:
def __init__(self) -> None:
self._lock = threading.Lock() # private: callers cannot take it by accident
self._balance = 0 # invariant: only touched with the lock held
def deposit(self, amount: int) -> int:
with self._lock: # acquired here, released on ANY exit
self._balance += amount
return self._balanceRules that prevent most lock bugs:
- Use
with. A barelock.acquire()followed bylock.release()leaks the lock if anything between them raises. (An earlyreturnhas the same effect.) - One lock per invariant, and write down which data it guards. A comment ("
_lockguards_balanceand_history") is worth more than clever code. - Guard reads too when they must be consistent with writes (a total read in two pieces can be torn; see
snapshot()in 6.1). - Never call unknown code while holding the lock: callbacks, user hooks, logging handlers you do not control,
printto a pipe that can block. Unknown code can re-enter your class, take other locks and cause a deadlock.
threading.Lock is not reentrant: if the thread that holds it tries to acquire it again it blocks forever (a self-deadlock). threading.RLock is reentrant: the same thread may acquire it repeatedly and must release it the same number of times; only then can another thread enter. Use it when a public method that holds the lock calls another public method that takes the same lock. Prefer restructuring (a private _locked helper that assumes the lock is held) over RLock where you can: reentrancy hides design problems by letting a method run in the middle of another method's half-finished update.
Acquisition has three modes you should know: blocking (the default), non-blocking acquire(blocking=False) (a try-lock; returns immediately with False if held), and timed acquire(timeout=seconds) (waits up to a limit and returns False on timeout). The documentation forbids combining a timeout with blocking=False. Timed acquire is the first line of defence against a lock that is never released; 01C.4 turns it into a deadlock-prevention strategy. The script shows the modes, and an RLock being re-entered:
# f_lock_modes.py: RLock re-entry, and the three ways to acquire a Lock.
import threading
rl = threading.RLock()
with rl:
with rl: # the same thread may re-enter an RLock
print("RLock: reentered")
lock = threading.Lock()
lock.acquire() # held by this thread
print("Lock, second acquire by the same thread, 50 ms timeout ->", lock.acquire(timeout=0.05))
print("try-lock while held:", lock.acquire(blocking=False))
print("timed lock while held:", lock.acquire(timeout=0.05))
lock.release()
print("after release:", lock.acquire(blocking=False))
lock.release()RLock: reentered
Lock, second acquire by the same thread, 50 ms timeout -> False
try-lock while held: False
timed lock while held: False
after release: True7.3 Semaphore and BoundedSemaphore: limiting how many#
A semaphore is a counter-guarded gate: it admits up to N holders at once and blocks the rest. Where a lock says "one at a time", a semaphore says "at most N at a time", which is the primitive behind "at most 5 concurrent calls to this provider" (01B.4 Part 1 uses asyncio.Semaphore; this is the thread version, 03.9 §4.8 uses it with sync SDKs).
Prefer BoundedSemaphore: it raises ValueError if release() is called more times than acquire(). A plain Semaphore lets the counter grow past its starting value, which silently raises your concurrency limit when you have an unbalanced release (a double release in an error path is the usual cause). The script runs ten threads through a BoundedSemaphore(3) and then releases once too often:
# f_semaphore.py: BoundedSemaphore limits concurrency and catches an unbalanced release.
import threading
import time
sem = threading.BoundedSemaphore(3)
guard = threading.Lock()
running = 0
peak = 0
def job() -> None:
global running, peak
with sem: # at most 3 threads inside at once
with guard:
running += 1
peak = max(peak, running)
time.sleep(0.02) # the slow call
with guard:
running -= 1
ts = [threading.Thread(target=job) for _ in range(10)]
for t in ts: t.start()
for t in ts: t.join()
print("BoundedSemaphore(3): concurrency never exceeded 3:", peak <= 3)
try:
sem.release() # more releases than acquires
except ValueError as exc:
print("BoundedSemaphore over-release:", exc)BoundedSemaphore(3): concurrency never exceeded 3: True
BoundedSemaphore over-release: Semaphore released too many times7.4 Event, Condition and Barrier: waiting for something#
These three are about waiting, not exclusion.
| Primitive | Meaning | Use for |
|---|---|---|
Event |
A one-bit flag; set() wakes all current and future waiters; clear() resets it |
"Shutdown requested", "cache warmed", "leader elected" |
Condition |
A lock plus "wait until this predicate about shared state is true" | Bounded buffers, "wait until the list is non-empty", anything with a state to wait for |
Barrier(n) |
Blocks until n parties have arrived, then releases all | Phase gates in a pipeline, and tests (it is how 3.1 forced the bad schedule) |
# Condition.wait_for and Barrier
import threading
cv = threading.Condition()
items: list[str] = []
def consumer() -> None:
with cv:
cv.wait_for(lambda: bool(items)) # releases the lock while waiting; re-checks the predicate
print("Condition consumer got:", items.pop())
t = threading.Thread(target=consumer)
t.start()
with cv:
items.append("ticket-17")
cv.notify() # notify does NOT release the lock; the 'with' exit does
t.join()
b = threading.Barrier(2, timeout=0.05)
try:
b.wait() # the partner never arrives
except threading.BrokenBarrierError:
print("Barrier timeout -> BrokenBarrierError, broken =", b.broken)Condition consumer got: ticket-17
Barrier timeout -> BrokenBarrierError, broken = TruePoints to remember (all from the threading documentation): Condition.wait() returns True unless it timed out, and, in the documentation's words, "can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true", so always re-check the predicate in a loop or use wait_for(predicate), never if; wait/notify raise RuntimeError if the lock is not held; a Barrier that times out or is abort()ed enters the broken state and every waiter gets BrokenBarrierError (a RuntimeError subclass); Event.wait(timeout) returns whether the flag is set. asyncio has the same set (Event, Condition, Barrier since 3.11), and its Condition.wait carries the same spurious-wakeup warning (01B.4 Part 7).
7.5 Message passing: queue.Queue and the owner thread#
When many threads need to change one thing, the cleanest design is to let one thread own it and have everyone else send it messages. The owner has no race with itself; the queue does all the locking.
queue.Queue "implements all the required locking semantics" in the standard library's words. put() and get() block (with optional timeout), maxsize gives backpressure (01B.4 §3.3), task_done()/join() give a completion protocol, and since Python 3.13 Queue.shutdown() closes it cleanly. The third function in the fix-toolbox script above is the pattern: eight producer threads put(1), one owner thread does total += msg, and None is a stop sentinel. This is the actor idea: a private piece of state plus a mailbox. Its natural uses: a single database writer, a single log or metrics aggregator, a single file appender (instead of many threads writing one file), a single owner of a non-thread-safe client.
7.6 Immutability and publish-by-assignment#
If data never changes after it is built, concurrent readers cannot race with anything. For data that must change over time (a model configuration, a routing table, a prompt template set), use copy-on-write: never mutate the object that readers hold; build a new one and publish it with a single assignment. Readers see the old object or the new object, never a half-built one.
That is the fourth part of the fix-toolbox script:
# Excerpt of the fix-toolbox script: immutable value, replaced by one assignment
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
model: str
timeout: float
current = Config("small", 10.0)
def reload_config(model: str, timeout: float) -> None:
global current
current = Config(model, timeout) # readers see the old or the new, never a mixTwo cautions. First, a reader should read current once into a local variable (cfg = current) and use cfg for the rest of its work; reading current.model and then current.timeout separately could straddle a reload and mix old and new. Second, "immutable" must be deep: a frozen dataclass holding a list is not immutable (use tuples or frozensets). The built-in immutable types (str, int, bytes, tuple of immutables, frozenset) are always safe to share.
7.7 Lock hygiene: granularity, scope and what not to hold across#
| Principle | Why | Bad example |
|---|---|---|
| Hold the lock for the shortest time | Every other thread waits for you | Holding it while calling a provider (seconds) instead of only while updating a counter (nanoseconds) |
Never hold a lock across I/O, sleep, await or callbacks |
The slow thing runs in everyone's critical path and you invite deadlocks | with lock: resp = client.post(...) |
| Reserve, then work outside, then settle | Decouples correctness (fast, locked) from slowness (unlocked) | The TokenBudget and SafeBudget patterns (with a release or refund on failure) |
| Lock the invariant, not the object | Two fields that must change together share one lock; unrelated data should not | One global lock for the whole app |
| Prefer fine-grained only when contention is measured | Many small locks mean ordering rules and deadlock risk | Per-field locks "for performance" nobody measured |
| Make lock ownership obvious | A lock must be private to the class that owns the invariant | A public lock attribute that any module can take |
Release in finally / with, always |
An exception that skips release() freezes the service |
Manual acquire()/release() pairs |
7.8 Per-key locks and single-flight for threads#
A single global lock around a cache serializes all keys. When computation is slow (embedding a document, calling a model), you want different keys to compute in parallel and the same key to compute once. The thread-world counterpart of 4.2 uses concurrent.futures.Future as the shared "promise":
# e18_per_key.py: per-key locking and single-flight for threads (a sync cache).
import threading
import time
from collections.abc import Callable
from concurrent.futures import Future
class SingleFlightCache:
"""Thread-safe get-or-compute: one computation per key, shared by all waiters."""
def __init__(self) -> None:
self._lock = threading.Lock() # guards the two dicts below, never held during compute
self._values: dict[str, str] = {}
self._inflight: dict[str, Future[str]] = {}
def get(self, key: str, compute: Callable[[str], str]) -> str:
with self._lock:
if key in self._values:
return self._values[key]
fut = self._inflight.get(key)
leader = fut is None
if leader:
fut = Future()
self._inflight[key] = fut # register BEFORE leaving the lock
if not leader:
return fut.result() # followers wait for the leader's result
try:
value = compute(key) # slow work happens OUTSIDE the lock
except BaseException as exc:
with self._lock:
self._inflight.pop(key, None) # failure is not cached: next caller retries
fut.set_exception(exc) # every follower re-raises this one exception object
raise
with self._lock:
self._values[key] = value
self._inflight.pop(key, None)
fut.set_result(value)
return value
calls: list[str] = []
def slow_embed(key: str) -> str:
calls.append(key) # list.append is atomic
time.sleep(0.05) # the provider call
return f"vector({key})"
if __name__ == "__main__":
cache = SingleFlightCache()
results: list[str] = []
def worker(key: str) -> None:
results.append(cache.get(key, slow_embed))
ts = [threading.Thread(target=worker, args=("doc-1",)) for _ in range(8)]
ts += [threading.Thread(target=worker, args=("doc-2",)) for _ in range(4)]
for t in ts: t.start()
for t in ts: t.join()
print("provider calls:", sorted(calls))
print("callers served:", len(results), "| distinct results:", sorted(set(results)))
def boom(key: str) -> str:
raise RuntimeError("provider timeout")
try:
cache.get("doc-3", boom)
except RuntimeError as e:
print("failure propagated:", e)
print("failure not cached, retry works:", cache.get("doc-3", slow_embed))provider calls: ['doc-1', 'doc-2']
callers served: 12 | distinct results: ['vector(doc-1)', 'vector(doc-2)']
failure propagated: provider timeout
failure not cached, retry works: vector(doc-3)Study the structure; it is a template for most thread-safe lazy loading:
- One short lock guards the bookkeeping dictionaries and is never held during
compute. - The check and the registration of "I am the leader for this key" happen in one critical section; that is the check-then-act fix.
- Followers
fut.result()outside the lock, so waiting for a slow compute never blocks other keys. - On failure the future carries the exception to every waiter, the in-flight entry is removed so the failure is not cached, and the next caller retries; this matches the negative-caching advice in 11B.3 §7.7.
What it deliberately omits for readability: a timeout on fut.result(), an eviction policy and a size bound (use a real cache library or functools.lru_cache for those, mind the caveats in 8.3), and the case where the leader thread dies without setting the future (the except BaseException above covers exceptions but not a hard process kill).
7.9 Compare-and-swap and why Python has no atomic integer#
Compare-and-swap (CAS) is the hardware-level building block behind lock-free programming: "set this location to the new value only if it still holds the old value I read; tell me whether it worked." On failure you re-read and retry. Locks, atomic counters and lock-free queues in languages such as Java, C++ and Rust are built on it. Section 5.2's WHERE version = ? update is CAS at database scale.
Python's standard library does not expose atomic integers or a CAS instruction for ordinary variables, and you should not simulate one with a bare if x == old: x = new (that is a check-then-act). Within one process the idiom is a lock; across processes it is the database or the cache (Redis conditional writes: SET ... NX for claims, WATCH/MULTI or a Lua script for version checks, INCR for counters; verify command details on the Redis documentation for your version).
One idiom people use instead of += is next(itertools.count()) as a unique-id source: a single call on a C-implemented iterator. It is commonly relied on under the GIL, but the itertools documentation does not promise it is thread-safe (it explicitly says only that tee() iterators are not), and I have not verified its behaviour on free-threaded builds, so treat it as unverified folklore. A Lock around n += 1 is guaranteed on every build and costs almost nothing at id-generation rates. The conceptual takeaway is the optimistic versus pessimistic distinction:
| Strategy | Idea | Good when | Costs |
|---|---|---|---|
| Pessimistic (lock first) | Assume conflict; wait your turn | Conflicts are frequent or retries are expensive | Waiting, lock management, deadlock risk |
| Optimistic (CAS/version, retry) | Assume no conflict; detect and retry | Conflicts are rare and the operation is cheap to redo | Wasted work on conflict; retry storms under heavy contention |
For an LLM call, "redo" is expensive and costs money, so optimistic retry around the model call itself is usually wrong. Use optimistic CAS on the cheap bookkeeping (the quota row, the version of the stored document), not around the call.
7.10 Which primitive for which need#
| You need... | Reach for | Section |
|---|---|---|
| Only one thread in a critical section | Lock (RLock only if the same thread must re-enter) |
7.2 |
| At most N threads at once (a concurrency limit) | BoundedSemaphore(N) |
7.3 |
| Wait for a one-off flag ("ready", "stop") | Event |
7.4 |
| Wait until a predicate about shared state is true | Condition with wait_for |
7.4 |
| Make N threads start a phase together (tests, pipelines) | Barrier(N) |
7.4 |
| Hand work or results from many threads to one | queue.Queue |
7.5 |
| One thread to own and mutate a resource | Owner thread plus a queue | 7.5 |
| Readers that never see a half-built value | Immutable value, replaced by one assignment | 7.6 |
| A quantity limit (tokens, money) shared by in-flight calls | Reserve, settle and release under one lock | 6.1 |
| Many readers, one writer | No stdlib read-write lock: plain Lock or copy-on-write |
7.2, 7.6 |
Part 8: Thread safety#
8.1 What "thread-safe" means: five levels#
Thread-safe means a piece of code (a function, a class, a library) behaves correctly when used by several threads at once without the caller adding synchronization. The phrase hides a spectrum, which is why "is X thread-safe?" is rarely answerable with yes or no. A useful classification (from Joshua Bloch's Effective Java, Item 82, "Document thread safety"; Brian Goetz's Java Concurrency in Practice is the best long treatment of the underlying ideas) is:
| Level | Meaning | Python examples |
|---|---|---|
| Immutable | Cannot change after creation, so always safe | str, int, tuple of immutables, frozenset, frozen dataclasses of immutables |
| Unconditionally thread-safe | Safe for any concurrent use of its documented operations, no external locking | queue.Queue, logging module functions, threading.Lock, the global random functions |
| Conditionally thread-safe | Individual operations are safe, but sequences of operations need the caller's lock, or some usage patterns are unsafe | list, dict, set (single operations yes; iterate-while-modify and read-modify-write no) |
| Not thread-safe (thread-compatible) | Safe only if each thread has its own instance, or the caller serializes all access | A sqlite3 connection in a mode that forbids sharing; iterators and generators; most application classes you write |
| Thread-hostile | Unsafe even with external locking, usually because of hidden global state | Code that mutates process-wide state: os.chdir, os.environ tweaks, warnings.catch_warnings on the default build |
The Python 3.14 documentation's Thread Safety Guarantees page uses its own vocabulary for built-ins on free-threaded builds (incompatible, compatible, safe on distinct objects, safe on shared objects, atomic) maps onto the same idea with finer steps.
8.2 Designing a class that is safe to share#
A short recipe that works for nearly all cases:
- Decide the invariants (what must always be true between method calls).
- Put all state behind private attributes; give the class one private lock.
- Every public method that reads or writes that state does so entirely inside
with self._lock:. - Do no slow work (I/O, callbacks, other locks) inside the lock; use reserve/settle or compute outside, publish inside.
- Return copies or immutable snapshots, not references to internal mutable containers (a returned
listcan be mutated, or iterated while another thread changes it). - Document the thread-safety level and any methods that are not atomic together.
LockedCounter in the fix-toolbox script follows it for the smallest case; TokenBudget in 6.1 for a realistic one (note snapshot(), which returns a consistent pair as an immutable tuple). The next two subsections show what the standard library does for you, and the ways composing safe parts goes wrong.
8.3 What the standard library gives you#
This table is deliberately conservative: it lists what the official documentation says, marks what it does not say, and tells you the safe habit. "Docs say" means the Python 3.14 documentation as of November 2026.
| Component | What the docs say | Safe habit |
|---|---|---|
queue.Queue, LifoQueue, PriorityQueue |
"implements all the required locking semantics"; not reentrant within a thread | Use put/get; use get_nowait() instead of empty()/qsize() checks |
queue.SimpleQueue |
Reentrant C implementation (CPython detail), usable in __del__/weakref callbacks |
Use when you need reentrancy and no join() |
collections.deque |
"Deques support thread-safe, memory efficient appends and pops from either side" | append/appendleft/pop/popleft are safe; iterating a deque another thread mutates is not |
logging |
"intended to be thread-safe without any special work needing to be done by its clients"; each handler has a lock; one module-level lock | Safe from many threads. Do not call logging from a signal handler (locks are not always re-entrant). Call basicConfig() from the main thread before starting others. Be careful in a custom Handler.emit(): calling other locking parts of the logging API there can deadlock |
random |
"The global random number generator and instances of Random are thread-safe" (gauss() carries a note that two threads can get the same value; use normalvariate(), separate instances, or locks). On free-threaded builds heavy sharing contends |
One random.Random(seed) per worker for reproducible, contention-free streams |
sqlite3 |
threadsafety depends on how SQLite was compiled: 1 means "threads may share the module, but not connections", 3 means connections and cursors can be shared. check_same_thread=True (default) raises ProgrammingError if another thread uses the connection; with False "write operations may need to be serialized by the user to avoid data corruption" |
One connection per thread (or per task) is the simple, portable rule |
decimal |
Each thread has its own current context (getcontext()); new threads start from DefaultContext. Changing DefaultContext after threads have started "is not recommended as it would require thread synchronization" |
Set precision per thread or with localcontext(); set defaults before threads start |
functools.lru_cache / cache |
"The cache is threadsafe so that the wrapped function can be used in multiple threads", but "it is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached" | Safe data structure, not call-once. Do not use it as a lock for expensive work; use single-flight (7.8) |
functools.cached_property |
"does not prevent a possible race condition in multi-threaded usage. The getter function could run more than once on the same instance"; before 3.12 an undocumented per-property lock existed; it was removed | Fine if the getter is idempotent; otherwise lock inside the getter |
re |
The documentation makes no thread-safety statement; it only notes that recent patterns are cached | Treat compiled pattern objects as read-only and share them, which is the universal practice, but note that the docs give no explicit guarantee here |
threading.Lock, RLock, Condition, Semaphore, Event, Barrier |
These are the synchronization primitives | Use as described in Part 7 |
concurrent.futures.Future |
Designed to hand results between threads (set_result/result) |
Use as in 7.8 |
asyncio objects (Lock, Queue, Event, tasks, futures) |
"not thread-safe" | Touch only from the loop's thread; cross with call_soon_threadsafe / run_coroutine_threadsafe (4.3) |
warnings.catch_warnings |
Modifies global state; 3.14 added an optional context-variable mode (-X context_aware_warnings), default on for free-threaded builds and off for the GIL build |
Avoid in multithreaded code, or use the new flag |
| Iterators and generators | The free-threading HOWTO: "generally not thread-safe to access the same iterator object from multiple threads concurrently, and threads may see duplicate or missing elements". Entering a running generator raises ValueError: generator already executing |
One iterator per thread, or hand items out through a Queue |
httpx, requests, SDK clients, pandas, NumPy |
Not part of the standard library; each documents its own rules | Read the library's documentation, and never assume. In particular, a client may be safe to share while its response objects are not |
Four of these rows have a runnable proof (script e13_stdlib_safety.py):
# e13_stdlib_safety.py: things the stdlib does and does not do for you.
import io
import logging
import queue
import random
import threading
from collections import deque
def run(fn, n=8):
ts = [threading.Thread(target=fn, args=(i,)) for i in range(n)]
for t in ts: t.start()
for t in ts: t.join()
# 1. logging: records from many threads arrive whole, never torn mid-line
def logging_demo() -> None:
buf = io.StringIO()
log = logging.getLogger("demo")
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler(buf))
def work(i: int) -> None:
for j in range(200):
log.info("thread=%d item=%d done", i, j)
run(work)
lines = buf.getvalue().splitlines()
ok = all(l.startswith("thread=") and l.endswith(" done") for l in lines)
print("logging: lines =", len(lines), "| every line intact:", ok)
# 2. queue.Queue: put/get are safe; qsize()/empty() are only a snapshot
def queue_demo() -> None:
q: queue.Queue[int] = queue.Queue()
for i in range(1000):
q.put(i)
taken: list[int] = []
def drain(_: int) -> None:
while True:
try:
taken.append(q.get_nowait()) # the check and the act are ONE call
except queue.Empty:
return
run(drain)
print("queue: items taken =", len(taken), "| duplicates:", len(taken) - len(set(taken)))
# 3. deque: append/pop from both ends are atomic and documented as thread-safe
def deque_demo() -> None:
d: deque[int] = deque()
def work(i: int) -> None:
for j in range(1000):
d.append(j)
run(work)
print("deque: length after 8 x 1000 appends =", len(d))
# 4. random: the global generator is thread-safe; share one Random per thread if you want
# reproducible per-thread streams
def random_demo() -> None:
out: dict[int, list[float]] = {}
def work(i: int) -> None:
rng = random.Random(i) # private generator, seeded per worker
out[i] = [rng.random() for _ in range(2)]
run(work, 3)
again = {}
for i in range(3):
rng = random.Random(i)
again[i] = [rng.random() for _ in range(2)]
print("random: per-thread streams reproducible:", out == again)
# 5. iteration is never atomic: mutating while iterating fails even in ONE thread
def iteration_demo() -> None:
d = {"a": 1, "b": 2}
try:
for k in d:
d[k + "x"] = 0
except RuntimeError as e:
print("dict mutated during iteration ->", e)
snapshot = list(d) # copy first, then it is safe to mutate
for k in snapshot:
d[k + "y"] = 0
print("iterate over a snapshot instead: keys =", sorted(d))
# 6. a generator cannot be run by two callers at once
def generator_demo() -> None:
started = threading.Event()
go = threading.Event()
def gen():
started.set()
go.wait()
yield 1
g = gen()
t = threading.Thread(target=lambda: next(g))
t.start()
started.wait()
try:
next(g)
except ValueError as e:
print("second caller into a running generator ->", e)
go.set(); t.join()
if __name__ == "__main__":
logging_demo(); queue_demo(); deque_demo(); random_demo(); iteration_demo(); generator_demo()logging: lines = 1600 | every line intact: True
queue: items taken = 1000 | duplicates: 0
deque: length after 8 x 1000 appends = 8000
random: per-thread streams reproducible: True
dict mutated during iteration -> dictionary changed size during iteration
iterate over a snapshot instead: keys = ['a', 'ax', 'axy', 'ay', 'b', 'by']
second caller into a running generator -> generator already executingThe sixth demonstration shows an operation the standard library refuses loudly, and the fifth shows that iteration while mutating is a bug even with one thread: it is not atomic with respect to the loop body. The cure is to iterate over a snapshot (list(d), lst.copy()), which the free-threading documentation recommends for threads too.
8.4 Composition traps: two safe operations are not one safe operation#
If A and B are each atomic, "A then B" is not. The same applies to calls on a thread-safe container, and each line below is a bug:
| Looks safe | Why it is not | Fix |
|---|---|---|
if key in d: v = d[key] |
The key can be removed between the calls (KeyError) |
v = d.get(key) (one call), or try: d[key] except KeyError |
if key not in d: d[key] = make() |
Two threads can both make it | Lock; or setdefault when make() is cheap; or single-flight |
if not q.empty(): q.get() |
Another consumer can drain it first, and get() then blocks forever |
get_nowait() with except queue.Empty |
if lst: lst.pop() |
The list can empty in between (IndexError) |
try: lst.pop() except IndexError |
n = len(buf); buf.append(x); idx = n |
Another thread appended between | Hold a lock, or have the structure return the index |
if elem in s: s.remove(elem) |
The element can disappear in between (KeyError) |
s.discard(elem) |
for k in d: ... d[other] = ... |
Iteration is not atomic; changing size breaks it | Iterate over list(d) |
| Reading two fields of a shared object | You may see field one old and field two new | One lock, or one immutable snapshot object |
The fix is always the same family: make the combination one operation (a single call, a lock covering both, or a snapshot), or restructure so that the second operation tolerates the first one's result changing.
8.5 Per-thread and per-task state: threading.local and contextvars#
Sometimes you want ambient state: the current request id, the current user, an open database connection, a decimal context. A global would be shared by everyone (and cause 6.4). threading.local() gives each thread its own copy of every attribute set on it. contextvars.ContextVar gives each context its own value, and asyncio runs every task in its own copy of the context, so it also separates tasks, which share one thread. The distinction is the whole point:
# e11_locals.py: per-thread and per-task state: threading.local, contextvars, decimal.
import asyncio
import contextvars
import decimal
import sys
import threading
# 1. threading.local: each thread sees its own attributes
tls = threading.local()
def thread_body(name: str, out: dict[str, str]) -> None:
tls.request_id = f"req-{name}"
out[name] = tls.request_id
def threadlocal_demo() -> None:
out: dict[str, str] = {}
tls.request_id = "main-thread"
ts = [threading.Thread(target=thread_body, args=(n, out)) for n in "AB"]
for t in ts: t.start()
for t in ts: t.join()
print("threading.local:", dict(sorted(out.items())), "| main still sees", tls.request_id)
# 2. threading.local does NOT separate asyncio tasks (they share one thread)
async def task_local_wrong() -> None:
async def handler(name: str) -> str:
tls.user = name
await asyncio.sleep(0) # another task runs and overwrites tls.user
return tls.user
r = await asyncio.gather(handler("ana"), handler("bo"))
print("threading.local across tasks:", r, "(both see the last writer)")
# 3. contextvars gives each task its own value
user_var: contextvars.ContextVar[str] = contextvars.ContextVar("user")
async def task_local_right() -> None:
async def handler(name: str) -> str:
user_var.set(name)
await asyncio.sleep(0)
return user_var.get()
r = await asyncio.gather(handler("ana"), handler("bo")) # gather wraps each in its own Task = own context copy
print("contextvars across tasks: ", r)
# 4. decimal: the arithmetic context is per thread (and per task: contextvar-based)
def decimal_demo() -> None:
results: dict[str, str] = {}
def work(name: str, prec: int) -> None:
decimal.getcontext().prec = prec
results[name] = str(decimal.Decimal(1) / decimal.Decimal(7))
ts = [threading.Thread(target=work, args=a) for a in (("p4", 4), ("p10", 10))]
for t in ts: t.start()
for t in ts: t.join()
print("decimal per-thread precision:", dict(sorted(results.items())),
"| main prec still", decimal.getcontext().prec)
if __name__ == "__main__":
threadlocal_demo()
asyncio.run(task_local_wrong())
asyncio.run(task_local_right())
decimal_demo()
flag = getattr(sys.flags, "thread_inherit_context", "n/a (needs 3.14)")
print("thread_inherit_context flag on this build:", flag)threading.local: {'A': 'req-A', 'B': 'req-B'} | main still sees main-thread
threading.local across tasks: ['bo', 'bo'] (both see the last writer)
contextvars across tasks: ['ana', 'bo']
decimal per-thread precision: {'p10': '0.1428571429', 'p4': '0.1429'} | main prec still 28
thread_inherit_context flag on this build: 0Line two is the trap: with threading.local, two asyncio tasks on one thread share the same slot, so one overwrote the other (['bo', 'bo']) and ana's handler would have run with bo's identity. contextvars returns ['ana', 'bo']. Rules of thumb:
| Runtime | Per-unit state | Not |
|---|---|---|
| Plain threads (no asyncio) | threading.local |
Globals |
| asyncio tasks (also correct for threads) | contextvars.ContextVar |
threading.local (all tasks on a thread share it) |
A mix (async server calling to_thread) |
contextvars; asyncio.to_thread copies the current context into the worker thread, per the asyncio documentation |
threading.local in code that can run in a task |
The decimal module is a good example of correct design: getcontext().prec = 4 in one thread does not affect the 28 digits of precision in the main thread (output line four), and the C implementation uses a context variable by default, so the setting is also isolated between asyncio tasks (documented via HAVE_CONTEXTVAR).
New threads and contexts: a thread created with threading.Thread does not automatically see the creator's context variables on a GIL build. In 3.14 Thread(context=...) and the flag sys.flags.thread_inherit_context control it: per the threading documentation the flag defaults to true on free-threaded builds and false otherwise. The last line printed shows the value on this GIL build (0, false); on 3.11 to 3.13 the flag does not exist and the script prints n/a (needs 3.14). If you rely on request ids propagating into threads, pass the context explicitly (contextvars.copy_context().run(...)) rather than relying on the default, and see 01B.10 §1.7 for the logging use of ContextVar.
8.6 Reentrancy is not thread safety#
Reentrancy means a function can be safely re-entered before an earlier call has finished: recursion, a signal handler interrupting it, a __del__ running in the middle of it, a callback calling back. A function can be thread-safe but not reentrant (it takes a non-reentrant lock, so re-entry by the same thread self-deadlocks) or reentrant but not thread-safe (it uses only local variables, then reads a global without a lock). They are different questions.
Where reentrancy bites in Python:
- A signal handler runs on the main thread between bytecodes. If it calls
loggingwhile the main thread was inside a logging call that holds the handler lock, the lock is not reentrant and the program hangs. Theloggingdocumentation warns that you may not be able to use logging from signal handlers for that reason. Set a flag in the handler and do the work elsewhere. __del__methods andweakrefcallbacks run at arbitrary points when an object's reference count drops.queue.SimpleQueueexists partly so you canput()there safely.- Callbacks invoked while a lock is held (an event emitter holding its lock while notifying listeners, a listener that subscribes during notification). Either notify outside the lock on a copy of the listener list, or use an
RLockand accept that listeners can see intermediate state.
8.7 Lazy singletons and double-checked locking#
A lazy singleton creates an expensive shared object on first use (an embedding model, a tokenizer, a database pool, an SDK client). The naive version has a check-then-act race; the standard fix is double-checked locking: check without a lock (fast path), and if it looks missing take the lock, check again, and create it.
# e12_lazy_init.py: lazy singletons, double-checked locking, cache decorators.
import functools
import threading
def run_two(fn) -> None:
ts = [threading.Thread(target=fn) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
# --- 1. naive lazy singleton: both threads pass the `is None` check -----------
inits = 0
_model = None
_gate = threading.Barrier(2)
def get_model_naive():
global _model, inits
if _model is None:
_gate.wait() # test hook: force both threads past the check
inits += 1 # the "expensive" load (a model, a client pool ...)
_model = object()
return _model
# --- 2. double-checked locking: cheap fast path, correct slow path --------------
_model2 = None
_lock = threading.Lock()
inits2 = 0
def get_model_dcl():
global _model2, inits2
if _model2 is None: # first check, no lock (fast path)
with _lock:
if _model2 is None: # second check, inside the lock
inits2 += 1
_model2 = object()
return _model2
# --- 3. functools.cache: the DATA is safe, the CALL may run twice ---------------
calls = 0
gate3 = threading.Barrier(2)
@functools.cache
def load_prompt(name: str) -> str:
global calls
calls += 1
gate3.wait() # both threads are inside the function body together
return f"prompt:{name}"
# --- 4. cached_property: the getter may run twice (no lock since 3.12) ----------
class Index:
getter_runs = 0
gate = threading.Barrier(2)
@functools.cached_property
def vectors(self) -> list[int]:
Index.getter_runs += 1
Index.gate.wait()
return [1, 2, 3]
if __name__ == "__main__":
run_two(get_model_naive)
print("naive lazy init: initializations =", inits)
run_two(get_model_dcl)
print("double-checked locking: initializations =", inits2)
run_two(lambda: load_prompt("summarise"))
print("functools.cache: function body ran", calls, "times for one key")
idx = Index()
run_two(lambda: idx.vectors)
print("cached_property: getter ran", Index.getter_runs, "times for one instance")naive lazy init: initializations = 2
double-checked locking: initializations = 1
functools.cache: function body ran 2 times for one key
cached_property: getter ran 2 times for one instanceFour results, four lessons:
- Naive lazy init loaded the model twice (a
Barrierforced both threads past the check). For a 2 GB model, that is 4 GB of RAM and a startup spike. - Double-checked locking loaded it once. In Python this idiom is correct because publishing a reference with one assignment is atomic and a thread that sees a non-
Noneglobal sees a fully built object (assigned after construction finished). Java and C++ programmers will know DCL as a notorious trap because of memory-ordering subtleties in those languages; that is not the Python situation, and I am not aware of any Python-level reordering hazard for this exact pattern. I was not able to confirm this against an official guarantee for free-threaded builds, so if you target them, prefer the simpler options below. functools.cacheran the function body twice for one key. The dictionary was never corrupted; the function simply is not call-once. (Whichever result is stored last wins; later callers get the stored one.)cached_propertyran its getter twice for one instance (no lock since 3.12), as the documentation states.
Simpler, more robust options, in order of preference:
| Option | How | Notes |
|---|---|---|
| Initialize at startup, before threads exist | Create it in main(), in the application lifespan (01B.7 §4.2) or at import time |
No race is possible; startup cost is paid once, predictably. Best default |
| Module-level constant | MODEL = load_model() at import |
A module body runs once per process, when first imported; the cost is slow imports and awkward testing (do not start threads from inside an import) |
| DCL with a lock | As above | When you need real laziness |
| Single-flight keyed cache | 7.8 | When there is one object per key |
8.8 Thread-safety of what you call: how to find out#
When you meet an unfamiliar object and need to know whether to share it:
- Read its documentation for the words thread, concurrent, async, safe. Absence of a statement means assume not safe.
- Prefer one instance per thread/task (a connection, a Random, a session) over sharing, whenever creation is cheap. This sidesteps the question.
- If it must be shared, wrap it in your own class with one lock, or put it behind an owner thread and a queue (7.5).
- Check what it hands back: a thread-safe client returning a mutable response object that you share is a new problem.
- For C extensions, remember the GIL may have been hiding their lack of safety. Extension modules must opt in to running without the GIL (via the
Py_mod_gilslot); the free-threading extensions HOWTO says that an extension that does not declare support makes the import "raise a warning and enable the GIL at runtime".
8.9 Free-threaded CPython: what changes#
CPython 3.13 shipped an experimental free-threaded build (PEP 703, built with --disable-gil, executables named with a t suffix such as python3.14t). Python 3.14 made it officially supported (PEP 779 accepted in June 2025 placed it in "phase II": officially supported but still optional; the GIL build remains the default; the 3.14 release notes give its single-threaded performance penalty as "roughly 5-10%, depending on the platform and C compiler used"; the free-threading HOWTO reports about 1% to 8% on the pyperformance suite depending on platform, so do not treat 5-10% as universal; as of November 2026). Check what you are running with sys._is_gil_enabled() (3.13+) and sysconfig.get_config_var("Py_GIL_DISABLED") (1 for a free-threaded build). 01C.5 owns the full story. Here are only the race-related consequences, all from the official free-threading documentation unless stated:
| Topic | What it means for you |
|---|---|
| Python-level aims | "The free-threaded build of CPython aims to provide similar thread-safety behavior at the Python level to the default GIL-enabled build." Built-in dict, list, set protect themselves with internal locks, so single operations stay safe |
| No more accidents | Code that survived only because the GIL happened to make a multi-step sequence uninterruptible, like the plain += result of 2.3, loses that protection. The documentation lists read-modify-write and check-then-act as non-atomic. The experiment in 2.3 was not run on a free-threaded build, so treat "plain += now loses updates" as documentation-based and verify on your own build |
| Real parallelism | Two threads can execute Python code at the same instant on different cores. Races that needed a lucky switch now need only two cores |
| Iterators | "generally not thread-safe to access the same iterator object from multiple threads concurrently, and threads may see duplicate or missing elements" |
| Per-object locks and critical sections | CPython implements container safety with per-object locks. C extension authors use Py_BEGIN_CRITICAL_SECTION to lock objects; the extensions HOWTO warns a critical section "may temporarily release their locks" when a thread blocks, so it does not give exclusive access for the whole section. This matters for extension authors; Python code just uses threading.Lock |
| Extension compatibility | Extensions that do not declare free-threading support re-enable the GIL at import |
| Tooling | CPython can be built with ThreadSanitizer (--with-thread-sanitizer, added in 3.13), which detects data races in C-level code; for pure-Python logic races it will not find your check-then-act bugs (those are not memory races). The community "Porting Extension Modules to Support Free-Threading" guide at py-free-threading.github.io is the recommended starting point for library authors |
| Contention | Heavily shared objects (the global random generator, one hot dict) can become contention points; the random documentation recommends separate instances per thread on free-threaded builds |
| Context inheritance | sys.flags.thread_inherit_context and context_aware_warnings default to on in the free-threaded build |
What this means for an AI engineer: if you write code that is correct without the GIL (locks around multi-step state, confinement, queues), it will be correct on both builds, and will be positioned to use threads for CPU-heavy work (tokenizing, parsing, local embedding pre-processing) as the ecosystem catches up. Code that was "fine in production for years" because of the GIL is the code to audit first.
Part 9: Testing for races#
Deep-dive
A race you cannot reproduce is a race you cannot fix with confidence. Five techniques, from sharpest to broadest:
9.1 Force the interleaving#
Put a Barrier or Event in the window so the bad schedule happens every time, as in 3.1 and 3.3. This produces deterministic regression tests: they fail every time before the fix and pass every time after. Add a test hook in the code under test (window_hook() that is a no-op in production), or use unittest.mock.patch to replace a collaborator with a version that waits on a barrier, so the test can park a thread between check and act without changing production behaviour. See 01B.8 §6.3 for the async version of "test concurrency without sleeps".
9.2 An exhaustive schedule explorer#
For a small critical section you can prove a fix by testing every interleaving, as in 2.2. Generalize it: write each "thread" as a generator in which every yield marks a point where the scheduler may switch, and run all schedules against an invariant. Code between two yields is atomic by construction.
# e14_schedule_explorer.py: exhaustively test every interleaving of tiny "threads".
# Each thread is a generator; every `yield` marks a point where the scheduler MAY
# switch to another thread. Code between two yields is atomic.
from collections import Counter
from collections.abc import Callable, Generator, Iterator
from typing import Any
Thread = Generator[None, None, None]
def schedules(lengths: tuple[int, ...]) -> Iterator[tuple[int, ...]]:
"""All orders in which threads with the given step counts can run."""
if sum(lengths) == 0:
yield ()
return
for i, n in enumerate(lengths):
if n:
nxt = list(lengths); nxt[i] -= 1
for rest in schedules(tuple(nxt)):
yield (i,) + rest
def explore(make_world: Callable[[], tuple[dict[str, Any], list[Thread]]],
steps: tuple[int, ...],
invariant: Callable[[dict[str, Any]], bool]) -> tuple[int, list[tuple[int, ...]]]:
bad: list[tuple[int, ...]] = []
total = 0
for sched in schedules(steps):
total += 1
state, threads = make_world()
for t in sched:
next(threads[t], None)
if not invariant(state):
bad.append(sched)
return total, bad
# ---- scenario: two requests reserve the LAST seat of a workshop ---------------
def reserve_racy(state: dict[str, Any], who: str) -> Thread:
if state["seats"] > 0: # CHECK
yield # <- a switch is possible here
state["seats"] -= 1 # ACT
state["booked"].append(who)
yield # (padding so every thread has 2 steps)
def reserve_atomic(state: dict[str, Any], who: str) -> Thread:
# the same code with the check and act inside ONE step (what a lock gives you)
if state["seats"] > 0:
state["seats"] -= 1
state["booked"].append(who)
yield
def world(fn) -> Callable[[], tuple[dict[str, Any], list[Thread]]]:
def make() -> tuple[dict[str, Any], list[Thread]]:
state: dict[str, Any] = {"seats": 1, "booked": []}
return state, [fn(state, "A"), fn(state, "B")]
return make
no_overbooking = lambda s: len(s["booked"]) <= 1 and s["seats"] >= 0
if __name__ == "__main__":
total, bad = explore(world(reserve_racy), (2, 2), no_overbooking)
print(f"racy: {len(bad)} of {total} schedules overbook; first failing order:",
"".join("AB"[i] for i in bad[0]))
total, bad = explore(world(reserve_atomic), (1, 1), no_overbooking)
print(f"atomic: {len(bad)} of {total} schedules overbook")
outcomes = Counter()
for sched in schedules((2, 2)):
state, threads = world(reserve_racy)()
for t in sched:
next(threads[t], None)
outcomes[(len(state["booked"]), state["seats"])] += 1
print("racy outcomes (booked, seats_left): count ->", dict(sorted(outcomes.items())))racy: 4 of 6 schedules overbook; first failing order: ABAB
atomic: 0 of 2 schedules overbook
racy outcomes (booked, seats_left): count -> {(1, 0): 2, (2, -1): 4}Two threads race for the last seat in a workshop. Of six schedules, four overbook (the first failing order is ABAB: both check, then both book), and the outcomes split into the correct (1 booked, 0 seats left) in 2 schedules and the corrupt (2 booked, -1 seats left) in 4. The "atomic" version, where check and act share one step, has no failing schedule at all, which is exactly what a lock gives you. This is a toy model checker: it only sees the switch points you declare, so it proves things about your model of the code, not the code itself. Its value is thinking: writing the steps down forces you to find every gap. For a real project, the same idea scales via property-based tests (hypothesis has stateful testing, covered in 01B.8 §4.3) and model checkers such as TLA+.
9.3 Stress tests that actually stress#
When you cannot force the schedule (the race is inside a library, or the window is not obvious), stress it. A good stress test:
- Starts all threads at the same instant with a
Barrier, so they collide instead of running one after another (thread start-up is slow relative to the work). - Shrinks the switch interval with
sys.setswitchinterval(1e-6)(restore it infinally) so the interpreter offers a switch far more often. - Widens the window with a hook such as
time.sleep(0)(yield the GIL) at the suspicious spot. - Repeats many rounds with fresh state each time, and counts failing rounds. A race that fails one round in a hundred needs hundreds of rounds.
- Asserts an invariant, not a specific interleaving (never negative, one winner, total equals sum).
# e15_stress_test.py: the stress-test recipe: Barrier start, tiny switch interval, many rounds.
import sys
import threading
import time
from collections.abc import Callable
class Inventory:
"""Seats with a check-then-act race; a hook lets the test widen the window."""
def __init__(self, seats: int, lock: threading.Lock | None = None) -> None:
self.seats = seats
self.lock = lock
self.window_hook = lambda: None
def reserve(self) -> bool:
if self.lock is None:
return self._reserve()
with self.lock:
return self._reserve()
def _reserve(self) -> bool:
if self.seats > 0:
self.window_hook() # production: no-op; tests: yield the CPU here
self.seats -= 1
return True
return False
def hammer(make: Callable[[], Inventory], rounds: int = 200, threads: int = 8) -> int:
"""Return how many rounds broke the invariant `seats never negative, one winner`."""
old = sys.getswitchinterval()
sys.setswitchinterval(1e-6) # ask the interpreter to switch very often
failures = 0
try:
for _ in range(rounds):
inv = make()
start = threading.Barrier(threads) # release all threads at the same instant
wins: list[bool] = []
def worker() -> None:
start.wait()
wins.append(inv.reserve())
ts = [threading.Thread(target=worker) for _ in range(threads)]
for t in ts: t.start()
for t in ts: t.join()
if sum(wins) != 1 or inv.seats < 0:
failures += 1
finally:
sys.setswitchinterval(old)
return failures
def make_racy() -> Inventory:
inv = Inventory(1)
inv.window_hook = lambda: time.sleep(0) # sleep(0) = yield the GIL
return inv
def make_safe() -> Inventory:
inv = Inventory(1, threading.Lock())
inv.window_hook = lambda: time.sleep(0)
return inv
if __name__ == "__main__":
print("racy version: rounds that broke the invariant:", "some" if hammer(make_racy) else "none")
print("locked version: rounds that broke the invariant:", "some" if hammer(make_safe) else "none")racy version: rounds that broke the invariant: some
locked version: rounds that broke the invariant: noneA passing stress test is evidence, not proof (the lesson of 2.3). Run it in CI many times, on more than one Python version, on a multi-core runner, and under load (run the test suite in parallel). If a flaky test fails once in 500 runs, do not re-run until green: you have found the bug.
9.4 Other tools and habits#
| Technique | What it finds | Notes |
|---|---|---|
python -X dev (development mode) |
Turns on extra runtime checks, including faulthandler and asyncio debug mode, per the interpreter's documentation of that option |
Cheap to turn on in CI; it does not detect races by itself |
faulthandler.dump_traceback_later(timeout) and py-spy dump |
Where each thread is stuck; for hangs rather than wrong answers | 01C.4 goes deep |
asyncio debug mode (PYTHONASYNCIODEBUG=1, asyncio.run(..., debug=True)) |
Non-thread-safe asyncio calls from the wrong thread, slow callbacks | The asyncio documentation notes that many non-thread-safe APIs raise in debug mode when called from the wrong thread |
| ThreadSanitizer builds of CPython | C-level data races, mainly for extension authors on free-threaded builds | Awareness only, see 8.9 |
| Code review with a checklist (below) | Check-then-act, shared mutable globals, locks held across I/O | The cheapest and highest-yield technique |
Repeat-run tools (pytest --count from the pytest-repeat plugin, or a shell loop) |
Rare failures | Verify the plugin's current version on PyPI before use; or simply write `for i in $(seq 500); do pytest -x tests/test_race.py |
| Randomized scheduling libraries and deterministic simulators | Large-scale schedule exploration | Awareness only; they exist in other ecosystems (Rust's loom, Go's race detector) and Python has less mature equivalents as of November 2026 |
9.5 The review checklist#
Before merging code that touches shared state, ask:
- What is shared? List every mutable object reachable by more than one thread, task, process or request (globals, class attributes, module-level caches,
app.state, default arguments, closures). - Who writes it, and who reads it, and can they overlap?
- Where is the invariant, and is it ever briefly false? (Between a read and the write that depends on it? Across an
await?) - Is any decision based on a check that could go stale? (
if ... in,exists(),empty(),if budget >= n) - Is the fix the cheapest one? Confine, then immutable, then message passing, then database atomics, then a lock.
- If a lock: is it private, held briefly, never across I/O,
awaitor a callback, and acquired withwith? - Does it survive failure? Exceptions inside the critical section, cancellation, a worker that dies holding a claim.
- Does it survive a second process? If you scale to two replicas, which of your in-memory protections stop working?
- Is there a test that fails without the fix? (A forced-schedule test or an explorer; not a
sleep.) - Is the thread-safety level documented on the class, in one sentence?
Failure gallery#
The races below are the ones that reach production. Each row is a symptom, the cause and the fix; the section links point back to where the lesson shows it.
| Symptom | Cause | Fix |
|---|---|---|
| A counter, balance or quota is slightly low, never high | Read-modify-write without atomicity: a lost update (2.1, 5.2) | Lock around the whole update, or UPDATE ... SET n = n + ? in the database |
| Budget, stock or seat count goes negative | Check-then-act with a slow step (or await) between (3.1, 4.1) |
Reserve under a lock before the slow step; guarded UPDATE ... WHERE used + ? <= limit |
| The expensive object (model, client pool) is created twice | Naive lazy init (8.7) | Initialize at startup, or double-checked locking, or single-flight |
| The provider is billed N times for one key | Async cache stampede (4.2) | Single-flight per key, shield the shared task |
| One user receives another user's history or identity in logs | Module-level or class-level mutable state; threading.local used with asyncio (6.4, 8.5) |
Request-local variables; contextvars for ambient state |
| A value set while handling request A shows up while handling request B | threading.local on a reused thread-pool worker (8.5) |
Set and clear at the start/end of each job, or use contextvars with a token reset |
| Refund email, ticket or charge happens two or three times | At-least-once delivery, retries or double-clicks with a non-idempotent action (6.3, 5.3) | Idempotency key with a unique constraint; claim before acting |
| Two jobs both "won" the lock file | exists() then create (3.3) |
open(path, "x"), or a database/OS lock |
| A reader sometimes gets a half-written config or cache file | Writing straight into the final path (3.3) | Temp file in the same directory, fsync, then os.replace |
RuntimeError: dictionary changed size during iteration |
Iterating a container while it is mutated, from another thread or the same one (8.3) | Iterate over a snapshot (list(d), lst.copy()); or guard with a lock |
KeyError/IndexError right after an if key in d / if lst check |
Two safe calls are not one safe call (8.4) | get, pop(key, None), discard, EAFP, or a lock around both |
Consumer blocks forever after if not q.empty(): q.get() |
empty() is a snapshot (7.5) |
get_nowait() with except queue.Empty, or get(timeout=...) |
| Results arrive in odd order or some are missing from a shared list | Shared structure, no owner, and a wrong assumption about order | Collect (index, result) pairs, or per-worker lists merged at the end |
| Works on one worker, wrong with two replicas | The protection was an in-process lock or a global (5.3) | Move the guarantee into the database (constraint, atomic statement) |
| Tests pass locally, fail one run in 500 in CI | An unfixed race; a sleep-based test (9.1, 9.3) |
Forced-schedule test; stress with Barrier and a small switch interval; never re-run until green |
| A change that "only added a log line" now loses updates | An await or a Python call was added inside a previously atomic section (4.1) |
Keep atomic sections in tiny synchronous helpers; comment them |
| Reserved tokens or seats slowly vanish; the budget "fills up" with no real spend | A failure or cancellation between reserve and settle with no release/finally (6.1, 4.4) |
Release in finally or except BaseException and re-raise |
RuntimeError: ... is bound to a different event loop |
An asyncio.Lock/Queue created at import time and reused across asyncio.run() calls (4.4) |
Create primitives inside the running loop (main, lifespan) |
| Everything froze after adding a lock | The lock is held across I/O, or taken in inconsistent order, or re-acquired by the same thread | 7.7; 01C.4 |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The GIL makes my Python code thread-safe." | It makes single operations on built-in types that call no Python code atomic on the default build. It does not make sequences atomic, and in free-threaded builds it is absent (2.4, 8.9) |
| "I ran it 10 million times and it never failed, so it is safe." | A race you cannot trigger is still a race. The plain += loop never failed here either (2.3); a one-line change to the window made it fail every run |
"counter += 1 is atomic because it is one line." |
It is a load, an add and a store. One line of source is irrelevant; what matters is the number of interruptible steps (2.1) |
"asyncio has no races because it is single-threaded." |
Tasks can interleave at any await that suspends. Check-await-act is a race (4.1) |
| "I used a thread-safe container, so my code is thread-safe." | Safe calls do not compose. if k not in d: d[k] = ... is a race on a perfectly safe dict (8.4) |
"functools.lru_cache runs the function once per argument." |
The cache structure is thread-safe; the function can still run several times concurrently for the same key (8.3, 8.7) |
"queue.empty() tells me whether get() will block." |
It is a snapshot that can be stale before you act on it (7.5) |
| "A lock makes the code correct." | Only if it covers the whole invariant, is held for the right span, and is always released. A lock around only the write, or taken after the check, protects nothing (7.2) |
| "More locks means more safety." | More locks mean more contention and deadlock risk. Confine, make immutable or pass messages first (7.0) |
"threading.local is the right place for per-request state." |
Not under asyncio (tasks share the thread) and not on reused pool threads without cleanup. Use contextvars (8.5) |
| "An in-process lock protects me when I scale out." | It protects one process. Two replicas need database constraints, atomic statements or a distributed mechanism (5.3) |
"time.sleep() in the test fixes the ordering." |
It hides the race on your machine. Use join, Event, Barrier, or a queue (9.1) |
| "Free-threaded Python will make threads safe/fast automatically." | It removes the GIL's accidental protection and adds real parallelism. Correct programs stay correct; sloppy ones fail more often (8.9) |
Key takeaways#
- A race condition is a correctness bug whose outcome depends on timing. The recurring shapes are read-modify-write (lost update) and check-then-act (TOCTOU). A data race is the narrower, low-level cousin; in pure Python you mostly meet race conditions.
- A race needs something shared, mutable and concurrent. Remove one: confine it, make it immutable, or serialize access. Reach for a lock last (7.0).
counter += 1is three steps (disshows them). Of 20 possible interleavings of two threads, 18 lose an update; correctness must come from construction, not luck (2.2).- On Python 3.14.6 a plain integer
+=loop did not lose updates in 9.6 million attempts, while shapes with a Python function call or a Python__add__in the window did (a plain dict+=stayed exact too: the container does not matter, anything that can offer a thread switch does). That is an implementation accident of today's GIL build, not a guarantee, and absence of failure is not evidence of safety. - The official FAQ lists single operations (
L.append,D[x] = y,D1.update(D2)) as atomic on the GIL build, and read-modify-write and check-then-act as not. Treat that as an implementation detail and do not rely on it for multi-step logic. asyncioraces need anawaitinside the window. "No await, no race" is true and fragile: making a helperasynccan silently break an atomic section. Reserve before the slowawait, settle after it, and release in afinallyso a failure or cancellation cannot leak the reservation. Create asyncio primitives inside the running loop.- Across files, processes and databases the same shapes appear with weaker tools:
open(p, "x")andos.replace,multiprocessing.Value.get_lock(), atomic and guardedUPDATEstatements, version columns (CAS), idempotency keys. - Thread safety is a spectrum of five levels (immutable, unconditionally safe, conditionally safe, not safe, hostile; Bloch's classification) and a property of a documented specification. Compositions of safe operations are not safe. One class, one private lock, one invariant, no slow work inside.
- Use
contextvars, notthreading.local, for per-request state in async code; never keep per-user state in globals; bewarethreading.localon pooled threads. - Lazy singletons: prefer initialization at startup; otherwise double-checked locking or single-flight.
functools.cacheandcached_propertydo not guarantee call-once. - Free-threaded CPython (officially supported since 3.14, still optional) removes the GIL's accidental protection. Code that is correct without the GIL is correct on both.
- Test races by forcing the schedule (
Barrier/Eventhooks), by enumerating all schedules for small critical sections, and by stress (Barrierstart,sys.setswitchinterval(1e-6), many rounds). A passing stress test is evidence, not proof; never fix a race withsleep.
Where you'll use this in the AI path#
| Where | What it applies |
|---|---|
01B.4 §7.1 Single-flight and §7.2 asyncio.Lock |
The production tools for the races in Parts 3, 4 and 6 |
| 01B.9 §3.3 Idempotency keys | The cross-process cure for double-submits and duplicate tool calls (5.3) |
| 03.9 §4.8 Threads for code that isn't async | Sync SDKs in a thread pool: shared clients, shared results, thread-safe hand-off (4.3, 7.5) |
| 08A.2 §4.1 Parallel tool calls and §6.3 Idempotency for tools | Tool calls that run concurrently must be race-free and idempotent (6.3) |
| 08A.6 §4.3 Idempotency keys and safe retries | Designing tools so that duplicates are harmless |
| 11B.3 §7.6 Cache stampede | Single-flight for an LLM response cache |
| 11C.3 §4.1 Bulkheads | Limiting concurrent access to a shared dependency; budgets and quotas that must not be exceeded |
| 11C.1 §5.1 Stateless by design | Why per-user state must not live in the process (6.4) |
| 12.4 §1.5 Cross-tenant and cross-user leakage | Race-induced cross-talk is a data-leak incident |
01B.7 FastAPI lifespan and app.state |
Where shared, read-only resources belong (8.7) |
| Next in this module: 01C.4, 01C.5, 01C.7 | What locks cost; what the GIL really does; synchronizing shared memory across processes |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Race condition | A bug whose result depends on the relative timing of operations that were assumed ordered or exclusive |
| Data race | Unsynchronized concurrent access to one memory location where at least one access is a write (a low-level, memory-model term) |
| Check-then-act | A decision made from a check that can be stale by the time the action runs |
| TOCTOU | "Time of check to time of use": check-then-act applied to files and permissions |
| Read-modify-write / lost update | Read, compute from the old value, write back; a concurrent write in between is overwritten |
| Critical section | Code that must run as if it were atomic |
| Atomic operation | An operation others can observe only before or after, never half-done |
| Invariant | A condition that must hold between operations ("stock is never negative") |
| Heisenbug | A bug that disappears or changes when observed |
| Visibility | Whether one thread is guaranteed to see another thread's write, and in what order (synchronization objects provide the guarantee) |
| Schedule / interleaving | One possible order in which the steps of several threads run |
Mutex / Lock |
Primitive that admits one thread at a time to a critical section |
RLock |
Reentrant lock: the owning thread may acquire it repeatedly |
Semaphore / BoundedSemaphore |
Gate admitting at most N holders; the bounded form errors on over-release |
Condition |
A lock plus waiting for a predicate about shared state |
Barrier |
Blocks until N parties arrive, then releases all (also a testing tool) |
| Confinement | Keeping state private to one thread or task so nothing is shared |
| Message passing / owner thread | One owner mutates state; others send it messages through a queue |
| Copy-on-write / publish by assignment | Build a new immutable value and replace the shared reference in one step |
| Compare-and-swap (CAS) | Set a value only if it still equals what you read; retry on failure |
| Optimistic / pessimistic concurrency | Detect and retry conflicts versus lock to prevent them |
| Idempotency key | Unique id per intended operation, letting a repeat be recognized and ignored |
| Double-checked locking | Check without a lock, then lock and check again, then create |
| Single-flight | Collapsing concurrent identical computations into one shared one |
| Thread-safe | Behaves correctly under concurrent use without extra locking by the caller (level matters) |
| Reentrancy | A function can be safely re-entered before an earlier call finishes |
threading.local / contextvars |
Per-thread slot / per-context (per-task) slot |
| Schedule explorer | A test that runs every interleaving of small modelled steps against an invariant |
All terms are also collected in the glossary.
Exercises#
- Read the bytecode (2.1). Use
disto look atd["k"] += 1andlst.append(1). Which one contains a gap between a read and a write of the shared object, and which one does the whole job in a singleCALL? - Count schedules with a lock (2.2). Extend the interleaving enumerator to the steps
acquire, load, add, store, releasefor two threads, treating anacquirewhile the lock is held as impossible. How many schedules are possible, and what final values appear? - Fix a limiter (3.1). A sliding-window limiter with
limit=1doesif len(calls) < limit: calls.append(now)and returns whether it allowed the call. Show, with aBarrierplaced between the check and the append, that five simultaneous callers are all allowed; then fix it so exactly one is. - Claim a daily job (3.3). Write
try_claim(dir, day, who)so that exactly one of six simultaneous workers wins a day's report job, using exclusive file creation. - Predict the output (4.1). Two seats are left. Four tasks each run
book(user):if seats > 0:, thenawait write_audit(...)(an async log write), thenseats -= 1. All four are started together withasyncio.gather. What is printed for accepted bookings and seats left? Where is the race, and how would you fix it without a lock? - Make a webhook idempotent (5.3). A payments provider may deliver the same
event_idtwice. Use a primary-key constraint so each event creates its invoice at most once. - Spot the leak (8.5). A pool worker handles request after request. Show how a
threading.localvalue leaks into a later request, and say what to use instead. - One writer for many threads (7.5). Five threads must append events to one file without interleaving lines. Use an owner thread and a queue.
- Classify the thread safety (8.3, 8.4). For each statement say whether it is safe, safe only with a lock, or a trap, and why: (a)
results.append(x)from many threads; (b)if k in d: d[k] += 1; (c)for item in shared_list: ...while another thread appends; (d)q.get_nowait()in atryforqueue.Empty; (e)@functools.cacheon a function that loads a 2 GB model. - Why does the stress test need a Barrier? (9.3) Predict what happens to the failure rate of
e15_stress_test.pyif you remove theBarrierand why. - Which build am I on? (8.9) Write a script that prints the Python version, whether the build is free-threaded, whether the GIL is on, and the switch interval.
- Review a design (9.5). A teammate proposes caching LLM answers in a module-level
dict, checkingif prompt in cache, calling the model, then writingcache[prompt] = answer, deployed on four worker processes. List every problem and the cheapest fix for each.
Solution
1. Script ex01_dis_other.py (Python 3.14.6; opcode names differ between versions):
# ex01_dis_other.py: how many separate steps are these statements?
import dis
def a(d: dict[str, int]) -> None:
d["k"] += 1
def b(lst: list[int]) -> None:
lst.append(1)
for fn in (a, b):
print("==", fn.__name__)
dis.dis(fn)== a
4 RESUME 0
5 LOAD_FAST_BORROW 0 (d)
LOAD_CONST 0 ('k')
COPY 2
COPY 2
BINARY_OP 26 ([])
LOAD_SMALL_INT 1
BINARY_OP 13 (+=)
SWAP 3
SWAP 2
STORE_SUBSCR
LOAD_CONST 1 (None)
RETURN_VALUE
== b
7 RESUME 0
8 LOAD_FAST_BORROW 0 (lst)
LOAD_ATTR 1 (append + NULL|self)
LOAD_SMALL_INT 1
CALL 1
POP_TOP
LOAD_CONST 1 (None)
RETURN_VALUEd["k"] += 1 reads the value with BINARY_OP ([]), adds in a separate BINARY_OP (+=), and writes with STORE_SUBSCR: a read, a modify and a write, with a window in between. lst.append(1) is a single CALL: the FAQ's "one operation, atomic". The first needs a lock (or a different design); the second does not.
2.
# ex02_lock_schedules.py: enumerate schedules for `with lock: counter += 1` in 2 threads.
from collections import Counter
STEPS = ("acquire", "load", "add", "store", "release")
def schedules(n_steps, threads=2):
def rec(left):
if sum(left) == 0:
yield ()
return
for t in range(threads):
if left[t]:
nxt = list(left); nxt[t] -= 1
for rest in rec(tuple(nxt)):
yield (t,) + rest
yield from rec((n_steps,) * threads)
def run(schedule):
"""Return final counter, or None if the schedule is impossible with a lock."""
shared, holder = 0, None
local, pc = [0, 0], [0, 0]
for t in schedule:
step = STEPS[pc[t]]
if step == "acquire":
if holder is not None:
return None # a real thread would BLOCK here: schedule not possible
holder = t
elif step == "load":
local[t] = shared
elif step == "add":
local[t] += 1
elif step == "store":
shared = local[t]
else:
holder = None
pc[t] += 1
return shared
total = valid = 0
outcomes = Counter()
for s in schedules(len(STEPS)):
total += 1
r = run(s)
if r is not None:
valid += 1
outcomes[r] += 1
print(f"{total} step orders, {valid} are possible when a lock blocks the second thread")
print("final counter values over the possible ones:", dict(outcomes))252 step orders, 2 are possible when a lock blocks the second thread
final counter values over the possible ones: {2: 2}Of 252 orders of ten steps, only 2 are possible once the lock makes the second thread wait (one thread's whole acquire-to-release block, then the other's), and both give 2. A lock does not make the steps themselves atomic; it removes the bad schedules from existence.
3.
# ex03_rate_limiter.py: fix a check-then-act race in a sliding-window limiter.
import threading
class RacyLimiter:
def __init__(self, limit: int) -> None:
self.limit = limit
self.calls: list[int] = []
self.hook = lambda: None
def allow(self, now: int) -> bool:
if len(self.calls) < self.limit: # CHECK
self.hook() # window (test hook)
self.calls.append(now) # ACT
return True
return False
class SafeLimiter(RacyLimiter):
def __init__(self, limit: int) -> None:
super().__init__(limit)
self._lock = threading.Lock()
def allow(self, now: int) -> bool:
with self._lock: # check and act are one critical section
return super().allow(now)
def trial(limiter, hook=lambda: None) -> int:
limiter.hook = hook # what runs inside the window
allowed: list[bool] = []
def worker() -> None:
allowed.append(limiter.allow(0))
ts = [threading.Thread(target=worker) for _ in range(5)]
for t in ts: t.start()
for t in ts: t.join()
return sum(allowed)
if __name__ == "__main__":
print("limit 1, 5 simultaneous callers")
print("racy limiter allowed:", trial(RacyLimiter(1), hook=threading.Barrier(5).wait))
print("safe limiter allowed:", trial(SafeLimiter(1)))limit 1, 5 simultaneous callers
racy limiter allowed: 5
safe limiter allowed: 1The barrier sits in the window (between the check and the append) in the racy trial, forcing all five to pass the check; in the safe trial the lock means only one can be in the window at a time, so the check stays true for exactly one caller. The fix wraps check and act in one critical section.
4.
# ex04_claim_file.py: a once-per-day job claim with exclusive file creation.
import tempfile
import threading
from pathlib import Path
def try_claim(dirpath: Path, day: str, who: str) -> bool:
try:
with open(dirpath / f"report-{day}.claim", "x") as f:
f.write(who)
return True
except FileExistsError:
return False
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as d:
results: list[bool] = []
ts = [threading.Thread(target=lambda i=i: results.append(try_claim(Path(d), "2026-11-20", f"w{i}")))
for i in range(6)]
for t in ts: t.start()
for t in ts: t.join()
print("claims won:", sum(results), "of", len(results))
print("next day is independent:", try_claim(Path(d), "2026-11-21", "w0"))claims won: 1 of 6
next day is independent: Trueopen(..., "x") fails with FileExistsError for everyone but the first creator; the check and the create are the same system call.
5.
# ex05_async_seats.py: where is the race, and what does it print?
import asyncio
seats = 2
audit: list[str] = []
async def write_audit(msg: str) -> None:
await asyncio.sleep(0) # pretend this is an async log/DB write
audit.append(msg)
async def book(user: str) -> bool:
global seats
if seats > 0:
await write_audit(f"{user} booking") # an await inside the window
seats -= 1
return True
return False
async def main() -> None:
results = await asyncio.gather(*(book(u) for u in "abcd"))
print("accepted:", sum(results), "| seats left:", seats)
asyncio.run(main())accepted: 4 | seats left: -2All four tasks see seats > 0 before any of them reaches seats -= 1, because each awaits write_audit in between: 4 accepted, -2 seats left. Fix without a lock: deduct first, then await (seats -= 1 right after the check, with no await between them, then write the audit line), and refund if the later work fails. That makes the check-and-deduct atomic by the "no await, no race" rule; an asyncio.Lock around the whole block also works but would serialize the audit writes.
6.
# ex06_idempotent_webhook.py: process each webhook event id at most once (sqlite3).
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE seen (event_id TEXT PRIMARY KEY)")
con.execute("CREATE TABLE invoices (event_id TEXT, amount INTEGER)")
def handle(event_id: str, amount: int) -> bool:
with con: # ONE transaction: commit on success, roll back on error
cur = con.execute("INSERT OR IGNORE INTO seen VALUES (?)", (event_id,))
if cur.rowcount == 0: # the unique constraint said: seen before
return False
con.execute("INSERT INTO invoices VALUES (?, ?)", (event_id, amount))
return True # a crash before the commit leaves neither row
print([handle("evt_1", 100), handle("evt_1", 100), handle("evt_2", 50), handle("evt_1", 100)])
print("invoices:", con.execute("SELECT COUNT(*), SUM(amount) FROM invoices").fetchone())[True, False, True, False]
invoices: (2, 150)INSERT OR IGNORE against the primary key is the atomic "claim"; rowcount == 0 means the event was seen. (The claim and the invoice insert share one transaction (with con:), so a crash between them cannot leave an event marked seen with no invoice. Syntax for the same idea in PostgreSQL is INSERT ... ON CONFLICT DO NOTHING; check your database's documentation.)
7.
# ex07_pool_local_leak.py: threading.local leaks between jobs on a reused pool thread.
import threading
from concurrent.futures import ThreadPoolExecutor
tls = threading.local()
def job(user: str | None) -> str:
if user is not None:
tls.user = user
return getattr(tls, "user", "<nobody>")
with ThreadPoolExecutor(max_workers=1) as pool: # one reused worker thread
print(pool.submit(job, "ana").result())
print("next request sets no user ->", pool.submit(job, None).result())ana
next request sets no user -> anaWith one reused worker thread, the second request never set a user but still read ana's value. Use contextvars.ContextVar and set it at the start of every request (resetting with the token at the end), or pass the user explicitly as an argument.
8.
# ex08_owner_log.py: many threads, ONE writer thread that owns the file.
import queue
import tempfile
import threading
from pathlib import Path
def main() -> None:
with tempfile.TemporaryDirectory() as d:
path = Path(d) / "events.log"
q: queue.Queue[str | None] = queue.Queue()
def writer() -> None:
with open(path, "w") as f:
while (line := q.get()) is not None:
f.write(line + "\n")
w = threading.Thread(target=writer)
w.start()
def producer(i: int) -> None:
for j in range(100):
q.put(f"worker={i} event={j}")
ts = [threading.Thread(target=producer, args=(i,)) for i in range(5)]
for t in ts: t.start()
for t in ts: t.join()
q.put(None)
w.join()
lines = path.read_text().splitlines()
print("lines written:", len(lines), "| all intact:", all(l.startswith("worker=") for l in lines))
if __name__ == "__main__":
main()lines written: 500 | all intact: TrueOnly the writer thread ever touches the file; the five producers touch only the queue, which does its own locking.
9. (a) Safe: a single list.append is atomic (the FAQ); each worker makes one shared write. (b) Trap: check-then-act plus read-modify-write on a dict; the key can vanish and the += 1 can lose updates; use a lock around both, or collections.Counter per thread then merge. (c) Trap: iteration is not atomic; iterate over shared_list.copy() or lock around the loop. (d) Safe: check and act are one call; Empty is the normal "nothing there" signal. (e) Trap for expensive loads: functools.cache is not call-once; two threads can both load the model; use initialization at startup or single-flight (8.7).
10. Without a Barrier the threads start one by one while earlier ones may already have finished their one-line work, so they rarely overlap, and the failure rate drops sharply, possibly to zero in many rounds. The barrier makes all eight arrive at the check together. (Try it: delete the start.wait() line and compare. The exact rates are machine-dependent.)
11.
# ex09_build_info.py: which kind of Python am I on?
import sys
import sysconfig
print("version:", sys.version.split()[0])
print("free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED") == 1)
print("GIL enabled right now:", getattr(sys, "_is_gil_enabled", lambda: True)()) # 3.13+
print("switch interval (s):", sys.getswitchinterval())version: 3.14.6
free-threaded build: False
GIL enabled right now: True
switch interval (s): 0.005On a free-threaded build free-threaded build would be True, and GIL enabled right now would normally be False unless an incompatible extension or PYTHON_GIL=1 re-enabled it.
12. Problems and cheapest fixes: (1) check-then-act with a slow model call between: identical prompts arriving together all miss and all call the model: single-flight per key (7.8 or 4.2). (2) Four processes do not share a module-level dict: each has its own cache, hit rate is a quarter, and any invalidation reaches one process only: use a shared store (Redis, a database), where atomic commands and constraints give you the guarantees (5.3). (3) Unbounded growth and no expiry: bound the size and add a TTL. (4) Cache key = prompt only: a shared cache must key on everything that changes the answer, including the user's permission scope (see 11B.3 for the caching rules and 12.4 for the leakage risk). (5) Caching failed or partial answers: only store complete, successful responses (11B.3 §7.7).
Check yourself#
- In your own words: what is the difference between a data race and a race condition? Can you have a race condition without a data race?A data race is unsynchronized concurrent access to one memory location with at least one write: a low-level property. A race condition is a logic error that depends on timing, e.g. two safe calls that together are not atomic. Yes: check-then-act on a thread-safe container is a race condition with no data race.
- List the three bytecode-level steps of
counter += 1and say where another thread can cause a lost update.Load the value, add one to the private copy, store it back. A lost update happens when another thread's load-to-store window overlaps: both loaded the same old value, so the later store overwrites the earlier increment. - Of the 20 possible interleavings of two threads doing
counter += 1, how many give the right answer, and what do they have in common?Two of twenty (AAABBBandBBBAAA): the schedules where one thread completes all three steps before the other starts, i.e. the operation behaved atomically. - Why did the plain
counter += 1loop not lose updates in the Python 3.14.6 experiment, and why is that not a reason to skip the lock?In this implementation the three instructions contain no point where the interpreter hands over the GIL, so the loop was effectively uninterruptible; that is a detail of the current CPython build and changes between versions, and free-threaded builds remove it. Variants with a Python call or a Python__add__in the window did lose updates (the plain dict+=did not: the container is irrelevant). Absence of failure is not evidence of safety. - Name three operations the Python FAQ lists as atomic and two it lists as not atomic.Atomic:
L.append(x),D[x] = y,D1.update(D2)(alsoL.pop(),L.sort(),x = y). Not atomic:i = i+1,D[x] = D[x] + 1(alsoL.append(L[-1]),L[i] = L[j]). - In
asyncio, what is the minimum thing that must be inside a read-modify-write for it to be racy?A suspension point, usually anawait, between the read and the write (or between the check and the act). - What is the "reserve, then work, then settle" pattern and which race does it close?Under a short lock, check and deduct the estimate in one critical section; do the slow call outside the lock; then settle the real amount (and release the reservation on failure or cancellation). It closes the check-await-act race on budgets and quotas.
- Give two atomic ways to create a file only if it does not exist, and one way to replace a file so readers never see a partial write.
open(path, "x")(exclusive creation) oros.openwith the create-and-exclusive flags; a database row with a unique constraint. To replace: write a temp file in the same directory, flush andfsync, thenos.replace(tmp, final). - Why does
UPDATE quota SET used = used + ?avoid the lost update that "read in Python, write back" has? What doesWHERE version = ?add?The database applies the arithmetic to the current value inside one statement, so no stale read exists.WHERE version = ?(CAS) lets you update a whole record based on what you read and learn (zero rows updated) when someone else changed it, so you can re-read and retry. - Why is an in-process
threading.Locknot enough once you run two server replicas?It lives inside one process; the second replica has its own lock and its own memory. Cross-process guarantees must come from shared mechanisms: database constraints and atomic statements, or a distributed lock. - A class wraps a
dictand has methodsget,putandget_or_createthat each take the same private lock. Which levels of thread-safety does it offer, and what must a caller still not do?Each single operation is atomic (andget_or_createis correct), so it is conditionally thread-safe: the caller must still not compose calls (if c.get(k) is None: c.put(k, v)is a race), must not mutate returned mutable values, and must not iterate over internal state. Document the level. - What is the difference between
threading.localandcontextvars.ContextVarunder asyncio, and which should hold a request id?threading.localis per OS thread, so all tasks on one event loop thread share a slot and overwrite each other;ContextVarvalues are per context and each asyncio task runs in its own copy. Usecontextvarsfor a request id. functools.cachemakes a function thread-safe. True or false, and why?False. The cache's internal data structure is safe for concurrent use, but the function body can run more than once concurrently for the same arguments, and the function itself is not made thread-safe by caching.- Name three ways to test a suspected race, and one thing you must never do to "fix" it.Force the interleaving with a
Barrier/Eventhook; enumerate all schedules of a small model (schedule explorer); stress test with aBarrierstart,sys.setswitchinterval(1e-6), a window-widening hook and many rounds (also code review with a checklist). Never "fix" it withtime.sleep. - What changes about this lesson's advice on a free-threaded Python build?The GIL's accidental protection disappears, so check-then-act and read-modify-write sequences are exposed; single operations on
dict/list/setstay safe via internal locks, per the free-threading documentation. Code that is correct without the GIL (locks, confinement, queues, atomic DB statements) stays correct; code that relied on the GIL must be audited.
Further resources#
- Python FAQ: What kinds of global value mutation are thread-safe?: the official list of atomic and non-atomic operations.
threadingdocumentation:Lock,RLock,Condition,Semaphore,Event,Barrier,local.queuedocumentation andasynciosynchronization primitives.asynciodeveloping guide: concurrency and multithreading:call_soon_threadsafeandrun_coroutine_threadsafe.contextvarsandfunctools.cache/cached_property.sqlite3and thread safety,loggingthread safety,decimalworking with threads.- Python support for free threading (HOWTO) and free-threading extensions HOWTO.
- PEP 703: Making the Global Interpreter Lock Optional and PEP 779: Criteria for supported status for free-threaded Python.
- Python 3.14 release notes: free-threaded status,
thread_inherit_context,InterpreterPoolExecutor. - Thread Safety Guarantees (Python 3.14 documentation): what built-in types guarantee on the free-threaded build.
- Joshua Bloch, Effective Java (3rd ed.), Item 82 "Document thread safety": the source of the five-level classification in 8.1. Brian Goetz et al., Java Concurrency in Practice: the best long treatment of the underlying ideas; both transfer directly to Python.
- Share Memory By Communicating (Go blog): the proverb behind confinement and message passing. Rob Pike, "Concurrency is not parallelism": background for 01C.1.
- PostgreSQL transaction isolation and explicit locking: what a transaction does and does not protect (5.2b).
← 01C.2: Synchronous vs Asynchronous Programming and the asyncio Event Loop | Module 01C overview | 01C.4: Deadlocks, Livelock and Starvation →