Skip to content
WritingArticle
  • #serverless
  • #aws
  • #step-functions
  • #lambda
  • #workflows

AWS Step Functions for Beginners: Build a Workflow with Retries, Waits and Error Handling

Pawan Joshi

8 min read

Share
Cover image for “AWS Step Functions for Beginners: Build a Workflow with Retries, Waits and Error Handling”

Some jobs are a series of steps: do this, then that, wait, retry if it fails, and tell someone at the end. You can glue those steps together with code, but the glue grows into the most fragile part of your system.

AWS Step Functions does the glue for you. You describe the steps as a state machine, and Step Functions runs them, retries failures, waits when you ask, and records every run so you can see exactly what happened.

Quick summary

  • Step Functions runs a list of steps (a state machine) and handles ordering, retries, waits and error paths for you.
  • Retry handles temporary failures, Catch handles permanent ones, and Map loops over a list at a speed you control.
  • Use Standard workflows for long, important processes and Express for short, high-volume jobs.

What Step Functions is, in plain words

A state machine is a list of steps (called states) and the rules for moving between them. Each step can:

  • Call a service, such as a Lambda function, DynamoDB, SQS or Amazon SES.
  • Make a decision, such as "if the score is above 80, go to Pass".
  • Wait, for a few seconds or until a date.
  • Run things in parallel or loop over a list.

You write it in JSON (Amazon States Language) or draw it in Workflow Studio, the visual editor in the AWS console.

When to use it

Use Step Functions whenUse plain Lambda or a queue when
Steps must run in orderIt's a single short task
You need retries with backoff per stepOne retry policy for the whole job is enough
You need to wait minutes, hours or daysThe work finishes in seconds
You want a visual history of every runYou only need logs
Several services are involvedOne function does everything

The example: issuing workshop certificates

After a workshop, we want to:

  1. Fetch the attendees who checked in.
  2. For each attendee, generate a PDF certificate and email it.
  3. Retry if the email service is busy.
  4. Record who got their certificate and who failed.
  5. Notify the organizer with a summary.

Here is the whole workflow on one page. Keep this picture in mind as you read the JSON below.

Flow diagram of the certificate workflow: FetchAttendees, then a Map state that runs IssueCertificate and a one second pause for each attendee, five at a time, then NotifyOrganizer and a Succeed stateThe certificate workflow: fetch the list, loop over attendees five at a time, then notify the organizer.

Step 1: Understand the state types we'll use

StateWhat it does in our workflow
TaskCalls a Lambda function, for example "fetch attendees"
MapRuns the same steps for every attendee in a list
WaitPauses so we don't hit the email provider too fast
PassRecords a failed attendee without calling anything
SucceedEnds the run with a clear result

Step Functions also has a Choice state for if/else branches and a Parallel state for running different branches at the same time. We don't need them here.

Step 2: Write the state machine

{
  "Comment": "Issue workshop certificates",
  "StartAt": "FetchAttendees",
  "States": {
    "FetchAttendees": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "${FetchAttendeesFn}", "Payload.$": "$" },
      "ResultSelector": { "attendees.$": "$.Payload.attendees" },
      "Next": "IssueEach"
    },
    "IssueEach": {
      "Type": "Map",
      "ItemsPath": "$.attendees",
      "MaxConcurrency": 5,
      "ItemProcessor": {
        "ProcessorConfig": { "Mode": "INLINE" },
        "StartAt": "IssueCertificate",
        "States": {
          "IssueCertificate": {
            "Type": "Task",
            "Resource": "arn:aws:states:::lambda:invoke",
            "Parameters": { "FunctionName": "${IssueCertificateFn}", "Payload.$": "$" },
            "Retry": [
              {
                "ErrorEquals": ["Lambda.TooManyRequestsException", "States.Timeout", "ProviderBusy"],
                "IntervalSeconds": 2,
                "BackoffRate": 2,
                "MaxAttempts": 4,
                "JitterStrategy": "FULL"
              }
            ],
            "Catch": [
              { "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "MarkFailed" }
            ],
            "ResultSelector": { "status": "issued" },
            "Next": "Pause"
          },
          "MarkFailed": {
            "Type": "Pass",
            "Parameters": { "status": "failed", "email.$": "$.email" },
            "Next": "Pause"
          },
          "Pause": { "Type": "Wait", "Seconds": 1, "End": true }
        }
      },
      "ResultPath": "$.results",
      "Next": "NotifyOrganizer"
    },
    "NotifyOrganizer": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "${NotifyFn}", "Payload.$": "$" },
      "Next": "Done"
    },
    "Done": { "Type": "Succeed" }
  }
}

Read it top to bottom and it describes the process in order. A few parts deserve a closer look.

Retry: automatic, with backoff

The Retry block on IssueCertificate says: if Lambda is throttled, the step times out, or our function throws a ProviderBusy error, try again. The first retry waits about 2 seconds, then 4, then 8, then 16. MaxAttempts: 4 means up to four retries after the first call, so five calls in total. JitterStrategy: FULL picks a random wait up to each limit, so all attendees don't retry at the same moment.

Timeline of one task: the first try and four retries with maximum waits of 2, 4, 8 and 16 seconds, success at any attempt continues to the next state, and failure of all attempts goes to CatchEach retry waits longer than the last, and a random jitter spreads the retries out.

You throw a named error from Lambda simply by setting the error's name:

export const handler = async (attendee) => {
  const response = await sendCertificate(attendee);
  if (response.status === 429) {
    const error = new Error("Email provider is busy");
    error.name = "ProviderBusy";   // Step Functions matches this name in Retry
    throw error;
  }
  return { email: attendee.email };
};

Catch: fail one attendee, not the whole run

If an attendee still fails after all retries, Catch sends them to MarkFailed instead of crashing the workflow. The other attendees keep going.

Diagram of the IssueCertificate state: success goes to a Wait state, temporary errors loop back as retries, and errors that remain after retries are caught and sent to MarkFailed, which also continues to WaitInside one attendee's run: success, retry loop and the Catch path to MarkFailed.

Map with MaxConcurrency: control the speed

Map runs the steps for every attendee. MaxConcurrency: 5 means at most five run at once, which protects your email provider's rate limit. For very large lists (thousands of items), use distributed Map mode, which can read the list from an S3 file.

Step 3: Deploy it with AWS SAM

CertificateWorkflow:
  Type: AWS::Serverless::StateMachine
  Properties:
    Type: STANDARD
    DefinitionUri: statemachine/certificates.asl.json
    DefinitionSubstitutions:
      FetchAttendeesFn: !GetAtt FetchAttendeesFunction.Arn
      IssueCertificateFn: !GetAtt IssueCertificateFunction.Arn
      NotifyFn: !GetAtt NotifyFunction.Arn
    Policies:
      - LambdaInvokePolicy: { FunctionName: !Ref FetchAttendeesFunction }
      - LambdaInvokePolicy: { FunctionName: !Ref IssueCertificateFunction }
      - LambdaInvokePolicy: { FunctionName: !Ref NotifyFunction }

DefinitionSubstitutions fills in the ${...} placeholders with real function ARNs, so the JSON stays readable.

Step 4: Run it and watch it

Start a run from the console or the CLI:

aws stepfunctions start-execution \
  --state-machine-arn arn:aws:states:ap-south-1:ACCOUNT_ID:stateMachine:CertificateWorkflow \
  --input '{"workshopId":"aws-101"}'

Open the run in the console. You'll see the graph light up as each step finishes, with the input and output of every step. When something fails, click the red step to see the exact error. That visibility alone is worth using Step Functions.

Standard or Express?

StandardExpress
Maximum durationUp to 1 yearUp to 5 minutes
Best forLong, important business processesHigh-volume, short jobs like stream processing
Run historyFull visual history in the consoleLogs to CloudWatch
Pricing modelPer state transitionPer request and duration

Our certificate workflow is Standard: it's important, it waits, and we want the history.

Common beginner mistakes

  • Putting everything in one Lambda function. If one function does five things, Step Functions can't retry just the failed part. Give each step its own small task.
  • No Catch inside a Map. One failing item then fails the whole run. Catch errors per item.
  • Passing huge payloads between steps. Each state's input and output has a size limit. Store large data in S3 or DynamoDB and pass a key instead.
  • Retrying errors that will never succeed. Retry throttling and timeouts, not validation errors like "invalid email". Those should go straight to Catch.
  • Forgetting about cost in tight loops. Standard workflows are billed per state transition. A Wait inside a loop of millions of items adds up. Use distributed Map or Express for very high volume.

Key takeaways

  • Step Functions replaces fragile glue code with a visible, retryable workflow.
  • Retry handles temporary failures, Catch handles permanent ones, and Map processes lists with controlled speed.
  • Keep each step small, pass references instead of big payloads, and use Standard for important long-running processes.

Step Functions pairs well with events. See Event-Driven Serverless on AWS for when to use events between services and workflows inside a process.

Found this useful?

Share it with your group