Skip to the content

Lesson 236 of 296

Message queues and event-driven design

What you will learn

  • Synchronous vs asynchronous communication
  • Queues vs publish-subscribe
  • Kafka and logs vs traditional queues
  • Event-driven architecture
  • Choreography vs orchestration, and sagas
  • Ordering, duplicates and back-pressure
On this page

Synchronous vs asynchronous

Synchronous: service A calls service B over HTTP and waits. Simple, but A is slowed by B, and if B is down, A fails too. A chain of five synchronous calls is only as available as all five together.

Asynchronous: A puts a message on a queue or publishes an event and carries on. B processes it when it can. Benefits: decoupling (A does not need to know B), resilience (B can be down for a while; messages wait), load levelling (spikes are absorbed by the queue), and independent scaling.

Queues vs publish-subscribe

Queue (point-to-point)Publish-subscribe (pub/sub)
DeliveryEach message goes to one consumer (competing consumers)Each message goes to every subscriber
UseDistributing work: send this email, resize this imageBroadcasting events: "OrderPlaced" to billing, email and analytics
ExamplesSQS, RabbitMQ queues, BullMQSNS, EventBridge, RabbitMQ fan-out exchanges, Redis pub/sub, Kafka topics

The common AWS pattern: SNS topic → several SQS queues (fan-out), so each subscriber has its own durable queue (Lesson 256).

Logs: Kafka

Apache Kafka (and AWS Kinesis, Redpanda) store messages in an append-only log, split into partitions, and keep them for days or forever. Consumers track their own position (offset) and can replay history.

Traditional queue (SQS, RabbitMQ)Log (Kafka)
After consumptionMessage deletedMessage kept for the retention period
OrderingUsually not guaranteed (FIFO queues exist)Guaranteed within a partition
ReplayNoYes: new consumers can read from the beginning
ThroughputHighVery high (millions of messages per second)
Best forTask queuesEvent streaming, analytics pipelines, event sourcing, change data capture

Messages with the same key (for example the same order ID) go to the same partition, so events for one order are processed in order.

Event-driven architecture

Services communicate through events: facts about things that happened, named in the past tense (OrderPlaced, PaymentSucceeded, UserSignedUp).

Order service ── OrderPlaced ──> [event bus] ──> Payment service
                                             ├─> Email service
                                             ├─> Inventory service
                                             └─> Analytics

Adding a new feature (a loyalty-points service) means subscribing to the event, without changing the order service.

Event types:

  • Event notification: just "order 101 was placed"; consumers fetch details if they need them.
  • Event-carried state transfer: the event includes the data consumers need, so they do not call back.
  • Event sourcing: the events are the source of truth; current state is rebuilt by replaying them (bank ledgers). Powerful, complex.

Choreography vs orchestration

A business process across services (place order → take payment → reserve stock → ship):

ChoreographyOrchestration
HowEach service reacts to events and emits new ones; no central controllerA central orchestrator tells each service what to do next
ProsLoose couplingThe flow is visible in one place; easier to change and monitor
ConsThe overall flow is hard to see and debugThe orchestrator is a central component
ToolsEvent busAWS Step Functions, Temporal, a workflow service

Sagas

Distributed transactions across services cannot use one database transaction. A saga is a sequence of local transactions where each step has a compensating action that undoes it if a later step fails:

  1. Create order (compensate: cancel order).
  2. Charge payment (compensate: refund).
  3. Reserve stock (fails: out of stock) → run compensations: refund payment, cancel order.

Things that go wrong

  • Duplicates: most systems deliver at least once; consumers must be idempotent (Lesson 195).
  • Ordering: do not assume order unless the system guarantees it (Kafka per partition, SQS FIFO per message group).
  • Poison messages: use dead-letter queues (Lesson 204).
  • Dual writes: use the transactional outbox to publish events reliably (Lesson 204).
  • Back-pressure: if consumers are slower than producers, the queue grows; monitor queue depth and message age, scale consumers, or slow producers.
  • Eventual consistency: other services see changes a little later (Lesson 237); the UI may need "processing" states.
  • Schema evolution: events are contracts; version them and change them in backward-compatible ways.

How to say it in an interview

"Synchronous calls are simple but couple availability and latency, while asynchronous messaging decouples services, absorbs spikes and lets consumers fail and recover. Queues deliver each message to one worker for distributing tasks; pub/sub delivers each event to every subscriber, often SNS fanning out to SQS queues. Kafka is a retained, partitioned log with ordering per partition and replay, suited to event streaming. In event-driven designs services publish past-tense events; I choose choreography for loose coupling or orchestration with something like Step Functions when the flow must be visible, and use sagas with compensating actions instead of distributed transactions. I always plan for duplicates with idempotent consumers, ordering, dead-letter queues, the outbox pattern and monitoring queue depth."

Key words

WordMeaning
Asynchronous messagingSending a message without waiting for the result
Queue / competing consumersEach message processed by one worker
Pub/subEach event delivered to all subscribers
Kafka / logA retained, partitioned, replayable message store
OffsetA consumer's position in a log partition
Event-driven architectureServices communicating through events
Event sourcingStoring events as the source of truth
Choreography / orchestrationDecentralised / centrally controlled workflows
SagaLocal transactions with compensating actions
Back-pressureHandling producers faster than consumers

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.