Build an In-Memory Store with Nested Transactions and Value Counts
Data Structure DesignModel answerLast updated
Design a string key-value store with transactional writes, fast rollback, and a count of keys holding a given value, with all transaction semantics spelled out.
Task
Design a single-process, in-memory store that maps string keys to string values. It must support these operations:
set(key, value): create or overwrite a key.get(key): return the current value, or a defined "missing" result.delete(key): remove a key.count(value): return how many keys currently hold exactly that value.begin(),commit(),rollback(): transaction control.
Because the requirements do not say how nested transactions behave, you must choose a behavior and state it explicitly.
Assumptions
- Keys and values are strings.
- Within a transaction, reads observe that transaction's own earlier writes.
countmust reflect the state visible to the caller at that moment, including uncommitted changes in the current transaction.- Execution is single-threaded unless you are asked about concurrency as a follow-up.
- Durability is out of scope unless you choose to discuss it.
Questions worth settling up front
- Can transactions nest? What does committing an inner transaction mean?
- Is deleting a missing key an error or a no-op?
- What happens on
commitorrollbackwith no open transaction? - What cost do you target for ordinary operations, rollback, and
count?
What to cover
- Semantics. Define every command, including misses, overwrites, deletes, and what
countreturns before and after commit or rollback. - Data structures. Choose structures for key lookup, value counting, and reversible changes. Compare a full snapshot per transaction with an undo log or layered writes. Explain how repeated writes to one key inside a transaction are handled.
- Testing and extensions. Describe how you would test commits, rollbacks, misses, duplicate values, and misuse. Explain how adding concurrency or persistence would change the design.
Hints
Hint 1
Keep two indexes in sync: a map from key to value and a map from value to the number of keys holding it. Route every mutation through one internal function that updates both.
Hint 2
Do not copy the whole store on begin. Record, for each change, what is needed to reverse it: the key and its previous value, or the fact that it was absent.
Hint 3
To roll back, pop the newest transaction's undo entries and apply them in reverse order using the same internal mutation function, so the counts are repaired automatically.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Semantics to state first
set(k, v): insert or overwrite. Always succeeds.get(k): return the value, or a null/"missing" marker if absent.delete(k): remove the key; deleting a missing key is a no-op (no error, no undo entry needed).count(v): number of keys whose current visible value equalsv; returns 0 for unknown values.begin(): opens a new transaction on top of a stack, so nesting is supported.rollback(): discards the innermost open transaction's changes and restores the state as it was at itsbegin. With no open transaction, report an error (or return false).commit(): I choose merge-into-parent semantics: an inner commit folds its changes into the enclosing transaction, so they can still be undone by an outer rollback. Only committing the outermost transaction makes changes permanent. The alternative, wherecommitflushes everything and closes all levels, is also valid, but must be stated. With no open transaction, report an error.- Reads and
countalways see the live state, which includes uncommitted writes of open transactions. Since there is one caller and one thread, this gives read-your-writes automatically.
Data structures
data: HashMap<string, string>is the live key-to-value map.freq: HashMap<string, int>is a reverse index from value to the number of keys holding it. Entries that drop to zero are removed to avoid unbounded growth.txStack: Stack<List<UndoEntry>>holds one undo log per open transaction. AnUndoEntryis(key, hadValue, oldValue).
The central idea is a single private mutator, applyWrite(key, newValueOrAbsent):
- Look up the old value in
data. - If an old value exists, decrement
freq[old]. - If a new value is given, store it and increment
freq[new]; otherwise remove the key.
Both set and delete call it, and so does rollback. This makes it very hard for the two indexes to drift apart, which is the most common bug here. In particular, overwriting k from a to b must decrement a and increment b, and overwriting with the same value must leave the count unchanged (decrement then increment handles this correctly).
Transactions: undo log
When a public set or delete runs inside a transaction, first push (key, existedBefore, oldValue) onto the top log, then call applyWrite. Outside a transaction, skip logging.
- Rollback: pop the top log and replay entries from newest to oldest. For each, call
applyWrite(key, existedBefore ? oldValue : absent). Reverse order matters when a key was written several times: the oldest entry holds the true pre-transaction value and must be applied last. - Commit (merge): if a parent transaction exists, append the child's entries to the parent's log, preserving order, so an outer rollback still restores correctly. If it is the outermost transaction, simply drop the log.
- Optimization: log only the first write to each key per transaction by keeping a per-transaction set of touched keys. This bounds log size by the number of distinct keys changed. Without it, the log is bounded by the number of writes, which is still correct. When merging into a parent, entries for keys the parent has already logged can be dropped, since the parent's earlier entry already holds the older value.
Complexity
| Operation | Cost |
|---|---|
| set, get, delete, count | O(1) average |
| begin | O(1) |
| rollback | O(w), where w is the number of writes (or distinct keys) in that transaction |
| commit | O(1) for outermost; O(w) to append to parent, or O(1) with a linked-list splice |
Rollback never scans the whole store, which is the key advantage over snapshots.
Alternatives and trade-offs
- Snapshot per begin: simple to get right, but
begincosts O(n) time and memory, which is poor for large stores or deep nesting. Fine as a reference implementation in tests. - Layered overlay maps: each transaction holds a map of pending writes plus tombstones for deletes. Reads walk layers from innermost to outermost, and commit merges a layer downward. Rollback is O(1) (drop the layer), but reads cost O(depth), and
countbecomes harder because you need to combine layer deltas with the base counts. The undo log with eager application keepscounttrivial, so I prefer it.
Testing
- Model-based/property tests: run random sequences of commands against both the optimized store and a naive snapshot-based reference, and compare every
getandcount. - Targeted cases: set then delete then rollback; overwrite with the same value; repeated writes to one key in one transaction; delete of a missing key; nested begin/rollback/commit combinations;
countof a value that disappears and returns; commit or rollback with no open transaction. - Invariant check: after every operation, the sum of
freqvalues equalslen(data), and recomputing counts fromdatamatchesfreq.
Extensions
- Concurrency: eager application of uncommitted writes to shared state leaks dirty reads across threads. Options are a global lock (simple, serialized), or per-transaction write buffers (the overlay approach) with commit-time validation or key-level locking, to get snapshot or serializable isolation. Counts would need either locking or versioned counters.
- Persistence: keep in-memory semantics separate from durability. Append committed transactions to a write-ahead log, applying only on commit, and periodically checkpoint. Recovery replays the log. Uncommitted work never needs to be written.
Common mistakes
- Forgetting to decrement the old value's count on overwrite or delete.
- Rolling back in forward order, which restores the wrong value for repeated writes.
- Leaving zero-count entries in
freq, or logging a no-op delete and then "restoring" a key that never existed. - Leaving commit semantics for nested transactions unstated.