Introduction to pub-sub
easy 25 minIn 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
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
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
criticalIf the worker dies after the ack, the message is gone and the work was never done.
Wrongmessage.ack()handle(message)Righthandle(message)message.ack()A subscription per instance
criticalEvery subscription gets a copy, so three instances send three emails.
Wrongtopic.subscribe(f"email-{instance_id}")Righttopic.subscribe("email") # shared by all instancesHandlers that are not idempotent
majorAt-least-once delivery will one day deliver the same message twice.
Wrongcharge(order.amount)Rightcharge(order.amount, key=message.id)Publishing after the commit
majorA crash between the two leaves an order that nobody hears about.
Wrongdb.commit(order)topic.publish(order)Rightwith 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.