AWS Step Functions
Overview and exam-focused notes on AWS Step Functions: state machines, Amazon States Language, state types, error handling, service integrations, pricing/limits, examples and common exam mistakes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
AWS Step Functions is a managed service to coordinate components of distributed applications and microservices using state machines. Engineers use it when they need reliable, observable, and maintainable orchestration of tasks (Lambda functions, AWS services, or activities) with retries, branching, and long-running workflows.
Key ideas
Execution — A single run of a state machine. Each execution has an identifier, a start time, an end time (if finished), and an execution history of events (state entered, state exited, task failed, etc.).
Amazon States Language (ASL) — A JSON-based language used to declare state machines. An ASL program is a JSON object with at minimum a top-level
StartAtandStatesmap. Example minimal skeleton:{ "StartAt": "MyState", "States": { ... } }Core state Types (exact names to use in ASL): Task, Choice, Pass, Wait, Parallel, Map, Succeed, Fail. Define each:
- Task: performs work by calling a resource (Lambda, AWS SDK service integration, activity). Include
Resourceto identify the integration. If the Task calls a Lambda function, it may be synchronous or asynchronous depending on integration type. Tasks also supportTimeoutSeconds/TimeoutSecondsPathandHeartbeatSeconds/HeartbeatSecondsPathfor timeouts and heartbeats, and the WaitForTaskToken callback pattern for human/external callbacks. - Choice: branching by evaluating boolean conditions on the JSON input; has
ChoicesandDefaultfields. Choice rules use operators such asStringEquals,NumericGreaterThanEquals,BooleanEquals,TimestampGreaterThan, and can be combined withAnd/Or/Not;Defaultis optional. - Pass: passes its input to its output (can inject constants) and transitions immediately.
- Wait: delays the state machine for a specified time or until a timestamp. Allowed fields:
Seconds,Timestamp,SecondsPath, orTimestampPath. - Parallel: runs multiple branches in parallel; success requires all branches to succeed; outputs are merged as an array of branch results.
- Map: iterates over an input array (specified by
ItemsPath) and runs the same sub-state-machine (Iterator) for each element. Useful for per-item processing. SupportsMaxConcurrencyto limit parallelism; Distributed Map addsItemReader/ItemBatcher/ResultWriter. - Succeed and Fail: terminal states that end the execution successfully or with failure.
- Task: performs work by calling a resource (Lambda, AWS SDK service integration, activity). Include
Input and output processing — Every state receives JSON input and produces JSON output. Use these fields precisely:
- InputPath: JSONPath applied to the state's incoming JSON to select the input for the state.
- Parameters: constructs the JSON passed to the task/resource; can inject portions of the state's input and constants.
- ResultPath: where to place the result returned by a state into the state's input to form the new state output.
- OutputPath: JSONPath that selects the final output of the state that is passed to the next state. (Defaults: InputPath and OutputPath default to "$" (pass-through); if ResultPath is not specified, the state's result replaces the state's input (the output equals the result); if ResultPath is null, the state's result is discarded and the input passes through.)
Error handling: Retry and Catch — States can retry on errors and/or catch them to route to recovery states.
- Retry block fields:
ErrorEquals(list of error names orStates.ALL),IntervalSeconds(initial wait before first retry),BackoffRate(multiplier for exponential backoff),MaxAttempts(upper bound on retries). - Catch block fields:
ErrorEquals,Next(state to go to on catch), and optionalResultPathto capture error data. Provide exact semantics in exams: Retry triggers when a task fails with matching error, applyingIntervalSecondsandBackoffRatebetween retry attempts; Catch transitions immediately when the task exhausts retries or fails with a match and routes toNext.
- Retry block fields:
Service integrations — Step Functions can invoke many AWS services directly (Lambda, SNS, SQS, DynamoDB, ECS, Batch, Glue, SageMaker, CodeBuild etc.) using service integration patterns. Integration uses a
Resourcewith a specific ARN pattern or an SDK action binding in ASL. Examples includearn:aws:states:::lambda:invoke,arn:aws:states:::sns:publish, andarn:aws:states:::aws-sdk:dynamodb:putItem. Callback pattern ARNs use the.waitForTaskTokensuffix.Execution types — Two main flavors: Standard (suitable for long-running, exactly-once workflows, has detailed execution history and higher latency guarantees) and Express (low cost for very high event rates, at-least-once, short duration, limited execution history visibility). Choose based on latency, throughput and cost needs.
Observability and state history — Each execution produces an event history you can view in console or query via APIs. Integrate with CloudWatch Logs and X-Ray (where supported) to trace executions.
State machine-as-code and automation — Define state machines via ASL JSON in CloudFormation / SAM / Terraform. Use Step Functions Local and SAM CLI for local testing.
Diagram to draw for an exam question demonstrating a simple workflow:
- Draw a left-to-right flow of rounded boxes: Start -> Task:InvokeLambda -> Choice (diamond) with two outgoing arrows labelled "condition true" to Succeed and "condition false" to Task:SendToQueue -> Succeed. Label arrows with the JSONPath condition (e.g. $.orderTotal > 1000). In ASL, you express this using Choice rule operators (e.g.,
NumericGreaterThanEqualson$.orderTotal) rather than raw expressions.
Formulas
(For this programming/topic, list syntax lines to remember)
{ "StartAt": "StateName", "States": { "StateName": { "Type": "Task", "Resource": "arn:aws:lambda:region:acct:function:FunctionName", "Next": "NextState" } } } — minimal ASL skeleton.
"InputPath": "$.path", "Parameters": {"key.$": "$.value"}, "ResultPath": "$.out", "OutputPath": "$.final" — common data-shaping fields and JSONPath usage (note .$ when injecting JSONPath results into Parameters).
client = boto3.client('stepfunctions') — boto3 syntax to create Step Functions client.
response = client.start_execution(stateMachineArn='arn:aws:states:region:acct:stateMachine:Name', input=json.dumps({"key": "value"})) — start an execution via boto3.
Retry: [{ "ErrorEquals": ["States.ALL"], "IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 3 }] — Retry block example.
Catch: [{ "ErrorEquals": ["CustomError"], "ResultPath": "$.errorInfo", "Next": "RecoverState" }] — Catch block example.
Worked examples
Example 1 — Simple Choice workflow (trace): State machine definition (summary): StartAt: ValidateOrder States:
- ValidateOrder (Task -> Lambda: validates order; Next: CheckHighValue)
- CheckHighValue (Choice) -> If
$.total >= 1000-> Approve (Succeed); else -> QueueForManual (Task to send SQS) -> Succeed Input to execution:{ "orderId": 42, "total": 1250 }Step-by-step trace:
- Execution starts at
ValidateOrder. Input = whole JSON. The Task calls the Lambda with the same input (assume no Parameters transform). - Lambda returns
{ "orderId": 42, "total": 1250, "valid": true }. Because no ResultPath was set, the state output equals the Lambda result (or merged if ResultPath used). Put show exact values: output ={ "orderId": 42, "total": 1250, "valid": true }. - Transition to
CheckHighValue. Evaluate Choice condition$.total >= 1000. Because 1250 >= 1000, follow theApprovebranch which is aSucceedstate. Execution ends successfully. Final output: the state machine's output is the Succeed state's input (unless OutputPath changes it) — in this trace final output ={ "orderId": 42, "total": 1250, "valid": true }.
Example 2 — Retry and Catch behaviour (algorithmic trace):
Definition snippet for a Task CallPaymentGateway with Retry and Catch:
CallPaymentGateway: Type Task, Resource Lambda, Retry [{ErrorEquals:["Gateway.Timeout"], IntervalSeconds:2, BackoffRate:2.0, MaxAttempts:2}], Catch [{ErrorEquals:["Gateway.Permanent"], Next:"NotifyFailure"}] Next: PaymentSuccess
Assume Lambda fails first with Gateway.Timeout, second attempt fails Gateway.Timeout, third attempt returns success. Input initial: { "amount": 500 }.
Trace:
- Initial attempt (attempt 1): Lambda call fails with
Gateway.Timeout. Retry block matches; wait IntervalSeconds = 2s. - Attempt 2: after 2s wait, Lambda called again; fails again with
Gateway.Timeout. Backoff applies: next wait = 2s * BackoffRate (2.0) = 4s. - Attempt 3: after 4s wait, Lambda called; this time it returns success. Transition to
PaymentSuccessstate. If the third attempt had failed withGateway.Permanent(an error in the Catch list), the Catch would have matched and execution would transition immediately toNotifyFailure, bypassing further retries. (Note: exam answers should state Retry uses exponential backoff with IntervalSeconds and BackoffRate and that Catch performs error routing.)
Example 3 — boto3 start_execution (short program trace):
Python snippet:
import boto3, json client = boto3.client('stepfunctions') resp = client.start_execution(stateMachineArn='arn:aws:states:region:acct:stateMachine:OrderFlow', input=json.dumps({"orderId":42})) print(resp['executionArn'])
What happens: API returns executionArn and startDate. The execution proceeds asynchronously for Standard workflows; for Express you may get different behavior regarding synchronous vs asynchronous integrations. Express Workflows also provide StartSyncExecution to return the result in the response; Standard supports only asynchronous StartExecution.
Common mistakes
- Using
.$incorrectly inParameters(must usekey.$when injecting a JSONPath value). - Expecting strong exactly-once semantics for Express Workflows — Express is at-least-once, so design idempotent tasks if using Express.
- Not handling errors with Catch and Retry; relying only on Lambda retries instead of state machine retries.
- Forgetting to set IAM permissions: Step Functions needs permissions to call resources (Lambda:InvokeFunction, other service actions). Students often forget to mention required IAM role on exams.
For your exam
Question types you will see:
- Definitions and short notes: define ASL, state types, InputPath/ResultPath/OutputPath, differences between Standard and Express.
- Derivations / diagrams: draw and label a state machine for a described workflow, show execution trace for a given input, and show how JSON flows through Input/Result/Output paths.
- Programs / config: write a minimal ASL JSON for a described flow, or a short boto3 snippet to start an execution.
- Error handling and reasoning: given a Retry and Catch block, trace attempts and final state for a sequence of failure types. What a full-marks answer includes:
- Clear definitions of terms used (ASL, state, execution, Task/Choice/etc.).
- Exact ASL fields and correct JSON syntax (StartAt, States map). Use
NextandEndcorrectly. - Correct data-shaping explanation showing InputPath -> Parameters -> ResultPath -> OutputPath with at least one small JSON example.
- For diagrams: boxes for states, labelled arrows for transitions and labeled conditions for Choice.
- Mention of IAM role and service integration (if task calls Lambda or other AWS services).
Quick check
- What ASL top-level fields are required at minimum to define a state machine?
- Name three state Types and one use-case for each.
- Which field do you use to put a Task's output into a specific location in the state's JSON output? Answers: StartAt and States; Task (call an AWS resource), Choice (branch by condition), Map (iterate over array); ResultPath.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?