Transactional Key-Value Store with Nested Savepoints

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement TransactionalKVStore, an in-memory string-to-string dictionary supporting arbitrarily nested transaction blocks, named savepoints, partial rewinds, and full commits or rollbacks.

Provide the following methods on TransactionalKVStore:

  • get(key: str) -> Optional[str]: Look up the latest visible string mapped to key, returning None when key is absent.
  • set(key: str, value: str) -> None: Bind key to value within the active context (or directly in the base store when no transaction is open).
  • delete(key: str) -> None: Remove key if present; if key is already absent, leave state unchanged.
  • begin() -> None: Push a new transaction block onto the active transaction stack.
  • savepoint(name: str) -> None: Record a named bookmark inside the innermost open transaction block. Reusing name within that same block replaces the earlier bookmark and moves name to the newest position; calling savepoint with no open transaction does nothing.
  • rollback_to(name: str) -> bool: Search open transaction blocks from innermost to outermost for savepoint name. When found, undo every mutation performed since name, close any inner transaction blocks opened after name, discard savepoints created after name in that block while keeping name itself active for future rewinds, and return True. Return False if no open block contains name.
  • rollback() -> bool: Revert every mutation made inside the innermost open transaction block, close that block, and return True (or False when no transaction is open).
  • commit() -> bool: Finalize all uncommitted changes across every open transaction block into the base store, close the entire transaction stack, and return True (or False when no transaction is open).

Examples

Example 1

store = TransactionalKVStore()
store.set("host", "db1")
store.begin()
store.set("host", "db2")
store.savepoint("before_migration")
store.set("port", "5432")
store.delete("host")

assert store.get("host") is None
assert store.get("port") == "5432"

assert store.rollback_to("before_migration") is True
assert store.get("host") == "db2"
assert store.get("port") is None

assert store.rollback() is True
assert store.get("host") == "db1"
assert store.get("port") is None

Walk-through: "host" starts at "db1" in the base map. Inside the transaction, "host" becomes "db2" right before "before_migration" is saved; "port" is then inserted and "host" is deleted. Rewinding to "before_migration" restores "host" to "db2" and removes "port", while keeping the transaction and savepoint open. Calling rollback() aborts the transaction block and restores "host" to "db1".

Example 2

store = TransactionalKVStore()
store.set("plan", "free")
store.begin()
store.set("plan", "pro")
store.begin()
store.set("plan", "enterprise")
store.set("seats", "25")

assert store.rollback() is True
assert store.get("plan") == "pro"
assert store.get("seats") is None

store.begin()
store.set("seats", "5")
assert store.commit() is True
assert store.get("plan") == "pro"
assert store.get("seats") == "5"
assert store.rollback() is False

Walk-through: The first rollback() closes only the innermost block, reverting "plan" from "enterprise" back to "pro" and removing "seats". A new inner block sets "seats" to "5", and commit() persists both open levels at once, leaving zero open blocks (rollback() afterward returns False).

Constraints

  • Standalone get, set, and delete calls outside transactions must run in O(1) average time without leaking history memory.
  • Inside arbitrarily nested transactions, get must run in O(1) average time and set / delete in O(1) amortized time.
  • Rollback must distinguish keys created during a transaction (which must be deleted upon rollback) from pre-existing keys that were overwritten or deleted (whose prior string values must be restored).
  • Calling commit(), rollback(), or rollback_to(name) when no transaction block is open must return False.

Step-by-step walkthrough

  1. Restate the transaction and savepoint rules

    We need an in-memory key -> value store where get, set, and delete always operate on the latest state in O(1) time, even inside deeply nested transactions. Let's pin down the exact rules for blocks and savepoints:

    • Outside a transaction: set and delete modify the base map immediately; commit(), rollback(), and rollback_to(name) return False because nothing is open.
    • Nested blocks (begin, rollback, commit): begin() opens a new inner block on a stack. rollback() undoes only the innermost open block and closes it. commit() keeps changes from every open block and closes the entire stack at once.
    • Named savepoints (savepoint, rollback_to): savepoint(name) marks the current point inside the innermost open block. Following standard SQL ROLLBACK TO SAVEPOINT semantics:
      1. rollback_to(name) searches from the innermost block outward so the most recent savepoint of that name wins.
      2. It undoes every write made since name, closes any inner begin() blocks opened after name, and discards any later savepoints created after name in that block.
      3. Crucially, savepoint name remains active, so calling rollback_to(name) a second time works too!
      4. Calling savepoint(name) again in the same block overwrites name and moves it to the newest position.
  2. Brute force: full-dictionary snapshots vs. layered maps

    Before settling on our design, compare the two first-instinct approaches against the O(1) requirements on N total keys and D nested blocks:

    Approach                         get(key)   set / delete   begin / savepoint   rollback   commit
    -------------------------------  ---------  -------------  ------------------  ---------  --------------
    1. Copy full dict on checkpoint  O(1)       O(1)           O(N) time & space   O(1)       O(1)
    2. Layered overlay dicts         O(D)       O(1)           O(1)                O(1)       O(changed keys)
    3. Single live dict + undo log   O(1)       O(1)           O(1)                O(undone)  O(1)
    
    • Full-dictionary snapshots copy all N keys at every begin() and savepoint(). With 1,000,000 keys and 5 savepoints, that copies 5,000,000 entries even if the transaction edits a single key.
    • Layered overlay dicts push a fresh empty dict per begin() or savepoint(), which makes begin and rollback O(1), but get(key) must search up to D layers from top to bottom (O(D)), violating O(1) reads when transactions nest deeply.
  3. Key idea: mutate one live dictionary and append an undo log

    An undo log gives us O(1) get, set, delete, begin, savepoint, and commit all at once:

    1. Keep one live dictionary self.data holding the latest values, so get(key) is always a single O(1) hash lookup.
    2. Whenever a transaction is open, right before set or delete changes self.data[key], append (key, previous_state) to self.undo_log.
    3. How do we tell apart "key 'host' used to hold 'db1'" from "key 'port' did not exist at all"? We create a unique sentinel object _MISSING = object(). On rollback, if old_state is _MISSING, we del self.data[key]; otherwise we restore self.data[key] = old_state.

    When rolling back, we must pop undo entries newest-first (LIFO) — watch what happens if key "a" (initially "1") is written twice inside a block:

    Initial: data = {"a": "1"},  undo_log = []
      set("a", "2")  ->  append ("a", "1"),  data = {"a": "2"}
      set("a", "3")  ->  append ("a", "2"),  data = {"a": "3"}
    
    Pop newest-first (RIGHT):  restore ("a", "2"), then restore ("a", "1")  -> ends at "1"
    Pop oldest-first (WRONG):  restore ("a", "1"), then restore ("a", "2")  -> ends at "2"!
    

    Best of all, both begin() and savepoint(name) now just record one integer: len(self.undo_log) at that moment! Rolling back simply pops and applies undo records until len(self.undo_log) shrinks back to that integer.

  4. Code the store state and O(1) reads/writes

    Notice two small guards in set and delete:

    • Outside any open transaction (not self.transactions), writes skip self.undo_log completely so normal operations never accumulate log memory.
    • In delete(key), if key not in self.data, we return immediately. Deleting a non-existent key changed nothing, so there is nothing to undo.
    from typing import Dict, List, Optional, Tuple
    
    # Unique sentinel object stored in `undo_log` when a key did not exist prior to `set()`,
    # allowing rollback to distinguish "delete newly created key" from "restore string value".
    _MISSING = object()
    
    
    class _Transaction:
        """Metadata for one open transaction block on the nesting stack."""
    
        def __init__(self, log_start: int) -> None:
            # Index in `undo_log` when `begin()` opened this block.
            self.log_start = log_start
            # Maps savepoint_name -> undo_log length at creation time.
            # Python dicts preserve insertion order, which tracks savepoint creation order.
            self.savepoints: Dict[str, int] = {}
    
    
    class TransactionalKVStore:
        """In-memory key-value store supporting nested transactions and named savepoints."""
    
        def __init__(self) -> None:
            # Live key-value state: {"host": "db2", "port": "5432"} — always reflects latest writes in O(1).
            self.data: Dict[str, str] = {}
            # Chronological inverse records: [("host", "db1"), ("port", _MISSING)] — popped newest-first.
            self.undo_log: List[Tuple[str, object]] = []
            # Nesting stack of open `_Transaction` blocks, with the innermost block at `[-1]`.
            self.transactions: List[_Transaction] = []
    
        def get(self, key: str) -> Optional[str]:
            """Return the current value of `key` in O(1) time without consulting `undo_log`."""
            return self.data.get(key)
    
        def set(self, key: str, value: str) -> None:
            """Write `key = value`, logging its prior state only if a transaction is open."""
            if self.transactions:
                previous_state = self.data.get(key, _MISSING)
                self.undo_log.append((key, previous_state))
            self.data[key] = value
    
        def delete(self, key: str) -> None:
            """Delete `key` if present; missing keys are a no-op so no bogus undo entry is logged."""
            if key not in self.data:
                return
            if self.transactions:
                previous_value = self.data[key]
                self.undo_log.append((key, previous_value))
            del self.data[key]
    
  5. Code begin and savepoint (and why overwriting must refresh order)

    Why do we care about insertion order inside tx.savepoints? Suppose a block creates savepoint("s"), then savepoint("t"), and then overwrites savepoint("s") later:

    Timeline:  savepoint("s")  ->  set("a","1")  ->  savepoint("t")  ->  set("a","2")  ->  savepoint("s")
    Order of active savepoints must now be:  ["t", "s"]   ("s" is newer than "t"!)
    If we later call rollback_to("t"), "s" was re-created AFTER "t", so "s" must be discarded!
    

    In Python, doing savepoints["s"] = new_len on an existing key keeps "s" in its old dict slot before "t". Calling savepoints.pop(name, None) right before savepoints[name] = len(self.undo_log) moves name to the end of the dict so dict order always matches true creation order — even when zero writes occurred between two savepoints!

    class TransactionalKVStore:
        def begin(self) -> None:
            """Open a nested transaction block anchored at the current `undo_log` length."""
            self.transactions.append(_Transaction(len(self.undo_log)))
    
        def savepoint(self, name: str) -> None:
            """Record or overwrite savepoint `name` in the innermost open transaction block."""
            if not self.transactions:
                # Outside any transaction, writes cannot be rolled back, so ignore savepoints.
                return
            innermost_savepoints = self.transactions[-1].savepoints
            # Pop before re-inserting so an overwritten name moves to the newest dict position.
            innermost_savepoints.pop(name, None)
            innermost_savepoints[name] = len(self.undo_log)
    
  6. Code rollback, rollback_to, and commit

    All rollbacks funnel through one helper _undo_until(target_length). Look at how cleanly each transaction control method maps onto the stack and log:

    undo_log:   [ (host,db1) | (port,MISSING), (host,db2) | (region,MISSING) ]
                 ^            ^                            ^
                 |            |                            +-- Block 1: log_start = 3, savepoints = {"inner": 4}
                 |            +-- Block 0 savepoint "cp1" = 1 (savepoint "cp2" = 2 created after it)
                 +-- Block 0: log_start = 0
    
    Calling rollback_to("cp1") finds "cp1" in Block 0 (depth = 0):
      1. _undo_until(1)              -> undoes (region,MISSING), (host,db2), (port,MISSING)
      2. del transactions[0 + 1:]    -> closes Block 1 (and its "inner" savepoint)
      3. _drop_savepoints_after(...) -> deletes "cp2" from Block 0, keeping "cp1" alive!
    

    And commit() is O(1) work: because self.data already holds every committed change, we simply reset self.undo_log = [] and self.transactions = [].

    class TransactionalKVStore:
        def rollback_to(self, name: str) -> bool:
            """Roll back all mutations since savepoint `name`, keeping `name` itself active."""
            # Search from innermost transaction outward so shadowed names resolve to the newest one.
            for depth in range(len(self.transactions) - 1, -1, -1):
                tx = self.transactions[depth]
                if name in tx.savepoints:
                    target_log_len = tx.savepoints[name]
                    self._undo_until(target_log_len)
                    # Close any nested transaction blocks opened after `tx`.
                    del self.transactions[depth + 1:]
                    # Discard savepoints created after `name` in `tx`, while keeping `name` itself.
                    self._drop_savepoints_after(tx, name)
                    return True
            return False
    
        def rollback(self) -> bool:
            """Undo every write in the innermost open transaction block and close it."""
            if not self.transactions:
                return False
            innermost_tx = self.transactions.pop()
            self._undo_until(innermost_tx.log_start)
            return True
    
        def commit(self) -> bool:
            """Persist all uncommitted writes across every nested block and close all blocks."""
            if not self.transactions:
                return False
            # `self.data` already holds the latest values; discarding undo history commits everything.
            self.undo_log = []
            self.transactions = []
            return True
    
        def _undo_until(self, target_length: int) -> None:
            """Replay undo entries newest-first (LIFO) until `len(undo_log) == target_length`."""
            while len(self.undo_log) > target_length:
                key, old_state = self.undo_log.pop()
                if old_state is _MISSING:
                    del self.data[key]
                else:
                    self.data[key] = old_state
    
        def _drop_savepoints_after(self, tx: _Transaction, target_name: str) -> None:
            """Delete savepoints in `tx` created strictly after `target_name`."""
            names_to_remove = []
            seen_target = False
            for existing_name in tx.savepoints:
                if seen_target:
                    names_to_remove.append(existing_name)
                elif existing_name == target_name:
                    seen_target = True
            for later_name in names_to_remove:
                del tx.savepoints[later_name]
    
  7. Walk through Example 1 step by step

    Let's trace self.data, self.undo_log, and self.transactions across every call in Example 1:

    Call                            self.data                        self.undo_log
    ------------------------------  -------------------------------  ------------------------------------------------
    set("host", "db1")              {"host": "db1"}                  []   (no open block -> nothing logged)
    begin()                         {"host": "db1"}                  []   (transactions = [B0(start=0, sp={})])
    set("host", "db2")              {"host": "db2"}                  [("host", "db1")]
    savepoint("before_migration")   {"host": "db2"}                  [("host", "db1")]   (sp={"before_migration": 1})
    set("port", "5432")             {"host": "db2", "port": "5432"}  [("host", "db1"), ("port", _MISSING)]
    delete("host")                  {"port": "5432"}                 [("host", "db1"), ("port", _MISSING), ("host", "db2")]
      -> get("host") is None, get("port") == "5432"
    
    rollback_to("before_migration") pop ("host", "db2") -> data["host"] = "db2"
                                    pop ("port", _MISSING) -> del data["port"]
                                    {"host": "db2"}                  [("host", "db1")]   ("before_migration" stays at 1)
      -> returns True; get("host") == "db2", get("port") is None
    
    rollback()                      pop B0 (start=0); pop ("host", "db1") -> data["host"] = "db1"
                                    {"host": "db1"}                  []   (transactions = [])
      -> returns True; get("host") == "db1", get("port") is None
    
  8. Complete solution

    from typing import Dict, List, Optional, Tuple
    
    # Unique sentinel object stored in `undo_log` when a key did not exist prior to `set()`,
    # allowing rollback to distinguish "delete newly created key" from "restore string value".
    _MISSING = object()
    
    
    class _Transaction:
        """Metadata for one open transaction block on the nesting stack."""
    
        def __init__(self, log_start: int) -> None:
            # Index in `undo_log` when `begin()` opened this block.
            self.log_start = log_start
            # Maps savepoint_name -> undo_log length at creation time.
            # Python dicts preserve insertion order, which tracks savepoint creation order.
            self.savepoints: Dict[str, int] = {}
    
    
    class TransactionalKVStore:
        """In-memory key-value store supporting nested transactions and named savepoints."""
    
        def __init__(self) -> None:
            # Live key-value state: {"host": "db2", "port": "5432"} — always reflects latest writes in O(1).
            self.data: Dict[str, str] = {}
            # Chronological inverse records: [("host", "db1"), ("port", _MISSING)] — popped newest-first.
            self.undo_log: List[Tuple[str, object]] = []
            # Nesting stack of open `_Transaction` blocks, with the innermost block at `[-1]`.
            self.transactions: List[_Transaction] = []
    
        def get(self, key: str) -> Optional[str]:
            """Return the current value of `key` in O(1) time without consulting `undo_log`."""
            return self.data.get(key)
    
        def set(self, key: str, value: str) -> None:
            """Write `key = value`, logging its prior state only if a transaction is open."""
            if self.transactions:
                previous_state = self.data.get(key, _MISSING)
                self.undo_log.append((key, previous_state))
            self.data[key] = value
    
        def delete(self, key: str) -> None:
            """Delete `key` if present; missing keys are a no-op so no bogus undo entry is logged."""
            if key not in self.data:
                return
            if self.transactions:
                previous_value = self.data[key]
                self.undo_log.append((key, previous_value))
            del self.data[key]
    
        def begin(self) -> None:
            """Open a nested transaction block anchored at the current `undo_log` length."""
            self.transactions.append(_Transaction(len(self.undo_log)))
    
        def savepoint(self, name: str) -> None:
            """Record or overwrite savepoint `name` in the innermost open transaction block."""
            if not self.transactions:
                # Outside any transaction, writes cannot be rolled back, so ignore savepoints.
                return
            innermost_savepoints = self.transactions[-1].savepoints
            # Pop before re-inserting so an overwritten name moves to the newest dict position.
            innermost_savepoints.pop(name, None)
            innermost_savepoints[name] = len(self.undo_log)
    
        def rollback_to(self, name: str) -> bool:
            """Roll back all mutations since savepoint `name`, keeping `name` itself active."""
            # Search from innermost transaction outward so shadowed names resolve to the newest one.
            for depth in range(len(self.transactions) - 1, -1, -1):
                tx = self.transactions[depth]
                if name in tx.savepoints:
                    target_log_len = tx.savepoints[name]
                    self._undo_until(target_log_len)
                    # Close any nested transaction blocks opened after `tx`.
                    del self.transactions[depth + 1:]
                    # Discard savepoints created after `name` in `tx`, while keeping `name` itself.
                    self._drop_savepoints_after(tx, name)
                    return True
            return False
    
        def rollback(self) -> bool:
            """Undo every write in the innermost open transaction block and close it."""
            if not self.transactions:
                return False
            innermost_tx = self.transactions.pop()
            self._undo_until(innermost_tx.log_start)
            return True
    
        def commit(self) -> bool:
            """Persist all uncommitted writes across every nested block and close all blocks."""
            if not self.transactions:
                return False
            # `self.data` already holds the latest values; discarding undo history commits everything.
            self.undo_log = []
            self.transactions = []
            return True
    
        def _undo_until(self, target_length: int) -> None:
            """Replay undo entries newest-first (LIFO) until `len(undo_log) == target_length`."""
            while len(self.undo_log) > target_length:
                key, old_state = self.undo_log.pop()
                if old_state is _MISSING:
                    del self.data[key]
                else:
                    self.data[key] = old_state
    
        def _drop_savepoints_after(self, tx: _Transaction, target_name: str) -> None:
            """Delete savepoints in `tx` created strictly after `target_name`."""
            names_to_remove = []
            seen_target = False
            for existing_name in tx.savepoints:
                if seen_target:
                    names_to_remove.append(existing_name)
                elif existing_name == target_name:
                    seen_target = True
            for later_name in names_to_remove:
                del tx.savepoints[later_name]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine editing values on a single live whiteboard while keeping a stack of sticky notes on the side (an undo log, a chronological list of old values recorded right before each edit). Whenever you start a transaction or drop a named savepoint (a named bookmark inside a transaction that you can rewind to without aborting the whole transaction), you simply write down how tall the sticky-note stack is right now. Reading any key is always one glance at the whiteboard, committing just throws the sticky-note stack in the trash, and rolling back peels sticky notes off the top one by one until the stack returns to the bookmarked height.

Why do the two obvious designs struggle here? Copying the entire dictionary at every begin() and savepoint() takes O(N) time and memory per checkpoint, even when a transaction modifies just one key out of a million. Conversely, pushing a new empty "overlay" dictionary per nested block avoids copying N keys, but slows get(key) down to O(D) because a missing key must check all D stacked overlays from top to bottom before reaching the base dictionary.

Walk through Example 1 on host = "db1" to see how the undo log + _MISSING sentinel object (a unique marker value meaning "this key did not exist before") handles overwrites and deletions effortlessly:

  • begin(), then set("host", "db2"): Log ("host", "db1") at index 0, update whiteboard to {"host": "db2"}.
  • savepoint("before_migration"): Record bookmark "before_migration" -> length 1.
  • set("port", "5432"), then delete("host"): Log ("port", _MISSING) and ("host", "db2"); whiteboard becomes {"port": "5432"}.
  • rollback_to("before_migration"): Pop newest-first down to length 1 — ("host", "db2") puts "host": "db2" back, and ("port", _MISSING) deletes "port" — restoring {"host": "db2"} while keeping "before_migration" at length 1 for future rewinds.

Complexity

Let N be the number of keys currently stored, W be the number of writes made since the outermost begin(), D be the number of open nested blocks, and S be the number of savepoints in the matched block:

  • get(key): O(1) average time, because it performs a single hash-table lookup in self.data and never inspects self.undo_log or self.transactions.
  • set(key, value) and delete(key): Amortized O(1) average time (constant time per operation averaged over a sequence of calls, accounting for occasional list resizing), doing one O(1) dictionary operation on self.data plus at most one list.append onto self.undo_log.
  • begin() and savepoint(name): O(1) average time, because each only records the integer len(self.undo_log) in a list or dictionary without copying any keys.
  • rollback(): O(k) time for k undo entries in the innermost block (O(1) amortized per write across the whole run, because each undo entry was created by one prior write and can be popped at most once).
  • rollback_to(name): O(D + S + k) time — scanning up to D open blocks with O(1) dict membership checks, scanning S savepoint names in the matched block to remove later ones, and popping k undo entries.
  • commit(): O(1) active work (resetting self.undo_log and self.transactions to empty lists, while memory reclamation is amortized across the W writes that allocated those entries).
  • Space: O(N + W) total memory — O(N) for the live keys in self.data plus one (key, old_state) tuple per transactional write in self.undo_log (plus O(D + total_savepoints) for block metadata).

Edge cases

  • Key created inside a block, then deleted in the same block: set logs (k, _MISSING) and delete logs (k, val). Popping newest-first restores val and then deletes k, leaving k completely absent from self.data.
  • Key that existed before the block, then deleted: delete logs (k, old_val), so rollback restores self.data[k] = old_val.
  • Deleting a non-existent key: Treated as a pure no-op without appending to self.undo_log, preventing phantom restorations on rollback.
  • No active transaction (self.transactions is empty): commit(), rollback(), and rollback_to(name) return False, savepoint(name) does nothing, and set/delete skip self.undo_log so memory never leaks.
  • Rolling back to the same savepoint multiple times: rollback_to("before_migration") keeps "before_migration" in tx.savepoints, so subsequent writes can rewind to it again.
  • Rolling back to a savepoint in an outer block: del self.transactions[depth + 1:] closes every nested block opened after that outer savepoint, and _drop_savepoints_after forgets later savepoints created in that outer block.
  • Shadowed savepoint names across nested blocks: Searching depth from len(self.transactions) - 1 down to 0 ensures the innermost block's savepoint wins; once that inner block rolls back, the outer block's savepoint becomes visible again.

Common mistakes

  • Restoring a newly created key via self.data[key] = None instead of del self.data[key]: Although get(key) still returns None, key in self.data becomes True! A later delete(key) would think the key exists, and len(self.data) would leak dead keys forever.
  • Replaying the undo log oldest-first (FIFO) instead of newest-first (LIFO): If "a" changes "1" -> "2" -> "3", replaying oldest-first sets "1" and then "2", leaving the wrong value "2".
  • Appending to undo_log when no transaction is open: Unbounded writes outside begin() would grow undo_log forever with entries that can never be rolled back or committed.
  • Making commit() close only the innermost transaction: Per the specification, commit() persists all nested blocks to the base state and closes all open transactions.
  • Forgetting to delete savepoints created after the target savepoint (or failing to refresh dict order on overwrite): If "cp2" was created after "cp1", rewinding to "cp1" invalidates "cp2"; leaving "cp2" in tx.savepoints lets a later rollback_to("cp2") return True against an invalid log index.

Alternative approaches

  • Full-map snapshots (dict(self.data) per begin and savepoint): Trivial to implement (~30 lines) and great as a test oracle (_BruteKV), but O(N) time and space on every begin() and savepoint().
  • Copy-on-write layered dictionaries (overlays with tombstones): Push a fresh dict per block/savepoint and mark deletions with a tombstone (a special marker entry in an upper layer hiding a key that still exists in a lower layer). Dropping a layer on rollback is O(1) even after millions of writes, and repeated writes to the same key in one layer only store one entry, but get(key) degrades to O(D) across D layers and commit() costs O(total overlay entries) to merge down.
  • Persistent hash-array mapped trie (HAMT): Functional languages (like Clojure's persistent maps) share unchanged tree branches so snapshots cost O(1) and reads/writes cost O(log_32 N) (~1–5 pointer hops) with structural sharing, trading higher constant factors and implementation complexity for instant snapshots and immutability.

Follow-up questions

  • Under a read-heavy workload, how does an undo-log design trade off latency and memory against stacked overlay maps? When reads vastly outnumber writes (say 100:1), the undo log wins decisively on throughput: self.data always holds the flattened current state, so every get(key) does one hash lookup (O(1)) regardless of nesting depth D, whereas layered dictionaries force every miss in top overlays to probe up to D hash tables (O(D)). Write overhead in the undo log is just one list append per mutation, and rollback work (O(k)) is bounded by the rare writes already paid for. Layered dictionaries only pull ahead when D is guaranteed tiny (e.g., D = 1), uncommitted writes must stay isolated from concurrent readers, or a single transaction overwrites the exact same key thousands of times (storing O(unique keys) instead of O(total writes)).
  • What changes are needed to let multiple threads run isolated transactions concurrently and detect write conflicts at commit time? Replace single-value entries with MVCC (multi-version concurrency control) — storing a sorted version list [(commit_ts, value_or_tombstone), ...] per key alongside an atomic global commit_counter. When transaction T starts, it records read_ts = commit_counter for snapshot isolation (a guarantee that T sees a frozen, consistent database snapshot from read_ts), checks its own private write buffer + private undo log (for savepoints!) first on get, and otherwise reads the newest committed version with commit_ts <= read_ts. At commit(), under a brief lock or per-key latches, check whether any key in T's write set gained a version with commit_ts > read_ts; if so, abort T (first-committer-wins conflict detection), and otherwise assign new_ts = ++commit_counter and append T's final key values. Note that snapshot isolation still permits write skew (two transactions reading overlapping keys and writing disjoint keys that together break an invariant), which requires also validating T's read set for full serializability.
  • How would you add crash-safe disk durability using a write-ahead log and periodic snapshots? Because uncommitted writes and rolled-back savepoints never need to survive a crash, keep undo_log purely in RAM and write only committed state to an append-only on-disk write-ahead log (WAL) (a sequential redo log of committed mutations). On commit() (or on standalone writes outside begin()), collect the final values/deletions of modified keys, write a framed WAL record containing (lsn, payload_length, key_mutations, crc32_checksum), and call fsync (an OS system call that flushes buffered disk writes to physical non-volatile storage) before returning True (batching concurrent commits via group commit to share one fsync). Periodically write a background checkpoint file containing a snapshot of self.data plus its checkpoint_lsn to a temp file, fsync it, atomically rename it into place, and truncate older WAL segments; on crash recovery, load the latest checkpoint and replay WAL records with lsn > checkpoint_lsn, stopping cleanly if the final tail record has a truncated length or bad checksum.

Follow-up questions

Similar questions

More Nextdoor interview questions

All 21 Nextdoor questions →