The Publish-Subscribe Model
A beginner-friendly guide to one of the most important patterns in software design — how programs can talk to each other without knowing who is listening, explained step by step with everyday analogies.
Think about a newspaper. The publisher does not know your name, your address, or how many other people are reading today’s edition. It simply prints the paper and sends it out. Anyone who wants it can subscribe, and anyone who no longer wants it can cancel, without ever contacting the publisher directly or disturbing anyone else’s subscription. This simple idea — announce something once, let anyone interested receive it — is the heart of a pattern used everywhere in software, called the publish-subscribe model. In this guide we will build up the whole picture slowly, defining every new word the first time it appears.
1The Problem: Everyone Talking to Everyone
Before learning a solution, it helps to feel the problem it was built to solve.
Direct communication does not scale
Imagine a weather station that measures temperature every minute. A mobile app wants this reading. So does a farming dashboard, a news ticker, and a research database. The simplest approach is for the weather station to call each of these programs directly, one by one, every single minute. This works fine with three or four listeners. But what happens when fifty new apps want the same reading? The weather station’s code must be changed every time someone new wants to listen, and it must remember the exact address of everyone it talks to.
Software engineers call this kind of arrangement tight coupling, meaning two programs are so directly wired together that a change in one forces a change in the other. Tight coupling makes systems fragile and hard to grow, because the sender must always know the full list of receivers, and the whole system can slow down if any one receiver is slow to respond.
Imagine you have exciting news and, instead of posting it once, you had to personally phone every single friend, one after another, reading them the same sentence each time. It would take forever, you would need everyone’s phone number memorized, and adding a new friend would mean remembering to call them too. A group announcement, like a notice board, removes all of that effort.
What we actually want
What most systems really need is a way to announce “something happened” without caring who is listening, how many listeners there are, or what they plan to do with the news. The sender’s job should end the moment it shares the information. This is exactly what the publish-subscribe model provides.
2So, What Is the Publish-Subscribe Model?
The pattern in one sentence, and then in plain words.
A short definition
The publish-subscribe model, often shortened to pub-sub, is a messaging pattern in which senders, called publishers, send messages without knowing who will receive them, and receivers, called subscribers, express interest in certain kinds of messages without knowing who sent them. A go-between, usually called a broker or message bus, sits in the middle, collecting messages from publishers and forwarding them to every matching subscriber.
In everyday terms, a publisher shouts an announcement into the air, the broker hears it and knows who has asked to be told about announcements like that one, and each interested party receives a copy. The publisher never learns who received it, and subscribers never learn who else is listening.
Where the idea comes from
The pattern grew out of much older ideas in computing, such as the observer pattern used inside single programs, where one part of an application notifies other parts when something changes. As software systems grew from single programs into networks of many separate services, the same notify-whoever-is-interested idea was extended across machines and the network, giving rise to dedicated pub-sub systems. Today the pattern shows up everywhere, from small mobile apps to the backbone of the largest technology companies in the world.
Pub-sub is a pattern, not a single product. Many different tools implement it, including dedicated messaging systems, event streaming platforms, and simple in-app libraries. The core idea — publish once, deliver to many, without either side knowing the other — stays the same across all of them.
3The Core Building Blocks
Five words explain most of the pub-sub pattern. Learn these and the rest becomes easy.
Publisher
Any program that creates and sends out a message, without knowing or caring who will read it. A weather station publishing a temperature reading is a publisher.
Subscriber
Any program that has expressed interest in certain messages and receives a copy whenever one is published. A weather app is a subscriber to temperature readings.
Message (Event)
The actual piece of information being shared, such as “temperature is now 24 degrees”. It usually carries a timestamp and some structured content.
Broker (Message Bus)
The middleman software that receives messages from publishers, figures out which subscribers care, and delivers copies to them.
Topic (Channel)
A named category that groups related messages together, so subscribers can say “I only want weather updates” rather than receiving everything.
Why the broker matters so much
The broker is what makes the whole pattern work without publishers and subscribers ever needing each other’s contact details. It keeps track of who is subscribed to what, receives every published message, and takes on the job of delivering it to the right places. Without a broker, publishers would be back to calling every subscriber directly, which is the exact problem pub-sub was built to avoid.
Think of a radio station. The station is the publisher. It broadcasts music on a certain frequency, which is the topic. Anyone with a radio tuned to that frequency is a subscriber. The airwaves themselves act as the broker, carrying the signal to every tuned radio without the station knowing how many radios are on, or who owns them.
flowchart LR
P1[Publisher: Weather Station] --> B
B --> S1[Subscriber: Mobile App]
B --> S2[Subscriber: Farming Dashboard]
B --> S3[Subscriber: News Ticker]
4Topics: Organizing the Noise
Without topics, every subscriber would drown in messages meant for someone else.
Grouping related messages
A real system publishes many different kinds of messages. An online shop might publish order updates, payment confirmations, and stock level changes, all at the same time. If every subscriber received every message, most of it would be irrelevant noise. Topics solve this by giving each kind of message a name, so a subscriber can choose exactly what it wants to hear about.
Two common ways to filter
There are generally two styles of filtering. In topic-based filtering, messages are published to a named channel, such as “orders” or “payments”, and subscribers pick the channels they care about, receiving everything sent to that channel. In content-based filtering, subscribers describe the kind of message they want using conditions, such as “only orders over one hundred dollars”, and the broker checks each message’s content against every subscriber’s conditions. Topic-based filtering is simpler and far more common, while content-based filtering is more powerful but more demanding for the broker to compute.
A topic is like a specific magazine subscription. You do not subscribe to “all printed material in the world” — you subscribe to “Cooking Weekly” or “Car Monthly”, and only issues of that magazine arrive at your door. Content-based filtering would be like asking for only the recipes in “Cooking Weekly” that use fewer than five ingredients, which is a much more specific request.
| Filtering style | How it works | Trade-off |
|---|---|---|
| Topic-based | Subscribe to a named channel | Simple and fast, but coarse-grained |
| Content-based | Subscribe using conditions on message content | Flexible, but heavier work for the broker |
Beginners sometimes assume a subscriber automatically gets messages from every topic. In reality, a subscriber only receives messages from the topics it has explicitly subscribed to. Interest must always be declared first.
5How a Message Travels: The Full Journey
Follow a single message from the moment it is born to the moment it is read.
Something happens
A real-world event occurs, such as a customer placing an order or a sensor recording a new reading.
The publisher creates a message
The relevant program packages the event into a message and sends it to a chosen topic on the broker, then moves on to its next task.
The broker receives it
The broker accepts the message and checks its internal list of who has subscribed to that topic.
The broker matches interested subscribers
Every subscriber whose interest matches the topic, or the message’s content in content-based systems, is identified for delivery.
Delivery happens
The broker sends a copy of the message to each matching subscriber, either by pushing it to them immediately or letting them pull it when ready.
Subscribers process it
Each subscriber handles the message in its own way and at its own pace, completely independent of what the other subscribers are doing.
sequenceDiagram
participant Pub as Publisher
participant Br as Broker
participant S1 as Subscriber A
participant S2 as Subscriber B
Pub->>Br: Publish message to topic "orders"
Br->>S1: Deliver copy
Br->>S2: Deliver copy
S1-->>Br: Processed independently
S2-->>Br: Processed independently
6Push Versus Pull Delivery
There are two ways a subscriber can actually receive its messages.
Push delivery
In push delivery, the broker actively sends messages to subscribers the moment they arrive, without waiting to be asked. This feels instant and is simple for the subscriber, but it means a slow or overwhelmed subscriber can be flooded with messages faster than it can handle them.
Pull delivery
In pull delivery, subscribers ask the broker for new messages whenever they are ready. This gives subscribers control over their own pace, since nothing arrives faster than they request it, but it introduces a small delay between a message being published and a subscriber actually noticing it, depending on how often it asks.
Push delivery is like a doorbell that rings the instant a parcel arrives, whether or not you are ready to answer the door. Pull delivery is like checking your mailbox yourself whenever you feel like it. Push is more immediate, pull is more forgiving of a busy household.
Push Delivery
- Very low delay between publish and receipt
- Simple for the subscriber to implement
- Can overwhelm a slow subscriber
Pull Delivery
- Subscriber controls its own pace
- Naturally resistant to being overwhelmed
- Slightly more delay, depending on polling frequency
7Delivery Guarantees: How Sure Can You Be?
Networks and machines fail sometimes, so pub-sub systems let you choose how strict to be about delivery.
Three common promises
When a message travels from a publisher to a subscriber, three outcomes are possible. At-most-once delivery means the message might be lost along the way but will never be delivered twice. At-least-once delivery means the message is never lost, but it might occasionally be delivered more than once if something goes wrong and a retry happens. Exactly-once delivery means the message is neither lost nor duplicated, which is the hardest promise to keep and usually the most expensive to guarantee.
| Guarantee | What can happen | Typical use |
|---|---|---|
| At most once | May be lost, never duplicated | Non-critical live data, such as a live cursor position |
| At least once | Never lost, may be duplicated | Most everyday systems, especially if duplicates are handled safely |
| Exactly once | Neither lost nor duplicated | Financial or billing events that must be counted precisely |
Imagine sending an important form by courier. With at-most-once, you send it and hope for the best. With at-least-once, you keep sending copies until the receiver confirms, so they may get two. With exactly-once, the receiver stamps a unique number on each copy and throws away any repeat with a number they have already seen.
Many teams choose at-least-once delivery and design their subscribers to safely handle receiving the same message twice, a property called idempotence. This is often much simpler to build than a true exactly-once system, and works well for most everyday needs.
8Pub-Sub Compared with Other Messaging Styles
Pub-sub is not the only way programs can send each other messages. Seeing it next to the alternatives makes it clearer.
Point-to-point queues
In a point-to-point queue, a message sent by a producer is delivered to exactly one consumer, even if several consumers are listening. This is useful for distributing tasks among a group of workers, where you want each task handled once and only once. Pub-sub is the opposite: a message is delivered to every interested subscriber, not just one.
Request-response
In a request-response pattern, one program directly asks another a question and waits for a direct answer, similar to a phone call. This requires both sides to know about each other and to be available at the same time. Pub-sub removes both requirements: publishers do not wait for a reply, and subscribers do not need to be online at the exact moment a message is published, if the broker is designed to hold messages for them.
| Pattern | Who receives each message | Sender and receiver know each other? |
|---|---|---|
| Request-response | One specific receiver, directly addressed | Yes, directly |
| Point-to-point queue | Exactly one consumer from a pool | No, but only one gets it |
| Publish-subscribe | Every interested subscriber | No, fully decoupled |
If you want a task done once by any available worker, a point-to-point queue fits best. If you want every interested part of your system to learn about something that happened, publish-subscribe is the natural choice.
9Advantages and Trade-offs
No pattern is free of cost. Knowing the trade-offs helps you use pub-sub wisely.
Advantages
- Publishers and subscribers are fully decoupled from each other
- New subscribers can be added without changing the publisher
- Naturally supports many-to-many communication
- Publishers are never slowed down waiting for subscribers
- Systems can grow and evolve piece by piece
Disadvantages / Trade-offs
- The broker becomes a critical piece of infrastructure that must be reliable
- Harder to trace the exact path a message took while debugging
- Delivery guarantees add complexity depending on how strict they need to be
- Too many topics with unclear naming can become confusing to manage
- Overkill for two programs that only ever need to talk to each other directly
10Security in Pub-Sub Systems
Because a broker often carries sensitive business information, protecting it matters.
Encryption in Transit
Messages travelling between publishers, the broker, and subscribers can be encrypted so that anyone intercepting the network traffic sees only scrambled data.
Authentication
Publishers and subscribers prove their identity before the broker lets them send or receive anything, keeping unknown programs out.
Authorization
Rules decide which programs may publish to a given topic and which may subscribe to it, so sensitive topics stay limited to the right systems.
Auditing
Recording who published or subscribed to what, and when, helps teams investigate problems and meet compliance requirements.
Securing a broker is like securing a private radio network. Encryption scrambles the signal so outsiders cannot listen in, authentication checks each radio’s ID before it can transmit or receive, authorization decides which channels a given radio is allowed to use, and auditing is the log book recording who used which channel and when.
11Monitoring a Pub-Sub System
A broker you cannot see is a broker you cannot trust.
Message Backlog
How many published messages are still waiting to be delivered or processed. A growing backlog means subscribers cannot keep up.
Delivery Latency
How long it takes a message to travel from being published to being received by a subscriber.
Throughput
How many messages per second are being published and delivered across the system.
Failed Deliveries
How often a message could not be delivered to a subscriber, which may point to a crashed or unreachable service.
Broker Health
Whether the broker itself, and any machines it runs on, are online and responding normally.
If you set up only one alert, make it backlog size. A rising backlog is usually the earliest sign that some subscriber is struggling to keep pace with the real world.
12Design Patterns and Anti-patterns
Good habits to copy and bad habits to avoid when using pub-sub.
Helpful patterns
Event-Driven Architecture
Services announce facts as they happen and other services react, keeping the whole system loosely connected and independently scalable.
Fan-out Notification
One event, such as “order placed”, is published once and fans out to many unrelated systems, such as billing, shipping, and analytics, all at once.
Dead Letter Topic
Messages a subscriber repeatedly fails to process are routed to a separate topic for later inspection, so one bad message does not block everything else.
Habits to avoid
Problem
Using a single, broadly named topic for every kind of message in the whole system.
Why It’s Harmful
Subscribers must sift through irrelevant messages, and it becomes impossible to control who can access which kind of data.
Correct Approach
Create focused topics with clear, specific names that reflect the kind of event they carry.
Problem
Assuming messages will always arrive in the exact order they were published, without checking whether the chosen broker actually promises this.
Why It’s Harmful
Many pub-sub systems do not guarantee strict ordering across all subscribers, so relying on it silently can cause subtle bugs.
Correct Approach
Check the ordering guarantees of the specific system you are using, and design your subscribers to cope if strict ordering is not promised.
13Real-World Uses of Publish-Subscribe
The pattern quietly powers a huge amount of the software people use every day.
Mobile Push Notifications
When an app sends you a notification, it typically publishes a message describing the alert, and a notification service delivers it to every subscribed device, without the app needing to know your phone’s exact address.
Stock Price Updates
Financial platforms publish price changes as they happen, and every connected trading screen, app, and alerting system subscribes to receive live updates instantly.
Chat Applications
When someone sends a message in a group chat, it is published once and delivered to every member currently subscribed to that conversation.
IoT and Smart Devices
Sensors in homes, factories, and vehicles publish readings, and multiple systems, such as dashboards, alerting tools, and data archives, subscribe to the same stream independently.
Microservices Communication
In systems built from many small services, pub-sub lets one service announce a fact, such as “user registered”, while other services react in their own way, without being directly wired together.
Live Collaboration Tools
When someone edits a shared document or moves a cursor, that change is published and every other open session subscribed to that document receives the update in real time.
14Best Practices and Common Mistakes
Practical lessons that save teams from painful surprises.
Best practices
Name topics clearly
Use consistent, descriptive topic names so anyone browsing the system can understand what each one carries without guessing.
Design messages to stand alone
Include enough information in each message that a subscriber does not need to call back the publisher to understand it.
Make subscribers safe against repeats
Design processing so receiving the same message twice causes no harm, which makes recovering from failures far easier.
Agree on message formats
Define and document the shape of each topic’s messages so publishers and subscribers do not drift apart over time.
Monitor backlog and failures
Watch delivery metrics closely so a struggling subscriber is noticed and fixed before it causes bigger problems.
Mistakes beginners often make
Every broker can fail or become overloaded. Systems should plan for what happens if the broker is briefly unreachable, rather than assuming perfect uptime.
Under at-least-once delivery, duplicates will eventually happen. Subscribers that assume every message is unique will eventually process something twice by accident.
If only two programs will ever talk to each other and nothing else needs the information, a direct call may be simpler than adding a whole broker into the picture.
15Frequently Asked Questions
Not quite. A classic queue usually delivers each message to exactly one consumer. Pub-sub delivers each message to every subscriber interested in that topic, so the two solve different problems.
Not necessarily. If the broker is designed to hold messages for a while, a subscriber that starts later can still receive messages published earlier, depending on how the system is configured.
Yes. A single program can publish to some topics and subscribe to others at the same time, which is common in larger systems built from many cooperating services.
The publisher still sends its message successfully, since it never checks who is listening. Depending on the system, the message may simply be discarded if there is nobody to deliver it to.
No. Small applications use it too, often through lightweight in-app libraries, whenever different parts of an app need to react to the same event without being tightly wired together.
A callback usually connects two specific pieces of code directly. Pub-sub adds a broker in between, so any number of unrelated listeners can react to the same event without the publisher knowing about any of them individually.
Yes. Subscribing and unsubscribing are meant to be easy and safe operations that do not affect the publisher or any other subscriber.
16Summary and Key Takeaways
The publish-subscribe model is a messaging pattern that lets programs share information without ever needing to know each other directly. Publishers announce messages to named topics, a broker takes on the job of tracking interest and delivering copies, and subscribers receive only the messages they have chosen to care about. This decoupling makes systems easier to grow, since new subscribers can be added without touching the publisher, and it supports the many-to-many communication that modern software increasingly depends on. Like every pattern, it comes with trade-offs around reliability, ordering, and delivery guarantees that are worth understanding before relying on it. Used thoughtfully, publish-subscribe gives teams a simple, flexible way to build systems that stay loosely connected and ready to grow.
Key Takeaways
- Pub-sub decouples senders from receivers — publishers and subscribers never need to know about each other directly.
- The broker does the heavy lifting — it tracks interest and delivers messages, freeing publishers from that responsibility entirely.
- Topics organise the flow — subscribers choose exactly what they want to hear about, avoiding irrelevant noise.
- Push and pull are two delivery styles — each with its own trade-off between immediacy and subscriber control.
- Delivery guarantees vary — at-most-once, at-least-once, and exactly-once each fit different needs and costs.
- Pub-sub differs from queues and request-response — it is built for one message reaching many independent listeners.
- Choose it deliberately — pub-sub shines when many parts of a system must react to the same events, but can be more than a simple two-program conversation needs.