A relay race with a course map
Picture a relay race through town. Nobody runs the whole course alone. It's split into legs, and at each station a different runner does one job and hands the baton on. The baton carries a note, say a customer's order, and each runner can add a line to it.
The race has an official. The official doesn't run. They hold the course map, hand the baton to the next runner, take it back when the leg is done, and check the map to see where it goes next. Every handover goes in the official's logbook, with the time and what the note said.
The course map is drawn once, in a set format any official can read, and it's called a state machine. Each time someone fires the starting pistol, a new race runs on the same map, with its own baton and its own logbook page.
Why bother with an official? Because each runner only has to know their own leg. The order of the legs, what to do when one goes wrong, and remembering how far the race has got: that's all the official's job, so nothing is lost if a runner goes home.
State machines and executions
AWS Step Functions is a managed workflow orchestrator. You define a state machine in Amazon States Language
(ASL), a JSON document: StartAt names the first state, States maps state names to their definitions, and each
state has a Type and either Next or End: true.
Each run is an execution, started with the StartExecution API (or by EventBridge, API Gateway or another state
machine) with a JSON input. Each state receives JSON input and passes JSON output to the next one; the payload
between states is limited to 256 KiB, so pass references (an S3 key, an order id) rather than large documents.
Task states do the work: invoke a Lambda function, call an AWS API directly, or wait for an external worker. The state machine owns sequencing, retries, timeouts and the progress of each execution, so your functions stay small and stateless, and a workflow can outlive Lambda's 15-minute limit.
1{2"Comment": "Process an order",3"StartAt": "CheckOrder",4"States": {5"CheckOrder": {6"Type": "Task",7"Resource": "arn:aws:states:::lambda:invoke",8"Parameters": { "FunctionName": "check-order", "Payload.$": "$" },9"OutputPath": "$.Payload",10"Next": "TakePayment"11},12"TakePayment": {13"Type": "Task",14"Resource": "arn:aws:states:::lambda:invoke",15"Parameters": { "FunctionName": "take-payment", "Payload.$": "$" },16"OutputPath": "$.Payload",17"Next": "PackParcel"18},19"PackParcel": {20"Type": "Task",21"Resource": "arn:aws:states:::lambda:invoke",22"Parameters": { "FunctionName": "pack-parcel", "Payload.$": "$" },23"OutputPath": "$.Payload",24"End": true25}26}27}
Step Functions records every step in the execution's history: state entered and exited, task scheduled, started,
succeeded or failed, with the input and output of each. The console draws it as a graph of the state machine with each
state coloured by its status, which makes it the first place to look when a run goes wrong. Paths like $.Payload are
JSONPath, the default; a state machine, or a single state, can set QueryLanguage to JSONata instead, which
replaces Parameters and OutputPath with Arguments and Output.
Forks, side-by-side legs and the finish line
Not every station on the map is a runner doing a job. The map has a few kinds of station, called states:
- A runner's leg: someone does one job with the baton.
- A fork in the road: the official reads the note and points the way. "In stock? Go left. Out of stock? Go right."
- A side-by-side stretch: the note is copied, several runners set off at once, and the official waits until all of them are back before going on.
- One runner per item: if the note lists five parcels, five runners each take one, and the official collects all five results.
- A rest stop: the race just waits, for ten minutes or until a set time.
- A checkpoint: nobody runs; the official only tidies the note or adds a line.
- The finish line, or a red flag that ends the race as failed, with the reason written down.
The state types
| Type | What it does |
|---|---|
Task | Does one unit of work: a Lambda invoke, an AWS API call, an activity |
Choice | Picks the next state from Choices rules evaluated in order, else Default; it can't end the execution |
Parallel | Runs every branch in Branches concurrently on the same input; output is an array of branch outputs |
Map | Runs the same sub-workflow for each item of an array (or, in Distributed mode, of an S3 dataset) |
Wait | Pauses for Seconds or until a Timestamp (or a value read from the input) |
Pass | Passes input to output, optionally injecting a fixed Result; handy for reshaping data and stubs |
Succeed | Ends the execution (or a branch) successfully |
Fail | Ends the execution as failed with an Error and Cause |
1"InStock?": {2"Type": "Choice",3"Choices": [4{ "Variable": "$.stock", "NumericGreaterThan": 0, "Next": "ShipAndNotify" }5],6"Default": "OutOfStock"7},8"OutOfStock": { "Type": "Fail", "Error": "OutOfStock", "Cause": "No units left" }
Parallel waits for all branches; if any branch fails and nothing catches it, the whole state fails and the other
branches are stopped. Map in Inline mode runs iterations inside the parent execution, up to 40 concurrently
(MaxConcurrency limits it further), and shares its history and payload limits. Distributed mode runs each
iteration as a child execution with its own history, reads items straight from S3, and scales to 10,000 child
executions in parallel, for jobs like processing millions of objects.
A dropped baton
Runners drop the baton now and then: a busy crossing, a stall that's shut for a minute. The map says what to do about it, station by station.
For most legs it says: "if the baton drops, wait a moment and run the leg again". Running it again is called a retry. Each time, the official waits longer before the next try, one second, then two, then four, so whatever got in the way has time to clear. The map also says how many tries a leg gets.
When the tries run out, the map can show a detour: a different path, for example to a station that phones the customer to say the card didn't work. If the map shows no detour, the official raises the red flag and the race ends as failed. Every try and every detour goes in the logbook.
There's one catch. Sometimes a runner did finish the job but tripped on the way back. The leg is run again, so every runner should check the note first: "did I already do this one?"
Retry and Catch
By default, when a state fails, the whole execution fails. Task, Parallel and Map states can declare Retry and
Catch to handle errors by name.
1"TakePayment": {2"Type": "Task",3"Resource": "arn:aws:states:::lambda:invoke",4"Parameters": { "FunctionName": "take-payment", "Payload.$": "$" },5"TimeoutSeconds": 30,6"Retry": [7{8"ErrorEquals": ["Lambda.TooManyRequestsException", "States.Timeout"],9"IntervalSeconds": 1,10"BackoffRate": 2.0,11"MaxAttempts": 2,12"MaxDelaySeconds": 10,13"JitterStrategy": "FULL"14}15],16"Catch": [17{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "TellCustomer" }18],19"Next": "PackParcel"20}
- Retriers are checked in order and the first whose
ErrorEqualsmatches is used. Defaults:IntervalSeconds1,MaxAttempts3 (retries after the first attempt; 0 means never retry),BackoffRate2.0.MaxDelaySecondscaps the growing interval andJitterStrategy: FULLrandomises it, so many failing executions don't retry in lockstep. - Catchers run once retries are exhausted (or when no retrier matches) and transition to
Next. WithoutResultPath, the error object replaces the state's input;"ResultPath": "$.error"keeps the input and adds the error alongside it. - Error names: your function's exception type,
States.Timeout(exceededTimeoutSecondsor missed a heartbeat),States.TaskFailed(any task failure except a timeout), andStates.ALL, which matches everything and must be the last entry, on its own, when used.
Set TimeoutSeconds on tasks explicitly. A retry re-runs work that may already have happened (a Lambda that charged
the card and then timed out), so tasks with side effects must be idempotent: pass a key such
as the order id and skip work already done.
Long races and sprints
There are two kinds of race, and you pick one when you draw the map.
A long race can go on for up to a year. The official writes every handover in the logbook, which anyone can read afterwards, and makes sure each leg is run exactly once, unless the map asks for a retry. You pay per handover.
A sprint, called Express, has to finish within five minutes. Sprints are for huge numbers of short races, many thousands every second. To keep up, the official keeps no logbook of their own; if you ask, they send a summary to the town records office. You pay for how many sprints you run, how long they last and how much they carry, which is far cheaper when there are lots of quick ones.
The price of speed: if you start a sprint and walk away, now and then a race gets run twice. So every runner in a sprint must cope with seeing the same baton again.
Standard and Express workflows
The workflow type is chosen when the state machine is created and can't be changed afterwards.
| Standard | Express | |
|---|---|---|
| Maximum duration | 1 year | 5 minutes |
| Execution semantics | Exactly-once: states don't run more than once unless Retry says so | Asynchronous: at-least-once. Synchronous (StartSyncExecution): at-most-once |
| Pricing basis | Per state transition | Per execution, plus duration (rounded up to 100 ms) times memory (in 64 MB steps) |
| Execution history | In the console and API, kept 90 days after the execution closes; at most 25,000 events per execution | Only in CloudWatch Logs, if logging is enabled |
| Integration patterns | Request Response, .sync, .waitForTaskToken | Request Response only |
StartExecution by name | Idempotent: same name and input returns the running execution | Not idempotent |
Use Standard for long-running, auditable business processes, human approvals and anything non-idempotent. Use Express for high-volume, short event processing (IoT ingestion, stream transforms, request-path orchestration behind API Gateway) where every step is idempotent. They combine well: a Standard parent can start Express workflows as nested children for its high-volume parts.
Stopping at shops on the way
Runners don't have to be hired helpers. The official can hand the baton straight to a shop along the route. The order-book shop, for example, can write the order in its big book, with no runner in between to pay or look after.
There are three ways to stop at a shop:
- Hand it over and take the receipt. The shop says "done" at once and the race goes on.
- Wait at the bakery. The official orders a big cake and waits at the counter until it's baked, however long that takes.
- Hand out a numbered ticket. The official drops a numbered ticket in a ticket box, and a helper outside the race picks it up, say a manager who has to approve a large order. The race pauses. When the helper brings the ticket back saying "approved", the race carries on. That ticket is called a task token: without it, nobody could tell which paused race to wake up. Give it a time limit, so a lost ticket can't hold the race forever.
Only long races can wait at the bakery or hand out tickets. A sprint has no time to stand around.
Service integrations
A Task's Resource can call AWS services directly, without a Lambda function as glue (no code, no cold start).
Optimized integrations (arn:aws:states:::dynamodb:putItem, sqs:sendMessage, sns:publish, ecs:runTask,
glue:startJobRun, states:startExecution and more) handle their service's details; AWS SDK integrations
(arn:aws:states:::aws-sdk:<service>:<action>) reach most other AWS APIs. Every call is made with the state machine's
IAM execution role, which must allow it.
Three integration patterns, chosen by the resource suffix:
- Request Response (no suffix): call the API and move on as soon as it responds, as with
PutItem. - Run a Job (
.sync): start a job and wait for it to finish, for exampleecs:runTask.sync,glue:startJobRun.syncorstates:startExecution.sync:2for a child workflow. The output is the job's result. - Wait for Callback (
.waitForTaskToken): pass the context value$$.Task.Tokento someone else (in an SQS message, an SNS notification, an email link) and pause. The execution resumes when anyone callsSendTaskSuccessorSendTaskFailurewith that token.
1"WaitForApproval": {2"Type": "Task",3"Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",4"Parameters": {5"QueueUrl": "https://sqs.eu-west-1.amazonaws.com/123456789012/approvals",6"MessageBody": { "orderId.$": "$.orderId", "taskToken.$": "$$.Task.Token" }7},8"HeartbeatSeconds": 3600,9"TimeoutSeconds": 172800,10"Next": "PackParcel"11}
A callback without TimeoutSeconds can wait as long as the execution lives (a year for Standard). Long-running
workers can call SendTaskHeartbeat to show they're alive; missing the HeartbeatSeconds window fails the task with
States.Timeout. .sync and callbacks need Standard workflows; Express supports only Request Response.
Undoing legs when the race can't finish
Some races change things along the way. The stockroom sets a parcel aside, the till takes the customer's money, and then the courier has no van. You can't just stop there: the parcel would sit set aside forever and the customer would have paid for nothing.
So the map has a detour that runs backwards: the till gives the money back, then the stockroom puts the parcel back on the shelf, and only then does the official raise the red flag. Each undo is a leg of its own. A race that cleans up after itself like this is called a saga. An undo can be re-run too, so the till checks the order number first and never refunds twice.
When the shop starts a long race, it fires the pistol with a race name, such as the order number. If someone fires it twice with the same name, the official sees a race by that name already exists and doesn't start a second one.
Sagas with compensating steps, and Java
A workflow across several services can't use one database transaction. A saga runs each step as its own local
transaction and, when a later step fails, runs compensating actions for the steps already done, in reverse order.
In Step Functions, each forward step's Catch routes into the compensation chain at the point that undoes the steps
already done (BookCourier to RefundPayment, TakePayment to ReleaseStock), and the chain ends in a Fail state so the
execution still reports the failure:
1"BookCourier": {2"Type": "Task",3"Resource": "arn:aws:states:::lambda:invoke",4"Parameters": { "FunctionName": "book-courier", "Payload.$": "$" },5"Retry": [ { "ErrorEquals": ["States.TaskFailed"], "MaxAttempts": 2 } ],6"Catch": [ { "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "RefundPayment" } ],7"End": true8},9"RefundPayment": {10"Type": "Task",11"Resource": "arn:aws:states:::lambda:invoke",12"Parameters": { "FunctionName": "refund-payment", "Payload.$": "$" },13"Retry": [ { "ErrorEquals": ["States.ALL"], "MaxAttempts": 5 } ],14"ResultPath": null,15"Next": "ReleaseStock"16},17"ReleaseStock": {18"Type": "Task",19"Resource": "arn:aws:states:::dynamodb:updateItem",20"Parameters": {21"TableName": "stock",22"Key": { "orderId": { "S.$": "$.orderId" } },23"UpdateExpression": "SET reserved = :no",24"ExpressionAttributeValues": { ":no": { "BOOL": false } }25},26"ResultPath": null,27"Next": "OrderFailed"28},29"OrderFailed": { "Type": "Fail", "Error": "CourierUnavailable", "Cause": "Order compensated" }
Compensations must not give up easily (retry them generously) and must be idempotent, keyed on the order id, because they can run more than once too.
From Java, start executions with the AWS SDK v2 SfnClient. Using the order id as the execution name makes the start
idempotent for Standard workflows: repeating the call with the same name and input returns the running execution,
and a closed one or different input raises ExecutionAlreadyExistsException.
1@Service2public class OrderWorkflow {34private final SfnClient sfn = SfnClient.create();5private final String stateMachineArn;67public OrderWorkflow(@Value("${orders.state-machine-arn}") String stateMachineArn) {8this.stateMachineArn = stateMachineArn;9}1011public String start(String orderId, String orderJson) {12try {13return sfn.startExecution(StartExecutionRequest.builder()14.stateMachineArn(stateMachineArn)15.name("order-" + orderId) // one execution per order16.input(orderJson)17.build())18.executionArn();19} catch (ExecutionAlreadyExistsException e) {20return null; // this order already ran21}22}2324// Called by the approval worker that received the task token from SQS25public void approve(String taskToken, boolean ok) {26if (ok) {27sfn.sendTaskSuccess(SendTaskSuccessRequest.builder()28.taskToken(taskToken).output("{\"approved\":true}").build());29} else {30sfn.sendTaskFailure(SendTaskFailureRequest.builder()31.taskToken(taskToken).error("Rejected").cause("Manager declined").build());32}33}34}
The Lambda functions behind each Task are ordinary handlers: they read the state input as their event and return the state output, so they stay small and testable on their own.
Gotchas: the 256 KiB payload limit applies to every state's input and output, so a Map over a big array or a
chatty Lambda response can fail with States.DataLimitExceeded, which States.ALL doesn't catch; keep data in S3 or
DynamoDB and pass keys. A Standard execution fails when its history reaches 25,000 events, so long loops belong in a
Distributed Map or in child executions. Standard executions that failed, timed out or were aborted can be redriven
within 14 days, resuming from the unsuccessful state with the same input instead of starting over (not available for
Express). Every state transition is billed on Standard, so a tight polling loop with Wait and
Choice costs more than a .sync integration or a callback.