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 tokey, returningNonewhenkeyis absent.set(key: str, value: str) -> None: Bindkeytovaluewithin the active context (or directly in the base store when no transaction is open).delete(key: str) -> None: Removekeyif present; ifkeyis 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. Reusingnamewithin that same block replaces the earlier bookmark and movesnameto the newest position; callingsavepointwith no open transaction does nothing.rollback_to(name: str) -> bool: Search open transaction blocks from innermost to outermost for savepointname. When found, undo every mutation performed sincename, close any inner transaction blocks opened aftername, discard savepoints created afternamein that block while keepingnameitself active for future rewinds, and returnTrue. ReturnFalseif no open block containsname.rollback() -> bool: Revert every mutation made inside the innermost open transaction block, close that block, and returnTrue(orFalsewhen 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 returnTrue(orFalsewhen 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, anddeletecalls outside transactions must run inO(1)average time without leaking history memory. - Inside arbitrarily nested transactions,
getmust run inO(1)average time andset/deleteinO(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(), orrollback_to(name)when no transaction block is open must returnFalse.
Step-by-step walkthrough
Restate the transaction and savepoint rules
We need an in-memory
key -> valuestore whereget,set, anddeletealways operate on the latest state inO(1)time, even inside deeply nested transactions. Let's pin down the exact rules for blocks and savepoints:- Outside a transaction:
setanddeletemodify the base map immediately;commit(),rollback(), androllback_to(name)returnFalsebecause 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 SQLROLLBACK TO SAVEPOINTsemantics:rollback_to(name)searches from the innermost block outward so the most recent savepoint of that name wins.- It undoes every write made since
name, closes any innerbegin()blocks opened aftername, and discards any later savepoints created afternamein that block. - Crucially, savepoint
nameremains active, so callingrollback_to(name)a second time works too! - Calling
savepoint(name)again in the same block overwritesnameand moves it to the newest position.
- Outside a transaction:
Brute force: full-dictionary snapshots vs. layered maps
Before settling on our design, compare the two first-instinct approaches against the
O(1)requirements onNtotal keys andDnested 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
Nkeys at everybegin()andsavepoint(). With1,000,000keys and5savepoints, that copies5,000,000entries even if the transaction edits a single key. - Layered overlay dicts push a fresh empty dict per
begin()orsavepoint(), which makesbeginandrollbackO(1), butget(key)must search up toDlayers from top to bottom (O(D)), violatingO(1)reads when transactions nest deeply.
- Full-dictionary snapshots copy all
Key idea: mutate one live dictionary and append an undo log
An undo log gives us
O(1)get,set,delete,begin,savepoint, andcommitall at once:- Keep one live dictionary
self.dataholding the latest values, soget(key)is always a singleO(1)hash lookup. - Whenever a transaction is open, right before
setordeletechangesself.data[key], append(key, previous_state)toself.undo_log. - 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, ifold_state is _MISSING, wedel self.data[key]; otherwise we restoreself.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()andsavepoint(name)now just record one integer:len(self.undo_log)at that moment! Rolling back simply pops and applies undo records untillen(self.undo_log)shrinks back to that integer.- Keep one live dictionary
Code the store state and O(1) reads/writes
Notice two small guards in
setanddelete:- Outside any open transaction (
not self.transactions), writes skipself.undo_logcompletely so normal operations never accumulate log memory. - In
delete(key), ifkey 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]- Outside any open transaction (
Code begin and savepoint (and why overwriting must refresh order)
Why do we care about insertion order inside
tx.savepoints? Suppose a block createssavepoint("s"), thensavepoint("t"), and then overwritessavepoint("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_lenon an existing key keeps"s"in its old dict slot before"t". Callingsavepoints.pop(name, None)right beforesavepoints[name] = len(self.undo_log)movesnameto 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)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()isO(1)work: becauseself.dataalready holds every committed change, we simply resetself.undo_log = []andself.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]Walk through Example 1 step by step
Let's trace
self.data,self.undo_log, andself.transactionsacross 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 NoneComplete 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(), thenset("host", "db2"): Log("host", "db1")at index0, update whiteboard to{"host": "db2"}.savepoint("before_migration"): Record bookmark"before_migration" -> length 1.set("port", "5432"), thendelete("host"): Log("port", _MISSING)and("host", "db2"); whiteboard becomes{"port": "5432"}.rollback_to("before_migration"): Pop newest-first down to length1—("host", "db2")puts"host": "db2"back, and("port", _MISSING)deletes"port"— restoring{"host": "db2"}while keeping"before_migration"at length1for 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 inself.dataand never inspectsself.undo_logorself.transactions.set(key, value)anddelete(key): AmortizedO(1)average time (constant time per operation averaged over a sequence of calls, accounting for occasional list resizing), doing oneO(1)dictionary operation onself.dataplus at most onelist.appendontoself.undo_log.begin()andsavepoint(name):O(1)average time, because each only records the integerlen(self.undo_log)in a list or dictionary without copying any keys.rollback():O(k)time forkundo 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 toDopen blocks withO(1)dict membership checks, scanningSsavepoint names in the matched block to remove later ones, and poppingkundo entries.commit():O(1)active work (resettingself.undo_logandself.transactionsto empty lists, while memory reclamation is amortized across theWwrites that allocated those entries).- Space:
O(N + W)total memory —O(N)for the live keys inself.dataplus one(key, old_state)tuple per transactional write inself.undo_log(plusO(D + total_savepoints)for block metadata).
Edge cases
- Key created inside a block, then deleted in the same block:
setlogs(k, _MISSING)anddeletelogs(k, val). Popping newest-first restoresvaland then deletesk, leavingkcompletely absent fromself.data. - Key that existed before the block, then deleted:
deletelogs(k, old_val), so rollback restoresself.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.transactionsis empty):commit(),rollback(), androllback_to(name)returnFalse,savepoint(name)does nothing, andset/deleteskipself.undo_logso memory never leaks. - Rolling back to the same savepoint multiple times:
rollback_to("before_migration")keeps"before_migration"intx.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_afterforgets later savepoints created in that outer block. - Shadowed savepoint names across nested blocks: Searching
depthfromlen(self.transactions) - 1down to0ensures 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] = Noneinstead ofdel self.data[key]: Althoughget(key)still returnsNone,key in self.databecomesTrue! A laterdelete(key)would think the key exists, andlen(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_logwhen no transaction is open: Unbounded writes outsidebegin()would growundo_logforever 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"intx.savepointslets a laterrollback_to("cp2")returnTrueagainst an invalid log index.
Alternative approaches
- Full-map snapshots (
dict(self.data)perbeginandsavepoint): Trivial to implement (~30 lines) and great as a test oracle (_BruteKV), butO(N)time and space on everybegin()andsavepoint(). - 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, butget(key)degrades toO(D)acrossDlayers andcommit()costsO(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 costO(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.dataalways holds the flattened current state, so everyget(key)does one hash lookup (O(1)) regardless of nesting depthD, whereas layered dictionaries force every miss in top overlays to probe up toDhash 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 whenDis 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 (storingO(unique keys)instead ofO(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 globalcommit_counter. When transactionTstarts, it recordsread_ts = commit_counterfor snapshot isolation (a guarantee thatTsees a frozen, consistent database snapshot fromread_ts), checks its own private write buffer + private undo log (for savepoints!) first onget, and otherwise reads the newest committed version withcommit_ts <= read_ts. Atcommit(), under a brief lock or per-key latches, check whether any key inT's write set gained a version withcommit_ts > read_ts; if so, abortT(first-committer-wins conflict detection), and otherwise assignnew_ts = ++commit_counterand appendT'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 validatingT'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_logpurely in RAM and write only committed state to an append-only on-disk write-ahead log (WAL) (a sequential redo log of committed mutations). Oncommit()(or on standalone writes outsidebegin()), collect the final values/deletions of modified keys, write a framed WAL record containing(lsn, payload_length, key_mutations, crc32_checksum), and callfsync(an OS system call that flushes buffered disk writes to physical non-volatile storage) before returningTrue(batching concurrent commits via group commit to share onefsync). Periodically write a background checkpoint file containing a snapshot ofself.dataplus itscheckpoint_lsnto a temp file,fsyncit, atomicallyrenameit into place, and truncate older WAL segments; on crash recovery, load the latest checkpoint and replay WAL records withlsn > checkpoint_lsn, stopping cleanly if the final tail record has a truncated length or bad checksum.
Follow-up questions
- Under a read-heavy workload, how does an undo-log design trade off latency and memory against stacked overlay maps?
- What changes are needed to let multiple threads run isolated transactions concurrently and detect write conflicts at commit time?
- How would you add crash-safe disk durability using a write-ahead log and periodic snapshots?
Similar questions
- Recruiter Screen: Motivation, ML Projects, and Recent Research
- End-to-End Tabular ML Pipeline in Pure NumPy
- Tabular Classification Training and Batch Scoring Pipeline
- Score-Ranked Feed with Three-Photo Grouping
- CAP Trade-Offs, Distributed Architecture, and Multithreading in Practice
- Presenting Key ML Projects and Onboarding Logistics
More Nextdoor interview questions
- Merge Weekly Schedule Intervals Medium
- Recruiter Screen: Motivation, ML Projects, and Recent Research Medium
- Score-Ranked Feed with Three-Photo Grouping Medium Pro
- End-to-End Tabular ML Pipeline in Pure NumPy Medium Pro
- Tabular Classification Training and Batch Scoring Pipeline Medium Pro
- CAP Trade-Offs, Distributed Architecture, and Multithreading in Practice Hard Pro
- Presenting Key ML Projects and Onboarding Logistics Medium Pro
- Analytical Data Model for KPI Dashboards, Retention, and Timezones Hard Pro
- Asynchronous Background Job Scheduler Scaling 100x Medium Pro
- Privacy-Bounded Local Community Feed and Urgent Alert System Medium Pro