Building an Append-Only Log Store with Real-Time File Following
System DesignModel answerLast updated
Design a durable, scalable store that ingests huge volumes of appended log records, serves whole-file reads, and lets readers follow files that are still being written.
Problem
Design a storage service for a very large stream of log records. Producers keep appending records to named log files. The service must store them durably and let users read the files back. Some users read a file that is still being written and want to see new records soon after they arrive.
Reads are by file only: read from the start, or resume from where the reader stopped. There are no range queries and no searching inside records.
The write rate, record size, retention and freshness targets are not given. Ask about them or state your own assumptions and size the system from them.
Questions to answer
- Write volume and partitioning. How does the system absorb a huge write rate, and how is data spread across storage nodes? Cover the ingestion tier, the partition key, hot files, adding nodes, replication, and what an acknowledgement promises.
- Locating data. If a file's data lives on many nodes, how does a reader find it? Cover the metadata layer, its schema, its consistency with the data nodes, and how it scales and survives failures without sitting on the per-record write path.
- Write efficiency. How do you raise write throughput under heavy load? Cover batching, on-disk layout, compression, the durability and latency cost of buffering, and backpressure.
- Following a live file. How do readers see new data promptly, and how does the system track what is new for each reader? Compare polling with a long-lived push connection, and describe positions, reconnects, and exposing only durable data in order.
- Many readers and further scale. Do long-lived connections overload the servers? How do you scale storage, metadata and delivery independently, including tiering of old data?
State your assumptions about durability, freshness and retention, and justify each design choice with the access pattern above.
Hints
Hint 1
Since reads are always whole-file or resume-from-offset, think about which partition key keeps one file's data together and sequential, and what you do when a single file is extremely hot.
Hint 2
Keep metadata (file to segments to nodes) small and off the per-record path: update it per segment or per rollover, not per record. A reader's position can be a simple monotonically increasing offset.
Hint 3
For live readers, only advance a 'committed offset' once data is replicated, let readers ask for data after their offset, and consider a separate delivery tier so reader fan-out never competes with ingestion.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Peak around 1M records/s, average 500 B, so roughly 500 MB/s raw ingest. With 3x replication that is about 1.5 GB/s of disk writes, spread over many nodes. Compression at about 3-5x cuts this a lot.
- Acknowledged writes must not be lost after a single machine failure.
- Live readers should see records within 1-2 seconds.
- Retention is about 30 days hot and longer in cheap storage. Old files are read rarely.
Architecture overview
Four independently scaled layers:
- Ingestion tier (stateless): authenticates, validates, batches, and routes appends.
- Storage tier: data nodes holding append-only segment files with replication.
- Metadata service: maps file to ordered segments to replica locations.
- Delivery tier: serves readers, including live followers.
Part 1: Write traffic and partitioning
- Stateless ingestion servers sit behind a load balancer and scale horizontally. They look up where a file's active segment lives and forward the append.
- Partition key: file ID. Reads are by file with no range queries, so keeping a file's records together makes reads sequential and avoids scatter-gather. Use consistent hashing (with virtual nodes) so adding a node moves only a small fraction of data.
- Segments. A file is a sequence of segments (for example 256 MB each). Once a segment fills, it is sealed and the next one may be placed on a different node set. This bounds hot spots: one very hot file spreads over nodes over time, and for extreme cases a file can be sharded into sub-streams that are merged by sequence number on read.
- Replication. Each active segment has a leader and 2 followers. A write is acknowledged once a quorum (2 of 3) has persisted it. Say explicitly what the ack means: durable on a majority, not just in memory.
Part 2: Finding the data
- A metadata service stores:
file_id -> [segment_id, start_offset, end_offset, state(open/sealed), replica_nodes, checksum]. - Metadata changes only on segment creation, sealing, and re-replication, so it is far off the per-record path. Appends go straight to the leader of the open segment, whose location is cached by ingestion servers.
- Store metadata in a replicated, strongly consistent store (Raft-based or a consensus-backed database), sharded by file ID for scale. Cache it aggressively on clients and ingestion nodes with versioned entries; a stale cache is detected when a node rejects a request for a segment it no longer owns.
- Consistency with data nodes: the segment is registered in metadata before data is written to it, and sealed with its final length after. A background reconciler compares node inventories to metadata to catch orphans and under-replication.
Part 3: Efficient writes
- Producer batching: buffer by size (say 64 KB) or time (say 10-50 ms), whichever comes first. Fewer round trips, better compression.
- Server batching and group commit: the leader groups many appends into a single sequential write and a single fsync, then replicates the batch.
- Append-only layout: records written sequentially to segment files, with a sparse index of offsets. Sequential I/O gets near disk bandwidth.
- Compression per batch (LZ4 or Zstd) reduces network, disk and replication cost.
- Trade-off: larger batches and longer linger time raise throughput but add latency and widen the loss window if the producer crashes before sending. Offer a per-producer setting: low-latency (small linger) versus high-throughput. Acknowledge only after quorum persistence, so buffered-but-unacked data is the only thing at risk, and the producer retries it with idempotent sequence numbers to avoid duplicates.
- Backpressure: bounded queues at each hop; when storage lags, return throttling signals, and producers slow down or spill to a local disk buffer. Never grow memory unboundedly.
Part 4: Live readers
- Position: each record has a monotonically increasing offset within its file. A reader remembers the last offset it consumed. On reconnect it asks for "everything after offset N", so there is no gap or duplicate.
- Commit offset: the leader maintains a high-water mark, the highest offset replicated to a quorum. Readers only see data up to it, which prevents exposing records that could vanish after a leader failover and keeps ordering consistent.
- Polling vs. push:
- Polling is simple, stateless and easy to load-balance, but wastes requests when idle and adds latency of up to the poll interval.
- Long-poll or streaming (WebSocket, gRPC stream, SSE) gives sub-second delivery and fewer empty requests, but holds state per connection.
- A good answer: long-poll with an offset. The server holds the request until new committed data appears or a timeout (about 30 s) elapses, then the client immediately re-issues it with the new offset.
Part 5: Scale to many readers
- Cost of long-lived connections: memory per connection (tens of KB), file descriptors, heartbeats, and reconnect storms after a deploy or failure. A single tuned server can hold hundreds of thousands of idle connections, but fan-out of a hot file to thousands of readers multiplies egress.
- Decouple delivery from ingestion: ingestion nodes publish commit notifications (file, new high-water mark) to a lightweight pub/sub. Delivery servers subscribe per file that has active readers, fetch the new bytes once (often from a page cache or a small in-memory tail buffer), and fan them out to their connected readers. This protects the write path from reader load. The cost is an extra hop, typically tens of milliseconds, which is well inside the 1-2 s target.
- Reconnect storms: jittered exponential backoff, connection limits, and graceful draining.
- Independent scaling: ingestion scales with write QPS, storage with bytes and replication, metadata with file/segment count, and delivery with concurrent readers.
- Tiering: sealed segments older than a few days are moved to object storage with erasure coding, with metadata updated to point to the new location. Reads of old files are rarer and can tolerate higher latency. Optionally compact or re-compress cold data.
Common mistakes
- Putting metadata updates on every record write.
- Choosing a partition key (such as timestamp) that makes the newest data a single hot partition.
- Exposing unreplicated data to readers, which can later disappear.
- Acknowledging writes before durability without stating the risk.
- Ignoring reconnect storms and duplicate delivery on retries.
- Not sizing anything: state numbers to justify node and connection counts.