Video in progress
Why do systems that write to disk sequentially (append), like Kafka, run much faster than ones that update data in place? How do you use this idea in your own service design?
Sequential IO is where both the disk and the OS work best: writing in large blocks, read-ahead, reads from the page cache, no seeks on HDD, low write amplification on SSD. In a design this means an append-only log, batched writes, a small index and compacting old data later.
📖 Answer
The numbers show the difference well. An HDD gives 100-200 MB per second for sequential reads and writes, but only 100-200 IOPS for random 4 KB operations, which is under 1 MB/s. On an SSD the gap is smaller but still there: small random writes multiply the internal "erase-write" cycle, while big sequential blocks make full use of the device's parallelism.
Kafka drew several conclusions from this:
- Write only at the end. A message is appended to the end of a segment file and never modified in place. The disk works almost entirely sequentially.
- The page cache is the cache. The broker doesn't cache data on the JVM heap, it leaves that to the OS. There is no GC pressure, the cache stays warm even after a restart, consumers read new data from RAM, and it is handed to the socket with
sendfile. - Batching. The producer collects messages (
linger.ms,batch.size) into one big write.fsyncis not done per message; replication gives the reliability. - A sparse index. One index entry per so many KB, not per message: the index is small and is mmapped.
- Deleting is cheap. Old data goes away by deleting a whole segment file, not individual records.
In my own services I apply these ideas like this: if I need an audit or event journal, I add a new record instead of updating a row in a table; I write to disk in batches (collecting a few ms or KB) rather than on every request; I split files into segments by size and delete old segments whole.
There is a price too: to get the current state you have to replay the log or keep a separate index, duplicate records take space, and compaction becomes a background job. If reads are random and frequent (for example a lookup by key), structures like a log + index or an LSM-tree are used: RocksDB is exactly this trade-off.
Sign up to mark studied questions and save your progress.