KatInterview

Build a Time-Travel Key-Value Store with Snapshots

Data Structure DesignModel answer
MediumModel answerData Structure Designsnapshotsversioningbinary-search

Last updated

Design a key-value store that supports cheap snapshots and historical reads without copying the entire map on each snapshot.

Build a Time-Travel Key-Value Store with Snapshots

You need to design and implement a key-value store where you can freeze the current state at any point and later read values as they existed at that frozen point, even after subsequent writes.

API to implement

  • set(key, value) — write a string value to a string key.
  • get(key) — return the current value for a key, or None if the key does not exist.
  • snapshot() — capture the current state and return an opaque snapshot_id string.
  • get_snapshot(snapshot_id, key) — return the value of a key as it existed when that snapshot was taken.

Requirements

  • Support an unlimited number of snapshots. Writes made after a snapshot must never affect what that snapshot returns.
  • Do not copy the entire map on each snapshot() call. The solution should be space-efficient across many snapshots — store only what actually changed.
  • Target roughly O(log u) per get_snapshot call, where u is the number of distinct versions stored for a key. Justify your complexity.
  • Clearly define the behavior for: overwriting a key, deleting a key, reading a key that never existed, reading a key that was written after a snapshot was taken, and calling snapshot() twice in a row with no writes in between.
  • Describe how you would handle concurrent reads during writes, and optionally how you would add persistence.

Example

set("x", "foo")
set("y", "bar")
id = snapshot()
set("x", "foo2")

get("x")              # "foo2"
get_snapshot(id, "x") # "foo"
get("y")              # "bar"
get_snapshot(id, "y") # "bar"

What is expected: a working implementation with explanation of the data structure chosen, its complexity, defined edge-case behavior, and a discussion of trade-offs versus at least one alternative approach.

Hints

Hint 1

Instead of copying the whole map, think about tracking version history on a per-key basis. What's the minimum information you need to store per key to reconstruct its value at any past point?

Hint 2

A global counter that increments only on snapshot() calls lets you stamp every write with a timeline marker. How does that stamp help you answer historical queries efficiently?

Hint 3

Once each key has a sorted list of (timestamp, value) pairs, retrieving the value at a past snapshot becomes a search problem. What standard algorithm finds the right version in O(log u) time?