SkillSprout
Chapter 4 · Lesson 3
Advanced
6 min read

AWS Step Functions and Workflow Orchestration

Overview

AWS Step Functions lets you coordinate multiple services into a state machine: a visual, JSON-defined workflow with branching, parallel work, retries, error handling and waits. Instead of burying orchestration logic inside Lambda functions calling each other, the workflow itself becomes explicit, observable and durable.

Think of an airport check-in process: check the ticket, then in parallel weigh baggage and verify the passport, wait for security approval, and route problems to a desk. Step Functions is the process manager that remembers where each passenger is, even if a counter is closed for a while.

You write the definition in Amazon States Language (ASL), and Step Functions calls Lambda, DynamoDB, SQS, SNS, ECS, Glue and 200+ services directly via SDK integrations, often without any glue code.

Key Concepts

  • Standard workflows: up to 1 year, exactly-once execution, full history, priced per state transition. Express workflows: up to 5 minutes, at-least-once (async) or at-most-once (sync), very high rate, priced per execution and duration.
  • State types: Task, Choice, Wait, Parallel, Map, Pass, Succeed, Fail.
  • Retry (with IntervalSeconds, BackoffRate, MaxAttempts) and Catch handle errors declaratively per state.
  • Service integrations: request-response, .sync (wait for job to finish) and .waitForTaskToken (callback pattern for humans/external systems).
  • Map processes arrays; Distributed Map handles millions of S3 objects at high concurrency.
  • Data flows via InputPath, Parameters, ResultSelector, ResultPath, OutputPath, and JSONata or intrinsic functions.
  • Workflows can be invoked by API Gateway, EventBridge, SDK, Lambda or schedule; Synchronous Express returns the result.
  • Use Step Functions to orchestrate long-running or human-approval work Lambda cannot handle (15-minute limit).

Detailed Notes

Standard vs Express

FeatureStandardExpress
Max duration1 year5 minutes
Execution semanticsExactly-onceAt-least-once (async), at-most-once (sync)
Execution historyIn service (90 days) and CloudWatchCloudWatch Logs only
Rate~2,000 starts/s100,000+/s
PricingPer state transitionPer request and duration
Best forOrder processing, approvals, ETLHigh-volume streaming, IoT, API backends

A workflow in ASL

json
{
  "StartAt": "ValidateOrder",
  "States": {
    "ValidateOrder": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "arn:aws:lambda:eu-west-1:111122223333:function:Validate", "Payload.$": "$" },
      "ResultSelector": { "valid.$": "$.Payload.valid" },
      "ResultPath": "$.validation",
      "Retry": [{
        "ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
        "IntervalSeconds": 2, "BackoffRate": 2.0, "MaxAttempts": 4
      }],
      "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "NotifyFailure" }],
      "Next": "IsValid"
    },
    "IsValid": {
      "Type": "Choice",
      "Choices": [{ "Variable": "$.validation.valid", "BooleanEquals": true, "Next": "ChargeAndShip" }],
      "Default": "NotifyFailure"
    },
    "ChargeAndShip": {
      "Type": "Parallel",
      "Branches": [
        { "StartAt": "Charge", "States": { "Charge": { "Type": "Task", "Resource": "arn:aws:states:::dynamodb:putItem",
          "Parameters": { "TableName": "Charges", "Item": { "id": { "S.$": "$.orderId" } } }, "End": true } } },
        { "StartAt": "Ship", "States": { "Ship": { "Type": "Task", "Resource": "arn:aws:states:::sqs:sendMessage",
          "Parameters": { "QueueUrl": "https://sqs.eu-west-1.amazonaws.com/111122223333/ship", "MessageBody.$": "States.JsonToString($)" }, "End": true } } }
      ],
      "End": true
    },
    "NotifyFailure": {
      "Type": "Task", "Resource": "arn:aws:states:::sns:publish",
      "Parameters": { "TopicArn": "arn:aws:sns:eu-west-1:111122223333:alerts", "Message": "Order failed" },
      "End": true
    }
  }
}

Without Retry/Catch, a failing Task fails the whole execution. Common error names: States.ALL, States.Timeout, States.TaskFailed, States.Runtime.

Integration patterns

PatternResource suffixBehaviour
Request-response(none)Call API, continue immediately
Run a job.syncWait until job completes (Batch, ECS, Glue, nested workflow)
Callback.waitForTaskTokenPause until SendTaskSuccess/SendTaskFailure with the token
python
import boto3
sfn = boto3.client("stepfunctions")
# A manager clicks "approve" in a web app:
sfn.send_task_success(taskToken=token, output='{"approved": true}')

Starting executions

bash
aws stepfunctions start-execution \
  --state-machine-arn arn:aws:states:eu-west-1:111122223333:stateMachine:OrderFlow \
  --name order-42 --input '{"orderId":"42"}'

Standard execution names are unique for 90 days, giving idempotent starts.

Saga pattern

For distributed transactions, add compensating states in Catch blocks (for example refund payment when shipping fails) instead of attempting a distributed ACID transaction.

SAM definition

yaml
OrderFlow:
  Type: AWS::Serverless::StateMachine
  Properties:
    DefinitionUri: statemachine/order.asl.json
    Type: STANDARD
    Policies:
      - LambdaInvokePolicy: { FunctionName: !Ref ValidateFn }

Step Functions vs alternatives

NeedUse
Multi-step workflow with branching, retries, waitsStep Functions
Simple async decouplingSQS / SNS
Pure event routingEventBridge
Large ETL DAG with PythonMWAA (Airflow)

Error handling in Amazon States Language

json
{
  "StartAt": "Charge",
  "States": {
    "Charge": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "charge-card", "Payload.$": "$" },
      "TimeoutSeconds": 30,
      "Retry": [{ "ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
                  "IntervalSeconds": 2, "MaxAttempts": 4, "BackoffRate": 2.0 }],
      "Catch": [{ "ErrorEquals": ["PaymentDeclined"], "ResultPath": "$.error", "Next": "NotifyCustomer" }],
      "Next": "Fulfil"
    },
    "NotifyCustomer": { "Type": "Task", "Resource": "arn:aws:states:::sns:publish",
      "Parameters": { "TopicArn": "arn:aws:sns:eu-west-1:111122223333:alerts", "Message.$": "$.error" }, "End": true },
    "Fulfil": { "Type": "Succeed" }
  }
}

Retry runs before Catch; ResultPath controls where results or errors are merged into the state input.

State types and integration patterns

StatePurpose
TaskDo work (Lambda, SDK integration to 200+ services)
ChoiceBranch on input
Parallel / MapRun branches or iterate over items (Distributed Map for millions of S3 objects)
WaitDelay for a time or until a timestamp
Pass / Fail / SucceedShape data or end

Integration patterns: Request-Response (continue immediately), Run a Job (.sync) (wait for completion, for example Batch, ECS or Glue), and Wait for Callback (.waitForTaskToken) for human approval or external systems. Standard workflows last up to one year with exactly-once execution and are billed per state transition; Express workflows run up to five minutes at very high rates with at-least-once (async) or at-most-once (sync) semantics and are billed by duration. Start workflows from API Gateway, EventBridge or StartExecution, and inspect failures in the execution history.

Real World Example

An insurance company processes claims that need document extraction, a fraud check, and a human adjuster approval that may take days. They built a Standard workflow: Textract and fraud Lambdas run in a Parallel state, a waitForTaskToken step emails the adjuster with a link, and a Catch branch triggers compensating actions and an SNS alert. Previously this lived in cron jobs and a status table; now every claim has a visual execution history that auditors can inspect.

Architecture Diagram

Order workflow state machine
Architecture
AWS Step Functions
Startevent / API
ValidateRetry + Catch

Parallel

Charge
Ship
Notify failure

A Standard workflow validates, runs parallel work, and handles errors declaratively.

  1. 1An event or API call starts an execution with the order as input.
  2. 2The Validate task retries transient errors and catches failures.
  3. 3A Choice state routes valid orders to Parallel branches.
  4. 4Failures route to a notification state; the execution records every step.

Best Practices

  • ✓Prefer direct SDK integrations over Lambda glue functions.
  • ✓Define Retry with backoff and Catch for every Task that can fail.
  • ✓Use Express for high-volume short flows, Standard for long or auditable ones.
  • ✓Pass small payloads (256 KB limit); store large data in S3 and pass references.
  • ✓Use .waitForTaskToken instead of polling loops for human or external steps.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Workflow longer than 15 minutes or with human approval -> Step Functions Standard.
  • Wait for a job to complete -> .sync integration.
  • Orchestration with retries/branching and no custom code -> Step Functions.
  • State input limit 256 KB; use ResultPath to merge results.

Finished this lesson?

0 of 46 lessons done · 0% of the course