Transactional Key-Value Store with Rollback Support
Data Structure DesignModel answerLast updated
Build a key-value store supporting nested transactions with set, get, delete, begin, commit, and rollback operations.
Problem
Implement a key-value store that maintains transactional boundaries. Your store must track modifications across multiple nested scopes and allow callers to either apply or discard changes.
Interface
Provide these operations:
set(key, value): Store a value under the given key within the active scopeget(key): Retrieve the most recent value for a key, searching through nested scopes if necessary; returnNonewhen the key doesn't existdelete(key): Remove a key from visibility in the current scopebegin(): Open a new transaction scopecommit(): Merge the active scope's changes into its parentrollback(): Discard all modifications made in the active scope
Behavior
The store maintains a hierarchy of scopes. When you open a transaction with begin(), subsequent writes affect only that scope. A get() looks in the current scope first, then walks up through parent scopes until it finds the key or exhausts all scopes.
Calling delete(key) makes that key invisible in the current scope and any child scopes, even if a parent scope contains it. After commit(), the current scope's changes overwrite parent values. After rollback(), the scope's changes vanish as if the transaction never happened.
Example Usage
store = TransactionalStore()
store.set("x", 10)
print(store.get("x")) # 10
store.begin()
store.set("x", 20)
store.set("y", 30)
print(store.get("x")) # 20
print(store.get("y")) # 30
store.rollback()
print(store.get("x")) # 10
print(store.get("y")) # None
store.begin()
store.set("x", 40)
store.commit()
print(store.get("x")) # 40
Implementation Notes
- Use a stack-based architecture where each level represents one transaction scope
- Optimize
getto run in time proportional to nesting depth, not total key count - Handle the case where a caller tries to
commitorrollbackwithout an active transaction
Hints
Hint 1
Maintain a stack of dictionaries where each dictionary holds only the changes made in that scope, not a full copy of all data
Hint 2
Use a special marker object to represent deleted keys so you can distinguish deletion from a missing key
Hint 3
When committing, merge the top scope into its parent; when the parent is the base level, convert deletion markers into actual removals
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to represent transaction scopes as a stack of change sets. Each dictionary in the stack records only the modifications made within that scope, avoiding expensive full-state copies.
Stack Structure
- Position 0 holds the base dictionary, which persists across all transactions
- Each
begin()pushes an empty dictionary onto the stack setanddeletealways modify the dictionary at the topgetsearches from top to bottom, returning the first match
Handling Deletion
Deletion requires special care. You cannot remove a key from a parent scope's dictionary because a rollback would permanently lose that entry. Instead, mark the key as deleted by storing a sentinel object in the current scope.
When get encounters this sentinel, it returns None immediately without searching lower scopes. Using object() as the sentinel (rather than None) allows legitimate storage of None values.
Commit Logic
Merging scopes depends on whether the parent is the base:
- Merging into another transaction: Copy all entries from the child, including deletion markers. The marker must survive to hide grandparent values.
- Merging into the base: Convert deletion markers into actual removals using
pop(). The base should never contain markers.
Example Walkthrough
store = TransactionalStore()
store.set("a", 1) # base = {"a": 1}
store.begin() # stack = [{"a": 1}, {}]
store.set("a", 2) # stack = [{"a": 1}, {"a": 2}]
store.get("a") # searches top first, finds 2
store.rollback() # stack = [{"a": 1}]
store.get("a") # finds 1 in base
Complexity Analysis
Let d = transaction depth (stack height), m = keys modified in current scope.
| Operation | Time Complexity | Explanation |
|---|---|---|
set | O(1) | Single hash table write |
delete | O(1) | Write sentinel or remove from base |
begin | O(1) | Push empty dictionary |
get | O(d) | One lookup per scope level |
commit | O(m) | Iterate current scope's entries |
rollback | O(1) | Pop top dictionary |
Space usage is O(total modifications across all active scopes).
Edge Cases
- Commit/rollback with no transaction: Throw an error or return a status message
- Delete then set in same scope: The set overwrites the deletion marker
- Delete in child, commit to another transaction: The marker must persist
- Storing None as a value: Works correctly because the sentinel is distinct
Common Mistakes
- Copying the entire state on
begin: Correct but inefficient at O(n) per transaction - Deleting from parent dictionaries directly: Breaks rollback semantics
- Using
Noneas the deletion marker: Conflicts with legitimateNonevalues - Not handling markers during commit: Causes deleted keys to reappear
- Forgetting to protect the base scope: Must prevent popping the last element
Implementation
class TransactionalStore:
_DELETED = object() # sentinel for deletions
def __init__(self):
self._stack = [{}] # base scope always present
def set(self, key, value):
self._stack[-1][key] = value
def get(self, key):
# search from most recent scope backward
for scope in reversed(self._stack):
if key in scope:
val = scope[key]
return None if val is self._DELETED else val
return None
def delete(self, key):
if len(self._stack) == 1:
# base scope: actually remove the key
self._stack[0].pop(key, None)
else:
# transaction scope: mark as deleted
self._stack[-1][key] = self._DELETED
def begin(self):
self._stack.append({})
def commit(self):
if len(self._stack) == 1:
raise RuntimeError("Cannot commit: no active transaction")
changes = self._stack.pop()
parent = self._stack[-1]
committing_to_base = (len(self._stack) == 1)
for key, value in changes.items():
if value is self._DELETED and committing_to_base:
parent.pop(key, None) # remove from base
else:
parent[key] = value # copy marker or value
def rollback(self):
if len(self._stack) == 1:
raise RuntimeError("Cannot rollback: no active transaction")
self._stack.pop()
Follow-Up Discussions
Optimizing get to O(1): Maintain a single materialized view plus undo logs. Each transaction records prior values before overwriting. get becomes a single lookup; rollback replays the undo log. This trades read speed for rollback cost—beneficial when reads dominate.
Thread safety: Per-user transaction stacks eliminate conflicts. Shared data requires locks or MVCC (multi-version concurrency control), where each transaction reads a consistent snapshot.
Durability: Append committed changes to a write-ahead log before applying them. On crash, replay the log to reconstruct the base state.