esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

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.

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

  1. 1begin() adds an empty layer on top.
  2. 2Each write lands in the newest layer only.
  3. 3Commit takes the newest layer out and merges it below.
  4. 4Rollback takes the newest layer out and drops it.
  5. 5Only the outermost commit reaches the main data.
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. 1

    begin()

    Push an empty layer on top of the stack.

  2. 2

    set and delete

    Write to the newest layer only. A delete writes None, a marker that means deleted.

  3. 3

    get

    Check the newest layer first, then older layers, then the main data.

  4. 4

    commit()

    Take the newest layer off the stack and write its changes into the layer below, or into the main data.

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

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

1 / 6

What will they ask next?

  1. Q471Implement a rate limiter (per-user and global).12 min
  2. Q473Run an LLM over 50,000 documents with concurrency limits and 429 retries.13 min
  3. Q479Implement an LRU cache.10 min
  4. Q482Write a minimal agent loop with tool dispatch.12 min
  5. Q447What are the challenges of long-running agents?10 min

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.