Back to all terms
S1S2S3
State & Archintermediate

Pub/Sub Pattern

A messaging pattern where publishers emit events to a message broker without knowledge of subscribers, enabling loose coupling between components.

Also known as: Publish-Subscribe, Publish/Subscribe Pattern, Message Bus Pattern

Description

The Publish-Subscribe pattern decouples message producers (publishers) from message consumers (subscribers) by introducing an intermediary message broker or event bus. Publishers emit named events or messages to the broker without knowing which, if any, subscribers exist. Subscribers register interest in specific event types with the broker, and the broker routes matching messages to them. This indirection enables extremely loose coupling: components can be added, removed, or modified independently as long as the message contract is maintained.

In frontend applications, Pub/Sub manifests as custom event emitters (Node.js EventEmitter, browser CustomEvents), framework-specific event buses (mitt, tiny-emitter), or global state tools that notify subscribers of changes. In backend and distributed systems, Pub/Sub is implemented by message brokers like Redis Pub/Sub, Google Cloud Pub/Sub, AWS SNS, RabbitMQ with fanout exchanges, and Apache Kafka's topic-based consumer groups. These systems add durability, ordering guarantees, and at-least-once delivery semantics.

The Pub/Sub pattern excels when you need to broadcast events to multiple consumers—audit logging, analytics, notification systems, cache invalidation—without introducing direct dependencies. However, it introduces complexity in debugging (messages are invisible to the call stack), can lead to event storms if publishers emit too frequently, and requires careful design around message ordering, idempotency, and dead-letter handling for failed deliveries.

Prompt Snippet

Implement an event-driven notification pipeline using Redis Pub/Sub for real-time fan-out and a durable fallback via AWS SQS for guaranteed delivery. Each microservice subscribes to specific channel patterns (e.g., 'order.*', 'user.updated') with idempotent handlers keyed on a unique event ID stored in a deduplication table with a 24-hour TTL. Include a dead-letter queue with CloudWatch alarms for messages that fail processing after three retry attempts with exponential backoff.

Tags

messagingarchitecturedesign-patternsevent-drivendecoupling