Implement Nested Transactions in an In-Memory Database
DRWData Engineer · Online AssessmentLast updated
This problem tests your ability to manage state and scope using stacks and dictionaries to implement transaction isolation in a key-value store.
Problem Statement
Design an in-memory key-value store that supports nested transactions. Your database should support the following operations:
SET(key, value): Stores a value for a key. If a transaction is active, this change is associated with the current transaction level.GET(key): Returns the value associated with the key. It should return the value from the most recent active transaction level; if not present, look in outer levels, and finally the base database.BEGIN(): Starts a new nested transaction level.ROLLBACK(): Discards all changes made in the most recent transaction level and returns to the previous level. If no transaction is active, return an error.COMMIT(): Persists all changes from the current transaction level to the parent level (or the base database if no parent exists).
Constraints
- Keys are strings; values are integers.
- The database must handle multiple nested levels (e.g.,
BEGINcalled multiple times).
Example
# db = TransactionalDB()
db.SET("a", 10)
db.BEGIN()
db.SET("a", 20)
db.COMMIT()
print(db.GET("a")) # Output: 20
db.BEGIN()
db.SET("a", 30)
db.ROLLBACK()
print(db.GET("a")) # Output: 20
Implementation Signature
class TransactionalDB:
def __init__(self): ...
def set(self, key, value): ...
def get(self, key): ...
def begin(self): ...
def rollback(self): ...
def commit(self): ...
Hints
Hint 1
Use a list of dictionaries to represent transaction levels, where each dictionary acts as a scoped layer.
Hint 2
The GET operation should iterate through the stack of dictionaries from top to bottom to find the most recent value.
Hint 3
For COMMIT, merge the top dictionary into the one immediately below it; for ROLLBACK, simply pop the top dictionary off the stack.
Follow-up questions
- How would you optimize the GET operation if the number of transaction levels becomes very large?
- What changes are required to support DELETE operations within nested transactions?
- How would you ensure thread safety if multiple clients access the database simultaneously?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.