SysDesignAtlas

Concurrency & What the OS Is Doing

Threads versus event loops, the real cost of a context switch and a syscall, and why the answer to "how many concurrent connections" depends on what they're waiting for.

CoreMedium13 min readfundamentalsconcurrencyosperformance
Confidence

#The question this page answers

"How many concurrent requests can one server handle?"

The honest answer is: it depends entirely on what those requests are doing while they're concurrent. A server holding 100,000 open connections that are mostly idle, and a server chewing through 100 requests that are all doing real computation, are both at their limit — for completely different reasons. Confusing the two is the most common source of bad capacity decisions.

Two terms for that split, used throughout this page. CPU-bound work is limited by how fast the processor can compute: resizing images, parsing, encryption. I/O-bound work is limited by waiting on something else: a database, a disk, another service. The first is limited by cores, the second by how many things you can wait on at once — and those need opposite designs.

#Two kinds of work

CPU-bound • Encoding, compression, parsing, crypto • Concurrency ceiling = number of cores • More threads make it SLOWER (switching overhead) • Scale by adding cores or machines I/O-bound • Waiting on DB, cache, network, disk • Ceiling = memory and the OS limit on open connections • Thousands of concurrent operations are fine • Scale by not tying up a thread for each wait
The concurrency model that's right for one is wrong for the other.

Almost all web and service work is I/O-bound: a request spends 1 ms computing and 40 ms waiting on a database. Little's Law says handling 2,000 req/s at 41 ms means 82 operations in flight. The design question is what mechanism holds those 82 waits.

#The cost of a thread

A thread is not free, and the costs are worth knowing precisely because they set the ceiling.

CostTypical valueNotes
Stack (virtual)1–8 MB reservedReserved address range; RAM is only used as it's touched
Stack (resident)8–64 KB typicalWhat you actually pay in RAM
Kernel task struct~2–10 KBScheduler bookkeeping
Creation10–100 µsWhy you use a pool
Voluntary context switch1–3 µsBlocking on I/O
Involuntary switch (preemption: the OS takes the core away)1–3 µs directPlus cache pollution
Cache pollution after a switch10–100 µsThe real cost, and the one people forget

#How waiting actually works

The mechanism underneath every async runtime is the same: ask the operating system to watch many connections at once and tell you which ones have data ready.

(A file descriptor, or fd, is just the number the OS gives you to refer to an open thing — a file, a socket, a pipe. "Watching 10,000 fds" means watching 10,000 open connections.)

   BLOCKING (one thread per connection)
     read(fd) ──► thread sleeps until data arrives
     10,000 connections → 10,000 sleeping threads

   select / poll  — O(n) per call
     "here are all 10,000 fds; which are ready?"
     kernel scans the whole list EVERY call
     → cost grows with connection count even when idle

   epoll (Linux) / kqueue (BSD)  — O(ready)
     register each fd ONCE
     "which of my registered fds became ready?"
     kernel returns only the ready ones
     → cost grows with ACTIVITY, not with connection count

   io_uring (Linux 5.1+)
     shared submission and completion ring buffers
     batch many operations, often ZERO syscalls per operation
     → works for disk I/O too, which epoll never did well

The select → epoll transition is the whole reason the C10K problem was solvable. (C10K — "10,000 concurrent connections" — was the famous late-1990s challenge of holding that many open connections on one server.) Once the kernel stopped scanning every descriptor on every call, idle connections became nearly free — and "100,000 open connections" turned from absurd into routine.

#Syscalls, and why they got expensive

A syscall is your program asking the operating system to do something it isn't allowed to do itself — read a file, send a packet, allocate memory. It's a controlled hop from your code into the kernel and back, and each hop costs: switching stacks, switching privilege level, and — since the Spectre and Meltdown security fixes of 2018 — throwing away some of the CPU's carefully built-up predictions.

   Syscall cost:
     pre-2018:    ~50-100 ns
     with mitigations:  ~200-1,000 ns

   A server doing 100,000 req/s with 10 syscalls per request:
     1,000,000 syscalls/s × 500 ns = 0.5 seconds of CPU per second
     → half a core doing nothing but crossing the kernel boundary

This is why the modern performance techniques all look like avoiding the kernel:

  • Batching — writev/sendmmsg send many buffers in one call.
  • io_uring — submit and complete through shared memory rings; the syscall becomes optional.
  • sendfile / zero-copy — the kernel moves file bytes straight to a socket, without first copying them into your program's memory and back. This is how static file servers and video origins send data as fast as the network card allows (line rate).
  • Kernel bypass (DPDK, AF_XDP) — the program talks to the network card directly, skipping the OS's networking code. Used at the extreme end, in load balancers and packet processors.

You will rarely reach for the last two. You should recognise them when you see them in a design, and you should know that "we're syscall-bound" is a real and diagnosable condition.

#Shared state is where it goes wrong

Concurrency is manageable. Concurrency plus data that several threads can change is where the bugs live.

Two words in the table below. Uncontended means nobody else wanted it at that moment — you took the lock and carried on. Contended means someone else already held it, so you had to wait. The gap between those two columns is the entire performance story of locking.

MechanismUncontended costBehaviour under contention
Atomic increment~5–20 nsCache line bounces between cores, each waiting its turn
Uncontended mutex~15–25 nsStays in userspace, cheap
Contended mutex1–10 µsSyscall, thread put to sleep, context switch
Read-write lock (read)~20 nsStill writes a shared counter — not free
Channel / queue handoff~50–200 nsDepends on implementation

The design principle that follows: partition the state so threads don't share it. A per-core, per-shard, or per-connection structure needs no lock at all. When you genuinely must share, prefer short critical sections (the code that runs while a lock is held) over clever lock-free algorithms — an uncontended mutex costs 20 ns and is comprehensible; a hand-rolled lock-free structure costs a week and a memory-ordering bug.

#Choosing a model

ModelWhere it fitsWhere it hurts
Thread per requestSimple services, <1,000 concurrent, CPU-heavy workMemory and switching at high concurrency
Thread pool + blocking I/OMost business services; the boring correct defaultPool exhaustion under a slow dependency
Event loop (single-threaded)High-concurrency I/O; Node, Redis, nginxOne long CPU task blocks everything
Event loop per core + shardingMaximum throughput; Envoy, ScyllaDB, SeastarComplex; needs a shardable workload
Async/await runtimeHigh-concurrency I/O with multi-core use; Go, Tokio, asyncioColoured functions, harder debugging, blocking-call landmines
Virtual/green threadsThread-per-request ergonomics, async costs; Go, Java 21+Still needs care with native blocking calls

Two terms from the table. Coloured functions: in async/await languages, an async function can only be awaited from another async function, so the codebase splits into two kinds that don't mix freely. Blocking-call landmines: one ordinary blocking call (a sync file read, a sleep) hidden inside async code stalls the whole thread, and every task sharing it.

Virtual threads are the notable recent shift. Go's goroutines and Java's virtual threads let you write straightforward blocking code while the runtime runs thousands of them on a few OS threads: when one waits, the runtime parks it and runs another on the same OS thread. You get the mental model of threads with the ceiling of an event loop — which is why "just use goroutines" is usually correct advice, and why Java 21 mattered.

#Applying it

Reasoning: (1) The event loop is single-threaded; a 200 ms parse blocks every other connection. Move it to a worker thread or stream the parse. (2) I/O-bound with a saturated downstream — measure connection pool wait time and downstream latency, not CPU. (3) False sharing: 8 counters share one cache line. Pad them. (4) Memory per connection and file descriptors — raise ulimit -n (the per-process limit on open fds), tune net.core.somaxconn (how many new connections can wait to be accepted) and socket buffer sizes, and shrink per-connection buffers, since 200,000 × 64 KB buffers is 12.8 GB before any application state.

#Check yourself

CPU-bound versus I/O-bound work: what sets the concurrency ceiling for each?Show answer
CPU-bound: the number of cores — more threads only add switching. I/O-bound: memory and file descriptors, because the work is mostly waiting; thousands of waits are fine if each doesn't hold a thread.
What is the real cost of a context switch, beyond saving registers?Show answer
Cache pollution. The incoming thread finds L1 and L2 full of the old thread's data and runs at DRAM speed for tens of microseconds until it warms them back up.
Why did epoll and kqueue make 100,000 open connections routine?Show answer
select and poll scan every descriptor on every call, so idle connections cost CPU. epoll registers each one once and returns only the ready ones, so cost tracks activity, not connection count.
"Async is faster than threads." Correct it.Show answer
Async is cheaper per waiting operation, not faster per operation. It wins when you need many thousands of simultaneous waits; for CPU-bound work or a few hundred requests, plain threads are simpler and just as fast.
Since the 2018 Spectre fixes a syscall costs ~500 ns. What does that mean at 100,000 requests a second with 10 syscalls each?Show answer
A million syscalls a second × 500 ns = half a core spent just crossing into the kernel. That's why fast systems batch calls, use io_uring or zero-copy sendfile.
What is false sharing, and how do you fix it?Show answer
Two threads writing different variables on the same 64-byte cache line fight over that line as if they shared one variable. Pad each to its own line, or give each core its own counter and sum them on read.
A service with a 200-thread pool sits at 15% CPU while p99 is 4 seconds. What's the likely bottleneck?Show answer
It's waiting, not computing: threads are blocked on a slow or saturated dependency, such as an exhausted database connection pool. Measure pool wait time and downstream latency.
How does one slow dependency take down a whole service, and what prevents it?Show answer
Every shared thread blocks waiting on it, so even requests that never touch it queue up. Bulkheads — a separate bounded pool per dependency — keep one failure from eating all the capacity.

#What to carry forward

  • Classify the work first. CPU-bound ceilings are cores; I/O-bound ceilings are memory and descriptors.
  • A context switch's real cost is cache pollution, not register saving.
  • epoll/kqueue made idle connections nearly free; that's what makes 100K connections routine.
  • Syscalls cost ~500 ns post-mitigations; high-throughput systems batch or bypass them.
  • The fastest synchronisation is none — partition state per core, per shard, per connection.
  • Bulkhead your pools, or one slow dependency takes the whole service with it.
00:00
/ 13m