Build a Time-Travel Key-Value Store with Snapshots
Data Structure DesignModel answerLast 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, orNoneif the key does not exist.snapshot()— capture the current state and return an opaquesnapshot_idstring.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_snapshotcall, whereuis 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: per-key version logs with a global epoch
The central insight is that you never need to copy the whole map. Instead, keep a global epoch counter and stamp every write with the current epoch. Each key maintains its own compact log of (epoch, value) pairs. A snapshot simply records the current epoch and bumps the counter — it copies nothing.
Data structure
_epoch: int # incremented on each snapshot()
_epochs: dict[str, list[int]] # key -> sorted list of write epochs
_values: dict[str, list[any]] # key -> values aligned 1-to-1 with _epochs
Because snapshot() is the only thing that increments the epoch, every write within the same snapshot interval gets the same epoch stamp. That means at most one log entry per key per snapshot interval is ever visible to callers — a useful property exploited below.
Key operations
set(key, value) — append (epoch, value) to the key's log. One refinement: if the last entry already carries the current epoch, no snapshot has been taken since that write, so no external caller can observe the intermediate value. Overwrite it in place. This collapses unbounded writes within one epoch into a single log entry.
snapshot() — record snap_id = f"snap-{epoch}", increment epoch, return the id. O(1), no allocation proportional to store size.
get(key) — return the last value in the key's log, or None if the log is empty or ends with a tombstone.
get_snapshot(snapshot_id, key) — parse the epoch e from the id, then binary-search the key's epoch list for the rightmost epoch ≤ e. If found, return the corresponding value (or None for a tombstone). If no entry has epoch ≤ e, the key didn't exist at snapshot time — return None.
Defined edge-case behavior
- Overwrite: last write wins. Intermediate writes within one epoch are collapsed and are never observable.
- Delete: implemented as a tombstone sentinel written to the log. Reads after the delete return
None; reads via earlier snapshots still see the old value. - Unknown key / key written after the snapshot:
get_snapshotfinds no entry with epoch ≤eand returnsNone. - Consecutive snapshots with no writes: each call returns a distinct id (different epoch numbers), but both resolve to identical views. No data is duplicated — distinct ids simply prevent callers from having to reason about aliasing.
- Invalid snapshot id: raise
KeyErrorimmediately. Silently returningNonewould hide bugs like passing a stale or mistyped id.
Complexity
| Operation | Time | Space |
|---|---|---|
set / delete | O(1) amortized | O(1) per retained version |
get | O(1) | — |
snapshot | O(1) | O(1) |
get_snapshot | O(log u) | — |
| Total space | — | O(W + keys), W = total retained versions |
Trade-offs vs. alternatives
Full copy per snapshot. get_snapshot becomes O(1) since you look up a dict directly, but snapshot() costs O(n) time and space. Completely impractical for large maps with frequent snapshots.
Per-snapshot delta chain. Each snapshot stores only keys changed since the last one. Space is good, but get_snapshot must walk backwards through snapshots until it finds the key — O(number of snapshots) in the worst case.
Persistent/functional tree (e.g., HAMT with path copying). snapshot() is O(1) by retaining a root pointer. Every operation is O(log n) in the number of keys. This approach is preferable when you need snapshot-wide iteration, range scans, or straightforward garbage collection of old snapshots. The per-key log approach wins for pure point lookups when the number of versions per key (u) is small relative to the total key count (n).
Python implementation
from bisect import bisect_right
from typing import Dict, List, Optional
_TOMBSTONE = object() # sentinel for deletions
class SnapshotKV:
_PREFIX = "snap-"
def __init__(self) -> None:
self._epoch: int = 0
self._epochs: Dict[str, List[int]] = {}
self._values: Dict[str, List[object]] = {}
def _write(self, key: str, value: object) -> None:
epochs = self._epochs.setdefault(key, [])
values = self._values.setdefault(key, [])
if epochs and epochs[-1] == self._epoch:
values[-1] = value # collapse same-epoch writes
else:
epochs.append(self._epoch)
values.append(value)
def set(self, key: str, value: str) -> None:
self._write(key, value)
def delete(self, key: str) -> None:
if key in self._epochs:
self._write(key, _TOMBSTONE)
def get(self, key: str) -> Optional[str]:
values = self._values.get(key)
if not values or values[-1] is _TOMBSTONE:
return None
return values[-1] # type: ignore[return-value]
def snapshot(self) -> str:
snap_id = f"{self._PREFIX}{self._epoch}"
self._epoch += 1
return snap_id
def _parse(self, snapshot_id: str) -> int:
if not isinstance(snapshot_id, str) or not snapshot_id.startswith(self._PREFIX):
raise KeyError(f"invalid snapshot id: {snapshot_id!r}")
try:
e = int(snapshot_id[len(self._PREFIX):])
except ValueError:
raise KeyError(f"invalid snapshot id: {snapshot_id!r}") from None
if e >= self._epoch:
raise KeyError(f"unknown snapshot id: {snapshot_id!r}")
return e
def get_snapshot(self, snapshot_id: str, key: str) -> Optional[str]:
e = self._parse(snapshot_id)
epochs = self._epochs.get(key)
if not epochs:
return None
i = bisect_right(epochs, e) - 1 # last write with epoch <= e
if i < 0:
return None
v = self._values[key][i]
return None if v is _TOMBSTONE else v # type: ignore[return-value]
Correctness invariant
Once snapshot() issues epoch e, every subsequent write is stamped with an epoch > e. The only entries ever mutated in place are those carrying the current (un-snapshotted) epoch. Therefore the set of log entries with epoch ≤ e is permanently frozen, and the last such entry is exactly the value that was current when the snapshot was taken. Each key's epoch list is sorted by construction (epochs are non-decreasing), which makes bisect_right valid.
Concurrency extension
Wrap writes and snapshot() in a write lock; reads (get, get_snapshot) only need a read lock since they never mutate data. Because get_snapshot only inspects entries with epoch ≤ e — a frozen prefix of each log — readers and writers can safely interleave with a standard reader-writer lock.
Common mistakes
- Forgetting to collapse same-epoch writes, leading to O(total writes) space rather than O(total versions).
- Using
Noneas the delete sentinel, making it impossible to distinguish "key deleted" from "key never existed." - Returning
Nonefor an unrecognized snapshot id instead of raising an error. - Binary-searching on values instead of the parallel epoch list, which is incorrect if values happen to be numeric.