Thuta Learning
AWS Advanced
Event-Driven & ServerlessDevOpsAdvanced

Step Functions: Workflows, Retry/Catch and the Saga Pattern

AWS AdvancedLesson 1850 min

What you'll walk away with

  • Choose Standard or Express workflows based on duration, delivery semantics and cost
  • Write valid ASL using Task, Choice, Parallel, Map, Wait, Pass, Fail and Succeed states
  • Configure Retry with backoff and jitter, and Catch that keeps the original input
  • Tell apart request-response, .sync and waitForTaskToken integrations
  • Design a saga with compensation steps

Explain it simply

Explain it simply

Step Functions is a flowchart that AWS runs for you. Each box is a state: 'call this Lambda', 'check a value and branch', 'wait one hour', 'process these items in parallel'. The flowchart itself is JSON, written in Amazon States Language (ASL).

The key point is that Step Functions remembers where it is. When a step fails it retries the way you specified, it can wait for days, and the console shows the exact path each execution took. Your Lambdas focus on business logic, while the workflow owns 'what happens next'.

Problem → Why → Solution

The problem: chaining Lambdas

An order needs to reserve stock, charge a card and create a shipment. The quickest approach is one Lambda calling the next. But if shipping fails, the card is already charged and the stock already reserved. Who undoes them?

Retries, timeouts and error branching all end up hand-written in code. The first Lambda waits for the last one to finish, so you pay for idle waiting and can hit Lambda's 15-minute limit. To find where one execution stopped, you search three log groups.

chained_lambda.py
import json

import boto3

lambda_client = boto3.client("lambda")


def handler(event, context):
    # Orchestration logic is buried inside business code.
    stock = lambda_client.invoke(
        FunctionName="reserve-inventory", Payload=json.dumps(event).encode()
    )
    charge = lambda_client.invoke(
        FunctionName="charge-payment", Payload=stock["Payload"].read()
    )
    # If this fails: no retry, no refund, no stock release, no visibility.
    return lambda_client.invoke(
        FunctionName="create-shipment", Payload=charge["Payload"].read()
    )

Why this hurts

Orchestration (order, retries, error handling, undo) is tangled into business logic and the state is stored nowhere. Half-finished orders are left behind as inconsistent data.

Core concept: Standard, Express and ASL

When you create a state machine you pick one of two types, and you cannot change it later. Standard workflows run for up to one year, execute each step exactly once (unless you configure retries), and keep a full execution history in the console. Express workflows run for at most five minutes, are built for very high start rates, and send their history to CloudWatch Logs.

StandardExpress
Max duration1 year5 minutes
SemanticsExactly-once workflow executionAt-least-once (async), at-most-once (sync)
PricingPer state transitionPer request + duration + memory
.sync / waitForTaskTokenSupportedNot supported

An ASL document has StartAt (the first state's name) and States (a map of states). Task does work (calls a Lambda or an AWS API), Choice branches on the input, Parallel runs branches at the same time, Map runs steps for each item in an array, Wait pauses for a duration or until a timestamp, Pass reshapes data and moves on, and Succeed and Fail end the execution.

Data flows from state to state as a JSON document, controlled by path fields. InputPath picks part of the input, Parameters builds the payload sent to the task, ResultSelector trims the task's result, ResultPath decides where in the input the result is placed, and OutputPath chooses what is passed to the next state. Since late 2024 you can opt into JSONata expressions instead of these paths, but this lesson uses the widely used JSONPath style.

Step Functions identifies errors by string names. Built-in names start with States.: States.ALL (any error), States.Timeout, States.TaskFailed and others. When a Lambda raises a custom exception class such as PaymentDeclined, that class name becomes the error name, so Retry and Catch can treat business errors and transient errors differently.

text
DATA FLOW THROUGH ONE TASK STATE
--------------------------------
  state input {"orderId": "1042", "total": 1500}
        |
        v  InputPath / Parameters   -> payload sent to the task
  +-----------------+
  |   Task (Lambda) |  -> raw result {"Payload": {"chargeId": "ch_9"}}
  +-----------------+
        |  ResultSelector           -> {"chargeId": "ch_9"}
        |  ResultPath "$.payment"   -> merged into the original input
        v  OutputPath
  {"orderId": "1042", "total": 1500, "payment": {"chargeId": "ch_9"}}
Mental model
  1. JSON input enters a state
  2. State works and merges its result
  3. Retry/Catch handle errors
  4. Next picks the following state

Without ResultPath, a task's result replaces the whole input, which is how fields like orderId get lost.

Minimal ASL shape

minimal.asl.json
{
  "Comment": "Wait, then branch on a flag",
  "StartAt": "WaitABit",
  "States": {
    "WaitABit": { "Type": "Wait", "Seconds": 10, "Next": "IsPriority" },
    "IsPriority": {
      "Type": "Choice",
      "Choices": [
        { "Variable": "$.priority", "BooleanEquals": true, "Next": "Done" }
      ],
      "Default": "Tag"
    },
    "Tag": {
      "Type": "Pass",
      "Result": "standard",
      "ResultPath": "$.lane",
      "Next": "Done"
    },
    "Done": { "Type": "Succeed" }
  }
}

Every non-terminal state needs Next (or "End": true). A Choice state has Choices and Default instead of Next. Succeed and Fail are terminal and take no Next.

Worked example: an order saga state machine

This Standard workflow reserves stock, charges the card, waits for a human approval on orders of $1,000 or more, then ships. If a step fails, it undoes the completed steps in reverse order (refund, then release stock). This is the saga pattern: restoring consistency with compensation steps where no distributed transaction exists.

order-saga.asl.json
{
  "Comment": "Order saga: reserve, charge, approve, ship; compensate on failure",
  "StartAt": "ReserveInventory",
  "States": {
    "ReserveInventory": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "reserve-inventory", "Payload.$": "$" },
      "ResultSelector": { "reservationId.$": "$.Payload.reservationId" },
      "ResultPath": "$.reservation",
      "Retry": [
        {
          "ErrorEquals": ["Lambda.TooManyRequestsException", "Lambda.ServiceException"],
          "IntervalSeconds": 2,
          "MaxAttempts": 3,
          "BackoffRate": 2.0,
          "JitterStrategy": "FULL"
        }
      ],
      "Catch": [
        {
          "ErrorEquals": ["States.ALL"],
          "ResultPath": "$.error",
          "Next": "OrderFailed"
        }
      ],
      "Next": "ChargePayment"
    },
    "ChargePayment": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "charge-payment", "Payload.$": "$" },
      "ResultSelector": { "chargeId.$": "$.Payload.chargeId" },
      "ResultPath": "$.payment",
      "Retry": [
        {
          "ErrorEquals": ["PaymentProviderUnavailable"],
          "IntervalSeconds": 5,
          "MaxAttempts": 4,
          "BackoffRate": 2.0,
          "MaxDelaySeconds": 30
        }
      ],
      "Catch": [
        {
          "ErrorEquals": ["States.ALL"],
          "ResultPath": "$.error",
          "Next": "ReleaseInventory"
        }
      ],
      "Next": "NeedsApproval"
    },
    "NeedsApproval": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.total",
          "NumericGreaterThanEquals": 1000,
          "Next": "WaitForApproval"
        }
      ],
      "Default": "ShipOrder"
    },
    "WaitForApproval": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
      "Parameters": {
        "QueueUrl": "https://sqs.us-east-1.amazonaws.com/111122223333/order-approvals",
        "MessageBody": { "orderId.$": "$.orderId", "taskToken.$": "$$.Task.Token" }
      },
      "ResultPath": "$.approval",
      "TimeoutSeconds": 86400,
      "Catch": [
        {
          "ErrorEquals": ["States.ALL"],
          "ResultPath": "$.error",
          "Next": "RefundPayment"
        }
      ],
      "Next": "ShipOrder"
    },
    "ShipOrder": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "create-shipment", "Payload.$": "$" },
      "ResultSelector": { "trackingId.$": "$.Payload.trackingId" },
      "ResultPath": "$.shipment",
      "Catch": [
        {
          "ErrorEquals": ["States.ALL"],
          "ResultPath": "$.error",
          "Next": "RefundPayment"
        }
      ],
      "Next": "OrderComplete"
    },
    "RefundPayment": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "refund-payment", "Payload.$": "$" },
      "ResultPath": null,
      "Retry": [
        {
          "ErrorEquals": ["States.ALL"],
          "IntervalSeconds": 5,
          "MaxAttempts": 5,
          "BackoffRate": 2.0
        }
      ],
      "Next": "ReleaseInventory"
    },
    "ReleaseInventory": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "release-inventory", "Payload.$": "$" },
      "ResultPath": null,
      "Retry": [
        {
          "ErrorEquals": ["States.ALL"],
          "IntervalSeconds": 5,
          "MaxAttempts": 5,
          "BackoffRate": 2.0
        }
      ],
      "Next": "OrderFailed"
    },
    "OrderFailed": {
      "Type": "Fail",
      "Error": "OrderFailed",
      "Cause": "A step failed and the completed steps were compensated"
    },
    "OrderComplete": { "Type": "Succeed" }
  }
}

Code breakdown

  1. Retry"ErrorEquals": ["Lambda.TooManyRequestsException", "Lambda.ServiceException"]

    Only throttling and transient Lambda service errors are retried. The interval grows 2, 4, 8 seconds, and JitterStrategy FULL spreads out retries from many executions failing at once. Do not retry business errors such as a declined card; the answer will not change.

  2. Catch + ResultPath{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "ReleaseInventory" }

    When retries are exhausted, or the error has no retrier, Catch routes to a compensation step. ResultPath "$.error" adds the error to the input instead of replacing it, so ReleaseInventory still sees reservationId.

  3. waitForTaskToken"taskToken.$": "$$.Task.Token"

    $$ is the context object. The task token is sent inside the SQS message and the execution pauses. It continues only when the approval app calls SendTaskSuccess or SendTaskFailure with that token, and after 24 hours (TimeoutSeconds) it raises States.Timeout.

  4. Compensation"ResultPath": null

    The refund and release steps discard their result and pass the input through unchanged. They retry more aggressively, because a failed compensation is the worst outcome.

You should see
Sample execution ($1,500 order, card declined):
ReserveInventory  -> succeeded
ChargePayment     -> failed (PaymentDeclined), caught
ReleaseInventory  -> succeeded
OrderFailed       -> execution status FAILED
Saga paths
  1. ReserveInventory
  2. ChargePayment
  3. NeedsApproval (Choice)
  4. ShipOrder

Every step succeeds

OrderComplete

Shipping fails

Refund -> Release -> OrderFailed

Three service integration patterns

PatternResource formWhat it waits for
Request-responsearn:aws:states:::sns:publishOnly the API call returning
Run a job (.sync)arn:aws:states:::ecs:runTask.syncThe job to finish
Callback...sqs:sendMessage.waitForTaskTokenSendTaskSuccess with the token

Request-response calls the API and moves on immediately. .sync starts a job, such as an ECS task, a Glue job, a CodeBuild build or a child state machine (states:startExecution.sync:2), and Step Functions polls until it completes, so you never write a polling loop. The callback pattern waits for a human or an external system; with HeartbeatSeconds set, the worker must prove it is alive with SendTaskHeartbeat.

deploy-and-run.sh
aws stepfunctions create-state-machine --name order-saga --type STANDARD \
  --definition file://order-saga.asl.json \
  --role-arn arn:aws:iam::111122223333:role/order-saga-sfn

SM_ARN=$(aws stepfunctions list-state-machines \
  --query "stateMachines[?name=='order-saga'].stateMachineArn" --output text)

aws stepfunctions start-execution --state-machine-arn "$SM_ARN" \
  --name order-1042 --input '{"orderId": "1042", "total": 1500}'

# The approval app resumes the paused execution with the token it received
aws stepfunctions send-task-success --task-token "$TASK_TOKEN" \
  --task-output '{"approved": true, "approver": "ops-lead"}'

Parallel, Map and writing it with CDK

A Parallel state runs each branch as its own sub-workflow at the same time and returns the results as an array; if any branch fails, the whole Parallel state fails. A Map state runs an ItemProcessor for every item in an array, and MaxConcurrency caps how many run at once. For large datasets, such as millions of S3 objects, Distributed Map mode runs many child executions in parallel.

parallel-map.asl.json
{
  "StartAt": "Enrich",
  "States": {
    "Enrich": {
      "Type": "Parallel",
      "Branches": [
        {
          "StartAt": "FraudScore",
          "States": {
            "FraudScore": {
              "Type": "Task",
              "Resource": "arn:aws:states:::lambda:invoke",
              "Parameters": { "FunctionName": "fraud-score", "Payload.$": "$" },
              "OutputPath": "$.Payload",
              "End": true
            }
          }
        },
        {
          "StartAt": "LoyaltyTier",
          "States": {
            "LoyaltyTier": { "Type": "Pass", "Result": { "tier": "gold" }, "End": true }
          }
        }
      ],
      "ResultPath": "$.enrichment",
      "Next": "NotifyEachItem"
    },
    "NotifyEachItem": {
      "Type": "Map",
      "ItemsPath": "$.items",
      "MaxConcurrency": 5,
      "ItemProcessor": {
        "ProcessorConfig": { "Mode": "INLINE" },
        "StartAt": "Notify",
        "States": {
          "Notify": {
            "Type": "Task",
            "Resource": "arn:aws:states:::sns:publish",
            "Parameters": {
              "TopicArn": "arn:aws:sns:us-east-1:111122223333:item-updates",
              "Message.$": "States.JsonToString($)"
            },
            "End": true
          }
        }
      },
      "ResultPath": null,
      "End": true
    }
  }
}

In production, teams often write ASL with CDK rather than by hand. The constructs wire up Lambda ARNs, IAM permissions and state names in a type-safe way, which removes mistakes like a forgotten invoke permission or a misspelled state name.

order-saga-stack.ts
import { App, Duration, Stack } from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as sfn from "aws-cdk-lib/aws-stepfunctions";
import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks";

const app = new App();
const stack = new Stack(app, "OrderSagaStack");

const step = (id: string, resultPath?: string): tasks.LambdaInvoke =>
  new tasks.LambdaInvoke(stack, id, {
    lambdaFunction: new lambda.Function(stack, id + "Fn", {
      runtime: lambda.Runtime.PYTHON_3_12,
      handler: "index.handler",
      code: lambda.Code.fromInline("def handler(event, context):\n    return event\n"),
    }),
    payloadResponseOnly: true,
    resultPath: resultPath ?? sfn.JsonPath.DISCARD,
  });

const orderFailed = new sfn.Fail(stack, "OrderFailed", { error: "OrderFailed" });
const release = step("ReleaseInventory").next(orderFailed);
const refund = step("RefundPayment").next(release);

const reserve = step("ReserveInventory", "$.reservation");
reserve.addCatch(orderFailed, { resultPath: "$.error" });

const charge = step("ChargePayment", "$.payment");
charge.addRetry({
  errors: ["PaymentProviderUnavailable"],
  interval: Duration.seconds(5),
  maxAttempts: 4,
  backoffRate: 2,
});
charge.addCatch(release, { resultPath: "$.error" });

const ship = step("ShipOrder", "$.shipment");
ship.addCatch(refund, { resultPath: "$.error" });

new sfn.StateMachine(stack, "OrderSaga", {
  stateMachineType: sfn.StateMachineType.STANDARD,
  timeout: Duration.days(2),
  definitionBody: sfn.DefinitionBody.fromChainable(
    reserve.next(charge).next(ship).next(new sfn.Succeed(stack, "OrderComplete")),
  ),
});

app.synth();

When Step Functions wins (and when it does not)

With three or more steps, branching, different retry policies per step, compensation, waits from minutes to days, or a need for per-execution history for audits, Step Functions is clearer than a chain of Lambdas. AWS SDK integrations can also call DynamoDB, SQS, SNS and others directly without a Lambda, which removes both code and cold starts.

But if one Lambda only drops a message on a queue, a workflow adds nothing. In a synchronous API path that must answer within a few milliseconds, every state transition adds latency. And for short workflows running thousands of times per second, per-transition Standard pricing climbs fast, so choose Express.

In production

In production

A common pattern combines both types. A long-running parent workflow that needs auditing, such as the order lifecycle, is Standard, while short high-volume parts, such as validating thousands of items, are split into Express child workflows. You then pay for history and exactly-once semantics only where they matter.

  • Data pipelines: a Glue job with .sync, then an Athena query, then an SNS notification with the result.
  • Human approvals: waitForTaskToken with the token stored behind an email or Slack link.
  • CloudWatch alarms on ExecutionsFailed and ExecutionsTimedOut, with X-Ray tracing enabled.
  • State machine versions and aliases to shift a small share of traffic to a new definition first.

In sagas, every compensation step is written to be idempotent: calling refund-payment twice must not refund twice. Teams therefore pass IDs such as chargeId to the payment provider as an idempotency key.

Common mistakes

Common mistakes

Mistake 1: forgetting ResultPath and losing the input

By default a task's result replaces the entire state input. After ChargePayment, orderId and reservationId are gone, and only in the compensation step do you discover it cannot tell what to release. Set ResultPath (for example "$.payment") on every task, and use "$.error" in Catch too.

Mistake 2: putting large payloads in the state

Each state's input and output is limited to 256 KB. Putting a whole CSV file or thousands of Map results in the state fails with States.DataLimitExceeded. Store data in S3 and pass only the bucket and key, and control Map results with ResultPath null or the Distributed Map ResultWriter.

Mistake 3: picking the wrong workflow type

Express workflows do not support .sync or waitForTaskToken and time out after five minutes, so an approval flow cannot be built on Express. Conversely, processing every IoT event with a Standard workflow racks up transition charges. The type cannot be changed later, so decide up front.

💰 Cost & Cleanup

Standard workflows are billed per state transition (roughly $0.025 per 1,000 transitions in us-east-1, with a monthly free tier of 4,000 transitions; check the pricing page). Every retry also counts as a transition. Express is billed by request count and duration times memory. Lambda invocations, SQS messages and CloudWatch Logs are billed separately. A few lab executions usually fit in the free tier, but stop any execution paused on waitForTaskToken and delete every resource.

Clean up when you are done

bash
aws stepfunctions stop-execution --execution-arn "$EXECUTION_ARN"
aws stepfunctions delete-state-machine --state-machine-arn "$SM_ARN"
for fn in reserve-inventory charge-payment create-shipment refund-payment \
  release-inventory; do
  aws lambda delete-function --function-name "$fn"
done
aws sqs delete-queue --queue-url "$APPROVALS_QUEUE_URL"
cdk destroy OrderSagaStack --force

Mini challenge

Mini challenge: a cooling-off period before shipping

Customers may cancel within one hour of ordering. Write the ASL for two states to insert between ChargePayment and ShipOrder.

  • A Wait state that waits 3600 seconds
  • A Choice state that goes to RefundPayment when $.cancelled is true, otherwise to ShipOrder
  • Valid JSON, with Next or Default on every state

Expected: Uncancelled orders ship one hour later; cancelled orders take the refund and release compensation path.

Show hint

Use the BooleanEquals comparison. If the field might be missing, combine IsPresent with And.

Show solution
cooling-off-states.json
{
  "CoolingOff": { "Type": "Wait", "Seconds": 3600, "Next": "WasCancelled" },
  "WasCancelled": {
    "Type": "Choice",
    "Choices": [
      {
        "And": [
          { "Variable": "$.cancelled", "IsPresent": true },
          { "Variable": "$.cancelled", "BooleanEquals": true }
        ],
        "Next": "RefundPayment"
      }
    ],
    "Default": "ShipOrder"
  }
}

Quick quiz 1 / 3

A workflow must wait up to three days for a manager's approval. What should you use?

Quick quiz 2 / 3

A task has a Catch with no ResultPath. When an error is caught, what does the Catch's Next state receive as input?

Quick quiz 3 / 3

You want to start a Glue job and wait until it finishes, without writing polling code. Which integration pattern?

What to remember

  • Standard suits long-running, auditable workflows; Express suits short, high-volume ones.
  • Retry transient errors with backoff and jitter; route everything else through Catch to compensation.
  • Always use ResultPath to keep the input, and keep large payloads in S3.
  • A saga undoes completed steps in reverse order with idempotent compensations.

AWS Step Functions Developer Guide — AWS Documentation

Amazon States Language — AWS Documentation

Service integration patterns — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Step Functions: Workflows, Retry/Catch and the Saga Pattern | Thuta Learning