Lesson 1 of 3 AWS Step Functions

Coordinating Workflows with Step Functions State Machines

This lesson explains how AWS Step Functions coordinates services into a workflow, defined as a state machine in Amazon States Language (JSON), with error handling built in.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the state types and the role each plays in a state machine.
  • Explain how Retry and Catch rules handle errors without custom code.
  • Choose between Standard and Express workflows from a workflow's duration, volume and execution guarantees.
  • Distinguish the request-response, run a job and wait for callback integration patterns.

States

A Step Functions state machine is defined in the Amazon States Language, a JSON format in which each state performs one step and names the next. The state types fall into three groups.

A Task state does the work. It can invoke a Lambda function or call an AWS service directly, such as writing an item to DynamoDB or publishing to SNS, so many workflows need no Lambda code at all. Task states can declare their own retries and error handling.

Flow states control the path through the workflow. A Choice state branches by comparing values in the input, such as sending orders above a limit for approval. A Parallel state runs several branches at the same time and continues when all have finished. A Map state runs the same steps for each item in an array, such as each line of an order. A Wait state pauses for a duration or until a timestamp, without paying for idle compute.

A Pass state passes or reshapes its input without doing work, which is useful for testing and for injecting fixed data. Succeed and Fail end the execution with the corresponding status. The following table summarises the state types.

StatePurpose
TaskDoes work, such as invoking Lambda or calling an AWS service
ChoiceBranches based on the input
ParallelRuns branches at the same time
MapRuns the same steps for each item in a list
WaitPauses for a time or until a timestamp
Pass, Succeed, FailPass data through, or end the execution

States pass JSON from one step to the next. JSONata expressions, or the older InputPath, Parameters, ResultSelector, ResultPath and OutputPath fields, select and reshape it, and variables let later states reuse earlier results.

Match the pairs

State types

Exam skills 1.1.2

Match each Step Functions state type with what it does.

Log in to try this activity Interactive activities are free with an account.

Error handling

A Task state can declare Retry rules with exponential backoff and Catch rules that route errors to a fallback state, so error handling needs no custom code.

Example. Throttling and gateway timeouts are retried three times; other errors go to a compensating step. ResultPath keeps the input and adds the error beside it.

"ChargeCard": {
  "Type": "Task",
  "Resource": "arn:aws:states:::lambda:invoke",
  "Parameters": {"FunctionName": "arn:aws:lambda:eu-west-1:111122223333:function:charge-card", "Payload.$": "$"},
  "Retry": [{
    "ErrorEquals": ["Lambda.TooManyRequestsException", "PaymentGatewayTimeout"],
    "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 2.0
  }],
  "Catch": [{"ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "CancelOrder"}],
  "Next": "ShipOrder"
}

The following diagram shows the paths the ChargeCard task from the example above can take.

Retry and Catch on the ChargeCard task. Throttling and gateway timeout errors are retried three times, after 2, 4 and 8 seconds. On success the workflow continues to ShipOrder. Any other error, or a retryable error after the last retry, is caught and sent to CancelOrder, with the error stored in $.error beside the original input.
Retry rules are tried first; Catch rules handle an error that is not retried or that is still failing after the last retry.

Standard vs Express workflows

Step Functions offers two workflow types, chosen when the state machine is created.

A Standard workflow can run for up to a year and records every step in an execution history that can be inspected in the console. Each step runs exactly once unless the workflow's own retry settings repeat it. This makes Standard workflows suitable for business processes that wait for people or external systems, such as order fulfilment with a manual approval, and for steps that must not run twice. They are charged per state transition, so very high volumes become expensive.

An Express workflow runs for at most five minutes and is charged by the number of executions and their duration, which is far cheaper at high volume. It can process thousands of executions per second, for example transforming each incoming IoT message or API request. Asynchronous Express executions run at least once, so steps must be idempotent, while synchronous Express executions, which return the result to the caller, run at most once. Execution details are sent to CloudWatch Logs rather than kept in a history. The following table summarises the differences.

Standard
Maximum duration1 year
Execution guaranteeExactly once
PricingPer state transition
Best forLong-running business processes
Express
Maximum duration5 minutes
Execution guaranteeAt least once (async) or at most once (sync)
PricingPer request and duration
Best forHigh-volume event processing

Example. A three-day approval process must be Standard. Processing 5,000 IoT messages per second, each in under a second, suits Express.

1year

Maximum Standard workflow duration

5min

Maximum Express workflow duration

Sort into groups

Standard or Express?

Exam skills 1.1.2

Choose the workflow type from duration, volume and execution guarantees.

Log in to try this activity Interactive activities are free with an account.

Service integration patterns

When a Task state calls another service, its integration pattern decides when the workflow moves on.

With request-response, the default, Step Functions calls the service API and continues as soon as the call returns. Starting an ECS task this way moves on once the task has started, not when it finishes. With the run a job pattern, written by adding .sync to the resource ARN, Step Functions starts the job and waits until it completes, then passes its result to the next state; it is supported for long-running work such as ECS tasks, AWS Batch jobs, Glue jobs and nested Step Functions executions.

With the wait for a callback pattern, written as .waitForTaskToken, Step Functions sends a unique task token with the request and pauses until some other system returns that token with SendTaskSuccess or SendTaskFailure. This lets a workflow wait for a person to approve a request or for an external system to finish, without polling. A heartbeat or timeout setting stops the execution from waiting for ever. The following table summarises the three patterns.

PatternBehaviour
Request-response (default)Calls the service and moves on
.syncWaits for a job, such as an ECS task, Glue job or nested workflow, to finish
.waitForTaskTokenPauses until an external system returns the task token, for example human approval

Example. The token is sent to an approvals queue; the execution waits until the approval app returns it, or fails with States.HeartbeatTimeout after an hour.

"WaitForApproval": {
  "Type": "Task",
  "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
  "Parameters": {
    "QueueUrl": "https://sqs.eu-west-1.amazonaws.com/111122223333/approvals",
    "MessageBody": {"orderId.$": "$.orderId", "taskToken.$": "$$.Task.Token"}
  },
  "HeartbeatSeconds": 3600,
  "Next": "Fulfil"
}
# In the approval app, once a manager clicks "Approve":
sfn.send_task_success(taskToken=token, output=json.dumps({"approved": True}))

For very large datasets, such as millions of S3 objects or CSV rows, Distributed Map runs child executions in parallel at high concurrency.

Sort into groups

Which integration pattern?

Exam skills 1.1.2 · 1.2.4

Choose when a Task state should move on after calling a service.

Log in to try this activity Interactive activities are free with an account.
Worked example

Standard or Express?

The appropriate Step Functions workflow type depends on the duration and volume of the workflow. The following table identifies the type suited to several workflows and the reason in each case.

WorkflowTypeReason
Loan approval waiting up to 5 days for a managerStandardRuns up to a year; waits cost nothing
Validate and enrich 3,000 IoT readings per second, each in 200 msExpressHigh volume, short duration, priced per execution
Payment workflow that must never run a step twiceStandardExactly-once execution
A synchronous API that must answer within a few secondsExpress (synchronous)Returns the result to the caller

Standard workflows are priced per state transition and keep a full visual history; Express workflows are priced per execution and duration and log to CloudWatch. Choosing wrongly can multiply the cost: a high-volume Express workload run as Standard pays for every transition.

Check yourself

A workflow pauses for up to three days until a manager approves an order. Which workflow type and integration pattern fit?

Show answer

A Standard workflow, because Express workflows run for at most five minutes, with the wait-for-callback pattern (.waitForTaskToken), which pauses until the approval returns the task token.

Exam Tips

Remember for the exam

  • To coordinate several Lambda functions with retries and branching, use Step Functions rather than chaining functions.
  • A human approval step uses the task token callback pattern.
  • Long-running, exactly-once workflows are Standard; high-volume, short-lived workflows are Express.
  • To process millions of S3 objects in parallel, use Distributed Map.
  • To wait for an ECS task or Glue job to finish, use the .sync integration pattern.