~/kyle

Building a Distributed KV Store from Scratch #1

8 min read

Introduction

In this series, we will build a distributed key-value store from scratch. A key-value store is one of the simplest database models. You give it a key and a value, and you can retrieve or update the value by that key, or delete it. There are no tables, no schemas and no query language, just three simple operations: Get, Put and Delete.

That simplicity is exactly why systems like etcd, Consul and Redis sit underneath so much of today’s infrastructure. They hold configuration, service addresses, locks and session data, the small pieces of state that everything else depends on.

Make it work first!

Let’s start with the simplest version of a key-value store: a single-node server with in-memory storage.

 ┌────────┐   Get / Put / Delete   ┌─────────────────────────┐
 │ Client │ ─────────────────────▶ │ Server                  │
 └────────┘ ◀───────────────────── │                         │
                  value / OK       │   Memory                │
                                   │   ┌─────────┬─────────┐ │
                                   │   │ key     │ value   │ │
                                   │   ├─────────┼─────────┤ │
                                   │   │ user:1  │ alice   │ │
                                   │   │ user:2  │ bob     │ │
                                   │   └─────────┴─────────┘ │
                                   └─────────────────────────┘

This version is extremely simple to understand and to implement. It’s fast (of course) but… to be honest, no one would use it, because the data is gone as soon as the server crashes.

[Problem 1]

Memory-only storage loses all data when the server restarts.

Make it durable

We need a way to store data so the server still remembers it after a crash and restart.

The obvious answer is the disk. But writing the whole map to disk on every Put would be painfully slow. So instead, we only write down what changed.

Every Put and Delete is appended to the end of a file, one after another. This file is called a write-ahead log (WAL). “Write-ahead” because we write each change to the log before we apply it to the hash map.

 ┌────────┐   Put user:1 alice     ┌─────────────────────────┐
 │ Client │ ─────────────────────▶ │ Server                  │
 └────────┘ ◀───────────────────── │                         │
                     OK            │   Memory                │
                                   │   ┌─────────┬─────────┐ │
                                   │   │ user:1  │ alice   │ │  2. update the map
                                   │   └─────────┴─────────┘ │
                                   ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤
                                   │   Disk                  │
                                   │   wal.log               │  1. append to wal
                                   │   PUT    user:2 bob     │
                                   │   DELETE user:2         │
                                   │   PUT    user:1 alice   │
                                   └─────────────────────────┘

When the server restarts, it reads wal.log from the start and replays every record. The hash map comes back exactly as it was, because Put and Delete are deterministic: apply the same list of operations, in the same order, to two empty hash maps, and you always end up with the same two maps.

wal.log:  PUT a 1  ──▶  PUT b 2      ──▶  DELETE a

map 1:    {a:1}    ──▶  {a:1, b:2}   ──▶  {b:2}
map 2:    {a:1}    ──▶  {a:1, b:2}   ──▶  {b:2}     same order, same result

Record framing

But how do we store a record like {operation, key, value} in a file? And when we read it back, how do we know where one record ends and the next one begins? This problem is called record framing. The easiest solution is to put a special character, a delimiter, after each record. A newline (\n) is the obvious choice:

┌──────────────────┬────┬────────────────┬────┬───────────────┬────┐
│ PUT user:1 alice │ \n │ PUT user:2 bob │ \n │ DELETE user:2 │ \n │
└──────────────────┴────┴────────────────┴────┴───────────────┴────┘
                     ▲                     ▲                    ▲
                     └──── one record ends at each \n ──────────┘

Easy, right? Until someone stores a value that contains a newline:

Put("note", "hello\nworld")

PUT note hello \n world \n
               ▲         ▲
               │         └── the real end
               └── the reader stops here, and reads "world" as a new, broken record

[Problem 2]

A delimiter only works if it can never appear inside the data. Keys and values are arbitrary bytes, so any byte we pick can show up in a value.

Length-prefixed records

The solution is length-prefixed records. Instead of using a ‘magic’ character to mark where a record ends, we write down how long the key and the value are, right before each of them. The reader then reads the fields in a fixed order, and each length tells it exactly how many bytes to take next.

Each record now looks like this:

┌────┬──────────┬───────┬────────────┬─────────┐
│ op │ key_len  │  key  │ value_len  │  value  │
│ 1  │ 4 bytes  │  ...  │  4 bytes   │   ...   │
└────┴──────────┴───────┴────────────┴─────────┘
  op: 1 = Put, 2 = Delete

Here is Put("note", "hello\nworld") from before, byte by byte:

01                 op         = Put
00 00 00 04        key_len    = 4
6e 6f 74 65        key        = "note"
00 00 00 0b        value_len  = 11
68 65 6c 6c 6f 0a  value      = "hello\nworld"
77 6f 72 6c 64                        ▲
                                      └── just another byte, nobody cares
func encodeRecord(op byte, key, value []byte) []byte {
	buf := make([]byte, 0, 9+len(key)+len(value))
	buf = append(buf, op)
	buf = binary.BigEndian.AppendUint32(buf, uint32(len(key)))
	buf = append(buf, key...)
	buf = binary.BigEndian.AppendUint32(buf, uint32(len(value)))
	buf = append(buf, value...)
	return buf
}

A Delete has no value, so it writes value_len = 0 and nothing after it.

[Note]

key_len and value_len are fixed 4-byte unsigned integers, so a key or a value can be at most 2³² − 1 bytes, about 4 GiB. That sounds like plenty, but the limit has a sharp edge: uint32(len(value)) on a 5 GiB value doesn’t fail, it silently wraps around to 1 GiB. The record gets written with the wrong length, and replay reads garbage from that point on.

So the server checks sizes before anything touches the log, and the real limits are much smaller than 4 GiB: keys up to 10,000 bytes, values up to 4 MiB. That’s plenty for a KV store.

The page cache, and fsync

But there is a problem: writing to a file does not mean the data is on disk.

When we call write(), the OS doesn’t touch the disk at all. It just copies our bytes into the OS page cache, a chunk of memory the kernel uses to batch writes, and says “done!”. The real disk write happens later. Maybe a few seconds later.

 ┌────────────┐
 │   Server   │
 └─────┬──────┘
       │ write()   "done!"  ← returns right away
       ▼
 ┌──────────────────────────────────┐
 │  OS page cache        (memory)   │
 │  ┌────────────────────────────┐  │
 │  │ PUT user:1 alice           │  │  ← our record is HERE
 │  └────────────────────────────┘  │
 ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┤
 │        ...a few seconds later    │
 │              │ kernel flushes    │
 │              ▼                   │
 ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┤
 │  Disk                            │
 │  wal.log                         │  ← not here yet
 └──────────────────────────────────┘

So if the machine loses power in between… the record is gone. And we already told the client OK.

 write()          power loss            reboot
    │                 ⚡                    │
    ▼                 │                    ▼
 page cache: [PUT user:1 alice]  ──▶   page cache: [ ]    ← memory is wiped
 disk:       [ ]                       disk:       [ ]    ← never got it

 client: "OK"  ✓                       data: gone  ✗

The fix is fsync(). It tells the kernel: “flush this file to disk right now, and don’t come back until the disk has it.”

 ┌────────────┐
 │   Server   │
 └─────┬──────┘
       │ fsync()   ...waiting...   ← blocks until the disk confirms
       ▼
 ┌──────────────────────────────────┐
 │  OS page cache        (memory)   │
 │  ┌────────────────────────────┐  │
 │  │ PUT user:1 alice           │  │
 │  └────────────────────────────┘  │
 ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┤
 │              │ flush NOW         │
 │              ▼                   │
 ├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┤
 │  Disk                            │
 │  wal.log                         │
 │  PUT user:1 alice                │  ← safe. now we can say OK
 └──────────────────────────────────┘

So every Put and Delete goes in this exact order:

func (e *walEngine) Put(key, value []byte) error {
	e.mu.Lock()
	defer e.mu.Unlock()

	e.file.Write(encodeRecord(opPut, key, value)) // 1. lands in the page cache
	e.file.Sync()                                 // 2. wait for the disk
	e.storage[string(key)] = value                // 3. update the map
	return nil                                    // 4. reply OK
}

The price

Problem solved! Now our key-value store is durable, but fsync is slow. On my laptop’s NVMe drive, one fsync takes about 2 ms, so the server drops from 19,000 writes per second to around 400.

clientsin memorywal, fsync every write
ops/sp50 / p99 msops/sp50 / p99 ms
119,2660.05 / 0.124112.37 / 3.97
895,6510.07 / 0.3342818.16 / 24.64
64135,8080.36 / 2.17419146.50 / 514.12

Throughput stays at ~400 writes per second no matter how many clients we add, while latency grows with them: about 2.3 ms × the number of clients. Why? Because every write holds the lock while it waits for its own fsync. Everyone else just stands in line:

time ------------------------------------------------------------------>

A  lock[write|fsync]unlock
B  .... waiting ..........lock[write|fsync]unlock
C  .... waiting .................................lock[write|fsync]unlock

[Problem 3]

Calling fsync() after every write makes the system too slow. How can we fix that?

[Problem 4]

wal.log only ever grows. A key updated a million times leaves a million records behind, and every restart replays all of them, even though only the last one matters.

Recap

What we went through:

  • Memory is fast, but it forgets everything on a crash.
  • Replaying the same operations in the same order always gives the same map.
  • A delimiter breaks as soon as it shows up inside the data. Length-prefixed records don’t care what’s inside.
  • write() only reaches the page cache. Only fsync() reaches the disk.
  • Durability isn’t free: from 19,000 writes per second down to ~400.

Open problems:

  • Problem 3: one fsync per write.
  • Problem 4: the log grows forever.

See you in part 2.