Notes
Option 1: threads
The simple fix is a thread or process per connection, each blocking in recv on its own client. It is easy to write, and classic Apache and older Java servers work this way. But each thread has its own stack and costs the scheduler, so ten thousand mostly idle clients means ten thousand mostly idle threads. Memory grows with connections, and context switching eats CPU. This was called the C ten K problem.
- each client gets a thread that blocks in recv()
- + easy to write
- each thread has a stack and scheduling cost
- 10,000 idle clients = 10,000 threads
- classic Apache prefork, old Java servlet servers
Option 2: event loop
The other way is an event loop. Every socket is set non-blocking, so a read with no data returns immediately instead of waiting. The program has one single waiting point: ask the kernel which of my sockets are ready, then handle exactly those, accepting, reading or writing, and go back to waiting. One thread serves every connection, and an idle connection costs only a little kernel memory.
make every socket
non-blocking
while True:
ready = wait_for_any()
for sock in ready:
accept, read or write
without ever blocking
one thread, many sockets select and poll
The first waiting calls were select and then poll. You hand the kernel the full list of sockets on every call, it checks each one, and tells you which are ready. select is also limited to one thousand and twenty four descriptors. The problem is the cost: with ten thousand connections and only three ready, every call still passes and scans all ten thousand. Work grows with the number of connections, not with the activity.
- select(): pass a bitmap of fds, kernel checks each limited to 1024 fds
- poll(): a list instead, no 1024 limit
- both: you pass ALL sockets on every call, kernel scans all of them → O(n)
- fine for a few hundred
epoll
epoll fixes that. You create an epoll instance, register each socket once, and the kernel itself keeps a list of the ready ones as data arrives. epoll wait returns only those. Ten thousand idle connections cost nothing per call. The work now grows with activity, not with the number of connections. BSD and macOS have the same idea, called kqueue, and libraries like libuv, behind Node.js, use whichever the system has.
epoll_create one interest list in the kernel epoll_ctl ADD register a socket once epoll_wait returns only the ready ones cost grows with activity, not total connections BSD/macOS: kqueue
Our server
Here is our server. Python's selectors module picked EpollSelector automatically on Linux. We set the listening socket non-blocking and register it. The loop calls select, which is epoll wait underneath. If the listening socket is ready, we accept the new client and register it too. Otherwise a client sent data, so we read it and reply. One thread, no blocking calls anywhere.
sel = DefaultSelector()
→ EpollSelector
s.setblocking(False)
sel.register(s, READ)
while True:
for key, _ in sel.select():
if key.fileobj is s:
accept + register
else:
read, reply "ok:" Measure it
Then we measured. A client opened a hundred, then two thousand, then five thousand connections and sent a message on each. Every message was answered. The server process held five thousand and five file descriptors at the peak, yet its memory went only from thirteen thousand and seventy six kilobytes to fourteen thousand seven hundred and forty four: about one point seven megabytes for four thousand nine hundred more connections. All five thousand replies came back in twenty nine milliseconds.
conns answered RSS 100 all 13,076 kB 2000 all 13,792 kB 5000 all 14,744 kB 5000 conns → 5,005 fds all 5000 replies in 29 ms +1,668 kB for 4,900 more connections
The catch
The catch: one thread means one slow handler stalls everyone. A blocking database call or a heavy computation inside the loop freezes every connection, the same problem as last episode in a new form. So event loop servers push slow work to worker threads and use async drivers. nginx runs one event loop per worker process, usually one per CPU core. In Node.js, event loop lag is a key metric to monitor.
- a CPU-heavy or blocking call inside a handler freezes every connection
- fixes: worker threads for slow work, async drivers
- nginx: one loop per worker process, one per core
- Node: "don't block the event loop"; watch loop lag
Common mistakes
Mistakes. Blocking calls inside an event loop. One worker on a machine with many cores. A file descriptor limit lower than the number of connections you expect. Thread per connection designs for long lived, mostly idle clients like websockets. And no metric for event loop lag, the earliest warning that the loop is overloaded.
- blocking calls in the loop
- one worker on a many-core machine
- fd limit lower than expected connections
- thread-per-connection for long-lived idle clients (websockets)
- no loop-lag metric
Say it like this
In the interview: nginx runs a few worker processes, each with an event loop over non-blocking sockets using epoll. Sockets are registered once and epoll wait returns only the ready ones, so idle connections cost almost nothing, unlike select and poll, which scan every descriptor on every call. The trade-off is that nothing may block the loop, so slow work goes to other threads or processes.
- "Each worker runs an event loop
- on non-blocking sockets with epoll: sockets are registered
- once and epoll_wait returns only ready ones, so idle connections
- are cheap. select and poll scan
- every fd each call. The rule: never block the loop."