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
Nested transactions with sheets of glass
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A key-value store maps a key to a value. A transaction is a group of changes that happens as a whole or not at all.
In memory, a transaction can be a layer: a small map with only the changes. Reading goes from the top layer down, rollback drops a layer, commit copies it onto the one below.
Two details make it interesting. A deleted key must hide the value below, so a layer needs a mark for wiped. And a count of keys by value must roll back with everything else.
Why it exists
People change their minds, and programs fail halfway. Without a transaction, each caller has to write its own repair, and forgets a case.
The problem is a favourite for a first round: small enough to finish, with one real trap, and a natural second half about several sessions.
The same idea is found in databases, editors, build tools and game saves: keep the changes apart until they are wanted.
A short history
1979
H. T. Kung and John T. Robinson propose optimistic concurrency control: work without locks, check before committing. Their journal paper appears in 1981.
1981
Jim Gray's paper The Transaction Concept describes a transaction as a change of state that is atomic, durable and consistent.
1995
Berenson and others criticise the SQL isolation levels and describe snapshot isolation and its anomalies.
2009
SQLite 3.6.8, released on 12 January, adds support for nested transactions: savepoints.
Words to know
- Layer
- The changes of one open transaction.
- Slate, base
- The committed values. The lowest layer.
- Mark, tombstone
- An entry that says: deleted here.
- Undo log
- Old values kept for a rollback.
- Redo
- New values kept until a commit. Layers are redo.
- Nested transaction
- One inside another. Its commit goes into the parent.
- Session
- One caller with its own layers.
- Lost update
- Two read the same value, both write, one write disappears.
- Snapshot
- The world as it was at one moment.
- Write skew
- Two read the same things and write different ones, and break a rule together.
- Write-ahead log
- A record on disk before the change is visible.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Begin. An empty layer on top, nothing is copied
Understand it
Start here
A slate and two sheets of glass
What an interviewer looks for
Do they avoid the copy?
A transaction that changes one key must cost one key, not a million.
Do they see the wiped mark?
"Not mentioned here" and "deleted here" are different. This is where most first versions fail.
Is count fast?
A second map, value to number, and it must be rolled back too.
Do they ask what commit means?
Into the parent, or everything at once? Both exist.
How to spend the round
- 1
Ask
Types of keys and values, nested or not, the meaning of commit, one caller or many.
- 2
Three designs
Copy, undo log, layers. Say the cost of each, choose one.
- 3
Code
get, one private_write, then begin, rollback, commit. - 4
Trace
Delete inside a transaction, then roll back. Count before and after.
- 5
Extend
Two sessions at once, or a crash, or a time to live.
Questions
Six questions, and what each answer changes
| Ask | One answer | The other |
|---|---|---|
| Nested transactions? | A pile of layers | One layer and a flag |
| What does commit do? | Into the parent | Everything at once |
| Count by value? | A map of numbers in each layer | Leave it out |
| Can a value be empty or null? | A separate mark for wiped | None may be the mark |
| One caller? | No lock at all | Sessions, with a check at commit |
| Survive a crash? | A log | Memory only |
Design, first try
The design most people start with
The design to avoid: a copy of everything, and a scan for every count
1/3Text, data and transactions in one class
execute splits the line, changes the map and knows about transactions. A test of rollback has to write sentences.
usesowns (dies together)
class CopyStore: def __init__(self): self.data = {} self.saved = [] def begin(self): self.saved.append(dict(self.data)) # a full copy, also for one small change def rollback(self): self.data = self.saved.pop() def commit(self): self.saved.pop() def count(self, value): return sum(1 for v in self.data.values() if v == value) # looks at every keyDesign, better
The design to reach
The design to reach: a pile of sheets, each with only its own chalk
1/4A sheet is only the changes
What was written, what was wiped, and how many keys gained or lost a value. Nothing else. An empty sheet costs nothing.
usesowns (dies together)depends on
Value? in a layer means a value or nothing. Nothing is the mark for wiped.Three ways to undo
| Copy | Undo log | Layers | |
|---|---|---|---|
| begin | O(all keys) | O(1) | O(1) |
| get | O(1) | O(1) | O(depth) |
| set | O(1) | O(1), and remembers the old value | O(depth), because count needs the old value |
| rollback | O(1) | O(writes) | O(1) |
| commit | O(1) | O(writes of the child) | O(writes) |
| Others see uncommitted values | Yes: one map | Yes: one map | No: the slate is clean |
Read
From the top down
get, with three layers
A transaction that is taken back
Wiped
Three answers, not two
What a layer can say about a key
| In the layer | Meaning | get does |
|---|---|---|
| No entry | I do not know | Look one layer down |
| Entry with a value | It is this | Stop, return it |
| Entry with nothing | It is gone | Stop, return nothing |
if layer.writes.get(key) cannot tell the first row from the third.How is a delete written into a layer?
BreaksRemove the key from the layer
- How
layer.pop(key)- Limit
- The value below shines through: the key is back.
- Choose when
- Only on the slate itself.
WorksNone as the mark
- How
layer[key] = None, andinto ask whether it is mentioned.- Limit
- Values must never be
None. - Choose when
- Values are text. Our case.
StrongA mark of its own
- How
GONE = object(), or an optional type in Java, C++ and TypeScript.- Limit
- One more name.
- Choose when
- Values of any type.
Count
Changes, not totals
A layer stores by how much each value gained or lost. The answer is the sum over all layers. So a rollback takes its changes with it, and a commit adds them to the layer below.
Slate: tea red, jam red
| Call | Top layer says | count red |
|---|---|---|
| 2 | ||
| begin, set tea blue | red -1, blue +1 | 2 - 1 = 1 |
| delete jam | red -2, blue +1 | 0 |
| rollback | gone | 2 |
Commit
What does it mean inside another one?
Two meanings
class CommitAll: """The other meaning: COMMIT ends every open level at once.""" def __init__(self): self.base, self.open = {}, [] def begin(self): self.open.append({}) def set(self, key, value): (self.open[-1] if self.open else self.base)[key] = value def commit(self): for layer in self.open: self.base.update(layer) self.open.clear()def to_parent(layers): top = layers.pop() layers[-1].update(top)layers = [{}, {"tea": "4"}, {"jam": "0"}]to_parent(layers)print("into the parent:", layers)other = CommitAll()other.begin(); other.set("tea", "4"); other.begin(); other.set("jam", "0"); other.commit()print("all at once: ", [other.base, *other.open])States
What may be called when
One session
Do
- Store only changes
- Write through one private method
- Look up the old value before you write
- Keep text outside the store
- Say what commit means
Do not
- Copy the map at begin
- Test a layer with
getalone - Count by walking through all keys
- Give set, delete and commit three ways to update counts
- Use a flag
inTransactionnext to a list
Summary
The whole topic in one minute.
A transaction is a layer with only its changes: values, marks for wiped keys, and differences of counts. Read from the top down, write on the top, drop it to roll back, copy it one layer down to commit.
With several callers each has its own layers. Commit checks under one lock that the versions it read are still the same. Disk adds a log that is written first.
- A transaction is a layer that holds only its own changes.
- Read from the top, write on the top, drop the top, or copy it one down.
- Not mentioned and wiped are different answers.
- Counts are differences too, so they come and go with their layer.
- Ask whether commit goes into the parent or all the way.
- Several callers: each has its own layers, and commit checks what was read.
Sources
- Redis: transactions
- SQLite: savepoints
- SQLite: release history
- PostgreSQL: subtransactions
- PostgreSQL: transaction isolation
- PostgreSQL: write-ahead logging
- LevelDB documentation
- LevelDB log format
- RocksDB: transactions
- Python: collections.ChainMap
- Clojure: refs and transactions
- etcd API: revisions
- MDN: using IndexedDB
- Jim Gray: The Transaction Concept
- Wikipedia: optimistic concurrency control
- Wikipedia: snapshot isolation