0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Concurrency Patterns
Event Loops and Reactors
An event loop is the engine underneath Node.js, nginx, Redis, Netty, Python asyncio and most browsers. It lets one thread serve thousands of clients by waiting for events and dispatching each one to a short handler. This section describes the reactor pattern that formalizes this design, its parts, and the rules a handler must follow.
The core loop
At its heart, an event loop is a few lines of code. It asks the operating system which registered sources are ready, using epoll, kqueue or a similar interface, waits until at least one is ready or the nearest timer is due, then calls the handler for each ready source, runs any due timers, and loops. Everything the program does happens inside these handler calls. A handler might read bytes from a socket and parse a request, write part of a response, accept a new connection and register it, or schedule a timer. Because handlers run one at a time on one thread, they never run concurrently with each other, so handlers can share data structures without locks. The loop is single threaded concurrency: many activities in progress at once, interleaved at the points where each would otherwise wait.
Parts of the reactor
Douglas Schmidt described the reactor pattern in 1995, naming the pieces that event driven servers share. Handles are the operating system resources that produce events, such as sockets, pipes, timers and signals. The synchronous event demultiplexer is the call that waits on many handles and reports which are ready, in practice epoll_wait or kevent. Event handlers are the objects that know how to react to events on a handle, usually with methods such as handle_read and handle_write. The reactor, or dispatcher, owns the registry of handles and handlers, runs the loop, and calls the right handler for each event. Application code registers handlers with the reactor and is called back; it never calls the demultiplexer directly. This inversion of control, where the framework calls you rather than you calling the framework, is the defining feature of the pattern and of callback based programming in general.
Handlers must be short
The single rule of the reactor is that handlers must return quickly. While a handler runs, the loop cannot wait, dispatch or run timers, so every other connection waits too. A handler that performs a blocking call, such as a synchronous database query, a file read that misses the page cache or a DNS lookup, stalls the entire loop for the duration of the call. A handler that performs heavy computation, such as compressing a large response, parsing a huge JSON document or hashing a password with bcrypt, has the same effect. A useful mental budget is that a handler should run for well under a millisecond, because with a thousand active connections, a handler that takes ten milliseconds means every one of those connections can see ten extra milliseconds of latency whenever it happens. Work that cannot be made short must be moved off the loop, to a worker pool or another process, with the result posted back to the loop when done.
Callbacks and state machines
Because handlers return before the work they start is finished, the state of each request must live outside the call stack. A request that reads a header, then a body, then queries a cache, then writes a response becomes a state machine, an object recording which step it is in and holding partial data, with a handler for each event that advances it. In early event driven code, this was written as nested callbacks: read a header, and in the callback read the body, and in that callback send a query, and so on. Deep nesting, known as callback hell, made control flow hard to follow, error handling hard to get right, since every callback had to check and propagate errors itself, and resource cleanup easy to forget on some paths. Futures, promises and later async await, covered in the following lessons, were invented largely to let programmers write this kind of sequential logic in a sequential style while still running on a reactor underneath.
Reactor versus proactor
The reactor pattern is built on readiness: the loop learns that a handle is ready and the handler performs the operation. The proactor pattern, also described by Schmidt and colleagues, is built on completion: the program initiates asynchronous operations, and the loop delivers completion events to completion handlers, which receive the result of an operation that has already happened. Windows I/O completion ports and io_uring naturally support proactors, and Boost.Asio exposes a proactor interface on every platform, emulating it with a reactor on systems that only provide readiness. From the application point of view, the main difference is who performs the I/O and who owns the buffers while an operation is in flight, which affects cancellation and memory use as the previous lesson discussed.
A tiny reactor in code
Writing a minimal reactor is a good way to understand one. In Python, the selectors module wraps epoll and kqueue. A server creates a listening socket, sets it nonblocking, and registers it with a selector together with a callback, the accept handler. The loop calls select on the selector, which returns a list of ready keys, each carrying the callback stored at registration, and calls each callback with the ready socket. The accept handler accepts a connection, sets it nonblocking and registers it with a read handler. The read handler reads available bytes into the connection buffer, and when a full line has arrived, it switches the registration to write interest with a write handler holding the response. The write handler sends as much as the socket accepts and, once the output buffer is empty, switches back to read interest. The whole server is perhaps sixty lines, serves thousands of clients on one thread, and contains every idea in this section: registration, readiness, dispatch, short handlers and explicit per connection state.
Why single threaded is often enough
It can seem surprising that a single thread is enough for a busy server, but the arithmetic works out for I/O bound services. If each request needs 50 microseconds of CPU for parsing, routing and serializing, one core can handle 20000 requests per second, regardless of how long each request waits on the network, because waiting costs the loop nothing. Redis serves well over one hundred thousand simple commands per second on a single thread for exactly this reason: each command is a few microseconds of work on in memory data, and the event loop never waits. The single thread also removes all locking overhead and makes behaviour deterministic, which simplifies reasoning and debugging. When one core is not enough, the usual answer is more loops, one per core, rather than threads inside a loop, as the multi loop section describes. Redis itself added I/O threads in version 6 for reading and writing sockets, while keeping command execution on a single thread.
Ordering guarantees
A reactor gives some ordering guarantees for free and withholds others. Events for a single connection are delivered in the order the kernel reports them, and since a connection is handled by one loop, its handlers never overlap, so a request is fully processed before the next one on the same connection unless the code explicitly pipelines them. Across connections, there is no ordering at all: two clients that send at nearly the same moment may be served in either order, depending on how the kernel lists ready descriptors. Code that relies on cross connection order, for example assuming that a write request from one client is processed before a read from another simply because it was sent first, has a race even on a single thread. Single threaded concurrency removes data races between handlers, but not logical races between events.
A reactor waits for readiness and calls short handlers one at a time on one thread, which removes the need for locks between them. Any handler that blocks or computes for long stalls every connection on the loop, so move such work to a worker pool and post results back. Keep request state in explicit objects, since handlers return before work finishes.