Communication Between Services

Lesson 4 of 10 · 26 min

x
40%

Message Queues & Pub/Sub

Message queues decouple producers from consumers in time. A producer publishes a message to a broker (RabbitMQ, Amazon SQS, Azure Service Bus, Google Pub/Sub). One or more consumers pull or receive messages and process them independently. If the consumer is down, messages accumulate in the queue until it recovers — the producer is not blocked. Pub/Sub extends this to one-to-many: a single event is broadcast to every subscriber. An OrderPlaced event might trigger inventory reservation, payment capture, and a confirmation email — three consumers, one message. The key design decision is idempotency: consumers must handle duplicate messages safely, because brokers guarantee at-least-once delivery, not exactly-once.

Before
Synchronous chain — one failure blocks all
await inventoryService.reserve(order);
await paymentService.charge(order);
await emailService.send(order);
// If payment fails, inventory is already reserved
After
Async queue — each step independent
// Producer publishes one event
await broker.publish('order.placed', {
  orderId: order.id,
  items: order.items,
  total: order.total,
});

// Consumers react independently
// inventory-consumer  → reserves stock
// payment-consumer    → charges card
// email-consumer      → sends confirmation

Key Takeaway

Queues absorb spikes and isolate failures — design every consumer to be idempotent because duplicates will happen.

PreviousNext Lesson