0% completed
Publish-Subscribe
On This Page
What Publish-Subscribe Means
A Topic Is Not a Queue
Each Subscriber Reads at Its Own Pace
The Event Is a Public Contract
Publishing Without Losing Events
Independent Reactions Versus Ordered Steps
When to Use Publish-Subscribe
Check Yourself
Summary
Five teams at the store want to hear about every order. Fulfillment ships it, the email team sends the receipt, analytics counts it, the fraud team checks it, and the loyalty team adds points to the buyer's account. On a normal day, checkout takes 200 orders per second. If checkout sends each order to each team itself, that is 200 × 5 = 1,000 outgoing calls per second, and checkout must know the address, the message format, and how each of five different services fails.
The calls also make orders fail more often. Suppose checkout calls the five teams before it answers the buyer, and each team's service is available 99.9 percent of the time. An order then succeeds only when all five are up, which is 0.999 to the fifth power, or about 99.5 percent of the time. That is about 216 minutes of failed orders in a 30-day month, caused by teams that do not decide whether an order is valid.
The third cost is in checkout's releases. Every new team, and every change to what a team needs, is a code change in checkout. Over the last 90 days, checkout shipped 12 releases, and 8 of them did nothing for buyers, because they only added or changed a call for another team. To avoid waiting for a release, the analytics team reads the orders tables directly, so checkout cannot rename a column without breaking a report.
This lesson shows how checkout can announce each order once and let every interested team receive its own copy. It also shows what this design costs.
What Publish-Subscribe Means
In publish-subscribe, a program announces that something happened by sending one message, called an event, to a named channel, called a topic. The program that sends the event is the publisher. A program that wants those events registers its interest in the topic once, which creates a subscription, and the program becomes a subscriber. A separate system between them, the broker, stores each event and delivers a copy of it to every subscription.
The name lists the two actions: one side publishes, and the other side subscribes. It is often shortened to pub/sub. Kafka, Google Cloud Pub/Sub, Amazon SNS, and RabbitMQ are common brokers. Sending one event to many subscribers is called fan-out.
In the store, checkout saves each order and then publishes an event named order.placed to a topic with the same name. The five teams each subscribe to that topic.
In the left panel, checkout knows all five teams and makes 1,000 calls per second. In the right panel, checkout sends 200 events per second to one topic, and the broker makes the 1,000 deliveries, 200 for each team. Checkout's box says "knows none". That is the most important change.
The publisher does not know who its subscribers are. Checkout does not wait for any of the five teams. This module asks whether the sender needs an answer before it continues, and checkout does not: it confirms the order without hearing from any team. If the loyalty service stops for 10 minutes, checkout keeps taking orders. The broker keeps loyalty's events, 200 × 600 = 120,000 of them, and loyalty processes them when it returns. No buyer notices.
A Topic Is Not a Queue
The Message Queue lesson already put orders on a queue for fulfillment, so the email team could ask to read from that queue too. That fails, because a queue gives each message to exactly one reader. A queue holds jobs, and a job should be done once.
The top panel shows four orders on one queue with two teams reading it. Each order goes to whichever worker asks first, so fulfillment receives orders 1 and 3 and email receives 2 and 4. At 200 orders per second, about 100 orders per second would never ship, and the other 100 would ship without a receipt.
The bottom panel shows the same four orders on a topic. Each subscription receives all four. Inside one subscription, the team's workers share the events the same way queue workers share jobs. Fulfillment can run four workers on its subscription, and each order goes to one of those four. Kafka calls such a set of workers a consumer group: within a group, each event goes to one worker, and every group receives every event.
For this reason, many systems combine the two patterns. A broker can copy each order.placed event into one queue per team, and each team then uses its queue exactly as the previous lesson describes. The table shows the difference in one place:
| Queue | Topic | |
|---|---|---|
| A message is | A job: work to do once | A fact: something that happened |
| Delivered to | One reader | Every subscription, separately |
| Adding a reader means | More workers for the same job | One more use of the same fact |
| The question it answers | "Who does this job?" | "Who needs to know?" |
Each Subscriber Reads at Its Own Pace
The broker keeps events for a fixed time, called the retention period, and the store sets it to 7 days. Each subscription has its own position, which marks how far that subscriber has processed the topic. Kafka calls this position an offset. Because each team has its own position, one slow team does not slow the others.
Suppose analytics stops its service for 2 hours to move to a new database. During that time, checkout publishes 200 × 7,200 = 1,440,000 events. Fulfillment, email, fraud, and loyalty keep up. Analytics restarts from its saved position and works through the 1.44 million events it missed.
The distance between the newest event and a subscriber's position is its lag, and lag is the number each team watches. If a subscriber falls more than 7 days behind, the broker deletes events that the subscriber has not read yet. Those events are gone for that subscriber.
Adding a sixth team now needs no change to anyone else's code. When the recommendations team wants every order, it creates a subscription. It can start from new events only, or from the oldest event the broker keeps, which replays up to 7 days of orders. Checkout does not release anything. Analytics moves from the orders tables to its own subscription, and the store makes a rule: no team reads another service's tables directly.
The Event Is a Public Contract
This independence has a cost. Checkout's event format, called the schema, is now read by five teams that release code on their own schedules. Checkout cannot see their code, and it cannot ask them to deploy together. Any change to order.placed reaches all five at once.
The event in the diagram has three fields: an event ID, the order ID 7f3a, and the time the order was placed. In the left panel, checkout adds a field named source, and all five teams keep working, because code that reads JSON usually ignores a field it does not expect. In the right panel, checkout renames orderId to id. Every subscriber looks for orderId, finds nothing, and fails on every event.
Three rules keep a shared event safe:
- Make additive changes only. Add optional fields. Never remove a field, rename it, or change its type, because some subscriber may read it.
- Check every change before release. A schema registry is a service that stores each version of an event's schema and checks a new version against the old one. Checkout's release process asks the registry first, and the registry rejects the rename.
- Publish a new version for a breaking change. Create a topic named
order.placed.v2and publish every order to both topics. Each team moves to v2 on its own schedule, and checkout stops publishing v1 when the last team has moved.
The same rule applies to an API that outside developers call, and the API Versioning lesson covers it.
Publishing Without Losing Events
Checkout now does two writes for each order: it saves the order in its database, and it publishes the event to the broker. The two writes are not one transaction, so a crash between them leaves an order that no team hears about. That order is never shipped, and the buyer gets no receipt.
The numbers are larger than they look. At 200 orders per second, the store takes 200 × 86,400 = 17,280,000 orders per day. If the publish fails after the save only 1 time in 10,000, that is 1,728 orders per day that never ship.
The common fix is a table called the outbox. In the same database transaction that saves the order, checkout also writes the event as a row in the outbox table. The transaction saves both rows or neither. A separate process, the relay, reads new outbox rows, publishes each one, and marks it as sent. The Change Data Capture lesson shows a relay that reads the database's own change log instead.
The relay can crash after it publishes an event but before it marks the row as sent. It then publishes that event again. A broker also sends an event again when a subscriber does not confirm it in time.
For both reasons, pub/sub delivery is at least once: each subscriber receives every event, and sometimes receives one twice. Each subscriber records the eventId values it has processed and skips any repeat, as the Idempotency lesson explains. Without that check, a repeated event gives the buyer loyalty points twice.
Independent Reactions Versus Ordered Steps
Subscribers often publish events of their own. Fraud publishes order.flagged, and fulfillment publishes order.shipped. When a business process moves forward only through events like these, with no single service in charge, the style is called choreography. The other style, orchestration, gives one service the job of telling each step what to do and recording how far each order has gone.
| Choreography | Orchestration | |
|---|---|---|
| Who decides the next step | Each subscriber, from the events it reads | One orchestrator service |
| Adding an independent reaction | Subscribe one more service | Change the orchestrator |
| "Where is order 7f3a?" | Ask every service | One query |
| Fits | Independent reactions | Ordered steps that may need undoing |
Use pub/sub for reactions that do not depend on each other, like the receipt, the loyalty points, and the analytics count. A process with ordered steps, like reserving the item, charging the card, and shipping, needs an orchestrator. If shipping fails, a service must refund the card, and one service should own that job. The Saga lesson compares the two styles in full.
When to Use Publish-Subscribe
Pub/sub fits when two things are true. The publisher does not need an answer before it continues, which is the module's question. In addition, more than one team needs the same fact, or more teams will need it later.
| Connection in the store | Needs an <span style="white-space:nowrap">answer</span>? | Who needs it | Pattern |
|---|---|---|---|
| Checkout charges the card | Yes | Payment only | <span style="white-space:nowrap">Request</span>-response |
| A worker builds one shipment | No | One worker, once | Message queue |
| An order was placed | No | Five teams, and more later | Pub/sub |
| The payment provider reports a refund | No | The store, across a company boundary | Webhooks |
Pub/sub is a poor fit for a single consumer, because a queue is simpler and a topic adds nothing. It is also a poor fit for a reply: a publisher that waits for one subscriber's answer is a slow request-response with a broker in the middle.
One weakness remains in the store's design. The order.placed event carries only an event ID, an order ID, and a time. Every team that needs the items, the address, or the total must call checkout to ask for them. The next lesson, Event-Driven Architecture, measures that cost and changes what the event carries.
Check Yourself
Q1. A store manager changes a product's price on an admin page. The page must show "Saved". The search index, the product-page cache, and the price-drop email service must all learn the new price. Which connections should use pub/sub?
<details> <summary>Show answer</summary>Saving the price is request-response, because the admin page needs the answer before it can show "Saved". After the save, the pricing service publishes one price.changed event, and search, the cache, and the email service each subscribe. The pricing service does not need an answer from any of the three, and a fourth team can subscribe later without a change to the pricing service.
Q2. Before the outbox, checkout lost 1 event in 50,000 after saving the order. At 200 orders per second, how many orders per day reached no subscriber? What new duty does the outbox give each subscriber?
<details> <summary>Show answer</summary>The store takes 200 × 86,400 = 17,280,000 orders per day, and 17,280,000 ÷ 50,000 is about 346 orders per day that no team hears about. The outbox saves the order and the event in one transaction, so no event is lost. However, the relay can publish an event twice after a crash, so each subscriber must skip any eventId it has already processed.
Q3 (incident). At 14:00, a checkout release changes placedAt from text like "10:00:02" to a number of milliseconds. Analytics and loyalty fail on every event after that, while the other three teams, which do not read placedAt, keep working. By 17:00, nobody has fixed it. What happened, what do the two teams have to do, and what should change?
Checkout changed the type of a field in a public contract, and it could not see which subscribers read that field. In three hours, 200 × 10,800 = 2,160,000 events were published, and analytics and loyalty are that far behind. The events are within the 7-day retention, so nothing is lost. Checkout should restore the text format.
The two teams update their code to accept both forms before they process the events from those three hours. To prevent a repeat, checkout's release process should check every schema change with a schema registry, which rejects a type change. A new time format should arrive as a new field or in an order.placed.v2 topic.
💡 In the interview: When several services need the same fact, say so and name the topic. A strong answer sounds like this: "Checkout saves the order and publishes
order.placedthrough an outbox. Fulfillment, email, analytics, fraud, and loyalty each have their own subscription, so a slow team only increases its own lag. Delivery is at least once, so every subscriber removes duplicates by event ID. The event schema is a contract, so we change it only by adding fields, check it with a registry, and use a v2 topic for a breaking change." Expect a follow-up about a multi-step process like reserve, charge, and ship. Answer that pub/sub carries independent reactions, and an orchestrator runs ordered steps.
Summary
| <span style="white-space:nowrap">Problem</span> | Five teams need every order, so checkout makes 200 × 5 = 1,000 calls per second and must know each team's address, format, and failures. Calling all five before answering cuts order success to about 99.5 percent. Eight of checkout's last 12 releases only added or changed a call for another team. |
| <span style="white-space:nowrap">Mechanism</span> | The publisher sends one event, order.placed, to a topic, and the broker delivers a copy to every team's subscription, which is fan-out. Each subscriber keeps its own position within a 7-day retention period, so a slow team only increases its own lag. |
| <span style="white-space:nowrap">Costs</span> | The schema becomes a public contract, so changes must be additive, checked by a schema registry, and moved to a v2 topic when breaking. Saving and publishing are two writes, so checkout needs an outbox. Delivery is at least once, so every subscriber skips repeated eventId values. |
| <span style="white-space:nowrap">When to skip</span> | Skip it for a single consumer, where a message queue is simpler, and for a reply, where waiting for one subscriber is a slow request-response. Ordered steps that may need undoing, like reserve, charge, and ship, need an orchestrator (see Saga). Across a company boundary, use webhooks. |
| <span style="white-space:nowrap">30-second answer</span> | Checkout saves the order and publishes order.placed through an outbox, and each of the five teams has its own subscription. Subscribers remove duplicates by event ID, and the schema changes only by adding fields, checked by a registry. Pub/sub carries independent reactions, and an orchestrator runs ordered steps. |
Flashcards Review
Which five teams want every order in the store?
Reading Progress
0%
On This Page
What Publish-Subscribe Means
A Topic Is Not a Queue
Each Subscriber Reads at Its Own Pace
The Event Is a Public Contract
Publishing Without Losing Events
Independent Reactions Versus Ordered Steps
When to Use Publish-Subscribe
Check Yourself
Summary