Skip to content

The Publish/Subscribe (Pub/Sub) Pattern

One-Liner

A messaging pattern where senders (publishers) do not send messages directly to specific receivers (subscribers), but instead publish messages to topics, and subscribers receive messages from the topics they are interested in.

What It Is

A form of asynchronous, many-to-many communication. Publishers categorize messages into topics, and subscribers express interest in one or more topics. The messaging system then delivers messages from a publisher to all subscribers of that topic.

Why It Exists

To decouple services from each other. Publishers don’t need to know who the subscribers are, and subscribers don’t need to know who the publishers are. This allows for a very flexible and scalable architecture.

How It Works

  1. A publisher sends a message to a specific topic on the message broker.
  2. The message broker forwards the message to all subscribers of that topic.

Tradeoffs

Pros

  • Highly decoupled.
  • Allows for easy addition of new subscribers without changing the publisher.
  • Enables event-driven architectures.

Cons

  • Can be harder to reason about the flow of data.
  • Risk of message loss if no subscribers are active (depending on the broker configuration).

Failure Modes

  • “Slow” subscriber: A subscriber that is slow to process messages can cause back pressure on the message broker.
  • Message duplication: A subscriber might receive the same message more than once if the broker has at-least-once delivery guarantees.

Interview Traps

  • Confusing Pub/Sub with a simple message queue.

Real-World Usage

  • Sending notifications to users.
  • Distributing events in a microservices architecture.
  • Real-time data streaming.

Anti-Patterns

  • Using Pub/Sub when you need strong guarantees about the order of messages across different subscribers.
  • Message Queues
  • Event-Driven Architecture
  • Message Brokers (e.g., Kafka, RabbitMQ)