The problem: many sockets, few threads
A gateway may hold connections to a dozen venues, a risk server and a few hundred internal clients. With blocking I/O, recv puts the thread to sleep until data arrives, so serving many sockets means one thread per socket. That works for tens of connections and fails for thousands: each thread has its own stack (8 MB of virtual address space by default on Linux), and every wake-up is a context switch costing microseconds plus cold caches.
Non-blocking sockets (O_NONBLOCK) never sleep: if no data is ready, recv returns immediately with EAGAIN/EWOULDBLOCK. Polling every socket in a loop wastes CPU, so the missing piece is a way to ask the kernel "which of these sockets are ready?" and sleep until at least one is. That is I/O multiplexing.
select, poll, epoll and kqueue
| API | How you use it | Cost per wait | Notes |
|---|---|---|---|
select | Pass bitmaps of descriptors each call | in descriptors watched | Limited to FD_SETSIZE (usually 1,024); bitmaps are overwritten and rebuilt each call. |
poll | Pass an array of pollfd each call | No descriptor limit, but the kernel still scans and copies the whole array every time. | |
epoll (Linux) | Register once with epoll_ctl; epoll_wait returns only ready descriptors | Interest list lives in the kernel. Level- or edge-triggered. | |
kqueue (macOS, BSD) | Register with kevent changes; the same call returns events | Also handles timers, signals and file changes. |
With 10,000 idle connections and 5 active, poll does 10,000 units of work per wake-up; epoll does about 5.
Level- versus edge-triggered. Level-triggered (the default, and the only mode of select/poll) reports a socket as ready for as long as unread data remains. Edge-triggered (EPOLLET) reports only the transition to ready. In edge mode you must read until EAGAIN, or the leftover bytes will never trigger another event and the connection silently hangs.
All four are readiness APIs: the kernel says "you can read now", and you then make the recv call yourself. Linux's io_uring is a completion API: you submit the operations to shared ring buffers and collect their results, which can batch many I/Os into few or no syscalls.
The event loop
An event loop is the program structure built on top:
loop:
ready = wait_for_events(timeout = time until the next timer)
for each ready socket: run its handler (read, parse, respond) without blocking
run any expired timers
One thread serves every connection, there are no locks because there is no concurrency inside the loop, and the order of events is deterministic for a given input. The price is that every handler must be short and non-blocking: a handler that sleeps, does a blocking call or a long computation freezes every other connection. Heavy work goes to a worker thread (often through an SPSC queue), and multi-core scaling is done by running one loop per core.
Worked example
an event loop with selectors
Using Python's selectors module, write a single-threaded server that accepts two clients and acknowledges one message from each, never blocking on a socket that is not ready.
Show solutionHide solution
selectors.DefaultSelector wraps the best mechanism on the platform. Register the listening socket for read events (a pending connection makes it readable); on accept, register the new connection too. Each select call sleeps until something is ready, and the handlers only touch sockets the kernel has reported as ready.
import selectors
import socket
sel = selectors.DefaultSelector() # epoll on Linux, kqueue on macOS/BSD
print(type(sel).__name__)
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
listener.setblocking(False)
sel.register(listener, selectors.EVENT_READ, data="accept")
# Two clients connect and send; nothing below blocks on any one socket.
clients = [socket.create_connection(listener.getsockname()) for _ in range(2)]
for i, c in enumerate(clients):
c.sendall(f"order {i}\n".encode())
handled = 0
while handled < 2:
for key, _ in sel.select(timeout=1.0): # wait until at least one socket is ready
if key.data == "accept":
conn, _ = key.fileobj.accept()
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, data="read")
else:
conn = key.fileobj
msg = conn.recv(4096) # ready, so this returns at once
conn.sendall(b"ack " + msg)
sel.unregister(conn)
conn.close()
handled += 1
for c in clients:
print(c.recv(4096).decode().strip())
c.close()
listener.close()
Output on macOS (on Linux the first line reads EpollSelector):
KqueueSelector
ack order 0
ack order 1
The data field attached at registration is how the loop dispatches to the right handler: here a string, in real code a connection object with its own parse buffer. Simplifications to name in an interview: a real server must handle partial reads (TCP has no message boundaries, so buffer until a full message is present), recv returning b"" for a closed peer, and a non-blocking send that writes only part of the data, which means registering for write readiness and sending the rest later.
Worked example
an asyncio quote server
With asyncio, write a quote server where each lookup takes 100 ms of simulated I/O, and five clients that each request one symbol. Time the clients run one after another and all at once. Then replace await asyncio.sleep(0.1) with time.sleep(0.1) and explain the change.
Show solutionHide solution
asyncio is an event loop (built on selectors) plus coroutines: await marks the points where a coroutine yields to the loop until its I/O is ready, so code reads sequentially while the loop interleaves many connections.
import asyncio
import time
async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Quote server: reply to each 'QUOTE <sym>' line after a simulated 100 ms lookup."""
while line := await reader.readline():
sym = line.decode().split()[1]
await asyncio.sleep(0.1) # stands in for slow I/O; does not block the loop
writer.write(f"{sym} 100.25 100.50\n".encode())
await writer.drain()
writer.close()
await writer.wait_closed()
async def client(port: int, sym: str) -> str:
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(f"QUOTE {sym}\n".encode())
await writer.drain()
reply = (await reader.readline()).decode().strip()
writer.close()
await writer.wait_closed()
return reply
async def main() -> None:
server = await asyncio.start_server(handle, "127.0.0.1", 0) # port 0: pick a free port
port = server.sockets[0].getsockname()[1]
syms = ["AAPL", "MSFT", "NVDA", "AMZN", "META"]
t0 = time.perf_counter()
for sym in syms: # one after another
await client(port, sym)
sequential = time.perf_counter() - t0
t0 = time.perf_counter()
replies = await asyncio.gather(*(client(port, s) for s in syms)) # all at once
concurrent = time.perf_counter() - t0
print(replies)
print(f"sequential: {sequential:.2f} s, concurrent: {concurrent:.2f} s")
server.close()
await server.wait_closed()
asyncio.run(main())
Output (Python 3.11):
['AAPL 100.25 100.50', 'MSFT 100.25 100.50', 'NVDA 100.25 100.50', 'AMZN 100.25 100.50', 'META 100.25 100.50']
sequential: 0.52 s, concurrent: 0.11 s
Sequentially the five 100 ms waits add up to about 0.5 s. With gather, all five handlers are suspended in asyncio.sleep at the same time on one thread, so the total is about one wait. The server code did not change at all between the two runs.
With time.sleep(0.1) in the handler the same program prints sequential: 0.53 s, concurrent: 0.53 s. time.sleep blocks the thread that runs the event loop, so while one handler sleeps no other coroutine can run, and concurrency disappears. The same happens with a blocking database driver, requests.get, or a long computation. Use the async version of the library, or move the call off the loop with await asyncio.to_thread(...).
Kernel bypass, briefly
Even epoll pays for the kernel: an interrupt when the packet arrives, the kernel network stack, a syscall, and a copy into user memory. That is typically a few microseconds per packet, plus jitter from interrupts and scheduling. The fastest trading systems skip it:
- Kernel-bypass NIC stacks (for example Solarflare/AMD OpenOnload and ef_vi, or DPDK) map the network card's receive rings into the process. A thread pinned to an isolated core busy-polls the ring, so a packet is visible to user code without any syscall or interrupt.
- The trade-off: a core spins at 100% even when idle, the application (or a user-space library) takes over protocol work, and the setup is vendor-specific.
- Beyond that, FPGAs parse feeds and can even send orders in hardware.
In an interview it is enough to explain why bypass helps (no syscalls, interrupts or copies; polling instead of sleeping) and its costs. The same logic of polling a ring instead of sleeping is what the SPSC queue applies between threads.
Knowledge check
A server watches 10,000 mostly idle connections and wakes up with 5 ready. Why does epoll scale better than poll here?
Knowledge check
An asyncio handler calls a synchronous HTTP library that takes 200 ms per request. With 50 clients connected, what happens?
Knowledge check
With edge-triggered epoll, a handler reads 4 KB from a socket that had 10 KB available and returns. What happens next?
Key takeaways
- Blocking I/O needs a thread per connection; non-blocking I/O plus multiplexing lets one thread serve thousands.
selectandpollare per wait;epollandkqueuekeep interest in the kernel and are .io_uringis completion-based.- Edge-triggered mode requires draining each socket until
EAGAIN. - An event loop has no locks and deterministic ordering, but any blocking call inside a handler stalls every connection.
asyncioturned five 100 ms waits from 0.52 s into 0.11 s on one thread; onetime.sleepundid it.- Kernel bypass replaces interrupts and syscalls with busy-polling the NIC from user space, trading a dedicated core for microseconds.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).