Sub topic 8
Handling failures with Retry and Catch
This chapter assumes you can read and write basic Amazon States Language (ASL), including Task and Choice states. It also assumes you know how ResultPath places a result into the state input, and that you have deployed a Lambda function. Retry and Catch are the two fields that turn a fragile chain of calls into a workflow that survives transient faults and handles permanent ones on purpose.
Two kinds of failure, two tools
Failures fall into two groups:
- Transient failures go away if you try again. Examples are a Lambda throttle, a network blip, or a service returning a 5xx error.
Retryhandles these. - Permanent failures repeat on every attempt. Examples are a declined card, a malformed input, or a missing permission.
Catchhandles these by sending the execution to a recovery state.
Both fields are arrays on a state. They are supported on Task, Parallel, and Map states. Pass, Choice, Wait, Succeed, and Fail states cannot have them. A Fail state is itself how you end an execution in failure on purpose.
What an error is
Every failure has a name (the Error field) and a human-readable Cause. The names come from three places:
- Your code. For a Lambda function, the name is the exception type, such as
OutOfStockfor a Python classOutOfStock(Exception). - The service integration. The Lambda integration reports
Lambda.ServiceException,Lambda.TooManyRequestsException, and similar names. - Step Functions itself. These begin with
States..
The most useful predefined names are below.
| Name | Meaning |
|---|---|
| `States.ALL` | Matches any error name. Must appear alone in its `ErrorEquals` array. |
| `States.TaskFailed` | Matches any task failure except `States.Timeout`. |
| `States.Timeout` | The task exceeded `TimeoutSeconds` or missed a heartbeat. `States.HeartbeatTimeout` is the heartbeat-specific name. |
| `States.Permissions` | The execution role lacks a permission the task needs. |
| `States.BranchFailed` | A branch of a `Parallel` state failed. |
| `States.ResultPathMatchFailure` | `ResultPath` could not be applied to the input. |
| `States.DataLimitExceeded` | A payload exceeded the 256 KiB limit. It cannot be retried. |
| `States.Runtime` | An internal runtime failure. It cannot be retried or caught. |
States.ALL does not match States.DataLimitExceeded or States.Runtime for the purpose of retrying, so do not rely on it as a guarantee that nothing escapes.
Retry in detail
Each entry in a Retry array is called a retrier. It has these fields:
| Field | Default | Meaning |
|---|---|---|
| `ErrorEquals` | required | Error names this retrier applies to. |
| `IntervalSeconds` | 1 | Wait before the first retry. |
| `MaxAttempts` | 3 | Number of retries. `0` means never retry. |
| `BackoffRate` | 2.0 | Multiplier applied to the wait after each retry. |
| `MaxDelaySeconds` | none | Upper cap on any single wait. |
| `JitterStrategy` | `NONE` | Set `FULL` to randomize each wait between 0 and the computed delay. |
With IntervalSeconds: 2, BackoffRate: 2.0, and MaxDelaySeconds: 30, the waits before retries 1 through 5 are 2, 4, 8, 16, and 30 seconds. The fifth wait would be 32 seconds, and the cap reduces it to 30.
Use JitterStrategy: FULL when many executions can fail at the same moment, for example when a downstream API throttles you. Without jitter, every execution retries at the same instants and recreates the spike.
The rules that cause most surprises:
- Retriers are checked in order, and the first one whose
ErrorEqualsmatches wins. Put specific errors before general ones. AStates.ALLretrier placed first swallows everything after it. - Each retrier keeps its own attempt counter. An error matching retrier 1 does not consume retrier 2's attempts.
- Counters reset when the state is entered again, for example in a loop. They do not persist for the whole execution.
- A retrier with
MaxAttempts: 0is a deliberate "do not retry this" rule. It stops a later, broader retrier from retrying an error you know is permanent. - Retries re-run the whole state, so the task must be idempotent. If a payment call succeeded but its response was lost, the retry charges the customer twice unless you pass an idempotency key.
Catch in detail
Once a state runs out of retries, or has no matching retrier, Step Functions checks Catch. Each catcher has three fields: ErrorEquals, Next, and an optional ResultPath.
The default ResultPath for a catcher is $. That replaces the whole state input with the error object {"Error": "...", "Cause": "..."}, and the original input is lost. Almost always you want "ResultPath": "$.error" so the recovery state still sees the order data and also sees what went wrong.
Catchers are checked in order, like retriers. If no catcher matches, the execution fails with that error.
A complete example
This state machine charges a card. A declined card is permanent, so it is not retried and goes to a notification state. Transient Lambda errors are retried with capped, jittered backoff. A timeout gets two slower retries. Anything else releases the reserved inventory.
{
"Comment": "Charge a card with targeted retries and catches",
"StartAt": "ChargeCard",
"States": {
"ChargeCard": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:ChargeCard:$LATEST",
"Payload.$": "$"
},
"ResultSelector": {
"charge.$": "$.Payload"
},
"ResultPath": "$.result",
"TimeoutSeconds": 30,
"Retry": [
{
"ErrorEquals": ["CardDeclined"],
"MaxAttempts": 0
},
{
"ErrorEquals": [
"Lambda.ServiceException",
"Lambda.AWSLambdaException",
"Lambda.SdkClientException",
"Lambda.TooManyRequestsException"
],
"IntervalSeconds": 2,
"MaxAttempts": 5,
"BackoffRate": 2.0,
"MaxDelaySeconds": 30,
"JitterStrategy": "FULL"
},
{
"ErrorEquals": ["States.Timeout"],
"IntervalSeconds": 5,
"MaxAttempts": 2,
"BackoffRate": 2.0
}
],
"Catch": [
{
"ErrorEquals": ["CardDeclined"],
"ResultPath": "$.error",
"Next": "NotifyDeclined"
},
{
"ErrorEquals": ["States.ALL"],
"ResultPath": "$.error",
"Next": "ReleaseInventory"
}
],
"End": true
},
"NotifyDeclined": {
"Type": "Fail",
"Error": "CardDeclined",
"Cause": "The customer's card was declined"
},
"ReleaseInventory": {
"Type": "Fail",
"Error": "ChargeFailed",
"Cause": "Charge failed after retries; inventory should be released"
}
}
}In a real workflow, NotifyDeclined and ReleaseInventory would be Task states that do the cleanup. They are Fail states here so the definition runs without extra resources.
The Lambda function raises the permanent error by throwing an exception whose class name matches the ErrorEquals entry:
class CardDeclined(Exception):
pass
def handler(event, context):
if event.get("cardStatus") == "declined":
raise CardDeclined("Issuer rejected the card")
return {"charged": True, "orderId": event["orderId"]}Python reports the class name as the error name, so CardDeclined in ErrorEquals matches. Error names are case-sensitive and must match exactly. A typo means the retrier never fires, and the failure falls through to States.ALL with no warning.
Timeouts and heartbeats
Without TimeoutSeconds, a task has a default timeout of 99,999,999 seconds, so a hung task can hold an execution open until the workflow's own limit. Set TimeoutSeconds on every Task. For long-running or callback tasks, also set HeartbeatSeconds. If the worker does not call SendTaskHeartbeat within that interval, the state fails with States.HeartbeatTimeout. This detects a dead worker much sooner than waiting for the full timeout.
A timeout counts as a failure like any other, so it can be retried and caught. Think about whether retrying is safe. Timing out does not prove the underlying work stopped.
Common mistakes
- Catching without preserving input. Leaving
ResultPathat its default makes the recovery state lose the original data. - Broad retrier first. Because the first match wins,
States.ALLat the top ofRetrymakes later entries unreachable. This includes yourMaxAttempts: 0rule. - Retrying non-idempotent work. Retries are safe only if repeating the task has no extra effect. Use idempotency keys or conditional writes.
- Retrying a permanent error. A validation error retried five times only delays the failure and adds cost.
- Ignoring the whole-state scope. In a
ParallelorMapstate, a retry re-runs the entire state, including branches that already succeeded. PutRetryon the inner Task states when you want finer control. - Expecting exactly-once behavior in Express workflows. Asynchronous Express executions run at least once, so the idempotency rule applies even when you configure no retries.
Exercise
A Task state has this Retry array: first entry ErrorEquals: ["States.ALL"] with MaxAttempts: 3, second entry ErrorEquals: ["ValidationError"] with MaxAttempts: 0. A ValidationError is raised. What happens, and how do you fix the definition?
Show answer
The first retrier matches, because States.ALL matches every error and retriers are checked in order. The task is retried three times even though the second entry was meant to stop retries. The fix is to put the specific ValidationError retrier with MaxAttempts: 0 first and the States.ALL retrier last.
Exercise
A Catch block on a state has ErrorEquals: ["States.ALL"] and Next: "Cleanup" but no ResultPath. Cleanup needs the original orderId. Why does it fail, and what single change fixes it?
Show answer
The default ResultPath for a catcher is $, so the error object {"Error": ..., "Cause": ...} replaces the whole input and orderId is gone. Adding "ResultPath": "$.error" stores the error under $.error and keeps the original input, so $.orderId is still available in Cleanup.
Exercise
With IntervalSeconds: 3, BackoffRate: 2.0, MaxAttempts: 5, and MaxDelaySeconds: 20, list the wait before each retry.
Show answer
3, 6, 12, 20, 20 seconds. The doubling sequence is 3, 6, 12, 24, 48, and every value above 20 is capped at 20.