How to Retry Steps in AWS Step Functions with AWS Emulator
Adding Retry to a Step Functions state lets you call a Lambda function again when it returns an error, up to a set number of times, with the wait between attempts growing each time. This is the usual way to handle transient errors, such as an external API that occasionally times out, without stopping the whole workflow. Without an AWS account, on AWS Emulator, I tested a flow that fails twice and succeeds on the third attempt, how the execution stops when the retries run out, how the waits grow, and how Retry combines with Catch. The commands and output are shown as they ran.
The test environment was Ubuntu 24.04.5 (x86_64), AWS Emulator 1.0.556 (released November 21, 2026, Debian package), AWS CLI 2.42.1, and the Lambda runtime was python3.12. I did not use an AWS account or credentials. I did not verify how real AWS Step Functions behaves, how accurate the waits are, or the pricing. Where I mention those, the source is the official documentation. I did not test Express workflows, definitions written in JSONata, retries on timeouts set with TimeoutSeconds, Retry on Parallel and Map states, redriving executions, or retries of errors raised by the Lambda service itself (such as Lambda.ServiceException).
- 1. Start the emulator and prepare a function that fails on purpose
- 2. Create a state machine with Retry
- 3. If it fails twice and succeeds on the third try, the execution succeeds
- 4. When the retries run out, the execution fails with the last error
- 5. Decide whether to retry by error name
- 6. Change the growth of waits with MaxDelaySeconds and JitterStrategy
- 7. If retries still fail, use Catch to move to another state
- 8. On AWS Emulator, I could not pass the retry count to the function
- 9. When calling Lambda on real AWS, also retry Lambda-side errors
Start the emulator and prepare a function that fails on purpose
The way to install AWS Emulator, the environment variables that point the AWS CLI at the emulator, and how to create the role are the same as in the blog article "How to Call Functions in Sequence with Step Functions on AWS Emulator". I installed it by following the Linux installation steps in the official guide, including checking the package signature, and started it with -t off to stop it from sending usage data (telemetry).
aws-emulator -t off
In a separate terminal, I set the environment variables that point the SDK at the emulator, as described in the guide to pointing the SDK at the emulator (such as AWS_ENDPOINT_URL=https://127.0.0.1:9297), and then used the AWS CLI.
To test retries, I needed a function that fails a fixed number of times. The following function example-flaky counts how many times it has been called for each state machine execution, using a file in /tmp, and raises TemporaryError until the count reaches fail_times. If the input contains "invalid": true, it always raises ValueError.
import os
class TemporaryError(Exception):
pass
def lambda_handler(event, context):
# Count calls per execution ARN in a file under /tmp (for testing only)
path = f"/tmp/count-{event['execution']}"
n = int(open(path).read()) + 1 if os.path.exists(path) else 1
with open(path, "w") as f:
f.write(str(n))
if event["input"].get("invalid"):
raise ValueError(f"invalid input (call {n})")
if n <= event["input"]["fail_times"]:
raise TemporaryError(f"failed on call {n}")
return {"ok": True, "calls": n}
Counting in /tmp is only a testing method. In the emulator, the files in /tmp stayed between calls. When I called the same function directly twice, the first call raised TemporaryError and the second returned {"ok": true, "calls": 2}. The official documentation says that the runtime environment is not always reused on real Lambda, so this method cannot be used to count calls in production code.
I created the function with python3.12. I also attached a policy to the execution role example-sfn-role that allows lambda:InvokeFunction on this function.
Create a state machine with Retry
I added Retry to a Task state. The value is an array of objects called retriers. The first retrier says: when TemporaryError occurs, wait 1 second at first, double the wait each time, and call again up to 3 times.
{
"StartAt": "CallFlaky",
"States": {
"CallFlaky": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "example-flaky",
"Payload": { "input.$": "$", "execution.$": "$$.Execution.Id" }
},
"OutputPath": "$.Payload",
"Retry": [
{ "ErrorEquals": ["TemporaryError"], "IntervalSeconds": 1, "MaxAttempts": 3, "BackoffRate": 2 }
],
"End": true
}
}
}
The meanings of the retrier fields, from the error handling documentation, are as follows.
ErrorEquals: the names of the errors to retry (required).IntervalSeconds: the number of seconds to wait before the first retry. If omitted, it is 1.MaxAttempts: the maximum number of retries. If omitted, it is 3. Setting it to 0 means no retries.BackoffRate: the multiplier applied to the wait each time a retry happens. If omitted, it is 2.0.
In the test environment, the class name of the Python exception raised by the Lambda function (TemporaryError) was used as the error name as is.
The "execution.$": "$$.Execution.Id" in Payload takes the execution ARN from the context object and passes it to the function. The function uses it as the name of the file that counts calls.
I created this state machine with the name example-retry. validate-state-machine-definition returned OK.
If it fails twice and succeeds on the third try, the execution succeeds
I ran the execution with fail_times set to 2. wait-exec.sh is a small script I wrote that calls describe-execution repeatedly until the execution's status is no longer RUNNING.
$ aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:<12桁のアカウントID>:stateMachine:example-retry --name run-fail2 --input '{"fail_times":2}' --query executionArn --output text
arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail2
$ bash wait-exec.sh arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail2
waited 3.64s
$ aws stepfunctions describe-execution --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail2 --query '{status:status,output:output,error:error,cause:cause}'
{
"status": "SUCCEEDED",
"output": "{\"ok\":true,\"calls\":3}",
"error": null,
"cause": null
}
In the commands and output, <12桁のアカウントID> replaces the account ID returned by the emulator. When you try this yourself, use the value returned by aws sts get-caller-identity --query Account --output text.
The "calls":3 in the output shows that the function was called three times and succeeded on the third call. In the execution history, TaskScheduled through TaskFailed appeared twice, and the third attempt was TaskSucceeded.
$ aws stepfunctions get-execution-history --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail2 --query 'events[].[id,type]' --output text
1 ExecutionStarted
2 TaskStateEntered
3 TaskScheduled
4 TaskStarted
5 TaskFailed
6 TaskScheduled
7 TaskStarted
8 TaskFailed
9 TaskScheduled
10 TaskStarted
11 TaskSucceeded
12 TaskStateExited
13 ExecutionSucceeded
TaskStateEntered appeared only once. The state was not entered again; the function was called again within the same state. In the taskFailedEventDetails of each failed attempt, error was TemporaryError, and cause contained the JSON error returned by the function (such as "errorMessage":"failed on call 1").
To measure how long the function waited before each retry, I wrote a Python script, waits.py. It reads the history JSON and prints the result of each call, along with the number of seconds from a failure to the next call.
# Read the JSON from get-execution-history, and print the result of each function call along with the seconds from a failure to the next call
import json, sys
from datetime import datetime
events = json.load(sys.stdin)["events"]
t = lambda e: datetime.fromisoformat(e["timestamp"])
call, failed_at = 0, None
for e in events:
if e["type"] == "TaskScheduled":
call += 1
wait = f" (失敗から {(t(e) - failed_at).total_seconds():.1f} 秒後)" if failed_at else ""
print(f"call {call}: scheduled {e['timestamp'][11:23]}{wait}")
elif e["type"] == "TaskFailed":
failed_at = t(e)
print(f"call {call}: TaskFailed {e['taskFailedEventDetails']['error']}")
elif e["type"] == "TaskSucceeded":
print(f"call {call}: TaskSucceeded")
$ aws stepfunctions get-execution-history --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail2 | python3 waits.py
call 1: scheduled 18:01:09.199
call 1: TaskFailed TemporaryError
call 2: scheduled 18:01:10.199 (失敗から 1.0 秒後)
call 2: TaskFailed TemporaryError
call 3: scheduled 18:01:12.199 (失敗から 2.0 秒後)
call 3: TaskSucceeded
The function waited 1 second after the first failure and 2 seconds after the second before calling again. This matches an IntervalSeconds of 1, growing by a BackoffRate of 2 each time. The total execution time measured by wait-exec.sh (3.64 seconds) also shows that the emulator actually waited these amounts.
When the retries run out, the execution fails with the last error
I set fail_times to 9 so the function kept failing. Since MaxAttempts is 3, the function was called four times: the first call plus three retries.
$ aws stepfunctions describe-execution --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail9 --query '{status:status,output:output,error:error,cause:cause}'
{
"status": "FAILED",
"output": null,
"error": "TemporaryError",
"cause": "{\"errorMessage\":\"failed on call 4\",\"errorType\":\"TemporaryError\",\"requestId\":\"2d9e1fc4-8209-4919-a8b6-990b3f646043\",\"stackTrace\":[\" File \\\"/var/task/lambda_function.py\\\", line 15, in lambda_handler\\n raise TemporaryError(f\\\"failed on call {n}\\\")\\n\"]}"
}
$ aws stepfunctions get-execution-history --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-retry:run-fail9 | python3 waits.py
call 1: scheduled 18:01:15.796
call 1: TaskFailed TemporaryError
call 2: scheduled 18:01:16.796 (失敗から 1.0 秒後)
call 2: TaskFailed TemporaryError
call 3: scheduled 18:01:18.796 (失敗から 2.0 秒後)
call 3: TaskFailed TemporaryError
call 4: scheduled 18:01:22.796 (失敗から 4.0 秒後)
call 4: TaskFailed TemporaryError
The waits grew to 1, 2, and 4 seconds. After the fourth failure, the execution ended with FAILED. cause contained the error from the last (fourth) call. In the history, TaskFailed appeared four times in a row, and the execution ended with ExecutionFailed.
Decide whether to retry by error name
An error that is not listed in ErrorEquals is not retried. When I passed "invalid": true to the same example-retry, the function raised ValueError, was called once, and the execution became FAILED. In the history, ExecutionFailed came right after TaskFailed.
You can also choose to retry every error except the ones that repeating the call will not fix, such as bad input. I followed the official Retry example: I placed a retrier with MaxAttempts set to 0 first, and a States.ALL retrier last.
"Retry": [
{ "ErrorEquals": ["ValueError"], "MaxAttempts": 0 },
{ "ErrorEquals": ["States.ALL"], "IntervalSeconds": 1, "MaxAttempts": 2, "BackoffRate": 2 }
]
Step Functions checks the retriers in array order and uses the first one whose ErrorEquals matches the error name (see the retry description). In this state machine, example-only-temp, an execution with "invalid": true was called once with ValueError and became FAILED. An execution with "fail_times": 1 retried after 1 second on TemporaryError, and succeeded on the second call with SUCCEEDED.
States.ALL is a special name that matches any error name. It must appear alone in ErrorEquals, not together with other error names, and it must be in the last retrier. When I ran validate-state-machine-definition on a definition with the two retriers in the reverse order, the emulator reported an error.
$ aws stepfunctions validate-state-machine-definition --definition file://sm-bad-order.json
{
"result": "FAIL",
"diagnostics": [
{
"severity": "ERROR",
"code": "SCHEMA_VALIDATION_FAILED",
"message": "States.ALL must appear alone and at end of list",
"location": "/States/CallFlaky/Retry[0]/ErrorEquals[0]"
}
],
"truncated": false
}
create-state-machine also refused to create it, with an InvalidDefinition error that had the same content.
Change the growth of waits with MaxDelaySeconds and JitterStrategy
When BackoffRate makes the waits grow, the waits get longer as the number of retries increases. If you set MaxDelaySeconds, the wait does not exceed that number of seconds. If you set JitterStrategy to FULL, the wait becomes a random value between 0 and the wait time that would otherwise apply (see the retrier field descriptions). This setting prevents many executions from retrying at the same moment.
I tested MaxDelaySeconds with IntervalSeconds 1, BackoffRate 3, MaxAttempts 4, and MaxDelaySeconds 4. Without the cap, the waits would grow to 1, 3, 9, and 27 seconds.
"Retry": [
{ "ErrorEquals": ["TemporaryError"], "IntervalSeconds": 1, "MaxAttempts": 4, "BackoffRate": 3, "MaxDelaySeconds": 4 }
]
$ aws stepfunctions get-execution-history --execution-arn arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-maxdelay:run-fail9 | python3 waits.py
call 1: scheduled 18:01:38.473
call 1: TaskFailed TemporaryError
call 2: scheduled 18:01:39.473 (失敗から 1.0 秒後)
call 2: TaskFailed TemporaryError
call 3: scheduled 18:01:42.473 (失敗から 3.0 秒後)
call 3: TaskFailed TemporaryError
call 4: scheduled 18:01:46.473 (失敗から 4.0 秒後)
call 4: TaskFailed TemporaryError
call 5: scheduled 18:01:50.473 (失敗から 4.0 秒後)
call 5: TaskFailed TemporaryError
The third retry (call 4) waited 4 seconds instead of 9. The fourth retry, which would have waited 27 seconds without the cap, also waited 4 seconds.
For JitterStrategy, I set IntervalSeconds to 2, BackoffRate to 2, MaxAttempts to 3, and added "JitterStrategy": "FULL". I ran the same definition three times. Without jitter, the waits would be 2, 4, and 8 seconds. The waits were different in each run: the first execution waited 1.2, 1.6, and 1.4 seconds; the second waited 0.8, 3.2, and 6.4 seconds; and the third waited 0.2, 3.4, and 5.6 seconds. In every case, the wait stayed below the no-jitter value (2 seconds for the first retry, 4 seconds for the second, and 8 seconds for the third).

If retries still fail, use Catch to move to another state
When you write both Retry and Catch, the retries run first, and Catch is used only if the error is still not resolved (see the Catch description). I set up two retries and wrote a Catch that moves to a Pass state named GiveUp.
The CallFlaky state is the same as in example-retry from Type through OutputPath, so I omit those lines below.
"CallFlaky": {
"Retry": [
{ "ErrorEquals": ["TemporaryError"], "IntervalSeconds": 1, "MaxAttempts": 2, "BackoffRate": 2 }
],
"Catch": [
{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "GiveUp" }
],
"End": true
},
"GiveUp": {
"Type": "Pass",
"Parameters": { "gave_up": true, "error.$": "$.error.Error", "cause.$": "$.error.Cause" },
"End": true
}
When I ran it with fail_times set to 9, the function was called three times with waits of 1 and 2 seconds, then moved to GiveUp, and the execution ended with SUCCEEDED. The cause in the output contains the error from the third call (I omitted part of it because it is long).
{
"status": "SUCCEEDED",
"output": "{\"gave_up\":true,\"error\":\"TemporaryError\",\"cause\":\"{\\\"errorMessage\\\":\\\"failed on call 3\\\",(中略)}\"}",
"error": null,
"cause": null
}
In the history, TaskFailed appeared three times in a row, followed by TaskStateExited, PassStateEntered, PassStateExited, and ExecutionSucceeded, in that order. When I set fail_times to 1, the first retry (the second call) succeeded, and the execution did not move to Catch.
Retry transient errors with Retry, and set the waits with IntervalSeconds and BackoffRate. For errors that will not go away, exclude them from retries with a retrier whose MaxAttempts is 0. Write where execution goes after the retries are used up in Catch.
On AWS Emulator, I could not pass the retry count to the function
The context object documentation says that under State there is a RetryCount that shows which retry this is. So I also tested a definition that passes "retry_count.$": "$$.State.RetryCount" to the function. On the emulator, the execution failed with States.Runtime before the function was called (I omitted part of the long output).
{
"status": "FAILED",
"output": null,
"error": "States.Runtime",
"cause": "An error occurred while executing the state 'CallFlaky' (entered at the event id #2). The JSONPath '$$.State.RetryCount' specified for the field 'retry_count.$' could not be found in the input '{(中略)\"State\":{\"Name\":\"CallFlaky\",\"EnteredTime\":\"2026-11-21T18:02:36.642Z\"}}'"
}
In the context object shown in the error, State contained only Name and EnteredTime. This is why I counted the calls in /tmp in the function in this article. States.Runtime is an error that Retry or Catch cannot catch, even with States.ALL (see the list of error names).
When calling Lambda on real AWS, also retry Lambda-side errors
Everything so far has retried exceptions raised by the function's own code. The Step Functions best practices note that transient errors can happen on the Lambda service side, and give the following example of retrying Lambda.ServiceException and similar errors.
"Retry": [ {
"ErrorEquals": [ "Lambda.ClientExecutionTimeoutException", "Lambda.ServiceException", "Lambda.AWSLambdaException", "Lambda.SdkClientException"],
"IntervalSeconds": 2,
"MaxAttempts": 6,
"BackoffRate": 2
} ]
Also, the official retry description says that each retry is counted as a state transition and affects billing.
Finally, I deleted the six state machines I created with delete-state-machine, deleted the function with delete-function, and stopped the emulator by sending it SIGTERM. The exit code was 0.





