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.
Video lesson · Chapter 1 of 5
One bell, three different desks
Theory
Read or listen first. About 2 min.
What it is
Publish-subscribe, or pub-sub, is a way to send messages without naming a receiver. A publisher sends a message to a topic, which is a named channel. Each subscriber chooses the topics it wants through a subscription.
The system that holds the topics, called the broker, makes one copy of every message for every subscription. Publishers do not know who reads, and subscribers do not have to know who wrote. Both agree only on the topic and on the shape of the message.
Why it exists
When a user signs up, several parts of a system care: the welcome email, analytics, the audit log. If the user service calls each one, it must know them all, wait for them all, and change every time another appears. A slow email service makes sign-up slow.
With pub-sub, the user service publishes one event and is done. Each reader works at its own speed and fails alone. The cost is that the work happens later, a message may arrive twice, and it is harder to see who depends on what.
A short history
1987
The Isis toolkit, presented at the SOSP conference, includes a news service that works by publishing to named subjects. It is one of the earliest publicly described pub-sub systems.
1999
Andy Stanford-Clark of IBM and Arlen Nipper of Arcom invent MQTT, a small pub-sub protocol now used by many connected devices.
2011
LinkedIn open-sources Kafka, which stores published messages in a log that many groups of readers can use.
2019
MQTT version 5 becomes an OASIS standard. It names three levels of delivery: at most once, at least once and exactly once.
Words to know
- Topic
- A named channel that messages are published to.
- Subscription
- A named attachment to one topic, with its own progress and settings.
- Fan-out
- One published message becoming a copy for each subscription.
- Attribute
- A small label on a message, readable without opening the body.
- Acknowledgement
- A subscriber's word that it has finished with a message.
- Ack deadline
- How long the broker waits for that word before it sends the message again.
- Retention
- How long the broker keeps messages.
- Dead-letter topic
- Where a message goes after failing too many times.
- Ordering key
- A label; messages with the same one are delivered in the order they were published.
How it works
Step through the idea, or press Play.
Publish once. The publisher sends a message with attributes to a topic, not to a receiver
Understand it
Start here
The town crier and the scarves
A town crier calls out notices for clubs. The crier keeps no list of members. People show which club they follow by the scarf they wear.
The crier's work never changes: one cry, whatever the number of listeners.
The idea
Publisher, topic, subscription
One message, three readers
What you get
Loose coupling
Publishers and subscribers are independent. They share a topic name and a message format.
Scalability
Add subscribers without changing publishers.
Fan-out
One message reaches many subscribers.
Asynchronous work
The publisher does not wait for subscribers. It waits only for the broker to accept the message.
Separate failures
One subscriber can stop and the rest carry on. Its messages wait, within the retention time.
Event-driven
Programs react when something happens instead of asking again and again.
Parts
Topics and subscriptions
| Topic | Subscription | |
|---|---|---|
| Is | A named channel | A named attachment to one topic |
| How many | Many subscriptions per topic | Many workers per subscription |
| Copies | Broadcasts to every subscription | Gives each message to one worker |
| Settings | Retention period, message schema | Filter, push or pull, ack deadline, dead-letter topic |
| Progress | None of its own | Remembers what is acknowledged |
Filters, and workers that share
Life of a message
From publish to acknowledge
Five steps
- 1
Publish
The publisher sends the body, some attributes and perhaps an ordering key to a topic.
- 2
Store
The broker writes the message down and returns an id. A broker without storage skips this, and messages can be lost.
- 3
Deliver
Each matching subscription gets a copy, pushed to it or pulled by it.
- 4
Process
The subscriber does its work. The ack deadline is running.
- 5
Acknowledge
The subscriber says it is done. This subscription will not normally see the message again.
Patterns
Four common patterns
| Pattern | What happens | Used for |
|---|---|---|
| Fan-out | One message goes to every subscription | Notifications, logging, several services reacting |
| Content filter | A subscription gets only messages whose attributes match | Orders service ignores user events |
| Competing consumers | Workers on one subscription share: worker 1 does messages 1 and 3, worker 2 does 2 and 4 | Spreading work |
| Event sourcing | Every event is kept and replayed to rebuild the current state | History, audit, new views of old data |
Who gets this message?
Guarantees
How many times will it arrive?
| Guarantee | How | Good | Bad | Fits |
|---|---|---|---|---|
| At most once | Send and forget | Lowest delay, no redelivery | May lose messages | Metrics, debug logs, live presence |
| At least once | Send again until acknowledged | Stored messages are not lost within retention | May arrive twice | Orders, most events |
| Exactly once | Deduplicate and save progress together | One effect per message, inside its limits | Slower, more complex, limited reach | Payments and stock, still with idempotent handling |
Ack, nack and silence
Choose the ack deadline
Order
Order is per key
With an ordering key
- Published A, B, C with key user-1
- Received A, B, C
- Other keys flow in parallel
- A failed message holds up its own key
Without one
- Published A, B, C
- May be received B, A, C
- Highest throughput
- Put a version in the message if late ones must be ignored
Choose a key that is as small as the order you need: one user, one order. One key for everything is correct and slow, because everything waits in one line. In Google Cloud Pub/Sub, sending one keyed message again also sends the later ones of that key again, even acknowledged ones.
Compare
Pub-sub or a queue?
| Pub-sub | Message queue | |
|---|---|---|
| Delivery | One to many: a copy per subscription | One to one: each message to one worker |
| Sender knows | A topic | A queue, usually with one purpose |
| Good for | Events: something happened | Tasks: please do this |
| After reading | Other subscriptions still have theirs | Removed after the acknowledgement |
| Replay | If the product retains messages | Rarely |
Which one?
Use pub-sub when
- Several services need the same event
- You want services that can change separately
- Many readers, and more to come
- Readers must be able to fall behind
- Replay is needed (with a product that retains)
Use a queue or a call when
- You are handing out tasks to workers
- Work must be balanced over one pool
- The caller waits for a reply: call it
- One strict sequence of steps
- Remote calls in disguise: use RPC
Queues have their own page: queues. Sending events to other companies over HTTP is webhooks. Working on a continuous flow of events is stream processing.
Numbers
Fan-out is multiplication
Publish rate and delivery rate
Practice
Habits that help, and habits that hurt
Do
- Acknowledge only after processing
- Send repeated failures to a dead-letter topic
- Put a unique id in every message for deduplication
- Use attributes for filtering
- Set the ack deadline above the real processing time
Do not
- Acknowledge before the work is done
- Swallow errors from a handler
- Rely on order without a key
- Put large files in messages: store them and send a link
- Create subscriptions nobody reads: they store messages and cost money
Failures
What goes wrong
Saved but not published
The order is in the database and the process dies before it publishes. Write the event to an outbox table in the same transaction and publish from there.
Poison message
One message fails every time. Limit attempts and move it to a dead-letter topic with an alert.
Slow subscriber
Its backlog grows while the others are fine. Add workers to that subscription.
Event loop
Service A reacts to B and B reacts to A. Follow one event by a correlation id, and do not publish when nothing changed.
Summary
The whole topic in one minute.
Pub-sub sends one message to a topic and one copy to each subscription. Writers and readers are separate in name, in time and in speed, so a new reader is a new subscription and nothing else changes.
Several workers may share one subscription, and then each message goes to one of them. Use an ordering key when order matters, make handling idempotent because duplicates happen, and watch the age of the oldest unread message.
- Publish once to a topic; each subscription gets its own copy.
- Publishers and subscribers know the topic, not each other.
- Workers on one subscription share its messages.
- At least once is the normal choice, so handle duplicates.
- Order holds per key, never for the whole topic for free.
- Retention and replay depend on the product.