AlgoViz

Introduction to pub-sub

easy 25 min

In publish-subscribe, a program publishes each message once to a named topic, and every subscription on that topic gets its own copy.

See it run

One publish, many readers: how copies are made, filtered, shared, acknowledged and kept in order.

Operations

Publish and fan out

The six moments of one message, from the publisher to two acknowledgements.

Step 1 of 6

The publisher sends

publishUser servicepublisheruser-eventstopicAnalyticsanalytics-subEmailemail-subAudit logaudit-sub

The user service publishes USER_CREATED to the topic user-events.

Step 1: The publisher sends

def publish(topic, data, **attributes):    message = store(topic, data, attributes)    for sub in topic.subscriptions:        if sub.matches(message):            sub.ready.append(message)    return message.id
Publisher sends
Once
Readers get
One copy each

The publisher's work ends at the store. Everything after that happens without it.

In the real world

The same introduction to pub-sub doing real jobs. Pick one and step through it.

Adding a reader does not touch the writer.

Step 1 of 4

Two readers

publishUser servicepublisheruser-eventstopicAnalyticsreadingEmailreadingAudit lognot attached

Analytics and email read the topic. The audit log is not attached yet.

Step 1: Two readers

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Acknowledging first

    critical

    If the worker dies after the ack, the message is gone and the work was never done.

    Wrong
    message.ack()handle(message)
    Right
    handle(message)message.ack()
  • A subscription per instance

    critical

    Every subscription gets a copy, so three instances send three emails.

    Wrong
    topic.subscribe(f"email-{instance_id}")
    Right
    topic.subscribe("email")  # shared by all instances
  • Handlers that are not idempotent

    major

    At-least-once delivery will one day deliver the same message twice.

    Wrong
    charge(order.amount)
    Right
    charge(order.amount, key=message.id)
  • Publishing after the commit

    major

    A crash between the two leaves an order that nobody hears about.

    Wrong
    db.commit(order)topic.publish(order)
    Right
    with db.transaction():    save(order)    save_outbox(order)# a relay publishes the outbox

Interview tips

  • How to explain it

    • Publish once to a topic.
    • Each subscription gets a copy.
    • Workers on one subscription share.
  • Memory trick: PUBS

    • Publish to a topic, not to a receiver.
    • Unaware of who reads.
    • Broadcast, then Subscribe to choose.
  • Reach for it when

    • Several services care about one event.
    • Readers come and go.
    • The request must not wait.
  • Be careful with

    • Duplicates and order.
    • Message formats that others depend on.
    • Flows that nobody can follow: add a correlation id.