Time-Travel Key-Value Store with Point-in-Time Snapshots
Data Structure DesignModel answerLast updated
Design a hash-map-backed store that records every write with an increasing timestamp, answers reads as of any past moment, and exports a frozen plain-map snapshot.
Time-Travel Key-Value Store
Build a generic class TimeTravelMap<K, V> that remembers the full write history of every key. It must answer "what was the value at moment T?" and export a point-in-time copy of everything it holds.
Operations
-
long put(K key, V value)Recordvalueas the newest value forkey. Return the timestamp of this write. -
V get(K key)Return the most recent value stored forkey, ornullif the key has never been written. -
V get(K key, long timestamp)Return the value that was current forkeyattimestamp. Concretely, pick the write with the largest write-timestamptsatisfyingt <= timestamp. If no such write exists, returnnull. -
Map<K, V> freeze(long timestamp)Return an ordinary, non-versioned hash map. For every key that had at least one write at or beforetimestamp, the map holds that key's value as oftimestamp. Keys with no write by then are absent. Later calls toputmust never alter a map that was already returned.
Assumptions
- Timestamps returned by
putare strictly increasing across successive calls (for example, from an internal counter). - Deletion is out of scope.
- State any extra assumptions you make (complexity targets, thread safety) before coding.
Example
put("a", 10) -> 1
put("a", 20) -> 2
put("b", 7) -> 3
get("a", 1) == 10
get("a", 2) == 20
get("a", 100) == 20
freeze(2) == { "a": 20 }
freeze(3) == { "a": 20, "b": 7 }
What to deliver
Explain your design, implement it, state the time and space complexity of each operation, and discuss edge cases and trade-offs.
Hints
Hint 1
Where do timestamps come from? If a single global counter produces them, think about what that implies for the order of writes within any one key's history.
Hint 2
For each key, keep its history as two parallel lists (timestamps and values) that you only ever append to. Which standard search lets you find the last timestamp that is <= a query time?
Hint 3
For freeze, apply the same 'as of' lookup to every key and include a key only if at least one of its writes qualifies. Build a brand-new map so later writes cannot leak into it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
- Timestamp source. Use an internal counter rather than wall-clock time. Clocks can repeat within a millisecond or move backwards after a sync adjustment, which would break the strictly-increasing guarantee the design relies on.
- Workload. Are point reads far more common than snapshots? That affects where to spend effort.
- Concurrency. Assume single-threaded for the exercise, but explain how to make it safe.
- Value semantics. The snapshot holds references to stored values; it does not deep-copy them.
Core idea
Keep a per-key history of (timestamp, value) pairs, stored as two parallel append-only lists. Since every timestamp comes from one increasing counter, each key's timestamp list is automatically sorted. No re-sorting or tree is needed, and binary search is valid.
| Operation | How | Time |
|---|---|---|
put | bump counter, append to the key's lists | O(1) amortized |
get(key) | last element of the key's list | O(1) |
get(key, ts) | binary search for the rightmost timestamp <= ts | O(log n_k) |
freeze(ts) | same search for every key, skip keys with no qualifying write | O(Σ log n_k) ≤ O(K log N) |
Here N is total writes, K is distinct keys, n_k is the number of versions of key k. Space is O(N) because all versions are retained.
Why it is correct
- Sorted invariant. Each
putreceives a timestamp larger than every earlier one, so appending preserves strict ordering in each list. - "As of" semantics.
bisect_right(times, ts)returns the countiof writes with timestamp<= ts. Ifi == 0, nothing qualifies and the answer isnull. Otherwisetimes[i-1]is the greatest qualifying timestamp, matching the spec exactly. - Snapshot isolation.
freezebuilds a fresh map. Subsequent writes only append to internal lists, so the returned map is untouched. Callingfreeze(ts)again later yields identical contents, because new writes have timestamps> tsand fall to the right of the search point.
Walk-through on the example: key a has times [1,2] and values [10,20]. get("a",1) gives bisect_right([1,2],1) = 1, so value index 0, which is 10. For freeze(2), a yields 20, while b has times [3] and bisect_right([3],2) = 0, so b is excluded. Result: {a: 20}.
Code (Python)
from bisect import bisect_right
from threading import Lock
from typing import Any, Dict, Hashable, List, Optional
class TimeTravelMap:
def __init__(self) -> None:
self._times: Dict[Hashable, List[int]] = {}
self._values: Dict[Hashable, List[Any]] = {}
self._clock = 0
self._lock = Lock()
def put(self, key: Hashable, value: Any) -> int:
with self._lock:
self._clock += 1
ts = self._clock
self._times.setdefault(key, []).append(ts)
self._values.setdefault(key, []).append(value)
return ts
def get(self, key: Hashable, timestamp: Optional[int] = None) -> Optional[Any]:
times = self._times.get(key)
if not times:
return None
values = self._values[key]
if timestamp is None:
return values[-1]
i = bisect_right(times, timestamp)
return values[i - 1] if i > 0 else None
def freeze(self, timestamp: int) -> Dict[Hashable, Any]:
snapshot: Dict[Hashable, Any] = {}
with self._lock:
for key, times in self._times.items():
i = bisect_right(times, timestamp)
if i > 0:
snapshot[key] = self._values[key][i - 1]
return snapshot
Edge cases
- Never-written key:
getreturnsnull. - Query time before the key's first write:
null(the search index is 0). - Query time beyond the last write: the latest value.
freeze(0)or any time before the first write: an empty map.- Negative or very large timestamps need no special handling.
- Repeated writes to one key: only the newest version at or before
tsappears in a snapshot. - Null values are ambiguous. If a caller stores
null,getcannot distinguish it from "missing". Mention this and, if needed, return anOptionalwrapper or a sentinel.freezeis unaffected because it checks key presence through the index, not the value.
Trade-offs worth raising
- Global write log with replay. Store
(ts, key, value)in order and rebuild snapshots by replaying up tots. Cost is O(writes up to ts). It can beat per-key search whentsis early and K is huge, but it is worse for late timestamps and makesget(key, ts)a scan unless a per-key index also exists. - Periodic checkpoints. Every C writes, save a materialized snapshot.
freeze(ts)copies the nearest earlier checkpoint and replays at most C writes. This spends memory to make frequent freezes cheaper. - Persistent maps with structural sharing (such as a HAMT). Each
putcreates a new root in O(log N), sofreezeis effectively O(1) and returns an immutable shared view. This is the most scalable approach but too heavy to implement in a short session; mention it. - Copy versus live view. The spec demands a plain map, so copy. A lazy view saves memory but couples the caller to internal state.
- Memory growth. All versions are kept forever. A real system would add compaction or a retention window for old versions.
Concurrency
Make timestamp assignment and the append a single critical section, otherwise two threads could append out of order and break the sorted invariant. Use a readers-writer lock so that get and freeze can run in parallel while put has exclusive access. freeze should hold the read lock for its whole scan to get a consistent view.
Common mistakes
- Using wall-clock time as the timestamp, allowing duplicates or regressions.
- Using
bisect_leftinstead ofbisect_right, which misses a write exactly atts. - Including keys in
freezewhose first write is afterts. - Returning the internal structure from
freezeinstead of a fresh copy. - Re-sorting on every
put, turning an O(1) append into O(n log n).