System Design

C13

Message queue

A durable, ordered log that many producers append to and many consumer groups read at their own pace. The hard parts are the disk layout, which replicas count as in sync, and what a leader's death can lose.

Not startedSaved in this browser only.
  1. 1Each partition is an append-only log in segment files with a sparse offset index. Appends and reads are sequential, so one broker moves hundreds of MB a second.
  2. 2A leader per partition takes writes. Followers fetch, and the high watermark is the smallest log end in the in-sync replica set.
  3. 3acks=all with min.insync.replicas = 2 and clean elections loses no acknowledged write. acks=1 loses the unreplicated tail at every leader death.
  4. 4Consumer groups split partitions among members and commit offsets. A rebalance replays from the last commit, so handlers stay idempotent.
C13
    A

    The prompt

    as the interviewer says it
    "Design a message queue: producers append, consumers read in order, and messages survive a broker dying."
    questionanswer assumed
    How many messages?10 billion a day; 3× the average at peak.
    How large?1 KB on average, 1 MB at most.
    Order?Per key: all events of one order stay in order.
    How long kept?7 days, so a new reader can replay.
    Who reads?About 5 consumer groups per topic, each at its own pace.
    Loss budget?No acknowledged message lost when 1 broker dies.
    Exactly once?At least once, with idempotent producers; transactions are a follow-up.

    I clarify throughput, message size, retention, ordering and the loss budget, because each changes partitions, replicas or acks.

    B

    Requirements

    as numbers
    functional
    Create topics with N partitions.
    Append a record with a key; get back partition and offset.
    Read a partition from any retained offset.
    Consumer groups with committed offsets.
    Delete by age or size; or keep the last value per key.
    non-functionaltarget
    Peak append rate≈ 347,000 messages/s
    Acknowledged messages lost, 1 broker down0
    Produce latency, acks=allp99 < 50 ms in one region
    OrderPer partition, the same for every reader
    Failoverseconds, no operator

    An acknowledged message survives one broker death, and readers see one partition in one order, always.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Messages10¹⁰ a day ÷ 86,400 s≈ 116,000/s; 3× peak ≈ 347,000/s
    Ingress347,000/s × 1 KB≈ 347 MB/s at peak
    Disk writes347 MB/s × 3 replicas≈ 1,042 MB/s for the cluster
    Egress116 MB/s × 5 groups≈ 579 MB/s average
    Storage10 TB a day × 7 days × 3 replicas210 TB
    Brokers210 TB ÷ 12 TB each (a choice)18 brokers; ≈ 58 MB/s each at peak
    Partitions347,000/s ÷ 5,000/s per consumer (to load test)≈ 70; round to 72, 4 leaders per broker

    Inputs are the assumed answers in panel A. One lab log on a laptop appended 398 MB/s in batches of 1,000, so 58 MB/s per broker leaves room. Method: R2.

    About 347,000 messages a second at peak, 210 TB on disk after 3 copies, so 18 brokers are set by storage, not by throughput.

    D

    API

    shown as HTTP; the wire protocol is binary over TCP
    callsuccesserrorsretry safe?
    POST /v1/topics/{t}/records?acks=all {key, value, producer_id, seq}200 partition, offset413, 503 not leader, 503 not enough replicasYes: (producer_id, seq) dedupes
    GET /v1/topics/{t}/partitions/{p}/records?offset=&max_bytes=200 records, high watermark416 offset out of rangeYes: a read
    POST /v1/groups/{g}/join {member_id, topics}200 partitions, generation409 rebalanceYes: rejoins
    POST /v1/groups/{g}/offsets {generation, partition: offset}204409 stale generationYes: last write wins
    GET /v1/topics/{t}/metadata200 leader and ISR per partition404Yes
    • Clients cache metadata and talk to each partition's leader directly. A "not leader" error makes them refresh it.
    • A commit carries the group generation. A member that missed a rebalance cannot overwrite the new owner's offset.

    Produce returns a partition and offset. Fetch takes an offset and returns records below the high watermark. Groups commit the next offset to read.

    E

    Data model

    the log on disk, and the metadata
    orders-3/ on one broker · 14 segments in the lab run00000000.log0 to 7,19900007200.log7,200 to 14,39900014400.log14,400 to 21,59900021600.logactive: takes appends…closed segments never change; retention deletes the oldest file wholeOne record on diskoffset8 Bsize4 Bcrc4 Bepoch4 Bproducer4 Bseq4 Bkey len4 Bkey9 Bvalue len4 Bvalue100 B36 B of framing per record; the CRC finds a torn write after a crashSparse index: one entry per 4,096 B of recordsoffset → byte position21,600 → 021,629 → 4,20521,658 → 8,41021,687 → 12,615read: binary search, jump to the entry, scan 14 records on average (max 28)
    storekeyvalue
    Segment fileoffsetRecords in offset order, appended only
    Offset indexoffsetByte position, one entry per 4 KB
    Metadata logtopic, partitionReplicas, leader, leader epoch, ISR
    Offsets topicgroup, topic, partitionNext offset to read; compacted
    Producer stateproducer IDLast sequence numbers, rebuilt from the log
    • A record never moves. Its offset is its address for its whole life.
    • In the lab, 100,000 records of 100 B filled 14 segments of 1 MB and 3,458 index entries: 27,664 bytes of index for 14.5 MB of log.
    • The index is small enough to keep in memory, so a lookup costs no disk read.

    Each partition replica is a directory of segment files named by base offset, each with a sparse index. The controller keeps leader, epoch and ISR per partition.

    F

    The architecture

    click a step; its path lights up
    Producerskey → partitionControllersRaft quorum, metadataBroker 1leader of P0Broker 2follower of P0Broker 3follower of P0Consumer groupa member per partitionOffsets topiccompacted

    Step 1: Produce

    • The producer hashes the key to pick a partition, and sends to that partition's leader.
    • It batches records per partition for a few milliseconds and compresses each batch.
    • Each record carries a producer ID and sequence number, so a retry is not stored twice.

    If it fails

    The leader is gone: the producer refreshes metadata and retries to the new leader. The sequence number makes the retry safe.

    Producers write to the partition leader, followers fetch, and the leader acknowledges once the high watermark passes the write. The controller moves leadership when a broker dies.

    G

    Capabilities used

    what each part gives you
    toolcapabilitywhat it gives this designalso used for
    BrokerAppend-only segment files, one write per batchSequential disk writes; old data is deleted a file at a time.Databases' write-ahead logs
    BrokerSparse offset indexFind any offset with two binary searches and a scan under 4 KB.LSM block indexes
    BrokerLeader, followers, ISR, high watermarkA write is committed once every in-sync copy has it.Raft logs, database replication
    BrokerLeader epochsA returning replica finds where its log diverges and cuts the tail.Raft terms, fencing tokens
    BrokerProducer ID and sequence numbersA retried batch is stored once.Idempotency keys
    OS page cacheWrites land in memory; reads of recent data hit memoryConsumers near the tail never touch the disk.Any file-backed store
    sendfile(2)File to socket inside the kernelFetch responses skip a copy through the broker process.Web servers, CDNs
    Raft quorumA replicated metadata logOne controller decides leaders; no split brain (X5).etcd, service discovery
    Consumer groupPartition assignment, committed offsetsWork spreads over members; a new owner resumes at the commit.Stream processors

    The file system gives me cheap appends and sendfile. Replication gives me durability without an fsync per write. A Raft quorum owns the metadata.

    H

    Deep dive: the log on disk

    why a broker moves hundreds of MB a second
    layoutstatuscost
    One file per messageNot approvedMillions of files; a metadata write per message.
    A table with a B-treeSmall volumeRandom page writes and vacuum; see the Postgres queue in B6.
    One big file per partitionNot approvedRetention must rewrite or punch holes in it.
    Segments plus a sparse indexApprovedSequential appends; delete a whole file to expire data.
    batchno fsyncfsync per batch
    1217,000/s · 21.7 MB/s50/s
    10986,000/s · 98.6 MB/s500/s
    1002,441,000/s · 244.1 MB/s4,939/s
    1,0003,982,000/s · 398.2 MB/s47,534/s

    Lab: one log, 100 B values, median of 3 runs of 1 s on a laptop SSD. The laptop's fsync flushes the drive cache, about 20 ms each; server disks with power-loss protection flush far faster.

    append and readpseudo code
    append(batch):                          // leader or follower
      IF active segment + batch > segment size:
        roll: open a new segment named by the next offset1
      write the batch at the end of the file  // one write call2
      every 4 KB written: add (offset, position) to the index3
      IF fsync per write: fsync               // else replicas carry durability4
    
    read(from, max):
      segment = last segment with base <= from   // binary search
      entry   = last index entry with offset <= from
      scan forward from entry.position to from5   // under 4 KB
      RETURN up to max records                   // sendfile to the socket6
    1. 1The file name is the first offset in it, so finding a file is a binary search on names.
    2. 2A batch costs one system call. In the lab, batches of 100 appended 11 times faster than single records.
    3. 3Sparse: one entry per 4 KB, not per record, so the index for a 1 GB segment is about 2 MB.
    4. 4Brokers usually leave flushing to the OS. A write is safe when other brokers hold it, not when one disk does.
    5. 5Less than one index interval: the lab scanned 14 records on average.
    6. 6The kernel copies page cache to the socket. The bytes never enter the broker process, and the format on disk is the format on the wire.
    Tested source Go: record format · Go: append · Go: read
    Go: record formatgo
    
    // Each record on disk is a 12-byte header (offset int64, size uint32) and a body of `size` bytes:
    // crc uint32 over the rest of the body, epoch int32, producer uint32, seq int32, key length int32
    // (-1 for nil), key, value length int32 (-1 for nil), value. The CRC finds a torn write after a
    // crash.
    const (
      headerBytes = 8 + 4
      bodyFixed   = 4 + 4 + 4 + 4 + 4 + 4
      // Overhead is the bytes a record costs on disk beyond its key and value.
      Overhead = headerBytes + bodyFixed
    )
    
    // indexEntry maps an offset (relative to the segment base) to a byte position in the segment.
    // The index is sparse: one entry every IndexEvery bytes, so it stays small enough for memory.
    type indexEntry struct {
      rel uint32
      pos uint32
    }
    
    Go: appendgo
    
    // Append writes a batch at the end of the log with one write call, then one fsync when Sync is
    // on. Records whose Offset is -1 get the next offsets (a leader); others must continue the log
    // exactly (a follower copying the leader). It returns the first offset of the batch.
    func (l *Log) Append(recs []Record) (int64, error) {
      if len(recs) == 0 {
        return l.next, nil
      }
      first := l.next
      var buf []byte
      sizes := make([]int64, len(recs))
      for i := range recs {
        if recs[i].Offset == -1 {
          recs[i].Offset = l.next + int64(i)
        } else if recs[i].Offset != l.next+int64(i) {
          return 0, fmt.Errorf("append at %d: record has offset %d", l.next+int64(i), recs[i].Offset)
        }
        before := len(buf)
        buf = encode(buf, recs[i])
        sizes[i] = int64(len(buf) - before)
      }
      s := l.segs[len(l.segs)-1]
      if s.size > 0 && s.size+int64(len(buf)) > l.opt.SegmentBytes {
        var err error
        if s, err = l.roll(); err != nil {
          return 0, err
        }
      }
      if _, err := s.log.WriteAt(buf, s.size); err != nil {
        return 0, fmt.Errorf("append to segment %d: %w", s.base, err)
      }
      pos, entries := s.size, len(s.index)
      for i, r := range recs {
        s.noteRecord(l, r, pos, sizes[i])
        pos += sizes[i]
      }
      s.size = pos
      l.next = s.next
      if len(s.index) > entries {
        var ib []byte
        for _, e := range s.index[entries:] {
          ib = binary.BigEndian.AppendUint32(ib, e.rel)
          ib = binary.BigEndian.AppendUint32(ib, e.pos)
        }
        if _, err := s.idx.WriteAt(ib, int64(8*entries)); err != nil {
          return 0, fmt.Errorf("append to index %d: %w", s.base, err)
        }
      }
      if l.opt.Sync {
        if err := s.log.Sync(); err != nil {
          return 0, fmt.Errorf("fsync segment %d: %w", s.base, err)
        }
      }
      return first, nil
    }
    
    Go: readgo
    
    // Read returns up to max records from offset `from`. It finds the segment by binary search on
    // the base offsets, then the closest index entry at or below `from`, then scans forward.
    func (l *Log) Read(from int64, max int) ([]Record, ReadStats, error) {
      var st ReadStats
      if from == l.next {
        return nil, st, nil
      }
      if from < l.Start() || from > l.next {
        return nil, st, fmt.Errorf("read %d of [%d, %d): %w", from, l.Start(), l.next, ErrOutOfRange)
      }
      si := sort.Search(len(l.segs), func(i int) bool { return l.segs[i].base > from }) - 1
      var out []Record
      for ; si < len(l.segs) && len(out) < max; si++ {
        s := l.segs[si]
        var pos int64
        if len(out) == 0 {
          rel := uint32(from - s.base)
          ei := sort.Search(len(s.index), func(i int) bool { return s.index[i].rel > rel }) - 1
          st.Segment, st.IndexEntry = s.base, s.base
          if ei >= 0 {
            pos = int64(s.index[ei].pos)
            st.IndexEntry = s.base + int64(s.index[ei].rel)
          }
        }
        buf := make([]byte, s.size-pos)
        if _, err := s.log.ReadAt(buf, pos); err != nil {
          return nil, st, fmt.Errorf("read segment %d: %w", s.base, err)
        }
        for p := 0; p < len(buf) && len(out) < max; {
          r, n, err := decode(buf[p:])
          if err != nil {
            return nil, st, fmt.Errorf("segment %d at byte %d: %w", s.base, pos+int64(p), err)
          }
          p += n
          if r.Offset < from {
            st.SkipRecords++
            st.SkipBytes += int64(n)
            continue
          }
          out = append(out, r)
        }
      }
      return out, st, nil
    }
    

    I append batches to segment files and keep a sparse index. Batching moves the cost from per message to per batch: 50 appends a second with an fsync each, 48,000 with one fsync per 1,000.

    I

    Deep dive: replication and acks

    what each setting can lose
    settingfailovers that lost acked writesacked writes lostcoststatus
    acks=0200 of 200612No answer, so no retryMetrics you can drop
    acks=1189 of 200422Loses the unreplicated tailLoss is fine
    acks=all, min ISR 10 of 2000110 ticks offlineDowntime is fine
    acks=all, min ISR 1, unclean11 of 20025No downtimeNot approved
    acks=all, min ISR 20 of 20003.8% of writes refusedApproved

    Lab: 3 replicas on disk, 200 seeded failovers per row. Each tick the producer sends 1 to 3 records and each follower fetches with probability 0.8. The leader dies after its appends, before the fetches.

    topic orders · 6 partitions · 3 replicas eachP0P1P2P3P4P5Broker 1leadercopycopyleadercopycopyBroker 2copyleadercopycopyleadercopyBroker 3copycopyleadercopycopyleaderproducers and consumers talk only to each partition's leader
    • Each broker leads some partitions and follows others, so writes spread over every broker.
    • The replicas of one partition sit in different racks or zones. One zone failure leaves 2 copies.
    • acks=all adds one follower fetch to each write: about one network round trip inside a region.
    • Producers send to leaders only. Consumers also read from leaders, unless they choose a nearby follower.
    produce, fetch, high watermarkpseudo code
    produce(record, acks):                  // on the leader
      IF acks = all AND size(ISR) < min.insync.replicas:
        RETURN NOT_ENOUGH_REPLICAS1            // nothing is written
      IF (producer, seq) is in the log: RETURN its offset2
      offset = append(record, epoch)
      acks = 0 or 1: answer now3
      acks = all:    answer once HW > offset4
    
    fetch(follower f, from):                  // from = f's LEO
      LEO[f] = from5
      IF f holds all the leader sent it last time: caught_up[f] = now
      HW = min(LEO of every ISR member)6
      RETURN records after from, and HW
    
    every tick:
      drop f from ISR IF now - caught_up[f] > replica.lag.time.max7
    1. 1Refuse instead of acknowledging on fewer copies than promised. The producer retries.
    2. 2An idempotent producer: a retry after a lost answer returns the first offset. The lab wrote 0 duplicates.
    3. 3With acks=1 the record is on one disk, in the page cache. The leader's death loses it.
    4. 4Every ISR member has the record, so any clean new leader has it.
    5. 5The fetch offset is the follower's ack: it holds everything before it.
    6. 6A follower outside the ISR does not hold the HW back. That is why the ISR shrinks.
    7. 7Measured in time, not in records, so a burst of writes does not push healthy followers out.
    Tested source Go: produce · Go: fetch · Go: high watermark
    Go: producego
    
    // Produce appends one record on the leader and returns its offset. With acks=all it refuses the
    // write while the ISR is smaller than MinISR. The caller treats an acks=all write as
    // acknowledged only once HW passes its offset. A retried record (same producer and seq) is not
    // appended again: the leader returns the offset it already has.
    func (p *Partition) Produce(r Record, acks Acks) (int64, error) {
      if p.leader < 0 || !p.Reps[p.leader].Up {
        return -1, ErrNoLeader
      }
      if acks == AcksAll && len(p.isr) < p.cfg.MinISR {
        return -1, fmt.Errorf("isr %v, min %d: %w", p.isr, p.cfg.MinISR, ErrNotEnoughReplicas)
      }
      if off, ok := p.seqs[r.Producer][r.Seq]; ok && r.Seq >= 0 {
        return off, nil // a retry of a write the log already holds
      }
      r.Offset, r.Epoch = -1, p.epoch
      recs := []Record{r}
      off, err := p.Reps[p.leader].Log.Append(recs)
      if err != nil {
        return -1, fmt.Errorf("leader append: %w", err)
      }
      p.noteSeq(recs[0])
      p.advanceHW()
      return off, nil
    }
    
    Go: fetchgo
    
    // Fetch has follower f copy the next records from the leader. The fetch offset tells the leader
    // how far f has got, which moves the HW. The answer carries the leader's HW, so a follower's HW
    // trails the leader's by one fetch.
    func (p *Partition) Fetch(f int) (FetchResult, error) {
      var res FetchResult
      fr := p.Reps[f]
      if !fr.Up {
        return res, ErrReplicaDown
      }
      if p.leader < 0 || p.leader == f || !p.Reps[p.leader].Up {
        return res, ErrNotLeaderOrStopped
      }
      ld := p.Reps[p.leader]
      if fr.truncate { // after a leader change: cut what the new leader does not have
        end := ld.Log.EndFor(fr.Log.LastEpoch())
        if leo := fr.Log.LEO(); leo > end {
          if err := fr.Log.Truncate(end); err != nil {
            return res, err
          }
          res.Truncated = leo - end
          fr.HW = min(fr.HW, end)
        }
        fr.truncate = false
      }
      res.From = fr.Log.LEO()
      p.known[f] = res.From
      if res.From >= p.lastEnd[f] { // f has all the leader had when it last answered f
        p.caughtUp[f] = p.tick
      }
      if !slices.Contains(p.isr, f) && res.From >= ld.HW {
        p.isr = append(p.isr, f) // caught up to the HW again: back in the ISR
        slices.Sort(p.isr)
        p.caughtUp[f] = p.tick
      }
      p.advanceHW()
      recs, _, err := ld.Log.Read(res.From, p.cfg.FetchMax)
      if err != nil {
        return res, fmt.Errorf("leader read: %w", err)
      }
      if _, err := fr.Log.Append(recs); err != nil {
        return res, fmt.Errorf("follower append: %w", err)
      }
      res.Got = len(recs)
      p.lastEnd[f] = ld.Log.LEO()
      fr.HW = max(fr.HW, min(ld.HW, fr.Log.LEO()))
      return res, nil
    }
    
    Go: high watermarkgo
    
    // advanceHW sets the leader's HW to the smallest LEO in the ISR. A follower outside the ISR
    // does not hold it back, and the HW never moves down.
    func (p *Partition) advanceHW() {
      ld := p.Reps[p.leader]
      hw := ld.Log.LEO()
      for _, f := range p.isr {
        if f == p.leader {
          continue
        }
        if p.known[f] < 0 {
          return // a new leader has not heard from this follower yet
        }
        hw = min(hw, p.known[f])
      }
      ld.HW = max(ld.HW, hw)
    }
    

    I use acks=all, min.insync.replicas = 2 on 3 replicas, and clean elections only. An acknowledged write is then on at least 2 brokers.

    J

    See it: four failovers, record by record

    recorded from the lab partition on disk

    The leader acknowledges after its own append, then dies before the followers fetch the last three writes.

    acks=1 · min.insync.replicas=2 · unclean election off · epoch 0

    replica
    B1leaderin ISRHW 0 · LEO 2
    B2followerin ISRHW 0 · LEO 0
    B3followerin ISRHW 0 · LEO 0

    below the HW: consumers can read it above the HW: not yet on every ISR membere0, e1 the leader epoch that wrote it

    producerm1 acknowledgedm2 acknowledged
    B1 appends m1 and m2 at offsets 0 and 1. With acks=1 it acknowledges each one after its own append.

    Each replica is a directory of real segment files. A restart reopens the files and checks every record's CRC before the replica fetches again.

    Under acks=1 the new leader never had the tail, so acknowledged writes vanish. Under acks=all the producer was never told those writes were safe, and it retries them.

    K

    Deep dive: leader failover

    the controller and the leader epoch
    methodstatuswhy
    Each broker elects itself when the leader is silentNot approvedTwo brokers both lead after a partition.
    A controller with its state in ZooKeeperOlder clustersWorks; the controller reloads all metadata when it changes.
    A Raft quorum of controllers (KRaft)ApprovedThe metadata is a replicated log; a standby controller has it already.
    Follower truncates to the HW on restartRare double failuresThe older rule can lose or mix records when two leaders change quickly.
    Follower truncates by leader epochApprovedAsks where its last epoch ends on the leader, then cuts exactly there.
    • Failover time is detection plus election plus clients refreshing metadata. Detection, a broker's session timeout, takes the longest.
    • The last ISR member stays in the ISR when it dies. It may hold writes that nobody else has, so a clean election waits for it.
    • The controller spreads leaders over brokers, so one death moves only that broker's share.
    controller and truncationpseudo code
    on broker death:                       // the controller quorum1
      remove dead replicas from ISR, but keep the last one2
      IF the leader is dead:
        IF a live replica is in ISR: leader = it          // clean
        ELSE IF unclean election is on: leader = any live replica3
        ELSE: offline until an ISR member returns
        epoch = epoch + 14
        write (leader, epoch, ISR) to the metadata log
    
    follower, after a leader change:
      end = the leader's end offset for my last epoch
      truncate my log to end5                  // drop the stale tail
      fetch as usual
    1. 1One controller decides at a time, and its decisions are entries in a Raft log. X5 covers the election.
    2. 2Otherwise an empty ISR would let any replica lead and lose acknowledged writes.
    3. 3Unclean election: availability over durability. The lab lost writes this way in 11 of 200 failovers.
    4. 4Every record carries the epoch of the leader that wrote it. A deposed leader's requests carry an old epoch and are refused.
    5. 5Records past that point were never committed, so no acks=all producer was told they were safe.
    Tested source Go: controller · Go: fetch, with truncation
    Go: controllergo
    
    // Controller runs when the controller notices a broker died. It removes dead replicas from the
    // ISR. If the leader is dead it picks the first live ISR member as the new leader in a new
    // epoch. With no live ISR member the partition goes offline, unless unclean election is on.
    func (p *Partition) Controller() (Election, error) {
      // The last ISR member stays in the ISR even when it is dead: it may hold acknowledged writes
      // that no other replica has, so a clean election waits for it.
      if live := slices.DeleteFunc(slices.Clone(p.isr), func(i int) bool { return !p.Reps[i].Up }); len(live) > 0 {
        p.isr = live
      }
      if p.leader >= 0 && p.Reps[p.leader].Up {
        p.advanceHW()
        return Election{Leader: p.leader, Epoch: int(p.epoch)}, nil
      }
      next, unclean := -1, false
      if p.Reps[p.isr[0]].Up {
        next = p.isr[0]
      } else if p.cfg.Unclean {
        for _, r := range p.Reps {
          if r.Up {
            next, unclean = r.ID, true
            break
          }
        }
      }
      p.leader = next
      if next < 0 {
        return Election{Leader: -1, Epoch: int(p.epoch), Offline: true}, nil
      }
      p.epoch++
      if unclean {
        p.isr = []int{next}
      }
      for _, r := range p.Reps {
        r.truncate = r.ID != next
        p.known[r.ID], p.lastEnd[r.ID] = -1, 0
        p.caughtUp[r.ID] = p.tick
      }
      ld := p.Reps[next]
      ld.HW = min(ld.HW, ld.Log.LEO())
      if err := p.loadSeqs(); err != nil {
        return Election{}, err
      }
      return Election{Leader: next, Epoch: int(p.epoch), Unclean: unclean}, nil
    }
    
    Go: fetch, with truncationgo
    
    // Fetch has follower f copy the next records from the leader. The fetch offset tells the leader
    // how far f has got, which moves the HW. The answer carries the leader's HW, so a follower's HW
    // trails the leader's by one fetch.
    func (p *Partition) Fetch(f int) (FetchResult, error) {
      var res FetchResult
      fr := p.Reps[f]
      if !fr.Up {
        return res, ErrReplicaDown
      }
      if p.leader < 0 || p.leader == f || !p.Reps[p.leader].Up {
        return res, ErrNotLeaderOrStopped
      }
      ld := p.Reps[p.leader]
      if fr.truncate { // after a leader change: cut what the new leader does not have
        end := ld.Log.EndFor(fr.Log.LastEpoch())
        if leo := fr.Log.LEO(); leo > end {
          if err := fr.Log.Truncate(end); err != nil {
            return res, err
          }
          res.Truncated = leo - end
          fr.HW = min(fr.HW, end)
        }
        fr.truncate = false
      }
      res.From = fr.Log.LEO()
      p.known[f] = res.From
      if res.From >= p.lastEnd[f] { // f has all the leader had when it last answered f
        p.caughtUp[f] = p.tick
      }
      if !slices.Contains(p.isr, f) && res.From >= ld.HW {
        p.isr = append(p.isr, f) // caught up to the HW again: back in the ISR
        slices.Sort(p.isr)
        p.caughtUp[f] = p.tick
      }
      p.advanceHW()
      recs, _, err := ld.Log.Read(res.From, p.cfg.FetchMax)
      if err != nil {
        return res, fmt.Errorf("leader read: %w", err)
      }
      if _, err := fr.Log.Append(recs); err != nil {
        return res, fmt.Errorf("follower append: %w", err)
      }
      res.Got = len(recs)
      p.lastEnd[f] = ld.Log.LEO()
      fr.HW = max(fr.HW, min(ld.HW, fr.Log.LEO()))
      return res, nil
    }
    

    A Raft quorum of controllers elects a new leader from the ISR and bumps the epoch. The lab's Raft elects a leader in a median 157 ms; detection takes longer.

    L

    Deep dive: consumer groups

    who reads which partition
    methodstatuseffect
    Eager rebalance: revoke all, assign againSmall groupsThe whole group stops each time.
    Cooperative sticky assignmentApprovedOnly moved partitions stop.
    Static membershipRolling restartsA restart within the timeout moves nothing.
    Commit before the workNot approvedA crash skips messages: at most once.
    Commit after the workApprovedA crash replays: at least once.

    In the B6 simulation, 6 partitions, commits every 5 s: one crash replayed 60 messages, and 1 member sat idle once members outnumbered partitions.

    Each partition goes to one member of a group. A crash costs a session timeout plus a replay since the last commit, so the handler must be idempotent.

    M

    Retention and compaction

    how a topic forgets
    policykeepslab result
    Delete, by sizeThe newest segments under the limit10 of 14 files deleted; start offset 72,000
    CompactThe newest record per key20,000 → 1,000 records; 2.9 MB → 145 KB
    TieredRecent segments local, old ones in object storageCheaper long retention (B9)
    retain and compactpseudo code
    retain(max_bytes):
      WHILE log > max_bytes AND more than 1 segment:
        delete the oldest segment file1        // no rewrite
    
    compact():                                // a background cleaner
      newest = key -> newest offset, over the whole log
      FOR EACH closed segment:
        keep record r only IF newest[r.key] = r.offset
        rewrite the segment; offsets stay as they were2
    1. 1Expiry is a file delete. No record is read or rewritten.
    2. 2A compacted log has gaps. A consumer at any offset still gets the next record left.
    Tested source Go: retain and compact
    Go: retain and compactgo
    
    // Retain deletes whole segments, oldest first, while the log is larger than maxBytes. The active
    // segment always stays. Deleting a file is cheap: no record is rewritten.
    func (l *Log) Retain(maxBytes int64) (int, error) {
      removed := 0
      for len(l.segs) > 1 && l.Bytes() > maxBytes {
        if err := l.remove(l.segs[0]); err != nil {
          return removed, err
        }
        l.segs = l.segs[1:]
        removed++
      }
      return removed, nil
    }
    
    // CompactStats is what one compaction pass did.
    type CompactStats struct {
      RecordsBefore int   `json:"records_before"`
      RecordsAfter  int   `json:"records_after"`
      BytesBefore   int64 `json:"bytes_before"`
      BytesAfter    int64 `json:"bytes_after"`
    }
    
    // Compact keeps, in every closed segment, only the newest record of each key. Offsets do not
    // change, so a consumer's position stays valid; the log just has gaps. A tombstone stays as the
    // newest record of its key, so readers learn about the delete.
    func (l *Log) Compact() (CompactStats, error) {
      var st CompactStats
      newest := map[string]int64{}
      all, err := l.All()
      if err != nil {
        return st, err
      }
      for _, r := range all {
        if r.Key != nil {
          newest[string(r.Key)] = r.Offset
        }
      }
      st.RecordsBefore, st.BytesBefore = len(all), l.Bytes()
      for _, s := range l.segs[:len(l.segs)-1] {
        recs, _, err := l.readSegment(s)
        if err != nil {
          return st, err
        }
        var buf []byte
        s.index, s.sinceIndex, s.records = nil, 0, 0
        for _, r := range recs {
          if r.Key != nil && newest[string(r.Key)] != r.Offset {
            continue
          }
          before := len(buf)
          buf = encode(buf, r)
          s.noteRecord(l, r, int64(before), int64(len(buf)-before))
        }
        s.next = s.base
        if len(recs) > 0 {
          s.next = recs[len(recs)-1].Offset + 1
        }
        if err := s.log.Truncate(0); err != nil {
          return st, fmt.Errorf("rewrite segment %d: %w", s.base, err)
        }
        if _, err := s.log.WriteAt(buf, 0); err != nil {
          return st, fmt.Errorf("rewrite segment %d: %w", s.base, err)
        }
        s.size = int64(len(buf))
        if err := s.writeIndex(); err != nil {
          return st, err
        }
      }
      after, err := l.All()
      if err != nil {
        return st, err
      }
      st.RecordsAfter, st.BytesAfter = len(after), l.Bytes()
      return st, nil
    }
    

    Delete retention drops whole segment files by age or size. Compaction keeps the newest record per key: 20,000 updates of 1,000 keys shrank to 1,000 records.

    N

    Failure cases

    what breaks, and what stays correct
    eventresultwhy it is safesaved by
    A partition leader diesA live ISR member leads in a new epoch.Every acks=all write is below the HW, so the new leader has it.ISR, HW
    A producer's answer is lost; it retriesThe leader finds (producer, seq) and returns the first offset.No duplicate in the log.Idempotent producer
    The old leader returns with extra recordsIt truncates to the new leader's end of its epoch.The extra records were never acknowledged under acks=all.Leader epoch
    Two followers fall behindThe ISR shrinks to 1; acks=all writes are refused.No write is acknowledged on one copy.min.insync.replicas
    A broker crashes mid-writeThe last record in the file is torn.On restart the CRC check cuts it; the replica fetches it again.CRC per record
    A network partition isolates the old leaderIt keeps an old epoch; the controller elects another.Followers and the controller refuse requests with the old epoch.Raft quorum
    A consumer crashes after work, before commitThe next owner replays the batch.The handler dedupes by message key or offset.Inbox table
    A consumer lags past retentionIts offset is deleted; fetch returns out of range.Alert on lag in time well before retention; reset by policy.Lag alert
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Postgres queue2Redis stream3Log, 3 brokers4+ brokers5+ tiered storage6+ regionsmore load →
    Messages per second against this prompt's demand101001k10k100k1M10MDemand: average: 115,741 messages per secondDemand: average115,741Demand: 3× peak: 347,222 messages per secondDemand: 3× peak347,222Postgres queue, batch 100: 356,712 messages per secondPostgres queue, batch 100356,712Redis stream, batch 100: 324,969 messages per secondRedis stream, batch 100324,969One log, fsync each: 50 messages per secondOne log, fsync each50One log, fsync per 1,000: 47,534 messages per secondOne log, fsync per 1,00047,534One log, batch 1,000: 3,982,436 messages per secondOne log, batch 1,0003,982,436messages per second, log scale
    stepaddit handlesmove up when you see
    1A Postgres table with SKIP LOCKED (B6).About 357,000 inserts a second in batches; jobs commit with the data.Several teams want the same events, or replay of last week.
    2A Redis stream with consumer groups.About 325,000 adds a second in the lab; retention bounded by memory.Retention passes RAM, or one node's failure must not lose data.
    3A replicated log on 3 brokers: segments, ISR, acks=all.One broker appends hundreds of MB a second; any 1 broker can die.Disk or network of 3 brokers runs out; consumers need more partitions.
    4More brokers and partitions, rack-aware replica placement.18 brokers and 72 partitions for this prompt's 210 TB.Disks fill with retention, not traffic.
    5Tiered storage: old segments move to object storage.Months of retention without more brokers.Readers or producers in other regions.
    6A cluster per region with asynchronous mirroring between them.Local latency; a region can fail. Mirrored topics lag by seconds.Top of the ladder.

    Demand from panel C. Postgres and Redis rates are the B6 lab's, 8 clients. Log rates are one lab log on a laptop SSD with 100 B values. Read them as orders of magnitude.

    I start with a Postgres table or a Redis stream. I move to a replicated log when several teams read the same events, or when one node cannot hold the rate or the retention.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    Can you give exactly-once processing?Idempotent producers stop duplicates in the log. Transactions write output and offsets atomically; otherwise make the consumer idempotent with an inbox table.T9
    How do you keep order across partitions?You do not; order holds per partition. Put every event of one entity under one key, or carry a sequence number and reorder.X4
    One key gets most of the traffic. Now what?Its partition runs hot on one leader. Split the key with a suffix if order allows, or give that key its own topic.X2
    How does the controller elect without split brain?Controllers form a Raft quorum. A leader needs a majority, and every decision is an entry in the replicated metadata log.X5
    How fast is a dead broker noticed?Brokers heartbeat to the controller. A missed session timeout marks the broker dead; that timeout dominates failover time.X6
    How do you replicate to another region?Mirror topics asynchronously; the other region lags by seconds. Consumers there use translated offsets.X1
    Windows, joins, aggregates over the stream?A stream processor reads partitions, keeps state per key, and checkpoints state with the input offsets.B7
    Q

    Drill

    predict, then reveal

    0 of 10 known

    1. A producer uses acks=1. The leader acknowledges a write and dies a millisecond later. Is the write safe?

    2. What does the high watermark mean, and who moves it?

    3. Why does a follower's HW lag the leader's?

    4. acks=all, min.insync.replicas = 1, and both followers have left the ISR. What is at risk?

    5. Why does min.insync.replicas = 2 with 3 replicas sometimes refuse writes?

    6. A new leader is elected. The old leader comes back with 3 records the new leader never had. What happens to them?

    7. How does a read find offset 72,512 without scanning the partition?

    8. Why does the broker not fsync every write?

    9. A consumer group has 6 partitions and 8 members. Why are 2 members idle?

    10. A compacted topic keeps a user's profile. How do you delete the user?

    R

    Numbers to say

    measured, derived or cited
    demand
    About 116,000 messages a second, 347,000 at peak; 210 TB for 7 days × 3.
    acks=1
    Lost acknowledged writes in 189 of 200 lab failovers.
    acks=all
    With min ISR 2: 0 lost; 3.8% of writes refused while the ISR was small.
    fsync
    50 appends a second with one each; 48,000 with one per 1,000.
    no fsync
    398 MB/s in batches of 1,000; 22 MB/s one at a time.
    index
    One entry per 4 KB: 28 KB for 14.5 MB; 14 records scanned per read.
    election
    Raft, 150 to 300 ms timeouts: median 157 ms, p99 413 ms (X5 lab).

    Failover trials are seeded and repeat exactly. Rates: one log on a laptop SSD, shared with other jobs; the laptop's fsync flushes the drive cache.