AWS from zero · Part 4: Automation and serverless · Lesson 24 of 38 · about 50 minutes

Step Functions

Taking an order is several steps that must happen in order: check it, reserve the stock, take payment, confirm. Step Functions runs them as a workflow you can see. Five orders took five different paths: one succeeded, one found no rye, one had its card declined and its stock put back, one got through a busy bank on the third try, and one was rejected at the first step. Every run kept a record, event by event. Inside the free allowance.

By the end you'll know

  • What a workflow service does that a chain of Lambda functions doesn't
  • How a state machine is written, in Amazon States Language
  • How Step Functions calls AWS services directly, without code in between
  • How Retry and Catch handle errors that might pass and errors that won't
  • How to undo earlier steps when a later one fails
  • How to read a run's history, and when to choose Standard or Express workflows

Before you start

  • You need: the juniper-rye profile, signed in, and Lesson 20's virtual environment. Lesson 18 covers the conditional writes the workflow uses, and Lesson 21 the Lambda function.
  • The script: workflow-lab.py from the practice folder's lesson-24. Everything it creates is named jr-lesson24-* and tagged lesson=24, and its delete step removes it.
  • How the script talks to AWS: only through boto3, as in Lessons 20 to 23.
  • To see every call the script makes that changes something, put SHOW=1 in front of any step. The "By hand" section has the same lab as AWS CLI commands.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from real runs on November 14, 2026.

A loop in a workflow bills every step

Standard workflows charge for every step entered, and a workflow can run for up to a year. A mistake that sends a run round a loop, or a retry with no maximum, keeps billing until someone stops it. Always set MaxAttempts on retries, give loops a counter that ends them, and set a timeout on the whole workflow with TimeoutSeconds.

The short version

  • A workflow is the steps, the order, and what happens when one fails, written down where you can see it, instead of buried in code.
  • Step Functions can call DynamoDB, SQS and hundreds of other services itself, so many steps need no Lambda function at all.
  • Retry for errors that might pass, like a busy bank; Catch for ones that won't, like a declined card.
  • When a later step fails, undo the earlier ones: the workflow put the reserved stock back.
  • Every run's history is kept, event by event, so "what happened to order 7004?" has an exact answer.

What this lesson costs

PartCost, in us-east-2
Standard workflow steps (state transitions)$25.00 per million
Free every month, on the free plan too4,000 state transitions
This lab's runsA few dozen transitions: inside the free allowance
The payments functionInside Lambda's free allowance
The stock tableUnder 1 cent
This lessonUnder 1 cent

Why a workflow?

Taking an order at Juniper & Rye is four things in order: check the order makes sense, reserve the stock, take payment, confirm. Each can go wrong in its own way. There might not be enough rye. The bank might be busy for a moment, or decline the card outright. And if payment fails after the stock was reserved, the stock has to be put back, or the shop will think it's sold bread it still has.

You could write all of that in one Lambda function. Then the order of steps, the retries, the waits and the clean-up would all live in code, and when an order went wrong, the only record would be whatever the code logged. Lambda functions also stop after 15 minutes, and you'd pay for every second spent waiting on the bank.

Step Functions makes the workflow a thing of its own. You write down the steps and the rules between them; it runs them, waits between them for free, retries what you said to retry, and records every step of every run.

A workflow is the recipe card pinned above the bench, not the baker's memory. Each step is written down in order, with what to do if something goes wrong: "if the oven isn't hot yet, wait and check again; if the flour's run out, put the butter back and tell the customer." Anyone can follow it, anyone can see which step an order is on, and the card is the same every time.
The take-an-order workflowThe main path runs: Check the order, Look up stock, Enough?, Reserve stock, Take payment, Order confirmed. A bad order goes from Check the order to Bad order. Not enough stock goes from Enough? to Out of stock, as does a failed reservation. Take payment retries BankBusy errors; a declined card goes to Put stock back, then Payment declined.Check theorderLook upstockEnough?ReservestockTakepaymentOrderconfirmedretry BankBusy: 2 s, then 4 sqty not above 0Bad ordertoo fewsold meanwhileOut of stockPaymentDeclinedPut stock backPayment declinedShaded steps call AWS: DynamoDB directly, and the payments function in Lambda.
The ten states of the workflow. Five orders in the lab took five different paths through it.

Is it allowed, and what does it cost?

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-24
source ../lesson-20/.venv/bin/activate
python workflow-lab.py fence
OUTPUT
== Is this allowed in us-east-2?
  Step Functions  allowed
  Lambda          allowed
  DynamoDB        allowed
  IAM roles       allowed
== What Step Functions costs, in us-east-2
  Standard workflows: $25.00 per million per state transition (each step entered)
  free every month, on the free plan too: 4,000 state transitions
  this lab: five runs of about 6 to 10 transitions each: inside the free allowance
  the payments function: inside Lambda's free allowance; the table: under 1 cent

$25 per million steps is 2.5 thousandths of a cent per step, so a seven-step order costs about $0.00018. That adds up at scale: a million orders a day would be about $175 a day. For high-volume, short workflows, the Express type, later in the lesson, is priced differently and is usually far cheaper.

The workflow

In the console: Step Functions > State machines > Create state machine, then build it in Workflow Studio, or paste the definition into the Code tab.

BASH
python workflow-lab.py build
OUTPUT
== The stock table
  in stock: sourdough 10, rye 2, croissant 24
== The payments function: pretends to be the bank
  card "declined" raises PaymentDeclined; card "busy" raises BankBusy on its first 2 tries
== The workflow's role: run the payments function, read and update the stock table. Nothing else.
== The workflow, jr-lesson24-take-an-order (a Standard workflow)
  definition checked by validate_state_machine_definition: OK
== The workflow's role works: a test run read the stock table after 20 seconds and 4 tries
  (the earlier tries failed with "states.amazonaws.com is not authorized to assume the provided role")
  10 states, starting at "Check the order":
    Check the order    Choice
    Bad order          Fail
    Look up stock      Task (dynamodb:getItem)
    Enough?            Choice
    Out of stock       Fail
    Reserve stock      Task (dynamodb:updateItem); on ConditionalCheckFailedException goes to "Out of stock"
    Take payment       Task (lambda:invoke); retries BankBusy up to 3 times, waiting 2s then x2; on PaymentDeclined goes to "Put stock back"
    Put stock back     Task (dynamodb:updateItem)
    Payment declined   Fail
    Order confirmed    Pass

A workflow, called a state machine, is written in Amazon States Language: JSON that names each state, what it does, and which state comes next. Each run is an execution: it starts with a JSON input, here the order, which each state can read, add to and pass on.

TypeDoesIn the lab
TaskDoes work: calls an AWS service or a Lambda functionLook up stock, Reserve stock, Take payment, Put stock back
ChoicePicks the next state by looking at the dataCheck the order, Enough?
PassReshapes the data, does no workOrder confirmed
Fail, SucceedEnd the run, failed with an error name, or succeededBad order, Out of stock, Payment declined
WaitWaits for a time or a date, for freeNot used
Parallel, MapRun branches at once, or the same steps for each item in a listNot used; a Map could take a whole basket of items

Three of the four tasks call DynamoDB with no code in between. Step Functions has built-in integrations for many services, and an AWS SDK integration that reaches more than 200 more, so a step can read a table, send to a queue or start a job directly. Here is Reserve stock, which is Lesson 18's conditional write:

JSON
"Reserve stock": {
  "Type": "Task", "Resource": "arn:aws:states:::dynamodb:updateItem",
  "Parameters": {"TableName": "jr-lesson24-stock", "Key": {"item": {"S.$": "$.item"}},
                 "UpdateExpression": "SET #l = #l - :q", "ConditionExpression": "#l >= :q",
                 "ExpressionAttributeNames": {"#l": "left"},
                 "ExpressionAttributeValues": {":q": {"N.$": "States.Format('{}', $.qty)"}}},
  "ResultPath": null,
  "Catch": [{"ErrorEquals": ["DynamoDB.ConditionalCheckFailedException"], "Next": "Out of stock"}],
  "Next": "Take payment"
}
FieldDoes
$.itemA JSONPath into the run's data: the order's item
A key ending in .$"Fill this from the data", not a fixed value
States.Format, States.StringToJsonBuilt-in functions, here turning numbers into DynamoDB's text form and back
ResultPathWhere the step's result goes in the data; null throws it away and keeps the order unchanged
ResultSelectorPicks the parts of the result to keep

The lab writes data handling in JSONPath, which you'll see in most existing workflows. New workflows can use JSONata instead, a shorter expression language Step Functions added in 2024, by setting "QueryLanguage": "JSONata".

The workflow's role needed 20 seconds and 4 tries before Step Functions could use it. Creating the workflow didn't check; the first runs would have failed at their first task with "states.amazonaws.com is not authorized to assume the provided role," and the first version of this lab's script did exactly that. Lessons 19 and 21 met the same delay with AWS Backup and Lambda. The role allows only what the steps need: running one function, and reading and updating one table.

The script also asked AWS to check the definition before creating it, with validate_state_machine_definition, which catches mistakes like a Next pointing at a state that doesn't exist.

Five orders, five paths

In the console: the state machine > Start execution, with an order as the input.

BASH
python workflow-lab.py run
OUTPUT
== 1. A normal order: {"order": 7001, "item": "sourdough", "qty": 2, "card": "ok"}
  SUCCEEDED in 0.5 s, 23 events in its history
  path: Check the order > Look up stock > Enough? > Reserve stock > Take payment > Order confirmed
  output: {"item":"sourdough","qty":2,"receipt":"r-7001-1","order":7001}
  sourdough in stock: 10 before, 8 after
== 2. More rye than there is: {"order": 7002, "item": "rye", "qty": 5, "card": "ok"}
  FAILED in 0.1 s, 12 events in its history
  path: Check the order > Look up stock > Enough? > Out of stock
  error: OutOfStock: not enough left to reserve
  rye in stock: 2 before, 2 after
== 3. A declined card: {"order": 7003, "item": "croissant", "qty": 3, "card": "declined"}
  FAILED in 0.5 s, 27 events in its history
  path: Check the order > Look up stock > Enough? > Reserve stock > Take payment > Put stock back > Payment declined
  task failures on the way: PaymentDeclined
  error: PaymentDeclined: the card was declined; stock put back
  croissant in stock: 24 before, 24 after
== 4. A busy bank: {"order": 7004, "item": "sourdough", "qty": 1, "card": "busy"}
  SUCCEEDED in 6.8 s, 29 events in its history
  path: Check the order > Look up stock > Enough? > Reserve stock > Take payment > Order confirmed
  task failures on the way: BankBusy, BankBusy
  output: {"item":"sourdough","qty":1,"receipt":"r-7004-3","order":7004}
  sourdough in stock: 8 before, 7 after
== 5. A nonsense order: {"order": 7005, "item": "rye", "qty": 0, "card": "ok"}
  FAILED in 0.0 s, 5 events in its history
  path: Check the order > Bad order
  error: BadOrder: qty must be a number above 0
  rye in stock: 2 before, 2 after
== Every run is kept; list them with list_executions
  order-7005-1794638315        FAILED
  order-7004-1794638307        SUCCEEDED
  order-7003-1794638305        FAILED
  order-7002-1794638304        FAILED
  order-7001-1794638303        SUCCEEDED
OrderEndedShows
7001, sourdoughSucceeded, stock 10 to 8The main path, in half a second
7002, 5 ryeOutOfStock, stock unchangedA Choice state stopping the run before anything was reserved
7003, declined cardPaymentDeclined, stock 24 and 24Catch, and undoing the reservation
7004, busy bankSucceeded on the 3rd try, in 6.8 sRetry with growing waits
7005, zero ryeBadOrder, at the first stepChecking input before doing anything

Order 7003 reserved 3 croissants, then the card was declined, and the stock ended where it started. Take payment's Catch sent the run to Put stock back, which added the 3 back, then to a Fail state that names the reason. This is called a compensating step: each step that changes something gets a partner that undoes it, run when a later step fails. A chain of steps with compensations is often called a saga. Without it, every declined card would quietly lose stock.

The error names matter. OutOfStock, PaymentDeclined and BadOrder are names the workflow chose, so whatever started the run can tell "try another card" from "we've sold out" without reading messages. The payments function raised Python exceptions named PaymentDeclined and BankBusy, and Step Functions used the class names as the error names, which is what Retry and Catch match on.

Order 7002 never reached Reserve stock, because the Choice state saw 2 left. Reserve stock's own Catch is still needed: between Look up stock and Reserve stock, another order could take the last loaves. The conditional write refuses, and the Catch sends that order to Out of stock too.

Retries, event by event

BASH
python workflow-lab.py history
OUTPUT
== The history of order-7004-1794638307 (the busy bank), every event
    0.0 s  ExecutionStarted         
    0.0 s  ChoiceStateEntered       Check the order
    0.0 s  ChoiceStateExited        Check the order
    0.0 s  TaskStateEntered         Look up stock
    0.0 s  TaskScheduled            getItem
    0.0 s  TaskStarted              
    0.1 s  TaskSucceeded            
    0.1 s  TaskStateExited          Look up stock
    0.1 s  ChoiceStateEntered       Enough?
    0.1 s  ChoiceStateExited        Enough?
    0.1 s  TaskStateEntered         Reserve stock
    0.1 s  TaskScheduled            updateItem
    0.2 s  TaskStarted              
    0.2 s  TaskSucceeded            
    0.3 s  TaskStateExited          Reserve stock
    0.3 s  TaskStateEntered         Take payment
    0.3 s  TaskScheduled            invoke
    0.3 s  TaskStarted              
    0.4 s  TaskFailed               BankBusy: the bank is busy (attempt 1)
    2.4 s  TaskScheduled            invoke
    2.5 s  TaskStarted              
    2.6 s  TaskFailed               BankBusy: the bank is busy (attempt 2)
    6.6 s  TaskScheduled            invoke
    6.7 s  TaskStarted              
    6.7 s  TaskSucceeded            
    6.7 s  TaskStateExited          Take payment
    6.7 s  PassStateEntered         Order confirmed
    6.7 s  PassStateExited          Order confirmed
    6.8 s  ExecutionSucceeded       

The bank failed at 0.4 s, the retry came 2 seconds later, failed again, and the next came 4 seconds after that, and worked. That's the Retry on Take payment:

JSON
"Retry": [{"ErrorEquals": ["BankBusy"], "IntervalSeconds": 2, "BackoffRate": 2, "MaxAttempts": 3}],
"Catch": [{"ErrorEquals": ["PaymentDeclined"], "ResultPath": "$.error", "Next": "Put stock back"}]
RetryCatch
ForErrors that might pass: busy, throttled, timed outErrors that won't: declined, invalid, not found
DoesRuns the same step again, after a waitGoes to another state
SettingsFirst wait, how much longer each time, maximum tries, optional random jitterWhich errors, where to go, where to put the error
In the labBankBusy: up to 3 more tries, after 2 s, 4 s, 8 sPaymentDeclined: put the stock back

Retrying a declined card would be pointless, and retrying forever would be expensive, which is why each error gets its own rule, and why the warning box at the top asks for MaxAttempts. If all the retries fail, the error goes on to Catch, and if nothing catches it, the run fails with that error. The waits between tries cost nothing: Standard workflows charge per step entered, not per second.

The receipt r-7004-3 shows it was the third try: the payments function read $$.State.RetryCount, part of the context object Step Functions passes alongside the data, which says which try this is. A real bank would get the same order three times, so the payment call must be safe to repeat, usually by sending the order number as an idempotency key that the bank uses to ignore duplicates.

This is what the history is for. Every run keeps every event, with times, inputs and outputs, for 90 days after it ends, viewable in the console as a graph with the path lit up. When a customer asks why their order took seven seconds, the answer is above.

Standard or Express?

The lab used a Standard workflow. Express workflows run the same definitions, with different trade-offs:

StandardExpress
Longest run1 year5 minutes
Each step runsExactly once, unless you retry itAt least once when started in the background, at most once when the caller waits; either way, make steps safe to repeat
Priced bySteps entered: $25 per millionRuns and their duration and memory, like Lambda
HistoryKept by Step Functions, 90 days, in the consoleOnly what you send to CloudWatch Logs
Use it forLong or important processes: orders, approvals, anything a person might wait days onShort, high-volume work: processing each message from a queue or each API request

A failed Standard run can also be redriven: restarted from the step that failed, keeping everything before it, with redrive_execution. If order 7003's bank had been down rather than declining, a redrive after the outage would have finished the order without reserving the stock twice.

Take it down

In the console: delete the state machine, the payments function and its log group, the two roles, and the table.

BASH
python workflow-lab.py delete
OUTPUT
== Deleting the workflow (its run history goes with it)
== Deleting the payments function
== Deleted both roles
== Deleting the stock table
== Anything left from Lesson 24
  workflow jr-lesson24-take-an-order
  (a deleted workflow shows as DELETING for a short while)

A state machine shows as DELETING for a few seconds after it's deleted, and a new one with the same name can't be made until it's gone; python workflow-lab.py check a minute later reports "nothing: all clear". Deleting it also deletes its run history, so export anything you need to keep first.

By hand: the same lab with the AWS CLI

The workflow without the script. (Your machine) Save the full definition as workflow.json, from the script's definition() function or by copying it from the console's Code tab, with your own payments function's ARN, and the role's trust and permissions as trust.json and access.json.

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2

aws iam create-role --role-name jr-lesson24-workflow-role --assume-role-policy-document file://trust.json
aws iam put-role-policy --role-name jr-lesson24-workflow-role --policy-name lesson24 --policy-document file://access.json

aws stepfunctions validate-state-machine-definition --definition file://workflow.json --type STANDARD
SM_ARN=$(aws stepfunctions create-state-machine --name jr-lesson24-take-an-order --type STANDARD \
  --definition file://workflow.json --query stateMachineArn --output text \
  --role-arn "$(aws iam get-role --role-name jr-lesson24-workflow-role --query Role.Arn --output text)")

RUN=$(aws stepfunctions start-execution --state-machine-arn "$SM_ARN" --name order-7004 \
  --input '{"order": 7004, "item": "sourdough", "qty": 1, "card": "busy"}' --query executionArn --output text)
aws stepfunctions describe-execution --execution-arn "$RUN" --query '[status,output,error]'
aws stepfunctions get-execution-history --execution-arn "$RUN" --query 'events[].[type,timestamp]' --output table
aws stepfunctions list-executions --state-machine-arn "$SM_ARN" --query 'executions[].[name,status]' --output table

aws stepfunctions delete-state-machine --state-machine-arn "$SM_ARN"

trust.json lets Step Functions take on the role:

JSON
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "sts:AssumeRole",
  "Principal": {"Service": "states.amazonaws.com"}}]}

Run describe-execution again if it still says RUNNING; the busy bank takes about 7 seconds.

In real systems

  • Workflows are Terraform or AWS SAM, with the definition in its own file, reviewed like code (Lesson 28).
  • Every Retry has a maximum, and every workflow has a timeout, so nothing can run or bill forever.
  • Every step that changes something has an undo step, and every call outside AWS, like a bank, carries an idempotency key.
  • Error names are part of the design: callers and alarms act on OutOfStock and PaymentDeclined, not on message text.
  • Failed runs raise alarms through EventBridge, which receives an event when a run fails, or CloudWatch metrics (Lesson 32).
  • Steps call AWS services directly where they can, keeping Lambda for real logic, which means less code and fewer cold starts.
  • Long waits, like waiting for a person's approval, use a task token: the workflow pauses, for up to a year, until something calls back with the token.

Spot the problem

Work out what's wrong before you read the explanation.

"Our stock count keeps drifting down, but the shelves are full." The order workflow reserves stock, then takes payment. When the bank declines a card, the workflow fails with PaymentDeclined and the customer is told. Every week the stock count is lower than what's on the shelves. What's wrong? The reservation is never undone when payment fails, so every declined card permanently removes stock that's still there. The fix: catch PaymentDeclined on the payment step and go to a step that adds the stock back, then fail with a clear error. Then check: run an order with a declined card; is the stock the same before and after?

Keep this

RememberWhy
Write the workflow down, not in codeOrder, retries and clean-up you can see
Call services directly where you canThree of four tasks needed no code
Retry what might pass, Catch what won'tThe busy bank worked on try 3; the declined card went straight to clean-up
Every retry needs a maximumStandard workflows bill every step
Undo earlier steps when a later one failsThe croissants went back: 24 before, 24 after
Name your errorsCallers act on OutOfStock, not on messages
Check the role works before relying on itIt took 20 seconds and 4 tries
The history has every eventThe retries at 2 s and 4 s were all there
Standard for long and important; Express for short and manyDifferent limits, guarantees and prices

Where you are now

Taking an order at Juniper & Rye is now a workflow anyone can read: ten states, three of them calling DynamoDB with no code, and one calling a payments function. Five orders took five paths: a normal sale, a rye shortage caught before anything was reserved, a declined card whose croissants went back on the shelf, a busy bank that worked on the third try with waits of 2 and 4 seconds, and a nonsense order turned away at the door. Every run left a full history. Next, Lesson 25 brings in AI: calling a model in Amazon Bedrock from a Lambda function, and what that costs.

Check yourself

  1. Which steps in the lab ran without any Lambda function?

  2. Why did order 7003's croissant stock end where it started?

  3. The busy bank's retries came 2 s and then 4 s after each failure. Why?

  4. Why is PaymentDeclined caught rather than retried?

  5. The first runs in an earlier attempt failed at Look up stock. Why?

  6. Which workflow type suits processing each message from a busy queue in a second or two?

  7. How did the payments function know which try it was on?

Key terms

  • Step Functions: AWS's service for running workflows of steps.
  • State machine: a workflow's definition; an execution is one run of it.
  • Amazon States Language (ASL): the JSON a state machine is written in.
  • State: one step: Task, Choice, Pass, Wait, Parallel, Map, Succeed or Fail.
  • Service integration: a Task that calls an AWS service directly, without a function.
  • JSONPath and JSONata: two ways of reading and reshaping a workflow's data.
  • Retry: running a failed step again, with growing waits and a maximum.
  • Catch: going to another state when a step fails with a given error.
  • Compensating step: a step that undoes an earlier one when a later step fails; a chain of them is a saga.
  • Execution history: every event of a run, with times, inputs and outputs.
  • Context object: data about the run itself, like $$.State.RetryCount.
  • Standard and Express workflows: long-running, exactly-once and billed per step, or short, at-least-once and billed per run.
  • Redrive: restarting a failed Standard run from the step that failed.
  • Idempotency key: an ID sent with a request so repeats of it are ignored.

Go deeper