Search

Search papers and lessons

Publish-Subscribe Messaging

Level 2 · 11 min read

Publish-subscribe messaging lets senders post messages to a named topic without knowing who will read them, and a broker delivers a copy to every subscriber of that topic.

On this page

  • Colour = topic mix
  • Discrete math
  • Distributed systems
  • Networking
  • Programming languages
  • ReadReady to readNot yet

TL;DR

In publish-subscribe messaging, a program that has news (a publisher) sends it to a named topic, and programs that want the news (subscribers) register interest in that topic. A broker sits between them. It stores each message and delivers a copy to every current subscriber, so the publisher never needs to know who is listening or how many of them there are. The two sides are decoupled: they do not have to run at the same time, and neither has to change when the other changes.

Builds on: Asynchronous Message Passing · Leads to: Message Delivery Guarantees (what the broker promises about delivery), the Kafka paper (a broker that stores topics as durable logs)

Where it's used

Market data. A stock exchange feed publishes every trade and quote on a topic per symbol. Trading desks, risk systems and charting tools each subscribe to the symbols they care about. The feed does not know how many desks are listening, and adding a new risk system does not slow the feed down.

Event fan-out in an online shop. When a customer places an order, the order service publishes one message, "order placed", to a topic. The email service, the inventory service and the analytics service each subscribe. One publish produces three deliveries. Adding a fourth service that needs the same events means one new subscription, not a change to the order service.

Apache Kafka. LinkedIn released Apache Kafka in 2011 as a messaging system built on this model. Kafka keeps each topic as an ordered, durable append-only log. Subscribers, called consumers, read the log at their own pace and remember how far they have read. The Kafka paper describes that design. Many data pipelines in companies use Kafka as the shared bus that connects their services.

How it works

Take one topic called "weather". A station publishes to it. Two subscribers, Ann and Ben, are interested.

  1. Ben subscribes. He tells the broker, "send me everything on weather". The broker records Ben in the list of subscribers for that topic. The list is now [Ben]. Check: one subscriber, no messages yet.

  2. Ann subscribes. The same happens for Ann, and the list becomes [Ben, Ann]. Check: two subscribers.

  3. The station publishes "rain 3 mm". The station sends the message to the broker and names only the topic. The broker looks up the subscribers, [Ben, Ann], and places a copy of the message in a private inbox for each of them. Ben's inbox is now ["rain 3 mm"], and so is Ann's. Check: one message in, two copies out. The station never saw Ben or Ann.

  4. Ben reads, Ann has not. Ben takes his copy out of his inbox. Ann's copy stays where it is until she reads it. Each subscriber consumes at its own pace, so a slow reader does not hold up a fast one.

  5. Ann unsubscribes, and the station publishes "wind 12 km/h". The broker now has the list [Ben] and puts one copy in Ben's inbox. Ann's inbox receives nothing. Check: a message reaches exactly the subscribers present when it was published.

The key idea is the topic: a name that is the only thing the publisher and subscribers share.

flowchart LR
  P[Publisher] -->|publish to weather| B[(Broker)]
  B -->|copy| Ben[Ben]
  B -->|copy| Ann[Ann]

The math

Let T be the set of topics. For each topic t in T, let S(t) be the set of subscribers currently registered to t. Each subscriber s has an inbox Q_s, which is a first-in, first-out queue of messages waiting to be read.

Definition: Publish

Publishing a message m to topic t is the operation

Q_s ← Q_s followed by m, for every subscriber s in S(t).

The publisher is not part of the definition. The publish operation returns once the broker has accepted m, and it does not wait for any subscriber to read it.

Step 3 in symbols: the fan-out

One publish adds one message to each inbox in S(t), so it causes

deliveries(m)=∣S(t)∣\text{deliveries}(m) = |S(t)|

copies, where |S(t)| is the number of subscribers to the topic at that moment. The publisher sends one message in both cases. The broker does the copying, which is why the cost of a publish grows with the number of subscribers.

Step 4 in symbols: totals over a stream

If messages m_1, m_2, … are published to topics t_1, t_2, …, the total number of deliveries is

∑i∣S(ti)∣\sum_{i} |S(t_i)|

where S(t_i) is the subscriber set at the moment message i was published. The sum changes when subscribers join or leave, because the set is read at publish time, not at the end of the stream.

Ordering

Within one inbox, messages keep the order in which the broker accepted them. If Ann's inbox holds "rain" and then "wind", she reads them in that order. Across different topics, or across different brokers, there is no global order that every subscriber agrees on, and most systems do not promise one.

Worked examples

Example
Tiny: one publisher, one subscriber, two messages

Topic "news". Subscribers: S(news) = [Eve]. Eve's inbox starts empty.

  1. Publish "hello". Eve's inbox becomes ["hello"]. The count of deliveries is |S(news)| = 1.
  2. Publish "bye". Eve's inbox becomes ["hello", "bye"]. The count of deliveries is again 1.
  3. Eve reads one message. She gets "hello" first, because the inbox is first in, first out.
  4. Interpretation: with one subscriber, pub/sub behaves like a mailbox with a single reader. The order is preserved and no message is lost while Eve is subscribed.
Example
Standard: two subscribers and an unsubscribe

Topic "prices". Subscribers at the start: S = [A, B, C].

  1. Publish price 10. The subscriber set has 3 members, so the deliveries are 3: one copy each in the inboxes of A, B and C.
  2. Publish price 11. Again 3 deliveries. Each subscriber's inbox now holds 2 prices.
  3. C unsubscribes. The set becomes [A, B].
  4. Publish price 12. The set has 2 members, so 2 deliveries. C's inbox does not change.
  5. Count the total deliveries over the three publishes: 3 + 3 + 2 = 8.
  6. Interpretation: C has 2 prices, and A and B each have 3. The publisher made three publishes and never looked at the subscriber list. The broker's choice at each publish decided who got what.
Example
Realistic: an analytics service that falls behind

An order service publishes to the topic "orders". Three subscribers exist: email, inventory and analytics. Over one hour, two orders are placed, order 1 and order 2. Analytics goes down after order 1 and returns after order 2.

  1. Order 1 is published with all three subscribed. Deliveries: 3. Each inbox gets one copy. Email and inventory read theirs at once. The analytics copy waits in its inbox.
  2. Analytics crashes. Its inbox still holds order 1, and the broker keeps the message.
  3. Order 2 is published. The subscriber set is still three services, so the deliveries are 3. Analytics' inbox now holds order 1 and order 2.
  4. Analytics restarts and reads both messages in order, catching up without the order service's help.
  5. Total deliveries over both orders: 3 + 3 = 6. Every service received every order in this run.
  6. Interpretation: the order service did not wait for analytics at any point. The cost is that analytics sees its data late, and the broker must store the backlog. The shop's customers saw no delay.

Try it: a topic has 4 subscribers. Five messages are published in order. The fourth subscriber unsubscribes after the second message. How many deliveries are made in total? Answer: 17. Messages 1 and 2 each reach all 4 subscribers, which is 8. Messages 3, 4 and 5 each reach the 3 remaining subscribers, which is 9. The total is 8 + 9 = 17.

Common mistakes and tradeoffs

It is tempting to think the publisher waits until every subscriber has the message. In fact the publisher returns once the broker has the message. Delivery happens afterwards, which is why pub/sub is asynchronous and why the publisher is not slowed by a slow reader.

It is tempting to think a subscriber receives only the messages published while it is running. In fact that depends on the broker. Some systems keep a queue for each subscriber, so a subscriber that was offline receives its backlog later, as in the realistic example. Others deliver only to subscribers that are connected at publish time, and a message published during an outage is lost to that subscriber. Which one you have is a design choice, and the delivery guarantees describe it.

It is tempting to think pub/sub and a message queue are the same thing. In fact a work queue gives each message to one consumer, so consumers share the work. Pub/sub gives each subscriber its own copy, so every subscriber sees all the messages. Both are called queues in common speech, and the difference matters when you pick one.

When to use it. Use publish-subscribe when many independent parts of a system need the same events, when producers and consumers should not know about each other, or when the consumers' speed varies a lot.

When not to use it. Do not use it when the publisher needs an answer right away, such as a payment confirmation. Use a direct request and reply instead. Do not use it to hand each job to exactly one worker; a work queue is simpler and more precise for that.

PatternWho gets a messagePublisher needs an answer?Typical use
Direct request and replyOne named serviceYesChecking a payment
Work queueOne of several workersNoResizing uploaded images
Publish-subscribeEvery current subscriberNoOrder events for several services

History

Before the 1990s, programs that needed the same live information, such as price changes on a trading floor, had to know each other's addresses and send them copies one by one. In the early 1990s researchers and vendors built publish-subscribe systems so that a producer could send once and many consumers could receive, with the bus doing the copying. That made it possible to add a new consumer without touching the producer. Standard interfaces for the model, such as the Java Message Service, followed in the late 1990s and early 2000s.

The model caught on because it fits event-driven systems well. When many services need to react to the same change, publish-subscribe puts the change in one place and lets each service decide what to do. In 2011 the release of Kafka as open source added a broker that keeps a durable, replayable log per topic, so a subscriber can read the history again instead of only the messages that arrive from now on.

Recap

  • A publisher sends a message to a named topic and does not know its subscribers.
  • A broker stores each message and places a copy in the inbox of every subscriber registered to that topic at publish time.
  • Each subscriber reads its own inbox at its own pace, and messages keep their order within one inbox.
  • The cost of a publish is the number of subscribers, which the broker pays.
  • Pub/sub is not a work queue: each subscriber gets every message, not a share of the messages.

Next, read Message Delivery Guarantees to see what a broker can promise about delivery, and the Kafka paper to see one design that stores topics as logs.

Check yourself

QuestionRecall: what does a subscriber receive when one message is published to a topic with three subscribers?Show answer

Each of the three subscribers receives its own copy of the message. The broker places one copy in each subscriber's inbox, so one publish produces three deliveries.

QuestionComputation: a topic has 5 subscribers. Four messages are published, and 2 subscribers unsubscribe between the second and third publish. How many deliveries are made in total?Show answer

The first two messages each go to 5 subscribers, which is 10. After the two unsubscribes there are 3 subscribers, and the last two messages each go to 3, which is 6. The total is 10 + 6 = 16.

QuestionWhy: why does a slow subscriber not slow down the publisher in this model?Show answer

The publisher's job ends when the broker accepts the message. The broker keeps a separate inbox for each subscriber and each subscriber reads at its own pace. A slow subscriber's inbox simply grows, and the publisher never waits for it to read.

QuestionApplied: a team uses pub/sub for payment confirmations, and a customer's payment confirmation sometimes arrives after the page has already timed out. What should they check, and what would you change?Show answer

They should first check whether the broker queues messages for subscribers that are offline, and what delivery guarantee applies, because a timed-out page usually means the confirmation was slow rather than lost. The core issue is that the page needs an answer right away, which pub/sub does not give. A better design is a direct request and reply for the confirmation the page waits for, with pub/sub used afterwards for the other services that need to know about the payment.

Sources