Skip to content

Saga Pattern for Distributed Transactions: Maintaining Consistency Without ACID

Implement the Saga pattern across microservices with AWS Step Functions and EventBridge, covering idempotency, compensation logic, and production patterns.

Ayhan Sipahi Ayhan Sipahi

Microservices split a single business transaction across several databases, and ACID guarantees stop at the service boundary. The Saga pattern fills that gap with local transactions plus compensating transactions: each committed step can be undone when a later step fails, and the system settles into eventual consistency.

Orchestration with AWS Step Functions is the safer default for order-shaped flows, because saga state and failure paths stay visible in one place. EventBridge choreography is cheaper and looser, and it earns its slot when three or four autonomous services already exchange domain events. Whichever coordination style you pick, idempotent steps, reverse-order compensation, and semantic locking are what keep the pattern standing under retries.

The Distributed Transaction Problem#

Traditional ACID transactions do not work across service boundaries, and two-phase commit (2PC) buys atomicity at the price of tight coupling and a single point of failure.

Consider a typical e-commerce order flow: creating an order, reserving inventory, processing payment, and confirming shipment. Each step involves a different microservice with its own database. If payment processing fails after inventory has been reserved, you need a reliable way to roll back the inventory reservation. Without proper patterns, services drift apart: orders created, payments failed, inventory never restored. Network timeouts, provider rate limits, and transient outages all produce this shape of partial failure, so compensation logic has to ship with the first version of the flow.

Compensation works at the business level, not at the storage level. The forward step has already committed and its effect may already be visible to other readers, so you release the reservation, refund the charge, and mark the order cancelled as explicit compensating transactions. Designing those undo steps is most of the work in a saga.

Saga Pattern Fundamentals#

A saga is a sequence of local transactions where:

  1. Each transaction updates data within a single service
  2. Each transaction publishes an event or message to trigger the next transaction
  3. If a transaction fails, the saga executes compensating transactions to undo completed steps
  4. The system achieves eventual consistency instead of immediate ACID consistency

Key characteristics that make sagas work:

  • Eventual Consistency: The system converges to a consistent state once every step has settled
  • Local Transactions: Each service manages its own database with local ACID guarantees
  • Compensating Transactions: Explicit rollback logic for each forward step
  • Idempotency: All saga steps must be safe to retry
  • Observability: Critical for debugging distributed flows; correlation IDs and structured logging belong in every step

When to use the Saga pattern:

  • Microservices architecture with multiple databases
  • Business processes spanning multiple services
  • Cannot use distributed transactions due to performance or coupling concerns
  • Acceptable to have temporary inconsistency
  • Typically 3-5 steps maximum (complexity increases rapidly beyond this)

Orchestration vs Choreography#

There are two main approaches to coordinating sagas: orchestration and choreography. Understanding when to use each is critical for successful implementation.

Choreography: Event-Driven Coordination#

In choreography, services coordinate through domain events without a central coordinator. Each service knows what to do when it receives an event.

OrderCreated

InventoryReserved

PaymentCompleted

PaymentFailed

InventoryReleased

Order Service

Inventory Service

Payment Service

Advantages:

  • Loose coupling between services
  • No single point of failure
  • Scales well for independent services
  • Natural fit for event-driven architecture

Disadvantages:

  • Control flow not visible in one place
  • Difficult to understand complete saga flow
  • Debugging complexity (distributed logic)
  • Harder to track saga state
  • Risk of cyclic dependencies

Best for:

  • 3-4 services maximum
  • Independent, autonomous services
  • Event-driven architecture already in place
  • Simple linear flows

Orchestration: Centralized Coordination#

In orchestration, a central coordinator (typically AWS Step Functions) manages the saga flow, telling each service what to do.

1. Create Order

2. Reserve Inventory

3. Process Payment

4. Confirm Order

Compensate

Compensate

Compensate

Step Functions Orchestrator

Order Service

Inventory Service

Payment Service

Advantages:

  • Clear control flow visualization
  • Easier debugging and monitoring
  • Centralized error handling
  • State management built-in
  • Better for complex flows

Disadvantages:

  • Orchestrator is coordination point
  • Services coupled to orchestrator
  • Orchestrator must know all services

Best for:

  • Complex multi-step workflows
  • Need visibility into saga state
  • Human approval steps
  • More than 4 services involved
  • Strict ordering requirements

Decision Framework#

Use this decision logic when choosing your approach:

Yes

No

Yes

No

Yes

No

Yes

No

Start

More than 4 services?

Use Orchestration

Complex flow logic?

Need visibility into saga state?

Event-driven architecture?

Use Choreography

Orchestration Implementation with AWS Step Functions#

The stack below defines an e-commerce order saga on AWS Step Functions with AWS CDK v2 (aws-cdk-lib). The execution input carries the identifiers every step and compensation needs: orderId, transactionId, productId, quantity and the payment idempotencyKey.

Infrastructure Setup#

import * as cdk from 'aws-cdk-lib';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
import { Construct } from 'constructs';

export class OrderSagaStack extends cdk.Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // DynamoDB tables for saga state persistence
    const ordersTable = new dynamodb.Table(this, 'Orders', {
      partitionKey: { name: 'orderId', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST
    });

    const inventoryTable = new dynamodb.Table(this, 'Inventory', {
      partitionKey: { name: 'productId', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST
    });

    const paymentsTable = new dynamodb.Table(this, 'Payments', {
      partitionKey: { name: 'paymentId', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST
    });

    // Failed compensations and abnormally ended executions land here for a person
    const manualInterventionQueue = new sqs.Queue(this, 'ManualIntervention', {
      retentionPeriod: cdk.Duration.days(14)
    });

    const fn = (id: string, handler: string, environment: Record<string, string>) =>
      new lambda.Function(this, id, {
        runtime: lambda.Runtime.NODEJS_22_X,
        handler,
        code: lambda.Code.fromAsset('lambda'),
        environment
      });

    // Forward transaction Lambdas
    const createOrder = fn('CreateOrder', 'createOrder.handler', {
      ORDERS_TABLE: ordersTable.tableName
    });
    const reserveInventory = fn('ReserveInventory', 'reserveInventory.handler', {
      INVENTORY_TABLE: inventoryTable.tableName
    });
    const processPayment = fn('ProcessPayment', 'processPayment.handler', {
      PAYMENTS_TABLE: paymentsTable.tableName
    });
    // Confirms the order and marks the reservation CONFIRMED so the sweeper keeps its stock sold
    const confirmOrder = fn('ConfirmOrder', 'confirmOrder.handler', {
      ORDERS_TABLE: ordersTable.tableName,
      INVENTORY_TABLE: inventoryTable.tableName
    });

    // Compensating transaction Lambdas (rollback)
    const cancelOrder = fn('CancelOrder', 'cancelOrder.handler', {
      ORDERS_TABLE: ordersTable.tableName
    });
    const releaseInventory = fn('ReleaseInventory', 'releaseInventory.handler', {
      INVENTORY_TABLE: inventoryTable.tableName
    });
    const refundPayment = fn('RefundPayment', 'refundPayment.handler', {
      PAYMENTS_TABLE: paymentsTable.tableName
    });

    // Returns expired reservations to stock when no saga is left to do it
    const sweepReservations = fn('SweepReservations', 'sweepReservations.handler', {
      INVENTORY_TABLE: inventoryTable.tableName
    });

    // Grant table permissions
    ordersTable.grantReadWriteData(createOrder);
    ordersTable.grantReadWriteData(confirmOrder);
    ordersTable.grantReadWriteData(cancelOrder);
    inventoryTable.grantReadWriteData(reserveInventory);
    inventoryTable.grantReadWriteData(confirmOrder);
    inventoryTable.grantReadWriteData(releaseInventory);
    inventoryTable.grantReadWriteData(sweepReservations);
    paymentsTable.grantReadWriteData(processPayment);
    paymentsTable.grantReadWriteData(refundPayment);

    // Every task keeps the execution input (orderId, transactionId, productId,
    // quantity, idempotencyKey, ...) and stores its own result under resultPath,
    // so a compensation later receives the same identifiers.
    // retryOnServiceExceptions (default true) already retries Lambda.ServiceException,
    // Lambda.AWSLambdaException, Lambda.SdkClientException and
    // Lambda.ClientExecutionTimeoutException.
    const invoke = (id: string, lambdaFunction: lambda.IFunction, resultPath: string) =>
      new tasks.LambdaInvoke(this, id, {
        lambdaFunction,
        resultSelector: { 'payload.$': '$.Payload' },
        resultPath
      });

    // Throttling plus the error class our handlers throw for transient failures
    const transientRetry: sfn.RetryProps = {
      errors: ['Lambda.TooManyRequestsException', 'TransientDependencyError'],
      interval: cdk.Duration.seconds(2),
      maxAttempts: 3,
      backoffRate: 2,
      jitterStrategy: sfn.JitterType.FULL
    };

    const createOrderTask = invoke('CreateOrderTask', createOrder, '$.order')
      .addRetry(transientRetry);
    const reserveInventoryTask = invoke('ReserveInventoryTask', reserveInventory, '$.inventory')
      .addRetry(transientRetry);
    const processPaymentTask = invoke('ProcessPaymentTask', processPayment, '$.payment')
      .addRetry(transientRetry);
    const confirmOrderTask = invoke('ConfirmOrderTask', confirmOrder, '$.confirmation')
      .addRetry(transientRetry);

    // Compensations retry every error with capped backoff (10 attempts),
    // then hand the saga to a person instead of failing silently
    const queueForManualIntervention = new tasks.SqsSendMessage(this, 'QueueForManualIntervention', {
      queue: manualInterventionQueue,
      messageBody: sfn.TaskInput.fromJsonPathAt('$')
    }).next(new sfn.Fail(this, 'CompensationFailed', {
      error: 'CompensationFailed',
      cause: 'A compensation kept failing, saga queued for manual intervention'
    }));

    const compensation = (id: string, lambdaFunction: lambda.IFunction) =>
      invoke(id, lambdaFunction, sfn.JsonPath.DISCARD)
        .addRetry({
          errors: ['States.ALL'],
          interval: cdk.Duration.seconds(1),
          maxAttempts: 10,
          backoffRate: 2,
          maxDelay: cdk.Duration.seconds(10),
          jitterStrategy: sfn.JitterType.FULL
        })
        .addCatch(queueForManualIntervention, {
          errors: ['States.ALL'],
          resultPath: '$.compensationError'
        });

    const refundPaymentTask = compensation('RefundPaymentTask', refundPayment);
    const releaseInventoryTask = compensation('ReleaseInventoryTask', releaseInventory);
    const cancelOrderTask = compensation('CancelOrderTask', cancelOrder);

    // One compensation chain in reverse order. Each state gets exactly one next;
    // a failing forward step enters the chain at the compensation of the last
    // step that may have committed.
    refundPaymentTask
      .next(releaseInventoryTask)
      .next(cancelOrderTask)
      .next(new sfn.Fail(this, 'SagaCompensated', {
        error: 'OrderSagaFailed',
        cause: 'A forward step failed, completed steps were compensated'
      }));

    const catchProps = { errors: ['States.ALL'], resultPath: '$.error' };
    reserveInventoryTask.addCatch(releaseInventoryTask, catchProps);
    processPaymentTask.addCatch(refundPaymentTask, catchProps);
    confirmOrderTask.addCatch(refundPaymentTask, catchProps);

    const sagaDefinition = createOrderTask
      .next(reserveInventoryTask)
      .next(processPaymentTask)
      .next(confirmOrderTask)
      .next(new sfn.Succeed(this, 'OrderSuccess'));

    const orderSaga = new sfn.StateMachine(this, 'OrderSaga', {
      definitionBody: sfn.DefinitionBody.fromChainable(sagaDefinition),
      stateMachineType: sfn.StateMachineType.STANDARD,
      timeout: cdk.Duration.minutes(5),
      tracingEnabled: true
    });

    // No Catch runs when the execution itself times out or is aborted:
    // route those status changes to the same queue
    new events.Rule(this, 'SagaEndedAbnormally', {
      eventPattern: {
        source: ['aws.states'],
        detailType: ['Step Functions Execution Status Change'],
        detail: {
          status: ['TIMED_OUT', 'ABORTED'],
          stateMachineArn: [orderSaga.stateMachineArn]
        }
      },
      targets: [new targets.SqsQueue(manualInterventionQueue)]
    });

    new events.Rule(this, 'ReservationSweep', {
      schedule: events.Schedule.rate(cdk.Duration.minutes(5)),
      targets: [new targets.LambdaFunction(sweepReservations)]
    });

    new cdk.CfnOutput(this, 'OrderSagaArn', {
      value: orderSaga.stateMachineArn,
      description: 'Order Saga State Machine ARN'
    });
  }
}

Each state in a CDK chain accepts exactly one next(). Calling it a second time on the same state throws State '...' already has a next state at synth, so two compensation chains cannot share the release and cancel states. The stack builds one chain instead: refund, release, cancel, then SagaCompensated. Each forward step’s Catch enters that chain at the compensation of the last step that may have committed. A reservation failure starts at the release, and a payment or confirmation failure starts at the refund. Entering a compensation with nothing to undo is safe, because every compensation is a no-op when its forward step never committed. confirmOrderTask gets the same retry and Catch as the other steps. Without them, a failed confirmation would end the execution with the card charged, the stock held and no compensation run.

Every task stores its result under its own key with resultSelector and resultPath. outputPath: '$.Payload' would replace the whole state with the last Lambda’s return value, and a later compensation could lose the orderId or transactionId it needs. With resultPath, the execution input (orderId, transactionId, productId, quantity, idempotencyKey, generated by the API that starts the execution) travels through every state, and the catchers write the error to $.error next to it.

Retry rules must name the errors Step Functions reports. Lambda invoke failures arrive as Lambda.* names: retryOnServiceExceptions (on by default) covers Lambda.ServiceException and its siblings, while throttling arrives as Lambda.TooManyRequestsException and needs its own entry. An error thrown inside the handler arrives under its name, so a transient business failure needs a named class such as TransientDependencyError. A name like ThrottlingException matches nothing the function reports, and its retry never fires.

Compensations retry any error ten times with capped backoff, then the saga goes to QueueForManualIntervention, an SQS queue that a person reads. The execution-level timeout is a backstop with a gap: catchers exist only on Task, Parallel and Map states, so a timed-out or aborted execution runs no compensation at all. The SagaEndedAbnormally rule sends TIMED_OUT and ABORTED status-change events to the same queue, and the reservation sweeper below returns the stock those executions held.

Implementing Idempotent Operations#

Idempotency is non-negotiable in sagas. Steps may execute multiple times due to retries, failures, or network issues. Here’s how to implement properly idempotent operations:

import { DynamoDBClient, ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, UpdateCommand, GetCommand } from '@aws-sdk/lib-dynamodb';
import { unmarshall } from '@aws-sdk/util-dynamodb';

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

// Step Functions matches Retry and Catch rules on the thrown error's name
export class TransientDependencyError extends Error { name = 'TransientDependencyError'; }
export class InsufficientInventoryError extends Error { name = 'InsufficientInventoryError'; }

interface ReserveInventoryEvent {
  orderId: string;
  productId: string;
  quantity: number;
  transactionId: string; // Idempotency key
}

export const handler = async (event: ReserveInventoryEvent) => {
  console.log('Reserving inventory', { orderId: event.orderId, productId: event.productId });

  try {
    // One conditional write is both the idempotency check and the stock check.
    // Product items are created with `reservations: {}`: DynamoDB rejects
    // SET reservations.#txId when the parent map does not exist.
    const result = await docClient.send(
      new UpdateCommand({
        TableName: process.env.INVENTORY_TABLE!,
        Key: { productId: event.productId },
        UpdateExpression:
          'SET availableQuantity = availableQuantity - :qty, ' +
          'reservedQuantity = reservedQuantity + :qty, ' +
          'reservations.#txId = :reservation',
        ConditionExpression:
          'attribute_not_exists(reservations.#txId) AND availableQuantity >= :qty',
        ExpressionAttributeNames: {
          '#txId': event.transactionId
        },
        ExpressionAttributeValues: {
          ':qty': event.quantity,
          ':reservation': {
            orderId: event.orderId,
            quantity: event.quantity,
            status: 'RESERVED',
            timestamp: Date.now(),
            expiresAt: Date.now() + (15 * 60 * 1000) // 15 min, longer than the 5 min execution timeout
          }
        },
        ReturnValues: 'ALL_NEW',
        // On a failed condition, return the current item so we can tell why
        ReturnValuesOnConditionCheckFailure: 'ALL_OLD'
      })
    );

    console.log('Inventory reserved successfully', {
      orderId: event.orderId,
      reservationId: event.transactionId
    });

    return {
      success: true,
      reservationId: event.transactionId,
      availableQuantity: result.Attributes?.availableQuantity
    };

  } catch (error) {
    if (error instanceof ConditionalCheckFailedException) {
      // The exception carries the item in DynamoDB JSON, even through the document client
      const current = error.Item ? unmarshall(error.Item) : undefined;

      if (current?.reservations?.[event.transactionId]) {
        // A retry or a concurrent duplicate already reserved for this transaction
        console.log('Idempotent: inventory already reserved', {
          transactionId: event.transactionId
        });
        return {
          success: true,
          message: 'Idempotent: Already reserved',
          reservationId: event.transactionId
        };
      }

      console.error('Insufficient inventory', {
        productId: event.productId,
        requested: event.quantity
      });
      throw new InsufficientInventoryError(`Insufficient inventory for ${event.productId}`);
    }

    console.error('Failed to reserve inventory', error);
    throw error;
  }
};

One conditional write does both checks atomically. A read before the write would leave a gap: two overlapping invocations for the same transaction (a retry while the first attempt is still running, or a duplicate start) would both find no reservation and both take stock. With attribute_not_exists(reservations.#txId) in the condition, only one write succeeds. ReturnValuesOnConditionCheckFailure: 'ALL_OLD' puts the current item into the ConditionalCheckFailedException, so the handler tells an existing reservation for this transaction (idempotent success) apart from missing stock (InsufficientInventoryError) without a second read. The parent map has to exist first: DynamoDB rejects an update to a nested map attribute when the parent map is missing, so product items are created with an empty reservations map.

Compensation: Releasing Inventory#

export const releaseInventoryHandler = async (event: ReserveInventoryEvent) => {
  console.log('Releasing inventory reservation', {
    orderId: event.orderId,
    transactionId: event.transactionId
  });

  try {
    const reservation = await docClient.send(
      new GetCommand({
        TableName: process.env.INVENTORY_TABLE!,
        Key: { productId: event.productId }
      })
    );

    const existingReservation = reservation.Item?.reservations?.[event.transactionId];

    if (!existingReservation) {
      console.log('Idempotent: Reservation already released or never existed', {
        transactionId: event.transactionId
      });
      return { success: true, message: 'Already released' };
    }

    // Atomic release with conditional check
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.INVENTORY_TABLE!,
        Key: { productId: event.productId },
        UpdateExpression:
          'SET availableQuantity = availableQuantity + :qty, ' +
          'reservedQuantity = reservedQuantity - :qty ' +
          'REMOVE reservations.#txId',
        ConditionExpression: 'attribute_exists(reservations.#txId)',
        ExpressionAttributeNames: {
          '#txId': event.transactionId
        },
        ExpressionAttributeValues: {
          ':qty': existingReservation.quantity
        }
      })
    );

    console.log('Inventory released successfully', { transactionId: event.transactionId });
    return { success: true };

  } catch (error: any) {
    if (error.name === 'ConditionalCheckFailedException') {
      // Reservation already released - idempotent success
      return { success: true, message: 'Already released' };
    }
    throw error;
  }
};

Notice how the compensation is also idempotent. If the reservation doesn’t exist, we return success; the desired end state is achieved.

Payment Processing with Idempotency#

// docClient and TransientDependencyError as in the reservation handler
interface ProcessPaymentEvent {
  orderId: string;
  customerId: string;
  amount: number;
  currency: string;
  paymentMethodId: string;
  idempotencyKey: string;
}

export const processPaymentHandler = async (event: ProcessPaymentEvent) => {
  console.log('Processing payment', {
    orderId: event.orderId,
    amount: event.amount
  });

  try {
    // Check idempotency: Has this payment already been processed?
    const existingPayment = await docClient.send(
      new GetCommand({
        TableName: process.env.PAYMENTS_TABLE!,
        Key: { paymentId: event.idempotencyKey }
      })
    );

    if (existingPayment.Item?.status === 'COMPLETED') {
      console.log('Idempotent: Payment already processed', {
        paymentId: event.idempotencyKey
      });
      return {
        success: true,
        paymentId: event.idempotencyKey,
        transactionId: existingPayment.Item.transactionId,
        message: 'Already processed'
      };
    }

    // Create the PENDING record, or resume one that an interrupted attempt left behind
    const paymentId = event.idempotencyKey;
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.PAYMENTS_TABLE!,
        Key: { paymentId },
        UpdateExpression:
          'SET #status = :pending, orderId = :orderId, ' +
          'amount = :amount, createdAt = :timestamp',
        ConditionExpression: 'attribute_not_exists(paymentId) OR #status = :pending',
        ExpressionAttributeNames: { '#status': 'status' },
        ExpressionAttributeValues: {
          ':pending': 'PENDING',
          ':orderId': event.orderId,
          ':amount': event.amount,
          ':timestamp': Date.now()
        }
      })
    );

    // Call external payment provider (Stripe, etc.)
    const paymentResult = await callPaymentProvider({
      amount: event.amount,
      currency: event.currency,
      customerId: event.customerId,
      paymentMethodId: event.paymentMethodId,
      idempotencyKey: event.idempotencyKey
    }).catch((providerError: any) => {
      // No response (network error, timeout) or a 5xx: the charge may be in flight.
      // The record stays PENDING, and the step's retrier re-runs it with the same key.
      if (providerError.statusCode === undefined || providerError.statusCode >= 500) {
        throw new TransientDependencyError(`Payment provider unavailable: ${providerError.message}`);
      }
      throw providerError;
    });

    if (!paymentResult.success) {
      await docClient.send(
        new UpdateCommand({
          TableName: process.env.PAYMENTS_TABLE!,
          Key: { paymentId },
          UpdateExpression:
            'SET #status = :failed, failureReason = :reason, updatedAt = :timestamp',
          ExpressionAttributeNames: { '#status': 'status' },
          ExpressionAttributeValues: {
            ':failed': 'FAILED',
            ':reason': paymentResult.error,
            ':timestamp': Date.now()
          }
        })
      );

      throw new Error(`PaymentFailed: ${paymentResult.error}`);
    }

    // Update to COMPLETED status
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.PAYMENTS_TABLE!,
        Key: { paymentId },
        UpdateExpression:
          'SET #status = :completed, transactionId = :txId, updatedAt = :timestamp',
        ExpressionAttributeNames: { '#status': 'status' },
        ExpressionAttributeValues: {
          ':completed': 'COMPLETED',
          ':txId': paymentResult.transactionId,
          ':timestamp': Date.now()
        }
      })
    );

    return {
      success: true,
      paymentId,
      transactionId: paymentResult.transactionId
    };

  } catch (error: any) {
    if (error.name === 'ConditionalCheckFailedException') {
      // The record is FAILED or REFUNDED: this idempotency key is already settled
      throw new Error('PaymentAlreadySettled');
    }
    throw error;
  }
};

// Simulated payment provider call
async function callPaymentProvider(params: any) {
  // In production: Stripe, Adyen, etc. with their idempotency keys
  return {
    success: Math.random() > 0.1, // 90% success rate
    transactionId: `txn_${Date.now()}`,
    error: 'CardDeclined'
  };
}

This payment implementation shows three-phase idempotency: check for existing completion, create a PENDING record, then update to the final state. A provider failure without a clear answer (network error, timeout, 5xx) is thrown as TransientDependencyError, and that name is what makes the step’s forward retrier run it again. A retry that finds the record still PENDING resumes it with the same provider idempotency key, so the provider sees one charge request even when the function runs several times. A declined card is a final answer: the record becomes FAILED and the Catch starts compensation.

Refunding Only What Was Charged#

The payment step’s Catch enters the compensation chain at the refund, including when the charge itself failed. The refund handler therefore reads the payment record before it touches the provider:

export class PaymentStateUnknownError extends Error { name = 'PaymentStateUnknownError'; }

export const refundPaymentHandler = async (event: ProcessPaymentEvent) => {
  const { Item: payment } = await docClient.send(
    new GetCommand({
      TableName: process.env.PAYMENTS_TABLE!,
      Key: { paymentId: event.idempotencyKey }
    })
  );

  // No record, a declined charge, or an earlier refund: nothing left to undo
  if (!payment || payment.status === 'FAILED' || payment.status === 'REFUNDED') {
    console.log('Idempotent: nothing to refund', {
      paymentId: event.idempotencyKey,
      status: payment?.status
    });
    return { success: true, message: 'Nothing to refund' };
  }

  // PENDING: the provider call never reported back, so the card may or may not be charged
  if (payment.status === 'PENDING') {
    throw new PaymentStateUnknownError(`Payment ${event.idempotencyKey} is still PENDING`);
  }

  // COMPLETED: a derived idempotency key keeps a retried refund from paying out twice
  await refundWithProvider({
    transactionId: payment.transactionId,
    amount: payment.amount,
    idempotencyKey: `refund_${event.idempotencyKey}`
  });

  await docClient.send(
    new UpdateCommand({
      TableName: process.env.PAYMENTS_TABLE!,
      Key: { paymentId: event.idempotencyKey },
      UpdateExpression: 'SET #status = :refunded, updatedAt = :timestamp',
      ExpressionAttributeNames: { '#status': 'status' },
      ExpressionAttributeValues: {
        ':refunded': 'REFUNDED',
        ':timestamp': Date.now()
      }
    })
  );

  return { success: true, paymentId: event.idempotencyKey };
};

No record, FAILED or REFUNDED means there is nothing to undo, so the refund returns success. PENDING is the one state the handler cannot settle alone: the provider call may have charged the card without reporting back. The handler throws, the compensation retries run out, and the saga reaches the manual-intervention queue with its full input.

Expired Reservations and the Execution Timeout#

The expiresAt field only matters if something acts on it. Two cases leave a reservation with no saga to release it: the execution times out or is aborted, so no Catch runs, or a compensation ends in the manual-intervention queue before the release ran. DynamoDB TTL looks like the obvious tool, but it deletes expired items within a few days of their expiration time, and it removes whole items, so it cannot expire one entry inside a product’s reservations map. A scheduled sweeper fits a 15-minute window:

// docClient, UpdateCommand and ConditionalCheckFailedException as in the reservation handler
import { paginateScan } from '@aws-sdk/lib-dynamodb';

export class ReservationExpiredError extends Error { name = 'ReservationExpiredError'; }

// Called by the confirmOrder Lambda before it marks the order CONFIRMED
export async function confirmReservation(productId: string, transactionId: string) {
  try {
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.INVENTORY_TABLE!,
        Key: { productId },
        UpdateExpression: 'SET reservations.#txId.#st = :confirmed',
        // CONFIRMED is accepted too, so a retried confirmation is a no-op
        ConditionExpression: 'reservations.#txId.#st IN (:reserved, :confirmed)',
        ExpressionAttributeNames: { '#txId': transactionId, '#st': 'status' },
        ExpressionAttributeValues: { ':reserved': 'RESERVED', ':confirmed': 'CONFIRMED' }
      })
    );
  } catch (error) {
    if (error instanceof ConditionalCheckFailedException) {
      // The sweeper released this reservation first: fail the step so its Catch compensates
      throw new ReservationExpiredError(`Reservation ${transactionId} expired`);
    }
    throw error;
  }
}

// Runs every 5 minutes from the ReservationSweep rule
export const sweepReservationsHandler = async () => {
  const now = Date.now();
  const pages = paginateScan(
    { client: docClient },
    {
      TableName: process.env.INVENTORY_TABLE!,
      ProjectionExpression: 'productId, reservations'
    }
  );

  for await (const page of pages) {
    for (const item of page.Items ?? []) {
      for (const [txId, reservation] of Object.entries<any>(item.reservations ?? {})) {
        if (reservation.expiresAt >= now) continue;
        // RESERVED goes back to the shelf. CONFIRMED stock stays sold; only the entry goes,
        // because every entry counts toward the product item's size limit.
        const restock = reservation.status === 'RESERVED';

        try {
          await docClient.send(
            new UpdateCommand({
              TableName: process.env.INVENTORY_TABLE!,
              Key: { productId: item.productId },
              UpdateExpression:
                (restock ? 'SET availableQuantity = availableQuantity + :qty, ' : 'SET ') +
                'reservedQuantity = reservedQuantity - :qty ' +
                'REMOVE reservations.#txId',
              // Re-checked at write time: the saga may have confirmed or released it meanwhile
              ConditionExpression:
                'reservations.#txId.#st = :st AND reservations.#txId.expiresAt < :now',
              ExpressionAttributeNames: { '#txId': txId, '#st': 'status' },
              ExpressionAttributeValues: {
                ':qty': reservation.quantity,
                ':st': reservation.status,
                ':now': now
              }
            })
          );
          console.log('Expired reservation swept', { productId: item.productId, txId, restock });
        } catch (error) {
          if (!(error instanceof ConditionalCheckFailedException)) throw error;
        }
      }
    }
  }
};

The 15-minute expiry stays longer than the 5-minute execution timeout, so by the time a reservation expires, the saga that created it has ended. The confirmOrder Lambda calls confirmReservation before it marks the order CONFIRMED, so stock from completed orders never returns to the shelf. In a stricter service split, the inventory service makes this change when it receives an OrderConfirmed event. The sweeper still removes a confirmed entry once it expires, and lowers reservedQuantity without touching availableQuantity. Without that, every completed order would leave its entry in the product item, and a popular product would reach the 400 KB item size limit, after which every reservation write for it fails. Both writes re-check the status at write time. If the execution timeout is ever raised above the expiry and the sweeper wins, confirmReservation throws ReservationExpiredError, and the Catch on confirmOrderTask refunds and cancels the order. The scan reads the whole inventory table every five minutes; with a large catalog, keep open reservations in their own items or index so the sweeper reads only those.

Choreography Implementation with EventBridge#

For simpler flows, choreography can provide better decoupling. Here’s how to implement event-driven saga coordination:

import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';

// Order Service: Creates order and publishes OrderCreated event
export const createOrderHandler = async (event: any) => {
  const orderId = `ord_${Date.now()}`;

  // Create order in database
  await saveOrder({
    orderId,
    customerId: event.customerId,
    items: event.items,
    status: 'PENDING'
  });

  // Publish OrderCreated event
  const eventBridge = new EventBridgeClient({});
  await eventBridge.send(
    new PutEventsCommand({
      Entries: [{
        Source: 'order.service',
        DetailType: 'OrderCreated',
        Detail: JSON.stringify({
          orderId,
          customerId: event.customerId,
          items: event.items,
          totalAmount: event.totalAmount,
          timestamp: Date.now()
        })
      }]
    })
  );

  return { orderId, status: 'PENDING' };
};

// Inventory Service: Listens to OrderCreated, reserves inventory
export const reserveInventoryOnOrderHandler = async (event: any) => {
  const { orderId, items } = event.detail;

  try {
    const reservationResult = await reserveInventoryForOrder(orderId, items);

    const eventBridge = new EventBridgeClient({});
    await eventBridge.send(
      new PutEventsCommand({
        Entries: [{
          Source: 'inventory.service',
          DetailType: 'InventoryReserved',
          Detail: JSON.stringify({
            orderId,
            reservationId: reservationResult.reservationId,
            items,
            timestamp: Date.now()
          })
        }]
      })
    );

  } catch (error: any) {
    // Publish failure event
    const eventBridge = new EventBridgeClient({});
    await eventBridge.send(
      new PutEventsCommand({
        Entries: [{
          Source: 'inventory.service',
          DetailType: 'InventoryReservationFailed',
          Detail: JSON.stringify({
            orderId,
            reason: error.message,
            timestamp: Date.now()
          })
        }]
      })
    );
  }
};

// Payment Service: Listens to InventoryReserved, processes payment
export const processPaymentOnInventoryReservedHandler = async (event: any) => {
  const { orderId } = event.detail;

  try {
    const order = await getOrder(orderId);
    const paymentResult = await processPayment({
      orderId,
      customerId: order.customerId,
      amount: order.totalAmount
    });

    const eventBridge = new EventBridgeClient({});
    await eventBridge.send(
      new PutEventsCommand({
        Entries: [{
          Source: 'payment.service',
          DetailType: 'PaymentCompleted',
          Detail: JSON.stringify({
            orderId,
            paymentId: paymentResult.paymentId,
            transactionId: paymentResult.transactionId,
            timestamp: Date.now()
          })
        }]
      })
    );

  } catch (error: any) {
    // Publish failure event - triggers compensation
    const eventBridge = new EventBridgeClient({});
    await eventBridge.send(
      new PutEventsCommand({
        Entries: [{
          Source: 'payment.service',
          DetailType: 'PaymentFailed',
          Detail: JSON.stringify({
            orderId,
            reason: error.message,
            timestamp: Date.now()
          })
        }]
      })
    );
  }
};

// Inventory Service: Listens to PaymentFailed, releases inventory (compensation)
export const releaseInventoryOnPaymentFailedHandler = async (event: any) => {
  const { orderId } = event.detail;

  console.log('Compensating: Releasing inventory due to payment failure', { orderId });

  await releaseInventory(orderId);

  const eventBridge = new EventBridgeClient({});
  await eventBridge.send(
    new PutEventsCommand({
      Entries: [{
        Source: 'inventory.service',
        DetailType: 'InventoryReleased',
        Detail: JSON.stringify({
          orderId,
          reason: 'PaymentFailed',
          timestamp: Date.now()
        })
      }]
    })
  );
};

In choreography, each service is responsible for listening to relevant events and publishing new events. Compensation happens through the same event mechanism; when a service publishes a failure event, other services react by executing their compensating transactions.

Semantic Locking for Isolation#

Sagas lack traditional transaction isolation, which can lead to concurrent saga conflicts. Semantic locking provides application-level isolation:

interface SagaLock {
  sagaId: string;
  lockedAt: number;
  expiresAt: number;
}

export const acquireSagaLock = async (orderId: string, sagaId: string) => {
  const lockDuration = 5 * 60 * 1000; // 5 minutes
  const now = Date.now();

  try {
    await docClient.send(
      new UpdateCommand({
        TableName: process.env.ORDERS_TABLE!,
        Key: { orderId },
        UpdateExpression:
          'SET sagaLock = :lock, #status = :processing',
        ConditionExpression:
          'attribute_not_exists(sagaLock) OR sagaLock.expiresAt < :now',
        ExpressionAttributeNames: {
          '#status': 'status'
        },
        ExpressionAttributeValues: {
          ':lock': {
            sagaId,
            lockedAt: now,
            expiresAt: now + lockDuration
          },
          ':processing': 'PROCESSING',
          ':now': now
        }
      })
    );

    console.log('Saga lock acquired', { orderId, sagaId });
    return true;

  } catch (error: any) {
    if (error.name === 'ConditionalCheckFailedException') {
      console.warn('Saga lock already held by another saga', { orderId });
      throw new Error('SagaLockConflict');
    }
    throw error;
  }
};

export const releaseSagaLock = async (orderId: string, sagaId: string) => {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.ORDERS_TABLE!,
      Key: { orderId },
      UpdateExpression: 'REMOVE sagaLock',
      ConditionExpression: 'sagaLock.sagaId = :sagaId',
      ExpressionAttributeValues: {
        ':sagaId': sagaId
      }
    })
  );

  console.log('Saga lock released', { orderId, sagaId });
};

This semantic lock prevents two sagas from modifying the same order concurrently. The lock includes an expiration time to handle cases where a saga crashes without releasing the lock.

Cost Analysis and Trade-offs#

Understanding the cost implications helps you choose the right approach.

Step Functions Orchestration Costs#

For 100,000 orders per month, a successful run of the four-step saga above enters 5 states: the four tasks plus the terminal Succeed. Catch branches are billed only when a failure actually routes through them (us-east-1 list prices):

  • Total state transitions: 500,000
  • Cost: (500,000 / 1,000) × $0.025 = $12.50/month
  • Failed sagas (5%, 4 compensation transitions each): 20,000 transitions = +$0.50/month
  • Total: ~$13/month

The Step Functions free tier covers 4,000 state transitions per month, which trims about $0.10 from this figure. Each retry is billed as an additional state transition, so a flow that retries often costs more than this happy-path count.

EventBridge Choreography Costs#

The same volume with 4 events per order:

  • Total events: 400,000
  • Cost: (400,000 / 1,000,000) × $1.00 = $0.40/month
  • Failed orders (5%, 2 compensation events each): 10,000 events = +$0.01/month
  • Total: ~$0.41/month

Cost Versus Visibility#

At this volume choreography lands about thirty times cheaper, and it charges the difference back in development and debugging time. Orchestration costs more and returns execution history, built-in retries, and one place to answer “where did this order stop?”. For most production systems that visibility is worth the extra twelve dollars a month; the figure to weigh it against is an engineer’s afternoon, not the invoice line.

Common Pitfalls and Solutions#

Pitfall 1: Non-Idempotent Operations#

Problem: Payment charged multiple times on retry.

Solution: Always implement idempotency checks and use provider idempotency keys.

Pitfall 2: Incomplete Compensation Chains#

Problem: Only compensating the last step, leaving earlier steps in inconsistent state.

Solution: Chain all compensations in reverse order. Each catch block must compensate all previous steps.

Pitfall 3: Ignoring Compensation Failures#

Problem: Compensation fails, saga hangs.

Solution: Retry compensations aggressively (ten attempts with capped backoff in the stack above), then send the saga to a manual-intervention queue that a person owns.

Pitfall 4: Timeout Too Short#

Problem: Timeout triggers compensation, but operation actually succeeded.

Solution: Set realistic timeouts with buffer. Verify actual state before compensating, as the refund handler does with its PENDING check. An execution-level timeout runs no Catch at all, so route TIMED_OUT executions to the manual-intervention queue.

Pitfall 5: No Saga State Tracking in Choreography#

Problem: Can’t determine which orders are in compensation.

Solution: Persist saga state even in choreography for observability.

Helper Functions#

// Simplified helper functions referenced in examples
import { PutCommand } from '@aws-sdk/lib-dynamodb';

async function saveOrder(order: any) {
  await docClient.send(
    new PutCommand({
      TableName: process.env.ORDERS_TABLE!,
      Item: order
    })
  );
}

async function getOrder(orderId: string) {
  const result = await docClient.send(
    new GetCommand({
      TableName: process.env.ORDERS_TABLE!,
      Key: { orderId }
    })
  );
  return result.Item as any;
}

async function reserveInventoryForOrder(orderId: string, items: any[]) {
  return { reservationId: `res_${Date.now()}` };
}

async function releaseInventory(orderId: string) {
  // Release logic
}

async function processPayment(params: any) {
  return {
    paymentId: `pay_${Date.now()}`,
    transactionId: `txn_${Date.now()}`
  };
}

async function refundWithProvider(params: {
  transactionId: string;
  amount: number;
  idempotencyKey: string;
}) {
  // In production: the provider's refund API with its own idempotency key
}

async function updateOrderStatus(orderId: string, status: string) {
  await docClient.send(
    new UpdateCommand({
      TableName: process.env.ORDERS_TABLE!,
      Key: { orderId },
      UpdateExpression: 'SET #status = :status',
      ExpressionAttributeNames: { '#status': 'status' },
      ExpressionAttributeValues: { ':status': status }
    })
  );
}

Where Each Approach Holds#

Default to Step Functions orchestration when the flow crosses more than three or four services, needs a human approval step, or has to be explained to someone during an incident: the execution history already answers which step failed and which compensations ran. Move to EventBridge choreography when the flow is linear, the services publish domain events anyway, and the cost of a central coordinator (one more deployment, one more owner) outweighs the visibility it buys.

Two constraints survive either choice. Every step needs an idempotency key, and every compensation must be safe to run twice; a saga that skips one of them breaks only under retry, which is the worst place to discover it. Once the happy path works, give the manual-intervention queue an owner and an alarm: failed compensations and timed-out executions end there, and it is the one queue a person has to read.

References#

Related posts