Building a Partitioned, Replicated Append-Only Log Store
System DesignModel answerLast updated
Design the storage tier of a distributed commit log: partitions, segments, indexes, compaction, leader/follower replication, retention, and crash recovery.
Problem
You are asked to design the storage layer of a distributed, durable event log. Producers write records to named streams. Each stream is divided into partitions, and consumers read from those partitions in order, starting from any position they choose.
Requirements
Functional
- Writes are append-only. Records are never modified in place.
- Order is guaranteed inside one partition, not across partitions.
- Consumers can read sequentially from an arbitrary offset, and can rewind and replay.
- Retention is configurable per stream: by age, by total size, or by "keep only the latest record per key".
Non-functional
- Very high write throughput and very high sequential read throughput.
- An acknowledged write must survive the failure of up to f replicas.
- Automatic failover within seconds when a node dies.
- Horizontal scalability by adding nodes and partitions.
What to cover
- Capacity estimates, with the assumptions you chose.
- A minimal client-facing API and how a record is routed to a partition.
- How a partition is laid out on disk: segments, rolling, and deletion for retention.
- Indexing: how you find the record at offset N or the first record after time T quickly.
- Compaction for "latest value per key" streams, including deletions.
- Replication: leader and follower roles, which replicas count toward durability, and when a write counts as committed.
- Failure handling and recovery: broker crash, leader loss, a lagging replica, and a partial write at the end of a log file.
- Trade-offs you would call out, and what you would add for scale (for example, offloading cold data).
Spend most of your time on items 3 to 7 rather than on client libraries.
Hints
Hint 1
Explain why an append-only, sequential layout is fast on both disks and the OS page cache, and split each partition into immutable segments plus one active segment so retention becomes whole-file deletion.
Hint 2
Use sparse indexes (offset to file position, and timestamp to offset) that are small enough to memory-map and can be rebuilt from the log. Lookup is a binary search over segments, a binary search over the index, then a short scan.
Hint 3
For replication, define an in-sync replica set and a commit point equal to the minimum log end offset across it. Tie each leadership term to an epoch so that a recovering replica truncates any data that diverges from the new leader.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and estimates
State assumptions out loud. Example: 1M records/s at 1 KB each is about 1 GB/s of ingress. With replication factor 3 the cluster writes about 3 GB/s. With three consumer groups, egress is about 3 GB/s, mostly tail reads from page cache.
Seven-day retention is roughly 1 GB/s x 604,800 s, about 605 TB raw and about 1.8 PB replicated. At about 40 TB usable and 300 MB/s sustained writes per broker, that suggests roughly 45 to 60 brokers with headroom. At about 10 MB/s per partition, you need at least 100 partitions, and you would provision 1,000 or more to leave room for consumer parallelism and growth.
2. API and routing
append(stream, key, value, acks) -> (partition, offset)
read(stream, partition, offset, max_bytes) -> records, next_offset, high_watermark
create_stream(name, partitions, rf, retention)
- If the producer gives no partition, use
hash(key) mod N. Without a key, use sticky round-robin per batch. ackscan be 0 (fire and forget), 1 (leader only), or all (all in-sync replicas). Durable setups useallwith a minimum in-sync count of 2.- Records are grouped into compressed batches. A batch is the unit of write, replication and storage, which amortizes syscalls and network round trips.
3. Architecture
- A small controller quorum (3 to 5 nodes, Raft) owns metadata: stream configs, replica assignments, current leader, leader epoch and in-sync set. It detects broker failure through heartbeats or leases and elects leaders.
- Brokers store partition replicas. Each partition has one leader and RF-1 followers, spread over racks or zones.
- Clients cache metadata and talk to the leader.
- Optional tiering: older immutable segments move to object storage, so retention is decoupled from local disk size.
4. Segments and retention
A partition is a directory of segment files named by their base offset. Only the newest, the active segment, takes appends. It rolls on size (say 1 GB) or age (say 1 hour). Older segments are immutable.
Why segments:
- Retention deletes whole files, with no in-place deletes or fragmentation.
- Immutable files are simple to checksum, cache, tier and copy to new replicas.
Write path: append to the page cache and flush periodically. Do not fsync every write, since throughput collapses. Durability comes from replication, not from a local fsync per record.
Read path: tail reads are served from page cache. Because the on-disk batch format equals the wire format, the broker can use zero-copy sendfile and skip decompression.
Retention thread: delete the oldest segments when their newest timestamp exceeds the age limit or when the partition exceeds its size limit. Never delete the active segment.
5. Indexing
Each segment has two sparse, memory-mapped indexes:
- Offset index: relative offset to byte position, one entry about every 4 KB of log.
- Time index: timestamp to offset, for "seek to time T" and age-based retention.
Lookup for offset N: binary search the segment list by base offset, binary search that segment's offset index for the greatest entry at or below N, then scan forward a few KB. Cost is O(log n) plus a small sequential read.
Sparse indexes are around 0.1% of log size, so they fit in memory. They are derived data and can always be rebuilt from the log, which simplifies recovery.
6. Compaction
For "latest value per key" streams:
- Split the log into a clean region (already compacted) and a dirty region (written since).
- A cleaner thread scans the dirty region and builds a map of key to latest offset.
- It rewrites old segments, keeping only records that are the latest for their key.
- It writes new segment files and swaps them in atomically.
Correctness rules:
- Preserve offsets. Gaps are fine, and consumer positions stay valid.
- Tombstones (null value) delete a key. Keep them for a grace period so lagging consumers observe the delete, then drop them.
- Never compact the active segment.
- Throttle cleaner I/O so it does not starve foreground traffic.
7. Replication
Leader accepts writes, assigns offsets and serves reads. Followers pull from the leader using the same fetch path as consumers and append to their local logs. Pull-based replication batches naturally and lets slow followers catch up without pushing load onto the leader.
In-sync replicas (ISR): replicas within a lag threshold (for example, caught up within 10 s). Laggards are removed and rejoin when they catch up.
High watermark (HW): the minimum log end offset across the ISR. Only records at or below the HW are committed and visible to consumers. With acks=all, the leader acknowledges once the HW passes the record.
Minimum ISR: if the ISR shrinks below the configured minimum (say 2), the leader rejects writes instead of accepting them unsafely. This trades availability for durability, and it should be stated as a deliberate choice.
Leader epochs: each leadership term has an increasing epoch, stored with the data. This is what makes recovery safe.
8. Failure handling and recovery
- Follower crash or lag: it is dropped from the ISR. On return it truncates to its last known-good point, fetches from the leader, and rejoins once caught up.
- Leader crash: the controller picks a new leader from the ISR only, bumps the epoch and publishes metadata. Because every ISR member has all committed records, no committed data is lost. Clients refresh metadata and retry.
- Divergent tail: a returning old leader may hold uncommitted records the new leader never saw. It asks the new leader for the end offset of its last known epoch and truncates to it. Truncating by epoch, not by HW alone, avoids silent divergence.
- Broker crash with a torn write: on restart, scan the active segment's tail, validate batch CRCs, truncate at the first invalid batch, and rebuild the indexes if they are missing or stale. Older segments are trusted because they are immutable and checksummed.
- Unclean election: allowing an out-of-sync replica to become leader gives availability but can lose committed data. Make it off by default and explicit per stream.
- Whole-zone loss: rack-aware placement ensures replicas live in different failure domains.
9. Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Replication instead of fsync per write | High throughput | Correlated power loss can drop un-flushed data |
| Larger batches | Throughput, compression | Added latency |
| More partitions | Parallelism | More files, more metadata, slower failover |
| Min ISR of 2 | Safer writes | Reduced availability when replicas fail |
| Tiered storage | Cheap long retention | Slower cold reads, extra complexity |
10. Common mistakes
- Spending time on client APIs instead of segments, indexes and replication.
- Proposing per-record fsync, or random-access updates to the log.
- Defining commit as "the leader wrote it" rather than the ISR high watermark.
- Forgetting leader epochs and log truncation, so replicas diverge after failover.
- Reassigning offsets during compaction, which breaks consumer positions.
- Deleting or compacting the active segment.
- Skipping capacity numbers or not stating the durability versus availability trade-off.