Zero-Copy I/O
The Problem in One Sentence
Kafka's broker doesn't need to look at the messages it sends to consumers — the bytes on disk are already in the exact format the consumer expects. So any step that copies those bytes into the broker's memory is pure overhead.
Two terms you'll need:
- Page cache — RAM that the operating system uses to keep recently read or written file data. Recent Kafka messages almost always live here.
- DMA (Direct Memory Access) — hardware (the disk or the network card) moving data by itself, without the CPU copying it byte by byte. DMA copies are cheap; CPU copies are not.
The Normal Way: Four Copies
A regular program serves a file with two calls: read() the file into its own buffer, then write() that buffer to the network socket. The bytes take this trip:
- Disk → page cache (DMA, cheap). Skipped if the data is already cached.
- Page cache → the program's buffer (CPU copy, during
read()). - The program's buffer → socket buffer (CPU copy, during
write()). - Socket buffer → network card (DMA, cheap).
Copies 2 and 3 are the waste: the CPU moves every byte up into user space and straight back down, and nothing is done with it in between.
Why it hurts: every byte crosses memory twice for nothing. If consumers fetch 500 MB/s, copies 2 and 3 burn about 1 GB/s of memory bandwidth plus the CPU time to do it — and a busy broker serves several consumer groups at once.
The Kafka Way: sendfile()
With sendfile(), the broker makes one call that says: "send this part of this file to this socket." The kernel does it all internally:
- Disk → page cache (DMA) — only if the data isn't already in RAM.
- Page cache → network card (DMA). The kernel just tells the card where the bytes sit in memory, and the card reads them directly.
The program's buffer and the socket buffer are never filled with data. The CPU copies nothing.
Net result: for a consumer reading recent messages (already in page cache), serving a fetch is a single hardware transfer from RAM to the network card. That's why one broker can feed many consumer groups without its CPU climbing.
Normal read() + write() | Kafka sendfile() | |
|---|---|---|
| System calls | 2 (read, then write) | 1 |
| CPU copies | 2 | 0 |
| DMA copies | 2 | 1 (2 if the data must come from disk) |
| Data enters the JVM? | Yes | No |
When Zero-Copy Stops Working
Zero-copy only works if the broker can send the bytes exactly as they are on disk. Anything that needs to change the bytes on the way out forces them back through the broker's memory:
| Situation | Why zero-copy is lost |
|---|---|
| TLS / SSL encryption | Bytes must be encrypted before they leave, and that happens in the JVM. The data has to come up into user space — back to the copying path. |
| Old consumer clients (pre-0.11) | They can't read the newer message format, so the broker converts ("down-converts") the batch in memory before sending it. |