KatInterview

Build a Nested-Transaction Key–Value Store from Scratch

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-mapstacktransactions

Last updated

Design and implement an in-memory key–value store that supports arbitrarily nested BEGIN/COMMIT/ROLLBACK transactions with correct shadowing and O(1) reads.

Nested-Transaction Key–Value Store

You are building a lightweight in-memory database that supports transactional reads and writes. It must handle the following five commands:

CommandBehavior
SET key valueStore value under key, overwriting any previous value.
GET keyPrint the value currently stored at key, or NULL if no such key exists.
BEGINOpen a new transaction block.
ROLLBACKUndo every change made inside the most recently opened transaction that has not yet been committed. Print NO TRANSACTION if there is no open transaction.
COMMITMake all pending changes permanent and close every open transaction. Print NO TRANSACTION if there is no open transaction.

Requirements

  • Transactions may be nested to any depth. A BEGIN inside an existing transaction opens an inner transaction.
  • Within a transaction, reading a key always returns the most recently written value — whether it was set before or during the transaction, or by an enclosing transaction.
  • Rolling back an inner transaction restores the value visible at the time that inner BEGIN executed, not the original pre-database value.
  • Rolling back an outer transaction afterward restores the state that existed before that outer BEGIN.
  • A key that was created for the first time inside a transaction must be fully removed (not set to null or an empty string) when that transaction is rolled back.
  • COMMIT with nested open transactions commits all of them at once.

What to produce

  1. Define the core data structures you would use.
  2. Walk through the algorithm for each of the five commands.
  3. State the time and space complexity of each operation.
  4. Compare your chosen approach to at least one alternative design, noting trade-offs.
  5. Call out the edge cases that must be handled correctly.
  6. Provide working code and a short example trace that demonstrates nested rollback behavior.

Example interaction

BEGIN
SET x 10
BEGIN
SET x 20
GET x       → 20
ROLLBACK
GET x       → 10
COMMIT
GET x       → 10

Hints

Hint 1

Think about what information you need to save at the moment of each SET so that a future ROLLBACK can undo exactly that write — and nothing more. You don't need to record every intermediate state, just the right one.

Hint 2

A stack pairs naturally with nested transactions: one entry per open BEGIN. What should each stack entry store — the full snapshot of the database, the full diff, or something smaller?

Hint 3

A key that never existed before a transaction is a special case. How do you distinguish 'the key was absent' from 'the key was set to some value'? You may need a sentinel.