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 outputs None.
  • "set" with [key, value]: stores key -> value inside the innermost active transaction if one exists, or directly in the permanent base store otherwise; outputs None.
  • "get" with [key]: resolves key by checking the innermost active transaction first, then each enclosing transaction outward, and finally the permanent base store. Returns the latest visible integer value, or -1 if key was never stored or its newest visible mutation is a deletion.
  • "delete" with [key]: marks key as removed in the active scope and outputs None. Inside an open transaction, a deletion hides any value from enclosing transactions or the base store (so get(key) returns -1), taking effect further down only when committed. Deleting a key that is already absent or hidden leaves get(key) returning -1.
  • "begin" with []: opens a new innermost transaction (nested inside any currently active transaction) and outputs None.
  • "commit" with []: returns False if 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 returns True.
  • "rollback" with []: returns False if no transaction is active. Otherwise, discards every write and deletion made in the innermost active transaction, closes it, and returns True.

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:
    1. set("x", 10) writes 10 to the permanent store; get("x") returns 10.
    2. begin() opens outer transaction T1, where set("x", 25) and set("y", 40) run; get("x") returns 25.
    3. begin() opens inner transaction T2, where delete("x") hides "x" so get("x") returns -1.
    4. rollback() aborts T2 (True), restoring T1's view so get("x") returns 25.
    5. commit() merges T1 into the permanent store (True), making "x": 25 and "y": 40 permanent.
    6. The final commit() has no open transaction to close and returns False.

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 at 7 in the permanent store. Inner transaction T2 deletes "k" and commits into outer transaction T1, so get("k") inside T1 still returns -1. Rolling back T1 discards that merged deletion and exposes 7 from the permanent store again.

Constraints

  • 1 <= len(operations) == len(arguments) <= 10^5 (the first operation is "VersionedKVStore")
  • Every key consists of 1 to 20 lowercase English letters ('a'–'z')
  • 0 <= value <= 10^9
  • Active transaction nesting depth never exceeds 10^3
  • Target efficiency: O(1) average time for set, delete, and begin; O(d) worst-case time for get at nesting depth d; and O(c) time for commit and rollback, where c is the number of distinct keys modified in the innermost transaction (independent of total store size)

Step-by-step walkthrough

  1. 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, otherwise self.store).
    • Lookups (get) search downward from layers[-1] through layers[0] and finally self.store, stopping at the first scope that mentions key (or returning -1 if absent or deleted).
    • commit() folds only layers[-1] one step down into its immediate parent transaction (or into self.store when closing the outermost transaction) and returns True (False when layers is empty).
    • rollback() discards only layers[-1] and returns True (False when layers is empty).
  2. Why copying the whole store on `begin()` is too slow

    A straightforward prototype clones the entire dictionary on every begin(): push dict(states[-1]) on begin(), mutate states[-1], overwrite states[-2] on commit(), and pop on rollback().

    That reference model is easy to reason about on tiny inputs, yet when self.store holds 40,000 keys and we run 15,000 one-key transactions, cloning the whole dictionary on each begin() copies 40,000 * 15,000 = 600,000,000 entries! To keep commit and rollback proportional only to modified keys, each transaction layer must store only the keys changed in that layer (its delta).

  3. Key idea: delta dictionaries plus a `DELETED` tombstone

    Suppose self.store contains {"x": 10}, outer transaction T1 sets "x" to 25, and inner transaction T2 calls delete("x"). What must T2's delta dictionary record?

    If delete("x") merely omitted "x" from T2's dictionary ({}), get("x") would fall right through to T1:

    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 setting self.layers[-1][key] = DELETED tells get(key) to stop immediately and return -1, while preserving T1 and self.store untouched in case T2 rolls back.

  4. Implement `set`, `get`, `delete`, and `begin`

    Because 0 is a valid stored integer (0 <= value <= 10^9), get(key) must test if key in layer: and if val is DELETED: rather than truthiness (bool(0) is False in 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({})
    
  5. Implement `commit` and `rollback` across nested layers

    rollback() simply pops self.layers[-1] (returning False first if self.layers is empty).

    commit() pops inner_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() and rollback() touch only inner_changes, costing time proportional to the keys modified in the innermost transaction rather than len(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 True
    
  6. Wire up the driver and trace Example 1

    versioned_kv_store(operations, arguments) instantiates VersionedKVStore and records None for void calls, the integer result for get, and the boolean result for commit and rollback. 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)
    
  7. Complete solution

    Here is the complete VersionedKVStore implementation 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), and begin(): O(1) average time. Each performs one dictionary assignment/pop on self.layers[-1] (or self.store) or appends {} to self.layers.
  • get(key): O(d) worst-case time. We probe key in layer in O(1) average time from innermost to outermost across at most d layers, returning on the first hit or falling back to one O(1) lookup in self.store.
  • commit(): O(c) average time. We pop the innermost delta dictionary of c keys and loop over its c entries once, applying each in O(1) average time to parent_layer or self.store.
  • rollback(): O(1) stack pop (plus O(c) deallocation as Python frees the popped c-entry dictionary), leaving self.store and 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 in self.layers[-1].

Edge cases

  • commit() or rollback() with zero active transactions (self.layers == []): Returns False immediately without altering self.store.
  • Operations outside any transaction: set and delete mutate self.store directly and permanently, unaffected by later rollback() calls.
  • Stored value 0: Because 0 is falsy in Python, testing if key in layer: and if val is DELETED: returns 0 cleanly 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, storing DELETED yields -1 on get and 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 overwrites self.layers[-1]["x"], so the latest state (3) wins.
  • Inner deletion committed into an outer transaction (Example 2): T2's DELETED marker copies into T1 (parent_layer[key] = DELETED), continuing to hide self.store[key] while remaining undoable if T1 rolls back.

Common mistakes

  • Calling self.layers[-1].pop(key, None) during delete(key) inside a transaction: Removing key from the inner delta lets get(key) fall through to enclosing layers or self.store and revive stale data.
  • Popping DELETED keys from parent_layer on an inner commit(): In Example 2 (store = {"k": 7}, T1 = {}, T2 = {"k": DELETED}), doing parent_layer.pop("k", None) leaves T1 empty and exposes 7 prematurely! Convert tombstones to .pop() calls only when committing into self.store.
  • Storing DELETED directly inside self.store on outermost commit: That leaks tombstones for deleted keys and makes self.store.get(key, -1) return DELETED instead 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 every set and delete straight to one current dictionary (O(1) get!), while each open transaction records an undo log mapping each key to its prior value (or a MISSING marker) the first time that layer touches it (detailed in the first follow-up).
  • Full dictionary clones on begin(): Push dict(states[-1]) on every begin(). Gives O(1) get, set, delete, commit, and rollback, but suffers O(S) time and memory per begin().

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.current so get(key) is always self.current.get(key, -1) in O(1) average time! Before modifying key in set or delete, if self.undo_logs is non-empty and key not in self.undo_logs[-1], save the pre-image self.undo_logs[-1][key] = self.current.get(key, MISSING). On rollback(), pop self.undo_logs[-1] and restore each saved value (or .pop(key) if MISSING) in O(c) time; on commit(), pop child_log and copy (key, old_val) into parent_log only when key not in parent_log (preserving the parent's older pre-image), or simply drop child_log at 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,000 child entries upward into 999 empty parent dicts performs 50,000 * 999 writes. Eliminate that bottleneck with small-to-large merging: whenever len(inner_changes) > len(parent_layer), copy only entries from parent_layer whose keys are absent in inner_changes into inner_changes, then set self.layers[-1] = inner_changes. Each entry moves only when the merged map at least doubles in size, bounding total merge work across N writes by O(N log N).
  • How would you adapt this design so multiple client threads can execute transactions concurrently? Give each client session its own private layers stack layered above a shared committed store whose 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, lock store, verify that none of its read versions changed (aborting on conflict), apply its delta, and bump version numbers on written keys.

Follow-up questions

Similar questions

More xAI interview questions

All 53 xAI questions →