Skip to content

Lesson 11 of 28Keeping code healthy

Concurrency Patterns

Find and fix the races you will actually ship, avoid deadlock, and pick the right model and pattern for I/O-bound and CPU-bound work.

16 min read0/5 questions

A customer has a gift card worth 50. They tap "Pay 30" on their phone and, because the first tap seemed slow, tap again. Two requests reach two workers at the same moment. Both read a balance of 50, both decide 30 is affordable, and both write 20. The shop has handed out 60 of goods for a 50 card, and no test caught it, because every test sends one request at a time. Concurrency bugs are the ones that pass review, pass CI, and show up at 2 a.m. under real load. This lesson gives you the vocabulary to spot them, the tools to fix them, and the patterns teams use to avoid writing them in the first place.

Concurrency is not parallelism

Concurrency means several tasks are in progress at once: their lifetimes overlap. Parallelism means several tasks are executing at the same instant on different CPU cores. A single-core machine can be concurrent (it switches between tasks) but never parallel. A Node.js server handling 5,000 open requests is highly concurrent and, for your JavaScript, not parallel at all.

The distinction matters because the bugs come from concurrency, not from parallelism. Any time two tasks can interleave, and one can observe the other's half-finished work, you can have a race. That is true on one core, in one thread, and inside async code.

There are three broad models you will meet:

ModelHow tasks share dataWhere you see itMain risk
Threads with shared memoryRead and write the same objectsJava, Go, C#, Python threadsRaces on shared state, deadlock
Event loop (async)One thread, tasks switch only at awaitNode.js, browsers, Python asyncioRaces across await, one blocking call freezes everything
Message passingEach task owns its data and sends copiesProcesses, actors (Erlang, Akka), Go channels (CSP)Lost or duplicated messages, mailbox backlog

Go is the classic hybrid: it has shared memory and locks, but the idiom is "do not communicate by sharing memory; share memory by communicating", meaning pass values through channels. CSP (communicating sequential processes) is the formal name for that channel style.

The three races you will ship

Almost every production race is one of three shapes.

Check-then-act. You check a condition, then act on it, and the condition changes in between. "If the username is free, insert it." "If stock is above zero, reserve one." Two requests both pass the check.

Read-modify-write. You read a value, compute a new one, and write it back. count += 1 is the smallest example: it is a read, an add and a store, and another thread can run between them. The second writer overwrites the first one's update, which is why this is also called a lost update.

Lazy initialisation. "If the cache client is None, create it." Two threads see None and both create one. Usually harmless, sometimes it opens two connection pools or runs a migration twice.

You cannot rely on luck to reproduce these, so the block below simulates two threads with generators. Each yield is a moment where the operating system could switch threads. The scheduler alternates between the two, which is the worst case.

Python
# Each `yield` is a point where the OS could switch to the other thread.def withdraw(name, card, amount, log): balance = card["balance"] # read yield if balance >= amount: # check yield card["balance"] = balance - amount # write log.append(f"{name} spent {amount}") else: log.append(f"{name} refused") def locked_withdraw(name, card, amount, log, lock): while lock["held"]: # wait for the lock yield lock["held"] = True yield from withdraw(name, card, amount, log) lock["held"] = False def run_round_robin(tasks): while tasks: for t in list(tasks): try: next(t) except StopIteration: tasks.remove(t) for label in ["no lock", "with lock"]: card, log, lock = {"balance": 50}, [], {"held": False} if label == "no lock": tasks = [withdraw("A", card, 30, log), withdraw("B", card, 30, log)] else: tasks = [locked_withdraw("A", card, 30, log, lock), locked_withdraw("B", card, 30, log, lock)] run_round_robin(tasks) print(f"{label}: {log}, balance left {card['balance']}")
Output
Press Run (⌘ Enter) to see what happens.

Without the lock, both withdrawals succeed and the balance says 20 after 60 was spent. With the lock, the read, check and write become one critical section, and B sees the real balance.

The same race across two HTTP requests

In a web app the shared state is usually a database row, and the "threads" are two requests on two servers. An in-process lock does nothing here, because the two requests may not even run on the same machine. The fix is to let the database do the check and the write in one statement, or to lock the row. You saw what transactions guarantee in the ACID section of Databases. This is where it bites.

Python
import sqlite3 db = sqlite3.connect(":memory:")db.execute("CREATE TABLE cards (id TEXT PRIMARY KEY, balance INTEGER NOT NULL)")db.execute("INSERT INTO cards VALUES ('GIFT-1', 50)") def balance(): return db.execute("SELECT balance FROM cards WHERE id = 'GIFT-1'").fetchone()[0] # Broken: read in the app, decide in the app, write the computed value.# Two requests interleave: both SELECT before either UPDATE.seen_by_a = balance()seen_by_b = balance()for seen in (seen_by_a, seen_by_b): if seen >= 30: db.execute("UPDATE cards SET balance = ? WHERE id = 'GIFT-1'", (seen - 30,))print("read-modify-write:", balance(), "left after spending 60") # Fixed: one conditional UPDATE. The database checks and writes atomically.db.execute("UPDATE cards SET balance = 50 WHERE id = 'GIFT-1'") def redeem(amount): cur = db.execute( "UPDATE cards SET balance = balance - ? WHERE id = 'GIFT-1' AND balance >= ?", (amount, amount), ) return cur.rowcount == 1 # 0 rows means the check failed print("atomic update:", redeem(30), redeem(30), "->", balance(), "left") # Check-then-act on inserts: let a UNIQUE constraint be the check.db.execute("CREATE TABLE redemptions (request_id TEXT PRIMARY KEY, amount INTEGER)")for attempt in ("req-7", "req-7"): # the client retried the same request cur = db.execute( "INSERT INTO redemptions VALUES (?, 30) ON CONFLICT DO NOTHING", (attempt,) ) print(attempt, "recorded" if cur.rowcount == 1 else "duplicate ignored")
Output
Press Run (⌘ Enter) to see what happens.

The interleaving is written out by hand here, but it is exactly what happens on a busy server. Your toolbox for database races, from lightest to heaviest:

  1. A conditional atomic update, as above. In Postgres at the default Read Committed level, the second UPDATE waits for the first to commit, then re-checks the WHERE against the new row. It finds balance = 20, matches nothing, and you see zero rows affected.
  2. A unique constraint turns check-then-act on inserts into one atomic step. Catch the violation or use ON CONFLICT.
  3. SELECT ... FOR UPDATE locks the row for the rest of the transaction when the logic is too complex for one statement.
  4. Optimistic concurrency: store a version column, update WHERE id = ? AND version = ?, and retry if zero rows changed. Good when conflicts are rare.
  5. A stricter isolation level (Serializable), with retries on serialization failures.
Predict the outputJavaScript

What does this print?

let seats = 1;
async function book(name) {
if (seats > 0) {
  await Promise.resolve();
  seats -= 1;
  console.log(name, "booked");
}
}
Promise.all([book("A"), book("B")]).then(() => console.log(seats));
Need a nudge? Hints walk you through it.

The toolbox: locks, atomics, queues, semaphores

Locks (mutexes) make a block run by one thread at a time. The design choice is granularity. One global lock is easy to reason about and serialises everything. A lock per entity (per account, per cart) lets unrelated work proceed in parallel, at the price of more locks to get right. A common shape is a dictionary of locks keyed by ID, created under one small global lock so the lazy-initialisation race does not bite the lock table itself.

import threading
from collections import defaultdict
 
_registry_lock = threading.Lock()
_account_locks: dict[str, threading.Lock] = defaultdict(threading.Lock)
 
def lock_for(account_id: str) -> threading.Lock:
    with _registry_lock:                 # protect the dict itself
        return _account_locks[account_id]
 
def transfer_in(account_id: str, cents: int) -> None:
    with lock_for(account_id):           # only this account is serialised
        ...

Hold locks for as short a time as you can, and never hold one across I/O such as an HTTP call. A lock held for 2 seconds of network wait turns your server into a single-file queue.

Atomic operations do a read-modify-write as one indivisible step: AtomicInteger.incrementAndGet() in Java, Atomics.add in JavaScript, UPDATE ... SET n = n + 1 in SQL, INCR in Redis. Prefer them to a lock when the whole critical section is one counter or flag.

Immutable messages remove the problem rather than guard it. If tasks only exchange frozen values, no one can see a half-written object.

Queues (queue.Queue for threads, asyncio.Queue for coroutines) are thread-safe hand-off points. The producer puts, the consumer gets, and the queue does the locking for you. A bounded queue (maxsize=100) also gives you backpressure: when consumers fall behind, producers block instead of filling memory.

Semaphores allow up to N holders at once. Use one to cap concurrent calls to a rate-limited partner API, or connections to a database. The mechanics in asyncio are in Asyncio in Depth.

Deadlock, livelock, starvation

A deadlock is a cycle of waiting: each task holds something the next one needs. The textbook case is two transfers running in opposite directions.

Two transfers, opposite directions
Transfer A to BLock ALock BTransfer B to Aacquireacquireacquire (waits)acquire (waits)fix: lock lower ID first

The first transfer locks account A, the account it debits.

1/5

Deadlock needs all four Coffman conditions at once:

  1. Mutual exclusion: a resource can be held by only one task.
  2. Hold and wait: a task holds one resource while waiting for another.
  3. No preemption: nobody can take a resource away from its holder.
  4. Circular wait: there is a cycle of tasks each waiting on the next.

Break any one and deadlock is impossible. In practice you break circular wait with a global lock order (always lock accounts in ID order, always lock tables in the same order inside transactions), and you limit the damage of no preemption with timeouts: lock.acquire(timeout=2), Postgres lock_timeout, then fail or retry. Databases detect deadlocks for you and kill one transaction with an error, so your code must be ready to retry it.

Livelock is deadlock's busy cousin: tasks keep reacting to each other and make no progress, like two people stepping aside in a corridor in the same direction forever. Retries without jitter cause it. Add randomised backoff. Starvation is when one task never gets its turn because others keep winning: a writer that never gets a lock because readers keep arriving, or a low-priority job that is always pre-empted. Fair locks and queues with ordering fix it.

Patterns that keep you out of trouble

The best concurrent code has very little shared mutable state. These patterns are how teams get there.

  • Producer-consumer. Producers put work on a bounded queue, consumers take it off. Neither knows about the other. This is the in-process version of a message broker.
  • Worker pool. A fixed number of workers pull from one queue. The pool size caps concurrency, so a burst of 10,000 jobs uses 8 workers, not 10,000 threads. ThreadPoolExecutor and ProcessPoolExecutor are ready-made pools.
  • Fan-out / fan-in. Split a job into independent parts, run them concurrently, then combine the results. Rendering 40 thumbnails, or calling 5 services for one page.
  • Pipeline. Stages connected by queues, each stage with its own workers: download, then parse, then store. A slow stage shows up as a growing queue in front of it, which tells you where to add workers.
  • Scatter-gather with a deadline. Ask several sources, wait up to a time limit, use whatever arrived, cancel the rest. A price comparison page that shows 9 of 10 suppliers beats one that waits forever on the tenth.
  • Actor model. Each entity (an account, a game room, a device) gets one mailbox and processes its messages one at a time. No locks, because only the actor touches its own state.
  • Single writer. Only one task ever writes a piece of state; everyone else sends it requests. It is the actor idea applied to a hot resource, and it is how high-throughput systems such as the LMAX exchange avoid lock contention.
A pipeline with fan-out and fan-in
Upload eventsUpload eventsBounded queue: maxsize 100Bounded queuemaxsize 100Resize worker 1Resize worker 1Resize worker 2Resize worker 2Resize worker 3Resize worker 3Results queueResults queueSingle writer: saves to DBSingle writersaves to DBputgetgetgetget

Producers put jobs on a bounded queue. When it is full, they block. That is backpressure, and it keeps memory flat during a burst.

1/4

Here is the actor idea in JavaScript. The racy version has an await between check and act, so two reservations both succeed on one item. The actor chains every message onto the previous one, so they run strictly in order.

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // A fake database call: reading takes a little while.const db = { stock: 1 };async function readStock() { await sleep(5); return db.stock; }async function writeStock(n) { await sleep(5); db.stock = n; } // Racy: check-then-act with an await in the middle.async function reserveRacy(user) { const stock = await readStock(); if (stock < 1) return `${user}: sold out`; await writeStock(stock - 1); return `${user}: reserved`;} // Actor: one mailbox per entity. Messages run one at a time, in order.function createActor(handle) { let tail = Promise.resolve(); return { send(msg) { const result = tail.then(() => handle(msg)); tail = result.catch(() => {}); // a failed message must not jam the mailbox return result; }, };} async function main() { console.log(await Promise.all([reserveRacy("ana"), reserveRacy("ben")]), "stock:", db.stock); db.stock = 1; const item = createActor(reserveRacy); console.log(await Promise.all([item.send("ana"), item.send("ben")]), "stock:", db.stock);} main();
Output
Press Run (⌘ Enter) to see what happens.

This only serialises messages inside one process. Across many servers, the same idea needs a partitioned queue (all messages for one key go to one consumer, as with Kafka partitions) or the database techniques above.

Match the pairs0/5 matched

Match each situation to the pattern that fits it best.

Choose an item, then its match on the other side.

Python and JavaScript in 2026

Python. CPython's standard build still has the GIL (global interpreter lock): only one thread runs Python bytecode at a time. Threads still help with I/O, because the GIL is released while a thread waits on a socket or file. They do not speed up pure-Python CPU work. The GIL does not make your code thread-safe: count += 1 is several bytecodes, and a switch can happen between them.

The free-threaded build (no GIL) has been officially supported since Python 3.14 under PEP 779, but it is a separate build (python3.14t), not the default. Some C extensions are not yet ready for it, and single-threaded code runs a little slower. Check the official docs and your dependencies before betting on it.

Your tools, by job:

  • asyncio with TaskGroup for many concurrent I/O waits in one thread (covered in Asyncio in Depth).
  • concurrent.futures.ThreadPoolExecutor for blocking I/O libraries you cannot make async.
  • concurrent.futures.ProcessPoolExecutor or multiprocessing for CPU-bound work. Each process has its own interpreter and GIL. Arguments and results are pickled, so send small messages, not huge objects.
  • Subinterpreters: Python 3.14 added concurrent.interpreters (PEP 734) and InterpreterPoolExecutor. Each interpreter is isolated, with its own GIL, inside one process. It is message passing without the cost of starting processes, and still young.

JavaScript. Your code runs on one thread with an event loop, as you saw in The Event Loop. For CPU work, use Web Workers in the browser or worker_threads in Node. Workers share nothing by default and talk with postMessage, which copies data: the message passing model. SharedArrayBuffer lets workers share raw memory, and Atomics gives you atomic reads, writes and Atomics.wait/notify on it. That is the shared memory model, with all of its risks, so reach for it only for measured hot paths.

Choosing a model

The work isUseWhy
I/O-bound, many waits (HTTP calls, DB queries)async, or a thread poolTasks spend their time waiting, so one thread can juggle thousands
I/O-bound, with a blocking libraryThread poolThe GIL is released during the wait
CPU-bound in PythonProcesses, or native code (NumPy, Rust, C)Bytecode does not run in parallel under the GIL
CPU-bound in JSWorker threadsKeeps the event loop free for requests
Shared state across serversThe database or a partitioned queueIn-process locks only cover one process
Quick check
A Python service increments a shared counter from 8 threads with counter += 1. Which statement is true on the standard CPython build?
Need a nudge? A hint rules out a wrong answer.
Quick check
Two background jobs lock rows in the orders and invoices tables and sometimes deadlock. Which change breaks the circular-wait condition?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

You suspect a race behind duplicate charges. Put these steps in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
race condition
A bug where the result depends on the timing of concurrent tasks, such as two requests interleaving between a read and a write.
critical section
Code that touches shared state and must run by one task at a time, usually guarded by a lock.
check-then-act
A race where a condition is checked, then acted on, and another task changes it in between.
deadlock
A cycle of tasks each waiting for a resource another holds. Prevented by a global lock order or timeouts.
backpressure
Slowing producers down when consumers fall behind, often with a bounded queue that blocks when full.
actor
An entity with private state and one mailbox that handles its messages one at a time, so it needs no locks.
GIL
CPython's global interpreter lock, which lets one thread run Python bytecode at a time in the standard build.