NIO & Reactor Patterns: select, poll, epoll Deep Dive with Netty Internals
This article traces the evolution from select to epoll, explains LT/ET semantics, compares three Reactor thread models, and dissects Netty's optimizations including selectedKeys array replacement, busy-wait workaround, and watermark-based backpressure.
Reading font
Three Classic Incidents That Frame the Problem
The article opens with three production incidents that map directly to three architectural lessons:
Incident 1 — 1024 connection ceiling: A gateway hit FD_SETSIZE (default 1024) because the underlying
select</call> uses a fixed-size bitmap. New connections were refused with <code>connection reseton the client side, misleading ops to investigate downstream services instead of the syscall itself.
Incident 2 — OP_WRITE spins CPU to 100%: A push service registered OP_WRITE permanently. Since the send buffer almost always has space, Selector.select() returned immediately every time, turning the event loop into a busy spin. The fix: register OP_WRITE only when a write cannot complete, then deregister immediately after the buffer drains.
Incident 3 — Single-thread Reactor freezes the whole site: A synchronous DNS lookup inside an event handler blocked the sole Reactor thread for 5 seconds, stalling every connection on that thread. The lesson: multiplexing reuses threads; one slow handler stalls all connections sharing that thread.
These incidents correspond to three lessons: I/O model sets connection-density ceiling; event semantics (when/who gets notified) must be internalized; thread model determines fault isolation.
From select to epoll: Three Structural Revolutions
2.1 Core Differences of Three Generations
// Three syscall generations compared
select: fd_set bitmap, cap 1024,
O(n) full scan, full copy each call
poll: pollfd array, no cap,
still O(n) scan + full copy
epoll: red-black tree stores fd + ready list,
O(1) only takes ready fds,
register once, kernel callback maintainsselect's three sins: fd limit 1024; full user-to-kernel copy per call; linear scan after return to find ready fds. Designed for low-connection eras.
poll's improvement and stagnation: Linked list removes the fd cap, but full copy + full scan remain. At 10k connections with only 1 ready, you still scan 10k entries.
epoll's root-cause fix: Splits registration ( epoll_ctl) from waiting ( epoll_wait). Registration happens once — fd enters kernel red-black tree. When data arrives, driver callback ( ep_poll_callback) pushes the fd onto a ready list. epoll_wait merely drains that list — complexity drops from O(n) to O(ready).
Concrete intuition: 10k connections, 50 ready per round. select copies and scans 10k for 50 events (200× waste). epoll processes only 50. The larger the connection pool and the sparser the activity, the greater epoll's advantage — exactly the profile of push, IM, and gateway workloads.
2.2 epoll's Two Tables: Red-Black Tree & Ready List
Only two data structures matter:
Red-black tree — all fds managed by the epoll instance; add/remove/lookup are logarithmic, enabling "register once, wait many".
Ready list — device driver callbacks ( ep_poll_callback) append ready fds here; epoll_wait returns this list.
Key insight: epoll is fast not because it "traverses smarter" but because it turns "which fd is ready" from the caller's guess into the kernel's record. Ready info is written by callback at data-arrival time; epoll_wait just collects results. Also debunks a myth: epoll does not use shared memory/mmap — ready events travel via ordinary kernel-to-user copy, but the volume shrinks from "all" to "only ready".
2.3 LT vs ET: Two Notification Semantics
// LT (level-triggered, Netty default)
// As long as buffer has data, every epoll_wait repeats notification
read(fd, buf, 100); // read only 100B
// 900B left -> next call still notifies
// Until drained, safe but verbose
//
// ET (edge-triggered, notify once)
// Only on "state change" instant
// Must drain completely:
while ((n = read(fd, buf,
sizeof(buf))) > 0) {
process(buf, n);
}
// fd must be non-blocking: when no data
// read returns EAGAIN instead of blockingOne-line distinction: LT asks "still data?"; ET asks "new data?". LT may repeat notify (keeps calling until drained); ET notifies once then goes silent (miss the drain and you never get reminded). ET saves repeated wakeups but demands a strict programming model — loop until EAGAIN, and only works with non-blocking fds.
2.4 Three Reactor Shapes: How "Hands" Are Arranged
Single-thread Reactor: One thread does accept + all I/O + business logic (early Redis). Simplest, but any slow step stalls everything — Incident 3.
Multi-thread Reactor: Reactor thread only dispatches; business handlers go to a worker pool — separates "wait" from "compute", tolerates heavy business, but codec for massive connections still bottlenecks on one dispatch thread.
Master-slave Reactor: Master Reactor dedicated to accept; N slave Reactors each own a partition of connections for I/O and codec. This is the Netty boss/worker prototype , from Doug Lea's "Scalable IO in Java". The paper's multi-thread and master-slave are progressive: first separate compute, then separate accept. Netty does both and adds a task queue to fold timed tasks into the same thread.
2.5 Java's Hidden Trap: Same Code, Different Fate by Platform
Incident 1 bites harder in Java: JDK NIO is a cross-platform abstraction — Windows Selector uses select (1024 cap), Linux uses epoll . Dev machine (Windows) passes tests; Linux production handles 100k connections; but a Windows-deployed service or certain containers hit the 1023 ceiling. Debug tip: print sun.nio.ch.Util implementation class names to confirm which SelectorProvider is active — a concrete instance of "config drift" (from the observability article) at the network layer.
Core Flow: One Request Packet's Complete Journey
// One request packet's journey (Linux)
NIC DMA -> kernel socket recv queue
|-> callback ep_poll_callback
|-> fd enqueued to epoll ready list
|-> epoll_wait wakes Reactor thread
|-> fd -> SelectionKey -> Channel
|-> pipeline.fireChannelRead
|-> decode -> decode -> business
|-> write to outbound buffer -> flush
|-> syscall send -> NIC
|-> back to epoll_wait continue waitingKernel receives: NIC DMAs data into kernel buffer, protocol stack queues it on the socket's receive queue, then callback ep_poll_callback pushes the fd onto epoll's ready list.
Wakeup: Reactor thread blocked in epoll_wait wakes, receives "fd X readable" — note it gets an event coordinate , not the data itself.
Event mapping: Framework (JDK Selector / Netty) maps fd back to SelectionKey, then to Channel object; ready bit ( OP_READ) is set.
Pipeline processing: fireChannelRead flows through decoders and business handlers; bytes land in ByteBuf, frame decoder slices complete request frames.
Write back: Business result serialized by encoder, write to channel's send buffer, flush triggers real write/send syscall — if send buffer fills, Netty parks remaining in outbound buffer, registers OP_WRITE to wait for writable (Incident 2's correct usage).
Return to loop: After processing this batch, Reactor thread blocks again on epoll_wait — the entire lifecycle is a never-exiting for(;;).
See the chain clearly: from kernel callback to pipeline, "one event" is handled end-to-end by the same thread — no lock contention, no context switches. That is Reactor's high-throughput essence, and the origin of the "handlers must not block" iron law.
Core Source: From Handwritten NIO Reactor to Netty Optimizations
4.1 Single-Thread Reactor Complete Implementation (Pure NIO)
public class ReactorEcho {
public static void main(
String[] args) {
Selector sel = Selector.open();
ServerSocketChannel ssc =
ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(
9000));
ssc.configureBlocking(false);
ssc.register(sel, OP_ACCEPT);
while (true) {
sel.select();
Iterator<SelectionKey> it =
sel.selectedKeys()
.iterator();
while (it.hasNext()) {
dispatch(it.next());
it.remove(); // must delete
}
}
}
}4.2 Accept and Read Two Branches
static void dispatch(SelectionKey k)
throws IOException {
try {
if (k.isAcceptable())
accept(k);
else if (k.isReadable())
read(k);
} catch (Exception e) {
k.cancel(); // cancel on error
}
}
static void accept(SelectionKey k)
throws IOException {
ServerSocketChannel ssc =
(ServerSocketChannel) k.channel();
SocketChannel ch = ssc.accept();
ch.configureBlocking(false);
// attachment holds read buffer, register read
ch.register(k.selector(), OP_READ,
ByteBuffer.allocate(1024));
}
static void read(SelectionKey k)
throws IOException {
SocketChannel ch =
(SocketChannel) k.channel();
ByteBuffer buf = (ByteBuffer)
k.attachment();
int n = ch.read(buf);
if (n == -1) { // peer closed
k.cancel();
ch.close();
return;
}
buf.flip();
ch.write(buf); // echo back
buf.compact();
}These 60 lines are the Reactor skeleton: select for events, dispatch, accept new connections and register OP_READ, read and consume data. Three details worth pausing on: attachment holds per-connection read/write buffers, avoiding a per-connection Map lookup; read returning -1 means peer closed — must cancel + close as a pair; exception handler must cancel and close resources together — these three are where beginners leak. Compare with the previous article's Netty bootstrap code — Netty has no magic; it just productizes the correct writing, error handling, and extension points of these 60 lines .
4.3 JDK Internals: EPollSelectorImpl.doSelect
Look one layer down at how JDK translates Selector into epoll calls — this layer is usually invisible but decides where "register once" actually happens.
// Linux JDK actually uses
// EPollSelectorImpl (simplified)
protected int doSelect(long timeout)
throws IOException {
// 1. JNI calls epoll_wait blocking
int n = EPoll.wait(epfd,
pollArrayAddress,
numFds, timeout);
// 2. Ready fds already placed by kernel
// into event array, map each back
// to SelectionKey and set ready bits
for (int i = 0; i < n; i++) {
int fd = ...;
int events = ...;
updateReadyOps(fd, events);
}
return readyCount;
}
// Registration: epoll_ctl(ADD) into red-black tree
// Ready: kernel callback enqueues to ready list
// epoll_wait only takes list -> O(1)4.4 Netty's selectedKeys Array Optimization
// JDK's selectedKeys is a Set,
// iteration needs iterator, boxing overhead
// Netty swaps via reflection to array direct access:
private void processSelectedKeys()
throws Exception {
if (selectedKeys != null) {
processKeysOptimized();
} else {
processKeysDefault();
}
}
// Optimized path (simplified):
private void processKeysOptimized() {
for (int i = 0;; i++) {
SelectionKey k =
selectedKeys[i];
if (k == null) break;
selectedKeys[i] = null;
Object a = k.attachment();
processSelectedKey(k,
(AbstractNioChannel) a);
}
}Two details to circle: attachment() directly yields the Netty Channel object, saving another key.channel() conversion; after processing, slot is nulled immediately , same rationale as "iterator remove" — if not cleared, next loop reprocesses the stale key. On the hot path, Netty flattens every micro-overhead.
4.5 Busy-Wait Workaround: Netty's Most Famous Patch
Application code can be correct and JDK still misbehaves. The busy-wait bug doesn't pick business code; it picks kernel versions. Netty, as a framework, must shield everyone.
// Selector busy-wait workaround (simplified)
int selectCnt = 0;
for (;;) {
int selected =
select(deadline);
boolean has = hasReadyChannels();
if (selected != 0 || has) {
selectCnt = 0;
break;
}
// Returns 0 and no events = busy-wait
if (++selectCnt >= 512) {
// Rebuild Selector, migrate all
// Channel registrations
rebuildSelector();
selectCnt = 0;
break;
}
}JDK's bug: select should block but returns 0 immediately. Netty's countermeasure: count + replace — after 512 consecutive spurious wakeups, create a fresh Selector and migrate all channel registrations wholesale. This is the "framework eats the pitfalls" mentioned in the previous article — more select optimizations appear in the next one.
Advanced Topics: Three Deep-Water Questions
5.1 Why Netty Chooses LT Over ET
Theoretically ET avoids repeated wakeups and performs better (Redis, Nginx use ET). Netty defaults to LT for three reasons:
Programmer-friendly — if user handler forgets to drain data, next round still notifies; framework can safety-net. ET: one missed drain = permanent event loss.
Consistent with NIO semantics — JDK Selector is LT; Netty's NIO transport wraps it directly.
Limited gain — Netty's own watermarks and outbound buffering already suppress repeated wakeups; ET's saved wakeups are a tiny fraction. Want ET? Netty offers EPollIoHandler edge-triggered variant, but user must guarantee full drain.
5.2 Thundering Herd: One Connection Wakes a Roomful
Accept thundering herd: Multiple threads/processes blocked on same listen fd; one connection wakes all, only one accept succeeds, rest wake for nothing. Kernel later fixed with WQ_FLAG_EXCLUSIVE — wake only one.
Epoll thundering herd: Multiple epoll instances (or multiple threads waiting on same epoll) monitoring same fd still herd. Kernel provides EPOLLEXCLUSIVE flag to mitigate; more thorough fix is SO_REUSEPORT — each thread independently binds same port, kernel hashes by 4-tuple to shard. Nginx's multi-process model relies on it.
Netty is naturally immune: A channel's I/O is handled only by its bound EventLoop; listen socket belongs to a single boss thread — the binding relationship itself eliminates contention , which is the core of the next article's EventLoop design.
5.3 AIO's Death and io_uring
Java AIO ( AsynchronousSocketChannel) promised beauty: kernel completes copy then callbacks, fully async. Reality: Linux lacks mature native AIO; JDK simulates with epoll + thread pool, adding callback scheduling overhead — performance worse than direct NIO multiplexing. Netty 4.0 had AioEventLoopGroup, quickly deprecated and removed in 4.1. The next-gen answer is io_uring : submission/completion ring buffers in shared memory, batch submit and reap, truly saving syscall counts too. Epoll remains today's workhorse; io_uring is the future worth watching.
5.4 Correct Write Event Posture & Watermarks
Incident 2 deserves expansion because it defines the correct write-event usage.
Read events are naturally scarce — no peer packet, no event.
Write events are naturally redundant — ready as long as send buffer has a slot.
Correct flow: business write puts data into send buffer (usually completes instantly); only when buffer fills and a write cannot complete do you register OP_WRITE, wait for writable notification, continue writing, deregister immediately after done .
Netty productizes this as watermarks : outbound buffer exceeds highWaterMark (default 64KB) → channel becomes unwritable, isWritable() returns false; drops below lowWaterMark (default 32KB) → writable again. Business code listens to writability changes to pause data production — this is backpressure at the network layer, far safer than manual OP_WRITE management.
5.5 Memory Accounting for 10k Connections
Beyond the model, memory is the real C1000K gate. Do the math:
BIO: 10k connections = 10k threads; thread stack at 1MB = 10GB — dead before business objects even count.
NIO: 10k connections = dozens of EventLoop threads; each connection one read/write ByteBuf (e.g., 32KB base) → ~300MB for 10k, controllable and tunable.
Per-connection resident memory drops from MB to KB — that's multiplexing's true memory-side dividend, and why pooled ByteBuf (article 4) exists.
5.6 High-Frequency Pitfall Checklist
Forget it.remove() . selectedKeys not cleared; LT re-processes same ready key every round — duplicate responses at best, CPU spin at worst.
Permanent OP_WRITE registration. Send buffer almost always has space → event always ready → loop becomes busy spin (Incident 2). Register only on partial write, deregister immediately after drain.
Forget configureBlocking(false) after accept. New connection defaults to blocking; one read can park the entire Reactor thread.
Forget cancel / close on connection close. SelectionKey invalid but channel open → fd leak → eventual fd exhaustion.
LT: register OP_READ but don't consume data. Ready state persists → event storm → CPU 100%.
ET: forget loop until EAGAIN . Read one chunk, remainder never notified → "connection mysteriously stalls".
Don't set SO_BACKLOG . Connection storm fills kernel accept queue → connect timeout (echoes article 01 pitfall 4).
Leave blocking ops on event thread. DNS, sync DB, file write — Incident 3's site-wide freeze. All latency logic must go to worker pool.
Learning Path & 20 Interview Questions
6.1 Four-Stage Roadmap
Starter (3 days): Type and run the 4.1/4.2 Reactor Echo; deliberately hit pitfalls 1 and 3, observe CPU and blocking — pits teach better than a week of reading.
Intermediate (1 week): strace -e trace=epoll_wait,epoll_ctl on java process; match 2.2's two tables to real syscalls; log one full "register" and one full "wait" with all parameters.
Deep (2 weeks): Read EPollSelectorImpl full source and Netty NioEventLoop 's select / processSelectedKeys / rebuildSelector; build a multi-thread Reactor — separate dispatch from business pool, feel the engineering gain of splitting "accept" from "compute".
Practice (ongoing): wrk/wrk2 load-test same service under BIO vs NIO; compare connection ceiling, CPU curve, P99; tune ulimit and somaxconn; turn theory into your own benchmark report — strongest interview material.
6.2 Twenty Interview Q&A (Selected Highlights)
Q1: select/poll/epoll differences? select bitmap 1024 cap, full copy + O(n) scan; poll array no cap but same O(n) copy+scan; epoll splits register/wait — epoll_ctl into kernel rbtree (once), kernel callback enqueues ready fds to ready list, epoll_wait drains list → O(1). Advantage grows with connection count.
Q2: Why epoll efficient? Uses mmap? Core: "kernel records ready, caller only collects". Register once in rbtree; data arrival → driver callback ( ep_poll_callback) pushes fd to ready list; epoll_wait takes list — no full scan/copy. No mmap — ready events are ordinary kernel-to-user copy, just volume shrinks from "all" to "ready only". Common misconception.
Q3: LT vs ET? Why Netty defaults LT? LT: data present → every epoll_wait repeats; ET: state-change instant only. Netty picks LT: safer programming model (missed drain → next round still notifies, framework can guard); matches JDK Selector LT semantics (lowest wrapping cost); ET's saved wakeups negligible under Netty's watermarks. Redis/Nginx use ET because they fully control read/write loops.
Q4: Why ET requires non-blocking I/O? ET demands drain loop; loop exits on read returning EAGAIN (no data now). If fd blocking, final read (buffer empty) blocks the thread in syscall, halting the entire event loop. ET and non-blocking fd are a bound pair.
Q5: Three Reactor shapes — suitable scenarios? Single-thread: many connections, ultra-light per-request (early Redis), simple lock-free; Multi-thread: offload business to pool, fits heavy logic; Master-slave: master accepts, slaves partition massive connections for I/O/codec, fits long-lived high-concurrency ingress. Netty boss/worker = master-slave standard impl.
Q6: Netty boss/worker vs master-slave mapping? Boss group = master Reactor: only runs listen channel, accepted connections round-robin to workers; Worker group = slave Reactors: each NioEventLoop binds one Selector, owns a batch of channels for I/O/codec. Channel-to-EventLoop binding is lifetime, giving single-thread no-lock guarantee.
Q7: What is thundering herd? Epoll solutions? One event wakes all waiters but only one succeeds; rest pay wake/schedule cost for nothing. Accept herd fixed by kernel mutex wake; epoll herd mitigated by EPOLLEXCLUSIVE (wake one); thorough fix SO_REUSEPORT — each thread binds same port, kernel 4-tuple hashes to shard, zero contention. Netty avoids by model: one listen socket → one EventLoop; binding eliminates competition.
Q8: Selector busy-wait bug? Netty workaround? Some Linux kernels: select() returns 0 with no events → event loop degrades to CPU 100% spin. Netty counts spurious wakeups in NioEventLoop: select returns 0 and no ready channels → counter++; consecutive > threshold (default 512) → rebuild Selector, migrate all channel registrations, reset counter. "Detect + replace" self-healing patch.
Q9: Netty's selectedKeys optimization? JDK uses HashSet → iterator overhead. Netty reflects to swap internal Set with own array at Selector open; processes ready events by direct index access, nulls slot after handling — saves iterator; plus attachment gives Netty Channel directly, avoids channel() conversion. Micro-optimization on hot path, pays off at scale.
Q10: Why Netty dropped AIO? Linux long lacked mature native async I/O (POSIX AIO = user-thread simulation); JDK AIO on Linux = epoll + thread pool wrapper, callback scheduling adds overhead, perf worse than direct NIO multiplexing, API more complex. Netty 4.0's AioEventLoopGroup removed in 4.1. True native async is io_uring — Netty incubating support.
Q11: Will io_uring replace epoll? io_uring uses shared-memory submit/completion dual rings, batches multiple I/Os per submit/reap, saves syscall count, supports file I/O — capability covers epoll. But production adoption still gated by kernel version (5.1+), ecosystem maturity, security policies. Network programming mainstream remains epoll. Sound verdict: io_uring is direction, epoll is now; learning priority: master epoll semantics first.
Q12: System configs for C1000K beyond model? Model is prerequisite; also need: ulimit to millions; net.core.somaxconn and app backlog raised; net.ipv4.tcp_max_syn_backlog, ip_local_port_range expanded; net.ipv4.tcp_tw_reuse for port reuse; per-connection buffers via tcp_wmem / tcp_rmem shrunk or rely on Netty pooling; disable unnecessary conntrack. Consistent theme — minimize per-connection kernel overhead.
Q13: Forget selectedKeys remove → what happens? Set not auto-cleared; same ready key reappears next select; LT → reprocessed — Echo shows duplicate responses; business shows duplicate consumption or CPU spin. Correct: it.remove() immediately after iterate, or Netty-style null the array slot.
Q14: interestOps vs readyOps? interestOps = "what I care about" — declared at register, dynamically modifiable; readyOps = "what happened now" — kernel sets after ready. key.isReadable() checks readyOps. Incident 2's OP_WRITE issue: treating "care about write" as permanent — write interest must be short-lived, on-demand.
Q15: Channel-EventLoop binding guarantees? Channel binds to one fixed EventLoop from registration; all its I/O events and user tasks run serially on that thread — handlers need no locks, event order guaranteed, no same-channel concurrent processing by two threads. Cross-channel still parallel, so overall throughput unaffected. Cost: blocking inside one channel stalls others on same thread — boundary of "no-block" iron law.
Q16: How to benchmark Reactor model gains? Same machine, same business logic, BIO vs NIO versions; compare three numbers: connection ceiling (BIO thread-bound, NIO fd/memory-bound), CPU curve (NIO low and flat), P99 latency (BIO degrades linearly with connections, NIO stable). Add strace on NIO to verify epoll_wait frequency — numbers + syscall evidence beats memorized conclusions.
Q17: One fd registered to multiple epoll instances? Allowed but dangerous: data arrival notifies every epoll (herd); multiple threads concurrent read race — half request read by A, half by B. Correct: single consumer per fd — either one epoll per fd, or SO_REUSEPORT for kernel-level connection (not event) sharding — shard to connection level, each connection still single-thread exclusive.
Q18: epoll_wait timeout usage? Netty's play? -1 block forever, 0 poll return, positive = max ms. Netty doesn't hardcode: if EventLoop has scheduled tasks (idle detection), uses "nearest task deadline" as timeout — ensures no spin yet wakes on time for tasks; no tasks → block forever. Source of "select with deadline" in article 01's run loop.
Q19: Channel close — what cleanup does Netty do? Sequence: cancel registration from Selector (equiv. cancel, fd removed from epoll rbtree); close underlying socket (release fd); fire pipeline channelInactive and handler removal callbacks; release unread ByteBuf refcounts. Missing any step leaves traces: busy-wait CPU, fd leak, missed offline event, off-heap leak (LEAK logs). Troubleshoot connection leaks by checking these four steps.
Q20: Handwritten Reactor vs Netty — what's missing? At least five: multi-thread Reactor connection partitioning & load distribution; ByteBuf pooling & refcounting; full sticky-packet/frame-decoder suite; unified exception propagation & connection cleanup; busy-wait self-heal & safety patches. This article's 60-line skeleton "runs"; the gap to "production-ready" is exactly these — the roadmap the next articles fill component by component.
6.3 One-Page Cheat Sheet
Three syscalls: select / poll / epoll
1024 -> no cap -> O(1)
epoll two tables: rbtree stores reg
ready list stores callback result
Two semantics: LT repeat notify (Netty)
ET once notify + non-blocking
Three shapes: single -> multi
-> master-slave (boss/worker)
Three big pits: OP_WRITE resident
forget remove / forget cancel
One line: reuse is thread, bind
eliminates contention, block is enemy
Watermark: exceed high unwritable, back
to low restore -> write-side backpressureSummary: select→poll→epoll solves "how to wait"; LT/ET defines "when to notify"; Reactor three shapes decide "who does the work". Internalize the mainline — "kernel callback + ready list + event thread serial processing" — and Netty's EventLoop reduces to engineering details. Next article dives in: "Netty Core Components & Bootstrap Full Flow — From ServerBootstrap to Pipeline's Seventeen Hops", walking the previous article's bootstrap template line by line.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.