KatInterview

In-Memory Versioned Store with Snapshot and Compaction

System DesignModel answer
MediumModel answerSystem Designversioningstoragesnapshots

Last updated

Build an in-memory key-value store that stages changes, creates atomic snapshots, supports historical queries, and limits retention to K versions.

Problem

You're building a document editor's backend storage layer. Users make changes to key-value pairs, create save points, and occasionally need to examine earlier states. Design an in-memory service that tracks these versions while preventing memory from growing without bound.

Core Operations

Your system must support:

  • Stage changes: set(key, value) and remove(key) operations that accumulate in a draft area
  • Create snapshots: save() that atomically freezes the current draft into an immutable version, returning a sequential version number
  • Query history: read(key, version=latest) that retrieves a key's value as it existed at a specific version
  • Limit retention: Keep only the most recent N versions (e.g., N=50); collapse older history into a base state

Behavior Details

  • Version numbers start at 1 and increment with each save()
  • Reading from the current draft (before the next save) returns staged values
  • If a key didn't exist or was removed at the requested version, return null
  • Queries for versions older than your retention window should signal that history is unavailable
  • Snapshot isolation: once created, a version never changes, even as new saves occur

Scale Context

  • Typical workload: 50,000 keys per workspace, 1KB average value size
  • Target retention: 50 historical versions
  • Expected load: 5,000 read/write operations per second
  • Memory budget: avoid full dataset copies per version

Your Design Should Address

  1. Storage structure: How you represent keys, values, versions, and deletions to enable fast lookups and memory sharing
  2. Operation mechanics: Detailed flow for staging, snapshotting, and querying specific versions
  3. Compaction strategy: How you collapse old versions when exceeding the N-version limit without disrupting active readers
  4. Trade-offs: Comparison of at least two approaches (e.g., per-key version chains vs. copy-on-write trees) with concrete pros and cons

Hints

Hint 1

Consider whether storing one full copy per version is feasible given the memory numbers, then explore incremental approaches

Hint 2

Think about how deletions differ from 'never existed'—you'll need a way to distinguish these in historical queries

Hint 3

Collapsing old versions means rewriting history; determine which snapshot becomes your new baseline and what data can safely be discarded