Concurrency & Asynchronous Performance Questions
How concurrency choices change throughput, latency and resource use in server-side software. Covers sizing and choosing thread pools and executors for CPU-bound versus I/O-bound work, including bounded queues, rejection policies and work-stealing pools, event-loop behavior and what blocks it, offloading blocking calls, the GIL and process-versus-thread trade-offs, connection and worker pool limits and exhaustion under a slow dependency, lock contention and how to find it (perf, eBPF, flamegraphs), lock sharding and striping, lock convoys, spinning versus blocking and backoff, head-of-line blocking, request coalescing so concurrent callers share one fetch, scheduling pipeline stages across pools, and the coordination costs that cap parallel speedup. Focuses on the performance consequences of concurrency design rather than the correctness theory of synchronization or any one language's API. Primitives and deadlock theory, per-language concurrency APIs, async syntax and promise semantics, message-driven system design, and database isolation are covered elsewhere.
What is head-of-line blocking? Describe where it shows up in server software (a single event loop, a shared FIFO work queue, a multiplexed connection) and how you would stop one slow request from delaying fast ones.
Sample Answer
What head-of-line blocking is
Head-of-line (HOL) blocking is what happens when work waits behind the item at the front of a line that cannot move yet, even though the waiting work could be finished immediately if it were allowed to go first. The line is anything that is served in order: a queue, a single thread, a byte stream. The slow item at the head is the "head-of-line"; everything behind it inherits its delay. The cost lands on the fast requests, so tail latency (the slow end of the latency distribution) rises while the average barely moves. Tail latency is usually quoted as p99, the latency that 99 percent of requests beat (p50 is the median). A related name is the convoy effect: many short jobs trail one long job like cars behind a slow truck.
Where it appears in server software
- A single event loop. An event loop is one thread that runs every ready callback in turn, switching between requests only when a handler waits (
await). A handler that blocks (a synchronous library call, a big JSON parse, a long loop) never yields, so every other connection served by that loop is the line behind it. - A shared FIFO work queue. A thread pool (a fixed set of reusable worker threads) pulls jobs from one first-in-first-out queue. If all workers are busy with slow jobs, a 10 ms job queues behind them. The effect grows when slow jobs are a small share of arrivals but a large share of the work.
- A multiplexed connection. Multiplexing means sending many requests over one connection. In short: HTTP/2 removes the blocking at the HTTP layer, but the TCP connection underneath still delivers bytes strictly in order, so one lost packet holds up every stream; HTTP/3 removes that too. In HTTP/1.1 a connection carries one response at a time, in request order, so one slow response delays the ones behind it on that connection (the introduction of RFC 9113 describes pipelined HTTP/1.1 as still suffering from application-layer head-of-line blocking). HTTP/2 gives each request its own stream, which removes that application-level blocking. It does not remove it at the transport: the same introduction notes that TCP head-of-line blocking is not addressed by HTTP/2, and RFC 9114 section 1.1 explains why: TCP's loss recovery cannot see the streams, so one lost packet stalls all active transactions on that connection. HTTP/3 runs over QUIC (a transport protocol built on UDP, which has no ordering of its own), which provides reliability per stream, so a lost packet stalls only the streams whose data it carried (RFC 9114 section 1.2).
Reproducing it: a slow handler on one event loop
The program below sends a fast request every 10 ms for 600 ms. At the sixth tick one slow request arrives. In the first run its handler blocks the loop (time.sleep). In the second it is moved to a worker thread with asyncio.to_thread. A second part simulates a shared queue (random arrivals, seed 7, 2% of jobs take 400 ms and 98% take 10 ms) with a plain event-driven calculation, so its numbers are deterministic.
import asyncio, heapq, random, time
# ---- Part 1: one slow handler on a single event loop ----
async def fast_handler(arrived, results):
await asyncio.sleep(0.001) # pretend 1 ms of non-blocking I/O
results.append(time.perf_counter() - arrived)
async def slow_blocking():
time.sleep(0.300) # blocking call: nothing else on the loop runs
async def slow_offloaded():
await asyncio.to_thread(time.sleep, 0.300) # runs on a worker thread, loop stays free
async def run(slow):
results, tasks = [], []
async def arrivals():
for i in range(60): # one fast request every 10 ms for 600 ms
if i == 5:
tasks.append(asyncio.create_task(slow()))
tasks.append(asyncio.create_task(fast_handler(time.perf_counter(), results)))
await asyncio.sleep(0.010)
await arrivals()
await asyncio.gather(*tasks)
results.sort()
return results
async def part1():
for name, slow in (("blocking call on the loop", slow_blocking), ("offloaded to a thread", slow_offloaded)):
r = await run(slow)
print("%-26s fast requests=%d median=%6.1f ms worst=%6.1f ms" % (name, len(r), r[len(r)//2]*1000, r[-1]*1000))
# ---- Part 2: shared FIFO queue vs separate pools (deterministic simulation, seed 7) ----
def simulate(jobs, workers_for):
"""jobs: list of (arrival_s, service_s, kind). workers_for(kind) -> pool id. Pools: dict id -> worker count."""
pools, pool_of = workers_for
free = {p: [0.0]*n for p, n in pools.items()} # next-free time of each worker
lat = {"fast": [], "slow": []}
for arr, svc, kind in jobs: # jobs already sorted by arrival, FIFO per pool
p = pool_of(kind)
heapq.heapify(free[p])
start = max(arr, heapq.heappop(free[p]))
heapq.heappush(free[p], start + svc)
lat[kind].append(start + svc - arr)
return lat
def pct(xs, q):
xs = sorted(xs); return xs[min(len(xs)-1, int(q*len(xs)))]
def part2():
rnd = random.Random(7)
t, jobs = 0.0, []
for _ in range(4000):
t += rnd.expovariate(60) # 60 requests/s on average
slow = rnd.random() < 0.02 # 2% slow
jobs.append((t, 0.400 if slow else 0.010, "slow" if slow else "fast"))
# offered work: 60 * (0.02*0.4 + 0.98*0.01) = 1.068 worker-seconds per second
layouts = {
"one shared FIFO, 3 workers ": ({"all": 3}, lambda k: "all"),
"fast pool 2 + slow pool 1 ": ({"fast": 2, "slow": 1}, lambda k: k),
}
for name, layout in layouts.items():
lat = simulate(jobs, layout)
print("%s fast p50=%6.1f ms p99=%7.1f ms slow p99=%7.1f ms" % (
name, pct(lat["fast"], .5)*1000, pct(lat["fast"], .99)*1000, pct(lat["slow"], .99)*1000))
print("offered load = %.3f worker-seconds per second" % (60*(0.02*0.4+0.98*0.01)))
if __name__ == "__main__":
asyncio.run(part1())
part2()
How simulate computes latency: free[p] is a heap holding the time each worker in pool p next becomes free, so heappop returns the worker that frees up first. A job starts at max(arrival, that time), meaning immediately if a worker is idle and otherwise when one frees up; that worker is then busy until start + service, which is pushed back on the heap; and the job's latency is start + service - arrival, its queue wait plus its own run time. Jobs are processed in arrival order, which is what makes each pool a FIFO queue. Arrivals use expovariate(60), random gaps averaging 1/60 s (about 60 requests per second), and the fixed seed 7 makes the same jobs appear every run. Tiny example with one worker: a 400 ms job arrives at 0.00 s and a 10 ms job at 0.01 s; the second starts at 0.40 s and its latency is 0.40 + 0.01 - 0.01 = 0.40 s, forty times its own run time.
Run in a python:3.12-slim container, it prints (the first two lines are timings and vary from run to run; the simulation lines are the same every run):
blocking call on the loop fast requests=60 median= 1.5 ms worst= 307.8 ms
offloaded to a thread fast requests=60 median= 1.5 ms worst= 4.0 ms
one shared FIFO, 3 workers fast p50= 10.0 ms p99= 187.6 ms slow p99= 715.4 ms
fast pool 2 + slow pool 1 fast p50= 10.0 ms p99= 18.7 ms slow p99= 1505.4 ms
offered load = 1.068 worker-seconds per second
Read it carefully. The median fast request is unaffected in both runs; only the worst case changes, from about the length of the blocking call (300 ms) to a few milliseconds. In the queue simulation, splitting 3 workers into 2 fast and 1 slow cut the fast p99 from 187.6 ms to 18.7 ms, and it did so at a price: the slow class now has one worker and its p99 doubled (715 ms to 1505 ms). Isolation moves the queueing to the class that can afford it; it does not create capacity. Total offered work is 1.068 worker-seconds per second on 3 workers (about 36% utilised), so the machine was not overloaded in either layout.
Stopping one slow request from delaying fast ones
Apply these in order of how much they usually buy (the first two are the main levers, the later ones refine them):
- Never block the loop. Move blocking or CPU-heavy work to a thread pool (
asyncio.to_thread, a Node worker thread) or a separate process. Confirm with a loop-lag measurement (how late a timer fires). - Separate pools per latency class. Give slow or unpredictable operations (reports, exports, calls to a flaky dependency) their own bounded pool and queue so they can only exhaust themselves. Size the fast pool for the fast work's rate times its latency (Little's law: requests in flight = arrival rate x time in system).
- Bound the queue and set timeouts. A request that has waited longer than its client will wait should be dropped, not processed. Bound the slow pool's queue and answer overflow with a fast 503 or 429.
- Prioritise or shard. A priority queue lets short or interactive jobs overtake, at the price of starving the low-priority class unless you cap its wait. Sharding (routing by key or by request type to separate queues) keeps one hot tenant from filling everyone's queue.
- Break the slow job up. Chunk a large job and re-enqueue between chunks, so the line moves.
- At the protocol layer, prefer HTTP/2 or HTTP/3 to HTTP/1.1 where clients and proxies support them, and keep several connections available to latency-critical traffic so a lost packet or a large response on one stream does not hold everything.
Recommendation and what would change it
Fix the one that is cheapest and cuts the tail most: take blocking calls off the loop, then split slow work into its own bounded pool with a timeout, and verify by watching fast-class p99 while injecting a slow request (as the program does). If the slow class is itself latency-sensitive, a split is the wrong tool and a priority queue with an aging rule is better.
Your service shows lock convoys and long tail latencies under certain workloads. What is a lock convoy, why does it inflate tail latency, and what remedies would you weigh, such as shorter critical sections, backoff, fair versus unfair locks, sharding or lock-free structures, and what does each cost?
Sample Answer
What a lock convoy is
A mutex (mutual-exclusion lock) lets one thread at a time run a critical section (the code that must not run concurrently). A lock convoy is a steady state in which many threads queue behind one lock and the system's throughput is set by how fast the lock is handed over, not by how long the protected code takes. Threads form a line, and the line does not drain even though each critical section is tiny.
The mechanism, in the order it happens:
- Thread A holds the lock. Threads B, C and D try to acquire it, fail, and park (the OS removes them from the CPU and puts them to sleep until woken; on Linux the Java and pthread locks do this through futexes, short for fast userspace mutexes: a Linux kernel facility that puts a thread to sleep on a memory word only if the word still holds the value the thread expected, until another thread explicitly wakes it, while an uncontended lock never enters the kernel; HotSpot's
parkreaches futexes through the C library's mutexes and condition variables). - A releases the lock and must wake B. Waking is a system call plus a scheduler decision plus, usually, a context switch (the OS saving one thread's registers and loading another's). That takes microseconds, while the critical section took nanoseconds.
- With a handoff (fair, FIFO) lock the lock is promised to B. A, having just released, immediately loops back for its next request, finds B ahead of it in the queue (the lock is reserved for B even before B has run), and joins the back of the queue. The lock is now never free for a running thread: every acquisition needs a wake-up first, so each one costs about one wake-up latency.
- With a barging (unfair) lock A can re-take the lock before B has even been scheduled. That avoids the wake-up cost on the fast path, but B can lose repeatedly.
Why this inflates tail latency (the slow end of the latency distribution, such as p99, the value 99% of requests beat): a request arriving behind a queue of N threads waits roughly N hand-overs, so its wait grows with queue length, and queue length is highest exactly when load is bursty. Median requests that hit a free lock see nothing, so averages look fine while p99 and p99.9 climb. Also, if a thread holding the lock is descheduled by the OS (preempted) or stalls on a page fault (the OS has to load a memory page that is not resident) or garbage collection pause, everyone behind it waits for that whole stall.
Shipped experiment
The program below makes 2, 8 and 32 threads each loop: take a lock, run a tiny critical section (20 loop iterations), release, then do 400 iterations of work outside the lock. It compares three guards: one unfair ReentrantLock, one fair ReentrantLock(true), and 16 unfair locks selected by thread id (sharding, also called striping). It records each acquisition's wait, and each thread's operation count.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
public class LockConvoy {
static volatile long sink;
static void spin(int n) { long x = sink; for (int i = 0; i < n; i++) x = x * 31 + i; sink = x; }
interface Guard { void lock(int key); void unlock(int key); }
static Guard single(boolean fair) {
ReentrantLock l = new ReentrantLock(fair);
return new Guard() {
public void lock(int k) { l.lock(); }
public void unlock(int k) { l.unlock(); }
};
}
static Guard striped(int n) {
ReentrantLock[] ls = new ReentrantLock[n];
for (int i = 0; i < n; i++) ls[i] = new ReentrantLock(false);
return new Guard() {
public void lock(int k) { ls[k % n].lock(); }
public void unlock(int k) { ls[k % n].unlock(); }
};
}
static void run(String name, Guard g, int threads, int millis) throws Exception {
final int CAP = 1_000_000;
long[][] waits = new long[threads][CAP];
int[] counts = new int[threads];
CountDownLatch go = new CountDownLatch(1);
long[] endAt = new long[1];
Thread[] ts = new Thread[threads];
for (int t = 0; t < threads; t++) {
final int id = t;
ts[t] = new Thread(() -> {
try { go.await(); } catch (InterruptedException e) { return; }
int n = 0;
while (System.nanoTime() < endAt[0] && n < CAP) {
long t0 = System.nanoTime();
g.lock(id);
long t1 = System.nanoTime();
spin(20); // critical section
g.unlock(id);
waits[id][n++] = t1 - t0;
spin(400); // work outside the lock
}
counts[id] = n;
});
ts[t].start();
}
endAt[0] = System.nanoTime() + millis * 1_000_000L;
long start = System.nanoTime();
go.countDown();
for (Thread t : ts) t.join();
double secs = (System.nanoTime() - start) / 1e9;
long total = 0; for (int c : counts) total += c;
long[] all = new long[(int) total]; int p = 0;
for (int t = 0; t < threads; t++) for (int i = 0; i < counts[t]; i++) all[p++] = waits[t][i];
Arrays.sort(all);
int minOps = Integer.MAX_VALUE, maxOps = 0;
for (int c : counts) { minOps = Math.min(minOps, c); maxOps = Math.max(maxOps, c); }
System.out.printf("%-12s threads=%-3d ops/s=%9.0f wait p50=%7.1f us p99=%8.1f us p99.9=%9.1f us max=%9.1f us ops/thread min..max=%d..%d%n",
name, threads, total / secs, all[(int)(total*0.50)]/1e3, all[(int)(total*0.99)]/1e3, all[(int)(total*0.999)]/1e3, all[(int)total-1]/1e3, minOps, maxOps);
}
public static void main(String[] a) throws Exception {
System.out.println("java " + System.getProperty("java.version") + " availableProcessors=" + Runtime.getRuntime().availableProcessors());
int[] tc = {2, 8, 32};
for (int threads : tc) {
run("unfair", single(false), threads, 300);
run("fair", single(true), threads, 300);
run("striped-16", striped(16), threads, 300);
}
}
}
Run in an eclipse-temurin:21-jdk container (Temurin OpenJDK 21.0.12.1, 4 available processors as the first output line shows) with javac LockConvoy.java && java -Xmx1g LockConvoy, one sample run printed:
java 21.0.12.1 availableProcessors=4
unfair threads=2 ops/s= 5698366 wait p50= 0.0 us p99= 0.2 us p99.9= 0.7 us max= 76.2 us ops/thread min..max=854888..855135
fair threads=2 ops/s= 1063050 wait p50= 0.0 us p99= 19.7 us p99.9= 26.9 us max= 379.7 us ops/thread min..max=146995..171982
striped-16 threads=2 ops/s= 5239694 wait p50= 0.0 us p99= 0.3 us p99.9= 0.7 us max= 68.0 us ops/thread min..max=779385..792986
unfair threads=8 ops/s= 3356147 wait p50= 0.0 us p99= 0.1 us p99.9= 80.7 us max= 13996.0 us ops/thread min..max=106046..163325
fair threads=8 ops/s= 309682 wait p50= 9.2 us p99= 88.5 us p99.9= 231.0 us max= 18890.5 us ops/thread min..max=11554..11732
striped-16 threads=8 ops/s= 4308946 wait p50= 0.0 us p99= 0.3 us p99.9= 0.3 us max= 61029.1 us ops/thread min..max=143783..201307
unfair threads=32 ops/s= 3009804 wait p50= 0.0 us p99= 0.1 us p99.9= 0.1 us max= 50432.3 us ops/thread min..max=6264..56987
fair threads=32 ops/s= 543888 wait p50= 41.9 us p99= 170.6 us p99.9= 1231.6 us max= 2246.2 us ops/thread min..max=5054..5234
striped-16 threads=32 ops/s= 3406556 wait p50= 0.1 us p99= 0.8 us p99.9= 1.3 us max= 89108.7 us ops/thread min..max=1503..81255
How to read each line: ops/s is lock acquisitions completed per second across all threads; wait p50, p99, p99.9 and max are percentiles of the time a thread spent between asking for the lock and getting it (p99.9 means the slowest 1 in 1,000 acquisitions); ops/thread min..max is the fewest and the most acquisitions completed by any single thread in the 300 ms window. A narrow min..max means every thread got an equal share; a wide one means some threads were starved while others kept winning, which is the starvation signal that a pooled percentile can hide.
These figures are host-dependent (a container on a shared VM is a noisy host) and are one sample, not constants: re-runs pinned to 1, 2, 4 and 8 CPUs with --cpuset-cpus changed the numbers below by large factors, so only the shape is stated. A CPU set is not a --cpus quota, which throttles in time slices and behaves differently: with --cpus=2 the sharded configuration came out below the single unfair lock in re-runs (about 0.5x to 0.75x of its throughput at 8 threads and about 0.25x to 0.4x at 32), where on a 2-CPU set it was ahead of it (about 1.3x to 1.8x). Say which of the two limits a benchmark ran under.
- Fair lock: throughput is lower than the unfair lock once threads queue, by an amount that varies from run to run (in the sample, about 11x lower at 8 threads and about 5.5x lower at 32; re-runs pinned to 2, 4 and 8 CPUs gave roughly 6x to 20x lower at 8 threads and about 4x to 7x lower at 32). The median wait of a fair-lock acquisition is about 30 to 50 us at 32 threads on 2 or more CPUs, and from 0 to tens of microseconds at 8 threads. The wait grows with the number of waiters, which is the convoy. At 2 threads on 2 or more CPUs the fair lock was always slower, from under 2x to about 50x lower in throughput, a wide spread because each handoff waits for a parked thread to be woken and scheduled and a noisy host can delay that for milliseconds. Per-thread operation counts are usually much closer together than under the unfair lock (5054..5234 at 32 threads in the sample; in re-runs on 2 or more CPUs the busiest thread's count at 32 threads ranged from nearly equal to about 6x the quietest thread's, and at 8 threads up to about 5x), but they are not guaranteed equal: a thread the OS has descheduled still falls behind. The Javadoc says a fair lock guarantees lack of starvation for lock requests but that "fairness of locks does not guarantee fairness of thread scheduling", which is what a descheduled thread shows.
- Unfair lock: high throughput and near-zero median wait, but per-thread counts spread widely at 32 threads (6264..56987 in the sample; in re-runs on 2 or more CPUs the busiest thread completed from about 3x to about 20x the quietest thread's count, occasionally much more, with one thread getting almost nothing). Some threads barge repeatedly while others rarely get in. On 4 or more CPUs the fair lock's near-equal counts show that every thread was running, so the unfair lock's spread there is the lock's doing. A starved thread's tail is not visible in an aggregate percentile, so look at per-thread or per-request-class latency too. On 1 or 2 CPUs a low count can instead be a scheduling artefact: the sharded configuration, which has almost no contention, showed a thread with zero acquisitions at 32 threads in every re-run, and recording each thread's first loop entry and CPU time shows why, because those threads had not started their loop when the 300 ms window ended. On 1 CPU the unfair lock's slowest thread also sometimes completed only one or a handful of acquisitions (such threads began their loop late in the window and then waited on the lock until it closed), while the fair lock's slowest thread usually completed thousands, so on one CPU a per-thread count says as much about the scheduler as about the lock. The
maxcolumn is dominated by OS descheduling on a shared host and should not be quoted. - Sharded: with 8 threads the ids 0 to 7 land on 8 different locks, so there is no collision at all by construction (with 32 threads two threads share each lock). At 8 and 32 threads on 4 to 8 CPUs its throughput was about 1.5x to 3x the single unfair lock's; on 1 or 2 CPUs it ranged from somewhat below to nearly 2x. Real keys hash unevenly, so a real workload will collide more than this one. The
min..maxspread at 32 threads (1503..81255 in the sample) shows that scheduling still skews which threads run in a 300 ms window. - With one CPU (
--cpuset-cpus=0): only one thread runs at a time, so a waiting thread cannot be running in parallel anyway. With 2 threads the two locks were in the same range (a few million ops/s each, host-dependent, with neither consistently ahead). At 8 and 32 threads the fair lock was about 1.4x to 4x slower than the unfair lock, much less than on several CPUs, because each handoff still needs a park and a wake-up once several threads queue, and results on one CPU are noisy. The unfair and sharded locks had a median wait of 0 because a thread seldom waits while it holds the only CPU; the fair lock's median wait was 0 at 2 threads, between 0 and about 10 us at 8 and from 0 up to about 40 us at 32. With more CPUs the gap widens mainly because the fair lock gets slower (each handoff must wake a parked thread and get it scheduled on another CPU), while the unfair lock's throughput stays in much the same range.
The Java documentation (ReentrantLock, Java SE 21) states the trade directly: a fair lock favours the longest-waiting thread, programs using fair locks "may display lower overall throughput (i.e., are slower; often much slower)" but "have smaller variances in times to obtain locks and guarantee lack of starvation" (the time to get the lock varies less from one acquisition to the next, and no waiting thread is passed over forever). It also notes the untimed tryLock() ignores the fairness setting and will take a free lock even when others wait.
Remedies and what each costs
In order of what to try first: shorter critical sections and sharding, which cut contention without giving up fairness; then an unfair lock or backoff where waking threads is the cost; then LongAdder-style structures for counters and maps; a fair lock and hand-written lock-free code are for specific needs. The table gives each remedy's cost.
| Remedy | Why it helps | What it costs |
|---|---|---|
| Shorter critical sections | The lock is held less, so arrivals collide less and queues drain faster. Move I/O, logging, allocation and serialisation outside; copy the data under the lock and process it after release. | Needs the invariant to survive the split (data copied under the lock may be stale afterwards). Does nothing if the cost is the hand-over, not the hold time. |
Backoff (spin briefly, then park; randomised exponential delay between retries; tryLock with a timeout) | Avoids a park and wake for locks that free up within nanoseconds, and de-synchronises threads so they do not all retry at once. | Burns CPU while spinning, and a spinner holds a core that could run useful work. A timeout adds a failure path the caller must handle. |
| Unfair (barging) lock | Releaser may re-acquire with no wake-up, so handovers do not each wait on a sleeping thread and the queue does not move in lock-step, as the near-zero median waits in the sample show. | Possible starvation of individual threads and a worse worst case for them. A fair lock is the right choice only when bounded wait per request matters more than throughput, and then the fix is usually to reduce contention rather than to keep the fair lock hot. |
| Fair (FIFO) lock | Bounded, evenly spread wait. | Each handoff is a wake-up, so it is the configuration that builds the convoy under load. A ticket lock is the spinning form of the same idea: each arrival takes a number and the lock serves numbers in order. It is fair and simple, but if the next ticket holder is descheduled, every thread behind it spins uselessly until it runs again. |
| Sharding (striping) | Splits one hot lock into N locks by key (user id hash, partition), so the collision probability drops by about N. | Operations spanning shards need all their locks in a fixed order (or a global lock), a hot key still serialises on its shard, and aggregate reads must visit every shard. |
| Lock-free structures and adders | No lock to queue on, so a descheduled thread cannot block the rest. For counters, LongAdder keeps several internal cells (separate counters that threads update independently, with sum() adding them up): per the Java docs, under high contention its expected throughput is "significantly higher" than AtomicLong, "at the expense of higher space consumption", and sum() is not an atomic snapshot. | A compare-and-swap (CAS: write only if the value is still what I read) loop can retry many times under heavy contention, so CPU is spent but progress per thread is not guaranteed. Harder to write correctly: the ABA problem (a value changes from A to B and back to A, so a CAS sees "unchanged" although the state moved in between) and memory ordering (the rules for when one thread's writes become visible to others, and in what order) are easy to get wrong, and only some operations have good lock-free forms. |
What to recommend
For a service with convoy-shaped tails, work in this order: first confirm it is a convoy (next section), then shrink the critical section and shard the hot state, because both reduce contention without trading away fairness. Prefer a library structure such as LongAdder or ConcurrentHashMap for counters and maps over hand-written lock-free code. Keep a default unfair lock where the data is not shared across request classes, and use a fair lock only on a path where a starved request violates an SLO (service-level objective, a latency target), and only after reducing contention. What would flip this: if profiling shows the time is spent inside the critical section (a slow call under the lock), shortening the section beats every other option; if keys are heavily skewed to one hot key, sharding barely helps and a per-key combining technique or a lock-free adder is the better route.
Proving it is a convoy and that the fix worked
- Look at lock wait time, not just CPU. Java: a Java Flight Recorder (JFR, the JVM's built-in profiler) recording shows
jdk.JavaMonitorEnterevents (a thread blocked trying to enter asynchronizedblock),jdk.JavaMonitorWaitevents (a thread sleeping inObject.wait) and, forReentrantLockwaits,jdk.ThreadParkevents (a thread parked). These events are only recorded for waits longer than a threshold, 20 ms in the default JFR settings and 10 ms in the profile settings, so a convoy whose waits are microseconds shows almost nothing until the threshold is lowered (for example-XX:StartFlightRecording:jdk.ThreadPark#threshold=0ms, which makes the event count jump by orders of magnitude for the program above); thread dumps (jstack) taken a few seconds apart show many threads parked on the same lock owner. - Check the signature: low CPU use and high latency together, with many threads waiting and a short critical section. Compare p50 against p99.9 (the median against the slowest 1 in 1,000 requests).
- Change one thing (shard count, a shorter section), re-run the same load at the same arrival rate, and compare p99 and p99.9 and the per-thread spread, across several runs, since a single run on a shared host is noisy.
An async API server goes from healthy to timing out on every endpoint within minutes of one downstream dependency slowing down, while CPU stays low. Which shared resources could be saturating, how would you tell which one it is, and how would you contain the blast radius next time?
Sample Answer
Why everything times out while CPU is low
An async server runs many requests on a few threads. A request that is waiting holds almost no CPU, but it can hold a shared, finite resource: a database connection, an outbound HTTP connection, a thread-pool slot, a file descriptor (fd, the OS handle for an open file or socket), or a lock. When the dependency slows from 20 ms to seconds, each request holds its resource a hundred times longer or more (150 times at 3 s). By Little's law (requests in the system = arrival rate x time each spends in it), the number held rises in proportion to latency: 30 requests/s that held a resource for 0.02 s occupy 0.6 of it on average, and at 3 s they want 90. A pool of 20 is exhausted within a second, new requests queue for a connection, and endpoints that never touch the slow dependency fail too because they share the pool. Low CPU is the signature: the process is waiting, not working.
Which shared resources could be saturating
The usual explanations in this pattern are items 1 to 3: a shared pool that something holds across a slow call. Items 4 to 7 are worth ruling out but explain fewer incidents.
- A database connection pool shared by all endpoints (above all if a request holds a connection while it calls something else).
- An outbound HTTP client pool or per-host connection limit.
- A thread pool used for blocking calls (all workers parked on the slow call).
- File descriptors / sockets: open connections accumulate; the per-process limit on open files and sockets (
ulimit -nshows it) or the kernel's ephemeral ports (the temporary local port numbers it hands out to outgoing connections, a finite range) run out. Errors read "too many open files". - A lock or a shared cache whose critical section includes a call to the slow dependency.
- The event loop itself, if retries or a flood of timeouts keep it busy (usually shows as high CPU on one core, so it is not this case, but rule it out).
- The database's own limit: all instances together can ask for more connections than the database allows. PostgreSQL's
max_connections(the server-wide cap on simultaneous client connections) defaults to typically 100, with some slots reserved for superusers (PostgreSQL docs).
Reproducing the blast radius
A semaphore is a counter of free slots: acquire() takes one and waits when none are left, release() returns one. Here it models a connection pool. asyncio.wait_for(x, t) gives up on x after t seconds, and asyncio.shield lets the server's work continue after the caller has stopped waiting.
The program models one server instance: a shared pool of 20 database connections, three endpoints (a calls a dependency, b and c only use the database for 5 ms), 90 requests/s, a 1 s caller timeout. Endpoint a holds a connection while it waits for the dependency. Reading the code: Server.db takes a pooled connection, uses it for work_s seconds and returns it, recording how long it waited for the connection. handle for endpoint a either holds a connection while it waits on the dependency (hold_conn_during_call, the anti-pattern) or calls the dependency first and takes a connection only afterwards. call_dependency optionally adds a timeout and a bulkhead (a small separate semaphore, so a slow dependency can fill only its own compartment). one_request counts a request as failed if the caller's 1 s timeout passes. Four scenarios follow, then the sizing arithmetic. The server keeps working after a caller times out, as most real servers do.
import asyncio, time
POOL_SIZE = 20 # shared database connection pool of one server instance
ACQUIRE_TIMEOUT = 0.5 # how long a request waits for a pooled connection
CLIENT_TIMEOUT = 1.0 # the caller gives up after this
RATE = 90 # requests per second, spread evenly over endpoints a, b, c
DURATION = 5.0
class Server:
def __init__(self, dep_latency, hold_conn_during_call, bulkhead, dep_timeout):
self.pool = asyncio.Semaphore(POOL_SIZE)
self.dep_latency = dep_latency
self.hold = hold_conn_during_call
self.dep_slots = asyncio.Semaphore(bulkhead) if bulkhead else None
self.dep_timeout = dep_timeout
self.db_wait = [] # time spent waiting for a pooled connection
async def db(self, work_s):
t = time.perf_counter()
await asyncio.wait_for(self.pool.acquire(), ACQUIRE_TIMEOUT)
self.db_wait.append(time.perf_counter() - t)
try:
await asyncio.sleep(work_s)
finally:
self.pool.release()
async def call_dependency(self):
if self.dep_slots is not None:
if self.dep_slots.locked():
raise RuntimeError("bulkhead full: fail fast")
await self.dep_slots.acquire()
try:
coro = asyncio.sleep(self.dep_latency)
await (asyncio.wait_for(coro, self.dep_timeout) if self.dep_timeout else coro)
finally:
if self.dep_slots is not None:
self.dep_slots.release()
async def handle(self, endpoint):
if endpoint != "a":
await self.db(0.005) # b and c only need the database
return
if self.hold: # anti-pattern: hold a connection while waiting on the dependency
await asyncio.wait_for(self.pool.acquire(), ACQUIRE_TIMEOUT)
try:
await self.call_dependency()
finally:
self.pool.release()
else:
await self.call_dependency()
await self.db(0.005)
async def one_request(server, endpoint, stats):
t = time.perf_counter()
task = asyncio.create_task(server.handle(endpoint)) # the server keeps working after the client leaves
try:
await asyncio.wait_for(asyncio.shield(task), CLIENT_TIMEOUT)
stats[endpoint]["ok"] += 1
except Exception:
stats[endpoint]["fail"] += 1
task.add_done_callback(lambda f: f.exception() if not f.cancelled() else None)
async def scenario(name, **kw):
server = Server(**kw)
stats = {e: {"ok": 0, "fail": 0} for e in "abc"}
cpu0, t0 = time.process_time(), time.perf_counter()
tasks = []
for i in range(int(RATE * DURATION)):
tasks.append(asyncio.create_task(one_request(server, "abc"[i % 3], stats)))
await asyncio.sleep(1 / RATE)
await asyncio.gather(*tasks)
cpu = (time.process_time() - cpu0) / (time.perf_counter() - t0)
waits = sorted(server.db_wait) or [0]
print("%-46s" % name, " ".join("%s ok %3d%%" % (e, 100 * s["ok"] // (s["ok"] + s["fail"])) for e, s in stats.items()),
" pool wait p95 %5.0f ms cpu %2.0f%%" % (waits[int(.95 * (len(waits) - 1))] * 1000, 100 * cpu))
async def main():
await scenario("dependency healthy (20 ms)", dep_latency=0.02, hold_conn_during_call=True, bulkhead=0, dep_timeout=0)
await scenario("dependency slow (3 s), conn held", dep_latency=3.0, hold_conn_during_call=True, bulkhead=0, dep_timeout=0)
await scenario("slow, conn NOT held across the call", dep_latency=3.0, hold_conn_during_call=False, bulkhead=0, dep_timeout=0)
await scenario("slow, held + timeout 0.3 s + bulkhead 5", dep_latency=3.0, hold_conn_during_call=True, bulkhead=5, dep_timeout=0.3)
# sizing arithmetic with stated, hypothetical inputs
instances, per_instance_pool, max_connections = 12, POOL_SIZE, 100
print("\nconnections if every instance fills its pool: %d x %d = %d (database max_connections %d)"
% (instances, per_instance_pool, instances * per_instance_pool, max_connections))
rate_a, normal_latency = RATE / 3, 0.02
print("normal in-flight calls to the dependency (Little's law): %.0f x %.2f = %.1f" % (rate_a, normal_latency, rate_a * normal_latency))
print("if the call takes 3 s, in-flight calls without a cap: %.0f x 3 = %.0f" % (rate_a, rate_a * 3))
asyncio.run(main())
Run in a python:3.12-slim container with --cpus=1, it printed (percentages for b and c in the second row vary widely from run to run, roughly from 10% to 35%, and a stays at 0%; the pool-wait p95 in that row is usually just under the 0.5 s acquire timeout but can read as low as 0 ms, because it is taken only over the acquisitions that succeeded; CPU stays in the low single digits throughout):
dependency healthy (20 ms) a ok 100% b ok 100% c ok 100% pool wait p95 0 ms cpu 1%
dependency slow (3 s), conn held a ok 0% b ok 26% c ok 32% pool wait p95 495 ms cpu 2%
slow, conn NOT held across the call a ok 0% b ok 100% c ok 100% pool wait p95 0 ms cpu 3%
slow, held + timeout 0.3 s + bulkhead 5 a ok 0% b ok 100% c ok 100% pool wait p95 0 ms cpu 1%
connections if every instance fills its pool: 12 x 20 = 240 (database max_connections 100)
normal in-flight calls to the dependency (Little's law): 30 x 0.02 = 0.6
if the call takes 3 s, in-flight calls without a cap: 30 x 3 = 90
Reading the second row: endpoint a takes 30 of the 90 requests per second and holds a connection for 3 s each, so about 30 x 3 = 90 connections are wanted against 20 available; the 20 are taken within about a second, everyone else queues for a connection until the 0.5 s acquire timeout, and b and c queue with them. The healthy endpoints lose most of their requests and the pool-wait p95 is usually just under the 0.5 s acquire timeout (it counts only waits that ended in a connection, so it can read lower when few late ones succeed): the time is going into waiting for the shared pool, not into the dependency, for these endpoints. In the last two rows a still fails (the dependency really is down) but b and c are untouched. The 12 instances x 20 connections figure uses hypothetical inputs.
How to tell which resource it is
Checks 1 to 3 usually settle it; take them in this order, each with what it tells you:
- Is it the slow dependency? Compare latency of the endpoints that call it and those that do not. If unrelated endpoints fail too, a shared resource is the link.
- Pool metrics: active, idle, waiting count and wait time (HikariCP, a common Java connection pool, exposes them as metrics; SQLAlchemy, a Python database library, prints them from
pool.status();pg_stat_activityis a PostgreSQL view with one row per database session, showing its state and last state change). Active at maximum with a growing wait queue means pool exhaustion, and the wait-time histogram shows how long requests queue. - What the held connections are doing:
pg_stat_activityshowing many sessions in stateidle(oridle in transactionif the request opened a transaction and has not finished it) with oldstate_changetimes, while the pool metrics from check 2 show every connection borrowed, means requests hold connections while doing something else, such as an outbound call: the pattern in the second row. Read it together with check 2, because a connection that sits unborrowed in the pool also shows asidlewith an oldstate_change, so idle sessions alone do not prove they are held. - Thread dumps (
jstack,py-spy dump): many threads parked in the same frame (a socket read, a poolacquire) point at the saturated resource. - File descriptors and sockets:
ls /proc/<pid>/fd | wc -lagainstulimit -n, andss -s(a summary of socket counts by state) for socket states.TIME_WAITis the state a closed TCP connection lingers in for a short while, so a flood of short outbound connections piles them up and eats ephemeral ports./proc/<pid>/fdlists a process's open descriptors, one entry each, so counting its entries counts them. A worked reading: 1,020 entries against a limit of 1,024 would make the descriptor limit the saturated resource; 60 entries would rule it out. - Event loop lag and CPU per core: rules the loop in or out.
- Instance arithmetic: instances x pool size against the database's
max_connections. If the sum is larger, the pools together can exhaust the database even when each looks fine.
Containing the blast radius next time
- Do not hold a scarce resource across a call to something else. Take the connection, do the database work, release it, then call out (the third row).
- Timeouts on every outbound call, shorter than the caller's timeout, so a slow dependency costs seconds of a slot rather than minutes.
- Bulkheads: a separate, small, bounded pool or semaphore per dependency, sized from rate x normal latency with headroom (0.6 in flight normally, so 5 is generous) so a slow dependency can fill only its own compartment. Fail fast when it is full (the fourth row).
- Circuit breaker (named after the electrical device): after repeated failures or timeouts, stop calling the dependency for a while and return a fallback or an error immediately.
- Sized pools across the fleet: instances x pool size must fit under
max_connections(12 x 20 = 240 over 100 here), or use a connection proxy. - Load shedding (refusing some work early so the rest stays healthy) and alerts on pool wait time and in-flight count, so the page comes before the timeouts do.
Recommendation: ship 1 and 2 first (cheap, remove the failure mode), then bulkheads per dependency; add a circuit breaker once you have measured how the dependency fails.
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.
Design an adaptive backoff strategy for a highly contended lock on cloud VMs whose performance varies because of noisy neighbors. How do you choose between spinning and blocking, where do exponential backoff and jitter fit, and which metrics would you collect to tune the parameters automatically?
Sample Answer
The decision in one sentence
Spin only while the expected wait is shorter than the cost of parking and waking a thread, and only while the lock holder is actually running. Otherwise block. On a cloud VM the second condition can be false without the program knowing, so the spin budget must be learned from outcomes, not hard-coded.
Terms
A spinlock keeps the waiting thread running in a loop that retries the lock. trylock is the non-blocking attempt: it takes the lock if free and otherwise returns at once instead of sleeping. A test-and-set is the atomic instruction (one that no other core can interleave with) that sets a flag and reports its old value, the basis of the simplest spinlock. A blocking lock (a mutex that parks) puts the waiter to sleep in the kernel until the owner wakes it. Parking and waking cost on the order of microseconds plus two context switches (the kernel saves one thread's registers and loads another's), so for a critical section of tens of nanoseconds a spin is cheaper. But spinning burns a CPU while it waits. A vCPU is a virtual CPU that a hypervisor (the software that shares one physical machine among several virtual machines) schedules onto a real core. With noisy neighbours (other tenants on the same host) the hypervisor can pause a vCPU for milliseconds; Linux's /proc/stat calls that steal time ("Stolen time, which is the time spent in other operating systems when running in a virtualized environment", per proc_stat(5)). If the lock holder's vCPU is paused, every spinner burns its whole time slice waiting for a thread that is not running. That is the cost to design around.
Policy
- Spin phase, bounded by a budget. Retry with
trylock, with exponential backoff between attempts: pause 1 unit, then 2, 4, up to a cap (on x86 apauseinstruction; on Armyield), so retries do not hammer the lock's cache line (the 64-byte block of memory that cores pass between their caches; every failed attempt pulls it to the retrying core, which makes it bounce away from the owner). Add jitter (a random part on each pause) so threads that started together do not retry in lock step. The AWS Architecture Blog's post on exponential backoff and jitter explains why: without randomisation, clients back off for identical durations and retry at the same moment, so contention persists, and its measurements show jittered backoff cutting client work and server load substantially. - Block phase. When the budget runs out, park (
pthread_mutex_lock). - Adapt the budget from outcomes. The budget is counted in pause instructions (calls to
CPU_RELAXin the program), not in nanoseconds; how long one pause takes depends on the CPU, which is one reason to learn the budget instead of fixing it. If a spin acquired the lock, double the budget (up to a ceiling). If the budget was spent and the thread had to block, halve it (down to a floor). A long-held lock drives the budget down to the floor, so threads park almost immediately; a short-held lock drives it up. - Cut the budget to zero when steal time is high. Read the steal counter from
/proc/statonce per second; if the steal percentage crosses a threshold (a tuned value, for example a few percent), disable spinning on that host until it falls. Rationale: a paused holder invalidates the assumption that the lock will be released soon. - Oversubscription rule. If runnable threads exceed vCPUs, a spinner may be spinning on a lock whose holder is waiting for a CPU, which the spinner is occupying. Never spin when threads outnumber CPUs.
Shipped comparison: spin, block, adaptive
The program has 8 threads taking one lock 20,000 times each. It exercises steps 1 to 3 of the policy only: it never reads steal time and has no rule that looks at how many threads are runnable, so steps 4 and 5 are not implemented in it and no row below demonstrates them; they follow from the reasoning above. In ctx vol / invol (the last columns), vol counts voluntary context switches (the thread parked itself, as a blocked mutex waiter does) and invol counts involuntary ones (the kernel took the CPU away at the end of the time slice). memory_order_acquire and release on the spin flag are the memory-ordering labels that make writes inside the critical section visible to the next owner; they do not change the performance story. Mode spin is a test-and-set loop; block is a plain pthread_mutex_lock; adaptive is the policy above (steps 1 to 3). It records each acquire's wait, the process CPU time, and the context-switch counts.
// Spin vs block vs adaptive spin-then-block: 8 threads, one lock.
#define _GNU_SOURCE
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <sys/resource.h>
#define NTHREADS 8
#define OPS 20000
static int hold_loops = 300; /* critical section length, set from argv[1] */
static inline uint64_t now_ns(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + ts.tv_nsec;
}
/* CPU_RELAX: a hint to the CPU that this thread is busy-waiting; it saves power and gives a sibling hyper-thread room. */
#if defined(__x86_64__)
#define CPU_RELAX() __builtin_ia32_pause()
#elif defined(__aarch64__)
#define CPU_RELAX() __asm__ __volatile__("yield")
#else
#define CPU_RELAX() ((void)0)
#endif
/* SPIN: test-and-set loop. BLOCK: plain mutex. ADAPT: trylock with backoff, then block. */
enum mode { SPIN, BLOCK, ADAPT };
static enum mode g_mode;
/* atomic_flag_test_and_set atomically sets the flag and returns its old value: true means someone else holds it. */
static atomic_flag spin_lock_flag = ATOMIC_FLAG_INIT;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static volatile long shared;
typedef struct {
uint64_t *waits; long spin_ok, spin_fail;
unsigned seed; int budget; /* adaptive: spin budget, counted in CPU_RELAX() calls (pause/yield instructions) */
} tstate;
static void lock_adaptive(tstate *t) {
/* Exponential backoff with jitter between trylock attempts, bounded by a spin budget. */
int spent = 0, pause = 1;
while (spent < t->budget) {
if (pthread_mutex_trylock(&mtx) == 0) {
t->spin_ok++;
if (t->budget < 4096) t->budget *= 2; /* spinning pays: spin longer next time */
return;
}
int n = pause + (int)(rand_r(&t->seed) % (unsigned)pause); /* jitter: pause..2*pause-1; rand_r is a thread-safe random generator */
for (int i = 0; i < n; i++) CPU_RELAX();
spent += n;
if (pause < 64) pause *= 2;
}
t->spin_fail++;
if (t->budget > 16) t->budget /= 2; /* spinning did not pay: spin less */
pthread_mutex_lock(&mtx); /* park in the kernel */
}
static void *worker(void *arg) {
tstate *t = arg;
for (int i = 0; i < OPS; i++) {
uint64_t t0 = now_ns();
if (g_mode == SPIN) { while (atomic_flag_test_and_set_explicit(&spin_lock_flag, memory_order_acquire)) CPU_RELAX(); }
else if (g_mode == BLOCK) pthread_mutex_lock(&mtx);
else lock_adaptive(t);
t->waits[i] = now_ns() - t0;
for (int k = 0; k < hold_loops; k++) shared += k;
if (g_mode == SPIN) atomic_flag_clear_explicit(&spin_lock_flag, memory_order_release);
else pthread_mutex_unlock(&mtx);
}
return NULL;
}
static int cmp(const void *a, const void *b) { uint64_t x = *(const uint64_t*)a, y = *(const uint64_t*)b; return x < y ? -1 : x > y; }
static void run(const char *name, enum mode m) {
g_mode = m;
pthread_t th[NTHREADS]; tstate st[NTHREADS];
struct rusage r0, r1; getrusage(RUSAGE_SELF, &r0);
for (int i = 0; i < NTHREADS; i++) { memset(&st[i], 0, sizeof st[i]); st[i].waits = malloc(OPS * sizeof(uint64_t)); st[i].seed = 7 + i; st[i].budget = 64; }
uint64_t t0 = now_ns();
for (int i = 0; i < NTHREADS; i++) pthread_create(&th[i], NULL, worker, &st[i]);
for (int i = 0; i < NTHREADS; i++) pthread_join(th[i], NULL);
double wall = (now_ns() - t0) / 1e6;
getrusage(RUSAGE_SELF, &r1);
uint64_t *all = malloc((size_t)NTHREADS * OPS * sizeof(uint64_t)); size_t n = 0;
long ok = 0, fail = 0;
for (int i = 0; i < NTHREADS; i++) { memcpy(all + n, st[i].waits, OPS * sizeof(uint64_t)); n += OPS; ok += st[i].spin_ok; fail += st[i].spin_fail; free(st[i].waits); }
double cpu_ms = (r1.ru_utime.tv_sec - r0.ru_utime.tv_sec) * 1e3 + (r1.ru_utime.tv_usec - r0.ru_utime.tv_usec) / 1e3
+ (r1.ru_stime.tv_sec - r0.ru_stime.tv_sec) * 1e3 + (r1.ru_stime.tv_usec - r0.ru_stime.tv_usec) / 1e3;
qsort(all, n, sizeof *all, cmp);
printf("%-9s wall %7.1f ms | wait p50 %6.1f us p99 %8.1f us max %9.1f us | cpu %7.1f ms | ctx vol %6ld invol %6ld",
name, wall, all[n / 2] / 1e3, all[n * 99 / 100] / 1e3, all[n - 1] / 1e3, cpu_ms,
r1.ru_nvcsw - r0.ru_nvcsw, r1.ru_nivcsw - r0.ru_nivcsw);
if (m == ADAPT) printf(" | spin success %.0f%%", 100.0 * ok / (double)(ok + fail));
printf("\n");
free(all);
}
int main(int argc, char **argv) {
if (argc > 1) hold_loops = atoi(argv[1]);
printf("hold_loops=%d threads=%d\n", hold_loops, NTHREADS);
run("spin", SPIN); run("block", BLOCK); run("adaptive", ADAPT);
return 0;
}
Compiled with gcc -O2 -Wall -Wextra -pthread backoff.c in a gcc:14 container (aarch64), run as ./backoff 300 (critical section of 300 loop iterations, roughly 0.3 microseconds) with --cpuset-cpus=0-7 (8 CPUs for 8 threads), one sample run:
hold_loops=300 threads=8
spin wall 272.9 ms | wait p50 7.8 us p99 57.0 us max 2420.1 us | cpu 2129.3 ms | ctx vol 3 invol 368
block wall 66.2 ms | wait p50 0.0 us p99 25.2 us max 3587.1 us | cpu 128.2 ms | ctx vol 19182 invol 4162
adaptive wall 64.3 ms | wait p50 0.0 us p99 40.8 us max 2290.5 us | cpu 184.8 ms | ctx vol 20832 invol 5418 | spin success 85%
Run again as ./backoff 3000 (a critical section ten times longer, about 3 microseconds), one sample run on --cpuset-cpus=0-7:
hold_loops=3000 threads=8
spin wall 2420.7 ms | wait p50 69.0 us p99 533.6 us max 3656.5 us | cpu 19116.4 ms | ctx vol 4 invol 902
block wall 519.5 ms | wait p50 0.0 us p99 32.0 us max 27271.0 us | cpu 551.5 ms | ctx vol 8447 invol 403
adaptive wall 574.4 ms | wait p50 0.0 us p99 154.7 us max 55461.7 us | cpu 624.9 ms | ctx vol 13164 invol 971 | spin success 98%
The qualitative results across re-runs with 1, 2, 4 and 8 CPUs and with both critical-section lengths: spin was always the slowest in wall time (roughly 2x to 10x slower than block). The gap was widest with one CPU, where a spinning thread burns its whole slice waiting for a holder that cannot run, but it did not grow steadily as CPUs were removed: with 2 and 4 CPUs it was smaller than with 8. spin also consumed far more CPU than the others (in the first sample about 2.1 seconds of CPU against 0.13 to 0.18 seconds, and in the second about 19 seconds against about 0.6 seconds), because every waiting thread burns cycles instead of sleeping. Contended test-and-set also bounces the lock's cache line between cores, which is the likely reason spin was slow even with enough CPUs. block and adaptive finished in about the same wall time, with adaptive using about the same CPU or, with the short critical section on several CPUs, somewhat more, and adaptive's spin success rate stayed high (roughly 70 to 100 percent depending on the run and the CPU count). On this host and with this lock the adaptive policy did not beat the plain mutex; it matched it. These rows also do not isolate the adaptation itself: a variant with the budget frozen at its starting value of 64 behaved much like it, so the doubling and halving are not shown to matter here. What to ship: the plain blocking mutex by default, since it matched the adaptive lock here at less CPU and with no tuning; add the spin phase only if profiling shows holds under a microsecond or two that vary, and then keep the steal-time and oversubscription rules, which are what make spinning safe on a shared VM. Its value would show when the hold time is very short and varies, and in the steal-time rule that the plain mutex has no equivalent of; neither is exercised by the program. These numbers depend on the host and the noisy neighbours of the moment, so re-run on the target VM type. Note wait p50 of 0 for the mutex modes: a mutex is not fair, so a thread that just released often re-acquires at once, and the cost shows up as a long maximum wait for the unlucky threads. For a latency target, watch p99 and max, not the mean.
Metrics to collect and how to tune automatically
| Metric | What it tells you | Tuning action |
|---|---|---|
| Lock wait time p50, p99, max | The user-visible cost | Objective to minimise (p99) |
| Hold time p50, p99 | Whether spinning can ever pay | Floor the budget when hold p99 exceeds the park cost |
| Spin success rate (acquired while spinning / spin attempts) | Whether the budget is right | Raise budget above about 90 percent, lower it below about 50 percent (starting thresholds to tune, not constants) |
| Voluntary context switches per second | How often threads park | Rising with falling success means spin budget too small or hold too long |
| CPU time spent spinning | The price of spinning | Cap as a share of total CPU |
Steal time percent (/proc/stat) | Noisy neighbour or an overcommitted host | Disable spinning above a threshold |
| Runnable threads / vCPUs | Oversubscription | Never spin when above 1 |
Automatic tuning loop: keep the per-thread budget adjustment shown (fast, local, no coordination), and let a slow outer loop (every 10 to 60 seconds) move the budget ceiling and the steal threshold with a simple hill climb (nudge a setting a little, keep the change if p99 wait improved, undo it if not) on p99 wait, with a guard that rolls back when request latency worsens. Compare the settings with an A/B split (half the instances run each setting at the same time under the same traffic) across instances, since one VM's noisy neighbour can masquerade as a better setting.
What flips the recommendation: if profiling shows hold times above a few microseconds, or the host is heavily oversubscribed, drop spinning altogether and use the plain blocking mutex; a hot lock held that long wants sharding (fewer threads on each lock) more than a smarter wait.
Unlock Full Question Bank
Get access to all 16 Concurrency & Asynchronous Performance interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.