Transactional Key-Value Store with Nested Transactions
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an in-memory key-value store that supports basic read and write operations along with arbitrarily nested transactions.
The store starts in a committed base state. Calling `begin` opens a new transaction layer, and later writes are buffered in that layer. Calling `commit` merges the top layer into its enclosing layer, or into the base store if it was the outermost transaction. Calling `rollback` discards the top layer entirely.
Reads always reflect the innermost visible value for a key, searching from the top transaction layer down to the base store. A deletion inside a transaction must hide the key's values in outer layers. If that transaction is rolled back, the deletion disappears with it. If it is committed, the deletion carries into the enclosing layer, or removes the key from the base store when the outermost transaction commits.
Implement the following methods:
- `set(key: str, value: str)`: set `key` to `value` in the current (top) transaction layer, or in the base store if no transaction is active.
- `get(key: str) -> Optional[str]`: return the current visible value for `key`, searching from the innermost transaction layer down to the base store. Returns `None` if the key is unset or deleted.
- `delete(key: str)`: mark `key` as deleted in the current layer. Later `get` calls return `None` until the deletion is rolled back or overwritten.
- `begin()`: start a new nested transaction layer on top of the current state.
- `commit() -> bool`: merge the top transaction layer into its enclosing layer (or the base store). Returns `True` on success, `False` if no transaction is active.
- `rollback() -> bool`: discard the top transaction layer. Returns `True` on success, `False` if no transaction is active.
In the examples, the first input list names the calls and the second gives their arguments. `null` in the output stands for `None`: methods that return nothing produce it, and so does a `get` that finds no visible value.
Example 1:
```text
Input:
["TransactionalKVStore", "set", "get", "begin", "set", "get", "rollback", "get"]
[[], ["a", "1"], ["a"], [], ["a", "2"], ["a"], [], ["a"]]
Output: [null, null, "1", null, null, "2", true, "1"]
kv = TransactionalKVStore() # empty store
kv.set("a", "1") # base: {a=1}
kv.get("a") # returns "1"
kv.begin() # open tx1
kv.set("a", "2") # tx1: {a=2}, base unchanged
kv.get("a") # returns "2" (innermost layer wins)
kv.rollback() # discard tx1
kv.get("a") # returns "1" (base value restored)
```
Example 2:
```text
Input:
["TransactionalKVStore", "set", "begin", "delete", "get", "begin", "set", "get", "commit", "get", "rollback", "get"]
[[], ["x", "10"], [], ["x"], ["x"], [], ["x", "20"], ["x"], [], ["x"], [], ["x"]]
Output: [null, null, null, null, null, null, null, "20", true, "20", true, "10"]
kv = TransactionalKVStore() # empty store
kv.set("x", "10") # base: {x=10}
kv.begin() # open tx1
kv.delete("x") # tx1: {x=deleted}
kv.get("x") # returns None (the deletion hides base)
kv.begin() # open tx2 inside tx1
kv.set("x", "20") # tx2: {x=20}
kv.get("x") # returns "20"
kv.commit() # tx2 merges into tx1: {x=20}, base unchanged
kv.get("x") # returns "20"
kv.rollback() # discard tx1, including what tx2 committed into it
kv.get("x") # returns "10"
```
```hint Deleted versus untouched
A layer has to tell "this key was deleted here" apart from "this layer never touched the key". Decide what a layer stores for a deletion so a read stops there.
```
```hint Where a commit lands
Committing an inner transaction must leave the base store alone. Check what your merge does with deletions when the target is another layer and when it is the base store.
```
### Constraints & Assumptions
- `1 <= key.length, value.length <= 100`
- Keys and values are non-empty strings.
- At most `10⁴` total operations across all method calls.
- `commit` and `rollback` are only called when at least one transaction is active. They should still return `False` correctly if no transaction is open.
### Clarifying Questions to Ask
- How deep can transactions nest, and how often is `get` called compared with writes? The answer decides whether a read may walk every open layer.
- Is the store used by one client, or do several clients each run their own transactions against shared data?
- Will we later need queries over the visible state, such as counting keys with a given value?
### What a Strong Answer Covers
- A representation of open transactions that leaves outer state untouched until commit, and a deletion marker that differs from a key the layer never touched.
- Commit semantics in both cases: merging into the enclosing layer and applying to the base store, including what happens to deletions in each.
- The cost of every operation, and how reads scale with nesting depth.
- Edge cases such as delete then set in the same layer, rolling back an outer transaction after an inner commit, and commit or rollback with nothing open.
### Follow-up Questions
- How would you make `get` constant time regardless of nesting depth, and what would `commit` and `rollback` cost then?
- How would you add `count(value)`, the number of keys whose visible value equals `value`?
- How would several clients, each with its own transaction, share one store, and what would each client see of the others' uncommitted writes?
- How would you make committed data survive a process crash?
Overview: Design an in-memory key-value store with get, set and delete plus arbitrarily nested begin, commit and rollback. It tests how to buffer uncommitted writes in layers, mark deletions so they hide outer values, merge a commit into its parent transaction, and how read cost grows with nesting depth.