What it is
Publish/subscribe (pub/sub) is a messaging pattern where a publisher sends a message to a topic without knowing who will receive it, and every subscriber interested in that topic gets its own copy. Compare it with a work queue, where each message is delivered to exactly one of the consumers.
Why it exists
Many events matter to several parts of a system. An order being placed should trigger a confirmation email, an analytics record, a fraud check and a warehouse pick list. Calling each of those services from the order service couples it to all of them: it must know them, wait for them and change whenever a new one appears. Putting the event on one shared queue doesn't work either, because the consumers would split the messages between them. Pub/sub lets the order service announce one fact once, and lets any number of services react to it independently.
How it works
Topics and subscriptions. The publisher sends to a topic. Each consuming service owns a subscription on that topic. The broker stores a copy of every new message in every subscription, and each subscription behaves like its own queue: messages wait there until that service's consumers take and acknowledge them.
Competing consumers inside a subscription. A service usually runs several instances. They all read from the same subscription and share its messages, exactly like workers on a work queue. Kafka calls this a consumer group; SNS + SQS achieve it with one SQS queue per service; RabbitMQ binds one queue per service to an exchange.
Durability. In most brokers a subscription is durable: it collects messages whether or not a consumer is connected, so a consumer that is down catches up later. Some systems (Redis PUBLISH/SUBSCRIBE, many in-process event buses) deliver only to subscribers connected at that moment, and messages for absent subscribers are gone.
Acknowledgement and redelivery. As with queues, a consumer acknowledges a message after processing it. Unacknowledged messages come back after a timeout, so delivery is at-least-once, independently for each subscription.
Log-based variants. Event streaming systems (Kafka, Kinesis, Pulsar) keep messages in an ordered log for a retention period. Each consumer group tracks its own position in the log instead of having its own copy. The effect is the same, and new subscribers can even replay old events.
When to use it
- One event, several independent reactions: notifications, analytics, search indexing, cache invalidation, audit logs.
- When new consumers will appear over time and the producer shouldn't change for each one.
- To keep services decoupled in time and availability: a consumer can be down or slow without affecting the producer.
When not to
- A job that one worker should do once (resize this image, charge this card). Use a work queue.
- When the caller needs the result to answer its own request. Pub/sub is fire-and-forget from the publisher's side.
- For a strict multi-step workflow where step 2 must follow step 1's outcome. Chains of events reacting to events become hard to follow; an orchestrator or a workflow engine is clearer.
- When you can't afford the operational cost: every subscription is a backlog to monitor.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Topic instead of direct calls | Publisher doesn't know or wait for consumers | Eventual processing; harder to trace what happens after an event |
| Topic instead of a shared queue | Every service gets every event | Storage and delivery multiplied by the number of subscriptions |
| Durable subscriptions | Consumers can be down and catch up | Backlogs that grow without bound if a consumer stays broken |
| Fat events (full data) | Consumers need no callbacks to the publisher | Larger messages, schema coupling, possibly stale data |
| Thin events (ids only) | Small messages, consumers read current data | Every consumer calls back to the publisher, adding load |
Alternatives
- Direct calls (HTTP/gRPC) when the caller needs the answer now and there are only one or two consumers.
- Work queues (competing consumers) for jobs that should happen once.
- Event streaming logs (Kafka) when consumers need ordering per key, replay of history or very high throughput.
- Change data capture (Debezium) publishes database changes as events without changing the application, often combined with the transactional outbox pattern.
Failure modes
- Slow subscriber. Its subscription backlog grows; eventually messages hit the retention limit and expire, or storage fills. Alert on the age of the oldest message per subscription, not only on count.
- Lost messages on publish. If the service saves an order and then crashes before publishing, the event never exists. The transactional outbox (write the event in the same database transaction, publish it afterwards) fixes that.
- Duplicates. Consumer crashes, slow processing past the visibility timeout and broker failovers all cause redelivery. Non-idempotent consumers double-charge, double-email or double-count.
- Poison messages. A message that always fails blocks or slows its subscription; cap deliveries and move it to a dead letter queue.
- Schema changes. Every subscriber parses the event. An incompatible change breaks consumers the publisher doesn't even know about. Version events and only add fields.
- Ordering. Different subscribers process the same events at different times, and within a subscription parallel consumers can reorder them.
In production
Name topics after facts ("order-placed"), not commands. Give every subscriber its own subscription and dead letter queue. Make every consumer idempotent, usually by storing handled event ids alongside the effect. Monitor per subscription: backlog size, age of the oldest message, error and redelivery rates. Publish through an outbox when the event must be consistent with a database write. Keep a schema registry or at least versioned event contracts.
Common misconceptions
- "Several consumers on one queue each get every message." No, they compete. That is a work queue. Broadcasting needs one subscription per service.
- "Pub/sub is exactly-once." Delivery is at-least-once per subscription. "Exactly-once" offerings cover narrow cases (a broker transaction); the end-to-end effect still needs idempotent consumers.
- "Adding subscribers is free." It doesn't cost the publisher anything, but the broker and the system as a whole do one more copy of all the work.
- "Decoupled means independent." Subscribers still depend on the event's schema and meaning. Changing them is a contract change.
Interview angle
Pub/sub appears whenever one action triggers several side effects: say "the order service publishes OrderPlaced; email, analytics and inventory each consume their own subscription". Expect follow-ups: how a new consumer is added, what happens when one consumer is slow or down (its own backlog; monitor age), how duplicates are handled (idempotency keys), how you avoid losing events between the database write and the publish (outbox), and when you'd use Kafka consumer groups instead of SNS/SQS-style topics (ordering per key, replay, throughput).
Model assumptions
The simulation in this lesson is a simplified model, not a benchmark. Orders arrive at random (Poisson) at 30 per second; publishing costs the API about 10 ms. The topic copies every message into each subscription at once; subscriptions are durable queues with room for 100,000 messages, a 3-second visibility timeout (0.8 s in the duplicates step) and redelivery of unacknowledged messages. Email workers take about 150 ms per message, Analytics about 40 ms and Fraud about 60 ms (lognormal, cv 0.3; cv 1.5 for the erratic email provider); each worker node processes 4 messages at a time. A consumer that crashes is restarted with nothing in progress; its unacknowledged messages come back after the timeout. Not modelled: retention limits, ordering guarantees, broker failures, publish-side failures (outbox) and the publisher's view of a missing subscriber. A subscription that is full or down when its copy arrives does not store it: the copy is counted as dropped (it is lost for that subscriber only; the publisher is still told "published"), but the lessons' steps never fill or crash a subscription, so the Dropped count stays at zero here. Message accounting: each message ends in one outcome, counted once: delivered (first successful acknowledgement), dead-lettered (moved to a dead letter queue after its last delivery) or dropped (it ran out of deliveries with no dead letter queue connected, or a subscription was full or down when its copy arrived). Redelivered (a delivery that came back after its timeout) and duplicates (a message processed again after it had already been processed) are not outcomes: they count extra deliveries of messages that are counted once above. Numbers show behaviour and orders of magnitude only.