# 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.

AI and LLM interview question Q472, Coding and practical. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-a-key-value-store-with-transactions

## Say it in 30 seconds

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.

## Say it in 2 minutes

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-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.

*Diagram, How a transaction's changes flow: Writes land in the newest layer. Commit merges that layer down, and only the outermost commit reaches the main data. Rollback throws the layer away, so the main data never sees its changes.*
1. begin() adds an empty layer on top.
2. Each write lands in the newest layer only.
3. Commit takes the newest layer out and merges it below.
4. Rollback takes the newest layer out and drops it.
5. Only 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.

```python
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:

```text
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." Better: Fine 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." Better: A 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." Better: Inside 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?

A. for key, value in self.layers.pop().items():
B. self.set(key, value)  # merges into the layer below
C. self.data.update(self.layers.pop())

**Answer:** C. Commit must merge into the layer below when a transaction is still open. This line writes straight into the main data, so an outer rollback can no longer undo it.

**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?

A. The refunded status, and the fraud hold stays
B. Nothing, since a rollback cancels every open layer
C. Only the removed hold, since the nested step saved
D. The refunded status and the removed hold

**Answer:** A. A rollback drops only the nested layer, so its hold removal is undone. The outer commit then saves the refunded status.

## Can you answer these from memory?

**Flash cards**

- **What is a transaction?** A group of changes that all save together, or none do.
- **What does commit do?** Merges the newest layer into the layer below, or into the main data.
- **What does rollback do?** Throws away the newest layer, so its changes never reach the data.
- **Why store a delete as a marker?** So the layer hides an older value. Without it, reads fall through to the old one.
- **Where do reads look first?** The newest layer, then older layers, then the main data.
- **What limits this sketch?** One shared stack, no locks, no crash safety. None means deleted, so it can't be a real value.

## Likely follow-up questions

- Q471 Implement a rate limiter (per-user and global). https://designervenkat.online/interview/ai/implement-a-rate-limiter
- Q473 Run an LLM over 50,000 documents with concurrency limits and 429 retries. https://designervenkat.online/interview/ai/run-an-llm-over-50000-documents
- Q479 Implement an LRU cache. https://designervenkat.online/interview/ai/implement-an-lru-cache
- Q482 Write a minimal agent loop with tool dispatch. https://designervenkat.online/interview/ai/write-a-minimal-agent-loop-with-tool-dispatch
- Q447 What are the challenges of long-running agents? https://designervenkat.online/interview/ai/what-are-the-challenges-of-long-running-agents
