AlgoViz

Log-based message queues

medium 30 min

A 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

Our systemProducerLeader logoffsets 0 to 7Index filesFollower log0 to 6Log cleanerConsumer

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

Topicalice 1bob 2alice 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

    critical

    The four letters null are a value. The key is never deleted.

    Wrong
    send(key, value=json.dumps(None))
    Right
    send(key, value=None)   # no bytes at all
  • Compacting events that all count

    critical

    Only the last payment of each customer would remain.

    Wrong
    payments.cleanup_policy = "compact"
    Right
    payments.cleanup_policy = "delete"balances.cleanup_policy = "compact"
  • Retention shorter than an outage

    major

    The consumer's offset points to a deleted segment.

    Wrong
    retention = hours(24)
    Right
    retention = days(7)alert(lag_seconds > days(2))
  • Stopping after the first partition

    major

    State is complete only when every partition is read to its end.

    Wrong
    if offset + 1 >= end[p0]:    break
    Right
    if 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.