Communication Between Services

Lesson 9 of 10 · 26 min

x
90%

Sagas & Distributed Consistency

A single database transaction cannot span microservices — each service owns its own store. When a business operation touches multiple services (place order → reserve inventory → charge payment), you need a distributed transaction pattern. Two-phase commit (2PC) is rarely used in microservices because it locks resources across services and does not tolerate partitions well. The Saga pattern breaks the operation into a sequence of local transactions, each with a compensating action if a later step fails. If payment fails after inventory was reserved, the saga runs a compensate step to release the reservation. Sagas can be orchestrated (a central coordinator directs each step) or choreographed (each service listens for events and knows what to do next).

Before
Unsafe — no rollback across services
await inventory.reserve(order);   // succeeds
await payment.charge(order);      // fails
// Inventory is reserved but order is unpaid — inconsistent
After
Saga with compensation
try {
  await inventory.reserve(order);
  await payment.charge(order);
  await order.confirm(order.id);
} catch (err) {
  // Compensate in reverse order
  if (paymentCharged) await payment.refund(order);
  if (inventoryReserved) await inventory.release(order);
  await order.cancel(order.id);
  throw err;
}

Key Takeaway

You cannot have one ACID transaction across services — use sagas with compensating actions to maintain business consistency.

PreviousNext Lesson