In-Memory Key-Value Store with Nested Transactions
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory key-value database that supports stacked, nested transactions via begin, commit, and rollback. Calling begin while a transaction is already active opens a child transaction layered directly above the current innermost transaction.
Implement versioned_kv_store(operations, arguments) (backed by a VersionedKVStore class) that replays parallel lists of operation names and argument lists and returns a list of outputs, one per operation:
"VersionedKVStore"with[]: constructs an empty database with zero active transactions and outputsNone."set"with[key, value]: storeskey -> valueinside the innermost active transaction if one exists, or directly in the permanent base store otherwise; outputsNone."get"with[key]: resolveskeyby checking the innermost active transaction first, then each enclosing transaction outward, and finally the permanent base store. Returns the latest visible integer value, or-1ifkeywas never stored or its newest visible mutation is a deletion."delete"with[key]: markskeyas removed in the active scope and outputsNone. Inside an open transaction, a deletion hides any value from enclosing transactions or the base store (soget(key)returns-1), taking effect further down only when committed. Deleting a key that is already absent or hidden leavesget(key)returning-1."begin"with[]: opens a new innermost transaction (nested inside any currently active transaction) and outputsNone."commit"with[]: returnsFalseif no transaction is active. Otherwise, folds all writes and deletions from the innermost active transaction into its immediate parent transaction (or into the permanent base store when committing the outermost transaction), closes that innermost transaction, and returnsTrue."rollback"with[]: returnsFalseif no transaction is active. Otherwise, discards every write and deletion made in the innermost active transaction, closes it, and returnsTrue.
Mutations performed when zero transactions are active update the permanent base store immediately and cannot be undone.
def versioned_kv_store(operations: List[str], arguments: List[List]) -> List[Optional[object]]:
Examples
Example 1
- Input:
operations = ["VersionedKVStore", "set", "get", "begin", "set", "set", "get", "begin", "delete", "get", "rollback", "get", "commit", "get", "get", "commit"]arguments = [[], ["x", 10], ["x"], [], ["x", 25], ["y", 40], ["x"], [], ["x"], ["x"], [], ["x"], [], ["x"], ["y"], []]
- Output:
[None, None, 10, None, None, None, 25, None, None, -1, True, 25, True, 25, 40, False] - Walk-through:
set("x", 10)writes10to the permanent store;get("x")returns10.begin()opens outer transactionT1, whereset("x", 25)andset("y", 40)run;get("x")returns25.begin()opens inner transactionT2, wheredelete("x")hides"x"soget("x")returns-1.rollback()abortsT2(True), restoringT1's view soget("x")returns25.commit()mergesT1into the permanent store (True), making"x": 25and"y": 40permanent.- The final
commit()has no open transaction to close and returnsFalse.
Example 2
- Input:
operations = ["VersionedKVStore", "set", "begin", "begin", "delete", "commit", "get", "rollback", "get"]arguments = [[], ["k", 7], [], [], ["k"], [], ["k"], [], ["k"]]
- Output:
[None, None, None, None, None, True, -1, True, 7] - Walk-through:
"k"starts at7in the permanent store. Inner transactionT2deletes"k"and commits into outer transactionT1, soget("k")insideT1still returns-1. Rolling backT1discards that merged deletion and exposes7from the permanent store again.
Constraints
1 <= len(operations) == len(arguments) <= 10^5(the first operation is"VersionedKVStore")- Every
keyconsists of1to20lowercase English letters ('a'–'z') 0 <= value <= 10^9- Active transaction nesting depth never exceeds
10^3 - Target efficiency:
O(1)average time forset,delete, andbegin;O(d)worst-case time forgetat nesting depthd; andO(c)time forcommitandrollback, wherecis the number of distinct keys modified in the innermost transaction (independent of total store size)
Step-by-step walkthrough
Understand nested transactions and visibility
We are building an in-memory key-value database where each
begin()opens a fresh transaction stacked above any active transaction:Lookup order (get) Stack of scopes | +-------------------------------------------+ | check 1st -----> | Innermost transaction T2 (layers[-1]) | | check 2nd -----> | Enclosing transaction T1 (layers[0]) | v check last ----> | Permanent base store (self.store) | +-------------------------------------------+- Mutations (
set,delete) touch only the topmost scope (layers[-1]when a transaction is active, otherwiseself.store). - Lookups (
get) search downward fromlayers[-1]throughlayers[0]and finallyself.store, stopping at the first scope that mentionskey(or returning-1if absent or deleted). commit()folds onlylayers[-1]one step down into its immediate parent transaction (or intoself.storewhen closing the outermost transaction) and returnsTrue(Falsewhenlayersis empty).rollback()discards onlylayers[-1]and returnsTrue(Falsewhenlayersis empty).
- Mutations (
Why copying the whole store on `begin()` is too slow
A straightforward prototype clones the entire dictionary on every
begin(): pushdict(states[-1])onbegin(), mutatestates[-1], overwritestates[-2]oncommit(), and pop onrollback().That reference model is easy to reason about on tiny inputs, yet when
self.storeholds40,000keys and we run15,000one-key transactions, cloning the whole dictionary on eachbegin()copies40,000 * 15,000 = 600,000,000entries! To keepcommitandrollbackproportional only to modified keys, each transaction layer must store only the keys changed in that layer (its delta).Key idea: delta dictionaries plus a `DELETED` tombstone
Suppose
self.storecontains{"x": 10}, outer transactionT1sets"x"to25, and inner transactionT2callsdelete("x"). What mustT2's delta dictionary record?If
delete("x")merely omitted"x"fromT2's dictionary ({}),get("x")would fall right through toT1:WRONG (if T2 leaves "x" absent): RIGHT (T2 writes a DELETED tombstone): T2: {} -> "x" not here T2: {"x": DELETED} -> sees DELETED -> return -1! T1: {"x": 25} -> returns 25 (BUG!) T1: {"x": 25} (preserved if T2 rolls back) store: {"x": 10} store: {"x": 10}Inside an active transaction, a deletion must actively mask enclosing scopes! Creating a unique sentinel
DELETED = object()(a tombstone) and settingself.layers[-1][key] = DELETEDtellsget(key)to stop immediately and return-1, while preservingT1andself.storeuntouched in caseT2rolls back.Implement `set`, `get`, `delete`, and `begin`
Because
0is a valid stored integer (0 <= value <= 10^9),get(key)must testif key in layer:andif val is DELETED:rather than truthiness (bool(0)isFalsein Python!).from typing import Any, Dict, List, Optional, Set, Tuple # Unique tombstone object marking a key deleted inside an open transaction layer. # Using `object()` guarantees `val is DELETED` never collides with 0 or any real value. DELETED = object() class VersionedKVStore: def __init__(self) -> None: # store: permanent committed data mapping {key: int_value}, e.g. {'x': 10} self.store: Dict[str, int] = {} # layers: stack of open transaction delta dicts (outermost -> innermost). # Each dict maps {key: int_value | DELETED}, e.g. [{'x': 25}, {'x': DELETED}]. self.layers: List[Dict[str, Any]] = [] def set(self, key: str, value: int) -> None: if self.layers: self.layers[-1][key] = value else: self.store[key] = value def get(self, key: str) -> int: # Search open transactions from innermost (most recent) outward to outermost. for layer in reversed(self.layers): # Check `key in layer` rather than truthiness because 0 is a valid value. if key in layer: val = layer[key] if val is DELETED: return -1 return val return self.store.get(key, -1) def delete(self, key: str) -> None: if self.layers: # Record a tombstone so `get` returns -1 without erasing outer layers yet. self.layers[-1][key] = DELETED else: self.store.pop(key, None) def begin(self) -> None: self.layers.append({})Implement `commit` and `rollback` across nested layers
rollback()simply popsself.layers[-1](returningFalsefirst ifself.layersis empty).commit()popsinner_changes = self.layers.pop()and distinguishes between merging into an enclosing transaction versus applying to the permanent base store:Case 1 — Inner commit (T2 -> T1, as in Example 2): store = {"k": 7}, T1 = {}, T2 = {"k": DELETED} T2 commits -> T1 MUST become {"k": DELETED} so get("k") still returns -1, while rolling back T1 later still exposes store["k"] == 7! Case 2 — Outermost commit (T1 -> store): store = {"k": 7}, T1 = {"k": DELETED, "y": 40} T1 commits -> pop "k" from store, set store["y"] = 40 -> store = {"y": 40} (never store DELETED sentinels inside self.store!)Both
commit()androllback()touch onlyinner_changes, costing time proportional to the keys modified in the innermost transaction rather thanlen(self.store).class VersionedKVStore: # ... __init__, set, get, delete, begin ... def commit(self) -> bool: if not self.layers: return False inner_changes = self.layers.pop() if self.layers: # Merge into parent transaction, keeping DELETED tombstones so they # continue shadowing older transactions and the permanent store. parent_layer = self.layers[-1] for key, val in inner_changes.items(): parent_layer[key] = val else: # Outermost commit: apply real values and permanently remove DELETED keys. for key, val in inner_changes.items(): if val is DELETED: self.store.pop(key, None) else: self.store[key] = val return True def rollback(self) -> bool: if not self.layers: return False # Discard the innermost transaction's delta dict in O(1) stack pop. self.layers.pop() return TrueWire up the driver and trace Example 1
versioned_kv_store(operations, arguments)instantiatesVersionedKVStoreand recordsNonefor void calls, the integer result forget, and the boolean result forcommitandrollback. Let's trace Example 1 (DEL=DELETED):Op # Call self.store self.layers Output ---- ------------------- --------------------- ---------------------------------- ------ 0 VersionedKVStore() {} [] None 1 set("x", 10) {"x": 10} [] None 2 get("x") {"x": 10} [] 10 3 begin() {"x": 10} [{}] None 4 set("x", 25) {"x": 10} [{"x": 25}] None 5 set("y", 40) {"x": 10} [{"x": 25, "y": 40}] None 6 get("x") {"x": 10} [{"x": 25, "y": 40}] 25 (from T1) 7 begin() {"x": 10} [{"x": 25, "y": 40}, {}] None 8 delete("x") {"x": 10} [{"x": 25, "y": 40}, {"x": DEL}] None 9 get("x") {"x": 10} [{"x": 25, "y": 40}, {"x": DEL}] -1 (masked in T2) 10 rollback() {"x": 10} [{"x": 25, "y": 40}] True (T2 discarded) 11 get("x") {"x": 10} [{"x": 25, "y": 40}] 25 (T1 intact) 12 commit() {"x": 25, "y": 40} [] True (T1 -> store) 13 get("x") {"x": 25, "y": 40} [] 25 14 get("y") {"x": 25, "y": 40} [] 40 15 commit() {"x": 25, "y": 40} [] False (no open tx)Complete solution
Here is the complete
VersionedKVStoreimplementation and replay entry point:from typing import Any, Dict, List, Optional, Set, Tuple # Unique tombstone object marking a key deleted inside an open transaction layer. # Using `object()` guarantees `val is DELETED` never collides with 0 or any real value. DELETED = object() class VersionedKVStore: def __init__(self) -> None: # store: permanent committed data mapping {key: int_value}, e.g. {'x': 10} self.store: Dict[str, int] = {} # layers: stack of open transaction delta dicts (outermost -> innermost). # Each dict maps {key: int_value | DELETED}, e.g. [{'x': 25}, {'x': DELETED}]. self.layers: List[Dict[str, Any]] = [] def set(self, key: str, value: int) -> None: if self.layers: self.layers[-1][key] = value else: self.store[key] = value def get(self, key: str) -> int: # Search open transactions from innermost (most recent) outward to outermost. for layer in reversed(self.layers): # Check `key in layer` rather than truthiness because 0 is a valid value. if key in layer: val = layer[key] if val is DELETED: return -1 return val return self.store.get(key, -1) def delete(self, key: str) -> None: if self.layers: # Record a tombstone so `get` returns -1 without erasing outer layers yet. self.layers[-1][key] = DELETED else: self.store.pop(key, None) def begin(self) -> None: self.layers.append({}) def commit(self) -> bool: if not self.layers: return False inner_changes = self.layers.pop() if self.layers: # Merge into parent transaction, keeping DELETED tombstones so they # continue shadowing older transactions and the permanent store. parent_layer = self.layers[-1] for key, val in inner_changes.items(): parent_layer[key] = val else: # Outermost commit: apply real values and permanently remove DELETED keys. for key, val in inner_changes.items(): if val is DELETED: self.store.pop(key, None) else: self.store[key] = val return True def rollback(self) -> bool: if not self.layers: return False # Discard the innermost transaction's delta dict in O(1) stack pop. self.layers.pop() return True def versioned_kv_store( operations: List[str], arguments: List[List] ) -> List[Optional[object]]: """Replay `operations` with `arguments` on a VersionedKVStore and collect outputs.""" kv_store: Optional[VersionedKVStore] = None results: List[Optional[object]] = [] for op, args in zip(operations, arguments): if op == "VersionedKVStore": kv_store = VersionedKVStore() results.append(None) elif op == "set": assert kv_store is not None kv_store.set(args[0], args[1]) results.append(None) elif op == "get": assert kv_store is not None results.append(kv_store.get(args[0])) elif op == "delete": assert kv_store is not None kv_store.delete(args[0]) results.append(None) elif op == "begin": assert kv_store is not None kv_store.begin() results.append(None) elif op == "commit": assert kv_store is not None results.append(kv_store.commit()) elif op == "rollback": assert kv_store is not None results.append(kv_store.rollback()) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture editing a master drawing by stacking transparent plastic sheets over it, adding one sheet per begin() call (nested transactions, where child transactions open inside parent transactions and commit or abort independently). Calling set writes only on the topmost sheet; get peers straight down from the top sheet until it hits the first sheet mentioning that key; rollback() lifts off and discards the top sheet; and commit() transfers the marks from the top sheet onto the sheet directly beneath it. Inside a transaction, delete cannot simply leave the top sheet blank or older values underneath would show right through — instead, it sticks on an opaque marker called a tombstone (a unique sentinel object DELETED = object()), hiding older values from get while leaving lower sheets intact until commit time.
Why does the naive approach fall short? Cloning the entire key-value dictionary on every begin() makes starting a transaction cost O(S) time and space for a database of S keys. Running 15,000 single-key transactions against a 40,000-key store would copy 600,000,000 entries! Keeping a per-transaction delta dictionary (a hash map holding only the keys modified in that specific layer) keeps begin, set, delete, commit, and rollback independent of total store size S.
Here is how set("x", 10) -> begin() -> set("x", 25) -> begin() -> delete("x") -> get("x") -> rollback() -> commit() evolves:
1. set("x", 10) -> store = {"x": 10}, layers = []
2. begin(); set("x",25) -> store = {"x": 10}, layers = [{"x": 25}]
3. begin(); delete("x") -> store = {"x": 10}, layers = [{"x": 25}, {"x": DELETED}]
4. get("x") -> checks layers[-1] first, sees DELETED -> returns -1
5. rollback() -> pops layers[-1]; layers = [{"x": 25}] (get("x") is 25 again!)
6. commit() -> pops layers[-1] into store -> store = {"x": 25}, layers = []
Complexity
Let d be the active nesting depth (d <= 10^3), c be the number of distinct keys modified in the innermost active transaction, and S be the number of keys in self.store.
set(key, value),delete(key), andbegin():O(1)average time. Each performs one dictionary assignment/pop onself.layers[-1](orself.store) or appends{}toself.layers.get(key):O(d)worst-case time. We probekey in layerinO(1)average time from innermost to outermost across at mostdlayers, returning on the first hit or falling back to oneO(1)lookup inself.store.commit():O(c)average time. We pop the innermost delta dictionary ofckeys and loop over itscentries once, applying each inO(1)average time toparent_layerorself.store.rollback():O(1)stack pop (plusO(c)deallocation as Python frees the poppedc-entry dictionary), leavingself.storeand enclosing layers untouched.- Space:
O(S + total distinct modified keys across open layers). Overwriting or deleting the same key repeatedly inside one transaction reuses a single dictionary slot inself.layers[-1].
Edge cases
commit()orrollback()with zero active transactions (self.layers == []): ReturnsFalseimmediately without alteringself.store.- Operations outside any transaction:
setanddeletemutateself.storedirectly and permanently, unaffected by laterrollback()calls. - Stored value
0: Because0is falsy in Python, testingif key in layer:andif val is DELETED:returns0cleanly instead of confusing it with a missing key. - Deleting an absent key: Outside transactions,
self.store.pop(key, None)safely no-ops; inside a transaction, storingDELETEDyields-1ongetand safely no-ops on outermost commit. - Multiple edits to one key in the same layer (
set("x", 1) -> delete("x") -> set("x", 3)): Each call overwritesself.layers[-1]["x"], so the latest state (3) wins. - Inner deletion committed into an outer transaction (Example 2):
T2'sDELETEDmarker copies intoT1(parent_layer[key] = DELETED), continuing to hideself.store[key]while remaining undoable ifT1rolls back.
Common mistakes
- Calling
self.layers[-1].pop(key, None)duringdelete(key)inside a transaction: Removingkeyfrom the inner delta letsget(key)fall through to enclosing layers orself.storeand revive stale data. - Popping
DELETEDkeys fromparent_layeron an innercommit(): In Example 2 (store = {"k": 7},T1 = {},T2 = {"k": DELETED}), doingparent_layer.pop("k", None)leavesT1empty and exposes7prematurely! Convert tombstones to.pop()calls only when committing intoself.store. - Storing
DELETEDdirectly insideself.storeon outermost commit: That leaks tombstones for deleted keys and makesself.store.get(key, -1)returnDELETEDinstead of-1. - Committing all layers at once:
commit()folds only the innermost transaction into its immediate parent; enclosing transactions stay open and rollback-capable.
Alternative approaches
- Single live dictionary + per-layer undo logs (
O(1)get): Apply everysetanddeletestraight to onecurrentdictionary (O(1)get!), while each open transaction records an undo log mapping each key to its prior value (or aMISSINGmarker) the first time that layer touches it (detailed in the first follow-up). - Full dictionary clones on
begin(): Pushdict(states[-1])on everybegin(). GivesO(1)get,set,delete,commit, androllback, but suffersO(S)time and memory perbegin().
Follow-up questions
- How can you reduce get(key) from O(d) worst-case time to O(1) average time without slowing down set, delete, commit, or rollback? Keep a single live dictionary
self.currentsoget(key)is alwaysself.current.get(key, -1)inO(1)average time! Before modifyingkeyinsetordelete, ifself.undo_logsis non-empty andkey not in self.undo_logs[-1], save the pre-imageself.undo_logs[-1][key] = self.current.get(key, MISSING). Onrollback(), popself.undo_logs[-1]and restore each saved value (or.pop(key)ifMISSING) inO(c)time; oncommit(), popchild_logand copy(key, old_val)intoparent_logonly whenkey not in parent_log(preserving the parent's older pre-image), or simply dropchild_logat the outermost commit. - Suppose a client opens 1,000 nested transactions, writes 50,000 keys in the deepest layer, and calls commit() 1,000 times. How do you avoid quadratic copying? Naively copying
50,000child entries upward into999empty parent dicts performs50,000 * 999writes. Eliminate that bottleneck with small-to-large merging: wheneverlen(inner_changes) > len(parent_layer), copy only entries fromparent_layerwhose keys are absent ininner_changesintoinner_changes, then setself.layers[-1] = inner_changes. Each entry moves only when the merged map at least doubles in size, bounding total merge work acrossNwrites byO(N log N). - How would you adapt this design so multiple client threads can execute transactions concurrently? Give each client session its own private
layersstack layered above a shared committedstorewhose entries hold(value, version_number). Under optimistic concurrency control (OCC) (executing transactions privately without locks and validating conflicts at commit time), track the(key, version_number)read set per session; when a session's outermost transaction commits, lockstore, verify that none of its read versions changed (aborting on conflict), apply its delta, and bump version numbers on written keys.
Follow-up questions
- How can you reduce get(key) from O(d) worst-case time to O(1) average time without slowing down set, delete, commit, or rollback?
- Suppose a client opens 1,000 nested transactions, writes 50,000 keys in the deepest layer, and calls commit() 1,000 times. How do you avoid quadratic copying?
- How would you adapt this design so multiple client threads can execute transactions concurrently?
Similar questions
- Calculate Courier Earnings Across Overlapping Order Events
- Aggregate User Session Duration per Audio Space
- O(1) Dynamic Set with Uniform Random Draws
- Processes vs. Threads
- Constant-Time LFU Cache
- Stream Iterator with Checkpoint Recovery
More xAI interview questions
- Continuous Batching Scheduler for Autoregressive Decoding Medium
- Hardest Engineering Problem and Team Motivation Hard
- Calculate Courier Earnings Across Overlapping Order Events Medium Pro
- Constant-Time LFU Cache Medium Pro
- Continuous Slot-Refilling Decode Loop for Batched Token Generation Medium Pro
- Walking Through Dataset Curation and Measuring Its Downstream Model Impact Medium Pro
- Top Three Accomplishments, Five-Minute Project Pitch, and Technical Deep Dive Medium Pro
- Quantity-Bounded LRU Cache Medium Pro
- Comparing OS Processes and Threads Medium Pro
- Single-Pass Web Corpus Cleaning Pipeline Medium Pro