SysDesignAtlas

Pub/Sub & Event-Driven Architecture

Fanout messaging, event notification vs event-carried state vs event sourcing, and the coupling problems event-driven systems trade for the ones they solve.

HLDMedium10 min readpubsubeventsarchitecture
Confidence

#Pub/sub vs queues

A queue distributes work: each message goes to exactly one consumer. Pub/sub distributes information: each message goes to every subscriber.

   QUEUE (competing consumers)      PUB/SUB (fanout)

   producer → [q] → worker A        publisher → [topic] → sub A
                  → worker B                            → sub B
                  → worker C                            → sub C
   each msg to ONE worker           each msg to ALL subs

The distinction matters because it determines coupling. With a queue, the producer is choosing work to be done. With pub/sub, the producer is announcing something that happened, and it neither knows nor cares who reacts. That's the decoupling that makes event-driven architecture attractive — you can add a fifth consumer of OrderPlaced without touching the order service.

Log-based systems like Kafka do both, using consumer groups — a named set of consumers that share the work. Consumers in the same group split the messages between them, each message going to one of them (queue behaviour). Different groups each get every message (pub/sub behaviour). So the email group with 3 workers and the analytics group with 5 workers both see every OrderPlaced, and within each group the work is shared.

#Three kinds of event

A distinction that clarifies most event-driven design arguments, and one worth naming explicitly.

#1. Event notification

The event is a bare fact plus an ID.

json
{ "type": "OrderPlaced", "order_id": "8821", "at": "2026-08-07T10:00:00Z" }

Consumers that need details call back to the order service. Tiny payloads, no duplicated data, and the producer's schema stays private.

Cost: every consumer makes a synchronous callback to fetch the details, so you've reintroduced runtime coupling — the services once again have to be running at the same time. If the order service is down, consumers can't process anything. And N consumers means N callbacks per event.

#2. Event-carried state transfer

The event carries everything a consumer might need.

json
{ "type": "OrderPlaced", "order_id": "8821",
  "customer": {...}, "items": [...], "total": 4999 }

Consumers are fully autonomous — they can process events while the producer is down. Each one can keep its own local copy of just the data it needs (a read model) — the shipping service might keep a table of order addresses, updated from these events. This is the pattern that actually delivers the availability benefits people want from events.

Cost: larger payloads, duplicated data across services, and the payload becomes a public contract that's hard to change. Consumers may also act on stale state (the order changed after the event was emitted).

#3. Event sourcing

The event log is the source of truth. Current state is derived by replaying events rather than stored directly.

   AccountOpened(id=1)          →  balance 0
   Deposited(id=1, 100)         →  balance 100
   Withdrew(id=1, 30)           →  balance 70
   Deposited(id=1, 50)          →  balance 120   ← current state
                                    (a projection, rebuildable)

Genuine strengths: a complete audit trail by construction (invaluable for finance and compliance), the ability to reconstruct state at any past point in time, and the ability to build new projections over historical data — answering questions nobody thought to ask when the events were written.

Genuine costs, and you should name them:

  • Reading current state needs a projection. A projection is a table built by replaying the events (like the "balance 120" above). It's updated after each event is written, so it lags slightly behind — it's eventually consistent.
  • Old events never go away, so their format can't either. If you change the shape of Deposited, the log still holds millions of old-format ones. You version every event type and write code that converts old versions to new as they're read (upcasting) — forever.
  • You can't simply UPDATE a mistake. A wrong deposit of 100 stays in the log; you fix it by appending a new event that reverses it (a compensating event), like DepositReversed(id=1, 100).
  • Deleting personal data conflicts with an append-only log. GDPR lets a user demand erasure, but the log can't be edited. The usual fix is crypto-shredding: encrypt each person's data with their own key, and "delete" them by destroying the key, leaving their events unreadable.
  • Replay gets slower as the log grows. An account with 10 years of events takes a long time to rebuild, so you periodically save the computed state (a snapshot) and replay only the events after it.

When it's right: finance, ledgers, audit-heavy domains, and systems where "how did we get here?" is a first-class question. When it's wrong: ordinary CRUD, which is most software. Proposing event sourcing for a straightforward application is a classic over-engineering signal.

#CQRS

Command Query Responsibility Segregation — an ugly name for a simple idea: stop using one model for both writing and reading. Store writes in whatever shape keeps the data correct, and separately maintain read-shaped copies built from those writes.

   commands ──► write model ──► events ──┬──► read model A (SQL)
              (normalized,               ├──► read model B (search)
               validates                 └──► read model C (cache)
               invariants)                    each optimized for
                                              its own queries

The write side optimizes for correctness — enforcing invariants, rules that must always hold, like "an account balance never goes below zero". The read side optimizes for the shape of each query. You can have several read models, each in whatever store suits it — a SQL table for the order-history page, a search index for product search, a cache for the dashboard. That's really just polyglot persistence (several kinds of database in one system), kept up to date by an event stream.

The cost is unavoidable and must be stated: read models are eventually consistent. A user submits a change and may not see it in a query immediately. Handle it in the UI (show the intended result optimistically) or with read-your-writes on the affected path — don't pretend it isn't there.

CQRS pairs naturally with event sourcing but doesn't require it; plain CDC from a normal database gets you most of the benefit for far less complexity.

#Delivery and ordering

Everything from message queues applies, with fanout multiplying the consequences:

  • At-least-once means every subscriber sees duplicates. Each one needs idempotency independently — the producer can't solve this for them.
  • Ordering is per-partition. A topic is split into partitions for throughput, and order is only guaranteed within one partition. So all events for one entity must go to the same partition — use the entity's ID (e.g. order_id) as the partition key. Otherwise OrderCancelled could be processed before OrderPlaced.
  • One slow subscriber must not block the others. In log-based systems each consumer group just keeps its own bookmark (offset) into the shared log, so a slow group falls behind on its own without affecting anyone else — this comes free. With a broker that copies each message into a separate queue per subscriber, a slow subscriber's queue keeps growing, and you need a policy for it (backpressure): cap its size, drop old messages, or slow the publisher.

#The coupling you traded for

Event-driven architecture removes runtime coupling and replaces it with schema coupling, plus new operational problems. Be explicit about these. Knowing the limits of your own design is the difference between a considered choice and a lucky one.

Schema evolution. Once five services consume OrderPlaced, its shape is a promise you can't change on your own. You need to only ever add fields, to version the event, and to keep a schema registry — a shared record of every event's agreed shape, which rejects a change that would break existing consumers before it ships.

No global view. A request that spans six services asynchronously has no stack trace. Distributed tracing with a correlation ID propagated through every event is mandatory, not optional.

Debugging is genuinely harder. "Why didn't this email send?" becomes an archaeology exercise across consumer lag, dead letter queues, and logs in six places.

Eventual consistency leaks to users. "I placed the order but it doesn't appear in my history" is a support ticket caused by architecture.

Emergent cycles. Service A emits an event that triggers B, which emits an event that triggers A. Nobody designed this; it assembled itself over three quarters. Event choreography makes control flow invisible.

#When not to use events

  • The caller needs the answer. A query is a query. Don't make "get the user's balance" asynchronous.
  • Strong consistency is required. Events are eventually consistent by nature. If a rule must hold across two services at every instant — say, "stock reserved must always equal items in paid orders" — that usually means the boundary is drawn wrong, and that data belongs inside one service.
  • Two services only. A direct call is simpler, debuggable, and adequate.
  • The team is small. Event-driven architecture front-loads complexity in exchange for later flexibility. With three engineers and one deployable, you're paying the cost and collecting none of the benefit.

#Check yourself

Queue versus pub/sub: who gets each message, and what does that say about coupling?Show answer
A queue gives each message to one worker — the producer is assigning work. Pub/sub gives it to every subscriber — the producer announces what happened and doesn't know who reacts, so new consumers need no producer change.
Event notification versus event-carried state transfer: what does each cost?Show answer
A bare ID keeps payloads small and schemas private, but every consumer calls back, re-coupling them at runtime. Carrying full state makes consumers autonomous even when the producer is down, but payloads grow and become a public contract.
What is event sourcing good for, and when is it the wrong choice?Show answer
A complete audit trail, state at any past moment, and new projections over history — great for ledgers and audit-heavy domains. Wrong for ordinary CRUD, where it's over-engineering.
How do event-sourced systems handle a GDPR deletion request?Show answer
Crypto-shredding: encrypt each person's data with their own key and discard the key, since the log itself can't be edited.
What is CQRS, and what cost must you state?Show answer
Separate models for writing (correctness, invariants) and reading (shaped for each query), fed by events or CDC. Read models are eventually consistent, so handle the lag with optimistic UI or read-your-writes.
What coupling does event-driven design add in place of runtime coupling?Show answer
Schema coupling: an event consumed by five services is a contract. Only add fields, version events, and use a schema registry that rejects breaking changes.
Choreography versus orchestration?Show answer
Choreography: services react to events independently — decoupled, but the overall process is invisible. Orchestration: a coordinator drives the steps — visible and able to compensate. Use choreography for side effects and orchestration for core workflows.
When shouldn't you use events?Show answer
When the caller needs the answer, when strong consistency spans services, when there are only two services, or when the team is small — you pay the complexity without the benefit.

#What to carry forward

  • Queues assign work to one consumer; pub/sub announces facts to all subscribers.
  • Choose deliberately between thin notifications, event-carried state and full event sourcing.
  • CQRS splits write and read models; its read side is eventually consistent.
  • Events trade runtime coupling for schema coupling, harder debugging and visible lag — use registries and tracing.
  • Choreograph side effects, orchestrate core workflows, and use plain calls when the caller needs the answer.
00:00
/ 10m