Skip to content
Tech Interview Prep
Technical interview guide

Concurrency (GIL, Threading, Asyncio)

Why Python threads don't parallelize CPU work, and the two real ways around it: multiprocessing and asyncio.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: Python 3.14, covering default GIL-enabled CPython and explicitly optional free-threaded builds.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain precisely what the GIL serializes and which application invariants it does not protect.

Answer

The 90-second answer. In a standard GIL-enabled CPython build, the GIL is one mutex per interpreter that a thread must hold to execute Python bytecode. It serializes bytecode execution, not your program's logic. It does not make x += 1 atomic, it does not protect check-then-act sequences, and it does not protect invariants that span more than one object. It does protect reference counts and the internal consistency of the built-in containers. If you need mutual exclusion for an application invariant, you still need a threading.Lock.

Mechanism. A thread holds the GIL and drops it every sys.getswitchinterval() seconds, 5 ms by default, so another thread can run. It also releases it around blocking I/O (file, socket) and inside C extensions that call Py_BEGIN_ALLOW_THREADS (numpy, hashlib, zlib, most DB drivers). A switch can land between any two bytecodes. That is the whole granularity: one bytecode.

Worked trace. counter += 1 on a global is not one bytecode. In CPython 3.12, dis.dis(bump) for

Python
counter = 0
def bump():
    global counter
    counter += 1

emits this sequence (offsets vary by version; the sequence is what matters):

#bytecodeeffect on stack
1LOAD_GLOBAL counterpush 0
2LOAD_CONST 1push 1
3BINARY_OP 13 (+=)pop 1 and 0, push 1
4STORE_GLOBAL counterpop 1, counter = 1

Four bytecodes, so a switch can land between any two. Two threads, counter starts at 0:

stepT1T2counter
1LOAD_GLOBAL → 00
2(switch)0
3LOAD_GLOBAL → 00
4LOAD_CONST 10
5BINARY_OP → 10
6STORE_GLOBAL 11
7LOAD_CONST 11
8BINARY_OP → 11
9STORE_GLOBAL 11

Final value 1, not 2. A lost update, with no exception and no warning.

Invariants the GIL does not protect.

  • Read-modify-write on shared state: counters, accumulators, total += row.amount.
  • Check-then-act (TOCTOU): if key not in cache: cache[key] = expensive(). Two threads both miss, both compute, one result is discarded. dict.setdefault is atomic; the surrounding pattern is not.
  • Multi-object invariants: a.balance -= x; b.balance += x. A concurrent reader can observe the money gone from both accounts.
  • Lazy initialization: if _client is None: _client = connect(). Two connections, one leaked.
  • Iteration while another thread mutates: RuntimeError: dictionary changed size during iteration.
  • Anything inside a C extension that released the GIL: numpy array writes, hashlib updates on a shared buffer.

What it does protect. Reference counts (Py_INCREF/Py_DECREF), so an object is not freed mid-use; the internal consistency of list, dict and set; and the atomicity of a single bytecode or a single non-releasing C call. d[k] = v is one STORE_SUBSCR; lst.append(x) is one C call that never drops the GIL: both are atomic. d[k] = d.get(k, 0) + 1 spans several bytecodes and is not.

Alternatives and when threads are wrong. CPU-bound work: threads give you roughly one core total, plus GIL convoy overhead from switching every 5 ms. Use multiprocessing or a C extension that releases the GIL. I/O-bound work: threads are fine, the GIL is released during the syscall. Many concurrent connections: asyncio avoids GIL contention entirely but needs async-aware libraries. Free-threaded CPython (PEP 703) shipped as an experimental --disable-gil build in 3.13 and a supported build in 3.14; it removes the GIL with per-object locks and biased reference counting, at a single-thread throughput cost.

Detection. Force the race: sys.setswitchinterval(1e-6) and run the stress test, asserting the invariant after every iteration. For free-threaded builds, run under ThreadSanitizer. A RuntimeError on dict iteration in production logs is the same class of bug already firing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Compare Events, Conditions, Semaphores, and queues for thread coordination.

Answer

Core answer (first 90 seconds)

All four coordinate threads, but each carries different state, and that state is the deciding question. Event carries one boolean. Condition carries an arbitrary predicate over state you own. Semaphore carries an integer count. queue.Queue carries a FIFO of items. Match the primitive to the state you're coordinating: a latch, a predicate, a permit count, or a handoff.

Assumptions: CPython 3.12, threading module, I/O-bound threads. Under the GIL none of these give CPU parallelism for pure-Python work; that's multiprocessing.

PrimitiveStateWaiter holds your lock?WakesReach for it when
Eventone boolnoall waiters, and every future wait() until clear()one-way latch: start, shutdown, "config loaded"
Conditionyour predicateyes: released in wait(), reacquired before returnone (notify) or all (notify_all)several waiters on a compound predicate you own
Semaphoreinteger counternoone per release()cap concurrency at N; count permits
queue.QueueFIFO + maxsizeinternal, not yoursone consumer per itemhand work to exactly one consumer

Mechanism and the trap. Condition.wait() releases the lock, blocks, and reacquires before returning. notify() only moves a waiter to the lock queue: it does not hand over the item. Between the notify and the waiter's reacquisition, a third thread can take the lock and consume the state, so the woken waiter must re-check. That's why the loop is mandatory:

Python
import threading
cond = threading.Condition()   # default lock is an RLock
items = []

def consumer():
    with cond:
        while not items:        # not `if` — re-check after every wake
            cond.wait()
        return items.pop(0)

def producer():
    with cond:
        items.append("job")
        cond.notify()

Trace: producer appends under the lock, calls notify(). Consumer wakes, reacquires the lock, re-evaluates while not items. If a second consumer already popped the item, items is empty and it waits again instead of raising IndexError. cond.wait_for(lambda: items, timeout=...) does this loop for you and returns the predicate's last value.

Semaphore, with a checkable output. BoundedSemaphore(2) admits at most two threads; release() beyond the initial count raises ValueError, which catches a missing acquire():

Python
import threading, time
sem = threading.BoundedSemaphore(2)
active = peak = 0
lock = threading.Lock()

def worker():
    global active, peak
    with sem:
        with lock:
            active += 1
            peak = max(peak, active)
        time.sleep(0.05)
        with lock:
            active -= 1

ts = [threading.Thread(target=worker) for _ in range(6)]
for t in ts: t.start()
for t in ts: t.join()
print(peak)   # 2

Six threads, two permits, 50 ms each: peak prints 2.

Failure modes. Event used as a counter: two items, one set(), both consumers wake and one starves. Event has no count. Condition lost wakeup: a consumer parked in wait() forever while items sit in the list; py-spy dump shows it in Condition.wait. Semaphore leak: a thread dies holding a permit and the pool drains to zero. BoundedSemaphore plus a timeout on acquire() surfaces it. Unbounded Queue() hides backpressure: the producer runs ahead and memory grows; set maxsize and handle queue.Full.

When not to. Don't use Condition when a Queue already gives you the handoff and the blocking get; don't use Event when you need to count; don't use Semaphore to protect a critical section: it has no ownership, so any thread can release() it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How does circular wait cause deadlocks in multi-threaded Python, and how does enforcing a strict lock hierarchy prevent it?

Answer

Core answer

Circular wait is the one Coffman condition you can actually remove in Python. Mutual exclusion is the point of a lock, hold-and-wait is what a critical section does, and CPython will not preempt a thread parked in acquire. But if every thread takes locks in the same global order, the wait-for graph is acyclic and no cycle can form.

Assumption: CPython with threading.Lock. The GIL does not save you. lock.acquire() releases the GIL while it blocks on the underlying OS primitive, so a blocked thread does not hold the interpreter: the other thread runs straight into its own block. Free-threaded builds behave the same way.

The deadlock, and what it looks like

Python
import threading, time

a, b = threading.Lock(), threading.Lock()

def worker(first, second, name):
    with first:
        print(f"{name} holds {first}")
        time.sleep(0.1)          # widen the window; without it this is a race
        with second:
            print(f"{name} got both")

t1 = threading.Thread(target=worker, args=(a, b, "T1"))
t2 = threading.Thread(target=worker, args=(b, a, "T2"))
t1.start(); t2.start()
t1.join(); t2.join()

Trace: T1 acquires a, prints, sleeps 100 ms. T2 acquires b, prints, sleeps 100 ms. T1 wakes and calls b.acquire(): blocked, b is held. T2 wakes and calls a.acquire(): blocked, a is held. The main thread is parked in t1.join(). Output is exactly two holds lines, no got both, and the process never exits. Both workers sit at 0% CPU inside _thread.lock.acquire.

Breaking it with a strict hierarchy

Give every lock an immutable rank at construction and acquire strictly in increasing rank. id() also works as a total order among live objects, but it is a memory address that can be reused after a lock is collected, so it is only safe if every lock outlives the process. A counter is safer:

Python
import itertools, threading
from contextlib import contextmanager, ExitStack

_rank = itertools.count()

class Account:
    def __init__(self, account_id, balance):
        self.account_id = account_id
        self.balance = balance
        self.lock = threading.Lock()
        self._rank = next(_rank)

@contextmanager
def locked(*accounts):
    with ExitStack() as stack:
        for acct in sorted(accounts, key=lambda x: x._rank):
            stack.enter_context(acct.lock)
        yield

def transfer(src, dst, amount):
    if src is dst:
        return                      # Lock is not reentrant: same lock twice self-deadlocks
    with locked(src, dst):
        if src.balance < amount:
            raise ValueError("insufficient funds")
        src.balance -= amount
        dst.balance += amount

Why it holds: if thread T waits on a lock held by U, then U holds that lock and any lock U waits on has a strictly higher rank. Rank increases along every wait-for edge, ranks are finite and distinct, so no cycle exists. The src is dst guard matters: sorted would hand the same lock to ExitStack twice and threading.Lock is not reentrant, so the thread would block on itself.

The rule has to be global. One code path that takes dst before src, or a library that takes its own locks inside your critical section, reintroduces the cycle.

Alternatives

StrategyMechanismTrade-off
Rank orderingSort locks by immutable rank before nestingNeeds every nested lock known up front; does not compose with third-party code that locks internally
One coarse lockA single mutex guards all transfersNo cycle possible; serializes every transfer, throughput collapses under concurrency
Try-and-backofflock.acquire(blocking=False); on False, release held locks, sleep jittered interval, retryLivelock under contention; the operation must be restartable with no partial state
Timeoutlock.acquire(timeout=1.0) returns False after 1 sConverts deadlock into an error, does not prevent it; with lock: has no timeout, so you must acquire and release explicitly

Detection

Symptoms are thread-pool starvation, health checks timing out, and workers at 0% CPU. faulthandler.dump_traceback_later(30, exit=True) at startup dumps every thread's stack after 30 s and exits: the standard production tripwire. faulthandler.register(signal.SIGUSR1) dumps on demand, and py-spy dump --pid <pid> reads stacks without stopping the process. The frames show threads parked in _thread.lock.acquire; the lock addresses in those frames identify the cycle.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you make a check-then-act invariant safe across current and free-threaded builds?

Answer

Core answer. The check-then-act was never atomic, in either build. The GIL only made individual bytecodes atomic; it never made a sequence of them atomic. Free-threading removes the accidental protection that came from long C calls holding the GIL, so the window between the check and the act becomes real parallel time on separate cores. The fix is to collapse the check and the act into one operation whose atomicity contract you can name: a single built-in call, a lock, or a storage primitive with a conditional write.

Why the GIL didn't save you. sys.getswitchinterval() defaults to 0.005 s, and the GIL is released between bytecodes and on blocking calls. if name not in seen: seen.add(name) compiles to a CONTAINS_OP for the check and a separate attribute-load/call sequence for the act: two bytecodes with a switch point between them. Two threads both see False and both add. The free-threaded build (PEP 703, python3.13t) has no GIL at all, so that window is wall-clock time rather than a 5 ms scheduling quantum.

Trace. Two threads, both claiming alice:

T1  CONTAINS_OP 'alice' in seen  -> False
    <switch, or genuine parallel execution>
T2  CONTAINS_OP 'alice' in seen  -> False
T2  seen.add('alice')            -> None   (claimed)
T1  seen.add('alice')            -> None   (claimed again)

Both callers return True. The "exactly one claim" invariant is broken.

Code.

Python
# CPython 3.13.0, default and free-threaded (python3.13t) builds
import threading

seen = set()
lock = threading.Lock()

def claim_broken(name):
    if name not in seen:      # check
        seen.add(name)        # act
        return True
    return False

def claim_locked(name):
    with lock:                # check and act share one critical section
        if name in seen:
            return False
        seen.add(name)
        return True

_claimed = {}
def claim_atomic(name):
    token = object()
    return _claimed.setdefault(name, token) is token

setdefault is a single C call: in the GIL build it holds the GIL for its duration, and the free-threaded build guards dict mutation with the dict's own lock, so the whole call is atomic with respect to other dict operations. The per-call token is what makes the return value meaningful: a shared sentinel would report a second claim as a first. Verify that on your build with the stress test below rather than trusting it.

Stress test. Eight threads, a threading.Barrier(8) to line them up, each calling claim_broken("alice") once:

Python
barrier = threading.Barrier(8)
results = []
def worker():
    barrier.wait()
    results.append(claim_broken("alice"))
threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads: t.start()
for t in threads: t.join()
print(sum(results))   # expect 1

Expect 1. The broken version prints more than 1 whenever two threads pass the check before either adds: 3 in one run on a 3.13.0 GIL build (illustrative; the count varies run to run). Swap in claim_locked or claim_atomic and it prints 1 every time.

Choosing between them.

approachatomic unitfree-threadedwrong when
threading.Lock around check+actthe with blockyeslock held across I/O or a callback; one global lock serializes unrelated keys
dict.setdefaultone C callyesthe invariant isn't expressible as one dict op
queue.Queue + single writerthe put/getyesyou need a synchronous answer; adds a hop and backpressure
DB UNIQUE / Redis SET NXthe store's writeyesthe store isn't the source of truth, or you need it in-process

Failure modes and detection. Duplicate claim: assert the count is 1. Lost update on counter[k] += 1, which is a read-modify-write and non-atomic in both builds: assert the final total equals the number of increments. Torn read of a compound object mutated in place: publish immutable snapshots instead. Run the stress test under both interpreters, python3.13 and python3.13t (or PYTHON_GIL=0 on a free-threaded build); sys._is_gil_enabled() tells you which mode you are actually in.

When not to reach for a lock. If the invariant spans processes, an in-process lock is decoration: the conditional write has to live in the store. If the critical section does I/O, a lock turns a race into a convoy; use a queue or a single-writer thread. If contention is per-key, a single global lock serializes unrelated keys: stripe the locks or lean on the dict's own atomicity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design a ThreadPoolExecutor workflow that cannot deadlock on internal future dependencies.

Answer

The 60-second answer. The deadlock is structural, not a tuning problem: a worker that blocks on a future whose task is queued behind it in the same pool can never be unblocked, because the only threads that could run that task are the ones already parked. So the design rule is one sentence: a blocking edge must never point back into the pool that owns the blocked thread. Enforce it by splitting executors along the blocking boundary and never calling get() on a future submitted to the executor you are currently running on.

The deadlock, traced. new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(100)). Submit 4 parents; each submits one child to the same executor and calls child.get().

steppoolSizeactiveCountqueuethread state
4 parents submitted440RUNNABLE
each submits a child444RUNNABLE
each calls get()444WAITING on FutureTask.get

The queue never fills (100 slots, 4 children), so nothing is rejected and nothing warns you. jstack shows 4 threads parked in LockSupport.park under FutureTask.get, activeCount == poolSize == 4, queue depth 4. That is the whole failure.

The workflow. Two executors, split by what the task does:

Java
// Java 17
ThreadPoolExecutor ioPool = new ThreadPoolExecutor(
    16, 16, 0L, TimeUnit.MILLISECONDS,
    new ArrayBlockingQueue<>(200),
    new ThreadPoolExecutor.CallerRunsPolicy());

ThreadPoolExecutor cpuPool = new ThreadPoolExecutor(
    8, 8, 0L, TimeUnit.MILLISECONDS,
    new ArrayBlockingQueue<>(200),
    new ThreadPoolExecutor.AbortPolicy());

Future<User> submitOrder(long id) {
    return ioPool.submit(() -> {
        User u = fetchUser(id);                              // I/O on ioPool
        Future<Score> s = cpuPool.submit(() -> score(u));    // CPU on cpuPool
        return new User(u, s.get(2, TimeUnit.SECONDS));      // bounded wait
    });
}

The blocking edge is ioPool → cpuPool. cpuPool tasks never submit back to ioPool, so the dependency graph is a DAG and no cycle can form. Re-run the trace: 4 parents park on ioPool, cpuPool has 8 free threads, children run, parents resume. activeCount is 4 on ioPool and 4 on cpuPool, never 4-and-0.

Trade-offs. Separate pools are simple and debuggable but double the thread count: each idle thread holds ~1 MB of stack, so 24 threads is ~24 MB reserved. CompletableFuture.thenComposeAsync on one executor removes blocking entirely (no thread is held while waiting) but makes queue bounds and back-pressure harder to reason about, and wraps failures in CompletionException. CallerRunsPolicy avoids queue-full rejection by running the task inline on the submitting thread (which also breaks the cycle, since the blocked worker runs its own child) but it can starve the pool and run I/O on the caller. ForkJoinPool with ManagedBlocker lets a joining thread help, but only for FJ tasks. If the dependency graph is genuinely cyclic, no pool layout fixes it; you need a different decomposition.

Failure modes and detection. cpuPool queue fills at 200 → AbortPolicy throws RejectedExecutionException inside the ioPool task, surfacing on the outer future; alert on rejection count. A score() that submits back to ioPool reintroduces the cycle: detect with a periodic jstack check for ioPool threads parked in get while cpuPool threads are also parked. The 2 s get timeout converts a stall into TimeoutException, but the cpuPool task keeps running unless you cancel(true) to interrupt it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design a bounded threaded client for a rate-limited blocking dependency.

Answer

Core answer (first 90 seconds)

Clarify two things before sizing anything: is the dependency's limit a hard quota that returns 429, or a budget we picked? And is its client library thread-safe? Assume a hard 50 rps quota, p50 40 ms, p99 300 ms, and a blocking client that is not thread-safe.

The design is four parts: a fixed pool of worker threads, a bounded queue in front of it, a token bucket in front of the dependency, and a per-call deadline carried into the socket timeout. The pool is sized for the tail, the bucket enforces the quota, the queue is the backpressure valve.

Sizing is Little's Law, L = λW. At 50 rps with p99 300 ms, L = 50 × 0.3 = 15 in flight. Sixteen workers covers the tail. More than sixteen buys nothing, because the bucket caps throughput at 50/s no matter how many threads are waiting on it.

Python
# Python 3.12
import queue, threading, time
from dataclasses import dataclass

class TokenBucket:
    """Thread-safe. acquire() returns False if the wait would pass deadline."""
    def __init__(self, rate_per_s: float, capacity: float):
        self.rate, self.capacity = rate_per_s, capacity
        self.tokens, self.ts = capacity, time.monotonic()
        self.lock = threading.Lock()

    def acquire(self, deadline: float) -> bool:
        while True:
            with self.lock:
                now = time.monotonic()
                self.tokens = min(self.capacity,
                                  self.tokens + (now - self.ts) * self.rate)
                self.ts = now
                if self.tokens >= 1.0:
                    self.tokens -= 1.0
                    return True
                wait = (1.0 - self.tokens) / self.rate
            if now + wait > deadline:
                return False
            time.sleep(min(wait, 0.005))

@dataclass
class Job:
    payload: bytes
    deadline: float
    out: "queue.Queue[object]"

def worker(bucket, q, stop, call):
    while not stop.is_set():
        try:
            job = q.get(timeout=0.1)
        except queue.Empty:
            continue
        try:
            if not bucket.acquire(job.deadline):
                job.out.put(TimeoutError("rate-limit wait past deadline"))
                continue
            remaining = job.deadline - time.monotonic()
            if remaining <= 0:
                job.out.put(TimeoutError("deadline passed before send"))
                continue
            job.out.put(call(job.payload, timeout=remaining))
        finally:
            q.task_done()

class BoundedClient:
    def __init__(self, call, workers=16, queue_size=200, rate=50.0, burst=50.0):
        self.q = queue.Queue(maxsize=queue_size)
        self.bucket = TokenBucket(rate, burst)
        self.stop = threading.Event()
        self.threads = [threading.Thread(target=worker, daemon=True,
                                         name=f"dep-{i}",
                                         args=(self.bucket, self.q, self.stop, call))
                        for i in range(workers)]
        for t in self.threads:
            t.start()

    def submit(self, payload: bytes, timeout_s: float) -> Job:
        job = Job(payload, time.monotonic() + timeout_s, queue.Queue(maxsize=1))
        self.q.put(job, timeout=timeout_s)   # raises queue.Full -> backpressure
        return job

    def close(self, drain_s: float = 5.0):
        self.stop.set()
        for t in self.threads:
            t.join(timeout=drain_s)

Trace of the bucket (capacity 50, rate 50/s, 16 workers, 40 ms calls):

ttokens after refillworkers that acquiretokens left
0 ms501634
40 ms361620
80 ms22166
120 ms880
160 ms220
180 ms110
200 ms110

Sixty acquisitions in 200 ms: 50 from the initial burst, 10 from refill (0.2 s × 50/s). Once the burst is spent the client settles at exactly 50 calls/s and the workers spend most of their time asleep in acquire. The bucket, not the pool, is the binding constraint.

Backpressure arithmetic. If arrivals run at 60/s against a 50/s service rate, the queue grows by 10/s; the 200-slot queue fills in 20 s, then submit raises queue.Full after the caller's timeout. That is the intended rejection, not a bug.

Failure modes

FailureDetectionCost
429 from the dependencycounter on status 429 vs. bucket ratewasted call; repeated 429s can extend a ban
queue saturationp99 of q.qsize(), rate of queue.Fullcallers rejected after waiting their full timeout
worker pinned by a call ignoring the socket timeoutper-worker last_start heartbeat; alert past 5× p99 (1.5 s)one of sixteen workers gone, 6% capacity, silently
deadline passed mid-flightcount of TimeoutError after senddependency may have processed it; needs an idempotency key

Alternatives. asyncio plus aiohttp holds thousands in flight on one thread, but a blocking C client lands in run_in_executor with the same pool. A process pool sidesteps the GIL for CPU-bound parsing at roughly 16 × 30 MB ≈ 480 MB RSS, versus threads sharing one heap. A single thread with retries caps at 1/0.04 = 25/s, half the quota. Unbounded threads are survivable on memory: 1000 threads is ~8 GB of reserved address space at the 8 MB default stack rlimit, mostly untouched, but they open 1000 connections to a dependency that allows 50/s, which is what actually triggers the ban.

Cancellation, honestly. Python threads cannot be killed. stop is checked between tasks; an in-flight blocking call is bounded only by the socket timeout you passed. Enforce the deadline at the socket, not in the pool. And if the client is not thread-safe, give each worker its own connection: requests.Session is not documented as thread-safe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How does free-threaded CPython remove the GIL, and what are the performance and thread-safety implications for pure-Python code vs C extensions?

Answer

The 90-second answer. Free-threaded CPython doesn't delete the GIL so much as remove the two jobs it was doing. Job one, serializing bytecode, is replaced by per-object locks taken through Py_BEGIN_CRITICAL_SECTION/Py_END_CRITICAL_SECTION, which now guard dicts, lists, module state and the import machinery. Job two, making reference counting safe without atomics, is replaced by biased reference counting: the thread that created an object owns a non-atomic local count, and only other threads pay for atomic operations on a shared count. Object allocation moves to mimalloc's per-thread heaps so alloc/free stops contending on one global lock. The GIL is still compiled into the binary and can be switched back on at runtime; sys._is_gil_enabled() tells you which mode you're in.

Assumptions: Python 3.14, where free-threading is a supported build (PEP 779) rather than the 3.13 experiment, via the python3.14t binary or a --disable-gil source build.

The biased refcount, traced on an object o created by thread A:

o created by A:   ob_ref_local=1, ob_ref_shared=0, owner=A
A: Py_INCREF(o)   ob_ref_local=2      plain add, no atomic
B: Py_INCREF(o)   ob_ref_shared=1     atomic add, B is not owner
A: Py_DECREF(o)   ob_ref_local=1
B: Py_DECREF(o)   ob_ref_shared=0
A: Py_DECREF(o)   local hits 0 -> A merges shared count, sees 0, frees

Pure Python. Individual operations on built-in containers stay internally consistent: d[k] = v, list.append(x), del d[k] take the container's lock, so they can't corrupt the object. What changes is everything between bytecodes. Under the GIL a thread switch only happens at a bytecode boundary and only every sys.getswitchinterval() (5 ms by default), so a check-then-act usually wins its race by luck. Free-threaded, two threads are genuinely inside the same window:

Python
# python3.14t
seen = {}
def register(k):
    if k not in seen:        # LOAD/COMPARE_OP
        seen[k] = k.upper()  # STORE_SUBSCR - a different bytecode

No lock spans those two bytecodes, so both threads can pass the test. The fix is what it always was: a threading.Lock, or seen.setdefault(k, k.upper()), which is one locked dict operation. The GIL was never a substitute for a lock; free-threading stops hiding that.

C extensions. This is where the real breakage is. An extension that mutates shared C state without a lock was correct only because the GIL serialized it. Now it races, and the failure mode is memory corruption or SIGSEGV, not a clean exception. Extensions must opt in:

C
static PyModuleDef_Slot slots[] = {
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},   /* multi-phase init */
    {0, NULL},
};

Single-phase modules call PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED) instead. If an imported extension hasn't declared this, the runtime re-enables the GIL for the whole process and emits a RuntimeWarning: one stale dependency silently costs you all the parallelism. The free-threaded build also has its own ABI tag (cp314t), so wheels must be built separately, and code that reads ob_refcnt or other struct internals directly must move to the accessor API.

Performance. PEP 703 targeted ≤10% single-threaded overhead. The 3.13 experimental build missed that badly, pyperformance's geometric mean came in around 40% slower, and 3.14 narrowed the gap, but the free-threaded build is still the slower one single-threaded. The cost is the biased-refcount slow path, immortal-object handling, and extra indirection in critical sections. Multi-threaded CPU-bound pure Python is the payoff: threads scale across cores without multiprocessing pickling or shared-memory plumbing. Scaling is not free, though: threads hammering one shared object contend on that object's lock and on its shared refcount, so a shared list taking 10 million appends will not scale linearly.

Default python3.14Free-threaded python3.14t
Bytecodeone thread at a timeconcurrent across cores
Refcountsingle ob_refcntob_ref_local (owner, non-atomic) + ob_ref_shared (atomic)
Containersserialized by the GILper-object locks / critical sections
Single-thread speedbaselineslower (PEP 703 target ≤10%; 3.13 shipped ~40%)
Extension ABIcp314cp314t, separate wheels
Un-opted-in extensionfineGIL re-enabled + RuntimeWarning

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Explain process isolation, IPC, and ownership of mutable state.

Answer

What a strong candidate says first

A process owns a private virtual address space. The kernel gives each process its own page tables, so a pointer valid in the parent is meaningless in the child. Everything else follows: to get state to another process you either copy it (pickle over a pipe, or fork's copy-on-write pages), map the same physical pages into both (shared memory), or put a proxy in front of it that performs a copy on every access (Manager). Mutable state should have exactly one owner; every other process sends it messages. I'll assume CPython 3.12 on Linux unless told otherwise.

Mechanism: fork, spawn, and why serialization is mandatory

fork clones the parent's address space with copy-on-write. The child shares physical pages until either side writes. CPython's reference counting writes to every object header it touches, so a large parent heap gets copied page by page as the child runs: a 2 GB parent can push the child's RSS toward 2 GB. spawn starts a fresh interpreter, re-imports __main__, and pickles the target and its arguments; nothing is inherited. macOS has defaulted to spawn since 3.8; Linux defaulted to fork through 3.13 and switched the default to forkserver in 3.14.

Serialization is not a style choice. Two address spaces have no shared pointers, so the only things that can cross are bytes (pickle, send/recv on a Pipe), a file descriptor, or a mapping of the same physical pages (multiprocessing.shared_memory.SharedMemory, backed by /dev/shm on Linux).

Worked trace

Python
import multiprocessing as mp

def bump(lst):
    lst.append(1)
    print("child:", lst)

if __name__ == "__main__":
    ctx = mp.get_context("spawn")
    data = [0]
    p = ctx.Process(target=bump, args=(data,))
    p.start()
    p.join()
    print("parent:", data)

Step by step: spawn launches a fresh interpreter, re-imports __main__ (the if guard stops it from re-creating the process), pickles bump by qualified name and data as [0]. The child unpickles into its own list, appends 1, prints child: [0, 1]. The parent's data was never touched. Output:

child: [0, 1]
parent: [0]

Swap spawn for fork and the output is identical: copy-on-write is still a copy. That is the trap: people read "fork shares memory" and expect the append to show up in the parent.

Costs, order-of-magnitude on a typical Linux box

mechanismwhat crossesper-op costparent sees child's mutation?
fork argsCOW pages, no pickle~1–5 ms startno
spawn argspickled bytes~50–200 ms start (re-import)no
Queuepickle through a pipe + feeder thread~20–50 µs per small messageno
Manager().list()RPC over a socket per attribute access~30–100 µs per opyes
SharedMemory + numpyraw bytes, zero copy~1 µsyes

Failure modes and how you see them

Lost update. A child mutates a list passed as an argument; the parent's copy is unchanged. Detect with an assertion on the parent value after join(), not by eyeballing logs.

Queue join deadlock. The child puts more than the pipe buffer (64 KiB default on Linux) and the parent calls join() before draining. The feeder thread blocks on a full pipe, the child never exits, join() never returns. Detect with py-spy dump showing the feeder thread parked in write; fix by draining before joining.

Fork in a threaded parent. The child inherits locks held by threads that do not exist in it and deadlocks on first acquisition. Python 3.12 emits a DeprecationWarning for os.fork() in a multi-threaded process: treat it as a real signal.

Orphaned proxies. If the parent exits, a child touching a Manager proxy raises BrokenPipeError or ConnectionResetError rather than hanging. Catch it and fail the task.

Zombies. Unjoined processes accumulate; ps -o stat shows Z.

When isolation is worth it

CPU-bound work over ~10 ms per task with no shared mutable state: processes win, because the GIL serializes threads. IO-bound work: threads or asyncio in one process, since the copy cost buys nothing. High-rate shared mutable state: keep it in one process and redesign around message passing, or accept the Manager RPC cost. If tasks run under a millisecond, spawn startup dominates and a process pool is the wrong tool.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Compare spawn, fork, and forkserver from a library author's perspective.

Answer

What a strong candidate says first

A library never owns the start method: the application does. multiprocessing.set_start_method() is process-global and can only be called once; if your library calls it you either raise RuntimeError in an app that already set it, or you silently change that app's concurrency model. So the library rule is: call multiprocessing.get_context("spawn") (or whichever you need) and pass that context to every Pool, Process, Queue and Lock you create. Never read the default.

The defaults you must not assume, stated exactly:

  • Windows: spawn only. forkserver is not available there.
  • macOS: spawn since Python 3.8.
  • Linux: fork through 3.13; forkserver from 3.14.

So the same library code runs under a different method on each platform and, on Linux, changes behaviour between 3.13 and 3.14.

The three, side by side

availablechild starts fromparent globals visible?startup
forkPOSIXcopy-on-write copy of parentyes~1 ms
spawnallfresh interpreter, re-imports __main__notens–hundreds of ms
forkserverPOSIXfresh server, then forks from itno (server's state only)server once, then ~1 ms/child

Startup numbers are order-of-magnitude, not benchmarks.

What that means in code

Python
# library.py — checked against CPython 3.12
import multiprocessing as mp

def _double(x):
    return x * 2

def run(values):
    ctx = mp.get_context("spawn")      # explicit, not the default
    with ctx.Pool(processes=4) as pool:
        return pool.map(_double, values)
Python
# app.py
from library import run
if __name__ == "__main__":             # required for spawn/forkserver
    print(run([1, 2, 3]))

Trace the difference: under spawn the child re-imports library, so any module-level side effect (binding a socket, adding a log handler, reading config) runs again in every child. Under fork it does not, because the child is a memory copy. That single fact is the source of most "works on my Linux box, breaks on macOS" bugs.

Failure modes and how you see them

  • fork in a threaded process: only the forking thread is copied. A lock held by another thread at fork time stays locked forever in the child. Symptom: the child hangs on its first acquire(). Detect with faulthandler.dump_traceback_later(10) or py-spy dump on the stuck child. CPython 3.12+ raises DeprecationWarning when os.fork() is called from a multi-threaded process.
  • fork with inherited sockets or DB connections: parent and child share the same fd, so both write to one TCP connection. Symptom: garbled protocol frames, duplicated rows. Detect by asserting the child opens its own connection.
  • spawn with unpicklable arguments: a lambda, a local class, or an open file handle raises PicklingError at submit time, not in the worker.
  • forkserver with late parent state: children inherit the server's memory, not the parent's. A global set after the server started is invisible. Preload deliberately with set_forkserver_preload(["library"]).

When not to use each

Don't use fork in a library that may be imported into a threaded app: a web server or asyncio service is exactly that case. Don't use spawn when tasks are short and you're creating a process per task; the import cost dominates: keep a persistent pool. forkserver is the middle ground: pay the import once in the server, then fork cheaply, with no parent-state inheritance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Reduce serialization overhead in a process-based CPU pipeline.

Answer

Core answer. Before changing anything, measure where the time goes, because serialization is invisible if you only time the worker function. Wrap the whole pool.map call in time.perf_counter and compare it against a serial run and against the sum of per-task worker times. The gap is pickle, pipe transfer, and process startup. If that gap is more than ~20% of wall clock, serialization is your bottleneck and adding workers makes it worse.

The mechanism: multiprocessing pickles every argument and every return value, writes the bytes into a pipe, and the worker unpickles. Pickle protocol 5 can pass numpy buffers out-of-band, but it is still a full copy into the pipe and a full copy out. A Linux pipe moves roughly 1–3 GB/s, so an 80 MB array costs tens of milliseconds each way before any compute runs. If per-task compute is a few milliseconds, transfer dominates.

The fix depends on payload size: shrink the results, share the inputs, or drop processes entirely.

Python
# Python 3.12, Linux, default fork start method
import multiprocessing as mp
import numpy as np

def chunk_sum(a):                 # module scope -> picklable by reference
    return float(a.sum())         # scalar result, not the array

if __name__ == "__main__":
    data = np.arange(10_000_000, dtype=np.float64)   # 80 MB
    parts = np.array_split(data, 64)                 # 64 x 1.25 MB
    with mp.Pool(8) as pool:
        totals = pool.map(chunk_sum, parts, chunksize=8)
    print(sum(totals))

Trace: data is 10M float64 = 80 MB. array_split gives 64 parts of 156,250 elements = 1.25 MB each. pool.map pickles each part (1.25 MB) to a worker; the worker unpickles, sums, and returns a float. Argument bytes over the pipe total 80 MB; result bytes total 64 × ~30 B ≈ 2 KB. Returning the arrays instead would push another 80 MB back.

ApproachBytes over pipe per 80 MB jobWhen it wins
Return full arrays~160 MB (args + results)never for large arrays
Return scalars/indices~80 MB args, ~KB resultsresults are small
shared_memory input~KB (name + indices)read-only large inputs
Threads (numpy releases GIL)0work is in C, releases the GIL

For shared inputs, create one multiprocessing.shared_memory.SharedMemory, wrap it with np.ndarray(..., buffer=shm.buf), and pass only (shm.name, start, stop) to workers; each attaches with SharedMemory(name=...). No array copy crosses the pipe.

Trade-offs. chunksize=8 amortizes dispatch, but if tasks run for seconds, chunksize=1 with imap_unordered balances better: a straggler chunk of 8 delays the whole batch. shared_memory needs explicit shm.close() and shm.unlink() and leaks if a worker crashes; it is safe only when workers don't write concurrently. Threads avoid serialization entirely for numpy ufuncs, which release the GIL, but any Python-level loop holds it and threads stop scaling.

Failure modes. A lambda or nested function raises PicklingError at submit time: move it to module scope. The spawn start method (default on macOS/Windows, opt-in on Linux) re-imports the module, so a missing if __name__ == "__main__" guard raises RuntimeError or spawns recursively. A worker dying mid-transfer surfaces as BrokenPipeError in the parent. Memory: each worker holds its own unpickled copy, so 8 workers × 1.25 MB is fine, but 8 × 80 MB is 640 MB.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How should production code manage process-pool lifecycle and broken workers?

Answer

Run one long-lived ProcessPoolExecutor per service, sized to the CPU budget, and treat a broken pool as terminal: catch BrokenProcessPool, discard the executor, build a new one. Never retry into the dead executor.

On Python 3.11+:

Python
import os
from concurrent.futures import ProcessPoolExecutor, BrokenProcessPool

def _init_worker():
    import signal
    signal.signal(signal.SIGINT, signal.SIG_IGN)  # parent owns Ctrl-C

def build_pool():
    return ProcessPoolExecutor(
        max_workers=os.cpu_count(),   # 3.13: os.process_cpu_count()
        max_tasks_per_child=200,      # recycle workers; needs spawn/forkserver
        initializer=_init_worker,     # runs once per worker
    )

max_tasks_per_child is the leak valve: a worker that has handled 200 tasks is retired and replaced, so a slow C-extension leak or a fragmenting allocator can't grow unbounded. It requires mp_context to be None or spawn/forkserver: it is incompatible with the default fork on Linux.

Why a broken pool is terminal

Each worker is a separate process. The executor's management thread holds a sentinel for each worker and waits on it. When a worker dies abruptly (OOM killer, segfault in a C extension, os._exit) the sentinel fires. The management thread marks the executor broken and sets BrokenProcessPool on every pending future; already-completed futures keep their results. From then on the executor rejects new submissions. There is no repair path: you cannot restart the dead worker in place.

Python
def submit_all(pool, items):
    try:
        return list(pool.map(work, items, chunksize=64))
    except BrokenProcessPool:
        pool.shutdown(wait=False, cancel_futures=True)
        raise  # caller rebuilds

Detection

BrokenProcessPool is the signal, and it subclasses RuntimeError, so a bare except Exception around your submit swallows it and you retry into a dead pool forever. Catch it explicitly. Log the worker exit code: -9 means the OOM killer, which is a sizing problem, not a code bug.

Shutdown

shutdown(wait=True, cancel_futures=True) (cancel_futures is 3.9+) on the way down. wait=True blocks until running tasks finish; if a task can hang, bound it with a per-task timeout inside the worker, because shutdown has no timeout of its own.

Alternatives

ApproachWhen it winsCost
One long-lived pool, rebuild on breakSteady CPU work, cheap per-task setupA break loses all in-flight tasks
New pool per batchTasks are rare and setup is cheapProcess spawn ~10–50 ms each; kills throughput
External supervisor (separate worker service)You need isolation from the web process and independent scalingAnother deploy, another queue

Deciding criterion: how expensive is a lost batch? If a broken pool costs a 30-second batch, rebuild. If it costs an hour of work, checkpoint and use a supervisor.

Failure modes

  • Worker OOM-killed → BrokenProcessPool on pending futures; detect via exit code, fix by lowering max_workers or chunksize.
  • Initializer raises → every worker fails at startup; the first submit raises BrokenProcessPool immediately. Test the initializer in isolation.
  • Fork plus threads → a forked child inherits a copy of the executor whose management thread does not exist; submitting from inside a worker is undefined. Use spawn if workers need to touch the pool.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Choose an execution model for CPU-bound pure-Python work and defend it.

Answer

Short answer. For CPU-bound pure-Python work on a GIL-enabled CPython, use processes (concurrent.futures.ProcessPoolExecutor), not threads. Threads give you concurrency but not parallelism: the GIL lets exactly one thread execute Python bytecode at a time. Processes each carry their own interpreter and GIL, so N processes use N cores. The alternatives: a free-threaded build (PEP 703, --disable-gil, Python 3.13+) or pushing the hot loop into a GIL-releasing C extension: are real but carry their own costs.

Why threads don't help. CPython's GIL is held by the thread running bytecode and released every sys.getswitchinterval() seconds (default 0.005, i.e. 5 ms) so other threads can run. That switch is a scheduling event, not parallelism: with 4 CPU-bound threads on 4 cores, total bytecode throughput is roughly that of one core, plus context-switch overhead. Threads do parallelize when the work sits inside a C call that releases the GIL (numpy ufuncs, hashlib, zlib, socket I/O) which is why "threads don't scale" is wrong as a blanket statement and right for pure-Python loops.

Worked check. CPython 3.12, GIL enabled, 4 physical cores. Timings are illustrative, not measured here.

Python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def burn(n):
    total = 0
    for i in range(n):
        total += i * i
    return total

N = 20_000_000

t0 = time.perf_counter(); burn(N); t1 = time.perf_counter()
print(f"serial  {t1-t0:.2f}s")

with ThreadPoolExecutor(4) as ex:
    t0 = time.perf_counter(); list(ex.map(burn, [N//4]*4)); t1 = time.perf_counter()
print(f"threads {t1-t0:.2f}s")

with ProcessPoolExecutor(4) as ex:
    t0 = time.perf_counter(); list(ex.map(burn, [N//4]*4)); t1 = time.perf_counter()
print(f"procs   {t1-t0:.2f}s")

Illustrative output:

serial  1.20s
threads 1.25s
procs   0.34s

Trace: burn is pure bytecode, so the four threads take turns on the GIL. Same total work, slightly worse wall time from switching. The four processes each run their own interpreter, so the four loops run on four cores and wall time drops to about a quarter. The arguments and results here are single ints, so pickling costs microseconds and is invisible.

Trade-offs. Process parallelism is not free. Every argument and return value is pickled and sent over a pipe; a round trip costs on the order of 0.1–1 ms depending on payload. Keep tasks at ≥10 ms of work or IPC dominates. Each worker is a full interpreter: budget 30–100 MB RSS per worker before your data, so 8 workers can add hundreds of MB. Startup is roughly 10–50 ms per worker on spawn. For large arrays, avoid pickling by putting them in multiprocessing.shared_memory (3.8+) and passing names. Don't reach for processes when the task is small, when workers need shared mutable state, or when the hot loop is already in a GIL-releasing extension.

Failure modes.

  • TypeError: cannot pickle 'X' object at submit time when arguments are lambdas, open sockets, or DB connections. Fix: pass plain data, open connections inside the worker.
  • Memory blowup: N workers × per-interpreter RSS. Detected as OOM kills or swap thrash, not as an exception.
  • fork + threads: forking a process that holds a lock (logging, a thread pool) can deadlock the child. Python 3.12 emits a DeprecationWarning for this; 3.14 changes the Linux default start method to forkserver. Use multiprocessing.get_context("spawn") explicitly.
  • Free-threaded build: Python 3.13 ships --disable-gil as experimental; check sys._is_gil_enabled(). It carries a single-threaded slowdown and only helps if your C extensions are thread-safe.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Explain coroutine creation, task scheduling, and cooperative suspension.

Answer

Core answer. Three separate things happen at three separate times, and conflating them is the usual mistake.

Calling an async def function creates a coroutine object and runs nothing: the body executes only when something drives it. await drives an awaitable inline: the current coroutine steps into it and doesn't return until it finishes. asyncio.create_task(coro) wraps the coroutine in a Task, registers it with the running loop via call_soon, and returns immediately: the body still hasn't run. asyncio.run(main()) creates a fresh event loop, runs main as a Task, and closes the loop.

Scheduling is a single-threaded loop over a ready queue plus a timer heap. The loop pops ready callbacks, runs each to completion, then blocks in select/epoll/kqueue (IOCP on Windows) until the next timer or I/O readiness. There is no preemption: a callback runs until it returns.

Suspension is cooperative and happens at await. When a coroutine awaits a future that isn't done, its __await__ yields that future up to the Task's __step, which attaches a done-callback and returns control to the loop. When the future completes, the callback re-schedules __step via call_soon. asyncio.sleep(0) is the explicit "yield once": it reschedules through call_soon without a timer.

Worked trace.

Python
import asyncio

async def worker(name, delay):
    print(f"{name} start")
    await asyncio.sleep(delay)
    print(f"{name} done")

async def main():
    t = asyncio.create_task(worker("A", 0.1))
    await worker("B", 0.05)
    await t

asyncio.run(main())

Step by step:

  1. create_task schedules A.__step via call_soon; A's body has not run.
  2. await worker("B", 0.05) drives B inline: prints B start, hits sleep, schedules a timer at +0.05 s, yields. main suspends.
  3. Loop drains the ready queue: A.__step runs, prints A start, schedules a timer at +0.1 s, suspends.
  4. Loop blocks. At +0.05 s B's timer fires, B prints B done and returns; main resumes, await t finds t pending, suspends.
  5. At +0.1 s A's timer fires, A prints A done; Task A completes, its done-callback schedules main.__step; main returns and the loop stops.

Output:

B start
A start
B done
A done

Note B start precedes A start: B ran inline in main before the loop ever got to A's scheduled step.

Trade-offs. asyncio wins when you have thousands of concurrent I/O waits: a Task costs a coroutine frame plus a Future, far cheaper than a thread. Threads still work for I/O-bound blocking libraries because the GIL is released during I/O, but each thread costs ~8 MB of stack by default. CPU-bound work belongs in processes: loop.run_in_executor(None, fn) uses a ThreadPoolExecutor with max_workers = min(32, os.cpu_count() + 4) (Python 3.8+), which does not help pure-Python CPU work under the GIL. Use a ProcessPoolExecutor or a separate service. Don't reach for asyncio when the whole workload is CPU-bound or when every dependency is blocking with no async equivalent.

Failure modes.

  • Blocking the loop. time.sleep(1) or requests.get() inside a coroutine stalls every other task for that second. Detect with asyncio.run(main(), debug=True), which logs a warning when a callback exceeds loop.slow_callback_duration (default 0.1 s).
  • Cancellation that can't land. task.cancel() raises CancelledError at the next await; a coroutine that never awaits runs to completion regardless. A bare except: or except BaseException: swallows it.
  • Fire-and-forget tasks. create_task without holding a reference lets the task be garbage-collected mid-flight; keep them in a set and await or discard them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Protect a read-await-write invariant in a single-threaded event loop.

Answer

What I'd say first

Single-threaded means no preemption between bytecodes, but every await on something that actually suspends hands control back to the loop, and any other ready task can run to its next suspension before you resume. So a read-await-write sequence is not atomic; the invariant has to be enforced explicitly. The cheapest fix is to remove the await from the critical section. If you can't, serialize with an asyncio.Lock scoped to the resource, not the module.

The interleaving, concretely

Python
import asyncio

balance = 100

async def withdraw(amount):
    global balance
    current = balance            # read
    await asyncio.sleep(0)       # suspend: loop runs other tasks
    balance = current - amount   # write
    return balance

async def main():
    await asyncio.gather(withdraw(30), withdraw(30))
    print(balance)

asyncio.run(main())

Trace (Python 3.12): gather schedules both coroutines as tasks. Task A reads current = 100, hits sleep(0), which reschedules it at the back of the ready queue. Task B reads current = 100, also suspends. A resumes and writes 100 - 30 = 70. B resumes and writes 100 - 30 = 70. Output is 70; the correct value is 40. One update is lost, and nothing raised.

Wrapping the body in async with lock: where lock = asyncio.Lock() gives 70 then 40: B blocks on lock.acquire() until A releases, so B reads the post-write value.

Choosing between the options

ApproachUse whenWrong when
No await in the critical section (read, compute, write synchronously, await after)The new value depends only on local stateThe write must be conditional on remote state
asyncio.Lock per resourceThe critical section must span an awaitThe awaited call is slow: you serialize on its latency
Single-writer task + asyncio.Queue(maxsize=N)One owner of a connection/file, producers decoupled, backpressure wantedCallers need a per-request result: you must add a future per item
Compare-and-swap at the store (Redis WATCH/MULTI, UPDATE ... WHERE version = n)The store supports CAS and you want no lock across the awaitNo CAS available

The lock is the blunt instrument: if the awaited call inside it takes 20 ms, that resource tops out near 50 operations/s no matter how many tasks are ready.

Failure modes

  • Lock leak: await lock.acquire() without finally: lock.release(). A cancelled task leaves the lock held and every waiter blocks forever. async with releases on cancellation; manual acquire does not. Detect by dumping asyncio.all_tasks() and seeing many tasks parked in lock.acquire.
  • Deadlock: two locks taken in opposite orders across coroutines.
  • Lock held across a long await: p99 for that resource becomes the sum of queued critical sections; instrument lock wait time, since asyncio's slow-callback warning won't fire for a task that is simply waiting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Choose between `gather` and TaskGroup for several related calls.

Answer

Core answer (first 60–120 seconds).

Default to asyncio.TaskGroup (Python 3.11+) when the calls are one unit of work: if any fails, you want the rest stopped and a single error surfaced. Reach for asyncio.gather when you want an ordered list of per-call outcomes and can tolerate partial failure: that is what return_exceptions=True is for. The decision hinges on one thing: what happens to the siblings when one call raises.

What each actually does.

gather(*aws, return_exceptions=False) schedules all awaitables concurrently and returns results in input order: results[i] is aws[i], independent of completion order. With the default, the first exception propagates to the caller immediately and the other awaitables are not cancelled; they keep running to completion and their results are dropped. The one case where gather cancels siblings is when the gather call itself is cancelled. With return_exceptions=True, no exception propagates: each slot holds either the result or the exception instance, so you aggregate partial failures yourself.

TaskGroup is a context manager. tg.create_task(...) schedules each coroutine; if any child raises, the group cancels the remaining children, waits for them to finish cancelling, then raises an ExceptionGroup (handle with except*). If the async with body raises, the same cancellation happens. On exit it always joins every task, so nothing leaks.

Worked trace.

Python
import asyncio

async def fetch(name, delay, fail=False):
    await asyncio.sleep(delay)
    if fail:
        raise RuntimeError(name)
    return name

async def via_gather():
    return await asyncio.gather(
        fetch("a", 0.1),
        fetch("b", 0.2, fail=True),
        fetch("c", 0.3),
    )

async def via_taskgroup():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(fetch("a", 0.1))
        tg.create_task(fetch("b", 0.2, fail=True))
        tg.create_task(fetch("c", 0.3))

via_gather: all three start at t=0. "a" returns at 0.1. At 0.2 "b" raises RuntimeError("b"), which propagates out of via_gather at t≈0.2. "c" is still sleeping and is not cancelled: it runs to t=0.3 and its result is discarded. If the loop shuts down first you get Task was destroyed but it is pending!.

via_taskgroup: same start. At 0.2 "b" raises; the group cancels "c" mid-sleep, awaits its cancellation, then raises an ExceptionGroup containing RuntimeError("b"). Wall time ≈0.2s, and no task outlives the block.

Choosing.

  • All-or-fail, structured scope, no leaked work → TaskGroup. Cost: 3.11+, and callers must handle ExceptionGroup/except*.
  • Ordered aggregate with partial failure → gather(..., return_exceptions=True), then inspect each slot.
  • On 3.10 or earlier you only have gather (plus asyncio.wait); TaskGroup is not available.

Failure modes to watch.

  • gather default: sibling leak. Detect via pending-task warnings at loop close, or assert len(asyncio.all_tasks()) in tests.
  • gather with return_exceptions=True: a CancelledError in a slot is easy to miss; check isinstance(r, BaseException).
  • TaskGroup: an unhandled ExceptionGroup masks which child failed unless you read .exceptions.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Compare TaskGroup failure semantics with ad hoc task creation.

Answer

The 90-second answer

asyncio.TaskGroup (Python 3.11+) is a structured-concurrency scope: async with TaskGroup() as tg: owns every task created inside it. When a child raises a non-cancellation exception, the group cancels the remaining children, waits for them to finish cancelling, then raises an ExceptionGroup at scope exit. Ad hoc creation, asyncio.create_task or asyncio.gather, has no such scope. gather propagates the first exception but leaves the other tasks running; a bare create_task leaves them running and, if you drop the reference, the exception is never retrieved.

That is the whole comparison: TaskGroup makes sibling failure a coordinated event; ad hoc creation makes it a per-task event.

Mechanism

TaskGroup.__aexit__ does three things in order: wait for all children, cancel any still running if one failed, then collect non-cancellation exceptions into an ExceptionGroup. CancelledError is excluded: it inherits from BaseException since Python 3.8, so it is not swept into the group. If the async with body itself raises, remaining children are cancelled and the body exception propagates.

gather has no exit hook. With return_exceptions=False it re-raises the first exception the moment it arrives and abandons the rest. With return_exceptions=True it waits for all and returns a list mixing results and exceptions: no cancellation, no grouping.

Worked trace

Python
import asyncio

async def work(name, delay, fail=False):
    await asyncio.sleep(delay)
    if fail:
        raise ValueError(f"{name} failed")
    print(f"{name} done")
    return name

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(work("a", 0.1))
        tg.create_task(work("b", 0.2, fail=True))
        tg.create_task(work("c", 5.0))
    print("scope exited cleanly")

asyncio.run(main())

Step by step: at t≈0.1 a prints a done. At t≈0.2 b raises ValueError; the group cancels c, whose sleep(5.0) raises CancelledError and ends. The group waits for all children, then raises ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) wrapping the ValueError. scope exited cleanly never prints. Wall time ≈0.2s, not 5s.

Swap the body for await asyncio.gather(work("a",0.1), work("b",0.2,fail=True), work("c",5.0)): a done prints, ValueError propagates at t≈0.2, and c keeps sleeping until t≈5.0. Close the loop first and you get Task was destroyed but it is pending!.

Comparison

TaskGroup (3.11+)gatherbare create_task
cancels siblings on failureyesnono
error surfacingExceptionGroup at scope exitfirst exception, or list with return_exceptions=Trueloop handler, only if retrieved
lifetime bound to scopeyesnono
reference retentionheld by groupheld by gathercaller must keep it

When ad hoc is right

Fire-and-forget is correct when the task genuinely outlives the caller and you keep a reference plus a done-callback for errors: a metrics flush, a cache warm. gather(return_exceptions=True) is right when you want every result and will inspect failures yourself. TaskGroup is right when the children form one unit of work whose partial completion is meaningless.

Failure modes

A child that catches BaseException (or bare except:) swallows its own cancellation, so the group waits forever: detect with a scope timeout. gather with return_exceptions=False discards successful siblings' results when one fails; collect into a list if you need them. Nested groups produce nested ExceptionGroups: unwrap with except* (3.11+) or eg.subgroup(ValueError). A dropped create_task reference lets the task be garbage-collected mid-run, surfacing as Task exception was never retrieved at GC time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Write cancellation-safe coroutine cleanup without reporting false success.

Answer

task.cancel() doesn't stop anything by itself: it schedules a CancelledError to be raised inside the task at its next suspension point (or immediately if it's already suspended on an await). So cleanup is ordinary finally / async with code, with one rule: let CancelledError propagate. The bug this question is about is catching it and returning a value, which makes task.cancelled() report False and every caller waiting on cancellation (TaskGroup, asyncio.timeout, a shutdown barrier) believe the work finished.

Since Python 3.8 CancelledError inherits from BaseException, not Exception, so except Exception is safe; except BaseException and bare except: are the ones that swallow it.

Correct pattern

Python
import asyncio

async def worker(q, sink):
    try:
        while True:
            item = await q.get()
            await sink.write(item)
    finally:
        # A second cancel() can land while we're here, so shield the flush.
        flush = asyncio.ensure_future(sink.flush())
        try:
            await asyncio.shield(flush)
        except asyncio.CancelledError:
            await flush          # flush wasn't cancelled; let it finish
            raise                # then keep propagating

asyncio.shield(flush) protects the inner task from the cancellation aimed at worker; the outer await still raises CancelledError, so we catch it, wait for the shielded flush to actually complete, and re-raise. Cleanup finishes and the cancellation still reaches the caller.

Trace: the swallow bug

Python
async def bad():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        return "done"

async def main():
    t = asyncio.create_task(bad())
    await asyncio.sleep(0)      # let bad() reach the sleep
    t.cancel()
    print(await t, t.cancelled())

Step by step: bad() runs to await asyncio.sleep(10) and suspends. main yields at sleep(0). t.cancel() schedules CancelledError at that suspension. await t resumes bad, the error is raised inside sleep, the except catches it and returns "done". Output: done False. The task reported success.

Why that breaks the machinery

asyncio.timeout() (3.11+) only raises TimeoutError from __aexit__ when the CancelledError it injected actually propagates out. Swallow it and exc_type is None, so the timeout silently succeeds: the caller thinks the operation beat its deadline. TaskGroup.__aexit__ waits for children to finish; a child that returns normally after being cancelled is indistinguishable from one that completed, so the group reports success and the cancellation is lost.

Trade-offs

ApproachWhenCost
Let it propagateDefaultNone
asyncio.shield(inner)Cleanup must finishTask ignores its own cancel for the cleanup's duration
Task.uncancel() (3.11+)You deliberately handled a cancel and want TaskGroup/timeout to knowEasy to get wrong; only for fully understood suppression

Bound shielded cleanup with asyncio.wait_for(flush, 5): a 50 ms flush is fine to shield, a 30 s network drain is not, because the task now ignores cancellation for 30 s.

Failure modes

  • Cleanup that awaits without shielding gets cancelled a second time and never runs: detect by asserting the flush completed in tests that cancel twice.
  • except BaseException: pass around the whole body: grep for it; it turns every cancellation into false success.
  • Orphaned shielded tasks: if you shield and never await the inner task, it keeps running after the worker ends.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

When is shielding a bounded operation justified, and who owns the inner task?

Answer

What a strong candidate says first

Shielding is justified when the inner operation must reach a terminal state even if the caller is cancelled, and it is bounded, idempotent, and cheap enough to finish unsupervised. Typical cases: a commit or ack that must not be torn mid-flight, flushing a small buffer, releasing a lease. It is not justified for anything unbounded, retryable, or whose result the caller needs to act on: there, cancellation should propagate.

Ownership: asyncio.shield does not own the work. If you pass a coroutine, shield wraps it with ensure_future and creates the Task, but the returned future is your only handle on it. If the outer await is cancelled and you drop that future, you can neither observe the outcome nor keep the Task from being collected mid-execution. So the caller owns it: keep a strong reference, and decide where its result and exceptions go.

Mechanism

asyncio.shield(arg) returns a new Future that awaits arg. Cancelling the outer await cancels that wrapper future, so the caller sees CancelledError, but the inner Task is untouched and keeps running. If the inner itself raises or is cancelled directly, that propagates normally. Shield does not survive loop shutdown: asyncio.run cancels all remaining tasks at teardown, so a shielded commit can still be killed.

Worked trace (CPython 3.12)

Python
import asyncio

async def commit():
    print("commit: begin")
    await asyncio.sleep(0.1)
    print("commit: done")
    return "ok"

async def handler():
    inner = asyncio.ensure_future(commit())
    try:
        await asyncio.shield(inner)
    except asyncio.CancelledError:
        print("handler: saw CancelledError")
        raise
    finally:
        print("handler: inner done?", inner.done())

async def main():
    t = asyncio.ensure_future(handler())
    await asyncio.sleep(0.02)
    t.cancel()
    try:
        await t
    except asyncio.CancelledError:
        print("main: handler cancelled")
    await asyncio.sleep(0.2)
    print("main: exit")

asyncio.run(main())

Output:

commit: begin
handler: saw CancelledError
handler: inner done? False
main: handler cancelled
commit: done
main: exit

The handler is cancelled at 20 ms; the commit still prints done at 100 ms. inner.done() is False at cancellation: the work is genuinely detached, not finished.

Alternatives and when to pick them

  • Let cancellation propagate and retry from a durable record (outbox, job queue). Best when the operation is idempotent and the caller can be re-driven.
  • asyncio.TaskGroup (3.11+) for structured concurrency: children are cancelled with the parent. Correct when partial completion is worse than none.
  • A long-lived worker task you own, fed by a queue, with explicit ack. Correct when the work outlives any single request.

Deciding criteria: is the operation bounded and idempotent? Does the caller need the result? Is there a durable place to record intent? Bounded and idempotent, with no need for the result, is where shield is defensible.

Failure modes

  • Detached Task collected before completion: keep a strong reference.
  • Exception in the inner Task never retrieved, surfacing as "Task exception was never retrieved" at GC.
  • Loop shutdown cancels the shielded task anyway.
  • Unbounded inner work holds connections or leases past the request that spawned it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design supervision for background asyncio tasks.

Answer

Core answer. Assume Python 3.11+ (so TaskGroup and asyncio.timeout exist) and a long-lived loop: a service, not a script. Never leave a background task unreferenced. Either scope it with asyncio.TaskGroup so its lifetime is tied to a block, or keep it in a supervised collection that holds a strong reference, retrieves exceptions, and cancels on shutdown. The deciding question is lifetime: work that must finish before the caller proceeds goes in a TaskGroup; work that outlives the request that spawned it goes in a supervised set with an explicit owner.

Mechanism. asyncio.create_task(coro) wraps the coroutine in a Task and schedules it on the running loop. The loop keeps only a weak reference to the task. The docs are explicit: "Save a reference to the result of this function, to avoid a task disappearing mid-execution." A task with no other reference can be garbage-collected before it finishes. The coroutine just stops, with no exception and no log.

Two consequences follow. Exceptions: a task that raises stores the exception on the Task object. It is raised into an awaiting caller, or logged as "Task exception was never retrieved" when the task is GC'd. If you never await it and never call task.exception(), the failure is silent until GC. Cancellation: task.cancel() schedules a CancelledError (a BaseException since 3.8) at the next await point. Code that catches bare except: or except Exception won't see it; code that swallows CancelledError breaks cancellation.

Options and when each is wrong.

patternlifetimeon child failurewhen it's wrong
asyncio.TaskGroup (3.11+)block-scopedcancels siblings, raises ExceptionGroupwork must outlive the block
supervised set + done-callbackowner-scopedretrieved and logged per taskyou need all-or-nothing semantics
asyncio.gathercaller-scopedfirst exception propagates, siblings keep runningyou assumed it cancels siblings: it doesn't

gather is the common trap: with the default return_exceptions=False it raises the first exception but leaves the other tasks running, so you leak work.

Code.

Python
import asyncio, logging

log = logging.getLogger(__name__)

class Supervisor:
    def __init__(self) -> None:
        self._tasks: set[asyncio.Task] = set()

    def spawn(self, coro) -> asyncio.Task:
        task = asyncio.create_task(coro)
        self._tasks.add(task)                 # strong ref: survives GC
        task.add_done_callback(self._done)
        return task

    def _done(self, task: asyncio.Task) -> None:
        self._tasks.discard(task)
        if not task.cancelled() and (exc := task.exception()) is not None:
            log.error("background task failed", exc_info=exc)  # marks retrieved

    async def aclose(self) -> None:
        for t in self._tasks:
            t.cancel()
        await asyncio.gather(*self._tasks, return_exceptions=True)

Trace: spawn adds a strong reference and a done-callback. When the task finishes, _done runs, discards it from the set, and calls task.exception(), which both retrieves the exception (suppressing the "never retrieved" log) and lets you route it to your error path. aclose cancels everything still running and awaits it with return_exceptions=True so one failure doesn't abort the shutdown sweep.

Failure modes and detection.

  • Silent GC of an unreferenced task: symptom is a coroutine that stops mid-way with no traceback. Detect by keeping the reference; asyncio.all_tasks() shows what's still live.
  • Swallowed exception: symptom is a job that never completes its side effect. Detect with the done-callback above, or PYTHONASYNCIODEBUG=1.
  • Blocking the loop: a synchronous call inside a task stalls every other task. Debug mode logs a warning when a callback runs longer than loop.slow_callback_duration, default 0.1 s.
  • Unbounded spawn: a burst creates thousands of tasks. Bound with asyncio.Semaphore(n) or a fixed worker pool over an asyncio.Queue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Use `to_thread` without creating unbounded work or pretending cancellation stops the thread.

Answer

Core answer

asyncio.to_thread(func, *args) (Python 3.9+) submits func to the loop's default ThreadPoolExecutor and awaits a future. It buys you one thing: the event loop keeps running while a blocking callable blocks. It does not buy you a stop button, and it does not buy you CPU parallelism.

Two constraints decide the design:

  1. Bound the in-flight work yourself. The default executor is a ThreadPoolExecutor with max_workers = min(32, os.cpu_count() + 4): 8 on a 4-core box. Its work queue is unbounded. asyncio.gather(*(to_thread(f, x) for x in million_items)) enqueues a million callables; memory grows and every caller's latency grows with queue depth.
  2. Cancellation cancels the await, not the thread. task.cancel() cancels the asyncio future. The underlying concurrent.futures.Future.cancel() returns False once the callable has started, so the thread runs to completion. If that callable holds a DB connection or a file handle, you keep paying for it after the caller has moved on.

Why cancellation can't reach the thread

A thread has no safe interruption point. CPython can only deliver a signal to the main thread, and there is no mechanism to raise an exception inside an arbitrary running thread. to_thread therefore has nothing to call. The only stop is cooperative: the callable checks a flag you give it.

Python
import asyncio, threading, time

def chunked_work(n, stop: threading.Event):
    for i in range(n):
        if stop.is_set():
            return None          # cooperative exit
        time.sleep(0.01)
    return n

async def main():
    stop = threading.Event()
    task = asyncio.create_task(asyncio.to_thread(chunked_work, 1000, stop))
    await asyncio.sleep(0.05)
    task.cancel()
    stop.set()                   # this, not cancel(), ends the thread
    try:
        await task
    except asyncio.CancelledError:
        print("await cancelled; thread exited via stop flag")

Trace: chunked_work would run ~10 s. At 50 ms task.cancel() marks the await cancelled; stop.set() makes the next loop iteration return None. await task raises CancelledError and the print runs. Without stop.set(), the thread keeps sleeping for the full 10 s.

Bounding

Cap concurrency with a semaphore, or give the work its own executor:

Python
sem = asyncio.Semaphore(8)                 # matches default pool size

async def bounded(fn, *a):
    async with sem:
        return await asyncio.to_thread(fn, *a)

For a separate pool: loop.run_in_executor(ThreadPoolExecutor(max_workers=16), fn, *a). Size it to the downstream resource: a DB with 20 connections should not see 32 threads.

When not to use it

Pure-Python CPU loops get no parallel speedup on standard CPython builds: the GIL serialises bytecode, so to_thread just moves the work off the loop and back. Use ProcessPoolExecutor or a native library that releases the GIL (numpy, hashlib, zlib, most socket and file I/O). Free-threaded builds change this, but they are not the default and you should not assume them.

Failure modes and detection

  • Pool saturation. p99 climbs once in-flight calls exceed max_workers; the queue absorbs the rest. Detect with an in-flight gauge and queue depth; alert when depth is non-zero for more than a few seconds.
  • Abandoned work. After a cancel, thread count and held connections stay flat instead of dropping. Detect by comparing cancelled tasks to a thread-liveness gauge.
  • Context drift. to_thread copies the current contextvars context at call time; mutations inside the thread do not propagate back. Detect with a request-id assertion in the thread.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Manage subprocess pipes, cancellation, termination, and reaping under asyncio.

Answer

What a strong candidate says first

Cancelling the task that awaits a subprocess does not stop the process. await proc.wait() and await proc.communicate() are coroutines waiting on asyncio's child watcher; cancel them and the child keeps running: you have leaked a process. So every call site needs an explicit terminate/kill path, and you must drain stdout/stderr or you deadlock on a full pipe.

Assume POSIX, CPython 3.11, a child that can emit unbounded output.

Why it behaves this way

Deadlock. A Linux pipe holds 64 KiB. If the child writes more than that to stdout and the parent does await proc.wait() without reading, the child blocks in write(2) and the parent blocks in wait(2). Neither moves. communicate() avoids this by reading stdout and stderr concurrently with waiting for exit; it also writes input to stdin and closes it.

Cancellation. proc.wait() and proc.communicate() are ordinary coroutines. Cancelling them raises CancelledError in your task and sends nothing to the child. The child is reparented to init when your process exits; it is not killed. asyncio.wait_for(proc.wait(), t) therefore gives you a timeout on waiting, not on the process.

Reaping. asyncio's default child watcher calls waitpid in a thread and sets proc.returncode, so you do not accumulate zombies. You still observe completion by awaiting proc.wait().

Worked pattern

Python
import asyncio, os, signal

async def run(cmd, timeout=10.0, grace=2.0):
    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        start_new_session=True,          # child becomes its own group leader
    )
    try:
        out, err = await asyncio.wait_for(proc.communicate(), timeout)
        return proc.returncode, out, err
    except asyncio.TimeoutError:
        try:
            os.killpg(proc.pid, signal.SIGTERM)   # pgid == pid
        except ProcessLookupError:
            pass
        try:
            await asyncio.wait_for(proc.wait(), grace)
        except asyncio.TimeoutError:
            os.killpg(proc.pid, signal.SIGKILL)
            await proc.wait()
        raise

start_new_session=True makes the child a session and group leader, so os.killpg(proc.pid, ...) reaches the whole tree: the shell and everything it spawned. Without it you signal only the direct child and orphan its grandchildren.

Trade-offs

choiceuse whencost
communicate()output is boundedbuffers all output in memory
manual readline() loopstreaming or large outputyou own the drain; must read both pipes concurrently
create_subprocess_shellnever with untrusted inputshell injection
terminate() (SIGTERM)graceful stopchild may trap and ignore it
kill() (SIGKILL)after the grace windowno cleanup; orphans grandchildren unless you used a process group

Failure modes and detection

  • Deadlock: parent parked in wait(), child in write(). ps shows the child in S/D; the task never completes.
  • Leaked process: you cancelled the waiter and the child is still alive. proc.returncode is None and ps shows an orphan.
  • SIGTERM ignored: wait_for(proc.wait(), grace) times out → escalate to SIGKILL.
  • Shell injection: create_subprocess_shell(f"ls {user_input}"). Caught in review; use create_subprocess_exec with an argument list.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design deadline handling for a non-idempotent remote operation.

Answer

Core answer: A client deadline bounds how long you wait; it does not bound what the remote side did. For a non-idempotent operation, design the deadline as one part of a three-part contract: (1) a client-generated idempotency key that makes retries safe, (2) a server-side deadline shorter than the client's so the server returns a definitive failure before the client gives up, and (3) an outcome-resolution path (status lookup or same-key retry) plus reconciliation for the window where the response is lost. The trap is treating a timeout as proof that no side effect happened. It is not.

Mechanism: The request can be in three states when the client deadline fires: never reached the server, reached and aborted before commit, or committed with the response lost. Only the first two are safe to retry blindly. The third is the double-charge. An idempotency key turns the third into a lookup: the server stores key -> result in the same transaction as the side effect, so a retry with the same key returns the stored result instead of executing again. The server deadline is a target, not a guarantee: it should check the deadline before the commit point and return DEADLINE_EXCEEDED if exceeded. If the commit already happened, it returns success. If gRPC, use the built-in deadline; it propagates as grpc-timeout and surfaces DEADLINE_EXCEEDED. For HTTP, send a Stripe-style Idempotency-Key header and a server-side deadline header.

SettingValueWhy
client deadline2.0 sp99 charge latency 800 ms, 2.5x headroom
server deadline1.5 sserver aborts before client gives up
idempotency key TTL24 hcovers retry and reconciliation window
status poll100, 200, 400, 800 ms1.5 s total, avoids hammering
reconciliation scanevery 5 min, age > 10 minfinds PENDING/UNKNOWN
Python
import httpx, uuid, time

def charge(amount, key=None):
    key = key or str(uuid.uuid4())
    try:
        r = httpx.post("https://api.example.com/charge",
                       json={"amount": amount},
                       headers={"Idempotency-Key": key},
                       timeout=2.0)
        return r.json()
    except httpx.TimeoutException:
        for delay in (0.1, 0.2, 0.4, 0.8):
            time.sleep(delay)
            s = httpx.get(f"https://api.example.com/charge/{key}", timeout=1.0)
            if s.status_code == 200:
                return s.json()
            if s.status_code == 404:
                return charge(amount, key)
        raise RuntimeError("outcome unknown; reconcile")

Trace: client sends POST with key K at t=0.0. Server commits charge at t=1.4, writes K -> SUCCESS, sends response. Response is lost. Client raises TimeoutException at t=2.0. At t=2.1 the client GETs /charge/K and gets 200 {status: SUCCESS, charge_id: ch_123}. No second charge. If the server had aborted at t=1.5 before commit, the GET returns 404; the client retries POST with the same K and the server executes once. If the GET returns 202 IN_PROGRESS, the client polls 0.1, 0.2, 0.4, 0.8 s; if still pending, it raises and reconciliation scans for K.

Trade-offs: The idempotency store adds one write per operation and 24 h of storage. For low volume, a DB unique index is fine; for high volume, Redis with TTL. If the downstream already supports idempotency keys (Stripe, most payment APIs), use theirs. If the operation is naturally idempotent (PUT, set balance), skip the store and use a simple timeout plus retry. A saga or two-phase commit gives stronger atomicity across services but adds coordination latency and failure modes; use it only when the operation spans multiple non-idempotent systems.

Failure modes: Key store down -> fail closed with 503 and alert; do not retry blindly. Clock skew -> propagate remaining time, not absolute timestamps; gRPC does this. Reconciliation backlog -> monitor age of PENDING > 10 min; if the scan lags, unknown outcomes accumulate. Duplicate key collision -> use UUIDv4 or ULID; collision is negligible. The operational cost is one extra RTT on the timeout path and a background scan; the cost of not doing it is a double charge.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Size and operate an asyncio queue to enforce backpressure and clean shutdown.

Answer

What I'd say first. Assume one event loop, one process, producers that can be slowed (HTTP handlers, DB readers) and an I/O-bound consumer. Then: asyncio.Queue(maxsize=N) is the backpressure primitive. put() suspends the producer when the queue is full, so the slowdown propagates upstream instead of piling up in RAM. Size N from Little's law plus the burst you must absorb, and shut down with a sentinel per consumer rather than cancelling mid-item.

Mechanism. put() checks full(); if there's room it calls put_nowait() and returns without yielding. If full it parks the producer on a future in _putters and awaits. get() mirrors this with _getters. task_done() decrements _unfinished_tasks; join() awaits until that counter hits zero. The key point: get() removes the item but does not mark it done. The counter only drops when you call task_done(). That separation is what makes join() mean "all work finished", not "queue empty".

Python
import asyncio

async def producer(q):
    for i in range(5):
        await q.put(i)              # suspends here when q is full
        print(f"put {i} qsize={q.qsize()}")
    await q.put(None)               # one sentinel per consumer

async def consumer(q):
    while True:
        item = await q.get()
        try:
            if item is None:
                return
            await asyncio.sleep(0.01)   # stand-in for real work
            print(f"got {item} qsize={q.qsize()}")
        finally:
            q.task_done()               # runs even on cancel

async def main():
    q = asyncio.Queue(maxsize=2)
    await asyncio.gather(producer(q), consumer(q))
    await q.join()

asyncio.run(main())

Trace with maxsize=2 (checked against CPython 3.12): the producer puts 0 and 1 without yielding (queue not full), then blocks on put(2). The consumer gets 0, prints, sleeps. The producer resumes, puts 2, blocks on 3. Output:

put 0 qsize=1
put 1 qsize=2
got 0 qsize=1
put 2 qsize=2
got 1 qsize=1
put 3 qsize=2
got 2 qsize=1
put 4 qsize=2
got 3 qsize=1
put None qsize=2
got 4 qsize=1

qsize never exceeds 2: that is the backpressure. join() returns after the sixth task_done() (five items plus the sentinel).

Sizing. Little's law: in-flight L = λ × W. At λ=500 items/s and W=20 ms, L=10. Add the burst you must ride out: to absorb a 2 s stall, N ≈ 500 × 2 = 1000. Memory is bounded at N × item size: 1000 × 1 KB = 1 MB. An unbounded queue with producer 10k/s and consumer 5k/s grows 5k items/s, i.e. 5 MB/s at 1 KB, and p99 latency climbs with depth.

Trade-offs.

choicewhencost
bounded, await putproducer can be slowedbackpressure reaches the caller
bounded, put_nowait + catch QueueFullfirehose you can't slowyou must drop or sample
unboundednever in prodmemory and latency grow without bound

Failure modes. (1) Consumer cancelled between get() and task_done() → _unfinished_tasks never reaches zero → join() hangs forever; detect via q._unfinished_tasks > 0 after tasks exit, fix with task_done() in finally. (2) Producer cancelled while parked in put() → the item is silently dropped; detect by comparing produced vs consumed counts. (3) Sentinel shutdown with K consumers needs K sentinels, or cancel and drain. (4) asyncio.Queue is not thread-safe: cross-thread use corrupts _queue; use loop.call_soon_threadsafe or janus.

Shutdown. Push one None per consumer, await q.join(), then await asyncio.gather(*consumers). If you must cancel, cancel consumers first, then drain with get_nowait() until QueueEmpty, calling task_done() for each.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Separate synchronization across asyncio, thread, and process domains.

Answer

Core answer

There are three synchronization domains, and a primitive only works inside the one that owns it.

  • asyncio: asyncio.Lock, Semaphore, Event, Condition, Queue. They coordinate coroutines on one event loop. They suspend the awaiting task and let the loop run other tasks; they never block a thread.
  • thread: threading.Lock, RLock, Semaphore, Event, queue.Queue. They coordinate OS threads inside one process. They block the calling thread.
  • process: multiprocessing.Lock, Queue, Manager().Lock(), shared_memory. They coordinate separate interpreters with separate address spaces.

The rule: an asyncio.Lock shared with a thread or a process protects nothing. It is bound to the loop that first used it, and its internals (_locked, the _waiters deque) are mutated with no thread lock around them.

Why asyncio primitives are loop-bound

Since 3.10 asyncio.Lock takes no loop argument. acquire() calls get_running_loop(), caches it in _loop, and raises on any later call from a different loop. Waking a waiter means future.set_result(), which must run on the loop thread; from another thread you need loop.call_soon_threadsafe. Calling loop.call_soon from a worker thread is not thread-safe and can drop the callback, so a waiter never wakes.

DomainPrimitiveProtectsCross-domain handoff
asyncioasyncio.Lockcoroutines on one looploop.call_soon_threadsafe, asyncio.run_coroutine_threadsafe, asyncio.to_thread
threadthreading.Lockthreads in one processqueue.Queue, concurrent.futures
processmultiprocessing.Lockprocessesinherited at fork, handle-duplicated at spawn

Worked trace

Python
import asyncio, threading

lock = asyncio.Lock()

async def main():
    async with lock:            # binds lock to the main loop
        await asyncio.sleep(0)

def worker():
    asyncio.run(lock.acquire()) # fresh loop in this thread

asyncio.run(main())
t = threading.Thread(target=worker); t.start(); t.join()
  1. asyncio.run(main()) creates loop L1 and runs main.
  2. async with lock calls acquire(); _get_loop() sees _loop is None, sets _loop = L1, sets _locked = True. await asyncio.sleep(0) yields, then __aexit__ releases.
  3. The thread runs asyncio.run(lock.acquire()), creating loop L2. _get_loop() finds the running loop is L2 but _loop is L1 and raises.

Output: RuntimeError: <asyncio.locks.Lock object at 0x...> is bound to a different event loop.

Trade-offs

Keep mutable state owned by the loop and pass plain data across the boundary: asyncio.Queue in, queue.Queue out. When a thread must touch loop state, use asyncio.run_coroutine_threadsafe(coro, loop) (returns a concurrent.futures.Future) or loop.call_soon_threadsafe. asyncio.to_thread (3.9+) runs a sync function on the default ThreadPoolExecutor, whose max_workers is min(32, os.cpu_count() + 4): size it for blocking I/O, not for CPU work. For CPU-bound work use ProcessPoolExecutor; multiprocessing.Lock is a POSIX semaphore on Linux, a named semaphore on macOS, a CreateSemaphore handle on Windows, and reaches a child only by fork inheritance or spawn handle duplication.

Failure modes

  • Lost wakeup. Two threads mutating _waiters can drop a set_result, so a task hangs forever. Detect with a watchdog timeout or by dumping asyncio.all_tasks().
  • Blocking the loop. threading.Lock.acquire() inside a coroutine stalls every task. Detect via loop.slow_callback_duration (default 0.1 s) warnings.
  • Unpicklable primitive. Passing threading.Lock or asyncio.Lock to a spawned child raises TypeError: cannot pickle '_thread.lock' object.
  • Stuck semaphore. A child killed while holding multiprocessing.Lock never releases it; there is no robust mutex by default. Detect with lock.acquire(timeout=...), which returns False instead of blocking forever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Select a concurrency model from workload, state-sharing, and failure-boundary requirements.

Answer

What I'd say first (60–120s)

Pin the workload before naming a model. Concrete case: a Python 3.12 HTTP service holding 10k concurrent connections, each waiting ~40 ms p99 on a downstream DB, a shared in-process LRU cache of 50k entries, and one CPU-bound step. Validating a 2 MB JSON body, ~15 ms of pure CPU. (Figures illustrative.)

That shape picks asyncio for connection handling plus a bounded process pool for the CPU step. The three requirements decide it: the workload is wait-dominated, so one event loop covers 10k sockets; the CPU step must not run on the loop; the cache is per-process state, so it stays in-process or moves to Redis if it must be shared.

Why, mechanically

CPython 3.12 still has the GIL: one thread runs bytecode at a time, so threads don't parallelize CPU work. asyncio is a single-threaded loop on one core: await yields at I/O, which is why 10k waiting sockets cost almost nothing. But a 15 ms CPU call inside a coroutine blocks every other task for those 15 ms.

Trace it:

Python
async def handle(req):
    data = await fetch(req)      # suspends; loop runs other tasks
    return heavy_parse(data)     # 15 ms pure CPU, no await

await asyncio.gather(*(handle(r) for r in range(10_000)))

gather schedules 10k tasks; each runs to await fetch and suspends. When one resumes, heavy_parse runs to completion before the loop touches another task. At 200 req/s the loop spends 200 × 15 ms = 3 s of every second in heavy_parse: it can't keep up, the ready queue grows, and p99 climbs by queue depth × 15 ms. Move it off the loop:

Python
await loop.run_in_executor(process_pool, heavy_parse, data)

The three axes

ModelParallel CPUShared mutable stateFailure boundary
asyncioNo: one coreIn-process, no locksOne loop crash kills all tasks
threadsNo: GILShared, needs locksA thread crash can corrupt shared state
processesYesNone by default; pickle/IPCProcess crash isolated

Defaults worth knowing: ThreadPoolExecutor uses min(32, os.cpu_count() + 4) workers; ProcessPoolExecutor uses os.cpu_count(). Go's GOMAXPROCS defaults to the CPU count; Node's loop is single-threaded with worker_threads for CPU.

Failure modes and detection

  • Blocking call on the loop: a sync DB driver or requests stalls all 10k connections. Detect with event-loop lag: asyncio's debug mode logs callbacks over 100 ms.
  • GIL contention: a C extension holding the GIL for 15 ms serializes threads. Detect with py-spy dump.
  • Process pool: pickling a 2 MB payload costs a few ms each way; a crashed worker raises BrokenProcessPool and kills the pool. Detect via pool-restart metrics.

Cancellation differs too: asyncio cancellation is cooperative. A task inside heavy_parse won't stop until it returns; killing a process is forceful. That's the failure-boundary requirement deciding the model.

Curated: · Written: · Reviewed:

Difficulty: Hard