Sub topic 12
Debugging with execution history, logs, and X-Ray
This chapter assumes you can write and start a state machine with Task, Choice, Retry, and Catch states, and that you know how to read an IAM policy. You'll learn the four places Step Functions records what happened and which one to open first for each kind of problem.
The working model: four sources of evidence
A running execution leaves traces in four places. Each answers a different question.
| Source | Question it answers | Workflow type | Retention |
|---|---|---|---|
| Execution history | Which states ran, in what order, with what input and output? | Standard only | 90 days after the execution closes |
| CloudWatch Logs | The same events, searchable across many executions | Standard and Express | Set by the log group |
| X-Ray traces | Where did the time go, and which downstream call failed? | Standard and Express | 30 days |
| CloudWatch metrics | How many executions fail, time out, or get throttled? | Standard and Express | Per CloudWatch metric retention |
Standard workflows record history for you. Express workflows do not keep history you can query through the API, so logging is the only way to see what an Express execution did. Turn it on before you need it.
Reading execution history
Every state transition is stored as an event with an ID, a timestamp, a type, and a previousEventId that links it to the event that caused it. A Task state that invokes Lambda typically produces this sequence:
TaskStateEnteredrecords the state's effective input.LambdaFunctionScheduledandLambdaFunctionStartedrecord the invocation.LambdaFunctionSucceededorLambdaFunctionFailedrecords the outcome.TaskStateExitedrecords the state's output afterResultSelector,ResultPath, andOutputPathare applied.
The pairing of TaskStateEntered and TaskStateExited is what makes data-flow bugs visible. If the Lambda output looks right in LambdaFunctionSucceeded but wrong in TaskStateExited, the mistake is in your ResultSelector, ResultPath, or OutputPath, not in the function.
Event names depend on the integration. Lambda has dedicated types such as LambdaFunctionFailed. Other integrations use the generic TaskScheduled, TaskStarted, TaskSucceeded, TaskFailed, and TaskTimedOut. Match on the prefix when you filter.
The console views
The Executions page gives you three views of the same data:
- Graph view colors each state by outcome. Click a state to see its input, output, and error. Start here for a first look.
- Table view lists states with their status and duration, which helps you spot a slow state.
- Event view shows the raw event list. Use it when you need
previousEventIdlinks or events inside Map and Parallel branches.
Reading history from code
The console is fine for one execution. For many, use the API. This script prints every failure event for an execution, with its error and cause.
import json
import sys
import boto3
sfn = boto3.client("stepfunctions")
def failure_events(execution_arn: str):
paginator = sfn.get_paginator("get_execution_history")
for page in paginator.paginate(
executionArn=execution_arn, includeExecutionData=True
):
for event in page["events"]:
etype = event["type"]
if "Failed" in etype or "TimedOut" in etype or "Aborted" in etype:
yield event
if __name__ == "__main__":
for ev in failure_events(sys.argv[1]):
# The details key is the event type with a lowercase first letter,
# for example lambdaFunctionFailedEventDetails.
key = next((k for k in ev if k.endswith("EventDetails")), None)
details = ev.get(key, {}) if key else {}
print(
ev["id"],
ev["type"],
json.dumps({"error": details.get("error"), "cause": details.get("cause")}),
)You can get the same data from the CLI:
aws stepfunctions describe-execution \
--execution-arn arn:aws:states:us-east-1:123456789012:execution:OrderWorkflow:run-1
aws stepfunctions get-execution-history \
--execution-arn arn:aws:states:us-east-1:123456789012:execution:OrderWorkflow:run-1 \
--reverse-order --max-results 10describe-execution returns the status, input, output, and for failed runs the top-level error and cause. --reverse-order puts the most recent events first, which is usually where the failure is.
Limits that affect debugging
- A Standard execution can hold at most 25,000 history events. A large Map state that iterates inline consumes events quickly and can hit this limit. The execution then fails with
States.Runtime, and the history ends abruptly. Distributed Map, covered in a later chapter, avoids this by running iterations as child executions. - History is deleted 90 days after the execution closes. Export what you need to CloudWatch Logs if you must keep it longer.
- Inputs and outputs larger than 256 KiB cannot pass between states. Failures from oversized payloads appear as
States.DataLimitExceeded.
Logging to CloudWatch Logs
You configure logging on the state machine. It needs a log group, a level, and a choice about whether to include execution data.
| Level | What is logged |
|---|---|
| `OFF` | Nothing. This is the default. |
| `ALL` | Every event |
| `ERROR` | Failed, timed-out, and aborted executions, plus failed state events |
| `FATAL` | Only execution-level failure, timeout, and abort events |
includeExecutionData controls whether input and output payloads appear in log entries. Turning it on makes debugging much easier. It also copies customer data into logs, so check your data-handling rules first. When it is off, the log entries still show state names, types, and errors.
aws logs create-log-group --log-group-name /aws/vendedlogs/states/OrderWorkflow
aws stepfunctions update-state-machine \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow \
--logging-configuration '{
"level": "ALL",
"includeExecutionData": true,
"destinations": [{
"cloudWatchLogsLogGroup": {
"logGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/vendedlogs/states/OrderWorkflow:*"
}
}]
}'The log group name starts with /aws/vendedlogs/ on purpose. Log delivery from AWS services can add a resource policy to the log group, and the size of that policy is limited. Names under /aws/vendedlogs/ avoid that limit, which matters if you create many state machines.
The execution role needs permission to deliver logs. These actions do not support resource-level restriction, so they use "Resource": "*":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogDelivery",
"logs:GetLogDelivery",
"logs:UpdateLogDelivery",
"logs:DeleteLogDelivery",
"logs:ListLogDeliveries",
"logs:PutResourcePolicy",
"logs:DescribeResourcePolicies",
"logs:DescribeLogGroups"
],
"Resource": "*"
}
]
}Each log entry is a JSON object with fields such as execution_arn, type, id, previous_event_id, event_timestamp, and a details object. That structure lets you query it with Logs Insights. This query lists recent failures across all executions of the state machine:
fields @timestamp, execution_arn, type, details.error, details.cause
| filter type in ["ExecutionFailed", "TaskFailed", "LambdaFunctionFailed", "ExecutionTimedOut"]
| sort @timestamp desc
| limit 50To follow one execution from start to finish, filter on execution_arn and sort ascending.
Tracing with X-Ray
Execution history tells you what happened. X-Ray tells you how long each piece took and how the services connect. Enable tracing on the state machine:
aws stepfunctions update-state-machine \
--state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow \
--tracing-configuration enabled=trueThe execution role needs xray:PutTraceSegments, xray:PutTelemetryRecords, xray:GetSamplingRules, and xray:GetSamplingTargets. Like the log delivery actions, these are granted on "*".
With tracing on, X-Ray shows a service map with Step Functions at the center and a timeline with one segment per state. Two details trip people up:
- Step Functions passes the trace header to services it calls. Lambda functions only produce their own segments if you also enable active tracing on the function. Without it, you see the Lambda call as one opaque block.
- If a caller already started a trace, such as an API Gateway request with tracing on, Step Functions joins that trace instead of starting a new one. Then you can see one request end to end.
A debugging routine
When an execution fails, work from the outside in:
- Run
describe-executionor open the Graph view. Note the status and which state is red. - Open that state's
TaskStateEnteredevent. Check that the input is what you expected. - Read the failure event for
errorandcause. Compare the error name to yourRetryandCatchErrorEqualslists. A common cause of an unexpected failure is an error name that no clause matches.States.TaskFailedandStates.ALLdo not cover every case in the way people assume, andStates.ALLcannot be used withStates.DataLimitExceededorStates.Runtimein aRetry/Catchas a way to hide them. - If the task succeeded but the next state broke, compare the
TaskStateExitedoutput to what the next state'sInputPathorChoicevariable expects. - If the problem is latency, open the X-Ray trace and look for the longest segment.
- If the problem recurs across executions, run the Logs Insights query and group by error.
Common errors
- No history for an Express execution. Express workflows do not expose history through the API. Enable logging at creation time.
- Logging is on but no entries appear. Check the execution role's log delivery permissions and that the log group ARN ends with
:*. States.RuntimeorStates.Timeoutwith no obvious cause. Runtime errors come from the state machine itself, for example a bad JSONPath that matches nothing. Look at theTaskStateEnteredevent for the state before the failure.- Status
SUCCEEDEDbut the business result is wrong. ACatchwithResultPathset to$replaces the whole state input with the error object. The execution then continues on the wrong data. Look atTaskStateExitedfor the catching state. - Throttling you cannot see in history. Throttled starts never become executions. Check the
ExecutionThrottledmetric in CloudWatch instead.
Exercise
A Standard execution of OrderWorkflow ended as SUCCEEDED, but the order record was never updated. The ValidateOrder Task has a Catch with "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", and "Next": "OrderFailed". Which events do you compare to decide whether the problem is in the Lambda function or in your data-flow settings, and why is logging not required to do this?
Show answer
Compare the LambdaFunctionSucceeded event, which holds the function's raw output, with the TaskStateExited event for ValidateOrder, which holds the state's output after ResultSelector, ResultPath, and OutputPath. If the raw output is correct but the exited output is wrong, the data-flow settings are at fault. If the raw output is already wrong, the function is at ftault. Logging is not required because Standard workflows keep execution history automatically for 90 days, and GetExecutionHistory or the console Event view returns these events with includeExecutionData.
Exercise
You must debug failures in a high-volume Express workflow, and you want to avoid logging every payload. Which logging level and setting do you choose, and which Logs Insights field do you filter on to find failed executions?
Show answer
Set the level to ERROR (or FATAL if only execution-level failures matter) and set includeExecutionData to false. Then filter on the type field, for example type = "ExecutionFailed", and use execution_arn to group or follow a single execution. Raise the level to ALL with includeExecutionData on only temporarily, if you need payloads for one investigation.