In-Memory Transactional Key-Value Store
Easy · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory string key-value engine supporting arbitrarily nested transactions, and expose it via:
def run_transactional_store(operations: List[List[str]]) -> List[object]:
Process operations in order on a single initially empty store and return a list of equal length holding each command's result:
["set", key, value]— Bindkeytovaluein the currently visible state and returnNone.["get", key]— Return the currently visible string bound tokey, orNoneifkeyis not present.["unset", key]— Removekeyfrom the currently visible state (doing nothing ifkeyis already absent) and returnNone.["count", value]— Return the integer number of currently visible keys whose value equalsvalue, reflecting all uncommitted writes that have not been rolled back.["begin"]— Start a new innermost transaction scope and returnNone.["rollback"]— Undo every write performed inside the innermost open transaction scope, close that scope, and returnTrue. If no transaction scope is open, leave the store unchanged and returnFalse.["commit"]— Close the innermost open transaction scope and returnTrue: if an enclosing parent transaction exists, transfer this scope's writes into that parent (so rolling back the parent later still undoes them); if closing the outermost transaction, make the writes permanent. If no transaction scope is open, returnFalse.
Examples
Example 1
Input:
operations = [
["set", "host", "alpha"],
["begin"],
["set", "host", "beta"],
["set", "replica", "beta"],
["count", "beta"],
["begin"],
["unset", "host"],
["count", "beta"],
["rollback"],
["get", "host"],
["commit"],
["count", "beta"]
]
Output:
[None, None, None, None, 2, None, None, 1, True, "beta", True, 2]
Walk-through: Inside the outer transaction, "host" is overwritten with "beta" and "replica" is set to "beta", giving count("beta") == 2. An inner transaction deletes "host", dropping count("beta") to 1, then rolls back so "host" returns to "beta". Committing the outer transaction makes both "beta" entries permanent.
Example 2
Input:
operations = [
["set", "mode", "safe"],
["begin"],
["begin"],
["set", "mode", "fast"],
["commit"],
["get", "mode"],
["rollback"],
["get", "mode"],
["rollback"]
]
Output:
[None, None, None, None, True, "fast", True, "safe", False]
Walk-through: Committing the inner transaction merges "mode" = "fast" into the outer transaction rather than making it permanent. Rolling back the outer transaction therefore restores "mode" to "safe", and the final ["rollback"] returns False because no transaction remains open.
Constraints
0 <= len(operations) <= 200,000- Every
keyandvalueis a non-empty string. - Simultaneously open nested transactions can reach depth
100,000. - Operations must run in
O(1)expected amortized time; cloning the full key-value map onbeginor linearly scanning keys oncountwill time out.
Step-by-step walkthrough
Understand the operations and transaction rules
We simulate an in-memory string key-value store across a list of operations and return one output item per operation:
Operation Effect on visible state Return value ["set", k, v]Store k -> vNone["get", k]Read current visible value of kValue string, or Noneif absent["unset", k]Remove kif present (no-op if absent)None["count", v]Count how many visible keys currently equal vInteger count ["begin"]Open a new innermost transaction None["rollback"]Undo all changes made since the innermost beginTrue, orFalseif none is open["commit"]Merge the innermost transaction into its parent (or make permanent if outermost) True, orFalseif none is openTwo rules matter most:
- Reads see uncommitted work:
getandcountalways reflect every open transaction that has not been rolled back. - Inner commits are not yet permanent: committing a child transaction folds its changes into its parent, so rolling back the parent later must still undo the child's changes.
- Reads see uncommitted work:
Why copying the dictionary on `begin` fails
The most direct brute-force design pushes
dict(data)onto a stack at everybegin, pops and restores that snapshot onrollback, throws the snapshot away oncommit, and scansdata.values()for everycount.That logic is easy to verify, so it makes a great test oracle, but it breaks the constraints:
- Up to
200,000operations and nesting depth up to100,000mean50,000keys followed by50,000begincalls would copy2.5 * 10^9dictionary entries. 50,000countcalls over50,000keys would scan another2.5 * 10^9entries.
To hit
O(1)expected time per operation, we must avoid copying the store onbeginand avoid scanning keys oncount.- Up to
Key idea: one live store, one shared undo log, and bookmark indices
Instead of saving snapshots of the whole store, keep one live dictionary
datathat always holds the current visible state. That makesget(key)a single dictionary lookup regardless of transaction depth.Whenever a write happens inside an open transaction, we record how to reverse that single write by appending
(key, old_value)to a shared listundo_log. Because real values in this problem are nonempty strings,old_value = Noneunambiguously serves as a sentinel meaning "this key did not exist before the write."To track nested transactions without creating separate dictionaries per level, we keep a stack
frame_startsstoring the length ofundo_logwhen each open transaction began:Start: data = {"host": "alpha"} 1) begin -> frame_starts = [0], undo_log = [] 2) set "host" = "beta" -> frame_starts = [0], undo_log = [("host", "alpha")] 3) begin -> frame_starts = [0, 1], undo_log = [("host", "alpha")] 4) set "replica" = "beta" -> frame_starts = [0, 1], undo_log = [("host", "alpha"), ("replica", None)] ^depth 1 ^depth 2 If we COMMIT depth 2: pop 1 from frame_starts -> frame_starts = [0] undo_log is untouched: [("host", "alpha"), ("replica", None)] now belongs to depth 1! If depth 1 later ROLLS BACK: pop 0 from frame_starts -> pop ("replica", None), then pop ("host", "alpha") both depth 2 and depth 1 writes are undone!Every undo entry is appended once and popped or cleared once, so even
100,000nestedbeginandcommitcalls takeO(1)time each.Keep `value_counts` synchronized through one write helper
To answer
count(value)inO(1)time, we maintain a dictionaryvalue_countsmapping each value to how many visible keys currently hold it.Whenever a key changes from
old_valuetonew_value: - Ifold_valuewas present, decrementvalue_counts[old_value](and delete the key fromvalue_countsif it reaches0so unused values do not linger in memory). - Ifnew_valueis notNone, storedata[key] = new_valueand incrementvalue_counts[new_value].By placing this logic in one helper
_apply_writeand routing all mutations through it (set,unset, androllback),value_countscan never drift out of sync withdata. For user writes (_record_and_write), we also checkif old_value == new_value: returnfirst so no-op calls (unseton a missing key, orsetto the exact same value) do not add useless undo entries.from typing import Dict, List, Optional, Tuple class TransactionalStore: def __init__(self) -> None: # data: live visible store mapping key -> current value, e.g. {"a": "y"}. self.data: Dict[str, str] = {} # value_counts: frequency map of value -> visible key count, e.g. {"y": 2}. self.value_counts: Dict[str, int] = {} # undo_log: stack of (key, previous_value) tuples recorded inside open transactions. # A previous_value of None is a sentinel meaning the key did not exist before the write. self.undo_log: List[Tuple[str, Optional[str]]] = [] # frame_starts: stack of undo_log lengths; frame_starts[d] marks where depth d+1 began. self.frame_starts: List[int] = [] def _apply_write(self, key: str, new_value: Optional[str]) -> None: """Mutate visible state (None deletes key) and keep value_counts in sync.""" old_value = self.data.get(key) # Phase 1: remove the key's contribution to its previous value's count. if old_value is not None: self.value_counts[old_value] -= 1 if self.value_counts[old_value] == 0: del self.value_counts[old_value] # Phase 2: delete the key or store new_value and increment its count. if new_value is None: self.data.pop(key, None) else: self.data[key] = new_value self.value_counts[new_value] = self.value_counts.get(new_value, 0) + 1 def _record_and_write(self, key: str, new_value: Optional[str]) -> None: """Apply a user write, logging the prior state first if a transaction is open.""" old_value = self.data.get(key) # Skip no-ops (unsetting an absent key, or setting a key to its current value) # so we do not pollute undo_log or churn value_counts. if old_value == new_value: return if self.frame_starts: self.undo_log.append((key, old_value)) self._apply_write(key, new_value)Implement store operations and transaction boundaries
Two subtle details are critical in
rollbackandcommit:- Undo newest-first in
rollback: Suppose"k"starts at"v0", and inside one transaction we set"k"to"v1"and then"v2". The log records("k", "v0")followed by("k", "v1"). Popping from the back restores"v1"first and"v0"last, landing on the exact pre-transaction value"v0". - Call
_apply_write, not_record_and_write, duringrollback: If an outer transaction is still open, calling_record_and_writewhile undoing would append a fresh undo record for every record we pop, causing an infinite loop! - Clear
undo_logon the outermostcommit: Onceframe_startsbecomes empty, no open transaction remains, so the logged history can never be rolled back and we free it immediately.
def set(self, key: str, value: str) -> None: self._record_and_write(key, value) def get(self, key: str) -> Optional[str]: return self.data.get(key) def unset(self, key: str) -> None: self._record_and_write(key, None) def count(self, value: str) -> int: return self.value_counts.get(value, 0) def begin(self) -> None: # Bookmark the current end of undo_log so rollback knows where to stop. self.frame_starts.append(len(self.undo_log)) def rollback(self) -> bool: if not self.frame_starts: return False stop_index = self.frame_starts.pop() # Replay undo entries from newest to oldest so a key modified multiple times # in this transaction ends at the value it had right before begin(). while len(self.undo_log) > stop_index: key, previous_value = self.undo_log.pop() # Call _apply_write directly so undoing does not append new undo records. self._apply_write(key, previous_value) return True def commit(self) -> bool: if not self.frame_starts: return False # Dropping the innermost bookmark hands this transaction's undo entries # to its parent in O(1) time without copying any dictionary entries. self.frame_starts.pop() if not self.frame_starts: # Outermost commit: changes are now permanent and cannot be rolled back. self.undo_log.clear() return True- Undo newest-first in
Trace Example 1 step by step
Let's trace every state transition on Example 1:
Operation undo_log frame_starts data value_counts Return ------------------------------------------------------------------------------------------------------------------------------------------------------------ ["set","host","alpha"] [] [] {"host":"alpha"} {"alpha": 1} None ["begin"] [] [0] {"host":"alpha"} {"alpha": 1} None ["set","host","beta"] [("host","alpha")] [0] {"host":"beta"} {"beta": 1} None ["set","replica","beta"] [("host","alpha"), ("replica",None)] [0] {"host":"beta","replica":"beta"} {"beta": 2} None ["count","beta"] [("host","alpha"), ("replica",None)] [0] {"host":"beta","replica":"beta"} {"beta": 2} 2 ["begin"] [("host","alpha"), ("replica",None)] [0, 2] {"host":"beta","replica":"beta"} {"beta": 2} None ["unset","host"] [("host","alpha"), ("replica",None), ("host","beta")] [0, 2] {"replica":"beta"} {"beta": 1} None ["count","beta"] [("host","alpha"), ("replica",None), ("host","beta")] [0, 2] {"replica":"beta"} {"beta": 1} 1 ["rollback"] [("host","alpha"), ("replica",None)] [0] {"host":"beta","replica":"beta"} {"beta": 2} True ["get","host"] [("host","alpha"), ("replica",None)] [0] {"host":"beta","replica":"beta"} {"beta": 2} "beta" ["commit"] [] [] {"host":"beta","replica":"beta"} {"beta": 2} True ["count","beta"] [] [] {"host":"beta","replica":"beta"} {"beta": 2} 2At
["rollback"],stop_index = 2, so only("host", "beta")is popped and restored, leaving the outer transaction's two undo entries intact. At["commit"],frame_startsbecomes empty, soundo_logis cleared and both"beta"bindings become permanent.Complete solution
Finally,
run_transactional_storecreates aTransactionalStore, dispatches each operation by name, and collects the return values in order.from typing import Any, Dict, List, Optional, Set, Tuple class TransactionalStore: def __init__(self) -> None: # data: live visible store mapping key -> current value, e.g. {"a": "y"}. self.data: Dict[str, str] = {} # value_counts: frequency map of value -> visible key count, e.g. {"y": 2}. self.value_counts: Dict[str, int] = {} # undo_log: stack of (key, previous_value) tuples recorded inside open transactions. # A previous_value of None is a sentinel meaning the key did not exist before the write. self.undo_log: List[Tuple[str, Optional[str]]] = [] # frame_starts: stack of undo_log lengths; frame_starts[d] marks where depth d+1 began. self.frame_starts: List[int] = [] def _apply_write(self, key: str, new_value: Optional[str]) -> None: """Mutate visible state (None deletes key) and keep value_counts in sync.""" old_value = self.data.get(key) # Phase 1: remove the key's contribution to its previous value's count. if old_value is not None: self.value_counts[old_value] -= 1 if self.value_counts[old_value] == 0: del self.value_counts[old_value] # Phase 2: delete the key or store new_value and increment its count. if new_value is None: self.data.pop(key, None) else: self.data[key] = new_value self.value_counts[new_value] = self.value_counts.get(new_value, 0) + 1 def _record_and_write(self, key: str, new_value: Optional[str]) -> None: """Apply a user write, logging the prior state first if a transaction is open.""" old_value = self.data.get(key) # Skip no-ops (unsetting an absent key, or setting a key to its current value) # so we do not pollute undo_log or churn value_counts. if old_value == new_value: return if self.frame_starts: self.undo_log.append((key, old_value)) self._apply_write(key, new_value) def set(self, key: str, value: str) -> None: self._record_and_write(key, value) def get(self, key: str) -> Optional[str]: return self.data.get(key) def unset(self, key: str) -> None: self._record_and_write(key, None) def count(self, value: str) -> int: return self.value_counts.get(value, 0) def begin(self) -> None: # Bookmark the current end of undo_log so rollback knows where to stop. self.frame_starts.append(len(self.undo_log)) def rollback(self) -> bool: if not self.frame_starts: return False stop_index = self.frame_starts.pop() # Replay undo entries from newest to oldest so a key modified multiple times # in this transaction ends at the value it had right before begin(). while len(self.undo_log) > stop_index: key, previous_value = self.undo_log.pop() # Call _apply_write directly so undoing does not append new undo records. self._apply_write(key, previous_value) return True def commit(self) -> bool: if not self.frame_starts: return False # Dropping the innermost bookmark hands this transaction's undo entries # to its parent in O(1) time without copying any dictionary entries. self.frame_starts.pop() if not self.frame_starts: # Outermost commit: changes are now permanent and cannot be rolled back. self.undo_log.clear() return True def run_transactional_store(operations: List[List[str]]) -> List[object]: store = TransactionalStore() results: List[object] = [] # Dispatch each command and record one return value per operation. for op in operations: op_type = op[0] if op_type == "set": store.set(op[1], op[2]) results.append(None) elif op_type == "get": results.append(store.get(op[1])) elif op_type == "unset": store.unset(op[1]) results.append(None) elif op_type == "count": results.append(store.count(op[1])) elif op_type == "begin": store.begin() results.append(None) elif op_type == "rollback": results.append(store.rollback()) elif op_type == "commit": results.append(store.commit()) else: raise ValueError(f"unknown operation: {op_type}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine editing a whiteboard while keeping a single undo log (an append-only list that records what a key's old value was right before you changed it) and placing a numbered bookmark on that list every time you start a nested transaction (begin). Because the whiteboard itself (data) always shows the latest state— alongside a live tally sheet (value_counts) of how many keys hold each value—get and count are instant single-dictionary lookups at any nesting depth.
The naive approach copies the entire dictionary at every begin and scans all keys for every count. With 50,000 keys and 50,000 nested begin or count calls, copying and scanning perform billions of steps and time out. Even keeping one small undo dictionary per transaction fails if an inner commit naively copies its entries into its parent at every level across 50,000 nested commits.
With one shared undo_log and a stack of bookmark positions frame_starts, begin and inner commit touch only a single integer bookmark (tracing Example 2):
1. set("mode", "safe") -> data={"mode": "safe"}, undo_log=[], frame_starts=[]
2. begin() (outer) -> bookmark index 0: frame_starts=[0]
3. begin() (inner) -> bookmark index 0: frame_starts=[0, 0]
4. set("mode", "fast") -> log old value: undo_log=[("mode", "safe")], data={"mode": "fast"}
5. commit() (inner) -> pop inner bookmark: frame_starts=[0]; undo_log stays intact!
6. rollback() (outer) -> pop bookmark 0, pop ("mode", "safe") -> data={"mode": "safe"} again!
7. rollback() (none) -> frame_starts is empty -> returns False.
Complexity
Let n be the total number of operations.
- Time: Amortized
O(1)expected time per operation, andO(n)expected time overall (amortizedO(1)means an occasional operation likerollbackmay do multiple steps, but averaged across the whole sequence each operation pays only a constant cost).get,count,set,unset,begin, and nestedcommiteach perform a constant number of dictionary lookups/updates (O(1)expected) and list pushes/pops (O(1)). Althoughrollbackand the outermostcommitprocess multiple undo entries, every entry inundo_logis appended at most once by a write and removed at most once by arollbackor finalclear(), so total log work across the entire run never exceedsn. - Space:
O(n)worst-case auxiliary space.dataandvalue_countsstore at most one entry per active key or value,undo_logstores at most one tuple per write inside open transactions, andframe_startsstores at most one integer per openbegin.
Edge cases
rollbackorcommitwhen no transaction is open:frame_startsis empty, so both immediately returnFalsewithout modifyingdataorvalue_counts.unsetof a missing key (orsetto the identical value):old_value == new_valuetriggers an early return, so nothing changes and no redundant record is pushed toundo_log.- Distinguishing an absent key from a present key:
Noneacts as a sentinel value (a special marker distinct from all valid data values) meaning "key was absent," which is safe because keys and values are guaranteed to be nonempty strings. Rolling back the creation of a brand-new key seesprevious_value = Noneand deletes the key rather than storingNone. - Multiple writes to the same key inside one transaction: Each real change logs a tuple, and
rollbackpops from newest to oldest, so the earliest pre-transaction value is applied last and wins. - Inner
commitfollowed by outerrollback: Innercommitonly pops its bookmark fromframe_starts, leaving its undo tuples above the parent's bookmark so the parent'srollbackundoes both. - Extreme nesting (
100,000levels): Eachbeginappends a single integer toframe_starts, using minimal memory andO(1)time.
Common mistakes
- Copying
dataon everybegin: Easy to write, but costsO(keys)perbeginand times out on deep transaction chains. - Making an inner
commitpermanent immediately: Clearingundo_logon everycommitprevents an enclosing parent transaction from rolling back the child's writes. - Replaying undo entries oldest-first instead of newest-first: If
"k"changed"v0" -> "v1" -> "v2", applying("k", "v0")before("k", "v1")leaves"k"stuck at"v1"instead of"v0". - Updating
value_countsinset/unsetbut forgettingrollback: Any separate rollback code path risks count drift; routing every state change through_apply_writemakes drift impossible. - Calling
_record_and_writeinsiderollback: When an outer transaction is still open, logging during an undo appends one new record for every record popped and loops forever. - Naively copying per-frame undo maps on
commit: Copying a child dictionary of50,000keys up through50,000parent commits takes2.5 * 10^9steps.
Alternative approaches
- Per-transaction map of first-seen old values with small-to-large merging: Each frame stores a dict mapping
key -> original_value_before_this_frame, recording only the first write to each key in that frame. On innercommit, entries merge into the parent without overwriting keys the parent already recorded. To avoidO(n^2)repeated copies, always merge the smaller dict into the larger dict (swapping when the child is larger), givingO(n log n)total time and bounding memory by unique(frame, key)pairs even if one key is overwritten millions of times. - Stacked overlay maps with tombstones: Each
beginpushes an empty write-buffer dict, and deletes store a tombstone marker.beginandrollbackareO(1), butgetmay have to walk all100,000layers unless combined with extra index bookkeeping, andcommitstill has to merge layers.
Follow-up questions
- How would you redesign the store to support concurrent readers and writers via snapshot isolation (MVCC)? Mutating
datain place with an undo log only works for a single thread at a time. Under multi-version concurrency control (MVCC)—a concurrency scheme where writes append new timestamped versions of a value instead of overwriting it in place—each transaction gets astart_ts, reads the latest version committed at or beforestart_ts, and stages its own writes privately. Oncommit, it checks whether another transaction committed a conflicting write afterstart_tsand, if not, publishes its buffered writes under a new commit timestamp; fastcount(value)then requires maintaining versioned count deltas or per-snapshot summaries. - If each transaction kept its own per-key undo map instead of a shared log, how would you merge an inner commit into its parent efficiently without losing earlier values? With our flat
undo_log, no merge loop is needed at all: dropping the child'sframe_startsbookmark leaves the child's newer undo tuples after the parent's older undo tuples, so a later parentrollbackpops newest-first and finishes on the parent's original state. If instead each transaction stores afirst_old_valuedictionary, the rule oncommitis "keep the parent's entry whenever a key exists in both," and swap-plus-insert when the child map is bigger so each entry moves at mostlog2(n)times. - How would you add durability so committed state survives a process crash? Use a write-ahead log (WAL)—an append-only disk file where committed changes are flushed before acknowledging success—that records only committed mutations. Uncommitted inner transactions stay purely in RAM; standalone writes outside any transaction and the net key changes of an outermost
commitare written as checksummed log records andfsynced before returningTrue. After a crash, recovery loads the latest periodic snapshot ofdata, replays valid WAL records after that snapshot, ignores any half-written trailing record whose checksum fails, and rebuildsvalue_countsin one pass.
Follow-up questions
- How would you redesign the store to support concurrent readers and writers via snapshot isolation (MVCC)?
- If each transaction kept its own per-key undo map instead of a shared log, how would you merge an inner commit into its parent efficiently without losing earlier values?
- How would you add durability so committed state survives a process crash?
Similar questions
- Minimum Crew Size for Scheduled Jobs
- Minimum-Worker Interval Task Scheduling
- Versioned Key-Value Store with Point-in-Time Reads
- Transactional In-Memory Key-Value Store
- Grid Propagation Timer and Nested Key-Value Store
- Offset and Cursor Transaction Pagination
More Lyft interview questions
- Distributed Web Crawler Across Heterogeneous Worker Nodes Medium
- Stateful Batch Reader for Paginated APIs Medium
- Shortest Substring Covering Character Multiplicities Medium Pro
- Minimum-Worker Interval Task Scheduling Medium Pro
- Chunked Word Reader Over a Variable-Size Page API Medium Pro
- Poisson Supply-and-Demand Coverage and Fill Rate Medium Pro
- Leading Through Ambiguity and Compensation Negotiation Medium Pro
- Multi-Device Direct Chat and Real-Time Sync Architecture Medium Pro
- Key-Value Store with Shared Monotonic Snapshot Versions Medium Pro
- Direct Messaging Service Architecture Medium Pro