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.
- 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.
- 2A leader per partition takes writes. Followers fetch, and the high watermark is the smallest log end in the in-sync replica set.
- 3acks=all with min.insync.replicas = 2 and clean elections loses no acknowledged write. acks=1 loses the unreplicated tail at every leader death.
- 4Consumer groups split partitions among members and commit offsets. A rebalance replays from the last commit, so handlers stay idempotent.
"Design a message queue: producers append, consumers read in order, and messages survive a broker dying."
| question | answer 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.
| 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-functional | target |
|---|---|
| Peak append rate | ≈ 347,000 messages/s |
| Acknowledged messages lost, 1 broker down | 0 |
| Produce latency, acks=all | p99 < 50 ms in one region |
| Order | Per partition, the same for every reader |
| Failover | seconds, no operator |
An acknowledged message survives one broker death, and readers see one partition in one order, always.
| quantity | arithmetic | result |
|---|---|---|
| Messages | 10¹⁰ a day ÷ 86,400 s | ≈ 116,000/s; 3× peak ≈ 347,000/s |
| Ingress | 347,000/s × 1 KB | ≈ 347 MB/s at peak |
| Disk writes | 347 MB/s × 3 replicas | ≈ 1,042 MB/s for the cluster |
| Egress | 116 MB/s × 5 groups | ≈ 579 MB/s average |
| Storage | 10 TB a day × 7 days × 3 replicas | 210 TB |
| Brokers | 210 TB ÷ 12 TB each (a choice) | 18 brokers; ≈ 58 MB/s each at peak |
| Partitions | 347,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.
| call | success | errors | retry safe? |
|---|---|---|---|
| POST /v1/topics/{t}/records?acks=all {key, value, producer_id, seq} | 200 partition, offset | 413, 503 not leader, 503 not enough replicas | Yes: (producer_id, seq) dedupes |
| GET /v1/topics/{t}/partitions/{p}/records?offset=&max_bytes= | 200 records, high watermark | 416 offset out of range | Yes: a read |
| POST /v1/groups/{g}/join {member_id, topics} | 200 partitions, generation | 409 rebalance | Yes: rejoins |
| POST /v1/groups/{g}/offsets {generation, partition: offset} | 204 | 409 stale generation | Yes: last write wins |
| GET /v1/topics/{t}/metadata | 200 leader and ISR per partition | 404 | Yes |
- 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.
| store | key | value |
|---|---|---|
| Segment file | offset | Records in offset order, appended only |
| Offset index | offset | Byte position, one entry per 4 KB |
| Metadata log | topic, partition | Replicas, leader, leader epoch, ISR |
| Offsets topic | group, topic, partition | Next offset to read; compacted |
| Producer state | producer ID | Last 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Broker | Append-only segment files, one write per batch | Sequential disk writes; old data is deleted a file at a time. | Databases' write-ahead logs |
| Broker | Sparse offset index | Find any offset with two binary searches and a scan under 4 KB. | LSM block indexes |
| Broker | Leader, followers, ISR, high watermark | A write is committed once every in-sync copy has it. | Raft logs, database replication |
| Broker | Leader epochs | A returning replica finds where its log diverges and cuts the tail. | Raft terms, fencing tokens |
| Broker | Producer ID and sequence numbers | A retried batch is stored once. | Idempotency keys |
| OS page cache | Writes land in memory; reads of recent data hit memory | Consumers near the tail never touch the disk. | Any file-backed store |
| sendfile(2) | File to socket inside the kernel | Fetch responses skip a copy through the broker process. | Web servers, CDNs |
| Raft quorum | A replicated metadata log | One controller decides leaders; no split brain (X5). | etcd, service discovery |
| Consumer group | Partition assignment, committed offsets | Work 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.
| layout | status | cost |
|---|---|---|
| One file per message | Not approved | Millions of files; a metadata write per message. |
| A table with a B-tree | Small volume | Random page writes and vacuum; see the Postgres queue in B6. |
| One big file per partition | Not approved | Retention must rewrite or punch holes in it. |
| Segments plus a sparse index | Approved | Sequential appends; delete a whole file to expire data. |
| batch | no fsync | fsync per batch |
|---|---|---|
| 1 | 217,000/s · 21.7 MB/s | 50/s |
| 10 | 986,000/s · 98.6 MB/s | 500/s |
| 100 | 2,441,000/s · 244.1 MB/s | 4,939/s |
| 1,000 | 3,982,000/s · 398.2 MB/s | 47,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(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- 1The file name is the first offset in it, so finding a file is a binary search on names.
- 2A batch costs one system call. In the lab, batches of 100 appended 11 times faster than single records.
- 3Sparse: one entry per 4 KB, not per record, so the index for a 1 GB segment is about 2 MB.
- 4Brokers usually leave flushing to the OS. A write is safe when other brokers hold it, not when one disk does.
- 5Less than one index interval: the lab scanned 14 records on average.
- 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
// 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
}
// 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
}
// 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.
| setting | failovers that lost acked writes | acked writes lost | cost | status |
|---|---|---|---|---|
| acks=0 | 200 of 200 | 612 | No answer, so no retry | Metrics you can drop |
| acks=1 | 189 of 200 | 422 | Loses the unreplicated tail | Loss is fine |
| acks=all, min ISR 1 | 0 of 200 | 0 | 110 ticks offline | Downtime is fine |
| acks=all, min ISR 1, unclean | 11 of 200 | 25 | No downtime | Not approved |
| acks=all, min ISR 2 | 0 of 200 | 0 | 3.8% of writes refused | Approved |
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.
- 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(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- 1Refuse instead of acknowledging on fewer copies than promised. The producer retries.
- 2An idempotent producer: a retry after a lost answer returns the first offset. The lab wrote 0 duplicates.
- 3With acks=1 the record is on one disk, in the page cache. The leader's death loses it.
- 4Every ISR member has the record, so any clean new leader has it.
- 5The fetch offset is the follower's ack: it holds everything before it.
- 6A follower outside the ISR does not hold the HW back. That is why the ISR shrinks.
- 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
// 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
}
// 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
}
// 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.
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
below the HW: consumers can read it above the HW: not yet on every ISR membere0, e1 the leader epoch that wrote it
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.
| method | status | why |
|---|---|---|
| Each broker elects itself when the leader is silent | Not approved | Two brokers both lead after a partition. |
| A controller with its state in ZooKeeper | Older clusters | Works; the controller reloads all metadata when it changes. |
| A Raft quorum of controllers (KRaft) | Approved | The metadata is a replicated log; a standby controller has it already. |
| Follower truncates to the HW on restart | Rare double failures | The older rule can lose or mix records when two leaders change quickly. |
| Follower truncates by leader epoch | Approved | Asks 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.
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- 1One controller decides at a time, and its decisions are entries in a Raft log. X5 covers the election.
- 2Otherwise an empty ISR would let any replica lead and lose acknowledged writes.
- 3Unclean election: availability over durability. The lab lost writes this way in 11 of 200 failovers.
- 4Every record carries the epoch of the leader that wrote it. A deposed leader's requests carry an old epoch and are refused.
- 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
// 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
}
// 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.
| method | status | effect |
|---|---|---|
| Eager rebalance: revoke all, assign again | Small groups | The whole group stops each time. |
| Cooperative sticky assignment | Approved | Only moved partitions stop. |
| Static membership | Rolling restarts | A restart within the timeout moves nothing. |
| Commit before the work | Not approved | A crash skips messages: at most once. |
| Commit after the work | Approved | A 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.
| policy | keeps | lab result |
|---|---|---|
| Delete, by size | The newest segments under the limit | 10 of 14 files deleted; start offset 72,000 |
| Compact | The newest record per key | 20,000 → 1,000 records; 2.9 MB → 145 KB |
| Tiered | Recent segments local, old ones in object storage | Cheaper long retention (B9) |
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- 1Expiry is a file delete. No record is read or rewritten.
- 2A compacted log has gaps. A consumer at any offset still gets the next record left.
Tested source Go: retain and compact
// 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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A partition leader dies | A 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 retries | The leader finds (producer, seq) and returns the first offset. | No duplicate in the log. | Idempotent producer |
| The old leader returns with extra records | It truncates to the new leader's end of its epoch. | The extra records were never acknowledged under acks=all. | Leader epoch |
| Two followers fall behind | The ISR shrinks to 1; acks=all writes are refused. | No write is acknowledged on one copy. | min.insync.replicas |
| A broker crashes mid-write | The 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 leader | It 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 commit | The next owner replays the batch. | The handler dedupes by message key or offset. | Inbox table |
| A consumer lags past retention | Its offset is deleted; fetch returns out of range. | Alert on lag in time well before retention; reset by policy. | Lag alert |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | A 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. |
| 2 | A 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. |
| 3 | A 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. |
| 4 | More brokers and partitions, rack-aware replica placement. | 18 brokers and 72 partitions for this prompt's 210 TB. | Disks fill with retention, not traffic. |
| 5 | Tiered storage: old segments move to object storage. | Months of retention without more brokers. | Readers or producers in other regions. |
| 6 | A 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 10 known
A producer uses acks=1. The leader acknowledges a write and dies a millisecond later. Is the write safe?
What does the high watermark mean, and who moves it?
Why does a follower's HW lag the leader's?
acks=all, min.insync.replicas = 1, and both followers have left the ISR. What is at risk?
Why does min.insync.replicas = 2 with 3 replicas sometimes refuse writes?
A new leader is elected. The old leader comes back with 3 records the new leader never had. What happens to them?
How does a read find offset 72,512 without scanning the partition?
Why does the broker not fsync every write?
A consumer group has 6 partitions and 8 members. Why are 2 members idle?
A compacted topic keeps a user's profile. How do you delete the user?
- 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.