Course contents

15. Performance Engineering Lesson 5 of 8

Concurrency

See threads as concurrent slots, why blocking I/O caps throughput, what async I/O changes, why CPU-bound work does not scale with threads, and lock contention.

16 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Max throughput = concurrent slots ÷ time each request holds a slot.
  • With blocking I/O a waiting request still holds a thread; I/O-bound services run out of threads long before CPU.
  • Async I/O and virtual threads make waiting cheap, so the limit moves to CPU, memory and downstream capacity.
  • For CPU-bound work, concurrency beyond the core count only adds queueing and context switches.
  • A critical section admitting one request at a time caps throughput at 1 ÷ its duration; shrink it or split the shared state.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Concurrency is the number of requests (or tasks) a system has in progress at the same time. It is not the same as parallelism, which is how many are actually executing on hardware at the same instant: a server with 4 cores can have 1,000 requests in progress, of which at most 4 are running on a CPU while the rest wait for a database, a network reply or a lock.

Every service has concurrency limits: thread pools, connection pools, in-flight request limits, worker counts, and shared resources that only one request can use at a time.

Why it exists

Most backend requests spend most of their time waiting: on databases, other services, disks. If a server could only work on one request at a time, it would sit idle during every wait. Concurrency lets it overlap those waits. How a runtime implements concurrency (threads, event loops, coroutines) determines how cheap each waiting request is, and therefore which limit you hit first.

How it works

Slots and hold time. By Little's law, a resource with N concurrent slots, each held for T seconds per request, completes at most N ÷ T requests per second. A pool of 4 threads, each held 103 ms per request, tops out near 39 req/s; with 32 threads near 310 req/s.

Blocking I/O (thread per request). The thread calls the database and is suspended until the answer arrives. It uses no CPU while waiting, but it is not available to anyone else. An I/O-bound service with blocking calls hits its thread limit while the CPU is mostly idle, as the lesson shows (threads 100%, CPU under 15%). Raising the pool helps up to the point where per-thread memory (each platform thread has its own stack, commonly about 1 MB reserved on the JVM and 8 MB of virtual address space by default on Linux), scheduler overhead, or the downstream system becomes the problem.

Non-blocking I/O. Event-loop runtimes (Node.js, Netty, Python asyncio, Rust's tokio) and green or virtual threads (Go goroutines, Java 21+ virtual threads) let a waiting request park as a small heap object; a handful of OS threads, typically one per core, run whichever requests are ready. In-flight requests become cheap, so concurrency is limited by memory and by explicit limits you set. The lesson's async step shows 300 req/s with about 38 requests in flight on 4 cores. The catch: anything that blocks an event-loop thread (CPU-heavy code, a blocking library call) stalls every request on that loop; virtual threads can be pinned to their carrier thread by some blocking operations.

CPU-bound work. If a request needs 10 ms of CPU, 4 cores complete at most 400 req/s. More threads or coroutines than cores do not raise that; they only lengthen the run queue and add context switches. The levers are less CPU per request, more cores, or more machines.

Contention. When requests need exclusive access to something shared (a row lock, a mutex, a single-writer partition, a global counter), that critical section is a stage with concurrency 1. Its throughput is 1 ÷ hold time, and requests queue for it no matter how many threads or cores exist. This is the practical face of Amdahl's law: the serialised fraction bounds the speedup. Cures: hold the lock for less time (no network calls inside transactions, atomic operations instead of read-modify-write), split the shared state (striped counters, sharding, per-partition ownership), or avoid sharing (immutable data, per-request state, commutative updates merged later).

Limits are also protection. A concurrency limit in front of a fragile dependency (a connection pool, a bulkhead, an in-flight limit) keeps a slow dependency from consuming every thread or exploding memory. Unlimited async concurrency can overwhelm a database just as surely as too many threads.

When to use it

  • Sizing thread pools, connection pools and in-flight limits from rate × hold time, plus headroom.
  • Choosing a runtime model: async or virtual threads for high-concurrency I/O-bound services (gateways, chat, streaming, fan-out to many APIs); simpler blocking code with a bounded pool when concurrency needs are modest.
  • Diagnosing throughput plateaus where CPU is low (thread or pool exhaustion) or where adding instances does not help (contention on shared state).

When not to

  • Do not add concurrency to CPU-bound work beyond the core count; add cores or reduce work.
  • Do not raise pool sizes to "fix" a slow dependency: more concurrent requests against a saturated database make every query slower.
  • Do not rewrite a working blocking service to async just for fashion; if threads are not the binding limit, it buys nothing and adds complexity.

Trade-offs

Choice You gain You pay
Thread per request (blocking) Simple, debuggable sequential code Memory and scheduling cost per waiting request; thread limits
Event loop / async Very high concurrency for I/O-bound work Coloured functions (async/await everywhere), one blocking call stalls the loop
Virtual threads / goroutines Blocking-style code with cheap waiting Runtime support; pinning pitfalls; still need explicit limits on downstream concurrency
Large pools Fewer rejections under bursts More concurrent load on dependencies, more memory
Fine-grained locks / striping Less contention More complex code, harder invariants

Alternatives

  • Horizontal scaling: more processes or machines multiply every limit, except shared contention points (one database row stays one row).
  • Queues and asynchronous processing: move slow work out of the request path so request handlers hold slots briefly.
  • Batching: amortise a contended operation over many requests (one lock acquisition per batch).

Failure modes

  • Thread pool exhaustion: a slow dependency makes every thread wait; the service stops answering even health checks while CPU is idle.
  • Unbounded async fan-out: thousands of concurrent calls overwhelm a downstream service or exhaust memory.
  • Blocking the event loop: one CPU-heavy or blocking call stalls every request on that loop.
  • Hot lock or hot row: throughput flatlines at 1 ÷ hold time; adding instances adds waiters, and lock waits turn into timeouts.
  • Deadlocks when several locks are taken in inconsistent orders.

In production

Expose and alert on pool utilisation and wait time (thread pools, connection pools, semaphores), event-loop lag for async runtimes, and lock wait time in the database. Size pools from Little's law with measured hold times. Put explicit concurrency limits (bulkheads) in front of each dependency. Keep transactions short and free of network calls. When throughput plateaus, check in this order: are slots full (threads, connections)? are cores saturated? is something waiting on a lock?

Common misconceptions

  • "More threads means more throughput." Only while threads are waiting rather than computing, and only up to the next limit.
  • "Async is faster." Each request is not faster; waiting is cheaper, so more requests fit.
  • "Concurrency and parallelism are the same." Concurrency is in progress at once; parallelism is executing at once.
  • "Scaling out fixes lock contention." A shared row or global lock admits one holder however many servers compete for it.

Interview angle

Expect questions like "how many threads does this service need?" (rate × latency, plus headroom), "why is CPU at 10% but the service is timing out?" (blocked threads or pool exhaustion), "why would you choose an async framework or virtual threads?" (I/O-bound, high concurrency), and "how would you implement an inventory counter at high write rates?" (avoid a single hot row: striping, atomic operations, reservations, or partitioned ownership). Naming the three kinds of limit (slots, compute, contention) and giving numbers stands out.

Model assumptions

The simulation is a simplified model, not a benchmark. The engine has no CPU model, so the application is drawn as three simulated stages a request visits while it holds one app slot: the slots themselves (threads, or in-flight requests in async mode), a "CPU" stage with 4 workers and 10 ms per request, and the payments API (80 ms plus 5 ms each way, practically unlimited concurrency). A slot is held while the request is on the CPU and while it waits, which is what a blocking thread does; in async mode the slot count is simply very large, and waiting costs nothing in the model. Context-switch overhead, per-thread memory and event-loop blocking are not modelled; they are described in the text. The stock row is a database node with 1 connection (4 with striping), 4 ms per update and a 300 ms wait limit. Arrivals are Poisson; service times are lognormal (cv 0.3). Utilisation is the busy fraction of slots, not CPU percentage. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Concurrency = requests in progress at once

    This app handles each request on its own thread, and it has 4 threads: at most four requests can be in progress at once. A request needs about 10 ms of CPU (top right), then waits about 90 ms for the payments API (bottom right). The thread is held for all of it, roughly 103 ms.

    By Little’s law a thread pool can complete at most threads ÷ hold time = 4 ÷ 0.103 s ≈ 39 requests per second. At 30 per second the threads are about three-quarters busy, while the CPU cores are almost idle.

    Scene: Users send 30 requests per second to an app with 4 threads. Each request uses about 10 ms of CPU and then waits about 90 ms for a payments API while holding its thread. The threads are about three-quarters busy; the CPU is almost idle.

    Key idea: Concurrency is how many requests can be in progress at once. Max throughput = concurrent slots ÷ time each request holds a slot.

  2. 2. Threads blocked on I/O cap throughput

    Traffic rises to 80 per second. Throughput stalls near 39: all four threads are taken, the app’s queue fills and the rest is rejected.

    Yet the CPU cores are under 15% busy. The machine is not short of compute; it is short of threads, because each thread spends about 90% of its time blocked, waiting for a network reply. This is the classic shape of an I/O-bound service with blocking calls.

    Scene: At 80 requests per second the app completes only about 39 per second: all 4 threads are busy waiting on the payments API, its queue is full and requests are rejected, while the CPU is less than 15% busy.

    Key idea: For I/O-bound work, blocked threads, not CPU, are the limit: a thread waiting for the network still counts against the pool.

  3. 3. More threads: more slots for waiting

    Raise the pool to 32 threads. The limit becomes 32 ÷ 0.103 s ≈ 310 per second, so all 80 per second complete and the rejections stop. CPU use rises to about 20%: the cores finally get work, because more requests can wait at the same time.

    This works for I/O-bound services, up to a point. Each platform thread has its own stack (commonly around 1 MB reserved on the JVM, 8 MB of virtual address space by default on Linux) and costs scheduling work, so thousands of threads per process get expensive.

    Scene: With 32 threads the app completes all 80 requests per second and nothing is rejected. The CPU is about 20% busy.

    Key idea: For I/O-bound work, more threads raise throughput because most of them are waiting, not computing; each thread still costs memory and scheduling.

  4. 4. Async I/O: waiting without a thread

    Now the app is rewritten with non-blocking I/O (an event loop such as Node.js, Netty or asyncio, or virtual threads on Java 21+). A request that is waiting for the payments API no longer occupies an OS thread; it is a small object the runtime resumes when the reply arrives. So the limit on requests in progress becomes memory, not threads; here up to 4,000.

    Traffic rises to 300 per second and everything completes. By Little’s law about 300 × 0.125 s ≈ 35 to 40 requests are in flight at any moment, most of them simply waiting. The CPU cores are now about 75% busy: they are the real limit again.

    Scene: The app now uses non-blocking I/O. At 300 requests per second everything completes; about 35 to 40 requests are in flight at once and the CPU is about 75% busy.

    Key idea: Async I/O decouples waiting from threads: in-flight requests are cheap, so an I/O-bound service is limited by CPU and downstream capacity instead.

  5. 5. Async does not create CPU

    Traffic rises to 450 per second. Four cores at 10 ms per request can do at most 400. The CPU saturates, requests line up for a core, latency climbs and once that line is full requests fail.

    More in-flight slots would change nothing: the waiting is no longer the problem, the computing is. For CPU-bound work, concurrency beyond the number of cores only adds queueing (and, on a real machine, context switches). The fixes are less CPU per request, more cores, or more machines.

    Scene: At 450 requests per second the 4 CPU cores are saturated: throughput stays near 400 per second, requests queue for a core, latency rises and some requests fail. The app has plenty of free slots.

    Key idea: Concurrency helps while requests wait; once the CPU is saturated, only less work per request or more cores add throughput.

  6. 6. Contention: everyone needs the same lock

    Back to 300 per second, but a new feature makes every request decrement one stock counter, a single database row. Updating it takes 4 ms under a row lock, and only one transaction can hold that lock at a time: at most 250 per second, no matter how many slots or cores there are.

    Requests pile up waiting for the lock, the wait grows past 300 ms and they fail, after the CPU and the payments API have already done their work for them. Slots and cores have room to spare; a serialised section limits the whole system to 1 ÷ its duration.

    Scene: Every request now also updates one shared database row under a lock, one at a time, 4 ms each. Throughput is stuck near 250 per second, requests queue for the lock and those waiting longer than 300 ms fail, while slots and CPU still have headroom.

    Key idea: A critical section that one request at a time may enter caps throughput at 1 ÷ its duration, regardless of threads or cores.

  7. 7. Shrink or split the critical section

    Split the counter into 4 stripes (four rows, each request decrements one, the total is their sum), so four updates can proceed at once: about 1,000 per second. Throughput returns to the full 300, the lock queue disappears and the errors stop.

    Other ways to cut contention: hold the lock for less time (move work outside the transaction), use an atomic operation instead of read-modify-write, or avoid sharing altogether (per-request or per-partition state). The aim is the same: fewer requests competing for the same thing at the same time.

    Scene: The stock counter is split into 4 rows that can be updated in parallel. All 300 requests per second complete and nothing waits long for the lock.

    Key idea: Reduce contention by holding locks briefly, splitting shared state, or not sharing it at all.

  8. 8. Which limit are you hitting?

    Concurrency limits come in three kinds. Slots: threads, connections or in-flight limits, sized by Little’s law (rate × hold time); blocking I/O makes hold times long, async I/O makes slots cheap. Compute: CPU cores; more concurrency than cores only queues. Contention: shared locks, rows or counters that admit one request at a time; they cap throughput at 1 ÷ hold time.

    When throughput stops growing, check which one is saturated before adding threads.

    Scene: An async app with 4 CPU cores and a striped stock counter serves 300 requests per second with headroom on slots, CPU and locks.

    Key idea: Slots (Little’s law), compute (cores) and contention (critical sections): find which one is saturated, then fix that one.