AAI Agentic Handbook
Problem 72 · Object & System Design

KV Store with Nested Transactions

MediumClassic DSA & systems
01Problem

Implement a KV store supporting set, get, delete, begin, rollback, and commit. Transactions nest: rollback undoes only the innermost; commit applies all open transactions. Rollback/commit with no open transaction returns False.

02Key insight

Maintain a stack of write-sets layered over the base map; reads check from innermost layer outward. A tombstone sentinel records deletes. Rollback pops a layer; commit flattens all layers into base.

03Solution

Try it first.

TimeO(1) write; O(depth) read; O(total writes) commit
SpaceO(writes in open txns)
tests.py · 4 passing
tests.pypython9 lines
kv = TransactionalKV()
kv.set("a", 1)
kv.begin(); kv.set("a", 2)
kv.begin(); kv.delete("a")
assert kv.get("a") is None
assert kv.rollback() and kv.get("a") == 2
assert kv.rollback() and kv.get("a") == 1 and not kv.rollback()
kv.begin(); kv.set("b", 5); kv.begin(); kv.delete("a")
assert kv.commit() and kv.get("a") is None and kv.get("b") == 5 and not kv.commit()
04Staff-level follow-up

Reads are O(depth) and some variants need COUNT(value). Alternative: undo-log per layer (apply writes to base, store prior values) gives O(1) reads and makes value-count indexes easy to maintain.