Skip to main content

I/O Models: Blocking, epoll, io_uring

Learning objectives
  • 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 EAGAIN immediately. 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 EAGAIN or 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 EAGAIN and 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:

ModelWaiting for dataCopying data to user spaceLinux examples
BlockingThread sleeps in read()Thread blocked during copyDefault sockets and files
Non-blockingread() returns EAGAIN; caller retries (busy-poll)Thread copies when data is thereO_NONBLOCK
I/O multiplexingBlock in select/poll/epoll_wait on many fdsThen read() the ready onesepoll servers, Go netpoller
Signal-drivenKernel sends SIGIO when readyThread copiesF_SETSIG — rarely used
AsynchronousKernel does bothNotification when completeio_uring, Linux AIO (O_DIRECT files)

The first four are all synchronous in POSIX terms: the copy happens in your thread.

select, poll, epoll​

selectpollepoll
Interest setBitmaps rebuilt every callArray passed every callKept in the kernel (epoll_ctl)
Cost per waitO(max fd) scanO(n) scanO(ready) returned
fd limitFD_SETSIZE, usually 1024NoneNone
PortabilityEverywherePOSIXLinux only (BSD/macOS: kqueue; Windows: IOCP)

How epoll works:

  1. epoll_create1() creates an epoll instance (itself an fd).
  2. 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.
  3. When a socket becomes ready, the callback appends it to the instance's ready list.
  4. 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_wait keeps 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) until EAGAIN; otherwise leftover bytes sit there with no further notification and the connection appears hung. Fewer wake-ups; more discipline.
  • EPOLLONESHOT disables 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 (Nginx reuseport).

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 for O_DIRECT file I/O; buffered I/O can silently block. Databases such as ScyllaDB and MySQL InnoDB used it with O_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_enter cuts 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​

ReactorProactor
Kernel APIepoll, kqueue, pollio_uring, IOCP
Buffer ownershipAllocate buffer when ready (good for many idle connections)Buffer committed at submit time (pre-registered pools help)
Disk filesNot supported (files are "always ready")Supported
ExamplesNginx, Redis, Netty, Node.js (network side of libuv), Go netpollerWindows 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 netpoll when it runs out of work (findrunnable), and sysmon polls periodically, so ready goroutines are picked up promptly.
  • Deadlines (SetReadDeadline, http.Server timeouts) 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/http allocates 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, Write and Sync on 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_NOFILE to the hard limit at startup, but the hard limit (container or systemd LimitNOFILE) 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 (Java FileChannel.transferTo) to serve consumers straight from the page cache; Nginx sendfile on for 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) calls TCPConn.ReadFrom, which uses sendfile on Linux; io.Copy between two TCP connections can use splice. Wrapping the conn (e.g. in bufio.Writer or a TLS conn) hides ReadFrom and falls back to a user-space copy.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Thread per connection, blocking I/OSimplest code; isolation per requestMemory and context-switch cost limit concurrency to thousandsLow 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 threadsDefault for Go services and gateways up to hundreds of thousands of conns
Hand-written reactor (epoll/kqueue event loop)Minimal memory per connection; full controlCallback/state-machine complexity; one slow handler stalls a loopProxies, massive idle-connection gateways, Redis-style servers
io_uring proactorFewest syscalls; async files and sockets; batchingNewer kernels; security restrictions; complex buffer management; not in Go stdlibStorage engines, high-IOPS file servers, specialised proxies
Kernel bypass (DPDK, AF_XDP)Lowest latency, millions of packets/s per coreRewrites the network stack; busy-polling cores; ops burdenExchanges, 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 in Recv-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 LimitNOFILE too low. Symptom: accept: too many open files, then a hot loop of failed accepts. Back off on accept errors (Go's http.Server does).
  • 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.Conn before io.Copy from 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.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Measure the I/O model, don't just read about it.

  1. Run the goroutine-per-connection echo server above. Write a Go load generator that opens 50,000 connections (raise ulimit -n and use several source IPs or ip_local_port_range if needed), sends one line per connection every 10 s, and measures echo latency.
  2. Record server RSS, goroutine count and thread count (/proc/PID/status) at 1k, 10k and 50k connections. Compute memory per connection.
  3. Run strace -f -c -p PID for 10 seconds under load and note the dominant syscalls (epoll_pwait, read, write, futex).
  4. Run the raw epoll server and repeat steps 2–3. Compare memory per connection and CPU per message.
  5. Bonus: serve a 1 GiB file with io.Copy(conn, file) and again with io.Copy(bufio.NewWriter(conn), file); compare CPU usage and confirm with strace -e trace=sendfile,read,write which 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.go and runtime/netpoll_epoll.go
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).