Skip to content
Visual explainer 3h to learn 5 steps

Orchestrate multi-step work with Step Functions

Model retries, durable state and compensation in a state machine and say when a queue-driven worker is simpler.

By Invicly Tech, , in AWS Cloud Engineering. About 11 minutes to read.

Topic 20 of 38

In short

AWS Step Functions runs a workflow defined as a state machine in Amazon States Language, a JSON format. Each state does one thing, such as calling Lambda or writing to DynamoDB, and Step Functions keeps the workflow's state, retries failed steps and can run compensation steps when something cannot be fixed. For a single step, a queue and a worker are often simpler.

Think of it like this: A state machine is a recipe card with a checklist: the kitchen manager ticks each step, retries what burnt, and knows how to undo a half-made dish.

Explained simply

Some jobs are not one step but several. To process an upload, you might check the file, reserve some of the user's quota, process it, save the result and notify the user. If step four fails, you may need to undo step two. Keeping track of that in your own code gets messy fast.

AWS Step Functions keeps track for you. You draw the steps as a state machine, written in a JSON format called Amazon States Language. Step Functions runs each state, passes data along, waits when told and records every step in an execution history you can inspect.

Errors are handled in the definition. A Retry block says which errors to try again, how many times and how long to wait. A Catch block says where to go when an error cannot be fixed, such as a step that releases the reserved quota. Undoing earlier work like this is called compensation.

Step Functions is not always the answer. If the job is one step that can simply be run again, a queue and a worker are cheaper and easier. Choose a workflow when you have several steps, branches, long waits, human approvals or undo steps to manage.

Press Play on a diagram to walk through it one step at a time.

FlowA file-processing workflow with compensation
  1. 1
    Validate file

    Task: Lambda, retry on throttling

  2. 2
    Reserve quota

    Task: DynamoDB conditional update

  3. 3
    Process file

    Task: Lambda or ECS, retry with backoff

  4. 4
    Save result

    Task: DynamoDB PutItem

  5. 5
    On failure: release quota

    Catch runs the compensating step, then Fail

CompareQueue worker vs Step Functions
SQS and a worker
  • One step, retried as a whole
  • Retries and DLQ from the queue
  • State lives in your database
  • Cheapest and simplest
Step Functions
  • Many steps, branches and waits
  • Retry and Catch per step
  • Workflow state kept for you
  • Visual history for debugging

In depth

States and how data flows

A state machine has a StartAt state and a set of named states. Task states do work. Choice states branch on data. Wait states pause for a time or until a timestamp. Parallel runs branches at once, and Map runs the same steps for each item in a list. Pass, Succeed and Fail shape data or end the run. Each state gets JSON input and produces JSON output. With the classic JSONPath style, InputPath, Parameters, ResultSelector, ResultPath and OutputPath choose which parts go in and out; newer definitions can use JSONata expressions instead. Optimized integrations let a Task call services such as DynamoDB, SQS, SNS, ECS or Lambda directly, so you often need no glue Lambda function at all.

  • Task: call a service
  • Choice: branch
  • Wait: pause
  • Parallel and Map: run several at once
  • Succeed and Fail: end

Retry and Catch in detail

A Retry entry lists ErrorEquals and how to retry: IntervalSeconds (default 1), MaxAttempts (default 3) and BackoffRate (default 2.0), plus optional MaxDelaySeconds and JitterStrategy FULL to spread retries out. Retriers are checked in order and the first match is used. When retries run out, or for errors with no retrier, Catch entries are checked; the first match moves the run to its Next state. Use ResultPath such as $.error to keep the original input and add the error to it. Built-in error names include States.ALL, States.Timeout, States.TaskFailed and States.Permissions. Only retry errors that might go away, such as throttling or timeouts. Validation errors should go straight to Catch.

FlowWhat happens when a task fails
  1. 1
    Task error

    For example Lambda.TooManyRequestsException

  2. 2
    Match a retrier

    First Retry entry whose ErrorEquals fits

  3. 3
    Wait and retry

    1 s, 2 s, 4 s with BackoffRate 2.0

  4. 4
    Retries exhausted

    Check Catch entries in order

  5. 5
    Go to fallback

    Compensate, then Fail or continue

Compensation: the saga pattern

Distributed steps cannot share one database transaction. The saga pattern gives each step that changes something an opposite step that undoes it. Reserve quota is paired with release quota, charge card with refund, create record with mark cancelled. If a later step fails, the Catch path runs the compensating steps for everything that already succeeded, in reverse order, and then ends in Fail so the failure stays visible. Compensations must be idempotent and should have their own Retry, because they can fail too. Durable state matters here: Step Functions remembers exactly which steps finished, even if a run lasts days, so the right undo steps run.

Standard vs Express, and when a queue is simpler

Standard workflows can run for up to one year, execute each workflow exactly once, keep a full visual history and support waiting for callbacks such as human approval. They are billed per state transition. Express workflows run for up to five minutes, are billed by number of requests and duration, suit high-volume event processing, and send their history to CloudWatch Logs if you enable it. Asynchronous Express runs are at-least-once, and synchronous ones at-most-once. A queue-driven worker beats both when the job is a single idempotent step: SQS gives retries and a DLQ, and there is no extra service to learn or pay for.

  • Standard: up to 1 year, exactly-once, per transition pricing
  • Express: up to 5 minutes, per request and duration
  • Callbacks with .waitForTaskToken for approvals
  • Single idempotent step: use SQS and a worker

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Define states in a state machine~35m
  2. 2
    Retry transient errors~35m
  3. 3
    Catch failures and compensate~35m
  4. 4
    Compare Standard and Express~35m
  5. 5
    Compare with a queue worker~35m

Key points

  • Retry handles transient errors with IntervalSeconds, MaxAttempts and BackoffRate.
  • Catch sends unrecoverable errors to a fallback state, where you undo earlier steps.
  • Standard workflows run up to one year with exactly-once workflow execution and a full history.
  • Express workflows run up to five minutes, cost less at high volume and have at-least-once or at-most-once semantics.
  • Choose a queue worker for one step; choose Step Functions when several steps, waits or rollbacks must be tracked.

Key terms

Tap a card to flip it. 0/5 known

Examples

json
"ProcessFile": {
  "Type": "Task",
  "Resource": "arn:aws:states:::lambda:invoke",
  "Parameters": { "FunctionName": "process-file", "Payload.$": "$" },
  "Retry": [{
    "ErrorEquals": ["Lambda.TooManyRequestsException", "States.Timeout"],
    "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 2.0
  }],
  "Catch": [{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "ReleaseQuota" }],
  "Next": "SaveResult"
}

Retries wait 2, 4 and 8 seconds; anything still failing goes to the compensating ReleaseQuota state.

A file workflow with retry and compensation

The machine reserves quota in DynamoDB, and processes the file with Lambda. ProcessFile retries throttling and timeouts with backoff. Any error after the reservation goes to ReleaseQuota, which adds the quota back, then to a Fail state. Evidence: start an execution with a broken file key and see, in the console graph, ProcessFile retried three times, then ReleaseQuota and Failed. Step Functions Standard has a small monthly free allowance of state transitions; check current pricing. For a design-only run, validate the definition and use the TestState API on single states.

json
{"StartAt": "ReserveQuota", "States": {
 "ReserveQuota": {"Type": "Task", "Resource": "arn:aws:states:::dynamodb:updateItem",
   "Parameters": {"TableName": "Quota", "Key": {"pk": {"S.$": "$.user"}},
     "UpdateExpression": "SET used = used + :one", "ConditionExpression": "used < #lim",
     "ExpressionAttributeNames": {"#lim": "limit"},
     "ExpressionAttributeValues": {":one": {"N": "1"}}},
   "ResultPath": null, "Next": "ProcessFile"},
 "ProcessFile": {"Type": "Task", "Resource": "arn:aws:states:::lambda:invoke",
   "Parameters": {"FunctionName": "process-file", "Payload.$": "$"},
   "Retry": [{"ErrorEquals": ["Lambda.TooManyRequestsException", "States.Timeout"], "MaxAttempts": 3, "BackoffRate": 2.0}],
   "Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "ReleaseQuota"}],
   "End": true},
 "ReleaseQuota": {"Type": "Task", "Resource": "arn:aws:states:::dynamodb:updateItem", "Parameters": {"TableName": "Quota", "Key": {"pk": {"S.$": "$.user"}}, "UpdateExpression": "SET used = used - :one", "ExpressionAttributeValues": {":one": {"N": "1"}}}, "ResultPath": null, "Next": "Failed"},
 "Failed": {"Type": "Fail", "Error": "ProcessingFailed"}}}

Deciding: workflow or queue for thumbnails

Requirement: make a thumbnail for every uploaded image. Step 1: count the steps. There is one: read image, resize, write thumbnail. Step 2: can it be retried as a whole? Yes, writing the same thumbnail twice is harmless. Step 3: are there waits, approvals or undo steps? No. Decision: an SQS queue with a Lambda consumer and a DLQ. Contrast: publishing a video needs transcode, human review that may take days, and removal of the draft if rejected. That has waits and compensation, so it becomes a Standard workflow with a callback task for the review.

Quick reference

  • Retry defaults: IntervalSeconds 1, MaxAttempts 3, BackoffRate 2.0
  • Catch with ResultPath $.error keeps the input and adds the error
  • States.ALL matches every error; put it last
  • Standard: up to 1 year, exactly-once; Express: up to 5 minutes, high volume
  • Optimized integrations call DynamoDB, SQS, SNS, ECS and Lambda without glue code
  • Saga: each changing step gets an idempotent undo step run from Catch
  • One idempotent step? Use SQS and a worker instead

Common mistakes

  • Retrying every error, including bad input that will never succeed, which wastes time and money.
  • Forgetting ResultPath on Catch, so the error object replaces the workflow's input data.
  • Using a Standard workflow for millions of tiny, short events where Express is far cheaper.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A Retry has IntervalSeconds 2, MaxAttempts 3 and BackoffRate 2.0. How long are the waits before each retry?

Question 2

2What happens to the state's input when a Catch has no ResultPath?

Question 3

3A workflow waits up to three days for a human approval. Which type fits?

Question 4

4Which error should normally go straight to Catch rather than be retried?

Question 5

5In the saga pattern, what should a compensating step be?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a Retry block that retries only States.Timeout and Lambda.ServiceException up to 4 times, starting at 3 seconds, doubling, with full jitter.

  2. Exercise 2medium

    A workflow does: create order record, charge card, reserve stock, send email. List the compensating step for each changing step and the order they run if reserving stock fails.

  3. Exercise 3hard

    Your Express workflow processes 2 million short events a day but some must wait 10 minutes for an external system. Propose a design.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need Lambda to use Step Functions?
No. Optimized and SDK integrations let tasks call many AWS services directly, such as DynamoDB, SQS, SNS, ECS and Glue.
How much does Step Functions cost?
Standard workflows are priced per state transition and Express workflows per request and duration. There is a small monthly free allowance; check the current pricing page.
Can I test a state machine without running the whole thing?
Yes. The TestState API runs a single state with input you supply, which is useful for checking data paths, retries and error handling.
Is Step Functions the same as a message queue?
No. A queue stores messages for workers to pull. Step Functions coordinates several steps and keeps the state of each run.

Go deeper

ShareXLinkedInWhatsApp