AWS Step Functions and Workflow Orchestration
Overview
AWS Step Functions lets you coordinate multiple services into a state machine: a visual, JSON-defined workflow with branching, parallel work, retries, error handling and waits. Instead of burying orchestration logic inside Lambda functions calling each other, the workflow itself becomes explicit, observable and durable.
Think of an airport check-in process: check the ticket, then in parallel weigh baggage and verify the passport, wait for security approval, and route problems to a desk. Step Functions is the process manager that remembers where each passenger is, even if a counter is closed for a while.
You write the definition in Amazon States Language (ASL), and Step Functions calls Lambda, DynamoDB, SQS, SNS, ECS, Glue and 200+ services directly via SDK integrations, often without any glue code.
Key Concepts
- Standard workflows: up to 1 year, exactly-once execution, full history, priced per state transition. Express workflows: up to 5 minutes, at-least-once (async) or at-most-once (sync), very high rate, priced per execution and duration.
- State types: Task, Choice, Wait, Parallel, Map, Pass, Succeed, Fail.
- Retry (with
IntervalSeconds,BackoffRate,MaxAttempts) and Catch handle errors declaratively per state. - Service integrations: request-response, .sync (wait for job to finish) and .waitForTaskToken (callback pattern for humans/external systems).
- Map processes arrays; Distributed Map handles millions of S3 objects at high concurrency.
- Data flows via InputPath, Parameters, ResultSelector, ResultPath, OutputPath, and JSONata or intrinsic functions.
- Workflows can be invoked by API Gateway, EventBridge, SDK, Lambda or schedule; Synchronous Express returns the result.
- Use Step Functions to orchestrate long-running or human-approval work Lambda cannot handle (15-minute limit).
Detailed Notes
Standard vs Express
| Feature | Standard | Express |
|---|---|---|
| Max duration | 1 year | 5 minutes |
| Execution semantics | Exactly-once | At-least-once (async), at-most-once (sync) |
| Execution history | In service (90 days) and CloudWatch | CloudWatch Logs only |
| Rate | ~2,000 starts/s | 100,000+/s |
| Pricing | Per state transition | Per request and duration |
| Best for | Order processing, approvals, ETL | High-volume streaming, IoT, API backends |
A workflow in ASL
{
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "arn:aws:lambda:eu-west-1:111122223333:function:Validate", "Payload.$": "$" },
"ResultSelector": { "valid.$": "$.Payload.valid" },
"ResultPath": "$.validation",
"Retry": [{
"ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 4
}],
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "NotifyFailure" }],
"Next": "IsValid"
},
"IsValid": {
"Type": "Choice",
"Choices": [{ "Variable": "$.validation.valid", "BooleanEquals": true, "Next": "ChargeAndShip" }],
"Default": "NotifyFailure"
},
"ChargeAndShip": {
"Type": "Parallel",
"Branches": [
{ "StartAt": "Charge", "States": { "Charge": { "Type": "Task", "Resource": "arn:aws:states:::dynamodb:putItem",
"Parameters": { "TableName": "Charges", "Item": { "id": { "S.$": "$.orderId" } } }, "End": true } } },
{ "StartAt": "Ship", "States": { "Ship": { "Type": "Task", "Resource": "arn:aws:states:::sqs:sendMessage",
"Parameters": { "QueueUrl": "https://sqs.eu-west-1.amazonaws.com/111122223333/ship", "MessageBody.$": "States.JsonToString($)" }, "End": true } } }
],
"End": true
},
"NotifyFailure": {
"Type": "Task", "Resource": "arn:aws:states:::sns:publish",
"Parameters": { "TopicArn": "arn:aws:sns:eu-west-1:111122223333:alerts", "Message": "Order failed" },
"End": true
}
}
}
Without Retry/Catch, a failing Task fails the whole execution. Common error names: States.ALL, States.Timeout, States.TaskFailed, States.Runtime.
Integration patterns
| Pattern | Resource suffix | Behaviour |
|---|---|---|
| Request-response | (none) | Call API, continue immediately |
| Run a job | .sync | Wait until job completes (Batch, ECS, Glue, nested workflow) |
| Callback | .waitForTaskToken | Pause until SendTaskSuccess/SendTaskFailure with the token |
import boto3
sfn = boto3.client("stepfunctions")
# A manager clicks "approve" in a web app:
sfn.send_task_success(taskToken=token, output='{"approved": true}')
Starting executions
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:eu-west-1:111122223333:stateMachine:OrderFlow \
--name order-42 --input '{"orderId":"42"}'
Standard execution names are unique for 90 days, giving idempotent starts.
Saga pattern
For distributed transactions, add compensating states in Catch blocks (for example refund payment when shipping fails) instead of attempting a distributed ACID transaction.
SAM definition
OrderFlow:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: statemachine/order.asl.json
Type: STANDARD
Policies:
- LambdaInvokePolicy: { FunctionName: !Ref ValidateFn }
Step Functions vs alternatives
| Need | Use |
|---|---|
| Multi-step workflow with branching, retries, waits | Step Functions |
| Simple async decoupling | SQS / SNS |
| Pure event routing | EventBridge |
| Large ETL DAG with Python | MWAA (Airflow) |
Error handling in Amazon States Language
{
"StartAt": "Charge",
"States": {
"Charge": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "charge-card", "Payload.$": "$" },
"TimeoutSeconds": 30,
"Retry": [{ "ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 2, "MaxAttempts": 4, "BackoffRate": 2.0 }],
"Catch": [{ "ErrorEquals": ["PaymentDeclined"], "ResultPath": "$.error", "Next": "NotifyCustomer" }],
"Next": "Fulfil"
},
"NotifyCustomer": { "Type": "Task", "Resource": "arn:aws:states:::sns:publish",
"Parameters": { "TopicArn": "arn:aws:sns:eu-west-1:111122223333:alerts", "Message.$": "$.error" }, "End": true },
"Fulfil": { "Type": "Succeed" }
}
}
Retry runs before Catch; ResultPath controls where results or errors are merged into the state input.
State types and integration patterns
| State | Purpose |
|---|---|
| Task | Do work (Lambda, SDK integration to 200+ services) |
| Choice | Branch on input |
| Parallel / Map | Run branches or iterate over items (Distributed Map for millions of S3 objects) |
| Wait | Delay for a time or until a timestamp |
| Pass / Fail / Succeed | Shape data or end |
Integration patterns: Request-Response (continue immediately), Run a Job (.sync) (wait for completion, for example Batch, ECS or Glue), and Wait for Callback (.waitForTaskToken) for human approval or external systems. Standard workflows last up to one year with exactly-once execution and are billed per state transition; Express workflows run up to five minutes at very high rates with at-least-once (async) or at-most-once (sync) semantics and are billed by duration. Start workflows from API Gateway, EventBridge or StartExecution, and inspect failures in the execution history.
Real World Example
An insurance company processes claims that need document extraction, a fraud check, and a human adjuster approval that may take days. They built a Standard workflow: Textract and fraud Lambdas run in a Parallel state, a waitForTaskToken step emails the adjuster with a link, and a Catch branch triggers compensating actions and an SNS alert. Previously this lived in cron jobs and a status table; now every claim has a visual execution history that auditors can inspect.
Architecture Diagram
A Standard workflow validates, runs parallel work, and handles errors declaratively.
- 1An event or API call starts an execution with the order as input.
- 2The Validate task retries transient errors and catches failures.
- 3A Choice state routes valid orders to Parallel branches.
- 4Failures route to a notification state; the execution records every step.
Best Practices
- ✓Prefer direct SDK integrations over Lambda glue functions.
- ✓Define Retry with backoff and Catch for every Task that can fail.
- ✓Use Express for high-volume short flows, Standard for long or auditable ones.
- ✓Pass small payloads (256 KB limit); store large data in S3 and pass references.
- ✓Use .waitForTaskToken instead of polling loops for human or external steps.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Workflow longer than 15 minutes or with human approval -> Step Functions Standard.
- Wait for a job to complete -> .sync integration.
- Orchestration with retries/branching and no custom code -> Step Functions.
- State input limit 256 KB; use ResultPath to merge results.
Finished this lesson?
0 of 46 lessons done · 0% of the course

