Implement an In-Memory Key-Value Store with Transactions
How to build a small key-value store with begin, commit and rollback, nested transactions and deletes, explained for your AI interview.
In short
A key-value store keeps values under keys. To add transactions, each open transaction writes into its own layer: commit merges the layer into the one below, and rollback throws it away.
10 min readIntermediateCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
I'd keep the data in a dictionary and give each open transaction its own layer of changes. Reads check the newest layer first. Commit merges that layer down, and rollback throws it away, so a half-finished refund never leaks out. Deletes leave a marker, so a rollback can bring a key back. It's a single-threaded sketch, so I'd add locks before sharing it between agents.
Start with the simplest working version: a Python dictionary holds the real data. The hard part is transactions, a group of writes that must all save or all disappear. The changes wait in a draft until the whole group checks out. If something fails, the draft is thrown away and the store stays as it was.
In code, begin pushes an empty layer onto a stack. A set writes into the newest layer only. A get checks the layers from newest to oldest, then the main data. Commit pops the newest layer and merges it into the layer below, or into the main data when none is left. Rollback pops the layer and drops it. A delete writes None, which means deleted, so an older value can't show through.
Nesting falls out of the same stack. An inner rollback removes only the inner changes, and an inner commit folds into its parent, so the outer transaction still decides the result. For a refund agent, a failed payment step can undo its own small changes while the earlier steps stay pending until the outer commit.
The honest limits: this sketch is not safe for threads, it shares one view of uncommitted changes, and nothing survives a crash. For many agents at once, I'd give each its own stack and lock the commit. This sketch is not durable, and I'd say so rather than pretend it is.
What is a key-value store with transactions, in plain words?
A key-value store is a lookup table. You give it a key, such as ticket:4812:status, and it gives back the value stored under that key. An in-memory store keeps everything in the program's memory, so it is fast, and it is gone when the program stops.
A transaction is a group of changes that must all happen, or none of them. Picture a loan officer with a draft sheet. She pencils the changes first, and copies them into the official file only once the whole file checks out. If something fails, she tears the sheet up and the file stays as it was.
The same idea helps an AI support agent. It might set a refund status, a refund hold and a note in one go. If the payment call fails halfway, you want none of those three changes to stay.
Key words
- Key-value store
- A lookup table: a key goes in, a stored value comes out.
- Transaction
- A group of changes that all save together, or none do.
- Commit
- Keep the group: its changes become part of the store.
- Rollback
- Throw the group away, so the store goes back to how it was.
- Tombstone
- A marker that says a key was deleted here. Our sketch uses None.
How do the layers work?
Each open transaction gets its own layer, a small dictionary of changes. Writes go only into the newest layer. Reads check the newest layer first, then the older ones, then the main data. Commit folds the newest layer into the one below it. Rollback drops it.
Python's collections module has a ChainMap class that links several dictionaries into one view, and it follows the same read and write rule. It is a good name to know for the interview.
How a transaction's changes flow
Your code
begin()
opens a new empty layer
set(key, value)
writes only the newest layer
Layers of changes
reads check the newest first
Then one of two
commit()
merges into the layer below
rollback()
throws the newest layer away
Main data
only committed changes land here
- 1begin() adds an empty layer on top.
- 2Each write lands in the newest layer only.
- 3Commit takes the newest layer out and merges it below.
- 4Rollback takes the newest layer out and drops it.
- 5Only the outermost commit reaches the main data.
- 1
begin()
Push an empty layer on top of the stack.
- 2
set and delete
Write to the newest layer only. A delete writes None, a marker that means deleted.
- 3
get
Check the newest layer first, then older layers, then the main data.
- 4
commit()
Take the newest layer off the stack and write its changes into the layer below, or into the main data.
- 5
rollback()
Take the newest layer off the stack and drop it. None of its changes reach the data.
Can you see it work on a refund?
Here is the whole sketch in plain Python, 30 lines with standard-library code only. The store holds one made-up refund ticket. An outer transaction marks it refunded, then a nested step deletes the fraud hold and rolls back.
class KVStore:
def __init__(self):
self.data, self.layers = {}, [] # layers: open transactions, oldest first
def get(self, key):
for layer in reversed(self.layers):
if key in layer: return layer[key]
return self.data.get(key)
def set(self, key, value): # None means "deleted"
if self.layers:
self.layers[-1][key] = value
elif value is None:
self.data.pop(key, None)
else:
self.data[key] = value
def begin(self):
self.layers.append({})
def commit(self):
for key, value in self.layers.pop().items():
self.set(key, value) # merges into the layer below, or into the data
def rollback(self):
self.layers.pop() # drops the newest layer
store = KVStore()
store.set("ticket:4812:hold", "fraud check")
store.begin() # a refund starts
store.set("ticket:4812:status", "refunded")
store.begin() # a nested step
store.set("ticket:4812:hold", None) # delete the hold
store.rollback() # the nested step fails, so the hold comes back
store.commit() # the outer refund succeeds
print(store.get("ticket:4812:status"), store.get("ticket:4812:hold"))Output
refunded fraud check
Read the output. The nested rollback brought the hold back, so the delete never happened. The outer commit kept the refunded status, so the refund stands.
Why a stack of layers, not a copy of the store?
- Copy
Copy everything
Each begin copies the whole store. Simple to write, but slow and heavy once the data is big.
- Layers
Store only the changes
Each begin adds a small empty layer. Reads and commits touch only the keys that changed.
Nested transactions come for free. An inner rollback drops only its own layer, and an inner commit folds into its parent, so the outer transaction still decides the final result.
Tip
Asked to pick a design, name the trade-off first: copying is simpler, layers are cheaper. Then say which one fits the size of the data.
What does this sketch leave out?
A lot, and an interviewer will want you to say so. Three gaps matter most.
Thread safety
Two threads writing at once can corrupt the shared layers. A lock is the usual fix.
Visibility
Every caller shares one stack, so one caller can read another's uncommitted changes.
Durability
The data lives in memory only, so a crash loses everything not yet saved to disk.
The official docs define the words used here:
“The ChainMap class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain.”
Python's collections module
“Roll back to the start of any pending transaction.”
Python's sqlite3 module
“A primitive lock is a synchronization primitive that is not owned by a particular thread when locked.”
Python's threading module
How would you make it safe for many agents at once?
Give each agent its own stack of layers, so one agent never reads another's open changes. Guard the shared main data with a lock, and hold that lock only while a commit writes to it.
Python lock objects can be used with the with statement, so the lock is released when the block is exited. Keep the locked part short. A slow payment call inside the lock would block every other agent.
Tip
Say the cost out loud. Locks serialise commits, so the number of commits per second is capped by how fast each one finishes.
What does the interviewer want to hear?
A strong answer covers
- Values in a dictionary, looked up by key.
- Transactions as layers: begin pushes, commit merges down, rollback drops.
- Reads check the newest layer first, then older layers, then the data.
- Deletes leave a marker, so a rollback can bring a value back.
- Honest limits: threads, shared visibility and crash safety.
- Commit or rollback with no open transaction should raise a clear error, not a bare IndexError.
Common traps
Trap"Just copy the dictionary before every change."
BetterFine for tiny data. Layers record only what changed, so they stay cheap when the store is big.
Trap"A single lock on every call is enough, so transactions are safe."
BetterA lock stops two threads colliding. It does not stop one agent's rollback from undoing work another agent can see.
Trap"Deleting a key just removes it from the dictionary."
BetterInside a transaction, removing the key from the newest layer lets an older value show through. Keep a marker instead.
Can you spot the bug?
Spot the bug
Which line in a teammate's commit breaks the rules?
Quick check
Your refund agent starts a transaction that marks ticket 4812 refunded. A nested step removes the fraud hold and then fails, so it is rolled back. The outer refund is then committed. What is saved?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 27 November 2026
Building an agent that has to undo half-finished steps?
I design and build AI products and agents, and the system behind them: the state, the checks and the undo path. Book a short call and say what yours needs to do.