SkillSprout
Chapter 8 · Lesson 4
Advanced
8 min read

Step Functions

Overview

AWS Step Functions is a serverless orchestration service that lets you coordinate multiple AWS services into visual workflows called state machines. Instead of chaining Lambda functions together with brittle code, you describe the steps, branching, retries, error handling and parallelism in a JSON-based language (Amazon States Language, ASL) or design it in the drag-and-drop Workflow Studio.

Each step is a state. Task states call Lambda, ECS/Fargate, Batch, Glue, SageMaker, DynamoDB, SQS, SNS, EventBridge and 200+ AWS services directly through service integrations, often with no Lambda glue code. Step Functions keeps track of the state, passes data between steps, retries failed steps and records a full execution history.

It is the right tool for long-running, multi-step, auditable processes such as order fulfilment, ETL pipelines, human-approval flows and saga transactions with compensation. On the exam you must know the Standard vs Express workflow types and when orchestration beats simple Lambda-to-Lambda calls or SQS.

Key Concepts

  • A state machine is defined in ASL (JSON); each execution runs one workflow instance with its own input, output and visual history.
  • State types: Task, Choice (branching), Parallel, Map (iterate over a list), Wait, Pass, Succeed, Fail.
  • Standard workflows: run up to 1 year, exactly-once execution, full history, priced per state transition; for long-running, auditable processes.
  • Express workflows: run up to 5 minutes, at-least-once (async) or at-most-once (sync), very high throughput (100,000+/s), priced by executions and duration; for high-volume event processing.
  • Service integrations: optimised (200+ AWS services, e.g. Lambda, DynamoDB, SNS, ECS) and AWS SDK integrations; request patterns Request-Response, Run a Job (.sync) and Wait for Callback (.waitForTaskToken).
  • Error handling: declarative Retry (interval, backoff, max attempts) and Catch (fallback states) on any Task state.
  • Human approval and long waits: Standard workflows can pause for days on a task token until an external system calls back.
  • Distributed Map processes millions of S3 objects in parallel (up to 10,000 child executions); invoked from API Gateway, EventBridge, SDKs, and console.

Detailed Notes

Standard vs Express workflows

StandardExpress
Max duration1 year5 minutes
Execution semanticsExactly-onceAt-least-once (async), at-most-once (sync)
Execution rate~2,000 starts/s (soft limit)100,000+/s
HistoryFull, in service (90 days) and consoleCloudWatch Logs only
PricingPer state transitionPer execution count + duration and memory
Callback / .sync patternsYesRequest-Response only
Use forOrder processing, ML pipelines, approvals, ETLIoT ingestion, streaming transforms, mobile backends, high-volume microservice glue

Amazon States Language

json
{
  "Comment": "Order fulfilment with retry and compensation",
  "StartAt": "ChargePayment",
  "States": {
    "ChargePayment": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "charge-payment", "Payload.$": "$" },
      "Retry": [{
        "ErrorEquals": ["Lambda.ServiceException", "States.Timeout"],
        "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 2.0
      }],
      "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "NotifyFailure" }],
      "Next": "InStock"
    },
    "InStock": {
      "Type": "Choice",
      "Choices": [{ "Variable": "$.inStock", "BooleanEquals": true, "Next": "ShipOrder" }],
      "Default": "RefundPayment"
    },
    "ShipOrder":     { "Type": "Task", "Resource": "arn:aws:states:::sqs:sendMessage",
                       "Parameters": { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/ship", "MessageBody.$": "$" },
                       "End": true },
    "RefundPayment": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke",
                       "Parameters": { "FunctionName": "refund-payment", "Payload.$": "$" }, "Next": "NotifyFailure" },
    "NotifyFailure": { "Type": "Fail", "Error": "OrderFailed", "Cause": "Payment or stock issue" }
  }
}

State types

StatePurpose
TaskDo work: invoke Lambda, call a service API, start a job
ChoiceIf/else branching on input values
ParallelRun branches simultaneously, wait for all
MapIterate over an array; Distributed Map for huge S3 datasets
WaitDelay for a duration or until a timestamp
PassTransform or inject data, useful for testing
Succeed / FailTerminate the execution

Integration patterns

  1. Request-Response (default): call a service and move on once the HTTP response returns.
  2. Run a Job (.sync): start a job (Batch, ECS task, Glue, EMR, CodeBuild) and wait for completion without polling code.
  3. Wait for Callback (.waitForTaskToken): pause until an external system or a person returns the task token with SendTaskSuccess / SendTaskFailure - used for human approval and legacy systems.

Error handling and the saga pattern

Use Retry with exponential BackoffRate and Catch to route failures. Combine with compensating steps (refund, release inventory) to implement the saga pattern, the idiomatic way to keep data consistent across microservices without distributed transactions.

Step Functions vs alternatives

NeedUse
Multi-step workflow with branching, retries, visibilityStep Functions
Simple decoupling, bufferingSQS
Fan-out notificationsSNS
Event routing by contentEventBridge
Workflow with Apache Airflow DAGsMWAA
Legacy human-task workflowStep Functions (callback), not SWF

Operations and security

  • Each state machine uses an IAM execution role; grant only the actions the states need.
  • Triggers: API Gateway, EventBridge, SDK, console, Lambda, CloudTrail events. Monitor with CloudWatch (ExecutionsFailed, ExecutionTime), X-Ray and the visual execution graph.
  • Standard history is limited to 25,000 events per execution; for very long loops use child executions or Distributed Map.

Real World Example

Scenario — a lending company automates loan applications.

Each application involves identity verification, a credit check with a third-party API, a risk-score Lambda, an optional manual underwriting step and, finally, document generation and funding. The old design chained Lambda functions with queues and had no clear view of where an application was stuck.

The company models the process as a Standard Step Functions workflow. A Parallel state runs identity and credit checks at the same time with Retry and Catch for flaky APIs. A Choice state sends risky applications to a .waitForTaskToken step where an underwriter approves through a web portal - the execution can wait for days at no compute cost. Approved loans continue to a Map state that generates and e-signs multiple documents in parallel, then funds the loan via a Lambda function. If funding fails, compensation states reverse earlier actions.

Auditors can see every step and its input and output in the execution history, and support staff find stuck applications at a glance.

Architecture Diagram

Order-processing workflow with Step Functions
Architecture
AWS Cloud
API Gatewaystart execution
EventBridgeor event trigger
Step Functions state machine
Standard workflowChoice / Parallel / Map
ValidateTask + Retry
Save stateSDK integration
Process job.sync (ECS/Batch)
Approval requestwaitForTaskToken
Fulfilment queue
Execution history

A state machine orchestrates parallel checks, branching, a human approval and compensation.

  1. 1An API call or event starts a state-machine execution with the order as JSON input.
  2. 2Task states call Lambda and AWS services directly, with Retry and Catch handling transient failures.
  3. 3A Choice state routes risky orders to a human approval step that pauses on a task token until someone responds.
  4. 4Successful orders continue to fulfilment; failures trigger compensating steps, and every step is recorded in the execution history.

Best Practices

  • ✓Use Step Functions for orchestration and keep Lambda functions small and single-purpose; do not chain Lambdas by calling each other.
  • ✓Prefer direct service integrations (DynamoDB, SQS, SNS, ECS, Glue) over wrapper Lambda functions to cut cost and latency.
  • ✓Add Retry with exponential backoff and Catch to every Task that calls an external or flaky dependency; add timeouts and heartbeats.
  • ✓Choose Standard for long-running, exactly-once, auditable flows and Express for high-volume, short, idempotent processing.
  • ✓Implement the saga pattern with compensation states for distributed transactions.
  • ✓Pass small payloads (256 KB limit); store large data in S3 and pass references, and use Distributed Map for large datasets.
  • ✓Use least-privilege execution roles, enable CloudWatch Logs and X-Ray, and deploy with SAM/CDK and version/alias state machines.
  • ✓Use .waitForTaskToken for human approvals and external callbacks instead of polling loops.

Common Interview Questions

Exam Tips

SAA-C03 focus

  • "Coordinate multiple Lambda functions/services with branching, retries and error handling" -> Step Functions (not SQS or SNS).
  • Standard = up to 1 year, exactly-once, priced per state transition. Express = up to 5 minutes, at-least-once, high rate, priced by executions and duration.
  • "Human approval / wait for external callback" -> Standard workflow with .waitForTaskToken. "Wait for a job to finish" -> .sync pattern.
  • "Process each item in a list" -> Map; "run steps at the same time" -> Parallel; "if/else" -> Choice; "delay" -> Wait.
  • Failures are handled declaratively with Retry and Catch in ASL; compensation logic implements the saga pattern.
  • Step Functions replaces the legacy SWF for new designs; MWAA is for Apache Airflow users.
  • Workflows are defined in Amazon States Language (JSON); payload limit is 256 KB; Standard history limit is 25,000 events.
  • Step Functions can call 200+ services directly (SDK integrations) without Lambda code and can be started by API Gateway, EventBridge or the SDK.

Chapter quiz

Serverless Architecture · 5 questions

  1. 1.A Lambda function processes messages from an Amazon SQS queue. Some messages take close to the function's 60-second timeout, and messages are being processed twice. What is the MOST likely fix?

  2. 2.A company exposes a public REST API through Amazon API Gateway backed by Lambda. The same read-only product data is requested thousands of times a minute and rarely changes. How can the solutions architect reduce backend load and latency with the LEAST effort?

  3. 3.A company needs to run a workflow lasting up to 3 days that includes a manual approval step performed by a manager before the process continues. The solution must be serverless and provide an audit trail of each step. Which service should be used?

  4. 4.A company wants to run a Lambda function every day at 02:00 UTC and also trigger a Lambda function whenever an EC2 instance changes state. Which single service can provide both capabilities without managing any servers?

  5. 5.A Lambda function in a private subnet must call a third-party API on the internet and read objects from Amazon S3 at the lowest cost and without exposing the function to inbound internet traffic. What should the architect do?

0 of 5 answered

Finished this lesson?

0 of 64 lessons done · 0% of the course