FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Linux I/O Multiplexing & epoll

select(), poll(), epoll() event loops, edge-triggered vs level-triggered notifications, and non-blocking file descriptors.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Build O(1) scalable event loops using Linux epoll
  • ✓Distinguish edge-triggered from level-triggered I/O modes
Full Technical Reference Document

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 O(k)O(k) time (O(1) cleanly independent of 100,000 total idle connections!).

Register O_NONBLOCK FDs in epoll RB-tree
NIC IRQ fires callback moving FD to ready list
epoll_wait returns strictly active K events
LT notifies continuously; ET demands EAGAIN drain
Handle socket without blocking reactor thread
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

Learning outcomes

  • Contrast linear O(N)O(N) bitmap copying and scans (select with its 1024-FD limit, poll) against stateful kernel epoll (RB-tree + lock-protected ready_list).
  • Distinguish Level-Triggered (LT) ease-of-use cleanly from Edge-Triggered (EPOLLET) efficiency and mandatory until EAGAIN socket 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 APIKernel Registration CostEvent Return ComplexityTrigger Modes & Scaling CapPrimary Edge Trap
select() (POSIX)Re-copies entire bitmask array user -> kernel every callScans O(max_fd)O(\text{max\_fd}) sequentially every returnHard 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 callLinear O(N)O(N) scan checking every idle slotNo 1024 FD limit; high CPU waste past ~2,000 idle streamsScans tens of thousands of sleeping HTTP/SSE pipes every loop cleanly
epoll (Level-Triggered default)Registers FD once via epoll_ctl(ADD) (RB-tree, O(log⁡N)O(\log N) insert)Returns strictly KK ready sockets (O(K)O(K) ready walk!)Scales smoothly cleanly to 100K–1M+ open idle streamsSingle 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 changeEliminates repeated notifications on partially drained sockets cleanlyUsed cleanly in Nginx / Envoy high-QPS loopsDeadlocks 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 until EAGAIN leaves 8 KB stranded 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 by epoll (EPERM or blocking read()); asynchronous local storage needs io_uring or dedicated blocking threadpools!
  • Omitting O_NONBLOCK on Sockets Under epoll: 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 EPOLLOUT Busy Spinning: Leaving write-interest EPOLLOUT subscribed cleanly when socket send buffers are empty wakes epoll_wait continuously in a 100% CPU busy spin (only subscribe EPOLLOUT when write returns EAGAIN or 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.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next