KatInterview

Transactional Key-Value Store with Rollback Support

Data Structure DesignModel answer
MediumModel answerData Structure Designtransactionsstackstate-management

Last updated

Build a key-value store supporting nested transactions with set, get, delete, begin, commit, and rollback operations.

Problem

Implement a key-value store that maintains transactional boundaries. Your store must track modifications across multiple nested scopes and allow callers to either apply or discard changes.

Interface

Provide these operations:

  • set(key, value): Store a value under the given key within the active scope
  • get(key): Retrieve the most recent value for a key, searching through nested scopes if necessary; return None when the key doesn't exist
  • delete(key): Remove a key from visibility in the current scope
  • begin(): Open a new transaction scope
  • commit(): Merge the active scope's changes into its parent
  • rollback(): Discard all modifications made in the active scope

Behavior

The store maintains a hierarchy of scopes. When you open a transaction with begin(), subsequent writes affect only that scope. A get() looks in the current scope first, then walks up through parent scopes until it finds the key or exhausts all scopes.

Calling delete(key) makes that key invisible in the current scope and any child scopes, even if a parent scope contains it. After commit(), the current scope's changes overwrite parent values. After rollback(), the scope's changes vanish as if the transaction never happened.

Example Usage

store = TransactionalStore()
store.set("x", 10)
print(store.get("x"))  # 10

store.begin()
store.set("x", 20)
store.set("y", 30)
print(store.get("x"))  # 20
print(store.get("y"))  # 30

store.rollback()
print(store.get("x"))  # 10
print(store.get("y"))  # None

store.begin()
store.set("x", 40)
store.commit()
print(store.get("x"))  # 40

Implementation Notes

  • Use a stack-based architecture where each level represents one transaction scope
  • Optimize get to run in time proportional to nesting depth, not total key count
  • Handle the case where a caller tries to commit or rollback without an active transaction

Hints

Hint 1

Maintain a stack of dictionaries where each dictionary holds only the changes made in that scope, not a full copy of all data

Hint 2

Use a special marker object to represent deleted keys so you can distinguish deletion from a missing key

Hint 3

When committing, merge the top scope into its parent; when the parent is the base level, convert deletion markers into actual removals