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 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.
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 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.
An in-memory cache takes heavy write traffic and stops scaling beyond a few threads. Profiling shows threads mostly waiting on one lock. How would you restructure it to scale, and what does each option cost you?
Sample Answer
Confirm the lock is the limit before changing anything
A lock (mutex) lets one thread at a time run a critical section, the code that touches shared data. Contention is threads queueing for it. The signature: throughput stops rising (or falls) as you add threads, CPU stays well below the core count, and threads show as blocked. Confirm with evidence:
- Thread dumps (
jstack <pid>several times): many threads in the stateBLOCKED (on object monitor)(the JVM's label for a thread waiting to enter asynchronizedblock) on the same lock address. - A lock profile: async-profiler (a sampling profiler for Java; its
-e lockoption profiles lock contention) reports the lock or monitor class and the nanoseconds spent entering it (async-profiler documentation), so it shows where threads wait; step 4 is what tells you whether the section itself is slow. - A scaling test: run 1, 2, 4, 8 threads and plot throughput. A flat or falling line while cores idle is the case described.
- Read the critical section: is anything slow inside it (allocation, logging, serialisation, I/O, a call out)? Moving that out is the cheapest fix.
The ceiling follows Amdahl's law: if a fraction f of every operation happens under the one lock, no number of threads can beat 1/f times the single-thread rate. With N threads the bound is 1 / (f + (1 - f) / N): the serial part f cannot be shared, and the rest shrinks N-fold. Worked for f = 0.30 and N = 8: 1 / (0.30 + 0.70 / 8) = 1 / (0.30 + 0.0875) = 2.58, shown as 2.6x. (us is microseconds.) The script computes the bound for a hypothetical operation of 1.0 us with 0.30 us under the lock, then the effect of splitting the lock into stripes (a stripe is one of several independent pieces, each with its own lock; the script's simplification: it assumes keys spread evenly and divides f by the stripe count).
# Hypothetical inputs: each operation takes 1.0 us in total, of which 0.30 us is spent holding the cache lock.
total_us, locked_us = 1.0, 0.30
f = locked_us / total_us
print("serial fraction f = %.2f, so throughput can never exceed 1/f = %.1fx the single-thread rate" % (f, 1 / f))
for stripes in (1, 4, 16, 64):
f_eff = f / stripes # keys spread evenly over independent locks
print("stripes=%2d effective f=%.4f bound on speedup with 8 threads: %.1fx"
% (stripes, f_eff, 1 / (f_eff + (1 - f_eff) / 8)))
Output:
serial fraction f = 0.30, so throughput can never exceed 1/f = 3.3x the single-thread rate
stripes= 1 effective f=0.3000 bound on speedup with 8 threads: 2.6x
stripes= 4 effective f=0.0750 bound on speedup with 8 threads: 5.2x
stripes=16 effective f=0.0187 bound on speedup with 8 threads: 7.1x
stripes=64 effective f=0.0047 bound on speedup with 8 threads: 7.7x
Four structures, measured
The bound is a ceiling for an ideal scheduler. The measurements below can sit under it, and with four or more cores the global lock even falls below one thread's rate, because Amdahl's formula ignores the cost of threads going to sleep and being woken when they fail to get the lock.
The program compares one global lock, a read-write lock (many readers or one writer), 64 lock stripes (the key picks one of 64 independent maps each with its own lock) and ConcurrentHashMap, under 90% writes on 100,000 keys, at 1, 2, 4 and 8 threads. Reading the code: Cache is the two-method interface all four share; xorshift is a cheap per-thread random-number generator, so the threads do not contend on a shared one; the CyclicBarrier makes every thread start together; sink is a result the loop keeps so the JIT (the JVM's run-time compiler, which can delete work whose result is unused) cannot remove the reads; the first pass is a warm-up so the JIT has compiled the hot code before the printed pass. CAS (compare-and-set) is a hardware instruction that changes a value only if it still holds what you expected, the basis of lock-free updates that ConcurrentHashMap uses in places.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class CacheScaling {
interface Cache { void put(int k, int v); Integer get(int k); }
// 1. one lock around everything
static class Global implements Cache {
final Map<Integer,Integer> m = new HashMap<>();
public synchronized void put(int k, int v) { m.put(k, v); }
public synchronized Integer get(int k) { return m.get(k); }
}
// 2. read-write lock (writers still exclusive)
static class RW implements Cache {
final Map<Integer,Integer> m = new HashMap<>();
final ReadWriteLock l = new ReentrantReadWriteLock();
public void put(int k, int v) { l.writeLock().lock(); try { m.put(k, v); } finally { l.writeLock().unlock(); } }
public Integer get(int k) { l.readLock().lock(); try { return m.get(k); } finally { l.readLock().unlock(); } }
}
// 3. lock striping: the key picks one of N independent maps, each with its own lock
static class Striped implements Cache {
final Map<Integer,Integer>[] maps; final Object[] locks;
@SuppressWarnings("unchecked")
Striped(int n) { maps = new Map[n]; locks = new Object[n];
for (int i = 0; i < n; i++) { maps[i] = new HashMap<>(); locks[i] = new Object(); } }
int s(int k) { return (k * 0x9E3779B9 >>> 16) % maps.length; }
public void put(int k, int v) { int i = s(k); synchronized (locks[i]) { maps[i].put(k, v); } }
public Integer get(int k) { int i = s(k); synchronized (locks[i]) { return maps[i].get(k); } }
}
// 4. the JDK's concurrent map (fine-grained internal locking and CAS)
static class Chm implements Cache {
final ConcurrentHashMap<Integer,Integer> m = new ConcurrentHashMap<>();
public void put(int k, int v) { m.put(k, v); }
public Integer get(int k) { return m.get(k); }
}
static double run(Cache c, int threads, int opsPerThread, int writePercent) throws Exception {
Thread[] ts = new Thread[threads];
CyclicBarrier start = new CyclicBarrier(threads + 1);
for (int t = 0; t < threads; t++) {
final int seed = t * 7919 + 1;
ts[t] = new Thread(() -> {
int x = seed; long sink = 0;
try { start.await(); } catch (Exception e) { return; }
for (int i = 0; i < opsPerThread; i++) {
x ^= x << 13; x ^= x >>> 17; x ^= x << 5; // xorshift: cheap per-thread random
int key = (x >>> 1) % 100_000;
if ((x & 0xFF) * 100 / 256 < writePercent) c.put(key, i);
else { Integer v = c.get(key); if (v != null) sink += v; }
}
if (sink == 42) System.out.print("");
});
ts[t].start();
}
start.await();
long t0 = System.nanoTime();
for (Thread t : ts) t.join();
double sec = (System.nanoTime() - t0) / 1e9;
return threads * (double) opsPerThread / sec / 1e6; // million ops per second
}
public static void main(String[] a) throws Exception {
System.out.println("availableProcessors = " + Runtime.getRuntime().availableProcessors() + ", 90% writes, 100k keys");
String[] names = {"one global lock", "read-write lock", "striped x64", "ConcurrentHashMap"};
for (int pass = 0; pass < 2; pass++) { // pass 0 warms up the JIT and is not printed
if (pass == 1) System.out.printf("%-18s %8s %8s %8s %8s (million ops/s by thread count)%n", "", "1", "2", "4", "8");
for (int n = 0; n < names.length; n++) {
StringBuilder sb = new StringBuilder(String.format("%-18s", names[n]));
for (int threads : new int[]{1, 2, 4, 8}) {
Cache c = switch (n) { case 0 -> new Global(); case 1 -> new RW(); case 2 -> new Striped(64); default -> new Chm(); };
double mops = run(c, threads, pass == 0 ? 300_000 : 4_000_000, 90);
sb.append(String.format(" %8.1f", mops));
}
if (pass == 1) System.out.println(sb);
}
}
}
}
One sample run in an eclipse-temurin:21-jdk container with --cpus=8 (OpenJDK 21; million operations per second; a noisy shared host, so absolute figures and even single-thread values differ from run to run):
availableProcessors = 8, 90% writes, 100k keys
1 2 4 8 (million ops/s by thread count)
one global lock 39.0 17.9 19.8 25.7
read-write lock 38.2 22.3 34.6 27.2
striped x64 26.1 40.7 93.6 59.3
ConcurrentHashMap 36.3 66.8 107.9 124.1
The shape, across re-runs at 1, 2, 4 and 8 CPUs (absolute figures swing by tens of percent between runs on a shared host, and a CPU set (--cpuset-cpus) gave different orderings from a CPU quota (--cpus) on one and two CPUs, so read the ordering, not the digits): with four or more cores, or a two-CPU quota, the global lock at 2 threads runs at roughly half its one-thread rate or less and stays below that rate out to 8 threads (threads spend time parking and waking), and striping and the concurrent map beat it from 2 threads up, typically by about 2 to 5 times at 2 and 4 threads (under 2 times at 2 threads in an occasional run). The concurrent map was usually the fastest row at 4 and 8 threads on 4 and 8 CPUs, but its 8-thread figure stayed within roughly a third either way of its 4-thread figure, so more threads than that did not buy more throughput even on 8 cores. Three rows need reading rather than explaining away. First, the read-write lock is erratic rather than a steady copy of the global lock: at 2 threads it is close to the global lock (often within half of it, in either direction), and at 4 and 8 threads it usually sat between the global lock and striping, sometimes close to striping at 8 threads (on two cores it was occasionally level with striping at 4 threads), so it is not reliably far below the striped map; its read path serves only the 10% of operations that are reads, and writers still exclude everyone. Second, single-thread figures are the least stable numbers in the table: striped x64 at one thread (26.1) is below the global lock (39.0) in this sample and in nearly all re-runs on 4 and 8 CPUs, though on one or two CPUs the two were close and either could lead, and a plausible reason is the extra work each operation does (computing the stripe, then touching one of 64 separate maps) that a single uncontended lock avoids, so treat the gap as a tendency, not a law. Third, striped x64 at 8 threads (59.3) is below its 4-thread figure (93.6), and on 8 CPUs that dip repeated in re-runs rather than washing out as noise, while the concurrent map stayed roughly level between 4 and 8 threads; the cause was not isolated here, so measure how this simple striped design scales from 4 to 8 threads on your own hardware. With one core there is no parallelism to unlock, so the order is not reliable and differed between a one-core CPU set and a one-CPU quota: striping gave no consistent gain over the global lock (ahead in some runs, behind in others), the read-write lock was ahead of the global lock at 4 and 8 threads in every re-run, and the concurrent map usually led the global lock on a one-core CPU set but trailed it at 8 threads under a one-CPU quota (every row is noisy, and striping cannot create CPU). With two cores the result depended on how they were given: under a two-CPU quota striping and the concurrent map beat the global lock by about 2 to 6 times at 2 threads, while on a two-core CPU set the global lock was often close to them or ahead at 2 threads, and its 2-thread rate was sometimes above its one-thread rate.
Options and what each costs
| Option | When it helps | What it costs |
|---|---|---|
| Shorten the critical section | Slow work (allocation, I/O, formatting) sits under the lock | Needs restructuring; compute outside, then lock only to publish |
| Lock striping (shards) | Keys are spread evenly | Whole-cache operations (size, iteration, eviction, snapshot) must touch all stripes; one hot key still serialises on its stripe; memory for N maps |
| Read-write lock | Reads dominate and the read section is long | Little for write-heavy loads (in the runs above it was close to the global lock at 2 threads and usually below striping at 4 threads on 4 and 8 CPUs, though it sometimes came close at 8); reader bookkeeping itself costs, and with very short read sections it can be slower than a plain lock |
Concurrent map (ConcurrentHashMap) | General case; reads do not block | size and similar are estimates under concurrent updates; compound operations need compute methods whose function must be short because other updates may block while it runs (class Javadoc) |
| Batching and per-thread buffers | Writes can be applied late (counters, statistics, a write-behind cache) | Readers may see stale data; buffered writes are lost on a crash; memory per thread |
| Optimistic or lock-free updates (compare-and-set, versioned entries) | Low conflict, tiny updates | Retries explode on a hot key; more complex to get right |
Recommendation
Start with the lock profile; if nothing slow is inside the section, replace the map with a concurrent one (or stripes if you need custom eviction per shard), because it fixes the measured failure at the least code. Use batching for write-behind data that tolerates staleness. Keep a read-write lock only if your own scaling test shows a read-dominated load. Verify the fix with the same 1, 2, 4, 8 thread test and by checking the lock profile no longer shows that lock on top. What flips the choice: a hot key (shard cannot spread it, so shorten the section or replicate), a need for exact size or consistent snapshots (stripes plus a global operation, or accept a coarse lock for those operations), or operating-system kernel code that runs in interrupt context (an interrupt handler is code that runs when hardware signals the CPU), where the code must not sleep, so a sleeping lock such as a mutex is not allowed there; use a spinlock (a lock that busy-waits instead of sleeping, in its interrupt-safe form when process-context code shares the data) held for a very short section, or per-CPU data (one copy of the data per CPU, needing no lock), to bound worst-case latency.
A server-side image pipeline runs fetch, decode, ML detection, annotate and render stages. How would you schedule the stages across thread pools to maximize throughput while keeping latency low for interactive requests? Discuss pool sizing per stage, batch sizes, backpressure between stages, prioritizing urgent requests, and memory limits.
Sample Answer
Principle: size each stage by what it consumes, then let the slowest stage set the pace
A pipeline moves at the speed of its bottleneck, the stage with the lowest capacity. The five stages consume different things, so they get different pools:
| Stage | Consumes | Pool type and size | Why |
|---|---|---|---|
| Fetch | Waiting on the network, almost no CPU | Many I/O workers (or async I/O): in-flight count = arrival rate x fetch time (Little's law) | Blocked threads cost memory, not CPU |
| Decode | CPU | About one worker per core at most | More threads than cores only add context switches (the OS swapping one thread for another on a core) |
| ML detection | An accelerator (a GPU or similar device that runs one large job much more efficiently than many small ones) or a shared model, usually one batch at a time | One batcher feeding the device; concurrency set by the device, not by cores | The device is the scarce resource |
| Annotate, render | CPU | Worker count near cores; can share the CPU budget with decode | Both are CPU-bound |
Backpressure means a full downstream queue slows the upstream stage instead of letting memory grow. Use bounded queues between stages, so a slow stage blocks the sender, and one admission limit (a semaphore, a counter of free slots that an image must take before it enters) on total images in flight, which is also the memory limit: in-flight images x decoded size.
Computed sizing (hypothetical inputs)
Which lever matters most: the bottleneck stage's capacity first (here the accelerator, set mostly by batch size), then the in-flight limit (it sets both memory and queueing latency), then pool sizes for the other stages, then priority and the maximum-wait timer, which only reshape latency once throughput is right.
The inputs below (40 ms fetch wait, 8 ms decode, accelerator 30 ms per batch plus 6 ms per image, 6 ms post-processing, 4 cores, a target of 120 images per second) are made-up numbers for the exercise, replace them with measured per-stage times. The script computes concurrency, core needs and the effect of batch size. Its last two columns are two different pictures of the batcher: the fill wait if it sat idle waiting for a batch to fill, and how many images arrive at the target rate while one batch is already running on the accelerator.
# Hypothetical stage costs (stated inputs, not measurements) for the pipeline.
FETCH_WAIT_MS = 40 # network wait, no CPU
DECODE_CPU_MS = 8
DETECT_SETUP_MS = 30 # per-batch fixed cost on the accelerator
DETECT_PER_IMG_MS = 6
POST_CPU_MS = 6 # annotate + render
CORES = 4
TARGET = 120 # images per second wanted
def detect_capacity(batch):
return 1000 / (DETECT_SETUP_MS / batch + DETECT_PER_IMG_MS)
print(f"target {TARGET} img/s on {CORES} cores")
print("fetch : in flight = rate x time (Little) =", round(TARGET * FETCH_WAIT_MS / 1000, 1), "requests -> I/O workers >= 5, no CPU used")
print("decode : cores needed =", round(TARGET * DECODE_CPU_MS / 1000, 2))
print("post : cores needed =", round(TARGET * POST_CPU_MS / 1000, 2))
print("CPU stages together :", round(TARGET * (DECODE_CPU_MS + POST_CPU_MS) / 1000, 2), "of", CORES, "cores")
print("batch accel img/s fill wait if the batcher idles arrivals while one batch runs")
for b in (1, 2, 4, 8, 12, 13, 16, 32):
fill = (b - 1) / TARGET * 1000
run_ms = DETECT_SETUP_MS + DETECT_PER_IMG_MS * b
print(f"{b:>5} {detect_capacity(b):>9.1f} {fill:>14.1f} ms {TARGET * run_ms / 1000:>16.1f}")
print("smallest batch that reaches the target:", next(b for b in range(1, 100) if detect_capacity(b) >= TARGET))
for cores in (1, 2, 4):
print(f"CPU-stage ceiling on {cores} core(s): {cores * 1000 / (DECODE_CPU_MS + POST_CPU_MS):.1f} img/s")
# Memory: hypothetical 1920 x 1080 RGB image decoded to 3 bytes per pixel, 48 images in flight.
img_mb = 1920 * 1080 * 3 / 1e6
print(f"decoded image {img_mb:.1f} MB; 48 in flight = {48 * img_mb:.0f} MB")
Run in a python:3.12-slim container (CPython 3.12), it prints:
target 120 img/s on 4 cores
fetch : in flight = rate x time (Little) = 4.8 requests -> I/O workers >= 5, no CPU used
decode : cores needed = 0.96
post : cores needed = 0.72
CPU stages together : 1.68 of 4 cores
batch accel img/s fill wait if the batcher idles arrivals while one batch runs
1 27.8 0.0 ms 4.3
2 47.6 8.3 ms 5.0
4 74.1 25.0 ms 6.5
8 102.6 58.3 ms 9.4
12 117.6 91.7 ms 12.2
13 120.4 100.0 ms 13.0
16 127.0 125.0 ms 15.1
32 144.1 258.3 ms 26.6
smallest batch that reaches the target: 13
CPU-stage ceiling on 1 core(s): 71.4 img/s
CPU-stage ceiling on 2 core(s): 142.9 img/s
CPU-stage ceiling on 4 core(s): 285.7 img/s
decoded image 6.2 MB; 48 in flight = 299 MB
Reading it: the CPU stages need 1.68 of 4 cores at the target, so they are not the limit. The accelerator is: with batch 1 it tops out at 27.8 img/s, and the smallest batch that reaches the 120 target is 13 (120.4 img/s); 16 gives 127 img/s with headroom. That is the batching trade-off in numbers: a bigger batch spreads the fixed 30 ms over more images (higher throughput) but takes longer to run and to fill.
How big a batch actually forms depends on the load, and the two columns explain it. Under a steady 120 img/s the accelerator is busy running the previous batch for 30 + 6 x 13 = 108 ms, and in that time 120 x 0.108 = 13 images arrive and queue up, so the next batch fills instantly from the backlog without anyone waiting for it. A batch of 13 is therefore self-consistent at the target rate: arrivals while it runs equal its size. If a batch happened to be smaller than that (say 3), capacity at that size would be about 1000 / (30 / 3 + 6) = 62 img/s, below the arrival rate, so the backlog grows and the next batch, which takes whatever has queued up to the batch limit, is bigger, until batches settle where capacity matches arrivals. The idle-batcher "fill wait" column (100 ms at 13) only applies when the queue is empty; then the batcher needs a maximum wait timer (20 ms in the program) that sends a partial batch so that a lone image is not held back. At light traffic that partial batch is small and capacity per image is poor, which is acceptable because the load is light. On 1 core the CPU stages cap the pipeline at 71 img/s, below the target, so with fewer cores the bottleneck moves from the accelerator to the CPU.
Simulation: batching, bulk versus interactive, priority lane
The Go program wires the stages with bounded queues and an admission limit of 48 images. Fetch and the accelerator are time.Sleep (they use no CPU); decode and post-processing spin on the CPU for their stated time. The costs are the simulated ones above, not a real model. A bulk producer keeps the pipeline full; 5 interactive requests per second arrive on top. In the third setup, interactive items go through a high-priority lane at every stage and flush the accelerator batch as soon as they arrive.
package main
import (
"fmt"
"runtime"
"sort"
"sync"
"time"
)
// Stage costs are SIMULATED: fetch and the accelerator sleep (they use no CPU), decode and
// post-processing spin on the CPU for the stated time so that cores really are the limit.
const (
fetchMs = 40
decodeMs = 8
setupMs = 30 // accelerator: fixed cost per batch
perImgMs = 6 // accelerator: cost per image in the batch
postMs = 6
maxWait = 20 * time.Millisecond // longest the batcher waits to fill a batch
inflight = 48 // total images allowed in the pipeline: the memory limit
)
type item struct {
interactive bool
start time.Time
}
func spin(ms int) {
end := time.Now().Add(time.Duration(ms) * time.Millisecond)
for time.Now().Before(end) {
}
}
// pq is a two-lane queue. A chan is a Go channel: a bounded pipe between goroutines (Go's lightweight threads).
// Receivers always take the high lane first.
type pq struct{ hi, lo chan item }
func newPQ() *pq { return &pq{make(chan item, 16), make(chan item, 16)} }
func (q *pq) send(it item, prio bool) {
if prio && it.interactive {
q.hi <- it
} else {
q.lo <- it
}
}
func (q *pq) recv() item {
// Step 1: non-blocking peek at the high lane. A select with a default case never waits.
select {
case it := <-q.hi:
return it
default:
}
// Step 2: high lane was empty, so block until either lane has an item. Using only this select would
// let Go pick at random when both lanes are ready, so a waiting high item could lose to a low one.
select {
case it := <-q.hi:
return it
case it := <-q.lo:
return it
}
}
func run(name string, batchMax int, prio bool, cores int, dur time.Duration) {
fetchQ, decodeQ, detectQ, postQ := newPQ(), newPQ(), newPQ(), newPQ()
done := make(chan item, 256)
sem := make(chan struct{}, inflight) // admission: bounds memory
var wg sync.WaitGroup
pool := func(n int, in *pq, work func(item) item, out *pq) {
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
it, ok := recvOrStop(in)
if !ok {
return
}
it = work(it)
if out != nil {
out.send(it, prio)
} else {
done <- it
}
}
}()
}
}
pool(16, fetchQ, func(it item) item { time.Sleep(fetchMs * time.Millisecond); return it }, decodeQ)
pool(cores, decodeQ, func(it item) item { spin(decodeMs); return it }, detectQ)
// Batcher: one accelerator, one batch at a time. An interactive item flushes the batch at once.
wg.Add(1)
go func() {
defer wg.Done()
for {
first, ok := recvOrStop(detectQ)
if !ok {
return
}
batch := []item{first}
deadline := time.After(maxWait) // channel that delivers one value after maxWait: the batch's wait budget
flush := prio && first.interactive
// Fill loop: keep adding items until the batch is full, the wait budget is spent, or an
// interactive item asks for an early flush (send the batch to the accelerator now).
fill:
for len(batch) < batchMax && !flush { // if a backlog is queued, items arrive instantly and the timer never matters
select {
case it := <-detectQ.hi:
batch = append(batch, it)
flush = prio
case it := <-detectQ.lo:
batch = append(batch, it)
case <-deadline:
break fill
}
}
time.Sleep(time.Duration(setupMs+perImgMs*len(batch)) * time.Millisecond)
for _, it := range batch {
postQ.send(it, prio)
}
}
}()
pool(cores, postQ, func(it item) item { spin(postMs); return it }, nil)
stop := make(chan struct{})
// Bulk producer: always has work, limited only by the in-flight cap (backpressure).
go func() {
for {
select {
case <-stop:
return
case sem <- struct{}{}:
fetchQ.send(item{false, time.Now()}, prio)
}
}
}()
// Interactive producer: 5 requests per second.
go func() {
t := time.NewTicker(200 * time.Millisecond)
for {
select {
case <-stop:
return
case <-t.C:
select {
case sem <- struct{}{}:
fetchQ.send(item{true, time.Now()}, prio)
case <-stop:
return
}
}
}
}()
var lat []float64
bulk := 0
t0 := time.Now()
for time.Since(t0) < dur {
it := <-done
<-sem
if it.interactive {
lat = append(lat, float64(time.Since(it.start).Microseconds())/1000)
} else {
bulk++
}
}
close(stop)
sort.Float64s(lat)
fmt.Printf("%-34s bulk %5.1f img/s | interactive n=%2d p50 %6.0f ms p99/max %6.0f ms\n",
name, float64(bulk)/dur.Seconds(), len(lat), lat[len(lat)/2], lat[len(lat)-1])
// goroutines are left to the process exit; this program is a one-shot experiment.
}
func recvOrStop(q *pq) (item, bool) { return q.recv(), true }
func main() {
fmt.Println("GOMAXPROCS =", runtime.GOMAXPROCS(0))
cores := runtime.GOMAXPROCS(0)
dur := 8 * time.Second
run("FIFO, batch 1", 1, false, cores, dur)
run("FIFO, batch 16", 16, false, cores, dur)
run("priority lanes, batch 16", 16, true, cores, dur)
}
Read it as: chan is Go's bounded queue between goroutines (lightweight threads); select waits on several channels and takes whichever is ready; recv first peeks at the high lane with a non-blocking select (the default case means "do not wait") and only then blocks on both lanes, which is why select appears twice: a single select over both lanes would choose at random when both are ready, and the high lane could lose. In the batcher, time.After(maxWait) is the wait budget, the fill loop adds items until the batch is full, the budget is spent, or an interactive item asks to flush (send the batch to the accelerator at once), and time.Sleep stands for the accelerator's run time. The semaphore channel sem is the admission window: a slot is taken before an image enters and returned when it leaves, so at most 48 images exist at once.
Compiled and run in a golang:1.23 container with go run pipeline.go and --cpuset-cpus=0-3 (GOMAXPROCS is the number of CPUs Go runs goroutines on at once, here 4), one sample run (host-dependent; repeat runs on 4 and 8 CPUs gave nearly the same figures. On 2 CPUs the batch-16 rows were the same or lower, about 85 to 118 img/s with FIFO and about 80 to 95 with priority lanes, because decode, post-processing and the batcher then compete for the cores. On one CPU, --cpuset-cpus=0, the CPU stages cap the pipeline as the script predicts: batch-16 FIFO ran at about 55 to 73 img/s, close to the 71 img/s ceiling the script computed, with an interactive median of about 0.55 to 0.75 s, priority lanes no longer cost bulk throughput there, and batch 1 was unchanged because the accelerator is its limit):
GOMAXPROCS = 4
FIFO, batch 1 bulk 20.4 img/s | interactive n=29 p50 2002 ms p99/max 2044 ms
FIFO, batch 16 bulk 113.4 img/s | interactive n=37 p50 409 ms p99/max 425 ms
priority lanes, batch 16 bulk 96.1 img/s | interactive n=38 p50 215 ms p99/max 346 ms
What the shape says:
- Batch 1 is accelerator-bound: bulk about 20 to 23 img/s plus about 4 interactive per second (n=29 to 31 in 8 s against about 39 requests issued at 5 per second: the missing ones arrived in the last two seconds of the window and were still in the pipeline when the measurement stopped, since each takes about 2 s) is about 26 img/s once all 5 interactive requests per second are counted, a little under the 27.8 img/s ceiling the script computed because real sleeps run slightly long. Every image, interactive or not, waits behind the full admission window: with 48 images allowed in flight at about 25 completions per second, a new request waits about 48 / 25 = 1.9 seconds, which matches the 2002 ms (re-runs gave a median of about 1.75 to 2.1 s). (p99/max is the slowest 1 percent; with only about 30 samples it is simply the slowest request.) The memory cap is also the latency cap: bounding in-flight work bounds the queue wait, and a smaller cap gives lower latency at the same throughput, but only while the cap stays above what the bottleneck needs in flight. By Little's law that need is the throughput times the unloaded time through the pipeline. For batch 1 the pipeline sustains under 28 img/s through a path of about 90 ms, so only about 3 images need to be in flight, and shrinking the cap from 48 to 12 cut the interactive median to roughly 0.5 seconds with about the same bulk throughput. For batch 16 at the 120 target the unloaded path is about 40 + 8 + (30 + 6 x 16) + 6 = 180 ms, so roughly 120 x 0.18 = 22 images must be in flight at the very least. That is a floor, not a target: the batcher also needs the next batch already waiting while the current one runs, so a cap of 12 gave about half the bulk throughput of a cap of 48 (about 60 against about 115 img/s) and even a cap of 24, just above the floor, gave only about three quarters of it (about 88 img/s). Choose a cap well above the floor (48 came close to the 127 img/s the accelerator can do at batch 16), then trim it only as far as the latency and memory budgets require.
- Batch 16 is about 5 to 6 times the bulk throughput (113 against 20 img/s in the sample) and interactive latency falls to about 400 ms, because the pipeline now drains the window much faster (Little's law again: 48 in flight at about 120 completions per second is about 0.4 s).
- Priority lanes roughly halve the interactive median (to about 200 to 290 ms in re-runs on 4 and 8 CPUs, against about 380 to 415 ms) at a cost to bulk throughput (about 94 to 102 against 113 to 120 img/s on 4 and 8 CPUs; on one CPU there is no such cost, because the CPU stages are the limit and the batch size is not), because each interactive arrival flushes a smaller batch and the fixed 30 ms is spread over fewer images. Interactive latency does not fall to its unloaded value (about 40 + 8 + 36 + 6 = 90 ms of service), mainly because the accelerator cannot preempt (interrupt) a batch already running (and decode and post-processing may be busy spinning on a bulk item already in service): an interactive item waits for the batch in progress, up to 30 + 6 x 16 = 126 ms, plus its own 36 ms.
Decisions, stated
- Pool sizing per stage: fetch by Little's law (about 5 in flight here, round up with headroom), CPU stages about one worker per core, one batcher per accelerator.
- Batch size: the largest batch whose fill wait plus run time still fits the interactive latency budget; in the example, 8 gives 102.6 img/s (short of the 120 target) and 13 is the smallest that reaches it, so the target forces a batch of 13 or more (16 with headroom) unless a second accelerator is added. The maximum-wait timer protects latency when traffic is low.
- Backpressure: bounded queues between stages plus the in-flight limit; the producer blocks, or the API returns 429 when interactive admission is full, rather than growing a queue.
- Prioritising urgent requests: a separate high-priority lane at each queue and early batch flush, and reserve a slice of in-flight capacity for interactive work so bulk cannot fill the whole admission window. Because a running batch cannot be preempted, cap the bulk batch size, or give interactive work its own small accelerator slot, if the p99 matters more than bulk throughput.
- Memory limit: in-flight images x decoded size (299 MB for 48 images at 6.2 MB, hypothetical); decode only when the next stage can accept the image, and pass compressed bytes until then. Do not set the limit at or near the minimum of roughly the target rate x the unloaded time through the pipeline (about 22 images here): the batcher needs a whole batch queued behind the one it is running, and a limit of 24 still left bulk throughput about a quarter short.
What would change this: if the detector is CPU-based and not an accelerator, it joins the CPU budget (decode + detect + render share the cores) and the sizing becomes one cores-limited pool with priorities; if a stage is separately scalable (its own service), size and autoscale it independently.
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.