Blocking and Nonblocking IO

Topics Covered

How IO Waits

The scale of waiting

What a blocking call does

Thread per connection

Kernel buffers and partial operations

Measuring where the time goes

Blocking is not only network IO

The cost of a context switch

Why async is not faster per request

Most concurrent programs spend far more time waiting for input and output than computing. A web server waits for requests, for databases and for clients to read responses. This section explains what happens inside the operating system when a program performs I/O, why waiting is so expensive in time compared with computing, and what blocking actually means for a thread.

The scale of waiting

A modern processor executes several billion instructions per second, so a nanosecond is a few instructions. Reading from main memory takes about one hundred nanoseconds. Reading from a fast NVMe SSD takes tens to around a hundred microseconds, a thousand times longer. A round trip within a data centre takes around half a millisecond, and a round trip across a continent tens of milliseconds, which is millions of instructions. A typical web request that calls a database and a cache spends nearly all of its time waiting for those calls to return, and only a tiny fraction executing code. How a program behaves while it waits therefore determines how many requests it can handle concurrently and how efficiently it uses the machine. The whole subject of asynchronous programming exists to make waiting cheap.

Each step down the hierarchy is roughly a thousand times slower. A request spends nearly all its life waiting.

What a blocking call does

When a thread calls read on a socket that has no data yet, the call enters the kernel through a system call. The kernel checks the receive buffer of the socket, finds it empty, and puts the thread to sleep: it marks the thread as waiting on that socket, removes it from the run queue and switches to another runnable thread. The thread consumes no CPU while asleep, but it still exists, holding its stack, typically reserved at one to eight megabytes of virtual memory with some resident, its kernel data structures and any locks it holds. When a packet arrives, the network card raises an interrupt, the kernel processes the packet, places the data in the socket buffer and wakes the waiting thread, which is put back on the run queue and, when scheduled, returns from read with the data. Blocking is therefore efficient in CPU terms: the thread is not spinning. The costs are elsewhere, in memory per waiting thread and in the context switches needed to put threads to sleep and wake them.

Read enters the kernel, which parks the thread on the socket. A packet wakes it later, and read returns with data.

Thread per connection

The simplest way to serve many clients is to give each connection its own thread, which reads a request, processes it with ordinary blocking calls, writes the response and loops. This model is easy to write and debug, because each connection is handled by straight line code, stack traces show exactly what a request is doing, and blocking calls are natural. Apache httpd with its prefork and worker models, classic Java servlet containers and most early database servers work this way. Its limit is the number of threads a machine can sustain. Each thread needs memory for its stack and kernel structures, and with thousands of threads, the scheduler spends a growing share of time switching between them, while caches are constantly refilled. Ten thousand threads is feasible on modern Linux, but tens or hundreds of thousands of mostly idle connections, typical of chat, push notifications and long polling, become expensive. This was named the C10K problem by Dan Kegel in 1999: how to handle ten thousand concurrent connections on one server.

Kernel buffers and partial operations

Every socket has a receive buffer and a send buffer inside the kernel. A read returns whatever data is in the receive buffer, which may be less than requested, even a single byte, so programs must loop until they have a complete message. A write copies data into the send buffer and returns, which means a successful write does not mean the peer has received anything; it means only that the kernel has accepted responsibility for sending it. If the send buffer is full, because the peer is slow or the network congested, a blocking write waits for space, and a nonblocking write accepts only part of the data or none. These partial reads and writes are the main source of complexity in nonblocking I/O code, since each operation may need to be resumed later from where it stopped.

Measuring where the time goes

Before redesigning a server around nonblocking I/O, it is worth confirming that waiting is really the bottleneck. A simple measurement is the ratio of wall clock time to CPU time for a typical request. If a request takes 80 milliseconds end to end but consumes only 3 milliseconds of CPU, it spends more than ninety percent of its life waiting, and the number of requests the server can hold in flight at once determines its throughput far more than the speed of its code. Tracing tools make this visible: a distributed trace shows the spans for each database query, cache lookup and downstream call, and the gaps between them show computation. On Linux, off CPU profiling with tools such as bpftrace or the offcputime script from BCC records where threads sleep and for how long, producing flame graphs of waiting rather than running. Profiles like these often reveal surprises, such as a lock that serializes requests, a DNS lookup on every call, or a connection pool that is too small, each of which looks like slow I/O but has a different fix.

Blocking is not only network IO

Threads block in many places besides sockets. Reading a file that is not in the page cache waits for the disk. Taking a contended mutex parks the thread until the holder releases it. Allocating memory can block while the kernel reclaims pages under memory pressure. A page fault on a memory mapped file waits for the page to be read in, which is invisible in the code, since it looks like an ordinary memory access. Logging to a file or to standard output can block when the output pipe is full, which is a common surprise when a log collector falls behind and every request suddenly stalls on a log statement. DNS resolution through getaddrinfo is a blocking library call on most systems. An asynchronous design has to account for all of these, either by avoiding them on threads that must stay responsive or by moving them to threads where blocking is acceptable.

The cost of a context switch

A context switch between threads costs a few microseconds directly, saving and restoring registers and switching kernel stacks, and often more indirectly, because the next thread runs with cold caches and translation lookaside buffers. Switching between threads of different processes also changes the address space. At a few thousand switches per second, this is negligible. At hundreds of thousands per second, which a thread per connection server can reach when many short requests wake and sleep threads, the switches themselves consume a noticeable share of CPU and the cache misses slow everything else. Tools such as vmstat and pidstat report context switch rates, and a rate that climbs with load while useful throughput levels off is a sign that the threading model, not the application logic, has become the limit.

Why async is not faster per request

Nonblocking I/O does not make an individual request faster. A database query takes the same time whether the caller blocks a thread or awaits a future. What changes is how many requests can wait at once for a given amount of memory and CPU, and how much overhead the waiting adds. An event loop can even add a little latency per request, since handlers wait their turn on the loop. The gain shows up as higher throughput and steadier latency under heavy concurrency, not as lower latency for a single call on an idle server.

Waiting is the main cost to manage

A request spends almost all its time waiting for I/O that is thousands to millions of times slower than computation. Blocking calls park the thread cheaply in CPU terms, but each waiting thread costs memory and context switches, which limits thread per connection servers. Reads and writes can be partial, so code must loop until messages are complete.