Publish-Subscribe Messaging
Publish-subscribe decouples producers from consumers through a broker and topics, letting many independent consumers react to the same event.
Definition
Publish-subscribe is a messaging pattern in which producers publish messages to a channel without knowledge of subscribers, and the messaging infrastructure delivers each message to all interested consumers.
Context and scope
It is used for event notification, fan-out to independent services, and integration where producers should not know their consumers.
Common misconceptions
- publish-subscribe guarantees each message is processed exactly once
- it is identical to a queue with a single consumer
Anti-patterns
- assuming ordering across topics is preserved
- using publish-subscribe for request-reply where a direct call would fit
Related concepts
Related examples
Authoritative source
https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
Definition
Publish-subscribe is a messaging pattern in which producers publish messages to a channel without knowledge of subscribers, and the messaging infrastructure delivers each message to all interested consumers.
It is used for event notification, fan-out to independent services, and integration where producers should not know their consumers. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.
When to use it
A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.
How it works
Fan-out is the defining property: one published message reaches every subscription, so adding a consumer does not require changing the publisher.
Delivery semantics vary by broker, and at-least-once delivery means consumers must be idempotent to tolerate duplicates.
Trade-offs and alternatives
It is asynchronous and decoupled, which improves resilience but makes end-to-end tracing and error propagation harder than in a direct call. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.
Common misconceptions
A persistent misconception is that publish-subscribe guarantees each message is processed exactly once. Another is that it is identical to a queue with a single consumer. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.
Anti-patterns to avoid
Two recurring anti-patterns are to assuming ordering across topics is preserved and to using publish-subscribe for request-reply where a direct call would fit. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Message Broker, Layered Architecture, Onion Architecture.