Layered Scopes for a Key-Value Store with Savepoints
Data Structure DesignModel answerLast updated
Build an in-memory key-value store whose writes can be grouped into nested, revertable scopes that either merge into the enclosing scope or are thrown away.
Nested Scopes in a Key-Value Store
Implement a small in-memory key-value store in which writes can be grouped into nested transactions. Keys are strings and values are integers.
The store exposes these operations:
set(key, value): Records a value forkey. If a transaction is open, the write belongs to the innermost open transaction. Otherwise it goes straight into the base store.get(key): Returns the value currently visible forkey. The innermost transaction that wrote the key takes precedence, then the enclosing ones, and finally the base store.begin(): Opens a new transaction nested inside the current one (or directly on the base store if none is open). Calls tobegin()can be repeated to any depth.rollback(): Throws away every write made in the innermost open transaction and closes it. The state returns to what it was just before the matchingbegin(). If no transaction is open, signal an error.commit(): Closes the innermost open transaction and folds its writes into the enclosing scope. That scope is the parent transaction if there is one, otherwise the base store. If no transaction is open, signal an error.
Example
db = TransactionalDB()
db.set("a", 10)
db.begin()
db.set("a", 20)
db.commit()
print(db.get("a")) # 20
db.begin()
db.set("a", 30)
db.rollback()
print(db.get("a")) # 20
Required interface
class TransactionalDB:
def __init__(self): ...
def set(self, key, value): ...
def get(self, key): ...
def begin(self): ...
def rollback(self): ...
def commit(self): ...
What to discuss
- Describe your data structure and why it gives the right visibility rules.
- State what
getreturns for an unknown key and how you report an error fromrollback/commitwith no open transaction. - Give the time complexity of each operation.
- Explain what happens when an inner transaction commits and then its parent rolls back.
- Follow-up: how would you make
getO(1) regardless of depth, and how would you add adelete(key)operation?
Hints
Hint 1
Think of each open transaction as a scope that only remembers the writes made while it was innermost. What container holds a sequence of scopes where you only touch the most recent one?
Hint 2
A read should check the innermost scope first and move outward until it finds the key. Test membership with `in`, not truthiness, so a stored value of 0 is not mistaken for a missing key.
Hint 3
Rollback just discards the innermost scope. Commit discards it too, but only after copying its entries over the matching entries in the scope beneath it. Never remove the base scope.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the store as a stack of dictionaries, one per scope:
stack[0]is the base store and is never removed.begin()pushes an empty dictionary that records only the writes made at that level.setalways writes into the top dictionary.getscans from the top dictionary down to the base and returns the first hit.rollback()pops the top dictionary, discarding its writes.commit()pops the top dictionary and merges it into the one below withupdate, so child values override parent values for the same keys.
This is the same idea as lexical scoping in an interpreter: inner scopes shadow outer ones, and leaving a scope either drops it or folds it outward.
Why it is correct
The invariant is: the visible value of a key is the value in the highest layer that contains it.
- set puts the value in the highest layer, so it is visible immediately. Outer layers are untouched, so their older values survive a rollback.
- rollback removes exactly the writes of this level. Since outer layers were never modified, the visible state equals the state before the matching
begin(). - commit leaves the visible state unchanged at that instant. What changes is ownership: the writes now belong to the parent. If the parent later rolls back, they vanish with it. This is the right nested semantics, because an inner commit is only provisional until the outermost transaction commits.
Contract decisions to state up front
geton a key that exists nowhere returnsNone.rollback/commitwith no open transaction raises an exception (a customNoTransactionError). Some interviewers prefer a returned string such as"NO TRANSACTION", so confirm.
Complexity
Let d be the nesting depth and k the number of keys written in the top layer.
| Operation | Time |
|---|---|
set | O(1) average |
get | O(d) worst case |
begin | O(1) |
rollback | O(1) |
commit | O(k) |
Space is proportional to the total number of writes across all live layers. A key written at several levels is stored once per level until those levels are merged or dropped.
Code
class NoTransactionError(Exception):
pass
class TransactionalDB:
def __init__(self):
self._stack = [{}] # index 0 is the base store
def set(self, key, value):
self._stack[-1][key] = value
def get(self, key):
for layer in reversed(self._stack):
if key in layer: # `in`, so a stored 0 still counts
return layer[key]
return None
def begin(self):
self._stack.append({})
def rollback(self):
if len(self._stack) == 1:
raise NoTransactionError("no active transaction")
self._stack.pop()
def commit(self):
if len(self._stack) == 1:
raise NoTransactionError("no active transaction")
top = self._stack.pop()
self._stack[-1].update(top)
Edge cases
- Value 0: valid data. Check membership, not truthiness.
- No open transaction:
rollback/commitmust raise and must never pop the base layer. - Repeated sets in one level: the last write wins, since the layer is a dictionary.
- Commit then parent rollback: the child's writes disappear, because they were merged into the parent layer and not the base.
- Key written only in a rolled-back transaction:
getreturnsNoneafterward. - Many empty
begin()calls: cheap, each adds one empty dictionary.
Follow-ups
O(1) reads. Keep a single current dictionary holding the visible state, plus an undo log per level.
- On the first write to a key at a level, record the key's previous value (use a sentinel for "absent") in that level's log, then write to
current. rollbackreplays the top log to restorecurrent, costing O(keys changed at that level).commitmerges the child's log into the parent's. For each key, keep the parent's entry if it already has one, since the parent must restore its own older value. Otherwise take the child's entry.
This trades simpler writes for faster reads, which suits read-heavy workloads. A per-key stack of (level, value) pairs is another route to O(1) reads.
Delete. Removing the key from the top dictionary is not enough, because get would fall through to an outer layer and return a stale value. Write a tombstone sentinel instead.
getreturnsNonewhen the first layer containing the key holds a tombstone.commitcopies tombstones into the parent like any other value. When one reaches the base layer, remove the key physically.rollbackneeds no change.
Concurrency. Decide whether transactions are per session or global. Real databases scope them per session, so each client would own its own stack on top of a shared base, and commit to the base would need a lock or optimistic version check. For a single shared stack, a coarse mutex around every operation is the simple correct answer.
Common mistakes
- Copying the entire base store on every
begin(), which makes it O(n) per call. - Using
if layer.get(key)and treating a stored 0 as missing. - Letting
commitwrite to the base store even when a parent transaction exists. - Allowing the base layer to be popped.