I/O Models: Blocking, epoll, io_uring
- Distinguish blocking/non-blocking and synchronous/asynchronous I/O, and name the five classic Unix I/O models
- Explain why epoll scales where select/poll do not, and the edge- vs level-triggered contract
- Compare the reactor (readiness) and proactor (completion) patterns, and where io_uring fits
- Describe exactly how Go's netpoller turns goroutine-per-connection code into an epoll event loop — and where it does not help (disk I/O)
- Apply zero-copy (
sendfile,splice) and know when TLS or user-space processing defeats it
TL;DR
- Blocking calls put the thread to sleep until data is ready; non-blocking calls return
EAGAINimmediately. Neither is "async": in both, your thread copies the data. Asynchronous I/O means the kernel completes the operation and notifies you. - select/poll scan every descriptor on every call (O(n)); epoll keeps an interest set in the kernel and returns only ready descriptors (O(ready)). That is what made the C10K problem tractable on Linux.
- Level-triggered epoll reports "still readable" until you drain the socket; edge-triggered reports only transitions, so you must read until
EAGAINor you stall. - Reactor = wait for readiness, then do the I/O yourself (epoll, Netty, Nginx, Redis). Proactor = submit the I/O, get a completion (io_uring, Windows IOCP).
- Go's netpoller sets sockets non-blocking, parks the goroutine on
EAGAINand uses edge-triggered epoll to wake it. You write blocking code; the runtime runs an event loop. Regular-file I/O is not pollable and still blocks a thread. - Zero-copy (
sendfile,splice) skips copying payload bytes through user space — Kafka consumers and static-file servers depend on it. TLS in user space breaks it unless kernel TLS is used.
Why it matters
An e-commerce platform's notification gateway holds 500,000 WebSocket connections open during a sale so it can push "order shipped" and "price drop" events. A bank's API gateway terminates TLS for tens of thousands of mobile clients and fans out to dozens of internal services. Both are dominated by mostly idle connections and lots of small reads and writes — exactly the regime where the I/O model decides whether you need 10 servers or 100.
Architecture interviews ask "how would you handle a million concurrent connections?" or "why is Nginx/Redis/Netty fast?". The answer is not "use more threads" — it is the I/O model, the number of copies and syscalls per message, and memory per connection.
Core concepts
Two axes and five models
Blocking vs non-blocking describes whether the call waits. Synchronous vs asynchronous describes who does the copy and when you learn about it. W. Richard Stevens' Unix Network Programming lists five models:
| Model | Waiting for data | Copying data to user space | Linux examples |
|---|---|---|---|
| Blocking | Thread sleeps in read() | Thread blocked during copy | Default sockets and files |
| Non-blocking | read() returns EAGAIN; caller retries (busy-poll) | Thread copies when data is there | O_NONBLOCK |
| I/O multiplexing | Block in select/poll/epoll_wait on many fds | Then read() the ready ones | epoll servers, Go netpoller |
| Signal-driven | Kernel sends SIGIO when ready | Thread copies | F_SETSIG — rarely used |
| Asynchronous | Kernel does both | Notification when complete | io_uring, Linux AIO (O_DIRECT files) |
The first four are all synchronous in POSIX terms: the copy happens in your thread.
select, poll, epoll
select | poll | epoll | |
|---|---|---|---|
| Interest set | Bitmaps rebuilt every call | Array passed every call | Kept in the kernel (epoll_ctl) |
| Cost per wait | O(max fd) scan | O(n) scan | O(ready) returned |
| fd limit | FD_SETSIZE, usually 1024 | None | None |
| Portability | Everywhere | POSIX | Linux only (BSD/macOS: kqueue; Windows: IOCP) |
How epoll works:
epoll_create1()creates an epoll instance (itself an fd).epoll_ctl(ADD/MOD/DEL)registers interest in fds; the kernel keeps them in a red-black tree and hooks a callback into each socket's wait queue.- When a socket becomes ready, the callback appends it to the instance's ready list.
epoll_wait()sleeps until the ready list is non-empty and returns up to N events — no scanning of idle connections.
Level-triggered vs edge-triggered
- Level-triggered (default):
epoll_waitkeeps reporting the fd while data remains in the buffer. Forgiving: if you read only part of the data, you are told again. - Edge-triggered (
EPOLLET): reported only when the state changes (new data arrives). You must read (or accept, or write) untilEAGAIN; otherwise leftover bytes sit there with no further notification and the connection appears hung. Fewer wake-ups; more discipline. EPOLLONESHOTdisables the fd after one event until re-armed — useful when several threads share one epoll instance and you want exactly one to handle a connection.- Thundering herd: many processes waiting on the same listening socket all wake for one connection. Linux mitigates it with
EPOLLEXCLUSIVE(4.5+) and, more commonly,SO_REUSEPORT(3.9+), which gives each worker its own accept queue (Nginxreuseport).
Asynchronous I/O and io_uring
- POSIX AIO in glibc is implemented with a user-space thread pool — not true kernel async.
- Linux native AIO (
io_submit) is only reliably asynchronous forO_DIRECTfile I/O; buffered I/O can silently block. Databases such as ScyllaDB and MySQL InnoDB used it withO_DIRECT. - io_uring (Linux 5.1, 2019, by Jens Axboe) is a general async interface built on two ring buffers shared between user space and the kernel:
- Batching many operations per
io_uring_entercuts syscalls; with SQPOLL a kernel thread polls the submission ring, so steady-state I/O needs no syscalls at all. Registered files and buffers avoid per-operation lookups. - Works for files (buffered and direct), sockets,
accept, timeouts, and chains of linked operations. - Caveat: io_uring has had many kernel vulnerabilities. Google reported that a large share of kernel exploits submitted to its bug bounty in 2022 used io_uring and restricted it on production servers and in ChromeOS/Android; recent Docker/containerd default seccomp profiles block the io_uring syscalls. Check your platform before designing around it. Go's standard library does not use io_uring.
Reactor vs proactor
| Reactor | Proactor | |
|---|---|---|
| Kernel API | epoll, kqueue, poll | io_uring, IOCP |
| Buffer ownership | Allocate buffer when ready (good for many idle connections) | Buffer committed at submit time (pre-registered pools help) |
| Disk files | Not supported (files are "always ready") | Supported |
| Examples | Nginx, Redis, Netty, Node.js (network side of libuv), Go netpoller | Windows servers on IOCP, io_uring-based runtimes |
C10K and C10M
- C10K (Dan Kegel, 1999): handling 10,000 concurrent clients on one server. Thread-per-connection hit limits in memory (stack per thread), scheduler overhead and
select's O(n) scans. The answer was event-driven servers on epoll/kqueue plus non-blocking I/O. - C10M (Robert Graham, around 2013): 10 million connections. At that scale the kernel network stack itself — interrupts, per-packet locking, copies — becomes the bottleneck. Answers include kernel bypass (DPDK, user-space TCP stacks),
AF_XDP/XDP, and per-core sharded designs. Few business systems need this; exchanges and telecom-grade gateways sometimes do.
How Go's netpoller works
Every net.Conn in Go wraps a non-blocking fd registered once with the runtime's epoll instance using edge-triggered mode (EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLET).
Key details:
- The scheduler calls
netpollwhen it runs out of work (findrunnable), andsysmonpolls periodically, so ready goroutines are picked up promptly. - Deadlines (
SetReadDeadline,http.Servertimeouts) are implemented with runtime timers that wake the parked goroutine with a timeout error — no extra threads. - Because registration is edge-triggered, the runtime itself retries until
EAGAIN; you never see it. - Cost per connection is a goroutine stack (starts at a few KiB) plus whatever buffers you allocate —
net/httpallocates read and write buffers of about 4 KiB each per connection. Rough budget: on the order of 10–20 KiB per mostly-idle HTTP connection, so 500k connections ≈ 5–10 GiB. Gateways that need millions of idle connections sometimes drop to raw epoll (for example the gobwas/ws approach described in "A Million WebSockets and Go") to avoid per-connection goroutines and buffers. - Regular files are not pollable — epoll always reports them ready.
os.File.Read,WriteandSyncon disk files are blocking syscalls that occupy an OS thread; the runtime hands the P off so other goroutines continue (see Processes & Threads). Thousands of concurrent slow disk operations means thousands of threads. Pipes and some devices are pollable and use the netpoller. - Go 1.19+ raises the soft
RLIMIT_NOFILEto the hard limit at startup, but the hard limit (container or systemdLimitNOFILE) still caps connections.
Zero-copy
Serving a file over a socket with read() + write() costs four copies (disk→page cache by DMA, page cache→user buffer by CPU, user buffer→socket buffer by CPU, socket buffer→NIC by DMA) and four user/kernel transitions.
sendfile(out, in): file → socket inside the kernel. With scatter-gather DMA the payload is never copied by the CPU. Kafka relies on this (JavaFileChannel.transferTo) to serve consumers straight from the page cache; Nginxsendfile onfor static files.splice/tee: move data between fds via a pipe without user-space copies (socket → socket proxies).MSG_ZEROCOPY(4.14+): send from user buffers without copying; completion arrives on the socket error queue. Pays off for large sends; small sends are cheaper to copy.copy_file_range: file → file in-kernel copies (and reflinks on supporting filesystems).- TLS defeats sendfile because encryption needs the bytes in user space — unless you use kernel TLS (kTLS), where the kernel (or NIC) encrypts. Kafka documents that zero-copy is lost when brokers use TLS without kTLS.
- Go:
io.Copy(tcpConn, file)callsTCPConn.ReadFrom, which usessendfileon Linux;io.Copybetween two TCP connections can usesplice. Wrapping the conn (e.g. inbufio.Writeror a TLS conn) hidesReadFromand falls back to a user-space copy.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Thread per connection, blocking I/O | Simplest code; isolation per request | Memory and context-switch cost limit concurrency to thousands | Low connection counts, CPU-heavy requests, legacy stacks |
| Goroutine per connection (Go netpoller) | Blocking-style code with epoll scalability; good multi-core use | ~10–20 KiB per idle conn; disk I/O still uses threads | Default for Go services and gateways up to hundreds of thousands of conns |
| Hand-written reactor (epoll/kqueue event loop) | Minimal memory per connection; full control | Callback/state-machine complexity; one slow handler stalls a loop | Proxies, massive idle-connection gateways, Redis-style servers |
| io_uring proactor | Fewest syscalls; async files and sockets; batching | Newer kernels; security restrictions; complex buffer management; not in Go stdlib | Storage engines, high-IOPS file servers, specialised proxies |
| Kernel bypass (DPDK, AF_XDP) | Lowest latency, millions of packets/s per core | Rewrites the network stack; busy-polling cores; ops burden | Exchanges, telecom, packet processing |
In practice
Goroutine-per-connection is all the code you write in Go:
package main
import (
"bufio"
"log"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("accept: %v", err)
continue
}
go handle(conn)
}
}
func handle(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
for {
// Idle timeout. ReadBytes parks the goroutine on the netpoller, not a thread.
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
line, err := r.ReadBytes('\n')
if err != nil {
return
}
if _, err := conn.Write(line); err != nil {
return
}
}
}
What the runtime does for you, written by hand (Linux only, level-triggered, simplified — no partial-write handling):
//go:build linux
package main
import (
"log"
"golang.org/x/sys/unix"
)
func main() {
lfd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM|unix.SOCK_NONBLOCK, 0)
if err != nil {
log.Fatal(err)
}
if err := unix.SetsockoptInt(lfd, unix.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil {
log.Fatal(err)
}
if err := unix.Bind(lfd, &unix.SockaddrInet4{Port: 9000}); err != nil {
log.Fatal(err)
}
if err := unix.Listen(lfd, 4096); err != nil {
log.Fatal(err)
}
epfd, err := unix.EpollCreate1(0)
if err != nil {
log.Fatal(err)
}
watch := func(fd int) error {
ev := unix.EpollEvent{Events: unix.EPOLLIN, Fd: int32(fd)}
return unix.EpollCtl(epfd, unix.EPOLL_CTL_ADD, fd, &ev)
}
if err := watch(lfd); err != nil {
log.Fatal(err)
}
events := make([]unix.EpollEvent, 256)
buf := make([]byte, 4096)
for {
n, err := unix.EpollWait(epfd, events, -1)
if err == unix.EINTR {
continue
}
if err != nil {
log.Fatal(err)
}
for i := 0; i < n; i++ {
fd := int(events[i].Fd)
if fd == lfd {
cfd, _, err := unix.Accept4(lfd, unix.SOCK_NONBLOCK)
if err == nil && watch(cfd) != nil {
unix.Close(cfd)
}
continue
}
r, err := unix.Read(fd, buf)
switch {
case err == unix.EAGAIN:
continue
case err != nil || r == 0: // error or peer closed
unix.Close(fd) // last close removes it from the epoll set
continue
}
_, _ = unix.Write(fd, buf[:r]) // real servers queue leftovers and wait for EPOLLOUT
}
}
}
Operational knobs and checks:
ss -s # socket summary: established, time-wait, orphaned
ss -ltn 'sport = :9000' # Recv-Q on a listener = accept backlog in use
sysctl net.core.somaxconn # accept-queue cap (default 4096 on 5.4+, 128 on older kernels)
cat /proc/"$(pgrep -n gateway)"/limits | grep 'open files'
strace -f -c -p "$(pgrep -n gateway)" # syscall mix: many tiny writes? epoll_wait storms?
Rules of thumb (approximate): one epoll-driven core can handle tens of thousands of mostly idle connections and on the order of 100k small requests per second, depending heavily on per-request work and TLS. TLS handshakes, not epoll, usually dominate CPU in API gateways — see TLS & HTTPS.
Common pitfalls
- Edge-triggered without draining. Reading once per event under
EPOLLET. Symptom: connections randomly "hang" with data inRecv-Q(ss -tn). - Blocking call inside an event loop. A synchronous DNS lookup, disk write or slow handler in a reactor thread (Node.js, Netty, Redis Lua scripts). Symptom: latency spikes across all connections on that loop.
- Assuming epoll helps disk I/O. Regular files are always "ready". Symptom: Go service with heavy file I/O shows hundreds of threads; event-loop servers stall on disk.
- File-descriptor limits. Container or systemd
LimitNOFILEtoo low. Symptom:accept: too many open files, then a hot loop of failed accepts. Back off on accept errors (Go'shttp.Serverdoes). - Small writes. Writing a response header and body in separate
write()calls, or log lines unbuffered. Symptom: high%sys, syscall-dominated profiles, Nagle/delayed-ACK latency in some stacks. - Breaking zero-copy by accident. Wrapping a
net.Connbeforeio.Copyfrom a file, or enabling TLS on Kafka brokers without budgeting the extra CPU. - Unbounded per-connection buffers. Allocating 64 KiB buffers for each of 200k connections = 12.5 GiB. Symptom: OOM kills on the gateway during peak.
Interview angle
- "How do you handle 1M concurrent connections?" — talk about the I/O model (epoll/netpoller), memory per connection (goroutine stack + buffers, kernel socket buffers), fd and port limits, sharding connections across instances behind an L4 load balancer, and heartbeats/idle timeouts. Mention when you would drop to a raw event loop.
- "Why is Redis single-threaded yet fast?" — in-memory operations + an epoll reactor: no lock contention, no context switches; the bottleneck is network and syscalls (hence I/O threads in Redis 6+).
- "Explain epoll vs select" and "edge vs level" — expect the O(n) vs O(ready) argument and the drain-until-EAGAIN rule.
- "How does Go make blocking code scale?" — netpoller, parking, edge-triggered registration, and the disk-I/O exception.
- Red flags: calling non-blocking I/O "async"; believing epoll works for files; claiming goroutines are free per connection; not knowing what zero-copy saves.
Self-check
1. Why is non-blocking I/O with epoll still called "synchronous" I/O?
Because your thread performs the data transfer: epoll only tells you that a descriptor is ready, then you call read() and the copy from kernel to user buffer happens in your thread. In asynchronous I/O (io_uring, IOCP) the kernel performs the copy and notifies you when the data is already in your buffer.
2. You switch an epoll server to edge-triggered mode and some clients hang. What is the likely bug?
The handler reads only once per event. With edge-triggered epoll you get one notification per state change; if bytes remain in the socket buffer after your read, no new event arrives until more data comes. Loop on read()/accept() until EAGAIN.
3. Walk through what happens inside the Go runtime when a handler calls conn.Read and no data has arrived.
The runtime calls read() on the non-blocking fd and gets EAGAIN. It parks the goroutine on the fd's pollDesc and the scheduler runs other goroutines on the same thread. Later, netpoll (from findrunnable or sysmon) sees the fd readable via epoll_wait, marks the goroutine runnable and queues it. When it runs, it retries read() and returns the data.
4. A Go service that writes many audit files concurrently shows 800 OS threads. Explain and suggest mitigations.
Regular-file I/O can't use the netpoller, so each in-progress write/fsync blocks an OS thread; the runtime creates more threads so other goroutines can run. Mitigations: bound concurrent file operations with a semaphore or a fixed worker pool, batch writes (buffer and write larger chunks, fewer fsyncs), or move audit output to a log pipeline/queue instead of local files.
5. When does sendfile not help, and what can you do instead?
When the bytes must be transformed in user space — TLS encryption in user space, compression, templating — or when the source is not a file in the page cache. Options: kernel TLS so encryption happens in the kernel (keeping sendfile), pre-compressed static assets, or accept the copy and optimise elsewhere.
6. Scenario: design the connection layer for a push-notification gateway with 2 million mostly idle mobile connections. What do you consider?
Per-connection memory (goroutine + buffers vs raw epoll with lazily allocated buffers; kernel socket buffer sizes), fd limits and ephemeral ports, sharding across instances behind an L4 load balancer with consistent routing, heartbeats and idle timeouts, TLS termination cost and session resumption, graceful draining on deploys (connection migration), and a backplane (pub/sub) to route a message to the instance holding the user's connection.
Exercise
Measure the I/O model, don't just read about it.
- Run the goroutine-per-connection echo server above. Write a Go load generator that opens 50,000 connections (raise
ulimit -nand use several source IPs orip_local_port_rangeif needed), sends one line per connection every 10 s, and measures echo latency. - Record server RSS, goroutine count and thread count (
/proc/PID/status) at 1k, 10k and 50k connections. Compute memory per connection. - Run
strace -f -c -p PIDfor 10 seconds under load and note the dominant syscalls (epoll_pwait,read,write,futex). - Run the raw epoll server and repeat steps 2–3. Compare memory per connection and CPU per message.
- Bonus: serve a 1 GiB file with
io.Copy(conn, file)and again withio.Copy(bufio.NewWriter(conn), file); compare CPU usage and confirm withstrace -e trace=sendfile,read,writewhich path was used.
Done looks like: a table (server type, connections, RSS, memory/conn, top syscalls) and a paragraph recommending a model for a 500k-connection notification gateway.
Further reading
- W. Richard Stevens, Unix Network Programming, Vol. 1 — the I/O models chapter
- Michael Kerrisk, The Linux Programming Interface — alternative I/O models (select, poll, epoll, signal-driven I/O)
man 7 epoll: https://man7.org/linux/man-pages/man7/epoll.7.html- Jens Axboe, "Efficient IO with io_uring" (2019)
- Dan Kegel, "The C10K problem"
- Sergey Kamardin, "A Million WebSockets and Go" (2017)
- Go source:
runtime/netpoll.goandruntime/netpoll_epoll.go
Related
- TCP & UDP — what happens below the socket: buffers, backlog, retransmits
- Polling, WebSocket & SSE — the long-lived-connection workloads this page sizes
- Proxies, Load Balancers & API Gateways — event-loop servers in the request path
- Goroutines & Channels — the goroutine model the netpoller supports
- Message Queues & Event Streaming — Kafka's page cache and zero-copy design
- Processes & Threads — GMP and syscall handoff
- File Systems & Durable Storage — the disk side of I/O
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).