I was just asked this "Let’s say we have a simple “database” in a key-value map. Implement Transaction functionality that can accumulate database operations and then commit them." How would you approach this problem and what would you look clarify from the problem statement right away? This problem definitely tests clarifying ambiguity One thing i thought to clarify was if operations should be atomic - all or nothing One thing didn't clarify early on was if the database should support concurrent operations The class design for this will eventually look something like . Class Database{ ... void commit(Transaction t){...} } Class Transaction { .. }
Priority queue for efficient DB operations. Stack for rolling back ops in a transaction
Oh this is a good thing to clarify- if there some be priority to the way the values are stored or if it's pure last access
Lock(key) SetInRedis() Unlock(key) EZ
snapshot isolation, I think. DDIA obviously covers it, but I think Database Internals by Alex Petrov also has some nice material on it.
Use a stack to keep track of key and old value. Use a keyword like "TRANSACTION" to signify the start of the transaction. When you need to rollback just pop off the stack until you get to the keyword. And use a different keyword to signify commit or just clear the stack