Sub topic 2
State machines and Amazon States Language
This chapter assumes you know what Step Functions is for (the previous chapter covered orchestration). You should be comfortable with JSON, IAM roles, and the AWS CLI. It covers what a state machine definition is, how its structure is validated, how an execution moves through it, and the mistakes that cause most definition errors. Later chapters cover Task, Choice, and the other state types in detail.
The working model
A state machine is a definition of a workflow: a set of named states and the rules for moving between them. An execution is one run of that state machine with one input. You can start many executions of the same state machine at once, and each keeps its own current state and data.
The definition is written in Amazon States Language (ASL), a JSON-based format. Step Functions stores the definition, and the service interprets it. The definition holds no code that runs on your machine. Your code lives in the services the states call, such as Lambda functions.
At any moment an execution is in exactly one state, except inside Parallel and Map states, which run inner executions of their own. Each state receives JSON, does its work, produces JSON, and names the next state. The execution ends when it reaches a terminal state.
Top-level structure
A definition is one JSON object. These are the top-level fields:
| Field | Required | Meaning |
|---|---|---|
| `StartAt` | Yes | Name of the first state to run. It must match a key in `States`. |
| `States` | Yes | Object whose keys are state names and whose values are state definitions. |
| `Comment` | No | Free-text description. |
| `TimeoutSeconds` | No | Maximum duration of the whole execution. If it is exceeded, the execution ends with status `TIMED_OUT`. |
| `Version` | No | ASL version string. The only value is `"1.0"`, which is also the default. |
| `QueryLanguage` | No | `JSONPath` (the default) or `JSONata`. This tutorial uses JSONPath. |
State names are the keys of States. They must be unique within the state machine and at most 80 characters long. Names appear in the execution history and in Next references, so choose descriptive ones like ValidateOrder. Avoid names like State1.
Fields every state shares
Each state is an object with a Type. Beyond that, the fields depend on the type, but a few are common:
Typeis one ofTask,Choice,Wait,Pass,Succeed,Fail,Parallel, orMap.Commentis optional text.Nextnames the state that runs after this one.End: truemarks this state as the last one on its path.InputPath,OutputPath, and (for most types)ResultPathcontrol the data passed through the state. They are covered in the data-flow chapter.
Transition rules differ by type:
| State type | How it leaves the state |
|---|---|
| Task, Wait, Pass, Parallel, Map | Exactly one of `Next` or `End: true`. |
| Choice | Each rule in `Choices` has its own `Next`, and an optional `Default` names the fallback state. A Choice state has no top-level `Next` or `End`. |
| Succeed, Fail | These are terminal. Neither takes `Next` or `End`. |
A state machine can have several terminal states, such as one Succeed and one Fail. Every path from StartAt must end in a terminal state or a state with End: true.
A complete example
This definition uses four state types and no external services, so you can run it with only an IAM role. Save it as greeting.asl.json.
{
"Comment": "Greet a named user",
"StartAt": "AddStatus",
"TimeoutSeconds": 60,
"States": {
"AddStatus": {
"Type": "Pass",
"Result": { "stage": "received" },
"ResultPath": "$.status",
"Next": "Pause"
},
"Pause": {
"Type": "Wait",
"Seconds": 2,
"Next": "CheckName"
},
"CheckName": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.name",
"IsPresent": true,
"Next": "Done"
}
],
"Default": "MissingName"
},
"Done": {
"Type": "Succeed"
},
"MissingName": {
"Type": "Fail",
"Error": "MissingName",
"Cause": "The input has no name field"
}
}
}The Pass state ignores its input except to merge a fixed Result into it at $.status. The Wait state sleeps for two seconds and passes its input through unchanged. The Choice state tests whether $.name exists. Succeed returns the data it received as the execution output.
Creating and running it
Every state machine needs an execution role, even when no state calls another service. The role's trust policy must allow the principal states.amazonaws.com to assume it. This example has no permissions to grant, but the chapter on IAM covers what to add once Task states appear.
aws stepfunctions create-state-machine \
--name Greeting \
--definition file://greeting.asl.json \
--role-arn arn:aws:iam::123456789012:role/GreetingStateMachineRole \
--type STANDARD
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:Greeting \
--input '{"name": "Ada"}'start-execution is asynchronous. It returns an executionArn immediately, not the result. To read the outcome, call describe-execution with that ARN:
aws stepfunctions describe-execution \
--execution-arn arn:aws:states:us-east-1:123456789012:execution:Greeting:EXECUTION_IDFor the input above, the status becomes SUCCEEDED after about two seconds, and output is a JSON string: {"name":"Ada","status":{"stage":"received"}}. Start another execution with the input {} and it ends with status FAILED, error MissingName.
How an execution proceeds
An execution has a status, and it moves through states by following Next until it stops.
Points that matter in practice:
- An error that nothing handles fails the execution. If a state raises an error and has no matching
Catch, the execution ends asFAILED. A Fail state does the same on purpose. - Each execution has its own data. The JSON that flows from state to state is not shared between executions.
- Standard executions record history. Every state entry, exit, and transition is an event you can read later. Standard history is capped at 25,000 events per execution, which matters for long loops.
- Payload size is limited. Input, output, and the data passed between states are limited to 256 KiB.
- The definition is versioned by update. Running executions keep using the definition they started with. When you update the state machine, only new executions use the new definition.
Validation and common errors
Step Functions checks the definition when you create or update the state machine. It rejects the definition if it cannot parse the JSON or if the structure breaks the rules above. You can run the same check without deploying by calling validate-state-machine-definition:
aws stepfunctions validate-state-machine-definition \
--definition file://greeting.asl.jsonThe result contains result: OK or a list of diagnostics, each with a severity, a code, and a location. Run it in CI so these errors never reach deployment.
| Mistake | What happens |
|---|---|
| `StartAt` or a `Next` names a state that does not exist | The definition is rejected. Names are case-sensitive, so `checkName` does not match `CheckName`. |
| A non-terminal state has neither `Next` nor `End: true` | The definition is rejected. |
| A state has both `Next` and `End: true` | The definition is rejected. |
| A state cannot be reached from `StartAt` | The definition is rejected as invalid. Remove the state or add a transition to it. |
| `Next` on a Succeed or Fail state | The definition is rejected, because terminal states take no transition. |
| A Choice state with no `Default`, where no rule matches | The definition is accepted, but the execution fails at run time with `States.NoChoiceMatched`. |
| A path such as `$.name` that points at a missing field | The state fails at run time with `States.Runtime`. This is not caught at validation. |
| Duplicate keys in `States` | Most JSON parsers keep the last one silently, so one state disappears. A linter helps here. |
Run-time failures in the last rows are why you add Default branches and use IsPresent before reading optional fields.
Reading the definition as a graph
A useful habit is to draw the definition as a directed graph before you write JSON. Each state is a node. Each Next, each Choice rule, and each Default is an edge. Then check three things:
- Exactly one entry point exists, which is the state named by
StartAt. - Every path ends in a terminal state or an
End: truestate. - Every Choice state covers its failure case with a
Default.
The Workflow Studio in the Step Functions console builds this graph visually and generates the JSON. Use it to learn the structure. Once you know it, editing the JSON directly is faster and easier to review.
Exercise
A teammate's definition fails to deploy. It has "StartAt": "Validate", and the States object contains a Task state called ValidateOrder and a Choice state called Route. The Task state has "Next": "Route", and the Choice state has "Default": "Failed", but States has no state named Failed. List every problem that makes the definition invalid and say how to fix each one.
Show answer
There are two problems. First, StartAt is Validate, but no state has that name. Change it to ValidateOrder, or rename the state, because names are case-sensitive and must match exactly. Second, the Choice state's Default points to Failed, which does not exist. Add a state named Failed (for example {"Type": "Fail", "Error": "RouteFailed", "Cause": "No route matched"}) or point Default at an existing state. Running aws stepfunctions validate-state-machine-definition reports both errors before deployment.
Exercise
You start an execution of the Greeting state machine with the input {"name": "Ada"}, but the Wait state in Pause is changed to "Seconds": 120 and the top-level TimeoutSeconds stays at 60. What is the final status of the execution, and why?
Show answer
The status is TIMED_OUT. The top-level TimeoutSeconds limits the total execution time, and the Wait state sleeps longer than that limit. The execution ends once 60 seconds have passed, before it reaches CheckName.