DEVOPS, SRE AND CLOUD · PART 2 · NETWORKING FOR DEVOPS · SOCKETS · 35 OF 187

select vs poll vs epoll: Serving Many Connections

How nginx, Node.js, Redis and Envoy serve thousands of connections: threads versus an event loop, non-blocking sockets, select and poll scanning every socket, epoll reporting only the ready ones. Measured with our one-thread Python server: 5,000 open connections all answered, using 5,005 file descriptors and only 14,744 kB of memory, up from 13,076 kB at 100 connections.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Thread per client
  • event loop
  • select/poll scan all
  • epoll returns ready
  • 5,000 conns in 14.7 MB
  • never block

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.

Thread per connection
  • 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.

The loop
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.

The old calls
  • 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.

Linux epoll
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.

ev_server.py
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.

Our runs, one thread
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.

One slow handler stalls all
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is the difference between select, poll and epoll?

select and poll take the full fd set on every call and scan it (select is capped at 1024); epoll registers fds once and returns only ready ones, scaling with activity.

Q2What is the C10K problem?

Serving ten thousand concurrent connections on one machine; thread-per-connection designs struggled, which led to event loops built on epoll and kqueue.

Q3Why is nginx efficient with many connections?

Each worker process runs a non-blocking event loop with epoll, so thousands of idle keep-alive connections cost little memory or CPU.

Q4What does "don't block the event loop" mean?

Any slow synchronous work in a handler stops the single thread from serving all other connections; offload it to workers or use async I/O.

Q5What is a non-blocking socket?

A socket whose read/write/accept return immediately (EAGAIN) when they cannot proceed, instead of waiting, so one thread can manage many.

Q6What is kqueue?

The BSD and macOS equivalent of epoll: a kernel event notification interface that reports only ready descriptors.