Distributed messaging queue
hard 32 minA distributed messaging queue spreads messages over many machines.
See it run
Route a message, copy it, lose a leader, and share the partitions.
Operations
One message, eight steps
From the producer to the committed offset, with one leader and two followers.
Step 1 of 8
Producer request
The producer sends a message to the frontend, through a load balancer.
Step 1: Producer request
p = hash(key) % partitionsleader = metadata.leader(topic, p) # cachedoffset = leader.append(p, message) # to the commit logleader.wait_for_in_sync(p, offset) # acks=allreply(offset)batch = consumer.poll(p, position)handle(batch)consumer.commit(p, batch[-1].offset + 1)- Confirmed after
- All in sync
- Result
- Read once
Metadata is asked rarely, because the answer is cached. Messages never pass through it.
In the real world
The same inside a distributed queue doing real jobs. Pick one and step through it.
Offsets 0 to 9. The consumer commits 5 and crashes after handling 7.
Step 1 of 3
Committed
| Offset | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|
0 to 4 are finished. The commit says 5.
Step 1: Committed
Common mistakes
The bugs interviewers watch for, with the fix beside each.
acks=all without a minimum
criticalIf only the leader is in sync, all means one copy.
Wrongacks = "all"Rightacks = "all"min_insync_replicas = 2 # of 3Committing before the work
criticalA crash skips messages.
Wrongconsumer.commit()handle(batch)Righthandle(batch)consumer.commit()A random hash for keys
majorPython's hash of a string differs between processes, so one key lands on several partitions.
Wrongp = hash(key) % nRightp = zlib.crc32(key.encode()) % nMore consumers than partitions
minorThe surplus is idle.
Wrongscale(consumers=20) # 12 partitionsRightscale(consumers=min(20, partitions))
Interview tips
How to explain it
- Partition for scale.
- Replicate for safety.
- Elect a leader from those in sync.
Memory trick: BROKER
- Brokers store, Replicate, Ordered in a partition.
- Key picks the partition.
- Elect from the ISR, Retain by policy.
A safe default
- Three replicas in three zones.
- Two required in sync, acks=all.
- Idempotent producer and consumer.
Watch these
- ISR shrinking.
- Lag in seconds.
- One partition larger than the others.