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.
#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
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.
| Cost | Typical value | Notes |
|---|---|---|
| Stack (virtual) | 1–8 MB reserved | Reserved address range; RAM is only used as it's touched |
| Stack (resident) | 8–64 KB typical | What you actually pay in RAM |
| Kernel task struct | ~2–10 KB | Scheduler bookkeeping |
| Creation | 10–100 µs | Why you use a pool |
| Voluntary context switch | 1–3 µs | Blocking on I/O |
| Involuntary switch (preemption: the OS takes the core away) | 1–3 µs direct | Plus cache pollution |
| Cache pollution after a switch | 10–100 µs | The 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 wellThe 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 boundaryThis is why the modern performance techniques all look like avoiding the kernel:
- Batching —
writev/sendmmsgsend 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.
| Mechanism | Uncontended cost | Behaviour under contention |
|---|---|---|
| Atomic increment | ~5–20 ns | Cache line bounces between cores, each waiting its turn |
| Uncontended mutex | ~15–25 ns | Stays in userspace, cheap |
| Contended mutex | 1–10 µs | Syscall, thread put to sleep, context switch |
| Read-write lock (read) | ~20 ns | Still writes a shared counter — not free |
| Channel / queue handoff | ~50–200 ns | Depends 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
| Model | Where it fits | Where it hurts |
|---|---|---|
| Thread per request | Simple services, <1,000 concurrent, CPU-heavy work | Memory and switching at high concurrency |
| Thread pool + blocking I/O | Most business services; the boring correct default | Pool exhaustion under a slow dependency |
| Event loop (single-threaded) | High-concurrency I/O; Node, Redis, nginx | One long CPU task blocks everything |
| Event loop per core + sharding | Maximum throughput; Envoy, ScyllaDB, Seastar | Complex; needs a shardable workload |
| Async/await runtime | High-concurrency I/O with multi-core use; Go, Tokio, asyncio | Coloured functions, harder debugging, blocking-call landmines |
| Virtual/green threads | Thread-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
What is the real cost of a context switch, beyond saving registers?Show answer
Why did epoll and kqueue make 100,000 open connections routine?Show answer
"Async is faster than threads." Correct it.Show answer
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
What is false sharing, and how do you fix it?Show answer
A service with a 200-thread pool sits at 15% CPU while p99 is 4 seconds. What's the likely bottleneck?Show answer
How does one slow dependency take down a whole service, and what prevents it?Show answer
#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.