The C10K problem, epoll and io_uring, a hand-written event loop, async/await pitfalls, and goroutines vs async.
Nginx serves tens of thousands of connections from a handful of worker processes. Node.js runs an entire web server's JavaScript on a single thread. Python's asyncio can handle thousands of open sockets in one process. None of them is doing anything magical. They all rely on the same idea: don't wait, get notified.
This article explains the problem async I/O solves, the operating system features that make it possible, how an event loop works (we'll write one), and the mistakes that make async code slow.
A typical web request does a little computation and a lot of waiting: on the database, on another service, on the client's slow mobile connection. Recall the latency numbers from How Computers Actually Run Your Code: a network round trip in the same data center takes about 0.5 ms, enough time for well over a million CPU instructions.
With blocking I/O, a call like sock.recv() puts the thread to sleep until data arrives. The simplest server design gives each connection its own thread:
thread-per-connection: 1 connection = 1 thread, blocked most of the time
10 connections → fine
10,000 connections → 10,000 threads: GBs of stack memory, constant context switching
This is the C10K problem, named by Dan Kegel in 1999: how do you handle 10,000 concurrent connections on one server? Threads are too expensive to keep idle by the thousand. Each one reserves stack memory (8 MB of virtual address space by default on Linux), and the scheduler pays for every switch between them.
Two operating system features solve it:
recv() on a socket with no data returns immediately with "would block" instead of putting the thread to sleep.| API | OS | Notes |
|---|---|---|
select / poll |
Everywhere | Passes the full list of sockets on every call, so cost grows with the number of connections |
epoll |
Linux (2.6, 2002) | Register sockets once; the kernel returns only the ready ones. The basis of most Linux servers |
kqueue |
BSD, macOS | Similar to epoll, handles more event types |
| IOCP | Windows | Completion-based: "tell me when the I/O has finished" |
io_uring |
Linux (5.1, 2019) | Shared ring buffers between app and kernel; completion-based, very few system calls |
With these, a single thread can watch thousands of sockets and only ever touch the ones that have something to do.
An event loop is the program structure built on top of that:
while True:
ready = wait_for_events(timeout=next_timer()) # epoll_wait / kqueue
for event in ready:
run the callback registered for it # read request, write response…
run any timers that are due
Here is a complete, working event loop: a single-threaded server that serves many clients at once, using Python's selectors module (epoll on Linux, kqueue on macOS):
import selectors
import socket
sel = selectors.DefaultSelector() # epoll on Linux, kqueue on macOS
def accept(server):
conn, addr = server.accept()
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, handle)
print("connected", addr)
def handle(conn):
data = conn.recv(4096) # won't block: the selector said it's ready
if data:
conn.sendall(data.upper()) # fine for small replies; big ones need write buffering
else:
sel.unregister(conn)
conn.close()
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 9000))
server.listen()
server.setblocking(False)
sel.register(server, selectors.EVENT_READ, accept)
print("echo server on :9000 (one thread, many clients)")
while True: # the event loop
for key, _ in sel.select(): # sleep until at least one socket is ready
key.data(key.fileobj) # call the registered callback
Open a few terminals and run nc 127.0.0.1 9000 in each. Every client gets served by one thread. Nginx, Redis, Node.js (via libuv) and Python's asyncio all have this loop at their core, with a lot more care around buffering, timers and errors.
Writing everything as callbacks gets painful quickly. Each step of a request becomes a separate function, errors have to be passed along by hand, and you end up with "callback hell". Languages solved this in stages:
read(sock, on_data). Simple, but logic is split across functions.async/await: code that looks sequential, but every await is a point where the function pauses and hands control back to the event loop until its result is ready.import asyncio
import time
async def fetch(name, seconds):
print(f"start {name}")
await asyncio.sleep(seconds) # stand-in for a network call: yields to the loop
print(f"done {name}")
return name
async def main():
t0 = time.perf_counter()
results = await asyncio.gather(fetch("users", 1), fetch("orders", 1), fetch("prices", 1))
print(results, f"in {time.perf_counter() - t0:.1f}s") # ~1.0s, not 3.0s
asyncio.run(main())
Three one-second waits finish in about one second, because they wait concurrently on a single thread. Under the hood, a coroutine is a function that can be suspended and resumed. Each await saves its state, and the event loop resumes it when the I/O is ready.
The key word is cooperative. The event loop can only switch tasks at an await. A task that doesn't await never gives up control, so one blocking call freezes every other task on the loop.
import asyncio
import time
async def bad_handler():
time.sleep(2) # ❌ blocks the whole event loop for 2 seconds
return "done"
async def good_handler():
await asyncio.sleep(2) # ✅ yields; other tasks keep running
return "done"
async def cpu_or_blocking_lib():
# ✅ unavoidable blocking work (a sync library, a big computation): run it in a thread
return await asyncio.to_thread(time.sleep, 2)
async def main():
t0 = time.perf_counter()
await asyncio.gather(good_handler(), good_handler(), cpu_or_blocking_lib())
print(f"good: {time.perf_counter() - t0:.1f}s") # ~2.0s, all three overlapped
t0 = time.perf_counter()
await asyncio.gather(bad_handler(), bad_handler())
print(f"bad: {time.perf_counter() - t0:.1f}s") # ~4.0s, they ran one after another
asyncio.run(main())
Common ways to accidentally block the loop:
requests instead of httpx/aiohttp, or a sync database driver.time.sleep instead of asyncio.sleep.Python's debug mode (PYTHONASYNCIODEBUG=1) logs any callback that blocks for more than 100 ms. Node has the same problem: a slow synchronous function stalls every request on that process.
Async makes it easy to start 10,000 operations at once, which is a good way to overload a database or get rate-limited by an API. Bound it with a semaphore:
import asyncio
async def call_api(i, limit):
async with limit: # at most 10 calls in flight at any moment
await asyncio.sleep(0.1) # stand-in for the real request
return i
async def main():
limit = asyncio.Semaphore(10)
results = await asyncio.gather(*(call_api(i, limit) for i in range(100)))
print(len(results), "calls done") # 100 calls done, in ~1s rather than 0.1s or 10s
asyncio.run(main())
| Model | How you write code | How it scales | Examples |
|---|---|---|---|
| Thread per connection | Plain blocking code | Hundreds to a few thousand connections | Classic Apache, traditional Java servlets |
| Event loop + async/await | async/await, everything must be non-blocking |
Tens of thousands per core | Node.js, Python asyncio, nginx, Rust tokio |
| Lightweight threads (M:N) | Plain blocking code, and the runtime does the async part | Hundreds of thousands to millions | Go goroutines, Java 21 virtual threads, Erlang processes |
The third row is worth understanding. In Go, you write ordinary blocking code (conn.Read(buf)), and each connection gets its own goroutine. A goroutine starts with a 2 KB stack instead of megabytes. When it blocks on the network, the Go runtime parks it, registers the socket with its built-in netpoller (epoll/kqueue underneath), and runs another goroutine on the same OS thread. You get the scalability of an event loop with the readability of threads. Java's virtual threads (Project Loom, Java 21) brought the same model to the JVM.
Async I/O is ultimately a scheduling trick. Instead of parking a thread for every wait, you park a small object and let one thread run whatever is ready. Most of the work in using it well is never blocking that thread.
For the threads-and-locks side of concurrency, see Concurrency Fundamentals.