Skip to main content

Module 5: Async Processing

Event-Driven Architecture

Pub/Sub and event-driven design — domain events vs commands, choreography vs orchestration, outbox pattern, and eventual consistency.

Services publish facts about what happened; other services react. That is the heart of event-driven systems — loose coupling with eventual consistency you must design for explicitly.

What you will learn

  • Describe pub/sub fan-out and why producers stay decoupled
  • Contrast events vs commands clearly
  • Choose choreography vs orchestration for a workflow
  • Explain the outbox pattern and duplicate/eventual-consistency issues
  • Sketch one business action as an event sequence
Order service publishes OrderPaid. Email, inventory, and analytics each subscribe.
Publish the fact once. Each subscriber reacts on its own clock.

What event-driven means

  • Instead of one service calling every dependency synchronously, it records a fact and lets interested parties react.
  • Producer emits “what happened” without knowing all consumers
  • Consumers scale and fail independently
  • User-facing APIs stay thin; side effects move async
  • Consistency becomes eventual across services — say that out loud
  • Not every call should be an event; sync reads often stay request/response

Events vs commands

  • Mixing these two muddies ownership. Keep the vocabulary sharp.
  • Command — request work: SendEmail, ChargeCard (imperative, usually one target)
  • Event — state a fact: OrderPaid, UserRegistered (past tense, many listeners OK)
  • Commands imply an expected handler; events imply interest, not a single owner
  • Event names should be stable business language, not UI click names
  • Tangled designs often publish “DoX” as if it were a fact

Pub/Sub fan-out

  • One published event can wake inventory, email, analytics, and search — without the producer listing them.
  • Publisher writes to a topic/stream/bus once
  • Each subscriber gets the event on its own pace
  • Adding a new consumer does not require changing the producer
  • Failure in email should not roll back analytics if they are separate consumers
  • Broker choice (queue vs log) still matters — see Message Brokers

Choreography

  • Each service listens for events and emits new ones. The workflow emerges from reactions.
  • Loose coupling — no central boss service
  • Harder to see the full flow — need tracing and clear event docs
  • Cycles and “who owns the saga?” can get fuzzy
  • Good for simple fan-out: OrderPaid → email + points + metrics
  • Risk: implicit workflows no one can debug at 2 a.m.

Orchestration

  • A workflow engine or orchestrator service directs steps and waits for outcomes.
  • Clear control flow and status (“step 3 of refund”)
  • Central dependency — orchestrator availability matters
  • Easier timeouts, compensation, and human-visible progress
  • Good for long multi-step business processes (onboarding, payouts)
  • Still use events/commands under the hood for the steps

Choreography vs orchestration

  • Use this comparison when the interviewer asks how services coordinate.
  • Coupling — choreography: looser; orchestration: explicit center
  • Visibility — choreography: distributed traces; orchestration: workflow state
  • Change — choreography: add listeners easily; orchestration: change the definition
  • Failure — both need retries/compensation; orchestration makes them obvious
  • Interview move: pick one and justify with workflow complexity

Transactional outbox

  • The classic bug: commit DB, then fail before publish — or publish, then fail before commit.
  • Write business row + outbox row in the same DB transaction
  • A publisher process reads the outbox and emits to the broker
  • Mark outbox rows sent; retry on broker failure
  • Gives at-least-once publication aligned with the commit
  • Consumers must still be idempotent

Consistency, duplicates, ordering

  • Async flows inherit broker realities. Design for them instead of wishing them away.
  • Eventual consistency across services — UI may need “processing” states
  • At-least-once delivery ⇒ duplicate events; idempotent handlers required
  • Per-key ordering if you partition by entity id; not global order
  • Compensating actions undo partial sagas (refund, release stock)
  • Define what the user sees when step 2 is still pending

Schemas and evolution

  • Events become a public API between teams. Version them on purpose.
  • Prefer additive changes; avoid renaming/removing fields casually
  • Use explicit versions or schema registry (Avro/Protobuf/JSON guidelines)
  • Include event id, type, timestamp, and aggregate id in every payload
  • Document compatibility: consumers should tolerate unknown fields
  • Contract tests beat tribal knowledge

Common pitfalls

  • These patterns look elegant and fail operationally.
  • Chatty event storms for every tiny field change
  • Hidden choreography nobody can sequence-diagram
  • Missing outbox → lost or double-side-effect publishes
  • Non-idempotent consumers under redelivery
  • Using events for hard sync reads that needed a query API

Interview framing

  • Use this order for an async business flow.
  • Draw the user request and the domain event that leaves the write path
  • List subscribers and whether fan-out is choreography or an orchestrated saga
  • Add outbox + at-least-once + idempotency
  • State user-visible eventual consistency
  • Note schema identity fields on the event

Quick revision checklist

  • Draw a sequence for one business action.
  • Mention duplicate events and idempotent handlers.
  • Keep events (facts) distinct from commands (requests).
  • Use outbox for DB + publish atomicity.
  • Pick choreography vs orchestration deliberately.
  • Say what the UI shows while the flow is eventually consistent.

FAQs

Are events the same as messages/commands?

Commands request work (“SendEmail”). Events state facts (“OrderPaid”). Keeping the distinction clean avoids tangled designs.

When do I choose orchestration over choreography?

When the multi-step process needs clear status, timeouts, and compensation owned in one place. Use choreography for simple independent fan-out.

What is the transactional outbox?

Store the event in an outbox table in the same DB transaction as the business write, then publish asynchronously. It prevents “committed but never emitted” gaps.

How do we handle duplicate events?

Assume at-least-once delivery. Use idempotency keys or dedupe tables so reprocessing the same event id does not double side effects.

Is event-driven always better than sync APIs?

No. Sync is simpler when you need an immediate consistent answer. Events shine for decoupling, fan-out, and spike absorption.

How should events be versioned?

Treat them as contracts: additive fields, explicit type/version, stable aggregate ids. Prefer expanding schemas over breaking renames.

Practice

Learner’s Task

  • Practice out loud for 8–10 minutes. Turn one business action into an event-driven flow.
  1. Pick a flow (place order or user signup) and write one domain event name in past tense.
  2. List 3 subscribers and choose choreography vs orchestration — justify in one sentence.
  3. Add outbox on the write path and state delivery + idempotency assumptions.
  4. Describe what the user sees before all subscribers finish.
  5. Write a 4-sentence closing: event, coordination style, consistency story, and one pitfall you avoided.