Build Your Own Database a show in 8 chapters
Goal: a store where every write it says yes to survives a crash, in about 240 lines of Go
1 of 8 Your guess
Before we start
You save something in an app, the power cuts out, and when it comes back the thing is still there. Something kept it safe through the crash. That something is a database.
At its smallest, which picture is closest to what a database is?
Pick the closest. You find out which fits at the end.
1977 − 1974 = 3 years to the first real customer
2 of 8 The problem
1974: three years before the first customer
In 1974 a team at IBM's research lab in San Jose began System R, a database you could ask questions in a new language, SQL, typed almost like English. It reached its first real customer, the aircraft-engine maker Pratt & Whitney, in 1977.
Most of those years went into the language and into answering fast. The rest went into two people changing the same row at once without one wiping out the other.
Almost none of it went into the one thing that makes a database more than a file: what you wrote is still there after a crash mid-write. That part is small.
You have read how real databases work but never built one. This project builds only that small part, as one Go file, and it ends up on your GitHub profile.
The machine has five parts. Each one arrives with what it does and a test whose number proves it works.
Your goal: a store where every write it says yes to is still there after a crash. Five parts, about 240 lines of Go.
db.Put("user:1", []byte("Alice"))
rec := encode(key, val, del)
4 + 4 + 4 + 6 + 5 = 23 bytes for user:1 = Alicethe crc covers the other 4 + 4 + 6 + 5 = 19 bytes
db.f.Write(rec)
the file was 0 bytes0 + 23 = 23, so the next write starts at byte 23
db.index[key] = off
db.Put("user:1", []byte("Alicia"))
cart:9 = socks: 12 + 6 + 5 = 23, at 23user:1 = Alicia: 12 + 6 + 6 = 24, at 4623 + 23 + 24 = 70 bytes
off, ok := db.index[key]
db.f.ReadAt(val, off+12+int64(klen))
46 + 12 header + 6 key bytes = 64: the value starts at byte 641 look in the index, 1 read of the file, however often user:1 was written
3 of 8 The idea
A file that only grows
Part 1 is three calls: Put stores a value under a key, Get reads it back, Delete forgets it. Behind them sits a table in memory, a Go map from key to value.
It is fast and it works, until the program stops.
Two keys in memory, nothing on disk.
Part 1 proof: the stage 1 test (Put, Get, an overwrite, Delete, a key never set) passes on a plain Go map.
Before anything reaches the disk, Put turns it into bytes. A byte is one small chunk of stored data, close to one character: "Alice" is 5 of them.
The record leads with the key's length and the value's length, so a reader knows where it ends. First of all comes a 4-byte fingerprint worked out from the rest. If any byte is missing or wrong, the fingerprint stops matching. That fingerprint is the crc.
Those first 12 bytes, the crc and the two lengths, are the record's header.
The 23 bytes are written at the end of one file. Counted from the file's first byte, the record starts at byte 0. That position is its offset.
The rule for this file: never edit, only add to the end. A file kept that way is an append-only log.
One small table in memory notes where each key's newest record starts: user:1 at 0. That table is the index.
The file holds the data. The index only holds where it is.
Two more Puts: cart:9 = socks, then user:1 changes to Alicia. The obvious move is to find Alice and write over her. The store doesn't. Alicia goes on the end, at 46, and only the index row moves, from 0 to 46.
Alice is still in the file, untouched, further back.
Why not overwrite Alice?
Adding to the end of a file is the fastest thing a disk does. Finding a spot in the middle and writing over it is one of the slowest. And the end is the only place a crash can leave half a record.
Part 2 proof: the stage 2 test: one Put makes the file exactly 23 bytes, three make 70, and Alice is still in the file.
Now Get user:1. The file holds two copies of it, and a file with a million writes can't be read end to end for every question.
So Get asks the index first. It says 46, the newest copy.
One read, straight to byte 64, 6 bytes: Alicia. No scanning, no matter how long the file grows.
The index lives in memory, so pulling the plug still wipes it. The file survives. Next chapter: get the index back from the file.
if h.Sum32() != crc { break }
break // torn tail: value never fully written
60 − 46 = 14 of Alicia's 24 bytes made itreplay stops at 46, so user:1 → 0, which is Alice
db.Put("user:2", []byte("Bob"))
Bob: 12 + 6 + 3 = 21 bytes, landed at 60, after the torn onesthe index says 46. A restart stops at 46 again and never reaches 60
db.f.Truncate(off)
cut back to 46, the end of the last whole recordBob lands at 46: 46 + 21 = 67 bytes, and a restart reads him back
4 of 8 Try it
Pull the plug
The program crashes. The index in memory is gone. The 70-byte file is all still there.
So on startup the store reads the file from its very first byte, one record at a time, and writes the index again from what it finds.
Press Play to read the file from byte 0.
Reading the whole file again, in order, on startup is what a database calls crash recovery, or replay.
Now the plug comes out while Alicia is being written: only 14 of her 24 bytes reach the file, which ends at 60.
Replay reads the header at 46, then tries to read the rest and runs off the end. A record cut short like this is a torn tail. Replay stops there and trusts everything before it.
user:1 reads Alice, and that is right: Put never said yes to Alicia, because she never fully reached the disk.
The store keeps going and takes a new write, user:2 = Bob. Replay stopped at 46, so the index notes 46. But the file still ends with the 14 torn bytes, and a file only adds at its end: Bob lands at 60.
Next restart, replay hits the torn bytes at 46 and stops again. Bob is never read back. A write the store said yes to, lost, with no error anywhere.
This is a real bug: the stage 3 test caught it in the lesson's own first version of kv.go.
The fix is one call at the end of replay: cut the file back to where the last whole record ended, before anything else is added.
Bob now lands at 46, right where the index says. Real write-ahead logs do the same on recovery.
The fix took kv.go from 237 lines to 242.
Part 3 proof: the stage 3 tests: a reopen gets every key back, a log cut to 60 bytes reopens as Alice, and the write after it survives one more restart.
db.Delete("cart:9")
4 + 4 + 4 + 6 = 18 bytes, no value bytes at all
db.append(key, nil, true)
70 + 18 = 88 bytes
delete(db.index, key)
if vlen == tombstone { delete(db.index, key) }
replay: at 23, cart:9 goes inat 70, the tombstone takes it out
break // torn tail: value never fully written
88 − 7 = 81 bytes left81 − 70 = 11 of the tombstone's 18replay stops at 70, so cart:9 → 23, which is socks
5 of 8 The fix
Delete by adding
Delete cart:9. You can't reach into the file and erase bytes: the whole point was never touching old ones. So a delete adds one more record.
Its value length is the largest number 4 bytes can hold, ff ff ff ff, which no real value uses. It means "this key is gone". That marker is a tombstone.
The tombstone goes on the end like any write, at 70. Nothing before it changes: socks is still at 23.
Then cart:9's row leaves the index. Get finds no row and says the key is not found, without touching the file.
Restart. Replay puts cart:9 in at 23, the way it did last chapter. Then at 70 it meets the tombstone and takes cart:9 out again, as if it had never been written.
Now cut the last 7 bytes off, in the middle of the tombstone. Replay stops at 70, so it never sees the delete. cart:9 is back, still socks.
That is the right answer: the delete never fully reached the disk, so the store never said yes to it, and replay must not invent it.
Part 4 proof: the stage 4 test: four writes make 88 bytes, the delete survives a reopen, and a torn tombstone brings cart:9 back.
dead: 23 + 23 + 18 = 64 of 88 bytes
os.Rename(tmp, db.path)
1 live record: 12 + 6 + 6 = 24 bytes88 − 24 = 64 bytes freed
db.f.Sync()
2,000 Puts took 7.495 s7.495 s ÷ 2,000 = 3.75 ms each2,000 ÷ 7.495 s = 267 writes a second
// db.f.Sync()
2,000 Puts took about 10 msthe timer read just under 10 ms: 203,513 writes a second203,513 ÷ 267 ≈ 762 times as many
3.75 ms ÷ 200 writes = 18.75 µs each · 200 writes every 3.75 ms = 53,333 a second, about 53,000
6 of 8 The cost
Shrink it, then time it
Every overwrite and every delete leaves old bytes in the file doing nothing. Of these four records only one is still read: user:1 = Alicia.
Given long enough, most of the file is dead weight.
Every so often the store writes a brand-new file holding only the newest live copy of each key, then gives it the old file's name. That is compaction, the only step that ever shrinks the file.
Why is the rename last?
A rename swaps the name over in one go. A crash leaves the old file or the new one, never half of each.
All five parts are in. One question left: how fast is it?
What changed
- File size: 88 → 24 bytes
Part 5 proof: the stage 5 test: compaction leaves 24 bytes, one live record, and the store still takes writes.
A file write first lands in the computer's memory, and the disk catches up a moment later. A crash in that moment loses it. So after every write, kv.go calls Sync: wait until the bytes really are on the flash. That call is an fsync.
Put says yes only after it. The lesson timed 2,000 Puts that way.
ms is a millisecond, a thousandth of a second.
Comment the Sync out and run the same loop. Hundreds of times faster, and both numbers are true.
What changed
- Writes a second: 267 → 203,513
A program crash still loses nothing: the bytes are already with the computer. A power cut loses the last few milliseconds of writes.
The project's board promises about 50,000 writes a second in its resume line. Real stores get there with both: they gather the writes that land within a millisecond and fsync once for all of them. That is group commit.
How many writes share one fsync?
µs is a microsecond, a thousandth of a ms. About 200 to a batch reaches the board's 50,000, and a busy server fills that in under a millisecond. It's the optional stage 6.
7 of 8 Your guess
Your picture now
Goal met: five parts, 242 lines of Go, and every write the store says yes to comes back after a crash. Which picture is closest now?
Pick one.
c is what you built: a log that only grows, and an index that points at each key's newest copy. a is the move the store refuses: writing over Alice in the middle of the file is slow. b is System R's years, spent on SQL and on many people editing at once, none of which keeping data through a crash needed.
8 of 8 Keep this
Keep this
Never touch an old byte, only add a new one. A small index remembers where each key's newest copy landed, and a restart reads the file again from byte 0.
The full lesson has the five stage test files, the byte dump, the fsync timer and how to put it on GitHub with a passing test badge.
Read the full lessonComing up Your store is one machine at one address, and that machine can crash. Next: put a front door before several identical servers, and build the load balancer that picks one for every visitor and never picks a dead one.