Log-based message queues
medium 30 minA log-based queue appends messages to a file and keeps them after they were read.
See it run
Append, read by position, read again, find an offset, and clean up.
Operations
Six steps in a partition
From the producer to the cleanup. Seven messages, 0 to 6, are stored.
Step 1 of 6
Append
The producer's message goes to the end of the log and gets offset 7.
Step 1: Append
offset = log.append(message) # end of the active segmentif active.size >= segment_bytes: roll()index.add_sometimes(offset, position) # sparse# followers fetch from the leaderbatch = log.read(committed_offset)cleaner.run() # sealed segments only- Cost
- Sequential
- Messages kept
- All, until cleanup
Only the active segment is written. Everything else is read-only.
In the real world
The same log-based message queues doing real jobs. Pick one and step through it.
The same three records, read in two ways.
Step 1 of 4
The records
| Topic | alice 1 | bob 2 | alice 3 |
|---|
alice 1, bob 2, alice 3.
Step 1: The records
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A tombstone that is a text
criticalThe four letters null are a value. The key is never deleted.
Wrongsend(key, value=json.dumps(None))Rightsend(key, value=None) # no bytes at allCompacting events that all count
criticalOnly the last payment of each customer would remain.
Wrongpayments.cleanup_policy = "compact"Rightpayments.cleanup_policy = "delete"balances.cleanup_policy = "compact"Retention shorter than an outage
majorThe consumer's offset points to a deleted segment.
Wrongretention = hours(24)Rightretention = days(7)alert(lag_seconds > days(2))Stopping after the first partition
majorState is complete only when every partition is read to its end.
Wrongif offset + 1 >= end[p0]: breakRightif all(position[p] >= end[p] for p in parts): break
Interview tips
How to explain it
- Append, number, keep.
- Each reader owns a position.
- Cleanup is separate from reading.
Memory trick: LOGS
- Log-append: only at the end.
- Offset, and a Guarantee: durable, replayable.
- Segments: manageable files.
Choose the cleanup
- Events: delete by age.
- State of keys: compact.
- Both: compact and delete.
Watch these
- Lag in time against retention.
- Disk of each broker.
- Effects during a replay.