Skip to content
Communication Between Services

Lesson 9 of 10 · 26 min

x
9/10

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

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
1await inventory.reserve(order);   // succeeds2await payment.charge(order);      // fails3// Inventory is reserved but order is unpaid — inconsistent
After
Saga with compensation
1try {2  await inventory.reserve(order);3  await payment.charge(order);4  await order.confirm(order.id);5} catch (err) {6  // Compensate in reverse order7  if (paymentCharged) await payment.refund(order);8  if (inventoryReserved) await inventory.release(order);9  await order.cancel(order.id);10  throw err;11}

Check your understanding

  • Why can’t one ACID transaction span microservices easily?Show answer

    Answer

    Each service owns its datastore; locking across services (2PC) is rarely acceptable under partitions.
  • What must every saga step have?Show answer

    Answer

    A compensating action (or equivalent remediation) if a later step fails.
  • Orchestration vs choreography?Show answer

    Answer

    Orchestration: a coordinator directs steps. Choreography: services react to each other’s events.
Previous

Progress is saved in this browser.

Next Lesson