Distributed Systems··2 min read

Saga Pattern vs Two-Phase Commit: How We Coordinated Multi-Service Order Refunds in Go Without Distributed Deadlocks

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Saga Pattern vs Two-Phase Commit: How We Coordinated Multi-Service Order Refunds in Go Without Distributed Deadlocks

Why Distributed Two-Phase Commit (2PC) Strangles Throughput

When a customer cancels an order, three separate systems must update cleanly:

  1. Order Service marks the order line items as REFUNDING.
  2. Payment Service calls Stripe/Adyen to refund the card charge.
  3. Inventory Service releases the reserved warehouse stock back to the sellable pool.

If you attempt to wrap those three steps in a synchronous Two-Phase Commit (XA transaction), your database connections stay locked while waiting for an external HTTP call to Stripe. A 3-second latency spike on the payment gateway exhausts your PostgreSQL connection pool in seconds.


1. Orchestrated Saga State Machine in Go

Instead of holding open cross-service locks, we persist a durable saga_executions row in PostgreSQL and drive forward recovery and backward compensation through explicit state transitions:

CREATE TABLE saga_executions (
    saga_id UUID PRIMARY KEY,
    order_id UUID NOT NULL UNIQUE,
    current_step VARCHAR(40) NOT NULL,
    status VARCHAR(24) NOT NULL,
    payload JSONB NOT NULL,
    retry_count INT NOT NULL DEFAULT 0,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

2. Forward Steps and Compensating Rollbacks

Every step in the Go Saga orchestrator defines both an Execute function and a Compensate function, each keyed by a deterministic idempotency_key:

type SagaStep struct {
    Name       string
    Execute    func(ctx context.Context, sagaID string, data OrderRefundPayload) error
    Compensate func(ctx context.Context, sagaID string, data OrderRefundPayload) error
}

var RefundWorkflow = []SagaStep{
    {
        Name:       "LOCK_ORDER_REFUND_INTENT",
        Execute:    orderClient.MarkRefundPending,
        Compensate: orderClient.RevertRefundPending,
    },
    {
        Name:       "RESTOCK_INVENTORY_LEDGER",
        Execute:    inventoryClient.ReleaseReservedUnits,
        Compensate: inventoryClient.ReReserveUnits,
    },
    {
        Name:       "EXECUTE_GATEWAY_REFUND",
        Execute:    paymentClient.IssueIdempotentRefund,
        Compensate: nil, // Pivot transaction: once gateway refunds money, roll forward only
    },
}

3. Identifying the Pivot Transaction

The most important rule in Saga design is ordering your steps so the irreversible external side effect (returning money via Stripe) happens only after reversible internal steps succeed. If the gateway rejects the refund with a permanent 4xx error, the orchestrator runs the Compensate handlers in reverse order with zero human intervention.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles