Build an In-Memory Key-Value Store with Savepoints
Data Structure DesignModel answerLast updated
Design a transactional key-value store supporting nested transactions, named savepoints, and full rollback using an undo-log approach.
In-Memory Key-Value Store with Transactions and Savepoints
You are building an in-memory key-value store that supports multi-level transactions. Each transaction can contain named checkpoints (savepoints) and can be rolled back either fully or to any named checkpoint.
Implement a class KVStore with the following interface:
get(key: str) -> Optional[str]— Returns the current value forkey, orNoneif absent.set(key: str, value: str) -> None— Writeskey = valuein the current context.delete(key: str) -> None— Removeskeyif it exists; does nothing otherwise.begin() -> None— Opens a new transaction. Transactions may be nested.checkpoint(name: str) -> None— Records the current state undernamewithin the active transaction. Reusing a name overwrites the previous checkpoint with that name.revert_to(name: str) -> bool— Restores the store to the state it was in whennamewas recorded. ReturnsTrueif the checkpoint was found,Falseotherwise. The checkpoint itself remains active after the revert.revert() -> bool— Undoes all changes made in the innermost open transaction and closes it. ReturnsTrueon success, orFalseif no transaction is open.commit() -> bool— Finalises all open transactions, permanently applying every pending change. ReturnsTrueon success, orFalseif no transaction is open.
Constraints
get,set, anddeletemust run in O(1) average time regardless of transaction depth.- Writes outside any transaction take effect immediately and permanently.
- Be prepared to explain the space/time trade-offs between an undo-log design and a layered-map design.
Example
kv = KVStore()
kv.set("x", "1")
kv.begin()
kv.set("x", "2")
kv.checkpoint("cp1")
kv.set("y", "3")
kv.delete("x")
assert kv.get("x") is None
assert kv.get("y") == "3"
# Restore to cp1
assert kv.revert_to("cp1") is True
assert kv.get("x") == "2" # restored
assert kv.get("y") is None # write after cp1 was undone
# Discard the whole transaction
assert kv.revert() is True
assert kv.get("x") == "1" # back to pre-transaction value
assert kv.get("y") is None
Edge Cases to Handle
- A key created inside a transaction and then deleted within the same transaction — after rollback it should be fully absent.
- Calling
commit,revert, orrevert_towhen no transaction is open. - A checkpoint name that appears in multiple nested transaction levels — the innermost match should win.
- Calling
revert_toon the same checkpoint more than once.
Hints
Hint 1
Keep a single live dictionary as the source of truth. Before each write, record what the key looked like before the change — that's your undo record. Reversing writes then means replaying those records in reverse order.
Hint 2
Represent each open transaction as a (log_start_index, savepoints_dict) pair on a stack. A checkpoint is just the current log length stored under its name. Rolling back means popping undo records off the log until you reach the saved index.
Hint 3
Watch out for stale checkpoint positions: after a revert_to, any checkpoints that pointed past the new log length would be wrong. Prune them. Also decide what _MISSING sentinel to use so that 'key was absent' is distinguishable from any real string value.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central idea is to maintain one flat dictionary (data) that always reflects the current visible state, and a separate undo log — an append-only list of pre-images. Every write inside a transaction appends one record: the key and whatever value (or a sentinel meaning "absent") the key held before the write. Rolling back is just replaying those records in reverse.
Transactions and checkpoints are cheap bookmarks into that log, not copies of the data.
Data Structures
data: dict— the live key-value map.log: list— each entry is(key, previous_value_or_MISSING).blocks: list— each entry is(log_start: int, checkpoints: dict[str, int]). The innermost open transaction is at the end._MISSING— a private sentinel object. UsingNonewould be ambiguous becauseNoneis a valid Python object; a dedicated sentinel makes "key did not exist" unambiguous.
Writes that happen outside any transaction skip the log entirely — they're plain dict operations.
Operation Walkthrough
set / delete: Before mutating data, call a helper that appends (key, data.get(key, _MISSING)) to the log. Then apply the mutation. delete on a key that isn't present changes nothing, so it skips the log append.
begin: Push (len(log), {}) onto blocks.
checkpoint(name): Store name -> len(log) in the top block's checkpoint dict. Re-using the name just overwrites the position.
revert_to(name): Walk blocks from innermost to outermost looking for name. On a hit, call _undo_to(saved_position) — pop records off the log and reverse each mutation until the log is back to that length. Then close any blocks that were opened after the owning block (their whole log range was just wiped), and prune checkpoints in the owning block that pointed past the restored position. The target checkpoint itself survives, so repeated calls work correctly.
revert(): Pop the top block, run _undo_to(block.start).
commit(): data already holds the merged result. Just clear the log and blocks stack. O(1) amortized — clearing a list that was built up by N appends charges the cost back to those appends.
Why the Edge Cases Work
Key created then deleted in the same transaction: set logs (k, _MISSING), delete logs (k, "v"). Undoing in reverse restores "v" then removes the key, leaving it absent — correct.
Stale checkpoints after revert_to: Any checkpoint position past the new log length would "undo nothing" on a future revert_to. The solution prunes them explicitly.
Unknown checkpoint name / no open transaction: Return False immediately without touching data or the log.
Complexity
| Operation | Time | Space |
|---|---|---|
get | O(1) avg | — |
set / delete | O(1) amortized | O(1) per write appended to log |
begin, checkpoint | O(1) | O(1) |
revert_to / revert | O(u + s) | — |
commit | O(1) amortized | — |
u = undo records replayed, s = checkpoints pruned. Each record is appended once and popped at most once, so rollback cost is bounded by the number of writes that caused it.
Overall space: O(n + w) — n live keys plus w pending writes. No data is duplicated per transaction level.
Trade-offs: Undo Log vs. Layered Maps
Layered maps give each transaction its own overlay dict and use tombstones for deletes. Writes are O(1) but get is O(depth) because it must walk all layers. Commit must merge them. Savepoints inside a block need extra layers or copies.
Full snapshot per checkpoint makes rollback an O(1) pointer swap but costs O(n) time and space per begin or checkpoint — expensive when the store is large.
Undo log keeps get at O(1) always. Rollback is proportional to the number of writes undone, which is usually the right trade because reads vastly outnumber rollbacks in practice.
Python Implementation
from typing import Optional, Dict, List, Tuple, Any
_MISSING = object() # sentinel: distinguishes "key was absent" from any string value
class KVStore:
def __init__(self) -> None:
self._data: Dict[str, str] = {}
# each log entry: (key, value_before_write | _MISSING)
self._log: List[Tuple[str, Any]] = []
# each block: (log index at begin, {checkpoint_name: log_index})
self._blocks: List[Tuple[int, Dict[str, int]]] = []
# ── internal helpers ──────────────────────────────────────────────
def _record(self, key: str) -> None:
"""Append a pre-image record only when inside a transaction."""
if self._blocks:
self._log.append((key, self._data.get(key, _MISSING)))
def _undo_to(self, index: int) -> None:
"""Replay the log backwards until it has exactly `index` entries."""
log, data = self._log, self._data
while len(log) > index:
key, prev = log.pop()
if prev is _MISSING:
data.pop(key, None)
else:
data[key] = prev
# ── data operations ───────────────────────────────────────────────
def get(self, key: str) -> Optional[str]:
return self._data.get(key)
def set(self, key: str, value: str) -> None:
self._record(key)
self._data[key] = value
def delete(self, key: str) -> None:
if key not in self._data:
return # nothing to undo; skip the log append
self._record(key)
del self._data[key]
# ── transaction control ───────────────────────────────────────────
def begin(self) -> None:
self._blocks.append((len(self._log), {}))
def checkpoint(self, name: str) -> None:
if not self._blocks:
return # no active transaction; treat as no-op
self._blocks[-1][1][name] = len(self._log)
def revert_to(self, name: str) -> bool:
for i in range(len(self._blocks) - 1, -1, -1):
start, checkpoints = self._blocks[i]
if name not in checkpoints:
continue
target = checkpoints[name]
self._undo_to(target)
# close any transaction blocks opened after this one
del self._blocks[i + 1:]
# prune checkpoints in this block that now point past the log end
stale = [n for n, pos in checkpoints.items() if pos > target]
for n in stale:
del checkpoints[n]
return True
return False
def revert(self) -> bool:
if not self._blocks:
return False
start, _ = self._blocks.pop()
self._undo_to(start)
return True
def commit(self) -> bool:
if not self._blocks:
return False
# data already reflects all pending changes; just discard the log
self._log.clear()
self._blocks.clear()
return True
Common Mistakes
- Using
Noneas the sentinel — collides withdict.getreturningNonefor missing keys. - Forgetting to prune stale checkpoints after
revert_to— leads to silent no-ops on a second call to that checkpoint. - Copying the whole dict on
begin— this is the snapshot approach; fine to mention, but it makes the complexity O(n) perbegin. - Not handling
deleteon a missing key — logging a no-op wastes space and pollutes the undo log with phantom undos.