Mental model
Spawning one dedicated OS thread per client connection crashes cleanly around 10,000 concurrent LLM SSE or HTTP streams due to megabytes of kernel/user stacks and heavy scheduler context switching. Linux epoll solves the C10K/C100K scaling wall by persisting watched socket file descriptors inside an in-kernel Red-Black tree (RB-tree) and appending sockets cleanly onto a rdllist Ready List dynamically via NIC interrupts—so epoll_wait() pops solely ready sockets in time (O(1) cleanly independent of 100,000 total idle connections!).
Learning outcomes
- Contrast linear bitmap copying and scans (
selectwith its1024-FD limit,poll) against stateful kernelepoll(RB-tree+ lock-protectedready_list). - Distinguish Level-Triggered (
LT) ease-of-use cleanly from Edge-Triggered (EPOLLET) efficiency and mandatoryuntil EAGAINsocket drain loops cleanly. - Prevent classic reactor deadlocks (
forgetting O_NONBLOCK), thundering-herd multi-worker wakeups (EPOLLEXCLUSIVE/SO_REUSEPORT), and starvation over huge read buffers cleanly.
Theory
Notice exact structural mechanics separating epoll from legacy multiplexing loops across production runtimes (Nginx, Envoy, Node libuv, Uvicorn uvloop, Tokio):
| Multiplexing API | Kernel Registration Cost | Event Return Complexity | Trigger Modes & Scaling Cap | Primary Edge Trap |
|---|---|---|---|---|
select() (POSIX) | Re-copies entire bitmask array user -> kernel every call | Scans sequentially every return | Hard limited at FD_SETSIZE = 1024 (crashes past 1024 sockets!) | Silent stack overflow corruption above FD 1023 cleanly |
poll() | Re-copies whole struct pollfd[] array user -> kernel per call | Linear scan checking every idle slot | No 1024 FD limit; high CPU waste past ~2,000 idle streams | Scans tens of thousands of sleeping HTTP/SSE pipes every loop cleanly |
epoll (Level-Triggered default) | Registers FD once via epoll_ctl(ADD) (RB-tree, insert) | Returns strictly ready sockets ( ready walk!) | Scales smoothly cleanly to 100K–1M+ open idle streams | Single blocking disk/DNS FD still freezes entire thread cleanly (use O_NONBLOCK!) |
epoll (Edge-Triggered EPOLLET) | Same once-per-FD registration; fires solely on state edge change | Eliminates repeated notifications on partially drained sockets cleanly | Used cleanly in Nginx / Envoy high-QPS loops | Deadlocks socket silently forever cleanly unless loop drains cleanly to EAGAIN! |
c#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <fcntl.h>#include <sys/epoll.h>#include <unistd.h>int set_nonblocking_fd(int fd) {int flags = fcntl(fd, F_GETFL, 0);if (flags < 0) return -1;return fcntl(fd, F_SETFL, flags | O_NONBLOCK);}/* Mandatory Edge-Triggered (EPOLLET) drain loop until EAGAIN / EWOULDBLOCK */int drain_edge_triggered_socket(int client_fd, char *buf, size_t cap) {for (;;) {ssize_t n = read(client_fd, buf, cap);if (n > 0) {/* Process chunk incrementally here */continue;}if (n == 0) return 0; /* Peer closed cleanly (FIN) */if (errno == EAGAIN || errno == EWOULDBLOCK) {return 1; /* Kernel receive queue drained safely; yield back to epoll_wait */}return -1; /* Real socket error */}}
Trade-offs
Level-Triggered (LT) epoll prevents subtle missed-edge starvation bugs cleanly when reading fixed upper-bound chunks per tick cleanly (letting other busy sockets share fair CPU time cleanly), explaining why many runtimes prefer LT or chunk-capped fairness cleanly unless chasing utmost syscall minimization (EPOLLET). Meanwhile, pairing epoll per CPU worker core with SO_REUSEPORT (distributing incoming TCP accepts directly cleanly across per-core queues) or EPOLLEXCLUSIVE eliminates waking 16 sleeping worker processes unnecessarily cleanly whenever one client opens a socket!
Failure modes and misconceptions
- Partial Read Bug in Edge-Triggered (
EPOLLET) Loops: Reading just 4 KB out of an incoming 12 KB packet cleanly without looping untilEAGAINleaves8 KBstranded cleanly inside kernel buffers forever without any new edge wakeup (silent client hang!). - Adding Regular Disk File Handles Directly Into
epoll: On Linux, local filesystem regular file descriptors (disk files) are always reported immediately ready and ignored cleanly byepoll(EPERMor blockingread()); asynchronous local storage needsio_uringor dedicated blocking threadpools! - Omitting
O_NONBLOCKon Sockets Underepoll: If two threads race reading or spurious wakeup fires on a blocking FD,recv()sleeps synchronously freezing every sibling SSE stream on that event loop cleanly. - Unchecked
EPOLLOUTBusy Spinning: Leaving write-interestEPOLLOUTsubscribed cleanly when socket send buffers are empty wakesepoll_waitcontinuously in a 100% CPU busy spin (only subscribe EPOLLOUT when write returns EAGAINor use Edge-Triggered!).
Decision scenario
A custom C++ SSE proxy handling 50,000 active streaming connections upgraded from Level-Triggered onto EPOLLET, immediately suffering stalled partial HTTP JSON requests and high CPU spikes (100% on 1 core) whenever 16 workers waited simultaneously on one shared listen socket! Fix EPOLLET loops strictly cleanly to drain until EAGAIN (with bounded fair yields), ensure O_NONBLOCK on all accepts (accept4(..., SOCK_NONBLOCK)), unsubscribe EPOLLOUT cleanly when write buffers drain cleanly, and partition accepts via SO_REUSEPORT or EPOLLEXCLUSIVE cleanly.