Publish/Subscribe Pattern
Publish/subscribe decouples senders from receivers: publishers emit messages to a topic without knowing who consumes them, and subscribers receive messages from topics they care about.
WHY IT EXISTS Direct, point-to-point communication forces a sender to know every receiver and to wait on them, creating tight coupling and brittle systems. As applications grew into many services that all needed to react to the same events, teams needed a way to broadcast events without hard-wiring producers to consumers. Publish/subscribe exists to decouple who emits an event from who reacts to it.
THE MENTAL MODEL Think of a magazine subscription. The publisher prints an issue and sends it to a distribution service; it has no idea who the individual readers are. Readers subscribe to the magazines they care about and receive every new issue automatically. New readers can subscribe and old ones can cancel at any time, and the publisher's job never changes.
HOW IT WORKS There are three roles: publishers, subscribers, and a broker or message bus. Publishers send messages tagged with a topic to the broker. Subscribers register interest in one or more topics. The broker maintains the subscription registry and, on each publish, routes a copy of the message to every matching subscriber, often asynchronously through queues. Messaging can be topic-based, where you subscribe to named channels, or content-based, where the broker filters by message attributes. Brokers may offer delivery guarantees, durable subscriptions, and ordering, with varying trade-offs.
WHEN IT MATTERS It matters for event-driven and microservice architectures where one event must trigger many independent reactions, such as an order placement updating inventory, billing, and notifications. It enables fan-out, asynchronous processing, and independent scaling of consumers. It is less suited when a strict request-response with an immediate reply is required, or when guaranteed exactly-once ordered delivery is hard to satisfy.
ONE CONCRETE EXAMPLE An e-commerce service publishes an OrderPlaced event to an orders topic. A billing service, an inventory service, and an email service each subscribe to that topic. When an order is placed, the broker delivers the event to all three, which charge the card, decrement stock, and send a confirmation, all without the order service knowing any of them exist. A new analytics consumer can subscribe later with zero changes to the publisher.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.