Concurrency & Asynchronous Performance Questions
How concurrency choices change throughput, latency and resource use in server-side software. Covers sizing and choosing thread pools and executors for CPU-bound versus I/O-bound work, including bounded queues, rejection policies and work-stealing pools, event-loop behavior and what blocks it, offloading blocking calls, the GIL and process-versus-thread trade-offs, connection and worker pool limits and exhaustion under a slow dependency, lock contention and how to find it (perf, eBPF, flamegraphs), lock sharding and striping, lock convoys, spinning versus blocking and backoff, head-of-line blocking, request coalescing so concurrent callers share one fetch, scheduling pipeline stages across pools, and the coordination costs that cap parallel speedup. Focuses on the performance consequences of concurrency design rather than the correctness theory of synchronization or any one language's API. Primitives and deadlock theory, per-language concurrency APIs, async syntax and promise semantics, message-driven system design, and database isolation are covered elsewhere.
What is head-of-line blocking? Describe where it shows up in server software (a single event loop, a shared FIFO work queue, a multiplexed connection) and how you would stop one slow request from delaying fast ones.
Sample Answer
What head-of-line blocking is
Head-of-line (HOL) blocking is what happens when work waits behind the item at the front of a line that cannot move yet, even though the waiting work could be finished immediately if it were allowed to go first. The line is anything that is served in order: a queue, a single thread, a byte stream. The slow item at the head is the "head-of-line"; everything behind it inherits its delay. The cost lands on the fast requests, so tail latency (the slow end of the latency distribution) rises while the average barely moves. Tail latency is usually quoted as p99, the latency that 99 percent of requests beat (p50 is the median). A related name is the convoy effect: many short jobs trail one long job like cars behind a slow truck.
Where it appears in server software
- A single event loop. An event loop is one thread that runs every ready callback in turn, switching between requests only when a handler waits (
await). A handler that blocks (a synchronous library call, a big JSON parse, a long loop) never yields, so every other connection served by that loop is the line behind it. - A shared FIFO work queue. A thread pool (a fixed set of reusable worker threads) pulls jobs from one first-in-first-out queue. If all workers are busy with slow jobs, a 10 ms job queues behind them. The effect grows when slow jobs are a small share of arrivals but a large share of the work.
- A multiplexed connection. Multiplexing means sending many requests over one connection. In short: HTTP/2 removes the blocking at the HTTP layer, but the TCP connection underneath still delivers bytes strictly in order, so one lost packet holds up every stream; HTTP/3 removes that too. In HTTP/1.1 a connection carries one response at a time, in request order, so one slow response delays the ones behind it on that connection (the introduction of RFC 9113 describes pipelined HTTP/1.1 as still suffering from application-layer head-of-line blocking). HTTP/2 gives each request its own stream, which removes that application-level blocking. It does not remove it at the transport: the same introduction notes that TCP head-of-line blocking is not addressed by HTTP/2, and RFC 9114 section 1.1 explains why: TCP's loss recovery cannot see the streams, so one lost packet stalls all active transactions on that connection. HTTP/3 runs over QUIC (a transport protocol built on UDP, which has no ordering of its own), which provides reliability per stream, so a lost packet stalls only the streams whose data it carried (RFC 9114 section 1.2).
Reproducing it: a slow handler on one event loop
The program below sends a fast request every 10 ms for 600 ms. At the sixth tick one slow request arrives. In the first run its handler blocks the loop (time.sleep). In the second it is moved to a worker thread with asyncio.to_thread. A second part simulates a shared queue (random arrivals, seed 7, 2% of jobs take 400 ms and 98% take 10 ms) with a plain event-driven calculation, so its numbers are deterministic.
import asyncio, heapq, random, time
# ---- Part 1: one slow handler on a single event loop ----
async def fast_handler(arrived, results):
await asyncio.sleep(0.001) # pretend 1 ms of non-blocking I/O
results.append(time.perf_counter() - arrived)
async def slow_blocking():
time.sleep(0.300) # blocking call: nothing else on the loop runs
async def slow_offloaded():
await asyncio.to_thread(time.sleep, 0.300) # runs on a worker thread, loop stays free
async def run(slow):
results, tasks = [], []
async def arrivals():
for i in range(60): # one fast request every 10 ms for 600 ms
if i == 5:
tasks.append(asyncio.create_task(slow()))
tasks.append(asyncio.create_task(fast_handler(time.perf_counter(), results)))
await asyncio.sleep(0.010)
await arrivals()
await asyncio.gather(*tasks)
results.sort()
return results
async def part1():
for name, slow in (("blocking call on the loop", slow_blocking), ("offloaded to a thread", slow_offloaded)):
r = await run(slow)
print("%-26s fast requests=%d median=%6.1f ms worst=%6.1f ms" % (name, len(r), r[len(r)//2]*1000, r[-1]*1000))
# ---- Part 2: shared FIFO queue vs separate pools (deterministic simulation, seed 7) ----
def simulate(jobs, workers_for):
"""jobs: list of (arrival_s, service_s, kind). workers_for(kind) -> pool id. Pools: dict id -> worker count."""
pools, pool_of = workers_for
free = {p: [0.0]*n for p, n in pools.items()} # next-free time of each worker
lat = {"fast": [], "slow": []}
for arr, svc, kind in jobs: # jobs already sorted by arrival, FIFO per pool
p = pool_of(kind)
heapq.heapify(free[p])
start = max(arr, heapq.heappop(free[p]))
heapq.heappush(free[p], start + svc)
lat[kind].append(start + svc - arr)
return lat
def pct(xs, q):
xs = sorted(xs); return xs[min(len(xs)-1, int(q*len(xs)))]
def part2():
rnd = random.Random(7)
t, jobs = 0.0, []
for _ in range(4000):
t += rnd.expovariate(60) # 60 requests/s on average
slow = rnd.random() < 0.02 # 2% slow
jobs.append((t, 0.400 if slow else 0.010, "slow" if slow else "fast"))
# offered work: 60 * (0.02*0.4 + 0.98*0.01) = 1.068 worker-seconds per second
layouts = {
"one shared FIFO, 3 workers ": ({"all": 3}, lambda k: "all"),
"fast pool 2 + slow pool 1 ": ({"fast": 2, "slow": 1}, lambda k: k),
}
for name, layout in layouts.items():
lat = simulate(jobs, layout)
print("%s fast p50=%6.1f ms p99=%7.1f ms slow p99=%7.1f ms" % (
name, pct(lat["fast"], .5)*1000, pct(lat["fast"], .99)*1000, pct(lat["slow"], .99)*1000))
print("offered load = %.3f worker-seconds per second" % (60*(0.02*0.4+0.98*0.01)))
if __name__ == "__main__":
asyncio.run(part1())
part2()
How simulate computes latency: free[p] is a heap holding the time each worker in pool p next becomes free, so heappop returns the worker that frees up first. A job starts at max(arrival, that time), meaning immediately if a worker is idle and otherwise when one frees up; that worker is then busy until start + service, which is pushed back on the heap; and the job's latency is start + service - arrival, its queue wait plus its own run time. Jobs are processed in arrival order, which is what makes each pool a FIFO queue. Arrivals use expovariate(60), random gaps averaging 1/60 s (about 60 requests per second), and the fixed seed 7 makes the same jobs appear every run. Tiny example with one worker: a 400 ms job arrives at 0.00 s and a 10 ms job at 0.01 s; the second starts at 0.40 s and its latency is 0.40 + 0.01 - 0.01 = 0.40 s, forty times its own run time.
Run in a python:3.12-slim container, it prints (the first two lines are timings and vary from run to run; the simulation lines are the same every run):
blocking call on the loop fast requests=60 median= 1.5 ms worst= 307.8 ms
offloaded to a thread fast requests=60 median= 1.5 ms worst= 4.0 ms
one shared FIFO, 3 workers fast p50= 10.0 ms p99= 187.6 ms slow p99= 715.4 ms
fast pool 2 + slow pool 1 fast p50= 10.0 ms p99= 18.7 ms slow p99= 1505.4 ms
offered load = 1.068 worker-seconds per second
Read it carefully. The median fast request is unaffected in both runs; only the worst case changes, from about the length of the blocking call (300 ms) to a few milliseconds. In the queue simulation, splitting 3 workers into 2 fast and 1 slow cut the fast p99 from 187.6 ms to 18.7 ms, and it did so at a price: the slow class now has one worker and its p99 doubled (715 ms to 1505 ms). Isolation moves the queueing to the class that can afford it; it does not create capacity. Total offered work is 1.068 worker-seconds per second on 3 workers (about 36% utilised), so the machine was not overloaded in either layout.
Stopping one slow request from delaying fast ones
Apply these in order of how much they usually buy (the first two are the main levers, the later ones refine them):
- Never block the loop. Move blocking or CPU-heavy work to a thread pool (
asyncio.to_thread, a Node worker thread) or a separate process. Confirm with a loop-lag measurement (how late a timer fires). - Separate pools per latency class. Give slow or unpredictable operations (reports, exports, calls to a flaky dependency) their own bounded pool and queue so they can only exhaust themselves. Size the fast pool for the fast work's rate times its latency (Little's law: requests in flight = arrival rate x time in system).
- Bound the queue and set timeouts. A request that has waited longer than its client will wait should be dropped, not processed. Bound the slow pool's queue and answer overflow with a fast 503 or 429.
- Prioritise or shard. A priority queue lets short or interactive jobs overtake, at the price of starving the low-priority class unless you cap its wait. Sharding (routing by key or by request type to separate queues) keeps one hot tenant from filling everyone's queue.
- Break the slow job up. Chunk a large job and re-enqueue between chunks, so the line moves.
- At the protocol layer, prefer HTTP/2 or HTTP/3 to HTTP/1.1 where clients and proxies support them, and keep several connections available to latency-critical traffic so a lost packet or a large response on one stream does not hold everything.
Recommendation and what would change it
Fix the one that is cheapest and cuts the tail most: take blocking calls off the loop, then split slow work into its own bounded pool with a timeout, and verify by watching fast-class p99 while injecting a slow request (as the program does). If the slow class is itself latency-sensitive, a split is the wrong tool and a priority queue with an aging rule is better.
Design the interface of a thread pool for a server that handles many short requests and occasional long-running tasks. How do tasks get submitted, how does the pool scale its workers, what are the queue and rejection policies, how does graceful shutdown work, and how do you keep long tasks from delaying short ones?
Sample Answer
The design in one paragraph
Give the server two lanes, each a fixed-size pool with a bounded queue, and make every caller say which lane a task belongs to: a SHORT lane for request-handling work and a LONG lane for occasional heavy work (exports, report generation). A full lane rejects immediately instead of queueing without limit, and the caller turns that into a fast error (for example HTTP 503 with a Retry-After header, which tells the client how long to wait before trying again). Shutdown stops intake, waits a deadline for running work, and then interrupts what is left (Java's Thread.interrupt() sets a flag and wakes a thread that is sleeping or blocked, which then sees an InterruptedException). The reason for two lanes is head-of-line blocking: in a single pool, a burst of slow tasks occupies every worker, and fast tasks wait behind them in the queue even though each fast task is cheap.
The public surface and the decisions behind it
A Future is a handle to a result that is still being computed (the caller can wait on it or cancel it), and a Callable is a task that returns a value or throws. AutoCloseable lets the pool be used in a try-with-resources block so close runs automatically. The program below implements these two methods and adds close:
interface RequestPool extends AutoCloseable {
<T> Future<T> submit(Lane lane, Callable<T> task) throws RejectedExecutionException; // never blocks the caller
boolean shutdown(long drainMillis) throws InterruptedException; // true if drained in time
}
| Question asked | Decision | Reason |
|---|---|---|
| How are tasks submitted? | submit(lane, task) returns a Future; the lane is part of the call | A pool cannot guess how long a task will run, and a guess that is wrong puts a slow task in the fast lane |
| How does the pool scale workers? | Fixed size per lane (core = max). Size each lane from its own workload with pool size = cores x (1 + wait/compute) for threads that mostly wait, and check with Little's law (threads in use = arrival rate x time in system) | See the note on the JDK's growth rule below |
| Queue policy | Bounded ArrayBlockingQueue per lane, length chosen as (latency budget / task time) x threads | Long queues just convert overload into latency. Worked example: the short lane has 4 threads and 5 ms tasks, so it clears 4 tasks per 5 ms; a 1.25 second queueing budget gives (1250 / 5) x 4 = 1000 slots, the size the program uses. The long lane has 2 threads and 300 ms tasks; a 3 second budget gives (3000 / 300) x 2 = 20 slots, the size the program uses |
| Rejection | Abort (throw), caller sheds the request with a fast error | Fail fast keeps tail latency bounded and lets clients back off |
| Graceful shutdown | shutdown() (stop accepting, let queued work finish) then awaitTermination(deadline) (block up to the deadline until workers are idle) then shutdownNow() (interrupt workers and drop the queue) | The documented two-phase pattern |
| Long tasks delaying short ones | Separate lane, with its own smaller thread budget | Isolation: the long lane can saturate and the short lane is unaffected |
How the JDK ThreadPoolExecutor decides to grow, from its Javadoc: with fewer than corePoolSize threads running it starts a new thread for each submit; at or above core it prefers to queue; only if the queue is full does it add threads, up to maximumPoolSize; and if the queue is full and the max is reached the task is rejected. So an unbounded queue means threads never exceed the core size and maximumPoolSize has no effect, and a pool with core below max grows only after its queue is full, meaning latency gets bad before capacity grows. Hence core = max with a bounded queue, and scaling decisions move to a slow outer loop (adjust the pool size from measured queue wait over minutes), not to per-request growth.
Rejection choices (from the Javadoc): AbortPolicy throws RejectedExecutionException (the default); CallerRunsPolicy runs the task on the submitting thread, which "provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted"; DiscardPolicy silently drops, only for work whose completion nobody relies on; DiscardOldestPolicy drops the head of the queue and the Javadoc calls it rarely acceptable. Recommendation: abort on the request path, because caller-runs would run a slow task on the thread that accepts network requests and stall all intake; caller-runs suits an internal batch producer that should slow down when the pool is full.
Run it: shared pool versus two lanes
The cost of lanes is a fixed split: with 4 short and 2 long threads, the 2 long threads sit idle when no heavy task is queued even if the short lane is saturated, and a heavy burst larger than 2 tasks waits in its own queue instead of borrowing idle short threads. That is the price of the guarantee. Both setups below have 6 threads in total. The load is 5 ms tasks every 4 ms, plus a burst of six 300 ms tasks each second for 6 seconds (the tasks sleep as stand-ins for waiting on downstream services, so the CPU count barely matters; with CPU-bound tasks the lane sizes would be set by cores). Latencies are reported as p50 and p99: percentiles meaning that half, and 99 percent, of the short tasks finished at or under that latency. Then the program tests shedding and the deadline shutdown.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class LanePool {
enum Lane { SHORT, LONG }
/** Two bounded lanes. A task is classified by the caller (Lane); each lane sheds when full. */
static final class RequestPool implements AutoCloseable {
private final ThreadPoolExecutor shortLane, longLane;
RequestPool(int shortThreads, int shortQueue, int longThreads, int longQueue) {
shortLane = lane("short", shortThreads, shortQueue);
longLane = lane("long", longThreads, longQueue);
}
private static ThreadPoolExecutor lane(String name, int threads, int queue) {
AtomicInteger n = new AtomicInteger();
// core == max, bounded queue: threads never grow, the queue never exceeds `queue`,
// and AbortPolicy rejects (the caller turns that into a fast 503) when both are full.
return new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(queue),
r -> new Thread(r, name + "-" + n.incrementAndGet()),
new ThreadPoolExecutor.AbortPolicy());
}
<T> Future<T> submit(Lane lane, Callable<T> task) throws RejectedExecutionException {
return (lane == Lane.SHORT ? shortLane : longLane).submit(task);
}
/** Two-phase shutdown with a deadline: stop intake, drain, then interrupt what is left. */
boolean shutdown(long drainMillis) throws InterruptedException {
shortLane.shutdown(); longLane.shutdown();
long end = System.nanoTime() + drainMillis * 1_000_000;
boolean clean = shortLane.awaitTermination(Math.max(0, (end - System.nanoTime()) / 1_000_000), TimeUnit.MILLISECONDS)
&& longLane.awaitTermination(Math.max(0, (end - System.nanoTime()) / 1_000_000), TimeUnit.MILLISECONDS);
if (!clean) { shortLane.shutdownNow(); longLane.shutdownNow(); }
return clean;
}
@Override public void close() throws InterruptedException { shutdown(1000); }
}
static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
/** 6 simulated seconds: short 5 ms tasks every 4 ms; every second a burst of 6 long (300 ms) tasks. */
static void scenario(String name, boolean split) throws Exception {
ExecutorService shared = split ? null : Executors.newFixedThreadPool(6);
RequestPool lanes = split ? new RequestPool(4, 1000, 2, 20) : null;
List<Long> lat = Collections.synchronizedList(new ArrayList<>());
long start = System.nanoTime(), nextBurst = 0;
int sent = 0;
while (System.nanoTime() - start < 6_000_000_000L) {
long el = (System.nanoTime() - start) / 1_000_000;
if (el >= nextBurst) {
nextBurst += 1000;
for (int i = 0; i < 6; i++) {
Callable<Void> longTask = () -> { sleep(300); return null; };
if (split) lanes.submit(Lane.LONG, longTask); else shared.submit(longTask);
}
}
long t0 = System.nanoTime();
Callable<Void> shortTask = () -> { sleep(5); lat.add((System.nanoTime() - t0) / 1_000); return null; };
if (split) lanes.submit(Lane.SHORT, shortTask); else shared.submit(shortTask);
sent++;
sleep(4);
}
if (split) lanes.shutdown(3000); else { shared.shutdown(); shared.awaitTermination(3, TimeUnit.SECONDS); }
long[] a = lat.stream().mapToLong(Long::longValue).sorted().toArray();
System.out.printf("%-26s short tasks %4d | latency ms: p50 %6.1f p99 %6.1f max %6.1f%n", name, a.length,
a[a.length / 2] / 1000.0, a[a.length * 99 / 100] / 1000.0, a[a.length - 1] / 1000.0);
}
public static void main(String[] args) throws Exception {
System.out.println("availableProcessors=" + Runtime.getRuntime().availableProcessors());
scenario("one shared pool (6)", false);
scenario("two lanes (4 short + 2 long)", true);
// Shedding: a full lane rejects at once instead of queueing without bound.
try (RequestPool p = new RequestPool(1, 2, 1, 1)) {
CountDownLatch hold = new CountDownLatch(1);
int accepted = 0, rejected = 0;
for (int i = 0; i < 10; i++) {
try { p.submit(Lane.SHORT, () -> { hold.await(); return null; }); accepted++; }
catch (RejectedExecutionException e) { rejected++; }
}
System.out.println("1 thread + queue of 2, 10 submits while blocked: accepted=" + accepted + " rejected=" + rejected);
hold.countDown();
}
// Shutdown with a deadline: a task that outlives the drain window is interrupted.
RequestPool p = new RequestPool(1, 2, 1, 1);
AtomicBoolean interrupted = new AtomicBoolean();
p.submit(Lane.LONG, () -> { try { Thread.sleep(10_000); } catch (InterruptedException e) { interrupted.set(true); } return null; });
sleep(100);
long t = System.nanoTime();
boolean clean = p.shutdown(500);
sleep(100);
System.out.printf("shutdown(500 ms): drained cleanly=%b, stuck task interrupted=%b, took %d ms%n",
clean, interrupted.get(), (System.nanoTime() - t) / 1_000_000 - 100);
}
}
Compiled and run in an eclipse-temurin:21-jdk container with java LanePool.java and --cpuset-cpus=0-7, one sample run printed (latency figures are host-dependent):
availableProcessors=8
one shared pool (6) short tasks 1335 | latency ms: p50 5.6 p99 297.4 max 307.3
two lanes (4 short + 2 long) short tasks 1338 | latency ms: p50 5.2 p99 7.0 max 22.2
1 thread + queue of 2, 10 submits while blocked: accepted=3 rejected=7
shutdown(500 ms): drained cleanly=false, stuck task interrupted=true, took 501 ms
The shape: the median short-task latency is the same in both setups (about the task time, 5 ms), but in the shared pool the 99th percentile jumps to about the long-task time (a burst of six 300 ms tasks takes all six workers, so a short task waits for one to finish). With two lanes the p99 stays near the task time. The same shape appears on 1, 2, 4 and 8 CPUs (shared p99 about 297 to 302 ms, lanes p99 about 6 to 10 ms, with the lanes' max anywhere from under 10 to about 60 ms, mostly scheduling noise); the accepted=3 rejected=7 line and the shutdown outcome do not vary. The r -> new Thread(r, name + "-" + n.incrementAndGet()) lambda in the program is a thread factory: the pool calls it to create each worker, and the AtomicInteger (a counter safe to increment from several threads) gives the workers names such as short-1, which make thread dumps and logs readable. The shedding test accepts 3 (one running plus two queued) and rejects the other 7, which is the bounded-queue rule working; the shutdown test shows shutdown() alone would have waited 10 seconds, while the deadline interrupts the stuck task after 500 ms. The printed 501 ms is the 500 ms drain window plus a little scheduling noise (it prints within a few milliseconds of 500): the program starts the clock, calls shutdown(500), sleeps 100 ms so the interrupted task can set its flag before it is read, then subtracts that 100 ms sleep from the elapsed time. Interruption only works if the task checks it: the JDK states shutdownNow makes best-effort attempts and typically uses Thread.interrupt(), so a task that ignores interrupts may never terminate; give long tasks interruption points and their own timeouts.
Keeping long tasks from delaying short ones, beyond lanes
- Classify by contract, then enforce it: record each task's run time and, if a SHORT task exceeds a budget (say 10 times its normal time), log it and alert, because it belongs in the other lane.
- Size the long lane small so it cannot starve downstream resources (the database pool) that the short lane needs; the lanes should share only what they must.
- Give the long lane a different rejection reaction (return 429 to the batch caller, or enqueue to a durable queue), since long work tolerates waiting. Its queue holds fewer slots than the short lane's (20 against 1000 in the program) but covers a longer wait, because each long task takes 60 times as long.
- Priorities inside one pool are weaker: a priority queue orders waiting tasks, but a running 300 ms task still cannot be preempted. Separate threads are the only way to give short work a guaranteed worker.
What would change the design: if long tasks are really I/O waits, do them asynchronously instead of holding a thread; if task times are unknown, put an admission limit in front and demote tasks that run over budget.
Build an asyncio connection pool in Python for a database driver whose calls block. It needs a hard cap on open connections, a bounded wait with a timeout when the pool is exhausted, connection reuse, and eviction of idle connections. Show the class and explain how it behaves under overload.
Sample Answer
Requirements and the design that satisfies them
A connection pool keeps a limited set of open database connections that requests borrow and return, because opening one is slow and the database allows only so many. The driver here blocks (a call holds its thread until the database answers), so inside asyncio every driver call must run on a worker thread via run_in_executor, or it would stop the event loop. A semaphore is a counter of free permits: acquire() takes one (waiting if none are left) and release() gives one back, which is exactly the shape of a pool's capacity. The design, one decision per requirement:
- Hard cap on open connections: an
asyncio.Semaphore(max_size)counts the connections that are borrowed, being opened or being closed, and a broken one whose query is still running on its thread. A request takes a slot before it does anything else. It then reuses an idle connection if one exists and opens a new one only when none does. A slot is returned when the connection goes back to the idle list or when it has finished closing, and a connection that is still closing keeps its slot, so connections that are open or closing never outnumber the cap. An idle connection holds no slot, so whatever closes one must first take a slot of its own and return it only when the close is over: the reaper (point 4) does this. If it closed without taking a slot, a new request could open a replacement while the old connection was still shutting down (a slow close, such as a TLS shutdown, would push the open count past the cap); if it returned a slot it never took, it would hand out one that was already free. - Bounded wait with a timeout: acquiring the slot is wrapped in
asyncio.timeout(...)(Python 3.11 or later), and raisesPoolTimeouton expiry. A timeout of 0 means fail fast: if no slot is free right now, raise at once. - Reuse: returned connections go on an idle deque. A connection older than
idle_timeoutis closed and replaced at borrow time rather than trusted. - Idle eviction: a background task (the "reaper") wakes every
idle_timeout / 2and closes (evicts) connections that have been idle too long, because databases and firewalls drop connections left quiet for a long time. It evicts only while a slot is free, because the close holds that slot; under sustained load, when every slot is busy, it waits for the next round. - Worker threads equal to the cap: the pool owns a
ThreadPoolExecutor(max_size). With fewer threads than connections an invisible second queue would form inside the executor and the timeout would no longer bound the wait. With one thread per slot it cannot: every job on a worker thread (a connect, a query or a close) belongs to a connection that holds a slot, so no job ever waits for a thread. - Cancellation: a cancelled
awaitdoes not stop the thread running the driver call. The pool therefore does not return such a connection to the idle list (the query may still be running on it) and frees its slot only when the thread finishes, so the cap stays true even then. A caller cancelled while still waiting for a slot never gets one, so nothing leaks. A caller cancelled while its connection is still being opened is the other case where a thread outlives the caller: the connect cannot be stopped, so the slot stays taken until the thread finishes, and the connection it opens is then closed instead of being lost. The same goes for a caller cancelled while a stale idle connection is being closed before its replacement is opened: the close is shielded from the cancellation, so it still runs to the end and the connection is not left open. - Failures while closing, and shutdown: closing a connection can itself fail (drivers often raise when asked to close a connection that is already broken), and that must never keep a slot or kill the reaper. The pool therefore swallows close errors (a connection that will not close is lost either way; log the error in production) and returns every slot in a
finally. Handing the same connection back twice must not return two slots, so each handle records whether it is borrowed.acloserefuses new requests, waits until every borrowed connection has come back (by taking all the slots), closes what is idle, and only then shuts the executor down. That work runs as a separate task whichaclosewaits for behindasyncio.shield, so a timeout aroundaclosestops only the waiting, not the shutdown, and callingacloseagain waits for the same shutdown instead of starting another.
The class and a driver run
How to read the class. Handle wraps one raw connection and remembers when it was last used, whether it is broken (never reuse it), inflight, the future of the query currently running on a worker thread, and borrowed, so that a second release of the same handle is ignored instead of returning a second slot. acquire first gets a slot, then either reuses an idle connection or opens a new one; its except BaseException also catches cancellation, so a slot is given back when connecting fails or the caller is cancelled. A stale idle connection is closed first, as a background task the caller waits for behind asyncio.shield while it keeps its slot. The connect itself runs behind asyncio.shield: if the caller is cancelled while a connection is still being opened, the thread cannot be stopped, so a done-callback (_abandon) closes the connection that thread eventually opens and only then returns the slot. execute runs the query with asyncio.shield, which lets the caller be cancelled while the worker thread carries on to the end, since a thread cannot be interrupted; if the caller was cancelled the handle is marked broken. release therefore has three cases: a broken connection with its query still running (free the slot only when the thread finishes, using add_done_callback, which calls a function when the future completes), a broken one that is idle (discard it now), and a healthy one (back on the idle deque, slot released). In _reap, for each stale connection the reaper checks slots.locked() (true when a slot cannot be taken immediately); if a slot is free it takes it, which returns without suspending, removes the connection from the idle list and starts _discard, which closes it and returns the slot. Nothing in that loop suspends, so no other task can borrow a connection that is about to be closed and cancelling the reaper cannot leave one behind; when no slot is free the reaper looks again on its next round. _close swallows driver errors, and _discard and _abandon return the slot in a finally, so a failing close() costs neither a slot nor the reaper. aclose sets closed (later calls to acquire raise PoolClosed) and starts, once, a shutdown task that takes every slot (which waits for every borrowed connection to come back), closes the idle connections, waits for all the background closes and stops the executor; aclose waits for that task behind asyncio.shield.
import asyncio, collections, itertools, threading, time
from concurrent.futures import ThreadPoolExecutor
# ---- a fake blocking driver (stands in for psycopg2, pymysql, ...) ----
class FakeDriver:
live, peak, ids, close_fails, close_delay = 0, 0, itertools.count(1), False, 0.0
lock = threading.Lock()
def __init__(self):
time.sleep(0.05) # blocking connect
self.id = next(FakeDriver.ids)
with FakeDriver.lock:
FakeDriver.live += 1
FakeDriver.peak = max(FakeDriver.peak, FakeDriver.live)
def query(self, seconds):
time.sleep(seconds) # blocking query
return self.id
def close(self):
time.sleep(FakeDriver.close_delay) # a slow close, e.g. a TLS shutdown
with FakeDriver.lock:
FakeDriver.live -= 1
if FakeDriver.close_fails: raise OSError("close failed") # some drivers raise when closing a broken connection
class PoolTimeout(Exception): pass
class PoolClosed(Exception): pass
class Handle:
"""One pooled connection plus bookkeeping."""
def __init__(self, raw):
self.raw, self.last_used, self.broken, self.inflight, self.borrowed = raw, time.monotonic(), False, None, True
class Pool:
def __init__(self, connect, max_size, acquire_timeout, idle_timeout, reuse="lifo"):
self.connect, self.acquire_timeout, self.idle_timeout, self.reuse = connect, acquire_timeout, idle_timeout, reuse
self.max_size, self.closed = max_size, False
self.slots = asyncio.Semaphore(max_size) # counts borrowed, opening and closing connections (an idle one holds no slot): the hard cap
self.idle = collections.deque()
self.threads = ThreadPoolExecutor(max_size) # one thread per possible connection, so the executor adds no second queue
self._background, self._closing = set(), None
self.reaper = asyncio.create_task(self._reap())
async def _acquire_slot(self):
if self.acquire_timeout == 0: # fail fast
if self.slots.locked(): raise PoolTimeout("pool exhausted")
await self.slots.acquire(); return
try:
async with asyncio.timeout(self.acquire_timeout): # bounded wait
await self.slots.acquire()
except TimeoutError:
raise PoolTimeout("no connection within %.2f s" % self.acquire_timeout) from None
async def acquire(self):
if self.closed: raise PoolClosed("pool is closed")
await self._acquire_slot()
handed_off = False
try:
if self.closed: raise PoolClosed("pool is closed") # closed while we were waiting for the slot
now = time.monotonic()
while self.idle:
h = self.idle.pop() if self.reuse == "lifo" else self.idle.popleft()
if now - h.last_used < self.idle_timeout:
h.borrowed = True
return h
closing = self._spawn(self._close(h.raw)) # stale: close it, keeping our slot so no replacement opens before it is gone
try:
await asyncio.shield(closing)
except asyncio.CancelledError:
handed_off = True # the close keeps running on its thread: it now owns the slot
closing.add_done_callback(lambda _: self.slots.release())
raise
opening = asyncio.get_running_loop().run_in_executor(self.threads, self.connect)
try:
return Handle(await asyncio.shield(opening))
except asyncio.CancelledError:
handed_off = True # the connect keeps running on its thread: it now owns the slot
opening.add_done_callback(lambda f: self._spawn(self._abandon(f)))
raise
except BaseException:
if not handed_off: self.slots.release() # connect failed or we were cancelled: give the slot back
raise
async def _abandon(self, opening):
"""The caller left while connecting: close whatever the thread opened, then free the slot."""
try:
if not opening.cancelled() and opening.exception() is None:
await self._close(opening.result())
finally:
self.slots.release() # whatever happened above, the slot comes back
def release(self, h):
if not h.borrowed: return # a second release of the same handle must not return a second slot
h.borrowed = False
running = h.inflight is not None and not h.inflight.done()
if h.broken or running:
h.broken = True
if running: # the thread still owns the connection: free the slot only when it is done
h.inflight.add_done_callback(lambda _: self._spawn(self._discard(h)))
else:
self._spawn(self._discard(h))
return
h.last_used = time.monotonic()
self.idle.append(h)
self.slots.release()
def _spawn(self, coro):
t = asyncio.get_running_loop().create_task(coro)
self._background.add(t); t.add_done_callback(self._background.discard)
return t
async def _discard(self, h):
try:
await self._close(h.raw)
finally:
self.slots.release()
async def _close(self, raw):
try:
await asyncio.get_running_loop().run_in_executor(self.threads, raw.close)
except Exception:
pass # a connection that will not close is lost either way; log it in production
async def execute(self, seconds):
h = await self.acquire()
try:
h.inflight = asyncio.get_running_loop().run_in_executor(self.threads, h.raw.query, seconds)
return await asyncio.shield(h.inflight) # cancelling the caller does not stop the thread
except asyncio.CancelledError:
h.broken = True; raise # the query may still be running: never reuse this connection
finally:
self.release(h)
async def _reap(self):
while True:
await asyncio.sleep(self.idle_timeout / 2)
now = time.monotonic()
for h in [h for h in self.idle if now - h.last_used >= self.idle_timeout]:
if self.slots.locked(): break # no free slot right now: look again next round
await self.slots.acquire() # a slot is free, so this takes it without suspending: nothing can interleave
self.idle.remove(h) # the close below holds the slot until the connection is gone
self._spawn(self._discard(h))
async def aclose(self):
self.closed = True # new requests are refused; connections coming back are closed below
self.reaper.cancel()
if self._closing is None:
self._closing = asyncio.ensure_future(self._shutdown())
await asyncio.shield(self._closing) # a timeout on this call leaves the shutdown running; call aclose again to wait for it
async def _shutdown(self):
for _ in range(self.max_size): # holding every slot means every borrowed connection is back
await self.slots.acquire()
while self.idle:
self._spawn(self._close(self.idle.pop().raw))
await asyncio.gather(*self._background, return_exceptions=True) # wait for every close still in progress
self.threads.shutdown()
async def main():
# 1. overload: cap 3, queries take 0.1 s, a request waits at most 0.15 s for a connection
pool = Pool(FakeDriver, max_size=3, acquire_timeout=0.15, idle_timeout=0.4)
await asyncio.gather(*[pool.execute(0.0) for _ in range(3)]) # warm up: three connections exist
res = await asyncio.gather(*[pool.execute(0.1) for _ in range(10)], return_exceptions=True)
print("overload: %d served, %d timed out; connections ever open at once: %d (cap 3)"
% (sum(isinstance(r, int) for r in res), sum(isinstance(r, PoolTimeout) for r in res), FakeDriver.peak))
# 2. cancellation: a queued waiter and a request cancelled in the middle of a query
tasks = [asyncio.create_task(pool.execute(0.3)) for _ in range(4)] # 3 run, 1 queued
await asyncio.sleep(0.05)
tasks[3].cancel(); tasks[0].cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await asyncio.sleep(0.4) # the threads of the cancelled query finish
print("after cancellations: free slots %d of 3, idle connections %d, live %d" % (pool.slots._value, len(pool.idle), FakeDriver.live))
# 3. idle eviction (idle_timeout 0.4 s, reaper checks every 0.2 s)
await asyncio.sleep(0.9)
print("after 0.9 s idle: idle connections %d, live %d, free slots %d of 3" % (len(pool.idle), FakeDriver.live, pool.slots._value))
FakeDriver.peak = 0
await asyncio.gather(*[pool.execute(0.1) for _ in range(10)], return_exceptions=True)
print("overload again after eviction: connections open at once: %d (cap 3)" % FakeDriver.peak)
await pool.aclose()
# 3b. cancellation while a connection is still being opened (the connect takes 0.05 s)
p = Pool(FakeDriver, max_size=2, acquire_timeout=0.15, idle_timeout=5)
tasks = [asyncio.create_task(p.execute(0.0)) for _ in range(2)]
await asyncio.sleep(0.01)
for t in tasks: t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await asyncio.sleep(0.2) # the connects finish and are closed
print("cancelled while connecting: free slots %d of 2, idle connections %d, live %d" % (p.slots._value, len(p.idle), FakeDriver.live))
await p.aclose()
# 4. reuse order: six sequential requests on a pool that already holds three connections
for mode in ("lifo", "fifo"):
p = Pool(FakeDriver, max_size=3, acquire_timeout=0.15, idle_timeout=5, reuse=mode)
await asyncio.gather(*[p.execute(0.05) for _ in range(3)])
used = [await p.execute(0.0) for _ in range(6)]
print("%s reuse: 6 sequential requests used %d distinct connection(s)" % (mode.upper(), len(set(used))))
await p.aclose()
# 5a. a close() that raises on a discarded connection must not leak its slot
FakeDriver.close_fails = True
p = Pool(FakeDriver, max_size=2, acquire_timeout=0.15, idle_timeout=5)
t = asyncio.create_task(p.execute(0.3)); await asyncio.sleep(0.1); t.cancel()
await asyncio.gather(t, return_exceptions=True)
await asyncio.sleep(0.4) # the query thread ends, the discard runs, close() raises
print("close() raises on a discarded connection: free slots %d of 2, live %d" % (p.slots._value, FakeDriver.live))
await p.aclose()
# 5b. a close() that raises in the reaper must not kill the reaper or strand the other stale connections
p = Pool(FakeDriver, max_size=2, acquire_timeout=0.15, idle_timeout=0.2)
FakeDriver.close_fails = False
await asyncio.gather(p.execute(0.0), p.execute(0.0)) # two idle connections
FakeDriver.close_fails = True
await asyncio.sleep(0.6)
print("close() raises in the reaper: idle %d, live %d, reaper still running %s" % (len(p.idle), FakeDriver.live, not p.reaper.done()))
FakeDriver.close_fails = False
await p.aclose()
# 6. aclose while a query is running: it waits for the connection, closes it, and later requests are refused
p = Pool(FakeDriver, max_size=2, acquire_timeout=0.15, idle_timeout=5)
busy = asyncio.create_task(p.execute(0.2)); await asyncio.sleep(0.1)
await p.aclose()
print("aclose with a query running: the query returned %s, live %d" % ("a result" if isinstance(await busy, int) else "nothing", FakeDriver.live))
try: await p.execute(0.0)
except PoolClosed as e: print("request after aclose:", e)
# 7. releasing the same handle twice must return only one slot
p = Pool(FakeDriver, max_size=1, acquire_timeout=0.15, idle_timeout=5)
h = await p.acquire(); p.release(h); p.release(h)
print("released twice: free slots %d of 1, idle connections %d" % (p.slots._value, len(p.idle)))
await p.aclose()
# 8. fail fast variant
p = Pool(FakeDriver, max_size=1, acquire_timeout=0, idle_timeout=5)
busy = asyncio.create_task(p.execute(0.2)); await asyncio.sleep(0.1)
try: await p.execute(0.0)
except PoolTimeout as e: print("fail fast:", e)
await busy; await p.aclose()
# 9. a slow close() must not let the cap overshoot (the reaper holds a slot while it closes)
FakeDriver.close_delay = 0.3
p = Pool(FakeDriver, max_size=3, acquire_timeout=1, idle_timeout=0.2)
a, b, c = await asyncio.gather(p.acquire(), p.acquire(), p.acquire())
p.release(a) # a goes idle; b and c stay borrowed
await asyncio.sleep(0.35) # a is stale and the reaper is part-way through closing it
FakeDriver.peak = FakeDriver.live
await p.execute(0.0) # a new request must wait for a's slot, not open a fourth connection
print("slow close() in the reaper: connections open at once: %d (cap 3)" % FakeDriver.peak)
p.release(b); p.release(c); await p.aclose()
FakeDriver.close_delay = 0.0
# 10. cancelled while waiting for a stale connection to close (both worker threads are busy closing others)
p = Pool(FakeDriver, max_size=2, acquire_timeout=1, idle_timeout=0.1)
p.reaper.cancel() # leave the stale connections to the borrow path
a, b = await asyncio.gather(p.acquire(), p.acquire())
p.release(a); p.release(b)
await asyncio.sleep(0.15) # both idle connections are now stale
FakeDriver.close_delay = 0.3
extra = await asyncio.get_running_loop().run_in_executor(None, FakeDriver)
first = asyncio.create_task(p.execute(0.0)) # closes a stale connection on one thread
p._spawn(p._close(extra)) # keeps the other thread busy
await asyncio.sleep(0.05)
second = asyncio.create_task(p.execute(0.0)) # its stale close waits for a free thread
await asyncio.sleep(0.05)
second.cancel()
await asyncio.gather(first, second, return_exceptions=True)
await asyncio.sleep(1.0)
FakeDriver.close_delay = 0.0
print("cancelled while a stale close was queued: live %d, idle %d, free slots %d of 2" % (FakeDriver.live, len(p.idle), p.slots._value))
await p.aclose()
# 11. aclose cut short by a timeout, then called again
p = Pool(FakeDriver, max_size=2, acquire_timeout=0.15, idle_timeout=5)
busy = asyncio.create_task(p.execute(0.3)); await asyncio.sleep(0.1)
try: await asyncio.wait_for(p.aclose(), 0.05)
except TimeoutError: print("aclose timed out with a query running")
await p.aclose()
print("aclose called again after the timeout: query returned %s, live %d" % ("a result" if isinstance(await busy, int) else "nothing", FakeDriver.live))
asyncio.run(main())
Output with Python 3.12 (the margins are about 50 ms wide on either side of each threshold, so a heavily loaded host could change a count):
overload: 6 served, 4 timed out; connections ever open at once: 3 (cap 3)
after cancellations: free slots 3 of 3, idle connections 2, live 2
after 0.9 s idle: idle connections 0, live 0, free slots 3 of 3
overload again after eviction: connections open at once: 3 (cap 3)
cancelled while connecting: free slots 2 of 2, idle connections 0, live 0
LIFO reuse: 6 sequential requests used 1 distinct connection(s)
FIFO reuse: 6 sequential requests used 3 distinct connection(s)
close() raises on a discarded connection: free slots 2 of 2, live 0
close() raises in the reaper: idle 0, live 0, reaper still running True
aclose with a query running: the query returned a result, live 0
request after aclose: pool is closed
released twice: free slots 1 of 1, idle connections 1
fail fast: pool exhausted
slow close() in the reaper: connections open at once: 3 (cap 3)
cancelled while a stale close was queued: live 1, idle 1, free slots 2 of 2
aclose timed out with a query running
aclose called again after the timeout: query returned a result, live 0
Walking the second line, "free slots 3 of 3, idle connections 2, live 2": four requests ask for 0.3 s queries on a pool with 3 slots, so three run and one waits. The waiting one is cancelled before it gets a slot, so it holds nothing. One running request is cancelled mid-query: its connection is marked broken, its thread runs on to the end, and then the connection is closed and its slot returned. The other two requests finish normally and their connections go back on the idle list. So all 3 slots are free again, but only 2 connections remain, both idle, and the driver's own count of live connections is 2: the third was deliberately thrown away, never recycled.
Walking the line "cancelled while connecting": two requests start opening connections (a connect takes 0.05 s) and are both cancelled after 0.01 s. The two connect threads keep running, finish, and _abandon closes the two connections they opened and returns both slots, so the pool ends with 2 of 2 slots free, nothing idle and nothing live. Without the hand-off, the slots would be returned at once while the connections stayed open and unknown to the pool (live 2 with none idle), and the cap would no longer describe the connections that exist. If _abandon skipped the close, live would stay at 2; if it skipped the slot release, free slots would stay at 0 of 2.
The test reads the semaphore's internal counter (slots._value) to show that no slot leaked or was handed out twice; application code should not. The two lines after the eviction matter: the free-slot count must come back to exactly 3, and a second overload must still never open more than 3 connections. If the reaper closed stale connections without first taking a slot, so that _discard returned a slot that was never taken, both lines would give it away (free slots 5 of 3, then 5 connections open at once), so the harness fails when the cap is broken that way.
The groups of lines after the reuse-order pair cover the remaining ways a slot or a connection can be lost, or the cap exceeded. close() raises on a discarded connection: a request is cancelled mid-query, its connection is discarded when the thread finishes, and the driver's close raises; the slot must still come back (free slots 2 of 2, live 0). If _discard returned the slot after an unguarded close (and _close let the error out), the line would read free slots 1 of 2: the pool would be one connection smaller for good, and a pool of size 1 would be dead. close() raises in the reaper: two idle connections go stale and every close raises; both must still be closed (idle 0, live 0) and the reaper must still be running. If the reaper awaited _discard itself and _close let the error out, the task would end after the first failure, one connection would stay open (idle 1, live 1) and the last field would read False. aclose with a query running: aclose waits for the running query, closes its connection, and then execute raises PoolClosed. An aclose that only closed the idle list and shut the executor down would leave that connection open (live 1). released twice: the second release of one handle is ignored (free slots 1 of 1); without the borrowed guard it would print free slots 2 of 1 and two idle entries for one connection. slow close() in the reaper: with every close taking 0.3 s, one idle connection goes stale while the other two are borrowed; the reaper holds the free slot while it closes it, so a new request waits for that slot instead of opening a fourth connection (3, cap 3). A reaper that closed without taking a slot would let the request connect at once and the line would read 4 (cap 3). cancelled while a stale close was queued: the test occupies both worker threads with slow closes (one of them closes an extra connection that the pool does not own, which the pool itself never does), so the close of a stale connection found by one request waits for a thread, and that request is cancelled; the close must still run (live 1 and idle 1 are the one connection the other request opened and returned). Without the asyncio.shield, the cancellation would cancel the close before it started and the stale connection would stay open for good (live 2). In the pool as written the shield only matters when a cancellation lands before a worker thread has picked the close up. aclose cut short by a timeout: the timeout stops the waiting, the shutdown carries on, and the second aclose waits for it and finds nothing left open (live 0); if aclose awaited the shutdown task directly, the timeout would cancel it and the second call would raise CancelledError.
How it behaves under overload
With cap 3, 0.1 s queries and a 0.15 s wait limit, 10 requests arriving together split into rounds: three run immediately; three more get connections at 0.1 s, inside their 0.15 s limit; the last four would have to wait until 0.2 s, so they time out at 0.15 s. That is the 6 served and 4 timed out above, and it is the intended shape. Demand beyond capacity is turned into fast, explicit PoolTimeout errors instead of an unbounded queue, and the number of open connections never moved past 3 (the fake driver counts live connections itself). Callers should turn PoolTimeout into a 503 or 429, ideally with a retry hint, rather than retrying immediately, because immediate retries add load to a pool that is already full.
Sizing the wait limit: a request that has waited longer than its caller will wait is wasted work. Set the acquire timeout below the request's own deadline minus its expected query time, and keep the pool plus its queue sized from Little's law (connections needed = request rate x time a connection is held). Across a fleet, instances x max_size must stay under the database's connection limit.
Wait vs fail fast, and FIFO vs LIFO
- Bounded wait smooths short bursts (a few extra milliseconds) at the cost of latency; fail fast (timeout 0) protects latency and sheds load immediately but turns every burst into errors. Use a short wait for user-facing calls that can tolerate it and fail fast for best-effort work.
- Waiters: CPython's semaphore wakes waiters in the order they queued, but the documentation does not promise fairness for
asyncio.Semaphore, so if strict first-come-first-served matters, keep your own queue of waiter futures. - Idle connection reuse order: the run above shows the effect. A "warm" connection is one that is already open and recently used, so the next request pays no connect cost. With LIFO (take the most recently returned connection) 6 sequential requests used 1 connection, so under light load the others stay idle and the reaper closes them, shrinking the pool to what the load needs. With FIFO (take the longest idle) the requests used all 3, so every connection stays warm and none sits idle long enough to age out while the load lasts. Prefer LIFO for pools that should shrink after a peak; FIFO spreads wear and keeps every connection tested, which suits servers that drop long-idle connections (they would otherwise fail the first query after a quiet spell).
Leaks and what the code deliberately does not do
The leak paths are handled: connect failure releases the slot, a timeout or a cancellation while waiting never holds one, cancellation while connecting leaves the slot with the connect thread and closes the new connection when it finishes, cancellation while a stale connection is being closed lets the close finish, cancellation mid-query discards the connection after its thread finishes, a close() that raises still returns its slot, a slow close() in the reaper cannot push the open count past the cap, releasing a handle twice returns one slot, and aclose waits for borrowed connections before closing anything and survives a timeout around it. Not covered: health checks (a SELECT 1 before reuse), resetting session state (open transaction, SET variables) on release, and a maximum connection lifetime; a query that raised leaves its connection on the idle list, so validate on borrow after idleness. One operational limit: aclose waits for every borrowed connection, so a query that never returns would hold it (wrap the call in asyncio.wait_for; the shutdown carries on in the background and a later aclose waits for it).
Build a Python worker system that consumes tasks from many sources with bounded queues so memory stays flat. Ordering must hold within a source while sources run in parallel. How do you reason about backpressure, fairness between sources, and recovery from worker failure?
Sample Answer
Requirements turned into mechanisms
| Requirement | Mechanism |
|---|---|
| Memory stays flat | A bounded queue per source. When a source's queue is full its producer blocks (this is backpressure: the slow part of the system pushes back on the fast part instead of letting a buffer grow without limit) |
| Order within a source | A source is owned by at most one worker at a time, and the worker takes tasks from the head of that source's queue |
| Sources run in parallel | Many workers, each owning a different source |
| Fairness | A worker runs at most QUANTUM tasks for a source, then puts the source at the back of the ready line (round-robin), so a source with a huge backlog cannot starve small ones |
| Recovery from failure | Remove a task from its queue only after it succeeds (an ack, short for acknowledgement); on error it stays at the head, so a retry keeps the order; after MAX_ATTEMPTS it moves to a dead-letter list (a side list for tasks that keep failing, kept for a human to inspect) and the source continues |
Two choices worth defending. First, ownership instead of a thread per source: with 10,000 sources, a thread each is thousands of stacks and context switches, whereas a fixed pool of N workers and a "ready" line gives the same ordering guarantee with N threads. Second, in-process queues: Python's GIL (global interpreter lock, which lets only one thread run Python bytecode at a time) is not a problem when handlers wait on network or disk, since a thread waiting on I/O releases it, but CPU-heavy handlers need processes. To keep the ordering rule with processes, route by hash(source) % N (the hash turns the source name into a number, and % N takes the remainder, a worker number from 0 to N-1) to one of N worker processes, each running this same structure; a given source then always lands in the same process, so one process owns it. Python's built-in hash of a string is randomised per process by default, so if more than one process (or a restart) must agree on the routing, use a stable hash such as zlib.crc32(source.encode()) % N instead.
Shipped implementation and self-check
How to read the code. A threading.Lock lets one thread at a time into a section. A threading.Condition is a lock plus a waiting room: wait() releases the lock and puts the thread to sleep until another thread calls notify() (wake one waiter) or notify_all() (wake every waiter); on waking, the thread re-takes the lock. Here two Conditions share one lock: not_full is where producers sleep while their source's queue is full, and has_ready is where idle workers sleep until some source has work. The backpressure is the two lines in submit, while len(q) >= self.bound: self.not_full.wait(): the producer sleeps and does nothing until a worker removes a task and calls notify_all(). It re-checks the condition in a while loop because another producer may have refilled the queue before this one got the lock back. Workers are daemon threads (background threads that do not keep the process alive on their own), and close joins them.
Each source is in one of three states: queued with no owner (in ready), owned (in owned, being run by exactly one worker), or empty. A tiny trace with 2 workers, QUANTUM = 2, and sources A and B with 3 tasks each: the producers fill both queues, so ready = [A, B]. Worker 1 pops A and marks it owned; worker 2 pops B. Worker 1 runs A1, A2, hits the quantum, un-owns A and, since A3 is still queued, puts A at the back of ready. Worker 2 does the same with B. Whichever worker is free next takes A again and runs A3. At no point can two workers hold A, because A is only in ready while nobody owns it, so A1 to A3 run in order.
"""Per-source ordering, bounded memory, fairness and retry, with a fixed pool of worker threads.
Design: one bounded deque per source. A source is "owned" by at most one worker at a time, so its
tasks run in order. Workers take ready sources round-robin and process at most QUANTUM tasks before
putting the source back at the END of the ready line, so a hot source cannot starve a cold one.
Producers block (backpressure) when their source's deque is full.
"""
import collections, threading, time, random
QUANTUM = 4 # max tasks a worker runs for one source before yielding it
MAX_ATTEMPTS = 3 # then the task goes to the dead-letter list
class KeyedPool:
def __init__(self, workers, per_source_bound, handler, quantum=QUANTUM):
self.bound, self.handler, self.quantum = per_source_bound, handler, quantum
self.lock = threading.Lock()
self.not_full = threading.Condition(self.lock) # producers wait here
self.has_ready = threading.Condition(self.lock) # workers wait here
self.queues = collections.defaultdict(collections.deque)
self.ready = collections.deque() # sources with work and no owner
self.owned = set() # sources a worker is running now
self.closed = False
self.dead = [] # (source, task, error) after MAX_ATTEMPTS
self.max_depth = 0
self.threads = [threading.Thread(target=self._run, daemon=True) for _ in range(workers)]
for t in self.threads: t.start()
def submit(self, source, task):
with self.lock:
q = self.queues[source]
while len(q) >= self.bound: # backpressure: the producer waits
self.not_full.wait()
q.append([task, 0]) # [task, attempts]
self.max_depth = max(self.max_depth, len(q))
if source not in self.owned and source not in self.ready:
self.ready.append(source)
self.has_ready.notify()
def _run(self):
while True:
with self.lock:
while not self.ready:
if self.closed: return
self.has_ready.wait()
source = self.ready.popleft()
self.owned.add(source) # exclusive: no other worker takes this source
for _ in range(self.quantum):
with self.lock:
q = self.queues[source]
if not q: break
item = q[0] # peek: only remove after success (ack)
try:
self.handler(source, item[0])
ok = True
except Exception as e:
ok, err = False, e
with self.lock:
q = self.queues[source]
if ok:
q.popleft(); self.not_full.notify_all()
else:
item[1] += 1
if item[1] >= MAX_ATTEMPTS: # give up on this task, keep the source moving
q.popleft(); self.dead.append((source, item[0], repr(err))); self.not_full.notify_all()
# else: it stays at the HEAD, so order is preserved on retry
with self.lock:
self.owned.discard(source)
if self.queues[source]:
self.ready.append(source) # back of the line: fairness
self.has_ready.notify()
elif self.closed and not self.ready and not self.owned:
self.has_ready.notify_all()
def close(self):
with self.lock:
self.closed = True
self.has_ready.notify_all()
for t in self.threads: t.join()
# ---------------- self-check ----------------
if __name__ == "__main__":
random.seed(1)
seen = collections.defaultdict(list) # per source, the order tasks completed in
last_done = {} # when each source's latest task finished
attempts = collections.Counter()
t_start = time.monotonic()
def handler(source, task):
seq = task
attempts[(source, seq)] += 1
if source == "flaky" and seq == 3 and attempts[(source, seq)] < 3:
raise RuntimeError("transient failure") # fails twice, succeeds on attempt 3
if source == "poison" and seq == 1:
raise RuntimeError("always fails") # dead-lettered after MAX_ATTEMPTS
time.sleep(0.002)
seen[source].append(seq)
last_done[source] = time.monotonic() - t_start
pool = KeyedPool(workers=4, per_source_bound=8, handler=handler)
producers = []
def produce(source, n):
for i in range(n): pool.submit(source, i)
# one hot source with 400 tasks, plus 5 small sources, all submitted together
for s, n in [("hot", 400), ("a", 10), ("b", 10), ("c", 10), ("flaky", 10), ("poison", 5)]:
th = threading.Thread(target=produce, args=(s, n)); th.start(); producers.append(th)
for th in producers: th.join()
pool.close()
print("per-source order preserved:", all(v == sorted(v) for v in seen.values()))
print("all hot tasks done:", len(seen["hot"]) == 400, "| flaky tasks done:", len(seen["flaky"]))
print("dead letters:", [(s, t) for s, t, _ in pool.dead])
print("poison source still ran its other tasks:", seen["poison"])
print("max queue depth seen (bound is 8):", pool.max_depth)
cold = ("a", "b", "c")
print("cold sources all finished before the hot source:", all(last_done[s] < last_done["hot"] for s in cold))
print("cold sources finished at (ms):", {s: round(last_done[s] * 1000) for s in cold})
print("hot source finished at (ms):", round(last_done["hot"] * 1000))
# ---- fairness check: 2 workers, 2 hot sources, 1 small source ----
def cold_wait(quantum):
done = {}
t0 = time.monotonic()
def h(source, task):
time.sleep(0.001)
done[source] = time.monotonic() - t0
p = KeyedPool(workers=2, per_source_bound=8, handler=h, quantum=quantum)
def prod(s, n):
for i in range(n): p.submit(s, i)
ths = [threading.Thread(target=prod, args=a) for a in (("hot1", 300), ("hot2", 300), ("small", 5))]
for th in ths: th.start()
for th in ths: th.join()
p.close()
return done["small"] * 1000, max(done["hot1"], done["hot2"]) * 1000
for q in (4, 10**9):
small_ms, hot_ms = cold_wait(q)
print(f"quantum={q:>10}: small source finished at {small_ms:6.0f} ms, hot sources at {hot_ms:6.0f} ms")
Run in a python:3.12-slim container (CPython 3.12), one sample run (timings are host-dependent; the True/False lines, the dead-letter and poison-source lines and the queue depth of 8 came out the same in every re-run on 1, 2, 4 and 8 CPUs):
per-source order preserved: True
all hot tasks done: True | flaky tasks done: 10
dead letters: [('poison', 1)]
poison source still ran its other tasks: [0, 2, 3, 4]
max queue depth seen (bound is 8): 8
cold sources all finished before the hot source: True
cold sources finished at (ms): {'a': 32, 'b': 36, 'c': 32}
hot source finished at (ms): 958
quantum= 4: small source finished at 17 ms, hot sources at 448 ms
quantum=1000000000: small source finished at 539 ms, hot sources at 547 ms
What each line proves:
- Order: every source's completion list is sorted, including
flaky, whose task 3 failed twice and succeeded on the third attempt while still staying in place. - Bounded memory: the deepest any queue got was exactly the bound of 8, even though one producer wanted to enqueue 400 tasks at once, because
submitblocks. Total buffered tasks are therefore at most (number of sources x bound). If the number of sources is unbounded too, add a global cap (a semaphore on total queued tasks) so memory stays flat as sources grow. Two details of this sketch also matter at thousands of sources: thequeuesdictionary keeps an empty deque for every source ever seen (delete the entry when a source is idle, under the lock), andsource not in self.readyis a linear scan of a deque, so keep a parallel set of queued sources instead. - Failure: the
poisonsource's task 1 always raises, lands in the dead-letter list after 3 attempts, and the rest of that source still runs: the extra line prints exactly tasks 0, 2, 3 and 4, in order. - Fairness: with 2 workers and two hot sources of 300 tasks, the 5-task small source finished after about 17 ms with a quantum of 4, versus about 540 ms when a worker runs a source until it is empty (quantum effectively infinite), which is about the time the hot sources take. Over repeated runs on 1, 2, 4 and 8 CPUs the quantum-4 time ranged from about 10 to 30 ms and the unbounded one tracked the hot sources' finish time (about 320 to 620 ms, host-dependent).
Reasoning about the three things asked
Backpressure. Pressure must reach the producer, not a distant buffer. Here the producer's submit blocks, which works for an in-process producer. For a network source (a Kafka partition, which is one ordered, append-only shard of a topic, or an HTTP stream) the equivalent is to stop reading from it: pause the consumer or stop acknowledging, so its own broker holds the data. Do not "solve" a full queue with an unbounded list or by dropping silently. Choose the bound as the number of tasks you can afford to hold for one source (memory per task x bound) and check that bound x number of active sources fits in the budget.
Fairness. The quantum trades fairness against efficiency: a small quantum gives smaller sources fast service but pays more hand-offs through the shared lock; a large quantum amortises that but increases the wait of other sources to roughly quantum x task time x (sources ahead in line) / workers. Worked with the fairness check above (quantum 4, 1 ms tasks, 2 workers, two hot sources already in line ahead of the small one, which has 5 tasks): each hot source runs one quantum on its own worker, so the small source waits 4 x 1 ms = 4 ms, then runs 4 tasks (4 to 8 ms) and rejoins the line. At 8 ms both workers come back at about the same moment, and which one re-queues first is a race: if the worker that ran the small source re-queues it before the other worker re-queues its hot source, the small source is already next in line and runs its fifth task at once, finishing at about 9 ms; if the other order happens, a hot source is ahead of it, so it waits one more quantum (about 4 ms) and finishes at about 13 ms. So the ideal case is 9 to 13 ms depending on that race, and real runs add lock hand-offs and the fact that each time.sleep(0.001) takes noticeably longer than 1 ms (about 1.8 ms on the sample host, the same overshoot the infinite-quantum case below shows; the figure depends on the host's timer), which stretches the 9 to 13 ms window to roughly 16 to 24 ms, so the sample's 17 ms is consistent with it. With an effectively infinite quantum a worker keeps a hot source until all 300 of its tasks are done, so the small source waits for one of them to finish: about 300 x 1 ms = 300 ms ideal, and the sample's 539 ms (547 ms for the hot sources) means each sleep took about 1.8 ms on that host; other runs gave about 320 to 620 ms. Start small (4 to 16) and look at the p99 wait of the smallest source. If some sources must have priority, keep separate ready lines per class and serve the high lane more often (weighted round-robin: for example take three sources from the high lane for every one from the low lane).
Recovery from worker failure. Three different failures have three different answers.
- A handler raises: caught here, retried in place with the same order, dead-lettered after N attempts. In production add backoff between attempts, because an immediate retry of a failing task holds its source's single owner and delays everything behind it in that source.
- A worker thread dies in the middle of a task: the task is still at the head of its queue (it is removed only on success), so a supervisor that notices the dead thread and starts a replacement loses nothing. The supervisor must also clear the source's ownership flag and put the source back on the ready line: otherwise the source stays marked as owned, its backlog never runs, and producers blocked on its full queue wait forever.
- The whole process dies: in-memory queues are lost. Durability needs a log outside the process (a database table or message broker with per-partition order). Consume with a lease (the broker hides the message for a visibility timeout and re-delivers it if no ack arrives) and write handlers to be idempotent (safe to run twice), because after a crash the last task may be redone. This is at-least-once delivery (every message is delivered one or more times, never silently dropped); exactly-once effects come from idempotent handlers, not from the queue.
Recommendation: ship the in-process structure above for the bounded-memory, fair, ordered scheduling, and put durability in the source system (partitioned log with acks) rather than rebuilding it in the worker. What would change this: if per-source ordering is not needed, drop the ownership rule and use one shared bounded queue, which is simpler and balances load better.
A Java service runs short parallel computations alongside many small asynchronous tasks, and some of those tasks occasionally block on I/O. When would you choose a work-stealing pool over a plain fixed-size executor, and what goes wrong when blocking calls land on its threads? How would you contain it?
Sample Answer
Two different pool designs
The names below are Java's, but the two designs exist in most runtimes. A fixed-size executor (ThreadPoolExecutor, as returned by Executors.newFixedThreadPool) has N worker threads that all take jobs from one shared queue. Jobs are independent: a job runs to completion on a thread. You choose the queue (bounded or not) and what happens when it is full (the rejection policy), and you can give each kind of work its own pool.
A work-stealing pool (ForkJoinPool) gives each worker its own double-ended queue (deque) of tasks. A worker that runs out of work steals a task from another worker's deque. This suits tasks that fork subtasks (split a big job into smaller pieces, run the pieces, combine the results: divide and conquer; also parallel streams, which run a collection pipeline on several threads, and CompletableFuture, Java's handle for a result that arrives later, in chains of small non-blocking steps) and many small tasks, because the forking worker keeps its own subtasks and there is no single queue to fight over. The Javadoc describes it as efficient when most tasks spawn subtasks and when many small tasks come from outside. The JVM provides one shared instance, the common pool, used by parallel streams and by CompletableFuture async methods that are not given an executor.
Choose the work-stealing pool for short, CPU-bound, non-blocking tasks, especially recursive ones, with parallelism near the core count. Choose a fixed executor for independent tasks of uneven length, anything that blocks, or when you need a bounded queue, a rejection policy and per-pool metrics.
What goes wrong when blocking calls land on the common pool
The common pool is deliberately small. Its parallelism (the number of threads it tries to keep running) is set by java.util.concurrent.ForkJoinPool.common.parallelism, and the program below prints what it actually is (the Javadoc does not state the default; on this JDK the program printed 1 with one or two CPUs, 2 with three, 3 with four and 7 with eight). Every blocking call (a JDBC query, JDBC being Java's database API, a synchronous HTTP call, Thread.sleep) parks one of those few threads while it does no CPU work. Once all are parked, every other task that wants the common pool waits, including unrelated parallel streams anywhere in the process and every other CompletableFuture stage. CPU looks idle and latency climbs: starvation by blocking (threads that are parked, meaning asleep and waiting, cannot run anything else). A parallelism of fewer than two behaves differently, as the --cpus=2 run described below shows.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class PoolStarvation {
static final int BLOCK_MS = 500;
static void blockingCall() { try { Thread.sleep(BLOCK_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
// Small CPU task of the kind the common pool exists for: a parallel sum.
static long smallParallelTask() { return LongStream.range(0, 2_000_000).parallel().map(x -> x % 7).sum(); }
static void sleepMs(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
// Blocking wrapped in a ManagedBlocker: tells the pool a thread is about to block so it may add a spare.
static void managedBlockingCall() {
try {
ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() {
boolean done;
public boolean block() { blockingCall(); done = true; return true; }
public boolean isReleasable() { return done; }
});
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
static void scenario(String name, Runnable submitBlockers) throws Exception {
submitBlockers.run();
sleepMs(50); // let the blockers occupy their threads
long t = System.nanoTime();
CompletableFuture.supplyAsync(PoolStarvation::smallParallelTask).get(); // runs on the common pool
System.out.printf("%-48s small task took %6.0f ms%n", name, (System.nanoTime() - t) / 1e6);
sleepMs(BLOCK_MS + 100); // let blockers finish before the next scenario
}
public static void main(String[] a) throws Exception {
int cpus = Runtime.getRuntime().availableProcessors();
int par = ForkJoinPool.commonPool().getParallelism();
System.out.println("availableProcessors = " + cpus + ", commonPool parallelism = " + par);
smallParallelTask(); // warm up
int blockers = par * 3;
scenario("no blocking calls", () -> { });
scenario("blocking calls on the common pool", () -> {
for (int i = 0; i < blockers; i++) CompletableFuture.runAsync(PoolStarvation::blockingCall);
});
ExecutorService ioPool = Executors.newFixedThreadPool(blockers);
scenario("blocking calls on a separate pool", () -> {
for (int i = 0; i < blockers; i++) CompletableFuture.runAsync(PoolStarvation::blockingCall, ioPool);
});
ioPool.shutdown();
scenario("blocking calls wrapped in managedBlock", () -> {
for (int i = 0; i < blockers; i++) CompletableFuture.runAsync(PoolStarvation::managedBlockingCall);
});
System.out.println("blockers submitted each time: " + blockers + " x " + BLOCK_MS + " ms");
}
}
Run in an eclipse-temurin:21-jdk container (OpenJDK 21) with --cpus=4, it printed (timings are from a shared host and vary):
availableProcessors = 4, commonPool parallelism = 3
no blocking calls small task took 2 ms
blocking calls on the common pool small task took 1449 ms
blocking calls on a separate pool small task took 1 ms
blocking calls wrapped in managedBlock small task took 1 ms
blockers submitted each time: 9 x 500 ms
How to read the four rows: each row submits 9 blocking calls of 500 ms (three times the pool's 3 threads), waits 50 ms, then times one small CPU task sent to the common pool. Row 1 is the baseline, 2 ms. In row 2 all 3 common-pool threads are parked in blocking calls, so the small task has no thread to run on until they free up. In row 3 the blockers run on their own pool, so the common pool is untouched. In row 4 each blocking call is wrapped in ManagedBlocker, an object with two methods: block() does the blocking and isReleasable() tells the pool whether blocking is still needed. Before running block(), managedBlock signals the pool that this thread is about to be unavailable, and the pool may add a spare thread to keep the target parallelism, so the small task finds a thread at once (1 ms in the sample, a few milliseconds up to a few tens on other runs). The spare threads are the price: 9 callers now mean up to 9 extra blocked threads (the number of spares is capped by java.util.concurrent.ForkJoinPool.common.maximumSpares, 256 by default).
The arithmetic: 9 blocking calls of 500 ms on 3 threads run in 3 waves (9 / 3 x 0.5 s = 1.5 s), so a small task queued behind them waits about 1.45 s (it was submitted 50 ms after the blockers). On the same code with --cpus=8 the pool had parallelism 7 and 21 blockers, and the small task waited 1461 ms; the pattern (about 3 waves x 500 ms) holds because the demo submits three times the parallelism. With --cpus=2 the pool reported parallelism 1 and the starvation disappeared (small task about 1 ms), a surprising result with a simple cause: CompletableFuture's Javadoc says that when the common pool does not support a parallelism level of at least two, it creates a new thread per async task. Passing -Djava.util.concurrent.ForkJoinPool.common.parallelism=3 on the 2-CPU container brought the starvation back (about 1.46 s); on the 4-CPU container, setting it to 6 left the picture unchanged (about 1.45 s, with 18 blockers). The lesson: behaviour depends on the container's CPU count, so a test on a 2-CPU build agent can hide a bug a 4-CPU production pod shows.
Containing it
The first step is the default fix. Steps 2 and 3 apply in particular situations (code you cannot move, or fork-join work that must be capped), and the rest are habits that keep the problem from returning.
- Move blocking work to its own bounded executor and pass it explicitly:
CompletableFuture.runAsync(task, ioPool), never the default. Size it for the wait-to-compute ratio of those calls and bound its queue. Its metrics (queue depth, active threads, rejections) now tell you when the blocking dependency is the problem. This is the row labelled "separate pool" above. - Wrap unavoidable blocking in
ForkJoinPool.managedBlockwhen you must stay in a fork-join pool. The Javadoc says it "possibly arranges for a spare thread to be activated" while the current one blocks, so parallelism for the other tasks is maintained (the last row above). It trades starvation for more threads, so it does not remove the need to bound how many calls block at once. - Cap parallelism where it matters. Run fork-join work in your own
ForkJoinPoolsized for that job (submit theForkJoinTaskto it) so a heavy job cannot take over the common pool (running a parallel stream from inside a task of a private pool is a widely used trick, but the Javadoc does not promise it, so prefer explicitForkJoinTasks or a separate executor), and add a semaphore on calls to a downstream with a connection limit. - Keep the common pool for CPU-bound, non-blocking steps and review any library that does blocking work inside
parallelStream()or default*Asynccalls. - Verify: thread dumps (
jstack) showForkJoinPool.commonPool-worker-Nthreads all parked in the same blocking frame while CPU is low; after the fix the same dump shows them idle, with the blocking frames on your pool's threads.
Recommendation and what would change it
For this service: keep the work-stealing pool (common pool or a private ForkJoinPool) for the short parallel computations, and send every task that may block to a separate fixed executor with a bounded queue and a named rejection policy; use managedBlock only for blocking inside code you cannot move. If the blocking tasks become the majority of the load, the better design is a pool (or virtual threads on Java 21) for the blocking side and a plain fixed pool for the computing side, with no need for fork-join at all.
Unlock Full Question Bank
Get access to all 25 Concurrency & Asynchronous Performance interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.