I/O models: blocking, non-blocking, epoll and file descriptors
How I/O works from the system call down to DMA and interrupts, the four bottleneck groups and how to measure them, the five Unix I/O models, select/poll/epoll, Java NIO, Tomcat, Netty, virtual threads, sequential vs random disk I/O, fsync, and Too many open files.
On this page
1. The problem
A service reads a 20 MB file byte by byte with FileInputStream.read() in 7 seconds, though the file is already in the page cache; reading 64 KB blocks takes 10 ms. In the same service, a WebFlux handler calls JDBC: p99 jumps to several seconds while CPU sits at 15%.
2. Key idea
A system call costs under one to a few µs; a random HDD read is 5–10 ms, a datacenter round trip 0.1–0.5 ms. Most of a request's time is waiting, so how you wait decides whether a server handles 200 or 50,000 connections.
A network read has two phases: waiting for data to reach the kernel, then copying it to the application. The models differ in which phase blocks the thread.
| Model | Waiting phase | Example |
|---|---|---|
| Blocking | blocks the thread | InputStream.read(), JDBC |
| Non-blocking | returns EAGAIN at once, you ask again |
sockets with O_NONBLOCK |
| Multiplexing | one thread waits on many fds in epoll_wait |
Java NIO, Netty, Nginx, Redis |
| Asynchronous | the kernel notifies after copying | io_uring, Windows IOCP |
select and poll scan all N fds every time (O(N)); epoll registers once with epoll_ctl and returns only ready fds. macOS uses kqueue.
2.1 Tomcat, Netty or virtual threads?
All three sit on epoll; they differ in which thread runs your code.
| Approach | Use when | Don't use when |
|---|---|---|
| Tomcat NIO, 200-worker pool | CRUD services, familiar blocking code | thousands of requests waiting on slow I/O at once |
| Netty, WebFlux (event loop) | gateways, streaming, long-lived connections | handlers calling JDBC, block(), reading large files |
Virtual threads (spring.threads.virtual.enabled=true) |
blocking code, many requests waiting on DB or HTTP | pure CPU work |
With virtual threads, the 200-worker limit moves to the connection pool (HikariCP defaults to 10): back-pressure in the right place, as long as acquiring a connection has a timeout.
3. In Java
Without a buffer, every byte is a system call.
// Slow: each read() enters the kernel. 20 MB ~ 7 s
try (var in = new FileInputStream(path)) {
int b;
while ((b = in.read()) != -1) count++;
}
// Fast: read 64 KB blocks. 20 MB ~ 10 ms
try (var in = new BufferedInputStream(new FileInputStream(path), 64 * 1024)) {
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) != -1) count += n;
}
// Simplest when you just move data
try (var in = Files.newInputStream(path)) { in.transferTo(out); }Writing is the same: an unbuffered OutputStream.write(int) is a syscall per byte. Other languages: Go uses bufio.Reader; Node.js streams already read in chunks.
File descriptors, connection limits and fsync
- Every socket, file and pipe is a file descriptor. The soft
ulimit -nis often 1024 in a shell; systemd usesLimitNOFILE. HotSpot raises the soft limit to the hard limit at startup by default, so for a JVM the number to watch is usually the hard limit. Count withls /proc/<pid>/fd | wc -l. - An idle TCP connection costs a few to a few tens of KB; with classic Java, threads run out before connections do.
write()copies into the page cache, marks it dirty and returns; the kernel flushes about 30 seconds later. Power loss before then loses data that was "written successfully".FileChannel.force(true)forces it to disk; databases batch many transactions into one fsync (group commit).- Sequential reads beat random ones by hundreds of times on HDD and tens of times on NVMe at queue depth one: that's why Kafka, WALs and redo logs append.
- High
%wa(iowait) means the CPU is idle while I/O waits, not busy;%utilnear 100% on NVMe isn't necessarily saturation, look atawaitandaqu-sz.
4. Working with AI
Hand to AI: converting I/O code to buffers, BlockHound tests catching blocking calls on event loops.
Check in AI-written code:
- No byte-by-byte
read()orwrite(int)on unbuffered streams. - WebFlux handlers don't call JDBC,
Thread.sleeporblock(); blocking work goes toSchedulers.boundedElastic(). - Streams, sockets and files are closed with try-with-resources.
- With virtual threads on, the connection pool has an acquisition timeout.
- Data that must be durable calls
force(true)or relies on replication deliberately.
5. Exercises
Exercise 1: Review a WebFlux handler
The AI wrote the handler below, saying "it's reactive, so it scales". Find the bug, show how to prove it, fix it.
@GetMapping("/orders/{id}")
Mono<Order> get(@PathVariable long id) {
Order o = jdbcTemplate.queryForObject("SELECT * FROM orders WHERE id = ?", mapper, id);
return Mono.just(o);
}Solution to Exercise 1
JDBC is blocking: the query runs right on a Netty event loop. Each loop serves thousands of connections, so one 500 ms query stalls every connection on that loop. The signature: p99 spikes, CPU stays low.
Proof: BlockHound in tests throws as soon as a blocking call runs on a non-blocking thread; or load test with a fake 500 ms DB and compare p99 of another endpoint in the same service.
Fix: Mono.fromCallable(() -> jdbcTemplate.queryForObject(...)).subscribeOn(Schedulers.boundedElastic()); better, use R2DBC, or move the service to Spring MVC + virtual threads if it's mostly DB calls.
Exercise 2: Read a Too many open files incident
After 3 days a service logs java.io.IOException: Too many open files and every new request fails. ls /proc/<pid>/fd | wc -l shows 65,536, exactly the hard limit; most are sockets in CLOSE_WAIT to a partner API. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis:
CLOSE_WAITmeans the partner closed the connection but our side never calledclose(): responses aren't fully read or streams aren't closed, so sockets leak until fds run out. Raisingulimitonly delays the crash. - 15 minutes: rolling-restart instances to free fds; add an alert on fd count.
- Root fix: find the partner calls that don't close responses (missing try-with-resources, body not consumed); use one shared HTTP client with a connection pool and timeouts; track
process_files_open_filesin metrics.
Summary
- Most of a request's time is waiting; how you wait decides how many connections you can hold.
- epoll returns only ready fds; Netty, Tomcat NIO and virtual threads all build on it.
- Never block an event loop; JDBC in WebFlux stalls the whole loop.
- Always buffer reads and writes; unbuffered means a syscall per byte.
write()only reaches the page cache; durability needsfsyncor replication.
Read more: ExecutorService, thread pools and virtual threads.
Practice interview questions on this topic
- What is a file descriptor? How do you investigate "Too many open files" at 3 a.m.?
- Blocking, non-blocking, multiplexed and async I/O: what's the difference? Why does epoll scale better than select?
- Tomcat has 200 threads by default: what happens to request 201 and connection 9,000?
- What are virtual memory, page faults and the page cache? Should you worry when free shows little free RAM?
Comments
Community rules