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.

Video lesson · Chapter 1 of 5

One bell, three different desks

0:00 / 3:36

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

  1. 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.

  2. 1999

    Andy Stanford-Clark of IBM and Arlen Nipper of Arcom invent MQTT, a small pub-sub protocol now used by many connected devices.

  3. 2011

    LinkedIn open-sources Kafka, which stores published messages in a log that many groups of readers can use.

  4. 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.

Step 1 of 3

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.

One cry, every red scarf

The crier's work never changes: one cry, whatever the number of listeners.

The idea

Publisher, topic, subscription

One message, three readers

The user service publishes once to a topic named user-events. The broker sends a copy to three subscriptions, read by analytics, email and the audit log.
The publisher makes one call. The broker does the copying.

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

TopicSubscription
IsA named channelA named attachment to one topic
How manyMany subscriptions per topicMany workers per subscription
CopiesBroadcasts to every subscriptionGives each message to one worker
SettingsRetention period, message schemaFilter, push or pull, ack deadline, dead-letter topic
ProgressNone of its ownRemembers what is acknowledged
Two services that each need every message need two subscriptions. Ten copies of one service share one subscription.

Filters, and workers that share

An order service publishes to the topic orders. Inventory gets only messages with type created, analytics only those with type completed. Billing gets every message, shared by two workers: worker 1 gets message 1 and worker 2 gets message 2.
Across subscriptions a message is copied. Inside one subscription it is shared out.

Life of a message

From publish to acknowledge

Five steps

The publisher hears back after the message is stored, long before anyone has processed it.
  1. 1

    Publish

    The publisher sends the body, some attributes and perhaps an ordering key to a topic.

  2. 2

    Store

    The broker writes the message down and returns an id. A broker without storage skips this, and messages can be lost.

  3. 3

    Deliver

    Each matching subscription gets a copy, pushed to it or pulled by it.

  4. 4

    Process

    The subscriber does its work. The ack deadline is running.

  5. 5

    Acknowledge

    The subscriber says it is done. This subscription will not normally see the message again.

Patterns

Four common patterns

PatternWhat happensUsed for
Fan-outOne message goes to every subscriptionNotifications, logging, several services reacting
Content filterA subscription gets only messages whose attributes matchOrders service ignores user events
Competing consumersWorkers on one subscription share: worker 1 does messages 1 and 3, worker 2 does 2 and 4Spreading work
Event sourcingEvery event is kept and replayed to rebuild the current stateHistory, audit, new views of old data
Event sourcing needs an event store that keeps everything in order. A topic that deletes messages after a week is not one.

Who gets this message?

The question is asked once for each subscription.

Guarantees

How many times will it arrive?

GuaranteeHowGoodBadFits
At most onceSend and forgetLowest delay, no redeliveryMay lose messagesMetrics, debug logs, live presence
At least onceSend again until acknowledgedStored messages are not lost within retentionMay arrive twiceOrders, most events
Exactly onceDeduplicate and save progress togetherOne effect per message, inside its limitsSlower, more complex, limited reachPayments and stock, still with idempotent handling
Redis Pub/Sub is at most once by design. Kafka is at least once by default.

Ack, nack and silence

A nack says: I could not process this. Silence past the deadline means the same.

Choose the ack deadline

deadline>batch×tmessage20×2 s=40 s>10 s\text{deadline} > \text{batch} \times t_{\text{message}} \qquad 20 \times 2\ \text{s} = 40\ \text{s} > 10\ \text{s}
Example: a worker takes 20 messages and needs 2 seconds each, one after another. With a 10 second deadline the later ones are delivered again while still waiting. Take smaller batches, extend the deadline while working, or set it above 40 seconds.

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-subMessage queue
DeliveryOne to many: a copy per subscriptionOne to one: each message to one worker
Sender knowsA topicA queue, usually with one purpose
Good forEvents: something happenedTasks: please do this
After readingOther subscriptions still have theirsRemoved after the acknowledgement
ReplayIf the product retains messagesRarely
Retention and replay belong to the product, not to the pattern. Redis Pub/Sub keeps nothing at all; a log keeps everything for a set time.

Which one?

A common mix is a topic that feeds one queue per service, so each service can fall behind alone.

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

10,000,000100,000=100/s average100×3=300/s peak300×4=1,200 deliveries/s\frac{10{,}000{,}000}{100{,}000} = 100/\text{s average} \quad 100 \times 3 = 300/\text{s peak} \quad 300 \times 4 = 1{,}200\ \text{deliveries/s}
Assume 10 million events a day, a peak of three times the average and 4 subscriptions. At 2 KB each, 1,200 deliveries a second is 2.4 MB/s leaving the broker. The publisher still sends only 300 a second.

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.

Sources