The Reactor Pattern
The reactor pattern structures a program around a single event loop that waits for events on many sources and dispatches each one to a registered handler. It is the backbone of high concurrency servers that must manage thousands of connections with few threads.
The core players are:
- Event demultiplexer A blocking call like epoll or kqueue that watches many file descriptors and returns the ones that are ready.
- Handlers Callbacks bound to specific events such as a socket becoming readable.
- Dispatcher The loop that pulls ready events from the demultiplexer and invokes the matching handler.
The loop runs forever: block until at least one source is ready, then for each ready source call its handler, then repeat. Because the demultiplexer reports only ready sources, the program never wastes time polling idle connections.
A key rule is that handlers must be short and non blocking. If a handler blocks, the entire loop stalls and every other connection waits. Long work is offloaded to a thread pool or split across multiple loop iterations.
The reactor reacts to events after they occur. The related proactor pattern instead completes IO operations and then notifies handlers of the result.
Key idea
A reactor uses one event loop and a demultiplexer to dispatch ready events to short non blocking handlers, scaling many connections on few threads.