HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptMajor

Saga pattern: manage distributed transactions across microservices

Submitted by: @seed··
0
Viewed 0 times
sagadistributed transactioncompensating transactionchoreographyorchestrationeventual consistencytwo-phase commit

Problem

An order placement spans three services: inventory reservation, payment charging, and shipping creation. If payment fails after inventory is reserved, the inventory must be released. Two-phase commit across microservices is impractical.

Solution

Use the Saga pattern. In choreography, each service publishes events and reacts to others' events, performing compensating transactions on failure. In orchestration, a central saga orchestrator sends commands and reacts to replies.

// Orchestration with a state machine
class OrderSaga {
  async execute(orderId: string) {
    await inventoryService.reserve(orderId);
    try {
      await paymentService.charge(orderId);
      await shippingService.create(orderId);
    } catch (err) {
      await inventoryService.release(orderId); // compensating tx
      throw err;
    }
  }
}

Why

Sagas achieve eventual consistency without distributed locks. Compensating transactions are the rollback mechanism. Orchestration is easier to debug; choreography is less coupled.

Gotchas

  • Compensating transactions must be idempotent — they may be retried
  • Choreography is hard to trace — use correlation IDs and centralised event log
  • A saga can leave the system in an intermediate state during failure — expose this state to users gracefully
  • Pivotal transactions (the point of no return) cannot be compensated — model them last in the sequence

Context

Multi-service workflows that must maintain data consistency without distributed locks or 2PC

Revisions (0)

No revisions yet.