AlgoViz

Distributed messaging queue

hard 32 min

A 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

Our systemProducerFrontendhas the messageMetadataBroker 1, leaderBroker 2Broker 3Consumer

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

Offset0123456789

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

    critical

    If only the leader is in sync, all means one copy.

    Wrong
    acks = "all"
    Right
    acks = "all"min_insync_replicas = 2     # of 3
  • Committing before the work

    critical

    A crash skips messages.

    Wrong
    consumer.commit()handle(batch)
    Right
    handle(batch)consumer.commit()
  • A random hash for keys

    major

    Python's hash of a string differs between processes, so one key lands on several partitions.

    Wrong
    p = hash(key) % n
    Right
    p = zlib.crc32(key.encode()) % n
  • More consumers than partitions

    minor

    The surplus is idle.

    Wrong
    scale(consumers=20)   # 12 partitions
    Right
    scale(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.