StackPractices
advanced By Mathias Paulenko

Orchestrate Serverless Workflows with AWS Step Functions

Build state machine workflows with AWS Step Functions using sequential, parallel, and map states to coordinate Lambda functions and long-running processes.

Overview

AWS Step Functions is Amazon’s managed orchestrator: you describe a workflow in Amazon States Language (ASL, a JSON dialect) and the service runs it — invoking Lambdas, branching on conditions, retrying failed tasks, and keeping state between steps for up to a year. The state machine lives server-side, so a crashed or timed-out Lambda doesn’t lose track of where the workflow was.

This recipe builds a complete order-processing workflow end to end: the ASL definition with retries and catches, parallel and map states, the SAM template that deploys it, the Python handlers, and the code that starts executions. If you’re still choosing an orchestrator rather than committing to AWS, the serverless orchestration recipe compares Step Functions against Temporal and Durable Functions — this recipe assumes you’ve already picked Step Functions and want working code.

Order workflow state machine: ValidateOrder feeds a choice on inventory; in-stock orders go through ProcessPayment and ShipOrder to completion, while failures route to notification states and a terminal OrderRejected fail state.

When to Use This

Reach for Step Functions when the work you’re coordinating has more structure than a single event handler can hold:

  • Multi-step processes that need coordination — order processing, ETL pipelines, user onboarding
  • Workflows with conditional branching and per-step error handling
  • Long-running processes (hours to days) that need the state persisted between steps
  • Batch processing where each item gets its own error handling via a Map state

It’s a poor fit for request/response paths that need sub-second latency — an extra state transition or two is cheap, but a synchronous API call chain usually belongs in a single Lambda or in API Gateway with a Lambda authorizer instead.

Prerequisites

  • Python 3.11+
  • AWS account with Step Functions and Lambda access
  • boto3 package
  • SAM CLI if you want to deploy the template in section 4

Solution

1. Order Processing State Machine (ASL Definition)

The core of the recipe: an order flows through validation, an inventory check, a conditional branch, payment, and shipping. Notice how ValidateOrder combines Retry (transient Lambda failures get three attempts with backoff) and Catch (a business-level OrderValidationError routes straight to rejection instead of retrying a permanently bad order).

{
  "Comment": "Process customer order workflow",
  "StartAt": "ValidateOrder",
  "States": {
    "ValidateOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder",
      "Next": "CheckInventory",
      "Retry": [
        {
          "ErrorEquals": ["States.TaskFailed"],
          "IntervalSeconds": 2,
          "MaxAttempts": 3,
          "BackoffRate": 2.0
        }
      ],
      "Catch": [
        {
          "ErrorEquals": ["OrderValidationError"],
          "Next": "OrderRejected"
        }
      ]
    },
    "CheckInventory": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:CheckInventory",
      "Next": "InventoryChoice"
    },
    "InventoryChoice": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.inStock",
          "BooleanEquals": true,
          "Next": "ProcessPayment"
        },
        {
          "Variable": "$.inStock",
          "BooleanEquals": false,
          "Next": "BackorderNotification"
        }
      ],
      "Default": "OrderRejected"
    },
    "ProcessPayment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessPayment",
      "Next": "ShipOrder",
      "Retry": [
        {
          "ErrorEquals": ["PaymentDeclinedError"],
          "IntervalSeconds": 5,
          "MaxAttempts": 2,
          "BackoffRate": 2.0
        }
      ],
      "Catch": [
        {
          "ErrorEquals": ["PaymentDeclinedError"],
          "Next": "PaymentFailed"
        }
      ]
    },
    "ShipOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ShipOrder",
      "Next": "OrderComplete"
    },
    "OrderComplete": {
      "Type": "Succeed"
    },
    "BackorderNotification": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:NotifyBackorder",
      "Next": "OrderRejected"
    },
    "PaymentFailed": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:NotifyPaymentFailed",
      "Next": "OrderRejected"
    },
    "OrderRejected": {
      "Type": "Fail",
      "Error": "OrderProcessingFailed",
      "Cause": "Order could not be processed"
    }
  }
}

Two things worth copying even if you change everything else: every external-facing task has a Retry for transient failures, and every terminal failure path converges on OrderRejected so the workflow ends in a predictable state instead of dying mid-graph.

2. Parallel Execution

When post-purchase work doesn’t depend on itself — sending the confirmation email, updating the CRM, generating the invoice — a Parallel state runs all three branches at once. The state only completes when every branch completes, and a failure in any branch fails the whole Parallel state (attach a Catch if a partial success is acceptable).

{
  "StartAt": "ProcessInParallel",
  "States": {
    "ProcessInParallel": {
      "Type": "Parallel",
      "Branches": [
        {
          "StartAt": "SendEmail",
          "States": {
            "SendEmail": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-east-1:123456789012:function:SendEmail",
              "End": true
            }
          }
        },
        {
          "StartAt": "UpdateCRM",
          "States": {
            "UpdateCRM": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-east-1:123456789012:function:UpdateCRM",
              "End": true
            }
          }
        },
        {
          "StartAt": "GenerateInvoice",
          "States": {
            "GenerateInvoice": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-east-1:123456789012:function:GenerateInvoice",
              "End": true
            }
          }
        }
      ],
      "Next": "Complete"
    },
    "Complete": {
      "Type": "Succeed"
    }
  }
}

Each branch gets the same input as the Parallel state itself, and the state’s output is an array with one result per branch — useful when the next step needs all three outcomes.

3. Map State for Batch Processing

Map iterates an array in the input and runs a sub-workflow per item. MaxConcurrency is the knob that protects whatever sits downstream — leave it unset and every item fires at once.

{
  "StartAt": "ProcessItems",
  "States": {
    "ProcessItems": {
      "Type": "Map",
      "ItemsPath": "$.items",
      "MaxConcurrency": 10,
      "Iterator": {
        "StartAt": "ProcessSingleItem",
        "States": {
          "ProcessSingleItem": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessItem",
            "End": true
          }
        }
      },
      "Next": "AllItemsProcessed"
    },
    "AllItemsProcessed": {
      "Type": "Succeed"
    }
  }
}

ItemsPath points at the array inside the state’s input ($.items here). For failure-tolerant batches, ItemProcessor with ToleratedFailurePercentage lets a few bad items fail without killing the run — worth enabling once you move past a demo dataset.

4. SAM Template with Step Functions

AWS::Serverless::StateMachine deploys the state machine alongside the functions. DefinitionSubstitutions keeps real ARNs out of the .asl.json file — the ASL references ${ValidateFunctionArn} placeholders and SAM fills them at deploy time, so the same definition file works across dev and prod stages.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  OrderWorkflow:
    Type: AWS::Serverless::StateMachine
    Properties:
      DefinitionUri: statemachine/order_workflow.asl.json
      DefinitionSubstitutions:
        ValidateFunctionArn: !GetAtt ValidateOrderFunction.Arn
        PaymentFunctionArn: !GetAtt ProcessPaymentFunction.Arn
        ShipFunctionArn: !GetAtt ShipOrderFunction.Arn
      Role: !GetAtt WorkflowRole.Arn
      Type: EXPRESS

  ValidateOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: validate.lambda_handler
      Runtime: python3.11
      CodeUri: src/

  ProcessPaymentFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: payment.lambda_handler
      Runtime: python3.11
      CodeUri: src/

  ShipOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: ship.lambda_handler
      Runtime: python3.11
      CodeUri: src/

The WorkflowRole needs lambda:InvokeFunction on each function ARN — scope it to the exact functions, not *, or the state machine becomes a privilege-escalation path.

5. Lambda Task Functions

Handlers stay deliberately thin: they read the state input, do one thing, and return the fields the next state needs. Errors are raised as exceptions whose names match the ErrorEquals entries in the ASL — that’s the contract between Python and the state machine.

import json

def validate_order_handler(event, context):
    order = event.get('order', {})
    items = order.get('items', [])
    customer = order.get('customer', {})

    if not items:
        raise Exception("OrderValidationError: No items in order")
    if not customer.get('email'):
        raise Exception("OrderValidationError: Customer email required")

    return {
        'orderId': order.get('id'),
        'valid': True,
        'itemCount': len(items),
        'total': sum(item['price'] * item['quantity'] for item in items),
    }

def check_inventory_handler(event, context):
    items = event.get('order', {}).get('items', [])
    all_in_stock = all(check_stock(item) for item in items)
    return {
        'orderId': event['orderId'],
        'inStock': all_in_stock,
        'items': items,
    }

def process_payment_handler(event, context):
    total = event.get('total', 0)
    payment_method = event.get('paymentMethod', {})

    result = charge_payment(payment_method, total)
    if not result['success']:
        raise Exception("PaymentDeclinedError: " + result['message'])

    return {
        'orderId': event['orderId'],
        'paymentId': result['paymentId'],
        'charged': total,
    }

Whatever a handler returns becomes the state output and the next state’s input. Keep payloads small — Standard workflows cap state payload at 256 KB, and dumping entire order histories into the state will hit that ceiling fast.

6. Start Execution from Lambda

An API-facing Lambda (or an SQS consumer — see serverless event-driven SQS + Lambda) kicks off the workflow with start_execution. Give every execution a unique name: Step Functions rejects duplicate names while an execution is still within its retention window, which makes retries idempotent for free.

import boto3
import json
import uuid

stepfunctions = boto3.client('stepfunctions')
STATE_MACHINE_ARN = 'arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow'

def start_order_workflow(order: dict) -> str:
    execution_name = f"order-{order['id']}-{uuid.uuid4().hex[:8]}"

    response = stepfunctions.start_execution(
        stateMachineArn=STATE_MACHINE_ARN,
        name=execution_name,
        input=json.dumps({
            'order': order,
            'paymentMethod': order.get('paymentMethod'),
        }),
    )

    return response['executionArn']

def check_execution_status(execution_arn: str) -> dict:
    response = stepfunctions.describe_execution(
        executionArn=execution_arn,
    )
    return {
        'status': response['status'],
        'output': json.loads(response.get('output', '{}')),
        'startDate': response.get('startDate'),
        'stopDate': response.get('stopDate'),
    }

Store the returned executionArn on the order record — it’s the handle you’ll need for describe_execution status polling or for surfacing the run in the Step Functions console during debugging.

7. Wait States and Human Approval

Wait pauses the workflow without burning compute — the classic pattern for approval steps. This example polls once an hour via a Wait + Choice loop: if approval hasn’t arrived, the Default branch loops back to WaitForApproval. Add a timeout path in production so an ignored request doesn’t keep the execution alive for a year.

{
  "StartAt": "SubmitForApproval",
  "States": {
    "SubmitForApproval": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:SubmitApproval",
      "Next": "WaitForApproval"
    },
    "WaitForApproval": {
      "Type": "Wait",
      "Seconds": 3600,
      "Next": "CheckApprovalStatus"
    },
    "CheckApprovalStatus": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:CheckApproval",
      "Next": "ApprovalChoice"
    },
    "ApprovalChoice": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.approved",
          "BooleanEquals": true,
          "Next": "ExecuteOrder"
        },
        {
          "Variable": "$.approved",
          "BooleanEquals": false,
          "Next": "RejectOrder"
        }
      ],
      "Default": "WaitForApproval"
    },
    "ExecuteOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ExecuteOrder",
      "End": true
    },
    "RejectOrder": {
      "Type": "Fail",
      "Error": "OrderRejected",
      "Cause": "Approval denied"
    }
  }
}

For event-driven approval (a manager clicks “approve” in a UI), the callback pattern with waitForTaskToken beats polling: the task pauses until an external call returns the token, so there’s no hourly delay and no wasted Lambda invocations.

How It Works

  1. State machine: a JSON-defined workflow in Amazon States Language. Each state is a step — Task (invoke a Lambda or service), Choice (branch), Parallel (fan out), Map (iterate), Wait (delay), Pass (reshape data), Succeed, or Fail.
  2. Task states: call a Lambda function or another AWS service. The function gets the state input as its event and its return value becomes the next state’s input.
  3. Choice states: evaluate conditions against the input — string, numeric, boolean, and timestamp comparisons — and route to the matching Next, falling back to Default.
  4. Parallel states: run branches concurrently. The state completes only when every branch does, and any branch failure fails the whole state unless caught.
  5. Map states: run a sub-workflow per array element, with MaxConcurrency capping parallelism so downstream services aren’t stampeded.
  6. Retry/Catch: Retry re-runs a failed task with exponential backoff for transient errors (States.TaskFailed, States.Timeout, throttling). Catch routes to an error-handling state for business errors — retries won’t fix a declined card.

The pieces from this recipe — handlers, ASL file, SAM template, and a start-execution script — are also bundled as a runnable project in the companion repo.

Variants

Express Workflow (High-Throughput)

OrderWorkflow:
  Type: AWS::Serverless::StateMachine
  Properties:
    Type: EXPRESS
    # Express workflows: up to 100,000 executions/second
    # Max duration: 5 minutes
    # Lower cost per execution
    # No execution history persistence (limited to 90 days via CloudWatch)

Standard Workflow (Long-Running)

OrderWorkflow:
  Type: AWS::Serverless::StateMachine
  Properties:
    Type: STANDARD
    # Standard workflows: up to 2,000 executions/second
    # Max duration: 1 year
    # Full execution history
    # At-least-once execution guarantee

Service Integrations (No Lambda Needed)

For calls that don’t need custom logic, Step Functions talks to AWS services directly via arn:aws:states::: resource ARNs — a DynamoDB put or an SNS publish never touches Lambda, so there’s no function to maintain and nothing to pay for between state transitions.

{
  "StartAt": "PutItem",
  "States": {
    "PutItem": {
      "Type": "Task",
      "Resource": "arn:aws:states:::dynamodb:putItem",
      "Parameters": {
        "TableName": "OrdersTable",
        "Item": {
          "orderId": {"S.$": "$.orderId"},
          "status": {"S": "PENDING"}
        }
      },
      "Next": "SendNotification"
    },
    "SendNotification": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "TopicArn": "arn:aws:sns:us-east-1:123456789012:OrderTopic",
        "Message.$": "$.orderId"
      },
      "End": true
    }
  }
}

The DynamoDB example pairs naturally with a single-table design — see serverless DynamoDB single-table design for the table layout that makes order records like this cheap to query.

Best Practices

  • Use Express for high-throughput, short workflows: cheaper and faster for event-driven processing under 5 minutes.
  • Use Standard for long-running workflows: persists state for up to a year with full history and at-least-once execution.
  • Define Retry for transient errors: throttling and network timeouts are transient; retry with backoff (IntervalSeconds=2, BackoffRate=2.0, MaxAttempts=3).
  • Use Catch for business errors: declined payments and validation failures aren’t transient — route them to error-handler states.
  • Keep Lambda functions small: each Task does one thing. Complex routing logic belongs in the state machine, not in a monolithic function.
  • Use DefinitionSubstitutions in SAM: never hardcode ARNs in the ASL definition; let SAM resolve placeholders per stage.

For the wider architectural picture — event sources, data layers, and where orchestration fits — the complete guide to serverless architecture covers the surrounding patterns.

Common Mistakes

  • Using Lambda for everything: direct service integrations (DynamoDB, SNS, SQS, S3) replace boilerplate wrapper functions entirely.
  • No Retry on task failures: a throttled DynamoDB call will fail an execution that a three-line Retry would have saved.
  • Catching all errors: States.ALL also swallows bugs in your code. Catch specific error names so programming errors still fail loudly.
  • Overusing Parallel for independent tasks: if branches don’t need concurrency, sequential states are simpler and cheaper per execution.
  • Skipping MaxConcurrency on Map: an unbounded Map can fire thousands of concurrent Lambdas and overwhelm the downstream service you were protecting with a queue.
  • Hardcoding ARNs in ASL: the definition then needs editing per environment; DefinitionSubstitutions keeps it stage-agnostic.

References

Frequently Asked Questions

Standard vs Express workflows — which should I use?

Use Express for short (< 5 min), high-throughput (> 2,000/sec) event-driven workflows. Use Standard for long-running (up to 1 year) stateful workflows that need full execution history and at-least-once guarantees.

How does Step Functions handle failures?

Each Task can have Retry (re-execute with backoff) and Catch (route to an error handler). If a Task fails and has no Catch, the whole execution fails. Failed Standard executions can be restarted from the failed state.

Can I update a running state machine?

You can update the definition, but running executions keep the old one. New executions pick up the update; to change a running execution you've got to restart it.

What is the maximum execution duration?

Standard: 1 year. Express: 5 minutes. For longer processes, chain state machines or use Standard with Wait states.

How much does Step Functions cost?

Standard: $0.025 per 1,000 state transitions. Express: $0.025 per 1,000 invocations plus $0.003 per 1,000 GB-seconds of duration. Express is cheaper for short workflows with few states — check current Step Functions pricing since rates change.