Design a key-value store with transactions
medium 75 minBuild an in-memory store with SET, GET, DELETE, COUNT and nested transactions: layers that hold only changes, a mark for wiped keys, counts that roll back, and then several sessions, snapshots and a log.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Sheets on a slate: watch which one answers, what is written, and what comes back.
Operations
Begin and set
An empty sheet, then one entry on it.
Step 1 of 5
The slate
Three committed keys.
Step 1: The slate
def _write(self, key, value): top = self._layers[-1] top.shift(self.get(key), -1) top.shift(value, +1) if value is None and self.depth == 0: top.writes.pop(key, None) else: top.writes[key] = value- Cost
- O(1), O(depth)
- Guarantee
- The slate is untouched
- Copy at begin
- O(all keys)
Read the old value before you write.
In the real world
The same key-value store with transactions doing real jobs. Pick one and step through it.
Every call is locked. The transaction is not.
Step 1 of 4
a reads
3.
Step 1: a reads
n = store.get("tea") # lockedstore.set("tea", n - 1) # locked# between the two lines: the gapCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Testing a layer with get
criticalA wiped key looks like an unknown one, and the old value comes back.
Wrongvalue = layer.writes.get(key)if value is not None: return valueRightif key in layer.writes: return layer.writes[key]Copying at begin
majorA million entries for one change, and again for each level.
Wrongself.saved.append(dict(self.data))Rightself._layers.append(Layer())Old value read too late
criticalAfter the write the old value is the new one, and the counts are wrong for ever.
Wrongtop.writes[key] = valuetop.shift(self.get(key), -1)Righttop.shift(self.get(key), -1)top.writes[key] = valueA lock for each call
criticalThe gap between get and set stays, and updates are lost.
Wrongsynchronized get(...)synchronized set(...)Rightsession.commit() # checks what it read, writes, one lockMarks on the slate
minorDeleted keys stay in memory for ever.
Wrongbelow.writes[key] = NoneRightif value is None and self.depth == 0: below.writes.pop(key, None)update at an undo commit
majorAn outer rollback restores a value that was never committed.
Wrongparent.update(child)Rightfor key, before in child.items(): parent.setdefault(key, before)
Interview tips
Open with
- What does commit mean?
- Three designs, three prices.
- One caller, or many?
Reject aloud
- No TransactionManager.
- No copy.
- No command classes.
Prove it
- Delete, then roll back.
- Count in a nested layer.
- The slow twin.
Never
- get in place of in.
- Memory before log.
- A lock for each call.