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.
A Node.js API's p99 latency spikes whenever one endpoint runs a roughly 200 ms synchronous computation, and every other request waits behind it. How do you confirm the event loop is the problem, and what are your options for fixing it?
Sample Answer
Step 1: confirm the event loop is the problem
The symptom (every request slow, only while one endpoint runs) points at a callback holding the single JavaScript thread. Confirm it with evidence, in this order:
- Measure event-loop delay. Node's
perf_hooks.monitorEventLoopDelay()returns a histogram (a table counting how many samples fell into each delay range, from whichmaxand percentiles are read) of how late the loop's timer fires. The timer resolution is how often it is set to fire, here everyresolutionms; if a 200 ms computation runs, the next sample is about 200 ms late. Exportmaxandp99(the value that 99 percent of samples are at or under;p50is the median) as metrics and alert on them. The histogram records the whole interval between timer firings, so a healthy idle loop shows delays near the resolution itself (about 10 ms when the resolution is 10), not near zero; spikes line up with the slow endpoint. - Correlate. Plot event-loop delay against per-endpoint request counts or traces. If loop delay spikes only when the heavy endpoint is hit, and other endpoints slow down by roughly the heavy endpoint's computation time, the loop is the cause. CPU on the process near 100% of one core while the host has idle cores is a supporting sign.
- Reproduce locally with a CPU profile:
node --cpu-prof app.jswrites a.cpuprofilefile you can open in Chrome DevTools, and the heavy function shows as a long block of self time. - Rule out the alternatives. A slow database or saturated libuv pool also slows requests, but event-loop delay stays low in those cases because the loop is idle waiting; the delay histogram separates them.
A runnable reproduction and fix
This program starts an HTTP server with a /heavy route (about 200 ms of synchronous arithmetic on a 4-CPU run like the one below; longer on a slower or shared core) and a cheap /ping route. A client sends 200 cheap requests 10 ms apart while four heavy requests are in flight, and prints latency and loop delay. Mode inline runs the work in the handler; mode worker runs it in a worker_threads Worker.
const http = require('node:http');
const { monitorEventLoopDelay } = require('node:perf_hooks');
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
function heavy() { // roughly 200 ms of synchronous CPU work
let x = 0;
for (let i = 0; i < 6e7; i++) x = (x + i * 7) % 1000003;
return x;
}
if (!isMainThread) {
parentPort.postMessage(heavy());
return;
}
const MODE = process.argv[2]; // 'inline' or 'worker'
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
const server = http.createServer((req, res) => {
if (req.url === '/heavy') {
if (MODE === 'inline') {
res.end(String(heavy()));
} else {
const w = new Worker(__filename);
w.once('message', (v) => res.end(String(v)));
}
} else {
res.end('ok');
}
});
function get(path) {
return new Promise((resolve) => {
const t = process.hrtime.bigint();
http.get({ port: 3000, path, agent: false }, (r) => {
r.resume();
r.on('end', () => resolve(Number(process.hrtime.bigint() - t) / 1e6));
});
});
}
server.listen(3000, async () => {
const lat = [];
const heavyCalls = [];
for (let i = 0; i < 200; i++) { // 200 cheap requests, 10 ms apart
if (i % 50 === 10) heavyCalls.push(get('/heavy')); // 4 slow requests spread over the run
lat.push(await get('/ping'));
await new Promise((r) => setTimeout(r, 10));
}
await Promise.all(heavyCalls);
lat.sort((a, b) => a - b);
const p = (q) => lat[Math.min(lat.length - 1, Math.floor(q * lat.length))].toFixed(1);
console.log(`mode=${MODE} cheap-request latency ms: p50=${p(0.5)} p99=${p(0.99)} max=${lat[lat.length - 1].toFixed(1)}`);
console.log(`loop delay (monitorEventLoopDelay) max=${(h.max / 1e6).toFixed(0)} ms, p99=${(h.percentile(99) / 1e6).toFixed(0)} ms`);
server.close();
h.disable();
process.exit(0);
});
Reading the client loop: each iteration sends one /ping and waits for it, sleeps 10 ms, and every 50th iteration (starting at 10) also fires a /heavy request without waiting for it, so four heavy requests overlap the pings at different moments; the latency of each /ping is what goes into lat. The /heavy handler in worker mode starts a new Worker per request only to keep the demo short; the recommendation below is a reusable pool, because a Worker has start-up cost.
Run with node lag.js inline and node lag.js worker. Sample run on node:22-slim (Node 22.23.3) with --cpuset-cpus=0-3, one run on a noisy host:
mode=inline cheap-request latency ms: p50=0.4 p99=202.9 max=217.3
loop delay (monitorEventLoopDelay) max=222 ms, p99=192 ms
mode=worker cheap-request latency ms: p50=0.5 p99=8.8 max=13.4
loop delay (monitorEventLoopDelay) max=19 ms, p99=15 ms
The shape: the median stays around a millisecond or less in both modes, but with the work inline the p99 jumps to roughly the length of the computation, because any request that lands during the 200 ms waits for it. With the work in a Worker the cheap requests stay far below the 200 ms stall, typically around 1 to 15 ms at p99 across re-runs, and occasionally higher on a busy host. With one CPU (--cpuset-cpus=0) the worker mode still protected the cheap requests in repeat runs (p99 roughly 2 to 16 ms in re-runs), though one core must then be shared between the loop and the worker, so it is the CPU limit that decides how much heavy work can run at once. The inline stall tracks how long the computation takes on the core it gets: it is single-threaded work, so adding CPUs does not shorten it, and on a slower or busier core the p99 and loop-delay maximum rise above 200 ms, so "roughly the length of the computation" means the length on that host. The roughly 10 ms floor in the loop-delay numbers is the timer resolution, not a stall: the minimum recorded delay is usually about 9 ms in both modes (an occasional run on a loaded host recorded less), so worker-mode loop-delay maxima of roughly 12 to 30 ms across re-runs (occasionally higher on a busy host) are that baseline plus the time the main thread spends creating each Worker and scheduling noise on a shared host.
Step 2: the options, and the cost of each
The first two rows are the cheapest to try and need no new infrastructure; the worker pool is the usual next step for a 200 ms computation; the process, queue and service rows apply when the work outgrows a single request or needs isolation.
| Option | What it buys | What it costs |
|---|---|---|
| Make the code cheaper (better algorithm, cache the result, stream instead of buffering) | Removes the problem; no new moving parts | May not be possible; only worth it if the computation is mostly waste |
Chunk the loop and yield with setImmediate | Other callbacks interleave; no extra thread | Total time for the heavy request grows; still uses the loop's one core; you must write the yielding by hand |
worker_threads pool (reuse a fixed set of workers) | Real parallelism inside one process; shared memory possible with SharedArrayBuffer (a block of memory several threads can read and write without copying) | Arguments and results are copied by structured clone (the algorithm that deep-copies a JavaScript value so another thread gets its own copy), so large objects cost real time and memory; a Worker has its own heap and start-up cost, which is why you keep a pool instead of starting one per request |
Child process (child_process/cluster) | Strong isolation; a crash or leak is contained | Heavier start-up and memory per process; data crosses a pipe via serialization |
| Job queue plus worker processes | Takes the work off the request path; scale workers separately; retry and rate-limit | The client no longer gets the result in the same response (polling, webhook or push); adds infrastructure and failure modes (duplicate delivery, backlog) |
| Separate service (or a native or WebAssembly implementation; WebAssembly, WASM, is a compact binary code format that runs at near-native speed) | Independent scaling and hardware; faster language for tight loops | Network hop, a deployment unit to run and monitor; data serialization again |
Recommendation
For a computation that is 200 ms and fits in one request: first check whether the work can be made cheaper or cached; if not, put it behind a fixed-size pool of worker threads, with a bounded queue (sized at about the cores you can give it, leaving a core for the loop) and reject or return 503 when the queue is full. If results can arrive later, or the computation grows past a second or two, move to a job queue so the API tier is never at the mercy of heavy jobs. Pass a result handle (SharedArrayBuffer, or transfer the ArrayBuffer) instead of copying big payloads. Choose child processes or a separate service when you need fault isolation or different scaling; the extra serialization and operations cost then pays for itself.
Verify the fix
Rerun the same load with event-loop delay exported: p99 loop delay should fall back toward the timer resolution and the other endpoints' p99 should stop tracking the heavy endpoint's rate. Also load-test the heavy endpoint itself at 2x expected traffic to confirm the pool's queue and rejection behave: the failure you want is a fast 503 on the heavy route, not slow responses everywhere.
How do you decide how many threads a server's worker pool should have? Compare a web service that mostly waits on downstream calls with one that spends its time resizing images, and say what you do about the queue in front of the pool when load exceeds capacity.
Sample Answer
Start by classifying the work, not by picking a number
A worker pool is a fixed set of reusable threads that pull jobs off a queue. A thread is an independent flow of execution that the operating system (OS) schedules onto a CPU core. Compared with thread-per-task (start a new thread for every request), a pool pays the thread start-up cost once, caps memory (every thread owns a stack), and caps how many threads the scheduler must juggle. Each switch between threads on one core is a context switch (the OS saves one thread's registers and loads another's), and it is pure overhead.
The deciding number is the wait-to-compute ratio of one job: time spent blocked (on a network call, disk, a lock) divided by time spent on a CPU. A blocked thread uses no CPU, so you can have more threads than cores only to the extent threads are blocked.
pool size = cores x (1 + wait / compute)
This is a starting estimate for a pool that has the machine to itself. It is then checked by a load test, because the real ratio shifts under load.
The two services
Hypothetical inputs: an 8-core machine. The image resizer spends 40 ms of CPU per image and does not wait. The web service spends 2 ms of CPU per request and waits 98 ms on downstream calls (so a request takes about 100 ms end to end).
| Service | compute | wait | pool size = 8 x (1 + wait/compute) | Throughput ceiling at 100% CPU |
|---|---|---|---|---|
| Image resizing | 40 ms | 0 ms | 8 | 8 / 0.040 s = 200 jobs/s |
| Web service on downstream calls | 2 ms | 98 ms | 400 | 8 / 0.002 s = 4000 req/s |
Little's law cross-checks the second row. It says the average number of requests in the system (L) equals arrival rate times time in system (W): L = lambda x W. At 4000 req/s with 100 ms per request, L = 4000 x 0.1 = 400 requests in flight, so 400 threads are all busy. A different example: 5000 req/s at 10 ms each is 5000 x 0.010 = 50 in flight, so about 50 concurrent slots are enough. A pool smaller than L cannot sustain that rate, and the excess piles up in the queue.
Two cautions on the 400. Memory for 400 stacks and the downstream service's own limit (for example its connection cap) can bind first, and then the right pool size is whatever the downstream can absorb, not the formula. For the resizer, 8 is the figure to start from and threads beyond that only add context switches and cache churn (each core's fast private memory, its cache, is refilled with a different thread's data after every switch, so the thread that resumes starts with cache misses: reads that must go to slower main memory).
Shipped sizing and measurement code
import os, time, math
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# ---- sizing formulas (inputs are hypothetical, stated here) ----
cores = 8
def pool_size(cores, wait_ms, compute_ms):
return cores * (1 + wait_ms / compute_ms)
print("cores =", cores)
print("image resize (hypothetical 40 ms compute, 0 ms wait):", pool_size(cores, 0, 40))
print("web call (hypothetical 2 ms compute, 98 ms wait): ", pool_size(cores, 98, 2))
def littles_law(rate_per_s, latency_s):
return rate_per_s * latency_s # L = lambda * W, average requests in the system
print("Little's law, 5000 req/s x 10 ms :", littles_law(5000, 0.010), "in flight")
print("Little's law, 4000 req/s x 100 ms :", littles_law(4000, 0.100), "in flight")
print("8 cores / 2 ms compute :", cores / 0.002, "req/s ceiling")
# ---- measured: I/O-bound tasks on thread pools ----
def io_task(_):
time.sleep(0.05) # stands in for a 50 ms downstream call
return 1
def cpu_task(n):
x = 0
for i in range(n):
x += i * i
return x
if __name__ == "__main__":
print("\nos.cpu_count() =", os.cpu_count())
N = 400
print("\nI/O-bound: %d tasks of 50 ms wait" % N)
for size in (4, 16, 64, 256):
t = time.perf_counter()
with ThreadPoolExecutor(size) as ex:
list(ex.map(io_task, range(N)))
dt = time.perf_counter() - t
print(" threads=%4d %6.2f s %7.0f tasks/s" % (size, dt, N / dt))
jobs = [2_000_000] * 32
print("\nCPU-bound: 32 jobs of pure Python arithmetic, process pool")
for size in (1, 2, 4, 8, 16, 32):
t = time.perf_counter()
with ProcessPoolExecutor(size) as ex:
list(ex.map(cpu_task, jobs))
dt = time.perf_counter() - t
print(" procs=%3d %6.2f s %6.1f jobs/s" % (size, dt, len(jobs) / dt))
Sample run, docker run --rm --cpus=4 on python:3.12-slim (Python 3.12.15). Timings are from a shared, noisy host and will differ on yours. Three different core counts appear and mean different things: 8 is the hypothetical machine in the formulas above, 4 is the CPU limit the container really got (--cpus=4), and 14 is what os.cpu_count() reports because it sees the host's cores and ignores the limit.
cores = 8
image resize (hypothetical 40 ms compute, 0 ms wait): 8.0
web call (hypothetical 2 ms compute, 98 ms wait): 400.0
Little's law, 5000 req/s x 10 ms : 50.0 in flight
Little's law, 4000 req/s x 100 ms : 400.0 in flight
8 cores / 2 ms compute : 4000.0 req/s ceiling
os.cpu_count() = 14
I/O-bound: 400 tasks of 50 ms wait
threads= 4 5.09 s 79 tasks/s
threads= 16 1.30 s 307 tasks/s
threads= 64 0.36 s 1116 tasks/s
threads= 256 0.12 s 3377 tasks/s
CPU-bound: 32 jobs of pure Python arithmetic, process pool
procs= 1 1.66 s 19.3 jobs/s
procs= 2 0.97 s 33.0 jobs/s
procs= 4 0.58 s 55.4 jobs/s
procs= 8 0.70 s 46.0 jobs/s
procs= 16 0.64 s 50.0 jobs/s
procs= 32 0.61 s 52.9 jobs/s
The shape is what to remember, not the figures. For waiting work, throughput rises almost in proportion to thread count (4 to 256 threads is more than a 40x gain here) because each extra thread overlaps another wait. For CPU-bound work, throughput climbs until the pool reaches the cores that are really available, then flattens or dips: with the 4-CPU limit the rows from 4 processes upward were roughly flat (0.58 s at 4 processes and 0.70 s at 8 in this sample). The small differences between those rows are within run-to-run noise on a shared host and do not reliably show a dip: re-runs gave 4, 8, 16 and 32 processes within roughly 30 percent of each other, and which of them was fastest changed from run to run. On one CPU more processes gave no speed-up, and the rows with more processes were often somewhat slower than the single-process row (the one core is the cap), and with 8 CPUs throughput kept rising past 4 processes; where it flattens depends on the host. This is also why a bigger pool can lower throughput: past the core count, extra runnable threads add context switches, cache misses and memory pressure and no extra work gets done.
Note os.cpu_count() printed 14 even though the container was limited to 4 CPUs. A pool sized from "number of cores" inside a container can therefore be sized for the host, not for the quota; pass the intended core count explicitly.
What to do with the queue when load exceeds capacity
When arrivals exceed the ceiling (200 jobs/s for the resizer), the queue grows without limit if it is unbounded: latency grows, memory grows, and clients time out while the server still works on requests nobody is waiting for. Little's law applies here too: waiting time = queue length / service rate. Tail latency is usually quoted as p99, the 99th percentile: 99 requests in 100 finish faster than this value, so it describes the slow tail that users notice.
- Bound the queue and size it from a latency budget. If a request may wait at most 200 ms in the queue and the pool drains 200 jobs/s, the queue holds 0.2 s x 200/s = 40 jobs. Deeper than that only delays the failure.
- Pick a rejection policy on purpose and make it visible to the caller. For a request/response service, fail fast with HTTP 503 (or 429) plus a
Retry-Afterheader so the client or load balancer can go elsewhere. Alternatives: block the producer for a bounded time, run the job on the caller's thread (this slows the producer, which is a form of backpressure, meaning pushing the slowness back to whoever is sending), or drop the oldest queued job when stale work is worthless. Silently discarding is acceptable only when nobody relies on the result. - Shed load early. Reject at the edge before doing expensive work, and prefer a short, honest failure to a long timeout.
- Watch queue depth, active threads, rejection rate and time-in-queue. A queue that is non-empty for long stretches means capacity is too low; a rejection spike means a burst or a slow downstream.
Java's executors show the three knobs (the ideas carry over to any language's pool; the class names are Java's, and the rule that matters is: bound the queue and choose the rejection behaviour). ThreadPoolExecutor takes a core size (the number of threads kept even when idle), a maximum size (the most it may grow to) and a queue. Per the Javadoc, when fewer than the core number of threads are running it starts a new thread, otherwise it prefers to queue, and it only adds threads beyond the core when the queue cannot accept the job; if the queue is unbounded, the maximum is never reached. If the queue is full and the maximum is reached the job is rejected, and the default AbortPolicy throws RejectedExecutionException; CallerRunsPolicy, DiscardPolicy and DiscardOldestPolicy are the alternatives. Executors.newFixedThreadPool uses a fixed thread count with an unbounded queue (the trap above), newCachedThreadPool uses a SynchronousQueue (a direct handoff with no waiting room, so a job goes to an idle thread or a new thread is created, with no upper limit on thread count) and retires idle threads after 60 seconds (unbounded threads under a burst), and newScheduledThreadPool runs delayed or periodic tasks on a core-sized pool. For a service, set core equal to max, an ArrayBlockingQueue with the capacity from step 1, and a rejection handler you chose.
Recommendation and what would change it
Use separate pools for the two kinds of work, sized 8 for the resizer and by measured downstream capacity (up to about 400 on these hypothetical numbers) for the web service, each with a bounded queue and fail-fast rejection. Verify by load testing at 1x, 2x and 4x the expected rate and confirming that latency for admitted requests stays flat while rejections rise. If the wait/compute ratio varies a lot, an adaptive limit (a concurrency cap the service adjusts itself: it raises the cap while latency is healthy and lowers it when latency inflates) works better than a static number.
You are choosing a concurrency model for a new high-throughput HTTP service: an event loop per process or a thread per request. How do you decide? Think through latency, memory per connection, what happens when a handler blocks, and how failures show up in production.
Sample Answer
Decide on the work each request does, then on the failure you can live with
A thread per request model gives each in-flight request its own operating-system (OS) thread, an independent flow of execution the kernel schedules onto CPU cores. Code reads top to bottom and a blocking call just parks that thread. An event loop model runs many requests on one thread (per process), which switches between requests only when a handler waits (await or a callback); a handler that blocks stops them all. A third option is a lightweight thread scheduled by the language runtime: goroutines in Go, virtual threads in Java 21. They read like blocking code but cost far less than OS threads.
Recommendation for a new service whose handlers mostly wait on databases and downstream calls: use the runtime-scheduled lightweight option if the stack has it (Java 21 virtual threads, Go), otherwise an event loop with a small separate pool for the work that blocks or burns CPU. Choose plain thread-per-request only when concurrency is modest (hundreds, not tens of thousands) and the team's code or libraries are synchronous. What would flip it: heavy CPU per request (then cores are the limit and the model barely matters; add worker processes), a mandatory blocking library you cannot replace (thread per request or an offload pool), or a team that cannot hold the discipline "nothing blocks the loop".
Latency and throughput
The sections below run one comparison on each runtime that matters for the model: a Java program for in-flight capacity and the pinning caveat, and a Python program for memory per connection. The table after them covers what a blocked handler does in each model.
When requests mostly wait, throughput is limited by how many can be waiting at once. By Little's law (requests in flight = arrival rate x time in system), 10,000 requests/s each spending 100 ms blocked needs 1,000 requests in flight. A pool of 200 OS threads caps this at 200 / 0.1 s = 2,000 requests/s no matter how many cores exist. An event loop or lightweight threads have no such cap from the thread count; their cap is CPU and the downstream's capacity.
The program below runs 10,000 handlers that each block 100 ms, once on 200 platform threads and once with one virtual thread per task, then times 64 sleeps inside synchronized (a Java monitor lock: the keyword makes a block of code run by one thread at a time per lock object).
How to read the program: handler() is a stand-in request that sleeps 100 ms (blocked, no CPU). run submits the requests to an executor (a pool that runs submitted tasks) and a CountDownLatch, a counter that starts at the request count and releases await() when every task has called countDown(), so the timer stops when the last request finishes. newFixedThreadPool(200) is 200 OS threads; newVirtualThreadPerTaskExecutor() starts one virtual thread per task; try (...) closes the executor afterwards. In the last block each task sleeps while holding its own private lock object, so any slowdown comes from the runtime, not from tasks waiting for each other.
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ModelCompare {
// A "handler" that spends 100 ms blocked on a downstream call, then a little CPU.
static void handler() {
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
static double run(ExecutorService ex, int requests) throws Exception {
long t = System.nanoTime();
CountDownLatch done = new CountDownLatch(requests);
for (int i = 0; i < requests; i++) ex.submit(() -> { handler(); done.countDown(); });
done.await();
return (System.nanoTime() - t) / 1e9;
}
public static void main(String[] a) throws Exception {
System.out.println("availableProcessors = " + Runtime.getRuntime().availableProcessors());
int requests = 10_000;
try (ExecutorService ex = Executors.newFixedThreadPool(200)) {
double s = run(ex, requests);
System.out.printf("200 platform threads : %d blocking requests in %.2f s (%.0f req/s)%n", requests, s, requests / s);
}
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
double s = run(ex, requests);
System.out.printf("virtual threads : %d blocking requests in %.2f s (%.0f req/s)%n", requests, s, requests / s);
}
// Little's law: 10_000 requests of 100 ms on 200 threads can finish no faster than 10_000 * 0.1 / 200 s
System.out.printf("lower bound for 200 threads: %.2f s%n", requests * 0.1 / 200);
// Pinning: blocking inside synchronized.
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
long t = System.nanoTime();
int n = 64;
CountDownLatch done = new CountDownLatch(n);
for (int i = 0; i < n; i++) ex.submit(() -> {
// each task uses its own monitor so tasks do not serialize on one lock
Object own = new Object();
synchronized (own) { handler(); }
done.countDown();
});
done.await();
System.out.printf("64 x 100 ms sleeps inside synchronized: %.2f s%n", (System.nanoTime() - t) / 1e9);
}
}
}
Run in an eclipse-temurin:21-jdk container (OpenJDK 21.0.12) with --cpus=1, then --cpus=4, it printed (availableProcessors reflected the CPU limit, not the host; timings are from a shared host and vary):
--- cpus=1
availableProcessors = 1
200 platform threads : 10000 blocking requests in 5.28 s (1894 req/s)
virtual threads : 10000 blocking requests in 0.13 s (76548 req/s)
lower bound for 200 threads: 5.00 s
64 x 100 ms sleeps inside synchronized: 6.47 s
--- cpus=4
availableProcessors = 4
200 platform threads : 10000 blocking requests in 5.16 s (1939 req/s)
virtual threads : 10000 blocking requests in 0.14 s (69427 req/s)
lower bound for 200 threads: 5.00 s
64 x 100 ms sleeps inside synchronized: 1.67 s
The shape: the 200-thread pool sits at its arithmetic ceiling (about 5 s, whatever the CPU count) while virtual threads finish in about 0.14 s because waiting costs almost nothing. The last line shows the caveat. Virtual threads are run by a small set of ordinary OS threads called carriers; the number of carriers defaults to the number of processors. Normally a virtual thread that blocks is unmounted: taken off its carrier so the carrier can run another virtual thread. On JDK 21 a virtual thread that blocks inside synchronized is pinned: it cannot unmount, so it holds its carrier for the whole block. With as many carriers as processors, so 64 pinned sleeps of 100 ms take about 64 x 0.1 / carriers seconds (6.4 s at one carrier, 1.6 s at four, matching the run). A JEP is a JDK Enhancement Proposal, the document that specifies a Java feature. JEP 444 documents the two pinning cases in JDK 21 (inside synchronized, and in native or foreign calls); JEP 491 removed the synchronized case in Java 24, leaving pinning while a native frame (a call into non-Java code) is on the stack, such as class loading or class initialisation that blocks.
Memory per connection
Each OS thread reserves a stack and kernel bookkeeping; a task on an event loop is a small heap object. A second program holds 2,000 idle waiting "connections" as asyncio tasks and as OS threads and reads resident memory (RSS, the memory actually held in RAM by the process) from /proc/self/status:
import asyncio, threading, resource
def rss_mb():
with open("/proc/self/status") as f:
for line in f:
if line.startswith("VmRSS"):
return int(line.split()[1]) / 1024
def threads(n):
stop = threading.Event()
ts = [threading.Thread(target=stop.wait) for _ in range(n)]
base = rss_mb()
for t in ts: t.start()
used = rss_mb() - base
stop.set()
for t in ts: t.join()
return used
async def tasks(n):
stop = asyncio.Event()
base = rss_mb()
ts = [asyncio.create_task(stop.wait()) for _ in range(n)]
await asyncio.sleep(0)
used = rss_mb() - base
stop.set()
await asyncio.gather(*ts)
return used
n = 2000
asyncio.run(asyncio.sleep(0)) # warm up the interpreter
a = asyncio.run(tasks(n))
t = threads(n)
print("%d idle connections: asyncio tasks +%.1f MB RSS (%.1f KB each), OS threads +%.1f MB RSS (%.1f KB each)"
% (n, a, a*1024/n, t, t*1024/n))
On Linux in python:3.12-slim, two consecutive runs printed:
2000 idle connections: asyncio tasks +0.8 MB RSS (0.4 KB each), OS threads +57.6 MB RSS (29.5 KB each)
2000 idle connections: asyncio tasks +1.8 MB RSS (0.9 KB each), OS threads +59.0 MB RSS (30.2 KB each)
The difference is about 30 to 70 times per idle connection here. RSS counts only touched pages; each thread also reserves virtual address space (the range of addresses the OS sets aside for the process, whether or not it is backed by RAM yet) for its stack, and the OS limits threads per process, so thread counts can hit those limits before RSS looks alarming. Virtual threads keep their stacks as garbage-collected heap objects, and JEP 444 says memory use and garbage-collector activity of thread-per-request and asynchronous code should be roughly similar.
What happens when a handler blocks
| Model | One handler blocks for 300 ms | Containment |
|---|---|---|
| Thread per request | One thread is parked; others run. A burst of blocked handlers exhausts the pool and queues new requests. | Bound the pool and queue, set timeouts |
| Event loop (one thread) | Every request on that loop stalls for 300 ms | Offload to a thread pool or process, measure loop lag |
| Virtual threads or goroutines | A blocked I/O call unmounts or parks cheaply. Pinned or CPU-bound work holds a carrier or a processor slot. | Avoid blocking in synchronized on JDK 21, limit CPU-bound parallelism |
Go's runtime documentation says GOMAXPROCS (the setting for how many goroutines may run on CPUs at once) limits the number of CPUs executing simultaneously and that there is no limit on threads blocked in system calls. In Node.js, file system, DNS lookup (dns.lookup), zlib and some crypto calls run on libuv's worker pool, whose default size is 4 threads (libuv docs; UV_THREADPOOL_SIZE changes it), so a handful of slow file or crypto calls can queue all the rest.
How failures show up in production
- Thread per request: thread count and queue depth climb, latency rises, then rejections or out-of-memory (OOM) errors, when the process is killed or refuses to allocate. Visible in thread dumps (
jstackis the JDK tool that prints every thread's stack and state). - Event loop: all endpoints get slow together, CPU is high on one core and idle on others, and timers fire late. A single bad regular expression or a large JSON parse can do it.
- Lightweight threads: unbounded concurrency moves the limit to the downstream: connection pools and databases saturate. Cap concurrency with a semaphore (JEP 444 says not to pool virtual threads), because a limit on thread count is gone.
Whatever you choose, set a timeout on every outbound call, bound every queue, and expose in-flight count and loop lag so the first failure is a graph, not a page.
When would you use processes instead of threads for a Python server? What does the GIL actually prevent, and what does going multi-process cost you?
Sample Answer
What the GIL does and does not prevent
The Global Interpreter Lock (GIL) is a lock inside the standard CPython interpreter. Only the thread holding it can execute Python bytecode (the interpreter's instructions), so in one process, two threads cannot run pure-Python code on two cores at the same time. A thread gives up the GIL while it waits on a blocking operation such as a socket read, time.sleep or file I/O, and many C extensions release it during long native work (the hashlib demo below does). It does not stop threads from overlapping waiting, and it does not make your own multi-step updates safe: counter += 1 on shared data can still interleave between threads, so you still need locks for correctness.
So the performance rule is:
- I/O-bound (mostly waiting on network or disk): threads or
asyncioare fine, because the GIL is released while waiting. - CPU-bound pure Python (parsing, number crunching in loops): threads do not speed it up; use processes, or move the hot loop into a C extension or library (NumPy, a compiled module) that releases the GIL.
Evidence
import hashlib, pickle, sys, time, sysconfig
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def py_cpu(n): # pure Python: holds the GIL while it runs
x = 0
for i in range(n):
x += i * i
return x
def sha_cpu(buf): # hashlib releases the GIL for large buffers
h = hashlib.sha256()
for _ in range(40):
h.update(buf)
return h.hexdigest()
def timed(label, pool_cls, workers, fn, args):
t = time.perf_counter()
with pool_cls(workers) as ex:
list(ex.map(fn, args))
print(" %-34s %5.2f s" % (label, time.perf_counter() - t))
if __name__ == "__main__":
print(sys.version.split()[0], "GIL disabled build:", sysconfig.get_config_var("Py_GIL_DISABLED"))
W = 4
jobs = [3_000_000] * W
print("pure-Python CPU work, %d jobs" % W)
t = time.perf_counter(); [py_cpu(n) for n in jobs]
print(" %-34s %5.2f s" % ("sequential", time.perf_counter() - t))
timed("%d threads" % W, ThreadPoolExecutor, W, py_cpu, jobs)
timed("%d processes" % W, ProcessPoolExecutor, W, py_cpu, jobs)
buf = b"x" * (8 * 1024 * 1024)
bufs = [buf] * W
print("hashlib.sha256 on 8 MiB buffers (releases the GIL), %d jobs" % W)
t = time.perf_counter(); [sha_cpu(b) for b in bufs]
print(" %-34s %5.2f s" % ("sequential", time.perf_counter() - t))
timed("%d threads" % W, ThreadPoolExecutor, W, sha_cpu, bufs)
print("cost of going multi-process")
t = time.perf_counter()
with ProcessPoolExecutor(1) as ex:
ex.submit(int, 1).result()
print(" %-34s %5.2f s" % ("first task incl. worker start", time.perf_counter() - t))
big = list(range(2_000_000))
t = time.perf_counter(); blob = pickle.dumps(big); pickle.loads(blob)
print(" pickle round trip of 2M ints (%d MB): %.2f s" % (len(blob) // 10**6, time.perf_counter() - t))
t = time.perf_counter()
with ProcessPoolExecutor(1) as ex:
ex.submit(sum, big).result()
print(" send 2M-int list to a worker, sum it: %.2f s" % (time.perf_counter() - t))
Sample run, docker run --rm --cpus=4 on python:3.12-slim (Python 3.12.15). Timings are from a shared, noisy host:
3.12.15 GIL disabled build: None
pure-Python CPU work, 4 jobs
sequential 0.34 s
4 threads 0.31 s
4 processes 0.12 s
hashlib.sha256 on 8 MiB buffers (releases the GIL), 4 jobs
sequential 0.45 s
4 threads 0.12 s
cost of going multi-process
first task incl. worker start 0.00 s
pickle round trip of 2M ints (9 MB): 0.06 s
send 2M-int list to a worker, sum it: 0.12 s
The shape: for pure Python, four threads take about as long as running the jobs one after another, while four processes finish in well under half the time (less than the full 4x because starting processes and returning results costs something). For the hashlib work that releases the GIL, threads do speed up. On one CPU the threads took about the same time as sequential and the processes were no faster (slightly slower, from start-up cost), since one core is the limit; with more CPUs the process speedup on four jobs was real but varied from run to run on a shared host, because only four jobs exist to run in parallel and process start-up is a fixed cost. GIL disabled build: None means this is a standard build with the GIL.
When to use processes
Use processes when the work is CPU-bound pure Python and you want multi-core throughput, when you want isolation (a crash, a memory leak or a stuck C library kills one worker, not the service), or when the web server model is already one process per worker. Many Python web servers are pre-fork: a parent starts N worker processes up front and each handles requests on its own, which gives multi-core throughput with no GIL contention between workers. A common arrangement is N processes (about one per core) each running a small thread pool or an event loop for I/O overlap.
What going multi-process costs
- Data crosses a process boundary by serialization.
ProcessPoolExecutorusesmultiprocessing, and per the docs only picklable objects can be sent and returned (no lambdas or local functions). Arguments and results are pickled (turned into bytes) and unpickled, which costs CPU time proportional to size: in the sample, a 2-million-int list (about 9 MB pickled) took 0.06 s to pickle and unpickle, and sending it to one worker and summing took 0.12 s, far more than the sum itself would take. If the job is cheaper than moving its data, processes lose. Send small arguments (an id, a file path) and let each worker load its own data, or use shared memory for large arrays. - Memory is multiplied. Each worker is a full interpreter with its own heap. A start method is how a new worker process comes into being:
forkcopies the running parent process;spawnstarts a fresh interpreter that imports your code again;forkserverasks a small helper process, started early while it is still clean, to fork each new worker. With theforkstart method (the default on Linux up to Python 3.13; since 3.14 the Linux default isforkserver, and code that needsforkmust ask for it explicitly, as the script below does) the child shares the parent's memory pages with the parent until one side writes to them, a scheme called copy-on-write: the OS gives the writer its own private copy of just that page. Reading Python objects still writes to them, because every object carries a reference count (a counter of how many references point at it) and evenlen(s)temporarily bumps and drops that counter. So the sharing erodes. This shipped script measures it with PSS (proportional set size: each shared page is divided among the processes that share it, so two processes sharing a 100 MB region are charged 50 MB each). The script reads thePss:line of Linux's/proc/self/smaps_rollup, which is in kB, hence the division by 1024 to get MB:
import multiprocessing as mp, os
def pss_mb():
for line in open("/proc/self/smaps_rollup"):
if line.startswith("Pss:"):
return int(line.split()[1]) / 1024
DATA = [str(i) * 3 for i in range(1_500_000)] # built before the fork, shared copy-on-write
def worker(touch, q):
before = pss_mb()
if touch:
n = 0
for s in DATA: # read-only use: len() of each object
n += len(s)
q.put((before, pss_mb()))
if __name__ == "__main__":
mp.set_start_method("fork")
print("parent PSS: %.0f MB" % pss_mb())
for touch in (False, True):
q = mp.Queue()
p = mp.Process(target=worker, args=(touch, q)); p.start()
b, a = q.get(); p.join()
print("child that %s the shared list: PSS before %.0f MB, after %.0f MB" % ("reads" if touch else "ignores", b, a))
Sample run (same container image): parent PSS: 117 MB, child that ignores the shared list: PSS before 60 MB, after 60 MB, child that reads the shared list: PSS before 60 MB, after 106 MB. Why the numbers move: the parent's 117 MB is measured before any child exists, so every page is the parent's alone. Right after the fork, parent and child share nearly all pages, so each is charged about half of the shared total, which is why the child's "before" is 60 MB, roughly half of 117 (the parent's own charge falls to a similar figure at that point). When the child only ignores the list, nothing is written and the 60 MB stays. When it reads every string, the reference-count writes force the OS to copy the pages that hold the strings, those copies become private to the child and are charged to it in full, and its charge rises to 106 MB. The child that only read the list pulled most of it into private memory. Budget memory per worker accordingly, not as "parent plus a little".
3. Start-up and warm-up. In the sample, with fork, starting a worker took a few milliseconds. The spawn method (the default on macOS and Windows) starts a fresh interpreter and re-imports your modules, which the docs describe as slower than fork; and per the docs, forking a process that already has threads is problematic and Python 3.12 emits a DeprecationWarning for it. Warm caches, connection pools and loaded models are per worker, not shared, so open database connections per process and watch the total (workers x pool size) against the database's connection limit.
4. Coordination and state. Shared in-memory caches, counters and locks need an external store or explicit shared memory. Debugging and tracing span processes.
5. Oversubscription. More processes than real cores stops helping, as in any CPU-bound pool.
Free-threaded builds
The GIL rule above describes the default CPython build that production servers run today; the free-threaded build is the one place it changes.
PEP 779 describes the free-threaded (GIL-less) build as experimental in Python 3.13 and sets the criteria for it to become officially supported, but still optional, in 3.14, the release the PEP targets for that step. The default build keeps the GIL. Check at runtime with sys._is_gil_enabled() (documented in the free-threading how-to). Adopting it means your dependencies must support it; a pure-Python thread pool could then use several cores, but threads would then also expose more of your own races.
Recommendation
For a typical I/O-heavy service keep threads or asyncio; add a process-per-core layer (pre-fork) for CPU-bound work or to use all cores, offload the heavy compute to a process pool or a native library, and size workers by cores and memory, not by hope. If the work is a long CPU job per request, a job queue with worker processes avoids tying request latency to a process pool.
You are moving a synchronous Python service to asyncio, but its database driver blocks. How can you keep the event loop responsive, and what does each way out cost you?
Sample Answer
The problem
asyncio runs all coroutines on one thread, the event loop. A coroutine (a function declared with async def, which can pause and resume) only yields control at an await (the point where it pauses and lets other coroutines run). A blocking driver call (one that waits on a socket without await) freezes the whole loop for its duration, so every other request waits (this is head-of-line blocking). There are five ways out, each moving the wait somewhere else. Options 1, 2 and 4 are the usual choices; option 3 applies only to CPU-bound work and option 5 to blocking code that cannot be changed.
The options and what each costs
| Option | How | Costs |
|---|---|---|
| 1. Offload to the default thread pool | await asyncio.to_thread(call, ...) or loop.run_in_executor(None, call, ...) | One thread per in-flight call; the pool is shared and small by default; the thread cannot be cancelled; the driver must be safe to use from threads |
| 2. Offload to a dedicated, bounded thread pool (a bulkhead: a separate pool reserved for one kind of work, so a flood of it cannot use up the capacity other work needs) | loop.run_in_executor(db_pool, call, ...) with your own ThreadPoolExecutor | One more pool to size and monitor; still a thread per in-flight call |
| 3. Offload to a process pool | ProcessPoolExecutor | Only helps CPU work; arguments and results must be picklable (convertible to bytes by Python's pickle); a database connection cannot be sent between processes, so each process needs its own |
| 4. Use an async driver | for example asyncpg or psycopg 3's async API | Code and query-layer rewrite, ORM (object-relational mapper, a library that turns database rows into objects) and library support to check; a connection pool is still needed; a different transaction and error-handling surface |
| 5. Keep the blocking code out of the loop entirely | a separate (sync) service or worker, reached over the network or a queue | Network hop, another deployment, serialization, new failure modes |
Evidence for the thread-pool options
Per the Python docs, run_in_executor(None, ...) uses the loop's default ThreadPoolExecutor, and that executor's default size is min(32, os.cpu_count() + 4). This script shows what that means:
import asyncio, os, time
from concurrent.futures import ThreadPoolExecutor
def db_call(ms):
time.sleep(ms / 1000) # a blocking driver call
return ms
async def timed(coro, label):
t = time.perf_counter()
await coro
print(" %-46s %5.0f ms" % (label, (time.perf_counter() - t) * 1000))
async def main():
loop = asyncio.get_running_loop()
print("os.cpu_count() =", os.cpu_count(), " default max_workers =", min(32, os.cpu_count() + 4))
# 1. 100 concurrent 100 ms blocking calls on the default executor
await timed(asyncio.gather(*(asyncio.to_thread(db_call, 100) for _ in range(100))),
"100 x 100 ms on the default executor")
# 2. A slow batch starves a fast request: 40 slow calls, then one 5 ms call
async def slow_batch():
await asyncio.gather(*(asyncio.to_thread(db_call, 500) for _ in range(40)))
async def fast_call():
await asyncio.sleep(0.05)
await timed(asyncio.to_thread(db_call, 5), "5 ms call submitted behind the slow batch")
await asyncio.gather(slow_batch(), fast_call())
# 3. Bulkhead: slow work gets its own small executor, fast work keeps the default one
slow_pool = ThreadPoolExecutor(8, thread_name_prefix="slow-db")
async def slow_batch_isolated():
await asyncio.gather(*(loop.run_in_executor(slow_pool, db_call, 500) for _ in range(40)))
async def fast_call_isolated():
await asyncio.sleep(0.05)
await timed(asyncio.to_thread(db_call, 5), "5 ms call, slow work on its own pool")
await asyncio.gather(slow_batch_isolated(), fast_call_isolated())
slow_pool.shutdown()
# 4. Cancelling the awaiting task does not stop the thread
finished = []
def slow_call():
time.sleep(0.3)
finished.append(True)
task = asyncio.create_task(asyncio.to_thread(slow_call))
await asyncio.sleep(0.05)
task.cancel()
try:
await task
except asyncio.CancelledError:
print(" task cancelled; thread finished yet?", bool(finished))
await asyncio.sleep(0.4)
print(" 0.4 s later, thread finished:", bool(finished))
asyncio.run(main())
Sample run, docker run --rm --cpus=4 on python:3.12-slim (Python 3.12.15). Timings are from a noisy host and the host has 14 CPUs, so the default pool is 18 threads:
os.cpu_count() = 14 default max_workers = 18
100 x 100 ms on the default executor 616 ms
5 ms call submitted behind the slow batch 955 ms
5 ms call, slow work on its own pool 10 ms
task cancelled; thread finished yet? False
0.4 s later, thread finished: True
What it shows:
- 100 blocking calls of 100 ms through 18 threads take about ceil(100/18) = 6 rounds, so roughly 600 ms; an async driver with a connection pool of 100 could overlap all of them in about 100 ms. That gap is the cost of the thread pool: concurrency of waiting is capped by the pool size.
- 40 slow (500 ms) calls fill the default pool and queue ahead of one fast 5 ms call; the fast call finished after about 955 ms because it waited behind the queued slow work. The arithmetic: 40 slow calls on 18 threads run as waves of 18, 18 and 4, 500 ms each; the fast call, submitted at 50 ms, queues behind all 40 and starts in the third wave at 1,000 ms, runs 5 ms, and so finishes at about 1,005 ms, which is 955 ms after it was submitted. This is pool exhaustion: the default executor is shared by everything that offloads, so one slow query class starves the rest. Giving the slow work its own 8-thread pool (the bulkhead) left the fast call at about 10 ms, at the cost of the slow batch taking longer (it is limited to 8 at a time).
- Cancelling the awaiting task (for example on a client timeout) did not stop the thread:
thread finished yet? Falseright after the cancel, thenTrue0.4 s later. The call still occupies a thread and a database connection until it returns, so timeouts must also be set in the driver or database (a statement timeout is a database setting that aborts any query running longer than a given time), not only inasyncio.
At --cpus=1 the same script gave the same shape (606 ms, 957 ms, 6 ms) because the work is waiting, not computing; it would change only if the offloaded work were CPU-bound.
Sizing the offload pool
Use Little's law: concurrent calls = arrival rate x call duration. At 200 queries/s of 20 ms each (hypothetical), 200 x 0.020 = 4 calls in flight, so a pool of 8 gives twice the headroom needed. A thread pool larger than the database connection pool does not help: the extra threads would just wait for a connection. So size the executor to match the connection pool (here a database pool of 8 connections and an executor of 8 threads, which is also the 2x headroom above), and bound how many requests wait for it (an asyncio.Semaphore, a counter that lets at most N coroutines proceed and makes the rest wait, or a bounded queue in front), so overload shows up as fast failures or timeouts rather than an ever-growing backlog. Keep CPU-heavy work off these threads.
Recommendation
Right now: wrap the blocking calls in run_in_executor with a dedicated, bounded executor sized to the database pool, so the event loop stays responsive and one slow path cannot starve the rest; set statement timeouts in the database. That is the smallest change that keeps the service correct. Then move the hot paths to an async driver, which removes the thread-per-call ceiling (the 100-call example above) and the cancellation problem. A process pool is the wrong tool for database waits, and a separate service is justified only when the blocking code cannot be changed (a vendor library) or needs different scaling.
What would flip this: if the number of simultaneous in-flight calls is large (thousands) the thread pool's memory and context-switch cost makes the async driver necessary; if the blocked call is CPU-heavy (for example big result parsing) a process pool or native library is the right offload.
Unlock Full Question Bank
Get access to all 9 Concurrency & Asynchronous Performance interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.