The replicated log was a Kafka all along: building a distributed database from scratch

Seven weeks ago I had a single append-only file and a hash index. This week I added a producer and a
consumer to the exact same replicated log that’s been running underneath every layer since, and nothing
about the log itself had to change. That’s not a coincidence I engineered — it’s the thing the whole
series was quietly building toward. A database, a consensus protocol, and a message queue are not three
different pieces of technology. They’re three different things you can do with one durable, ordered,
append-only sequence of records. This is the note that shows the one system, end to end, and the three
real bugs that rigorous testing surfaced along the way.

The system, one layer at a time

Week 7   Event log / Kafka reframe      producer appends, consumer replays from an offset
Week 6   Sharding across Raft groups    scale out without weakening consistency
Week 5   Linearizable KV on Raft        storage + consensus + consistency compose into a database
Week 3-4 Raft consensus (+ 3C)          election, replicated log, crash-recoverable persistence
Week 2   RPC + at-most-once dedup       the network lies; idempotency is how you stop believing it
Week 1   Storage engine (Bitcask)       an append-only log + a hash index that's just a cache of it

Every layer sits on the one below it, unmodified. raft and storage from Weeks 1–4 are byte-for-byte
the same code a kvraft KV store (Week 5), a shard router (Week 6), and a broker message queue
(Week 7) all build on. That’s the strongest claim in this whole note, and it’s falsifiable: go look.
Nothing above Week 4 ever edited raft.go’s core algorithm — the only changes across Weeks 5–7 were two
bug fixes, both liveness-only, both found by testing scenarios the original code never saw (more on that
below).

The concepts that showed up again and again

  • The log is the source of truth; everything else is a derived, rebuildable view of it. Week 1’s
    hash index is a cache of the log, rebuilt on every restart. Week 5’s KV map is a cache of the log too —
    just a Raft log instead of a local one. Week 7 makes this literal: the same log, read differently, IS
    a message queue. DDIA calls this turning the database inside out; by Week 7 it stopped being a clever
    phrase and started being just what the code does.
  • Idempotency via (ClientID, Seq), five times over. Week 2’s Clerk/KVServer dedup table. kvraft’s
    lastSeq. The broker’s produce dedup. Same two-field idempotency key, same reasoning every time: a
    network that can silently duplicate a request means something has to recognize “I’ve already done
    this,” and it has to be the receiver, not the sender’s good intentions.
  • Majority quorums are the one mechanism underneath leader election, commit safety, AND cluster
    sharding.
    A candidate needs a majority to become leader. A leader needs a majority to commit an
    entry. A shard’s replica group needs a majority to survive a partition. It’s the same arithmetic
    (N/2 + 1) solving three different-looking problems, because all three are really the same problem:
    “how do I make a decision that can’t be contradicted by whoever didn’t hear about it.”
  • The apply-loop pattern, unchanged from kvraft to broker. Propose via Start, wait on a channel
    registered for that log index, let a single dedicated goroutine drain applyCh and apply entries in
    order. kvraft applies to a map. The broker applies to an offset-addressable log instead. Same shape,
    different state machine — which is the entire definition of what “a state machine” means in this
    context, made concrete instead of abstract.
  • Reads don’t all need the same treatment, and knowing which kind you have is the actual skill.
    kvraft’s Get MUST go through the log — a stale leader or a lagging follower could legitimately be
    wrong. The broker’s Fetch must NOT need to — it only ever reads data that’s already been committed
    and applied, and Raft’s Log Matching Property guarantees a follower’s prefix can be behind but never
    wrong. Getting this distinction backwards in either direction is either a correctness bug or a
    needless latency tax; this series hit both mistakes in draft form before landing on the right answer
    each time.

Three bugs, and what they have in common

Each crown-jewel week shipped with its own tests green and -race clean. Each one still had a bug
waiting, found only once a later week asked something the original tests never did.

  1. Week 5 found a Week 3 bug. becomeFollower never reset the election timer, so a node demoted
    after merely seeing a higher term — not granting a vote, not hearing a real heartbeat — would
    re-campaign on the very next tick, cascading into seconds of pointless elections. Invisible to
    Week 3’s patient tests; caught because Week 5 imposed a tight client-facing timeout on top.
  2. Week 7 found two more, in the same two functions, for the same reason. startElection and
    advanceCommit both loop over “every OTHER peer” and silently assume there’s at least one — so a
    single-node Raft cluster could never elect a leader or commit anything. Nothing in four prior weeks
    had ever run Raft with n=1; a Week 7 test used one node for convenience and immediately hung.

All three are liveness bugs, never safety bugs — nothing was ever silently wrong, data was never lost or
duplicated, split-brain never happened. And all three share the identical lesson: a component passing
every test it has is not the same claim as a component with no bugs — it’s the claim that no bug has
been found by the specific inputs anyone has tried yet.
Six weeks in, the fix every time was small (one
line, one added call); the hard part was never the fix, it was noticing that a flaky test was reporting
a real finding and not a nuisance to be timed-out away.

Tradeoffs, made on purpose, across the whole series

  • No ReadIndex or leader lease (Week 5) — every read pays a full log round-trip. Correct by
    construction; the latency optimization is earned only after correctness is proven, not before.
  • No PreVote (Week 3/5) — the fix for the liveness bugs above was the minimal one for the specific
    pathology found, not the general etcd-style mechanism that prevents the whole class.
  • No consistent hashing (Week 6) — key2shard hashes on the first byte, which reshuffles almost
    everything when the group count changes. Consistent hashing fixes this at the cost of more mechanism
    than a “lighter build” needed to prove the point.
  • One partition, not many (Week 7) — a real Kafka topic spans partitions; this one reuses Week 6’s
    exact sharding pattern to get there, left undone on purpose so the capstone stayed a capstone and not
    a rewrite of Week 6 with different words.
  • The sharding controller isn’t fault-tolerant (Week 6) — a real one is its own tiny Raft group,
    which is also just… Raft, again, one more time, which is rather the point of stopping there.

None of these are oversights. Each is a place where the “lighter build, minimal impl” instruction was
honored on purpose, and each is a precisely nameable next step rather than a vague gesture at
“more could be done.”

Where this sits, now that there’s nowhere left for it to sit

Seven weeks, one system, no layer rewritten after it shipped — only two liveness bugs patched in place,
both found by exactly the kind of testing this series kept insisting on: not “did it pass,” but “did I
try to break the thing I’m claiming works.” The log that started as a single file with a hash index on
top is, unmodified underneath, now running a consensus protocol, a sharded database, and a message
broker. That’s the whole interview answer, if anyone asks what a distributed database actually is: it’s
a log, replicated for durability, applied in order for consistency, and read however the layer on top of
it needs to read it. Everything else is detail.


The final note in a series building a distributed database from scratch — storage → RPC → Raft → KV →
sharding → log, one system, revealed layer by layer.