Build a Nested-Transaction Key–Value Store from Scratch
Data Structure DesignModel answerLast updated
Design and implement an in-memory key–value store that supports arbitrarily nested BEGIN/COMMIT/ROLLBACK transactions with correct shadowing and O(1) reads.
Nested-Transaction Key–Value Store
You are building a lightweight in-memory database that supports transactional reads and writes. It must handle the following five commands:
| Command | Behavior |
|---|---|
SET key value | Store value under key, overwriting any previous value. |
GET key | Print the value currently stored at key, or NULL if no such key exists. |
BEGIN | Open a new transaction block. |
ROLLBACK | Undo every change made inside the most recently opened transaction that has not yet been committed. Print NO TRANSACTION if there is no open transaction. |
COMMIT | Make all pending changes permanent and close every open transaction. Print NO TRANSACTION if there is no open transaction. |
Requirements
- Transactions may be nested to any depth. A
BEGINinside an existing transaction opens an inner transaction. - Within a transaction, reading a key always returns the most recently written value — whether it was set before or during the transaction, or by an enclosing transaction.
- Rolling back an inner transaction restores the value visible at the time that inner
BEGINexecuted, not the original pre-database value. - Rolling back an outer transaction afterward restores the state that existed before that outer
BEGIN. - A key that was created for the first time inside a transaction must be fully removed (not set to
nullor an empty string) when that transaction is rolled back. COMMITwith nested open transactions commits all of them at once.
What to produce
- Define the core data structures you would use.
- Walk through the algorithm for each of the five commands.
- State the time and space complexity of each operation.
- Compare your chosen approach to at least one alternative design, noting trade-offs.
- Call out the edge cases that must be handled correctly.
- Provide working code and a short example trace that demonstrates nested rollback behavior.
Example interaction
BEGIN
SET x 10
BEGIN
SET x 20
GET x → 20
ROLLBACK
GET x → 10
COMMIT
GET x → 10
Hints
Hint 1
Think about what information you need to save at the moment of each SET so that a future ROLLBACK can undo exactly that write — and nothing more. You don't need to record every intermediate state, just the right one.
Hint 2
A stack pairs naturally with nested transactions: one entry per open BEGIN. What should each stack entry store — the full snapshot of the database, the full diff, or something smaller?
Hint 3
A key that never existed before a transaction is a special case. How do you distinguish 'the key was absent' from 'the key was set to some value'? You may need a sentinel.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: live map + undo-log stack
Core data structures
Two objects are all you need:
data— a single dictionary that always reflects the current visible state of the store.undo_stack— a list of dictionaries, one per open transaction. Each entry maps a key to the value that key held before the enclosing transaction first touched it. A specialABSENTsentinel marks keys that did not exist at all when the transaction started.
Because data is always up to date, every GET is a single dictionary lookup regardless of nesting depth.
Algorithm for each command
SET key value
If there is an open transaction and the current top log does not yet have an entry for key, record the key's current value (or ABSENT) in the top log. Then write data[key] = value. Recording only the first write per key per transaction is intentional: no matter how many times a key is reassigned, rollback only needs to restore the value it had at BEGIN.
GET key
Return data.get(key), printing NULL when absent. Because every write lands directly in data, no scope-walking is needed.
BEGIN
Push an empty dictionary onto undo_stack.
ROLLBACK
Pop the top log. Iterate its entries and restore each key: if the saved value is ABSENT, delete the key from data; otherwise, write the old value back. If the stack was already empty, print NO TRANSACTION.
COMMIT
If the stack is empty, print NO TRANSACTION. Otherwise, discard the entire stack. data already holds the final values, so there is nothing to merge.
Why nested rollback works correctly
When an inner BEGIN fires, the top log is empty. The first write to any key in the inner transaction logs the value that key had after the outer transaction may have already changed it. Rolling back the inner transaction restores that outer-transaction value. If the outer transaction is then rolled back, it restores the value from before both transactions started. The invariant holds at every depth.
Complexity
| Operation | Time | Space |
|---|---|---|
| SET | O(1) | O(1) per first write |
| GET | O(1) | — |
| BEGIN | O(1) | O(1) |
| ROLLBACK | O(m) where m = distinct keys touched | — |
| COMMIT | O(1) | — |
Total space is O(n + Σ m_t), where n is the number of live keys and m_t is the number of distinct keys each open transaction has touched.
Comparison with the layered-scope approach
An alternative is to give each BEGIN its own child map with a pointer to its parent. Writes go into the child; reads walk the chain from child to root.
| Undo-log stack (this solution) | Layered scopes | |
|---|---|---|
| GET | O(1) | O(depth) |
| SET | O(1) | O(1) |
| ROLLBACK | O(m) | O(1) — just drop the child |
| COMMIT | O(1) | O(total entries) — must flatten all layers |
| Deletions | handled via ABSENT sentinel | requires tombstones in each layer |
The undo-log stack wins when reads outnumber rollbacks, which is almost always true. It is also fully iterative, so there is no recursion-depth concern. The layered approach can be attractive in narrow scenarios where rollbacks are extremely frequent and nesting stays shallow, but the flush cost at COMMIT tends to offset the cheap rollback benefit. Real database engines use undo logs for the same reason.
Edge cases to handle
- ROLLBACK or COMMIT with no open transaction — print
NO TRANSACTION, leavedataunchanged. - GET on a missing key — print
NULL, not an exception. - A key created inside a transaction that is then rolled back — it must be deleted entirely. This is why
ABSENTmust be a distinct sentinel rather thanNone, sinceNoneis a valid value in many implementations. - Multiple SETs of the same key within one transaction — only the first write is logged; later writes update
datawithout touching the log. - An empty transaction (BEGIN → immediate ROLLBACK) — safe; the empty log is popped and nothing changes.
- COMMIT with nested open transactions — commits all layers at once by clearing the entire stack.
- SET outside any transaction — writes directly to
datawith no logging, which is correct.
Python implementation
_ABSENT = object() # sentinel: key did not exist when the transaction began
class KVStore:
def __init__(self):
self._data = {}
self._undo_stack = [] # list[dict[str, any]]
# ------------------------------------------------------------------ #
# Core commands #
# ------------------------------------------------------------------ #
def set(self, key: str, value: str) -> None:
if self._undo_stack:
log = self._undo_stack[-1]
if key not in log: # log only the first write
log[key] = self._data.get(key, _ABSENT)
self._data[key] = value
def get(self, key: str) -> str:
val = self._data.get(key)
return "NULL" if val is None else val # None == absent
def begin(self) -> None:
self._undo_stack.append({})
def rollback(self) -> str | None:
if not self._undo_stack:
return "NO TRANSACTION"
log = self._undo_stack.pop()
for key, old in log.items():
if old is _ABSENT:
self._data.pop(key, None) # key must disappear
else:
self._data[key] = old
return None
def commit(self) -> str | None:
if not self._undo_stack:
return "NO TRANSACTION"
self._undo_stack.clear() # data is already final
return None
# ------------------------------------------------------------------ #
# Command dispatcher #
# ------------------------------------------------------------------ #
def execute(self, line: str) -> str | None:
parts = line.split()
if not parts:
return None
cmd = parts[0].upper()
if cmd == "SET" and len(parts) == 3:
self.set(parts[1], parts[2])
return None
if cmd == "GET" and len(parts) == 2:
return self.get(parts[1])
if cmd == "BEGIN":
self.begin()
return None
if cmd == "ROLLBACK":
return self.rollback()
if cmd == "COMMIT":
return self.commit()
return "UNKNOWN COMMAND"
# ---------------------------------------------------------------------- #
# Example trace #
# ---------------------------------------------------------------------- #
if __name__ == "__main__":
commands = [
"BEGIN",
"SET x 10",
"BEGIN",
"SET x 20",
"GET x", # → 20
"ROLLBACK",
"GET x", # → 10
"COMMIT",
"GET x", # → 10
"ROLLBACK", # → NO TRANSACTION
]
store = KVStore()
for cmd in commands:
result = store.execute(cmd)
if result is not None:
print(f"{cmd:20s} → {result}")
else:
print(cmd)
Expected output for the trace:
BEGIN
SET x 10
BEGIN
SET x 20
GET x → 20
ROLLBACK
GET x → 10
COMMIT
GET x → 10
ROLLBACK → NO TRANSACTION
A common mistake is to log every write rather than only the first one per transaction. This wastes space and can cause incorrect restores when the same key is written several times inside one transaction. Another common mistake is treating a rolled-back key as having value None rather than deleting it outright, which causes GET to return NULL for the wrong reason and breaks the invariant when the key actually never existed.