How Kafka Stores Data: The File System
Kafka doesn’t use a database. It uses the file system. This is both its strength and its complexity.
Topic: user-events
├── Partition 0/
│ ├── 00000000000000000000.log # Segment file
│ ├── 00000000000000000000.index # Offset index
│ ├── 00000000000000000000.timeindex # Time index
│ ├── 00000000000000000001.log
│ └── 00000000000000000001.index
├── Partition 1/
│ └── ...
└── Partition 2/
└── ...
Each partition is a directory and each segment is a file. Because the layout is that plain, retention is just deleting old files.
Segment files
Kafka doesn’t write to one giant file. It writes to segments:
Segment 1: [msg-0] [msg-1] [msg-2] [msg-3] [msg-4] [msg-5]
Segment 2: [msg-6] [msg-7] [msg-8] [msg-9] [msg-10] [msg-11]
Segment 3: [msg-12] [msg-13] [msg-14] [msg-15] [msg-16] [msg-17]
Why segments?
- Parallelism: Multiple segments can be read/written simultaneously
- Retention: Delete old segments without affecting new ones
- Compaction: Compact segments independently
- Recovery: Faster recovery from crashes
Index files: how Kafka finds an offset fast
Kafka maintains two types of indexes for fast lookups:
1. Offset Index (.index)
# Maps offset → file position
Offset 0 → Position 0
Offset 100 → Position 1024
Offset 200 → Position 2048
Offset 300 → Position 3072
Use case: “Give me message at offset 150” → Jump to position 1024, scan forward
2. Time Index (.timeindex)
# Maps timestamp → offset
Timestamp 1609459200000 → Offset 0
Timestamp 1609459260000 → Offset 100
Timestamp 1609459320000 → Offset 200
Use case: “Give me messages from 2 hours ago” → Find offset, then use offset index
Page cache: why Kafka is fast without its own cache
This is why Kafka is so fast. It doesn’t read from disk - it reads from memory:
How Page Cache Works
-
Producer writes message to segment file
-
OS puts file in page cache (RAM)
-
Consumer reads from page cache (not disk!)
-
OS flushes to disk in background
Key insight: Kafka is essentially a RAM-based system with disk persistence.
Page Cache Gotchas
-
Other processes can evict your cache - don’t run other I/O heavy apps
-
OS decides what to cache - you can’t control it directly
-
Cold starts are slow - first read hits disk
Log Retention: Time vs Size
You can keep logs based on time, size, or both:
Time-based Retention
log.retention.hours = 168 # 7 days
log.retention.minutes = 60 # 1 hour
log.retention.ms = 3600000 # 1 hour (most precise)
Size-based Retention
log.retention.bytes = 1073741824 # 1 GB per partition
log.segment.bytes = 1073741824 # 1 GB per segment
Combined (Recommended)
log.retention.hours = 168 # 7 days
log.retention.bytes = 1073741824 # 1 GB
# Delete when EITHER condition is met
Log compaction: keep the latest value per key
Sometimes you don’t want to keep all messages - just the latest state:
# Before compaction
[user-123: {name: "John", age: 25}]
[user-123: {name: "John", age: 26}] # Update
[user-123: {name: "John", age: 27}] # Update
[user-456: {name: "Jane", age: 30}]
# After compaction
[user-123: {name: "John", age: 27}] # Only latest
[user-456: {name: "Jane", age: 30}]
Use cases:
- User profiles
- Configuration settings
- Account balances
- Any key-value state
Enable Log Compaction
# Per topic
kafka-topics.sh --create --topic user-profiles \
--config cleanup.policy=compact
# Global default
log.cleanup.policy = compact
Disk I/O Optimization
Kafka is I/O bound. Optimize your disks:
1. Use SSDs
Why: 10-100x faster than HDDs for random I/O
Cost: More expensive, but worth it for production
2. Separate Log and OS Disks
# Mount points
/var/log/kafka # OS logs
/data/kafka-logs # Kafka data
/tmp/kafka # Temporary files
3. RAID Configuration
RAID 0 (Striping)
-
Pros: Fastest write performance
-
Cons: No fault tolerance
-
Use: When you have replication
RAID 1 (Mirroring)
-
Pros: Fault tolerant
-
Cons: 50% storage efficiency
-
Use: When you need local redundancy
4. OS-level Tuning
# Increase file descriptor limits
ulimit -n 65536
# Optimize for sequential I/O
echo 'vm.swappiness = 1' >> /etc/sysctl.conf
echo 'vm.dirty_ratio = 15' >> /etc/sysctl.conf
echo 'vm.dirty_background_ratio = 5' >> /etc/sysctl.conf
# Disable swap for Kafka
swapoff -a
Partition Count Planning
More partitions = more parallelism, but also more overhead:
Partition Limits
-
Per broker: ~4000 partitions max
-
Per cluster: ~200,000 partitions max
-
Per topic: No hard limit, but performance degrades
Partition Planning Formula
target_throughput = 100,000 msg/sec
consumer_throughput = 1,000 msg/sec per consumer
num_partitions = target_throughput / consumer_throughput = 100
# Add 20% buffer for growth
final_partitions = 100 * 1.2 = 120
Storage Monitoring
Watch these metrics to avoid storage issues:
Disk Metrics
-
Disk usage % - Alert at 80%
-
Disk I/O wait - Alert at 20%
-
Disk queue length - Alert at 10
Kafka Metrics
-
Log size per partition - Track growth
-
Segment count - Too many = performance hit
-
Compaction lag - How behind compaction is
Production Configuration
Recommended Settings
# Retention
log.retention.hours = 168
log.retention.bytes = 1073741824
log.segment.bytes = 1073741824
log.segment.ms = 604800000
# Compaction
log.cleanup.policy = delete
log.cleanup.interval.ms = 300000
# Performance
num.io.threads = 8
num.network.threads = 3
socket.send.buffer.bytes = 102400
socket.receive.buffer.bytes = 102400
Hands-on exercise: look inside the log, then compact it
Goal: see segments and index files on disk, and watch log compaction keep only the latest value per key. (Paths below are for the plain-Java setup from Lesson 1; with Docker, run the same commands inside the container.)
- Small segments, so you get several of them:
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic small-segments \
--partitions 1 --replication-factor 1 --config segment.bytes=1048576
bin/kafka-producer-perf-test.sh --topic small-segments --num-records 50000 --record-size 100 \
--throughput -1 --producer-props bootstrap.servers=localhost:9092
ls /tmp/kraft-combined-logs/small-segments-0/
bin/kafka-dump-log.sh --files /tmp/kraft-combined-logs/small-segments-0/00000000000000000000.index | head
- A compacted topic that cleans aggressively (fine for a demo, not for production):
bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic user-profiles \
--partitions 1 --replication-factor 1 --config cleanup.policy=compact \
--config segment.ms=10000 --config min.cleanable.dirty.ratio=0.01
Produce alice:v1, bob:v1, alice:v2, bob:v2, alice:v3, bob:v3, carol:v1 (with --property parse.key=true --property key.separator=:). Wait 15 seconds, produce one more record (dave:v1) so the segment rolls, wait about 30 seconds, then read the topic from the beginning with --property print.key=true --property print.offset=true.
Questions: What are the file names based on? Why does the .index file have far fewer entries than there are messages? After compaction, which offsets are missing, and why do the remaining ones keep their original offsets?
What you should see
- Files come in sets named after the base offset of each segment, e.g.
00000000000000000000.log,00000000000000009463.log, with a matching.indexand.timeindex(and a.snapshotof producer state). Withsegment.bytes=1048576, 50,000 × 100-byte records make about 6 segments. - The offset index is sparse: Kafka adds an entry roughly every
index.interval.bytes(4 KB) of log, e.g.offset: 270 position: 13527. To find an offset it binary-searches the index, then scans forward a few KB in the.logfile. - After compaction the topic reads:
Offset:4 alice v3
Offset:5 bob v3
Offset:6 carol v1
Offset:7 dave v1Offsets 0–3 (the old alice and bob values) are gone. Offsets never change, so consumers’ committed positions stay valid; compaction just leaves gaps. The newest segment (the active one) is never compacted, which is why you had to roll it first.
Key Takeaways
- Kafka uses the file system, not a database - understand segments and indexes
- Page cache is your friend - keep data in RAM for speed
- Plan partition count carefully - more isn’t always better
- Use SSDs for production - the performance gain is massive
- Monitor disk usage and I/O - storage issues kill performance
Quiz
- Why is each partition split into segment files?
- How does Kafka find offset 150 quickly inside a segment?
- When would you use
cleanup.policy=compactinstead of time-based deletion?
Show answers
- So old data can be deleted or compacted a segment at a time, and recovery only needs to check recent segments.
- The sparse offset index (
.index) maps offsets to file positions; Kafka jumps to the nearest indexed position and scans forward. - When only the latest value per key matters, for example a table of current user profiles or settings; compaction keeps the newest record for each key.