Course map

Topic 109 / Core

Publish/subscribe

Chapter 7.1 · Asynchronous Foundations

What and why

Competing consumers (→ 107, 108) each handle a message once — correct for distributing work, wrong for notification, where every interested party needs its own copy of the same event. Publish/subscribe delivers each published message to every subscriber, not to just one. Builds on: → 106.

Diagram

Model Who gets each message
Point-to-point (competing consumers) Exactly one consumer in the group
Publish/subscribe Every subscriber (or every subscribed group)

How it works

  1. A publisher sends a message to a topic without knowing who, if anyone, is subscribed.
  2. The broker fans the message out to every current subscriber — independent copies or independent offsets on the same log, so each subscriber proceeds at its own pace.
  3. Each subscriber processes the message independently of the others' speed or success.
  4. By default, a late subscriber only sees messages published after it subscribed, unless the broker retains history and the subscriber can start from an earlier point (→ 111).
  5. Fan-out is the deliberate trade: N subscribers do N times the total consumption work of one consumer, in exchange for decoupled, independent consumers.

Practical example

(illustrative). An "OrderPlaced" event is published once; the inventory, analytics, and notification services each subscribe and process it independently. If the analytics consumer pauses for an hour, inventory and notification are unaffected, and analytics catches up later from where it left off.

When to use it

  • Use when multiple independent parties each need every event.
  • Avoid when exactly one consumer should ever act on a message — that's competing consumers (→ 107, 108); pub/sub to a single subscriber is pure overhead.
  • Failure scenarios: a forgotten subscription silently accumulating retained messages or disk usage; assuming pub/sub orders deliveries across different subscribers — it doesn't, each is independent.
  • Simpler alternative: a direct call, or a shared table other services poll, when there is genuinely one consumer and no plan for more.

Practice

(pattern — implement a minimal version; 15–20 min, lab Kafka). Publish 10 events to a topic; attach two independently-offset consumer groups; pause one group's consumer for 30 seconds, then confirm it catches up to 10/10 without affecting the other group's progress. Done when both groups independently report all 10 events received.

Shared lab setup

Key takeaway

Publish/subscribe gives every subscriber its own full copy of the stream — the fan-out primitive behind event-driven architecture. Done when you can: explain why pub/sub's total work scales with subscriber count, not message count alone. Used next in → 112 (RabbitMQ's exchange types implement this), → 113 (event-driven architecture is built on this fan-out).

References

None — this topic makes no external claims.

Source directory

Search the guide