Skip to content

AWS Step Functions stepfunctions

See which step of a workflow failed, and read the Lambda run that broke it

Find the state machines that fail, see where and why their executions stop, and follow one execution step by step down to the log lines of the Lambda run behind the failure, without clicking through the console.

  • One install, nothing to set up
  • Read-only: never starts or redrives an execution
  • The Lambda run's own lines, by request ID
  • Plain text outside Jupyter

The examples use acme's order-pipeline, a Standard workflow that validates an order, charges the card, loads the order with the orders-etl Lambda function and resizes its pictures in a Map. Some of its executions fail at LoadOrders, where orders-etl raises KeyError: 'customer_id'.

Watch it run

Five calls in a notebook, from every state machine to the path an execution took: each call typed and run, and the report it draws, with what to notice. It plays as you scroll to it; click it to pause, or pick a chapter to jump to a call.

Set up in SageMaker

  1. Install it in a notebook cell:

    %pip install aws-analyzer
    
  2. Make the view. It uses the notebook's IAM role and region, so there's nothing to configure.

    from aws_analyzer import StepFunctionsView
    
    sfn = StepFunctionsView()
    sfn.help()             # every command, grouped by task; sfn.help("execution") shows one in full
    
Another region or profile, plain text

State machines are regional, so if overview() comes back empty, check the region first. Only boto3 is required.

from aws_analyzer import StepFunctionsAnalyzer, StepFunctionsView

sfn = StepFunctionsView(StepFunctionsAnalyzer(region="eu-west-1", profile="dev"))
sfn = StepFunctionsView(mode="text")    # plain text, also what you get outside Jupyter

Start here

Six questions people bring to a workflow, and the one line that answers each. None of them change anything.

Health

One workflow

Rather click?

An execution is named by its ARN, a link copied from the console, or "state-machine/execution-name".

How to read a report

Every report puts the answer first: cards with the numbers that matter, then the findings, warnings first, each a bold headline with why it matters and what to do underneath. The tables of detail come after, and Next at the bottom lists two or three commands with the arguments filled in. One click on a command selects all of it, ready to copy.

Your state machines

overview() lists every state machine in the region with how many executions it ran in the last 7 days, how many didn't succeed, its average run and its estimated monthly cost, the ones with failures first.

sfn.overview()            # or overview(days=30)

The numbers are CloudWatch's (AWS/States), in whole UTC days, so they cover Express workflows too. The findings point at the next command, such as failures('order-pipeline').

overview(): cards for 4 state machines, 183,659 executions and 448 that didn't succeed, findings pointing at failures('order-pipeline'), and a table of each state machine's executions, failures, average run, cost and logging overview(): cards for 4 state machines, 183,659 executions and 448 that didn't succeed, findings pointing at failures('order-pipeline'), and a table of each state machine's executions, failures, average run, cost and logging

sfn.overview(): order-pipeline's warnings are its 4.0% failure rate and that its failures jumped three days ago, and the table puts the failing state machines first.

Worth knowing

An Express workflow keeps no history in Step Functions, so its executions are read from its log group. With logging off they leave no record at all, and at ERROR only its failures do (without even the state that failed). The finding shows the aws stepfunctions update-state-machine command that turns logging on, at ALL.

How Express executions are read

Step Functions writes each event of an Express execution to the log group as one JSON line, the same events a Standard execution's history holds. executions() reads the window's lines (the newest 20,000, read back from now in slices that double) and groups them by execution; execution() and failures() search for one execution's lines with a filter pattern, in the five minutes an Express execution can last. The lines turned back into history events go through the same reader, so the waterfall, the log and the failure groups work the same way. Express ARNs carry an ID beside the name, so executions() lists each ARN.

Why it fails

failures() groups the executions that failed, timed out or were aborted by the state they stopped at and the error, the most common first, each with the run to read next.

sfn.failures("order-pipeline")                  # the last 7 days, the newest 50 failures
sfn.failures("order-pipeline", since="30d", limit=200)

For each failure it reads only the end of the execution's history (one request, whatever the history's length), which is where the failure is. When the failing state called Lambda, the group names the function and the newest run's request ID, ready for LambdaView().logs('orders-etl', request_id='c0ffee00-…'). Each group says since when it has failed that way, as far back as the failures read go. It also says how many of the failed executions can still be redriven, started again from the state that failed, and shows the command; it never runs it.

Each kind of failure also says whether a Retry would have saved it, in a column and a finding. A throttle or a Lambda service error passes in seconds, so the finding gives the Retry rule to paste (or, when the state already retries it and ran out, a rule with more tries, further apart). A code error like KeyError fails the same way every time, so a Retry won't help, and one on States.ALL only repeats it. A timeout needs the slowness found first. It's judged from the error's name and the state's own Retry rules.

It then asks what changed before each kind of failure began: when the Lambda function it stopped in was deployed (each published version, or its last change), and when the definition the first failure ran with was last updated. A change in the two days before the first failure is the first thing to check, and a finding says so: "LoadOrders began failing with KeyError 4 minutes after orders-etl version 2 was published", with the call that shows the function. It's timing, not proof, and the finding says that too. When nothing changed nearby, the finding says when each last did and points at the failing execution's input instead.

A strip of bars shows the executions a day, the part that didn't succeed in red, from CloudWatch's whole UTC days. When most of the failures came in the last few days, the day they jumped is outlined and a finding says so: "Failures jumped on 12 Nov: 40 of the 49 in the last 7 days came since then", with the failures(..., since=) call that reads just those. state_machine() shows the same strip.

failures('order-pipeline'): 49 executions that didn't succeed in three groups, LoadOrders failing with KeyError in orders-etl the most common, each with since when, whether a Retry would help and the Lambda logs call or execution to read next, a warning that LoadOrders began failing 4 minutes after orders-etl version 2 was published, a note that 5 can be redriven, and the executions a day as bars failures('order-pipeline'): 49 executions that didn't succeed in three groups, LoadOrders failing with KeyError in orders-etl the most common, each with since when, whether a Retry would help and the Lambda logs call or execution to read next, a warning that LoadOrders began failing 4 minutes after orders-etl version 2 was published, a note that 5 can be redriven, and the executions a day as bars

sfn.failures("order-pipeline"): most failures stop at LoadOrders with KeyError: 'customer_id', and they began 4 minutes after orders-etl version 2 went out.

One execution, step by step

execution() shows each state an execution passed through: what it called, when it started, how long it took, how many tries, and where it failed and why.

sfn.execution("order-pipeline/ord-7f3a")
sfn.execution("arn:aws:states:us-east-1:123456789012:execution:order-pipeline:ord-7f3a")
sfn.execution("ord-7f3a", machine="order-pipeline", logs=False)    # skip the Lambda logs

A waterfall puts each state on one time axis, with a task's tries, the back-off between them and a Map's iterations in place. Then comes one log of what happened: Step Functions' own events and what each Lambda function logged in that very run, merged by time. Each run is found by the request ID Step Functions records in the step's result or error, so the lines are that run's and no other's. An older task that names a function's ARN as its resource records no request ID; then the run that started just after the step was scheduled is shown, and the report says it was matched by time.

The states inside a Map or Parallel are summed up under it (×12, how many failed, the longest), retries show as tries, and a Catch that moved on is said in a finding.

At the end, folded, are what it returned (for an execution that succeeded), the error the failed step returned, what that step was given and the execution's input. JSON shows as a tree: unfold the object or array you need, and point at a field for its path.

execution('order-pipeline/ord-7f3a'): findings, a waterfall where ChargeCard's throttled tries and back-off come before LoadOrders fails, the states in order, and one log merging Step Functions' events with the lines of validate-order, charge-card and orders-etl execution('order-pipeline/ord-7f3a'): findings, a waterfall where ChargeCard's throttled tries and back-off come before LoadOrders fails, the states in order, and one log merging Step Functions' events with the lines of validate-order, charge-card and orders-etl

sfn.execution("order-pipeline/ord-7f3a"): the waterfall, then one log where orders-etl's traceback sits between the step that called it and the Catch that ended the execution.

Beside the last success

compare() puts a failed execution beside the newest one that succeeded before it, and says what was different: the states, and the input's fields.

sfn.compare("order-pipeline/ord-7f3a")                    # with the last success before it
sfn.compare("order-pipeline/ord-7f3a", other="ord-25a8")  # with one you pick

A table lists each state either execution went through: how it ran in each, and the difference. It flags a state that failed only here, took more tries or ran much slower. The states it never reached after failing, and where its Catch sent the error, are shown but not counted as differences. A second table lists the input fields that are missing, extra, empty or of another type. Values that just differ aren't listed, since every order has its own ID.

When the error names a field the input lacks, the first finding says so: "The likely cause: ord-7f3a's input has no customer_id, which ord-cfae's had, and LoadOrders failed with KeyError, naming it". In the explorer, ⇄ Compare with the last success beside ↗ Console shows the same over a failed execution's page.

compare('order-pipeline/ord-7f3a'): ord-7f3a beside ord-cfae, cards for each run, the finding that its input has no customer_id, which ord-cfae's had, and LoadOrders failed with KeyError, then a table of each state in both and a table of the input field that differs compare('order-pipeline/ord-7f3a'): ord-7f3a beside ord-cfae, cards for each run, the finding that its input has no customer_id, which ord-cfae's had, and LoadOrders failed with KeyError, then a table of each state in both and a table of the input field that differs

sfn.compare("order-pipeline/ord-7f3a"): the run that succeeded just before it had a customer_id; this one didn't, and that's the key LoadOrders failed on.

How the Lambda lines are read

The Step Functions module doesn't read CloudWatch Logs itself: it asks the Lambda module for the run, LambdaAnalyzer.log_events(name, request_id=...), the same read LambdaView().logs() makes, and draws its lines the same way. The Lambda module loads only when a failed Lambda step needs it, so sfn.overview() never imports it.

One state machine

state_machine() shows a workflow's numbers, every state with what it calls, where it goes next, its retries and where an error sends it, and what its definition risks.

sfn.state_machine("order-pipeline")
sfn.graph("order-pipeline")                         # the flow drawn as a graph, and Mermaid to paste
sfn.graph("order-pipeline", execution="ord-7f3a")   # coloured by the path that execution took
sfn.graph("order-pipeline", failures="7d")          # shaded by where executions stopped

The findings read the definition: a Lambda task with no Retry for Lambda's own errors (Lambda.ServiceException, Lambda.TooManyRequestsException, ...) fails the whole execution on one throttle, and the finding shows the Retry rule AWS recommends, to paste; a task that waits for a callback (.waitForTaskToken, an activity) with no TimeoutSeconds or HeartbeatSeconds can wait up to a year.

It also reads the settings of the Lambda functions the states call (lambda:GetFunction) and holds each task against its function, in a table under the states. A state and its function each have a clock, and the shorter one wins:

The state The function When they clash
TimeoutSeconds Its timeout The state fails with States.Timeout while the run goes on, billed. A Retry on the timeout starts a second run beside the first
An Express workflow's 5 minutes Its timeout The run outlives the execution that started it
A Map's items at once (MaxConcurrency, else 40 inline or 10,000 distributed) Reserved concurrency The extra runs are throttled: they fail the item unless the task retries Lambda.TooManyRequestsException
A Map's items at once No reserved concurrency A Map as big as the region's pool (lambda:GetAccountSettings) throttles every other function in the region while it runs

A task that starts another state machine (states:startExecution) is held against it the same way, from the child's own definition:

The task The child When they clash
.sync with a TimeoutSeconds Its own TimeoutSeconds, 5 minutes for Express, else up to a year The task fails with States.Timeout before the child has to finish, and doesn't see how it ends. A Retry on the timeout starts the child again
.sync with no TimeoutSeconds No TimeoutSeconds either A stuck child holds the parent for up to a year
No .sync Anything Worth knowing: the parent goes on and succeeds whatever the child does, so a failed child shows only in its own executions

state_machine('order-pipeline'): cards for its type, executions, failures, average run, cost and logging, a finding that its failures jumped three days ago, one that LoadOrders has no Retry for Lambda's errors with the rule to paste, one that ProcessItems is throttled by resize-image's reserved concurrency, its executions a day as bars, a table of every state with what it calls, where it goes next, its retries and where an error sends it, and a table of how its states and Lambda functions limit each other, where ProcessItems runs 4 resize-image items at once against the function's reserved concurrency of 2, a clash state_machine('order-pipeline'): cards for its type, executions, failures, average run, cost and logging, a finding that its failures jumped three days ago, one that LoadOrders has no Retry for Lambda's errors with the rule to paste, one that ProcessItems is throttled by resize-image's reserved concurrency, its executions a day as bars, a table of every state with what it calls, where it goes next, its retries and where an error sends it, and a table of how its states and Lambda functions limit each other, where ProcessItems runs 4 resize-image items at once against the function's reserved concurrency of 2, a clash

sfn.state_machine("order-pipeline"): its failures jumped three days ago, the day outlined in the bars, LoadOrders has no Retry for Lambda's own errors (the finding gives the rule to paste), and ProcessItems runs more of resize-image at once than the function may run.

graph('order-pipeline', execution='ord-7f3a'): the flow drawn as boxes and arrows, the path ord-7f3a took in green up to LoadOrders in red, its error arrow to OrderFailed, and the states it never reached dashed graph('order-pipeline', execution='ord-7f3a'): the flow drawn as boxes and arrows, the path ord-7f3a took in green up to LoadOrders in red, its error arrow to OrderFailed, and the states it never reached dashed

sfn.graph("order-pipeline", execution="ord-7f3a"): drawn the way the console draws it, the path the execution took flowing along its arrows, where it failed, and what it never reached (the top of the report; a table of the states and the Mermaid source follow).

Where the time goes

graph(timings=True) reads the newest 20 executions that succeeded and shades each state by its share of their time, so you see which state is slow by habit and which one retries.

sfn.graph("order-pipeline", timings=True)           # the newest 20 succeeded executions
sfn.graph("order-pipeline", timings=50)             # more of them, for a steadier median

One execution's waterfall can be an outlier; twenty show a habit. Each state gets its median and longest run, its share of the executions' time and its tries a run. A state inside a Map gets how many times it runs an execution instead of a share, since its runs can overlap.

The findings name the state that takes most of the time and where to look in it (a Map's slowest inner state, a Lambda task's function), a state whose runs vary a lot with the execution that shows the slow one, and every state that retries in one run out of ten or more. A retry waits its back-off, and on a Standard workflow it's another state transition on the bill, so that finding prices it at your pace from CloudWatch and says what to change: for a throttled Lambda, reserved concurrency or a lower MaxConcurrency.

graph('order-pipeline', timings=True): findings that ChargeCard retries after Lambda throttles it, priced a month, that ProcessItems takes 69% of the time and ResizeImage inside it the most, and that LoadOrders runs unevenly; the flow with each box shaded by its share of the time; and a table of every state's runs, median, longest, share and tries a run graph('order-pipeline', timings=True): findings that ChargeCard retries after Lambda throttles it, priced a month, that ProcessItems takes 69% of the time and ResizeImage inside it the most, and that LoadOrders runs unevenly; the flow with each box shaded by its share of the time; and a table of every state's runs, median, longest, share and tries a run

sfn.graph("order-pipeline", timings=True): ChargeCard retries when Lambda throttles it, and ProcessItems, the Map of ResizeImage runs, is where the time goes.

Worth knowing

Each execution's history is one GetExecutionHistory call. Reading it costs nothing, but AWS rate-limits it, so the sample stays small and the report says how many it read. An Express workflow's executions come from its log group, and only when it logs everything (ALL): at ERROR the succeeded ones leave no line.

Explore by clicking

explore() opens a window with every state machine; click one to read its executions, each with its waterfall and one log of what happened.

sfn.explore()                                       # the state machine failing most, or the first
sfn.explore("order-pipeline", execution="ord-7f3a") # with one execution open

Its Graph tab draws the workflow with an execution's path on it, and its Failures tab groups the failures by the state they stopped at. The Step Functions explorer guide covers every tab, with its own video tour.

Take a report into pandas or Excel

Every report ends with 🐼 This report as data: its tables for pandas, each column explained, and a workbook to share. An execution's tables put each step beside the Lambda run behind it.

A minute in a notebook: the executions, the same rows in pandas, the failed one step by step, and the workbook.

The end of executions("order-pipeline", since="30d"): the fold This report as data opened, with the code to copy and the executions table's columns The end of executions("order-pipeline", since="30d"): the fold This report as data opened, with the code to copy and the executions table's columns

The end of sfn.executions("order-pipeline", since="30d"), opened: a row per execution, and each column in plain words.

sfn.execution("order-pipeline/ord-7f3a")
data = sfn.data()
data["steps"]            # each state: seconds, share_of_execution, retries, transitions, est_cost_usd
data["lambda_runs"]      # each Lambda step beside its run: step_seconds, lambda_ms, outside_ms, billed_ms, memory, cost
data["tries"]            # every try, with its error and request ID
sfn.to_excel()           # aws-analyzer-exports/stepfunctions-execution-ord-7f3a.xlsx

outside_ms is the step's time the function's code didn't account for: a cold start, throttling or Step Functions itself. A step whose outside_ms is large beside its lambda_ms isn't slow code. lambda_cost_usd plus the steps' est_cost_usd is what the execution cost.

sfn.to_excel() saying it saved stepfunctions-execution-ord-7f3a.xlsx, then the workbook opened: the Summary sheet, the Charts sheet and the steps sheet sfn.to_excel() saying it saved stepfunctions-execution-ord-7f3a.xlsx, then the workbook opened: the Summary sheet, the Charts sheet and the steps sheet

sfn.to_excel() after an execution: its summary, Excel's own charts, and its steps, tries and Lambda runs as sheets.

What each line gives back, in a notebook

The executions as a DataFrame:

A DataFrame of ten executions of order-pipeline: one running, three succeeded, five failed and one timed out, with when each started and how many seconds it took A DataFrame of ten executions of order-pipeline: one running, three succeeded, five failed and one timed out, with when each started and how many seconds it took

sfn.data()["executions"]: five failed and one timed out, with when and how long.

Each row's ref reads that execution as data:

The steps of the newest failed execution: ChargeCard took 3.995 s, 0.65 of the execution, over 3 tries, and LoadOrders failed after 1.75 s The steps of the newest failed execution: ChargeCard took 3.995 s, 0.65 of the execution, over 3 tries, and LoadOrders failed after 1.75 s

sfn.data("execution", failed)["steps"]: ChargeCard took 65% of the time, and LoadOrders failed.

Which tables each report gives
Report Tables
overview() machines (executions, failures, average run, estimated monthly cost), days (a row per state machine per day)
state_machine() states (each state, what it calls, its retries and catches), days
executions() executions (a row per execution with its run time and estimated cost, and the ref that opens it), days
execution() steps, tries, lambda_runs
failures() causes (a row per state and error), failed (every failed execution read)
graph(timings=True) timings: each state's median, longest and share of the time, and how often it retries

sfn.data("executions", "order-pipeline", since="30d") reads a report without showing it; each row's ref opens that execution: sfn.data("execution", ref). Costs are estimates at list prices (Lambda's at x86_64 prices), before the free tier.

That's the guide. Everything below is reference for when you need it: the data in Python, cost, permissions, troubleshooting and every command.

Use the data in Python

sfn.core is the StepFunctionsAnalyzer. Every report has a data method on it.

core = sfn.core

ov = core.overview(days=7)                          # Overview: .machines, .numbers (by ARN), .errors
machine = core.state_machine("order-pipeline")      # StateMachine: .type, .states, .functions, .log_level
core.executions("order-pipeline", status="failed").to_df()
detail = core.execution("order-pipeline/ord-7f3a")  # ExecutionDetail: .steps, .failed_step, .lambda_run
detail.failed_step.request_id                       # the Lambda run behind the failure
core.failures("order-pipeline").groups              # FailureGroup: state, error, count, newest, request_id
core.timings("order-pipeline").to_df()              # per state: runs, median, longest, share, tries a run

The analysis functions make no AWS calls, so they also work on a definition or a history you already have:

from aws_analyzer.stepfunctions import ExecutionDetail, fill_detail, parse_definition, parse_execution

start, states = parse_definition(open("order-pipeline.asl.json").read())
detail = fill_detail(ExecutionDetail(parse_execution(described)), history_events)

Cost

Costs are estimates at us-east-1 list prices (STEPFUNCTIONS_PRICES): $0.025 per 1,000 state transitions for Standard workflows, and for Express $1.00 per million executions plus $0.00001667 per GB-second at 64 MB, the least Express bills. A Standard execution is counted as one transition per top-level state; Map iterations add more, and the 4,000 free transitions a month aren't taken off. Pass your own prices with StepFunctionsAnalyzer(prices={"transition": 0.0000275}).

overview() reads 7 CloudWatch metrics per state machine ($0.01 per 1,000) and says how many it read. Executions, histories and Lambda logs cost nothing to read. A retry is a state transition too, so a state that retries often costs money as well as time: graph(timings=True) prices its retries.

Permissions

Everything is read-only. Anything the notebook's role can't read shows up as a note instead of an error. This policy covers every command:

IAM policy
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadStateMachines",
      "Effect": "Allow",
      "Action": [
        "states:ListStateMachines", "states:DescribeStateMachine", "states:ListExecutions",
        "states:DescribeExecution", "states:GetExecutionHistory", "states:DescribeStateMachineForExecution"
      ],
      "Resource": "*"
    },
    {
      "Sid": "ReadNumbers",
      "Effect": "Allow",
      "Action": "cloudwatch:GetMetricData",
      "Resource": "*"
    },
    {
      "Sid": "ReadLambdaRuns",
      "Effect": "Allow",
      "Action": [
        "lambda:GetFunction", "lambda:ListVersionsByFunction", "lambda:GetAccountSettings", "logs:FilterLogEvents"
      ],
      "Resource": "*"
    }
  ]
}

The last statement is only for the Lambda lines in execution(), the deploys failures() compares with when each kind of failure began, and the functions' timeouts and concurrency state_machine() holds its tasks against (lambda:GetAccountSettings only when a Map runs a function without reserved concurrency); without it the report says what it couldn't read and shows the call that reads it. states:DescribeStateMachineForExecution dates the definition a failure ran with.

Troubleshooting

“No state machine named …”

Names are case-sensitive and state machines are regional. The note lists the closest names; overview() lists them all. Use StepFunctionsView(StepFunctionsAnalyzer(region="eu-west-1")) for another region.

“… is an Express workflow with logging off”

Step Functions keeps no list or history of Express executions: they're read from the workflow's log group, so with logging off there's nothing to read. state_machine() shows the command that turns logging on; executions after that show up.

An Express failure says “(unknown state)”

At ERROR level, Step Functions logs the failed task's error but not the state it was in. Set the logging level to ALL to see every step.

The Lambda run behind a step couldn't be shown

The note says why: the function no longer exists, it has no log group, its logs have expired, or the role can't call logs:FilterLogEvents. The call it shows reads the run with the Lambda module.

ExecutionDoesNotExist

Step Functions keeps an execution for 90 days after it ends. executions("order-pipeline", since="90d") lists the ones there are.

Command reference

Every StepFunctionsView command. sfn.help() prints the same list grouped by task, and sfn.help("execution") shows one command's full description.

Command What it shows
overview(days=7) Every state machine: executions, how many didn't succeed, average run, cost, logging
state_machine(name, days=7) One state machine: its numbers, every state, what its definition risks, the definition
graph(name, execution=None, failures=None, timings=None) The flow drawn as a graph, coloured by an execution's path, where executions stop or where the time goes, and Mermaid to paste
executions(name, status=None, since="7d", n=25) Its latest executions, newest first
execution(ref, machine=None, logs=True, max_events=5000) One execution step by step: its waterfall, and one log with every Lambda run's lines
compare(execution, other=None, machine=None, since="30d") An execution beside the last success before it (or other=): the states and input fields that differ, and the likely cause
failures(name, since="7d", limit=50) Failures grouped by the state they stopped at and the error
explore(name=None, execution=None, tab=None, since="7d", height=None) The explorer window: every state machine, its executions with their waterfall and log, failures and definition
data(command=None, *args, **kwargs) The last report's tables as pandas DataFrames, each column explained
to_excel(command=None, *args, path=None, **kwargs) The last report as an Excel workbook: summary, charts, a sheet per table and how to read them
help(command=None) This list, grouped by task; help("name") shows one command in full