Sub topic 14
Deploying and testing state machines
This chapter covers how to get a state machine definition into AWS repeatably, how to release changes without breaking running work, and how to test a workflow at three levels: a single state, the whole definition, and a live execution. It assumes the following:
- You can read the Amazon States Language (ASL) definitions from earlier chapters.
- You have written a Lambda function.
- You know what an IAM execution role is.
- You can use the AWS CLI.
Treat the definition as code
A state machine is a JSON document plus an execution role. You can create it in the console, but a console-built workflow is hard to review, copy to another account, or roll back. Keep the definition in a file in version control, deploy it with a tool, and let the tool create the role and the resources the workflow calls.
| Option | Good for | Notes |
|---|---|---|
| Console and Workflow Studio | Prototyping, learning ASL | Can export the definition as JSON or as an infrastructure-as-code snippet |
| AWS CLI (`create-state-machine`, `update-state-machine`) | Scripts, quick experiments | You create the role and manage drift yourself |
| AWS SAM | Lambda-heavy workflows | `AWS::Serverless::StateMachine` generates the role from policy templates |
| AWS CDK | Teams that prefer a programming language | Generates the role from grants such as `grantInvoke` |
| CloudFormation or Terraform | Existing infrastructure-as-code pipelines | The definition is a string or a file with substitutions |
Whichever tool you pick, avoid hardcoded ARNs in the definition. The Lambda ARN in the order-validation example, with its fixed account ID and Region, only works in one place. Use placeholders and let the deployment tool fill them in.
A SAM template with definition substitutions
SAM keeps the ASL in its own file and replaces ${...} placeholders at deploy time. The next template deploys the order workflow and grants its role permission to invoke only the one function it calls.
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
ValidateOrderFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: functions/validate_order/
OrderWorkflow:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: statemachine/order.asl.json
DefinitionSubstitutions:
ValidateOrderArn: !GetAtt ValidateOrderFunction.Arn
Policies:
- LambdaInvokePolicy:
FunctionName: !Ref ValidateOrderFunction
Outputs:
OrderWorkflowArn:
Value: !Ref OrderWorkflowIn order.asl.json, change the FunctionName parameter to "${ValidateOrderArn}". The :$LATEST suffix is no longer needed, because the function ARN without a qualifier already resolves to the latest code. Then run sam build and sam deploy --guided.
What happens to running executions when you update
Updating a state machine changes the definition for new executions only. An execution that is already running keeps using the definition it started with, even if it is paused for days on a .waitForTaskToken state. This keeps in-flight work safe, but it has a consequence: if you rename or remove a state that an old execution is still waiting in, that execution still completes against the old definition. Your new code, such as the worker that calls SendTaskSuccess, must stay compatible with both shapes of the input and the task token until the old executions drain.
A second effect concerns the execution role. The role is attached to the state machine, not to each execution, so permission changes take effect on the next state transition. Removing a permission can therefore break an execution that is already running.
Versions and aliases for safe releases
Every update-state-machine call overwrites the current definition. To keep release history and shift traffic gradually, use versions and aliases.
- A version is an immutable snapshot of a definition and its configuration, numbered 1, 2, 3, and so on.
- An alias is a name, such as
live, that points to one version or splits traffic between two versions by weight.
# Validate, then update the state machine and publish a version in one call
aws stepfunctions update-state-machine \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow \
--definition file://statemachine/order.asl.json \
--publish \
--version-description "Add retry on TooManyRequestsException"
# Create the alias, pointing all traffic at version 1
aws stepfunctions create-state-machine-alias \
--name live \
--routing-configuration '[{"stateMachineVersionArn":"arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow:1","weight":100}]'
# Canary: send 10 percent of new executions to version 2
aws stepfunctions update-state-machine-alias \
--state-machine-alias-arn arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow:live \
--routing-configuration '[{"stateMachineVersionArn":"arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow:1","weight":90},{"stateMachineVersionArn":"arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow:2","weight":10}]'Callers then start executions against the alias ARN (...:stateMachine:OrderWorkflow:live) instead of the bare state machine ARN. The weights in a routing configuration must add up to 100. To roll back, point the alias at the previous version, which takes effect immediately for new executions. SAM can automate this with AutoPublishAlias and a deployment preference on the state machine resource, so a failing CloudWatch alarm can reverse the shift.
Testing at three levels
No single technique covers a workflow. Each level catches different mistakes.
Level 1: validate the definition
Before deploying, check syntax and structure. validate-state-machine-definition reports unreachable states, missing Next targets, bad JSONPath, and similar problems without creating anything.
aws stepfunctions validate-state-machine-definition \
--definition file://statemachine/order.asl.json \
--type STANDARDThe response has a result of OK or FAIL, plus a diagnostics list with the location of each problem. Run it in CI on every commit. It does not execute your workflow, so it cannot tell you whether the data flow is right.
Level 2: test one state with TestState
The TestState API runs a single state from a definition fragment, with an input you supply, and returns the output and the next state. It is the quickest way to check the input and output processing from the data flow chapter, where InputPath, Parameters, ResultSelector, ResultPath, and OutputPath interact. It is also a quick way to check a Choice rule.
aws stepfunctions test-state \
--definition '{"Type":"Choice","Choices":[{"Variable":"$.result.validation.valid","BooleanEquals":true,"Next":"OrderAccepted"}],"Default":"OrderFailed"}' \
--input '{"result":{"validation":{"valid":true}}}' \
--inspection-level INFOThe response includes status (for example SUCCEEDED, FAILED, RETRIABLE, or CAUGHT_ERROR), output, and nextState. Here nextState should be OrderAccepted. Change valid to false and it should be OrderFailed.
Set --inspection-level DEBUG to see how each stage transformed the data: the input after InputPath, the effective Parameters, the result after ResultSelector, and the final output. This is the fastest way to find out why ResultPath put a value somewhere you didn't expect.
For a Task state that calls a service, TestState calls the real service, so you must pass --role-arn with a role that has the required permissions. Calls have real effects and costs. Pure-logic states such as Choice, Pass, Succeed, and Fail need no role.
Level 3: run the whole workflow
Run complete executions to test retries, catches, and the integration between states. You have two ways to do this.
Step Functions Local is a Docker image (amazon/aws-stepfunctions-local) that runs a state machine on your machine. It can call local or real endpoints, and it supports mocked service integrations. You describe mock responses and errors in a JSON config file, point the container at it with the SFN_MOCK_CONFIG environment variable, and start an execution with a test-case suffix on the state machine name, such as OrderWorkflow#HappyPath. Mocks let you force a Lambda.ServiceException on the first two attempts and success on the third, which is difficult to trigger against real Lambda.
A deployed test stack uses real services in a development account. It is slower and costs money, but it exercises the real IAM role, which local tests cannot. Missing permissions are one of the most common failures at this stage.
The next test starts an execution on a deployed Standard workflow, polls until it finishes, and checks the result. It assumes the OrderWorkflow from earlier and STATE_MACHINE_ARN set in the environment.
import json
import os
import time
import boto3
sfn = boto3.client("stepfunctions")
STATE_MACHINE_ARN = os.environ["STATE_MACHINE_ARN"]
def run_execution(payload: dict, timeout_s: int = 60) -> dict:
execution_arn = sfn.start_execution(
stateMachineArn=STATE_MACHINE_ARN,
input=json.dumps(payload),
)["executionArn"]
deadline = time.time() + timeout_s
while time.time() < deadline:
description = sfn.describe_execution(executionArn=execution_arn)
if description["status"] != "RUNNING":
return description
time.sleep(2)
raise TimeoutError(f"Execution did not finish: {execution_arn}")
def test_valid_order_succeeds():
result = run_execution({"orderId": "1001", "quantity": 2})
assert result["status"] == "SUCCEEDED"
def test_invalid_order_is_rejected():
result = run_execution({"orderId": "1002", "quantity": -5})
assert result["status"] == "FAILED"
assert result["error"] == "OrderRejected"Polling suits Standard workflows. For Express workflows, call start_sync_execution, which returns the status and output in the same response.
For each failed run, open the execution history to see which state failed and what input it received. The observability chapter covers this.
Common errors
- Testing only the happy path. A workflow's value is in its failure handling. Add a test where the Lambda raises an error that your
Catchhandles, and one where retries are exhausted. - Role permissions that appear only at runtime.
validate-state-machine-definitiondoes not check IAM. A missinglambda:InvokeFunctionshows up as anAccessDeniedException-style failure on the first real execution. - Changing the contract under paused executions. Adding a required field to a callback payload breaks executions that are already waiting on the old shape.
- Dropping the alias. Callers that start executions on the bare state machine ARN bypass the alias traffic split, so a canary release sends them nothing to test.
- Idempotency. Retries and redeployments can run a task more than once, so each Lambda should tolerate repeated invocation with the same input.
Exercise
You deployed version 2 of a state machine and want to send 10 percent of new executions to it while keeping 90 percent on version 1. Callers currently use the state machine ARN directly. What do you need to create or change, and what must the weights add up to?
Show answer
Create an alias such as live with a routing configuration that lists version 1 at weight 90 and version 2 at weight 10. The weights must add up to 100. Change callers to start executions against the alias ARN, because starting on the bare state machine ARN bypasses the traffic split. To roll back, update the alias so version 1 has weight 100.
Exercise
A Task state uses ResultSelector and ResultPath, and the downstream Choice state never matches. Which API call lets you check what each processing stage produced without running the full workflow, and which setting shows the intermediate data?
Show answer
Call TestState (aws stepfunctions test-state) with the state's definition and a sample input, and set the inspection level to DEBUG. The response shows the data after each stage, so you can see where the value ended up and fix the Choice state's Variable path. A Task state that calls a service also needs a role ARN, because the call is real.