AlgoViz

Design a key-value store with transactions

medium 75 min

Build 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

0:00 / 4:54

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

  1. 1979

    H. T. Kung and John T. Robinson propose optimistic concurrency control: work without locks, check before committing. Their journal paper appears in 1981.

  2. 1981

    Jim Gray's paper The Transaction Concept describes a transaction as a change of state that is atomic, durable and consistent.

  3. 1995

    Berenson and others criticise the SQL isolation levels and describe snapshot isolation and its anomalies.

  4. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Begin. An empty layer on top, nothing is copied

Understand it

Start here

A slate and two sheets of glass

How to change your mind with chalk
teajamsalt351

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. 1

    Ask

    Types of keys and values, nested or not, the meaning of commit, one caller or many.

  2. 2

    Three designs

    Copy, undo log, layers. Say the cost of each, choose one.

  3. 3

    Code

    get, one private _write, then begin, rollback, commit.

  4. 4

    Trace

    Delete inside a transaction, then roll back. Count before and after.

  5. 5

    Extend

    Two sessions at once, or a crash, or a time to live.

Questions

Six questions, and what each answer changes

AskOne answerThe other
Nested transactions?A pile of layersOne layer and a flag
What does commit do?Into the parentEverything at once
Count by value?A map of numbers in each layerLeave it out
Can a value be empty or null?A separate mark for wipedNone may be the mark
One caller?No lock at allSessions, with a check at commit
Survive a crash?A logMemory only

Design, first try

The design most people start with

The design to avoid: a copy of everything, and a scan for every count

KeyValueStore- data: Map- backups: List<Map>- inTransaction: bool+ execute(line): String+ get(key)+ set(key, value)+ count(value)+ begin()+ rollback()

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)

It gives the right answers. With three keys in the example, nobody notices the price.
Python
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 key
Right answers, wrong price. Begin copies all keys, and count reads all keys.

Design, better

The design to reach

The design to reach: a pile of sheets, each with only its own chalk

Layer+ writes: Map<Key, Value?>+ counts: Map<Value, int>+ shift(value, by)

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

CopyUndo logLayers
beginO(all keys)O(1)O(1)
getO(1)O(1)O(depth)
setO(1)O(1), and remembers the old valueO(depth), because count needs the old value
rollbackO(1)O(writes)O(1)
commitO(1)O(writes of the child)O(writes)
Others see uncommitted valuesYes: one mapYes: one mapNo: the slate is clean
Layers are the only one of the three that grows into several sessions. That is the reason to choose them.

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 layerMeaningget does
No entryI do not knowLook one layer down
Entry with a valueIt is thisStop, return it
Entry with nothingIt is goneStop, return nothing
A language trap: 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, and in to 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

CallTop layer sayscount red
2
begin, set tea bluered -1, blue +12 - 1 = 1
delete jamred -2, blue +10
rollbackgone2

Commit

What does it mean inside another one?

Two meanings

Python
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])
The same calls, two worlds. Ask before you write.
Edit and run it in your browser

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 get alone
  • Count by walking through all keys
  • Give set, delete and commit three ways to update counts
  • Use a flag inTransaction next 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