Course contents

07. Messaging and Event-Driven Systems Lesson 3 of 10

Publish/Subscribe

Fan one event out to many services: subscriptions vs a shared queue, adding subscribers, slow and crashed consumers, fan-out cost and duplicate delivery.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A queue hands each message to one consumer; different services on one queue each see only part of the stream.
  • A topic copies every message into each subscription; consumers within a subscription compete for its messages.
  • New subscribers attach without touching the publisher, but every subscription adds a full copy of the stream.
  • Each subscription buffers on its own: slow or crashed consumers build their own backlog without slowing anyone else.
  • Delivery is at-least-once per subscription, so every subscriber needs idempotent handling.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. A work queue: one message, one consumer

    Every order puts an "order placed" message on a queue. Two email workers take messages from it: each message goes to exactly one of them, and together they send one confirmation per order.

    This is the competing consumers pattern. The workers are copies of the same job, so splitting the messages between them is exactly what we want: more workers, more throughput.

    Scene: The Orders API puts one message per order on the Orders Queue. Email 1 and Email 2 each take about half of the messages; every order gets one email.

    Key idea: A queue delivers each message to one consumer. Consumers on the same queue share the work.

  2. 2. Another team wants the same events

    The analytics team also needs every order. They attach their consumer to the same queue.

    But a queue still hands each message to one consumer. Analytics now takes about a third of the messages, and those orders never get a confirmation email. Analytics, in turn, sees only a third of the orders. Neither team gets what it needs.

    Scene: Analytics consumes from the same Orders Queue. Messages are split three ways: about a third of orders reach Analytics and get no email.

    Key idea: Different services on one queue compete for messages. Each one sees only part of the stream.

  3. 3. Publish to a topic

    The API now publishes to a topic. Each interested service has its own subscription, a queue the topic fills with a copy of every message.

    Email and Analytics now each receive every order. Inside the Email subscription the two workers still compete, sharing its messages; across subscriptions every service gets the whole stream.

    The API knows only the topic. It does not know, or care, who listens.

    Scene: The API publishes to the Order Events topic, which copies each message into the Email and Analytics subscriptions. Both services process every order; the two email workers share the Email subscription.

    Key idea: Publish/subscribe: one publish, one copy per subscription. Within a subscription, consumers share the work.

  4. 4. Adding a subscriber touches nothing else

    A fraud-detection service needs the orders too. It creates a Fraud subscription on the topic and starts consuming. The API is not changed or redeployed, and its latency is the same as before.

    Note the cost, though: every order now produces three messages to store and deliver. Fan-out multiplies the broker’s work and the total consumer work with every subscriber.

    Scene: A Fraud subscription and worker are added. The topic now copies every order into three subscriptions; the API is unchanged and just as fast.

    Key idea: New consumers subscribe without changing the publisher, but each subscription adds a full copy of the stream.

  5. 5. One slow subscriber

    One second in, the analytics warehouse slows down and every Analytics message takes six times longer. Analytics can now handle only about 17 messages per second out of 30.

    Its subscription’s backlog grows steadily. Email and Fraud are unaffected: their subscriptions stay near empty, and the API publishes as fast as ever. Each subscription is its own buffer, so one slow consumer does not slow the others.

    That isolation has a limit: the backlog lives in the broker, and an ever-growing one eventually hits retention or storage limits. Watch the age of the oldest message per subscription.

    Scene: Analytics becomes six times slower and its subscription’s backlog grows. The Email and Fraud subscriptions stay near empty and the API is unaffected.

    Key idea: Subscriptions isolate consumers from each other: a slow one builds its own backlog without slowing the publisher or other subscribers.

  6. 6. A subscriber is down for a while

    Analytics is fixed. Now, one second in, the Fraud worker crashes and stays down for three seconds.

    The topic keeps copying orders into the Fraud subscription, where they wait. Nothing is lost and nobody else notices. When the worker comes back it works through the backlog faster than new orders arrive, and the queue drains.

    This is a durable subscription: it exists in the broker whether or not a consumer is connected. (Some pub/sub systems, like plain Redis pub/sub, drop messages for subscribers that are not connected.)

    Scene: The Fraud worker is offline for three seconds. Messages pile up in the Fraud subscription, then drain when it recovers. Email and Analytics are unaffected.

    Key idea: A durable subscription keeps messages for a consumer that is down, so it can catch up later.

  7. 7. At least once means sometimes twice

    Subscriptions deliver at least once: a message counts as handled only when the consumer acknowledges it, and one not acknowledged in time is delivered again.

    The Email subscription’s visibility timeout was lowered to 0.8 s, and the email provider has become erratic: most sends still take about 150 ms, a few take seconds. Those slow sends are delivered a second time while the first attempt is still running, and both complete. Some customers get two emails.

    Every subscriber must be idempotent: record the event id it has handled and skip repeats. Each subscription handles its own duplicates; the topic cannot do it for them.

    Scene: Some email sends take longer than the 0.8 s visibility timeout, so the Email subscription delivers those messages again and both attempts complete: duplicate emails.

    Key idea: Pub/sub delivery is at-least-once per subscription. Every consumer needs idempotent handling.

  8. 8. Queue or topic?

    Use a queue when a message is a job that one worker should do. Use a topic when a message is a fact ("order placed") that several independent services react to.

    Pub/sub lets you add consumers without touching the publisher and keeps them isolated from each other. In exchange: work multiplies with every subscriber, ordering and timing differ per subscriber, every consumer must be idempotent, and every subscription is a backlog someone must monitor.

    Scene: The API publishes to the Order Events topic; Email (two workers), Analytics and Fraud each consume their own subscription. Everything is healthy.

    Key idea: Queues distribute work; topics broadcast facts. Most systems use both: a topic in front, competing consumers inside each subscription.