KatInterview

Building a Partitioned, Replicated Append-Only Log Store

System DesignModel answer
HardModel answerSystem Designdistributed-logsreplicationpartitioning

Last 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

  1. Capacity estimates, with the assumptions you chose.
  2. A minimal client-facing API and how a record is routed to a partition.
  3. How a partition is laid out on disk: segments, rolling, and deletion for retention.
  4. Indexing: how you find the record at offset N or the first record after time T quickly.
  5. Compaction for "latest value per key" streams, including deletions.
  6. Replication: leader and follower roles, which replicas count toward durability, and when a write counts as committed.
  7. Failure handling and recovery: broker crash, leader loss, a lagging replica, and a partial write at the end of a log file.
  8. 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.