Lesson 21 of 30Modern AWS
Step Functions and Durable Workflows
Build multi-step workflows that survive failure: Standard vs Express, JSONata, direct integrations, callbacks, retries, sagas, redrive and the alternatives.
The checkout flow started as one Lambda: reserve stock, charge the card, book the courier. Then the courier API got slow, so someone added a retry loop. Then payments sometimes timed out after charging, so someone added a "did it go through?" check. Then a large order needed manager approval, and the Lambda could not wait two hours for a human. Now it is 600 lines of state handling, and when it crashes halfway nobody knows which steps ran. That is the problem a durable workflow engine solves: it remembers where each run is, retries the right things, waits as long as needed, and shows you exactly what happened.
Queues and Events introduced Step Functions with one JSON example. This lesson covers how to design, run and debug real workflows, and when to use something else.
Standard vs Express
You pick the type when you create a state machine, and you cannot change it later.
| Standard | Express | |
|---|---|---|
| Max duration | 1 year | 5 minutes |
| Execution semantics | Exactly-once per state (unless you add Retry) | Async: at-least-once. Sync: at-most-once |
| Billing model | Per state transition | Per execution, duration and memory |
| History | Stored by the service for 90 days, visual in the console | Only what you send to CloudWatch Logs |
.sync and .waitForTaskToken | Yes | No |
| Distributed Map, redrive | Yes | No |
| Typical use | Business processes, payments, human approval, long jobs | High-volume event processing, API backends |
How to choose:
- Standard for anything that must not run a step twice by accident, waits for people or long jobs, or needs an audit trail. Payments, order fulfillment, onboarding, ML pipelines.
- Express for short, high-volume, idempotent work: transform each IoT message and write it to DynamoDB, or orchestrate three calls behind an API Gateway endpoint (a synchronous Express execution returns the result to the caller). Standard's per-transition billing gets expensive at millions of executions a day, which is exactly where Express is designed to run.
Standard also deduplicates on execution name: starting an execution with the name of one that is already running returns the same execution instead of starting a second. Use the order id as the name, and a double-submitted checkout cannot start two workflows.
A common pattern combines them: a Standard parent for the business process, calling Express children for bursts of short, idempotent work.
The states, and the limits that shape designs
A state machine is written in the Amazon States Language (ASL), as JSON. The state types:
- Task: do work (call a Lambda, an AWS API, an HTTP endpoint, an activity worker).
- Choice: branch on a condition.
- Parallel: run fixed branches at the same time and wait for all of them.
- Map: run the same steps for each item in a list. Inline Map runs inside the execution and suits tens of items. Distributed Map reads items from S3 (a CSV, a JSON array, or a whole prefix of objects) and runs each batch as a child execution, with up to 10,000 running in parallel. It is the tool for "process these 3 million files".
- Wait: pause for a duration or until a timestamp, at no compute cost.
- Pass: reshape data or inject a value.
- Succeed and Fail: end the execution.
Three limits drive design decisions:
- 256 KiB payload per state input or output. Pass S3 keys or ids between states, not documents.
- 25,000 events in a Standard execution's history. A loop that runs thousands of times hits this. Move bulk iteration into a Distributed Map or child executions.
- 1 year maximum for Standard, so a "subscription lifecycle" workflow that runs for years must restart itself periodically, or be modeled as many short executions.
JSONata and variables
Since late 2024, ASL supports JSONata as its query language, and AWS recommends it for new workflows. With JSONata, five old data fields (InputPath, Parameters, ResultSelector, ResultPath, OutputPath) collapse into two: Arguments (what you send to the task) and Output (what the state passes on). Expressions sit inside {% %}, and a reserved variable gives you $states.input, $states.result, $states.errorOutput (in a Catch) and $states.context. Assign stores workflow variables that later states read by name, so you stop threading every value through every state's output.
{
"QueryLanguage": "JSONata",
"StartAt": "SaveOrder",
"States": {
"SaveOrder": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:putItem",
"Arguments": {
"TableName": "orders",
"Item": {
"PK": { "S": "{% 'ORDER#' & $states.input.orderId %}" },
"SK": { "S": "#META" },
"status": { "S": "PENDING" }
},
"ConditionExpression": "attribute_not_exists(PK)"
},
"Assign": {
"orderId": "{% $states.input.orderId %}",
"total": "{% $states.input.total %}"
},
"Next": "NeedsApproval"
},
"NeedsApproval": {
"Type": "Choice",
"Choices": [{ "Condition": "{% $total > 1000 %}", "Next": "WaitForApproval" }],
"Default": "Charge"
},
"WaitForApproval": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
"Arguments": {
"QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/approvals",
"MessageBody": {
"orderId": "{% $orderId %}",
"taskToken": "{% $states.context.Task.Token %}"
}
},
"TimeoutSeconds": 172800,
"Next": "Charge"
},
"Charge": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Arguments": {
"FunctionName": "charge-card",
"Payload": { "orderId": "{% $orderId %}", "amount": "{% $total %}" }
},
"Output": "{% $states.result.Payload %}",
"End": true
}
}
}You will still meet JSONPath in older workflows ("Payload.$": "$", ResultPath: "$.error"). You can switch one state at a time, because QueryLanguage can be set per state as well as at the top.
Calling services without writing Lambdas
A Task's Resource decides what it calls and how it waits. There are three integration patterns:
- Request-response (the default, for example
arn:aws:states:::dynamodb:putItem): call the API and move on as soon as it returns.SaveOrderabove writes to DynamoDB with no Lambda in between. - Run a job (
.sync, for examplearn:aws:states:::ecs:runTask.sync): start an ECS task, Glue job, Batch job, CodeBuild build or child state machine, and wait until it finishes, polling for you. A two-hour batch job costs nothing while you wait. - Wait for a callback (
.waitForTaskToken): send a task token somewhere (an SQS message, an email via a Lambda, a ticket in another system) and pause until something callsSendTaskSuccessorSendTaskFailurewith that token. This is how human approval works. SetTimeoutSeconds, andHeartbeatSecondsfor long workers, or a lost token leaves the execution waiting for up to a year.
Beyond the optimized integrations, the AWS SDK integrations (arn:aws:states:::aws-sdk:<service>:<action>) reach almost any AWS API, and the HTTP Task calls external HTTPS APIs using an EventBridge connection for auth. There is also a Bedrock integration (arn:aws:states:::bedrock:invokeModel) for model calls as a workflow step.
Fewer Lambdas means less code, fewer cold starts and fewer deploys. Keep Lambdas for real business logic; do not write one whose only job is to call PutItem.
The state sends the order id and $states.context.Task.Token, then the execution pauses. No compute runs while it waits.
.waitForTaskToken as an Express workflow so it is cheaper at volume. Deployment fails validation. Why?Retries, catches and the saga pattern
When a Task, Parallel or Map state fails, Step Functions checks its Retry list first, then its Catch list, and only fails the execution if neither matches.
"Retry": [
{
"ErrorEquals": ["Payments.Timeout", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2,
"BackoffRate": 2,
"MaxAttempts": 3,
"MaxDelaySeconds": 30,
"JitterStrategy": "FULL"
}
],
"Catch": [
{
"ErrorEquals": ["States.ALL"],
"Output": "{% $merge([$states.input, {'error': $states.errorOutput}]) %}",
"Next": "ReleaseStock"
}
]What to know:
- Retry only transient errors: timeouts, throttling,
Lambda.ServiceException. Retrying "card declined" three times annoys the customer and changes nothing. Name your business errors (throwPayments.Declinedfrom your code) so you can route them precisely. - Jitter (
"JitterStrategy": "FULL") randomizes each wait so a thousand executions that failed together do not retry together.MaxDelaySecondscaps exponential growth. States.ALLmatches almost everything but must be last, and it does not catchStates.Runtime(a broken expression or data error) orStates.DataLimitExceeded(payload over the limit). Those fail the execution, so test your data paths.States.TaskFailedmatches any task failure exceptStates.Timeout.
What does this print?
interval, rate, attempts, cap = 3, 2.0, 3, 5 # IntervalSeconds, BackoffRate, MaxAttempts, MaxDelaySeconds waits = [] for n in range(attempts): waits.append(min(interval * rate ** n, cap)) print([int(w) for w in waits])
The saga. A distributed transaction across services (stock, payments, shipping) cannot use a database transaction. A saga runs each step as a local action with a matching compensation, and on failure runs the compensations for completed steps in reverse order. Step Functions is a natural saga coordinator: each forward step's Catch points to the compensation chain. This simulation follows the same rules: retry transient errors with backoff, catch everything else, compensate in reverse.
Press Run (⌘ Enter) to see what happens.Change FAILURES so charge_card fails four times and watch the retries run out and the saga compensate only the stock. Two rules make sagas safe in production: every step and every compensation must be idempotent (a retry after a timeout must not charge twice, so pass the order id as an idempotency key to the payment provider), and compensations must be retried until they succeed, because "refund failed" is the one outcome you cannot leave unfinished. Give them generous retries and an alarm.
Reserve stock. Its compensation is release.
Shipping fails permanently after stock was reserved and the card charged. Order what the workflow does.
- Tap the steps below in the right order.
Seeing what happened, and recovering
- Execution history: every Standard execution records each state's input, output, error and timing for 90 days. The console's graph view shows exactly where a run is or where it died. This alone is often the reason teams adopt Step Functions.
- CloudWatch Logs for Express (and optionally Standard), and CloudWatch metrics for failed, timed-out and throttled executions. Alarm on
ExecutionsFailed. - Tracing: enable X-Ray tracing on the state machine to follow a request through Lambdas and services. AWS's tracing direction is OpenTelemetry, so check the current recommendation for new instrumentation.
- Redrive: a failed, timed-out or aborted Standard execution can be redriven within 14 days. It resumes from the failed state with the same input, skipping steps that already succeeded. After you fix the bug or the downstream outage ends, redrive the failed executions instead of re-running whole workflows (which would charge cards twice).
Defining and testing workflows in code
Hand-written ASL is fine for small machines, but most teams generate it with infrastructure as code. In the CDK, each state class has a .jsonata() factory, and the construct grants the state machine's role permission to call each integrated resource.
import * as cdk 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";
import { Construct } from "constructs";
export class CheckoutStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const fn = (name: string) =>
lambda.Function.fromFunctionName(this, `${name}Fn`, name);
const release = tasks.LambdaInvoke.jsonata(this, "ReleaseStock", {
lambdaFunction: fn("release-stock"),
}).next(sfn.Fail.jsonata(this, "OrderFailed", { error: "OrderFailed" }));
const reserve = tasks.LambdaInvoke.jsonata(this, "ReserveStock", {
lambdaFunction: fn("reserve-stock"),
outputs: "{% $states.result.Payload %}",
});
const charge = tasks.LambdaInvoke.jsonata(this, "ChargeCard", {
lambdaFunction: fn("charge-card"),
outputs: "{% $states.result.Payload %}",
});
charge.addRetry({
errors: ["Payments.Timeout"],
interval: cdk.Duration.seconds(2),
backoffRate: 2,
maxAttempts: 3,
jitterStrategy: sfn.JitterType.FULL,
});
charge.addCatch(release, { errors: [sfn.Errors.ALL] });
new sfn.StateMachine(this, "Checkout", {
queryLanguage: sfn.QueryLanguage.JSONATA,
definitionBody: sfn.DefinitionBody.fromChainable(reserve.next(charge)),
tracingEnabled: true,
});
}
}For testing, the old Step Functions Local emulator is unsupported and lags features. The current answer is the TestState API: it runs one state, or one state inside a full definition, against AWS, and since late 2025 it accepts mocked task results and errors. That lets you assert in CI which Retry or Catch fires, what the backoff will be, and what data flows to the next state, without deploying Lambdas or granting IAM permissions. Pair it with a few end-to-end executions in a test account.
Choosing the right orchestration tool
| Tool | What it is | Pick it when |
|---|---|---|
| Step Functions Standard | Managed state machines, visual history | Multi-service business processes, approvals, long jobs, audit needs |
| Step Functions Express | Short, high-volume state machines | Event processing and API orchestration under 5 minutes |
| Lambda durable functions | Workflows written as ordinary code in a Lambda, with checkpoint and replay | The workflow is tightly coupled to one service's code and your team prefers code over a graph |
| EventBridge Scheduler | One-off or recurring schedules that call a target | "Send the reminder in 3 days", cron jobs at scale |
| EventBridge Pipes | Point-to-point source to target, with filter and enrichment | Stream or queue records to one target with light transformation |
| SQS between Lambdas | Queue-chained functions | Two simple stages with no shared state or compensation |
| Temporal | Open-source durable execution platform, code-first | Multi-cloud, very complex long-running logic, a team happy to run or buy it |
Lambda durable functions (re:Invent 2025) deserve a closer look because they compete directly. You write a normal handler with the durable execution SDK and wrap work in steps (checkpointed, retried) and waits (suspended at no compute cost). When the function resumes after a wait or a crash, it replays from the top, skipping completed steps by reading their stored results. Executions can last up to a year. The rule that comes with replay: code outside steps must be deterministic. Reading the clock, generating ids or calling an API outside a step gives a different answer on replay. Put every side effect and non-deterministic call inside a step. Step Functions gives you a visual graph, 200+ native integrations and no code to host; durable functions give you plain code, normal unit tests and language features. Both are good; pick per workflow, not per company.
Match each requirement to the tool.
- Standard workflow
- A durable state machine type: up to a year, exactly-once states, stored history, callbacks, .sync and redrive.
- Express workflow
- A short (5 minute) high-volume state machine type with at-least-once (async) or at-most-once (sync) semantics.
- JSONata
- The query language recommended for new state machines, using Arguments, Output, Assign and {% %} expressions.
- task token
- A token sent with .waitForTaskToken that pauses the state until SendTaskSuccess or SendTaskFailure is called with it.
- saga
- A multi-service process where each step has a compensation, run in reverse order when a later step fails.
- redrive
- Restarting a failed Standard execution from the failed state within 14 days, keeping results of steps that succeeded.
- durable functions
- Lambda workflows written as code that checkpoint each step and replay deterministically after waits or failures.