SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

Pub/Sub

Publish once and every subscriber gets a copy.

⏱ 12 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Pub/Sub (publish/subscribe) is a way to send a message to many receivers at once. A publisher sends a message to a topic. Every subscriber of that topic gets its own copy.

  • The publisher does not know who the subscribers are.
  • You can add a new subscriber without changing the publisher.
  • Queue: one message, one consumer. Pub/Sub: one message, many consumers.

02Concept: What is it?

In Pub/Sub, messages are grouped by topic (for example orders or alerts). Publishers send to a topic. Subscribers say which topics they care about. A broker in the middle delivers the copies.

Publish once, deliver many
πŸ“£PublisherOrder service
→↓publish
🧾Topic: orders
→↓copy
πŸ“§Email service
πŸ“ŠAnalytics
πŸ“¦Inventory
One β€œorder placed” event reaches three different services. The publisher does not call them one by one.

Queue vs Pub/Sub

Queue (point to point)
Share the work
  • Each message goes to ONE consumer
  • Workers compete for jobs
  • Best for tasks: send this email, resize this photo
Pub/Sub (fan-out)
Tell everyone
  • Each message goes to ALL subscribers
  • Each subscriber has its own copy
  • Best for events: an order was placed, a user signed up

03Real-Life Example

🍡The School Notice Board
The principal pins a notice: β€œSports day on Friday”. The principal does not visit every class. Students who follow the sports board read it. Students who follow the exams board do not see it. A new student can start following a board at any time.
School notice board
Pub/Sub
Principal
Publisher
A named notice board (sports, exams)
Topic
Pinning a notice
Publishing a message
Students who follow a board
Subscribers
Each student reads their own way
Each subscriber has its own copy and speed
The school office that manages boards
Message broker
Ride app: a trip ends
πŸš•Trip servicetrip.ended
→↓
🧾Topic: trips
→↓
πŸ’³Billing
⭐Rating
πŸ“§Receipt
πŸ“ŠReports

04Why Do We Need It?

πŸ”ŒLoose coupling
The publisher knows only the topic, not the listeners.
βž•Easy to add features
A new service subscribes. No change to old code.
πŸ“£Fan-out
One event can trigger many actions at once.
🧩Independent speeds
Each subscriber works at its own pace.
πŸ›‘οΈIsolated failures
If analytics is down, billing still works.
🌍Event-driven design
Systems react to β€œwhat happened” instead of being told what to do.
With Pub/Sub, the sender says what happened. The receivers decide what to do about it.

05Where Do We Use It?

πŸ›’Order events
Order placed β†’ email, stock, billing, analytics.
πŸ””Notifications
One alert sent to email, SMS and push.
πŸ”Search and cache sync
Database change β†’ update search index and cache.
πŸ“ˆLive dashboards
Metrics and logs sent to monitoring tools.
πŸ§‘β€πŸ€β€πŸ§‘Social feeds
A new post is announced to followers’ services.
🏭IoT
Sensors publish readings. Many apps listen.

06Types / Parts / How It Works

Parts of Pub/Sub

PartJob
PublisherSends messages to a topic. Does not know the subscribers.
TopicA named channel for one kind of message.
SubscriptionA subscriber’s β€œI want this topic” record. Often has its own backlog.
SubscriberReceives its copy and processes it.
BrokerStores messages and delivers copies (for example Google Pub/Sub, Amazon SNS, Kafka).

Delivery styles

StyleHow it worksExample (general idea)
PushThe broker calls the subscriber (for example an HTTPS endpoint).SNS to an endpoint, push subscriptions
PullThe subscriber asks the broker for messages at its own pace.Pull subscriptions, Kafka consumers

Pub/Sub plus queues

A common design: publish an event to a topic, and give each subscriber its own queue. Then every service gets a copy and can run many workers on its own queue.

Fan-out to queues
πŸ“£Publisher
→↓
🧾Topic
→↓
Email
πŸ“¬queue
πŸ‘·Γ—2
Analytics
πŸ“¬queue
πŸ‘·Γ—5
Queue Email workers Analytics workers
Each service has its own queue. A slow service only slows its own queue.
VisualizerTopics, subscribers and copiesTurn topics on and off for each subscriber, then publish. Switch to β€œQueue” mode to compare.
How does the topic deliver?
πŸ“£Publishersends once
↓
πŸ›’Topic: orders0 published
🚨Topic: alerts0 published
↓
πŸ“§ Email service
Received: 0
no messages yet
πŸ“Š Analytics
Received: 0
no messages yet
πŸ“¦ Inventory
Received: 0
no messages yet
Press 'Publish' on a topic. Then turn on 'Queue' mode and publish again to see the difference.

07How to Use It / Steps / Implementation

  1. 1
    Pick events, not commands
    Name topics after facts that happened: order.placed, user.signed_up.
  2. 2
    Create a topic
    One topic per kind of event keeps things clear.
  3. 3
    Define the message
    Include an id, a type, a time and the data. Add a version so you can change it later.
  4. 4
    Publish
    The publisher sends and moves on.
  5. 5
    Subscribe
    Each interested service creates its own subscription (and often its own queue).
  6. 6
    Make subscribers idempotent
    The same message can arrive twice. Store processed ids and skip repeats.
  7. 7
    Add retries and a dead letter queue
    So one bad message does not block a subscription.
πŸ’‘Filtering
Many brokers let a subscriber filter messages (for example only country = IN). This avoids waking up services for messages they do not need.
πŸ“Outbox again
To publish an event whenever the database changes, use the outbox pattern: write the event in the same transaction, then a relay publishes it. This keeps the data and the event in step.

08Key Terms to Know

TermMeaning in easy words
PublisherThe sender of messages
SubscriberA receiver that asked for certain topics
TopicA named channel for one kind of event
SubscriptionThe link between a subscriber and a topic
Fan-outOne message copied to many receivers
EventA fact that happened, like β€œorder placed”
Push / PullBroker sends to you / you ask the broker
FilterA rule so a subscriber only gets matching messages
Durable subscriptionMessages wait for you even when you are offline
Event-drivenA design where parts react to events

09Pros, Cons and Trade-offs

βœ… Pros
  • Publisher and subscribers are loosely coupled
  • Easy to add new subscribers
  • Great for fan-out
  • Failures stay local
  • Scales to many receivers
⚠️ Cons
  • Harder to follow the full flow of an event
  • Messages can arrive twice or out of order
  • A new subscriber may miss old messages (unless replay is supported)
  • Schema changes can break subscribers
  • Needs a broker to run and monitor

Trade-offs

ChoiceWe gainWe lose
Pub/Sub instead of direct callsLoose coupling, easy fan-outLess visibility, eventual results
A queue per subscriberEach service scales aloneMore queues to manage
Push deliverySimple for the subscriberSubscriber must handle bursts
Pull deliverySubscriber controls its speedSubscriber must poll

10Common Problems and Mistakes

Common mistakes

  1. Using Pub/Sub for a task that must run once. If three workers all subscribe to the same subscription they may each act. Use a queue or a shared subscription.
  2. Changing the message shape without a version. Old subscribers break.
  3. No idempotency. Retries create duplicates.
  4. Assuming order. Messages can arrive out of order unless the broker guarantees it for a key.
  5. Hidden dependencies. Nobody knows who listens to a topic, so a change breaks something far away. Keep a list of subscribers.
  6. Event storms. One event triggers an action that publishes another event, and so on in a loop.
πŸ•³οΈLate subscribers
A new service misses messages sent before it joined.
🐌Slow subscriber
Its backlog grows. Use its own queue and alarms.
πŸ”Duplicate events
Delivery is often at-least-once.

11Real-World Examples

☁️Cloud services
Amazon SNS and Google Pub/Sub are managed topic services.
🧡Kafka
A log of events that many consumer groups can read.
πŸ”΄Redis Pub/Sub
Light and fast, but messages are not stored if nobody is listening.
πŸ›’E-commerce and ride apps
Order and trip events fan out to billing, email and analytics.
πŸ“Note
These are general ideas. Exact features differ by product and change over time.
Mini case: new user signs up
πŸ™‹Sign up
→↓
🧾user.signed_up
→↓
πŸ‘‹Welcome email
🎁Give credit
πŸ“ŠAnalytics
πŸ›‘οΈFraud check
One event starts four separate actions.

12Related Topics to Read Next

Message Queues→

One message, one consumer. The other half of async messaging.

Message Brokers→

The software that runs topics and queues.

Delivery Semantics→

Why subscribers must handle duplicates.

Dead Letter Queues→

Where failing messages go.

Webhooks→

Notify an outside system over HTTP when something happens.

Server-Sent Events (SSE)β†’

Push updates from a server to a browser.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: publishers send to topics, and every subscriber gets a copy.
  • βœ”Queue vs Pub/Sub: queue = one consumer per message; pub/sub = all subscribers.
  • βœ”Pattern: topic + one queue per subscriber = fan-out and scaling.
  • βœ”Use for: events like order placed, user signed up, notifications.
  • βœ”Remember: delivery is often at-least-once, so make subscribers idempotent.
  • βœ”Watch: message versions, slow subscribers and unknown dependencies.
  • βœ”One line: β€œPub/Sub lets one event reach many services without the sender knowing them.”
← Previous
Message Queues
Next β†’
Message Brokers