Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

What Is AWS Step Functions? Orchestrate Lambda Workflows Explained

A bank loan needs many checks in order: KYC, credit score, offer letter, then SMS. If each check is a Lambda, something must remember where we are when one step fails. That something is AWS Step Functions — a traffic policeman for your cloud workflow.

In this chapter

  • Why long workflows need a state machine
  • What ASL, Task, Retry, Catch, Map and Parallel mean
  • Standard vs Express workflows
  • Industries that already use Step Functions
  • Lab path, errors, FAQ and interview answers

1. Everyday example first

Swiggy order: validate cart, reserve stock, charge card, notify rider. If charge fails after stock reserve, you must release stock. Hard-coding that in one Lambda becomes spaghetti. A state machine draws the path on a board.

AWS Step Functions runs a state machine described in Amazon States Language (ASL) JSON. Each state can call Lambda, DynamoDB, ECS, another workflow, wait, choose a branch, retry or catch errors.

Happy path (order)StartAt ValidateTask ChargeTask NotifyEnd success
Retries and Catch branches sit beside this happy path.

2. Core words

Imagine an order arrives with an order ID. The app must check stock, choose a path based on availability and tell support when processing fails. A state machine is the saved workflow. One execution is a run for one order. A state is one step, and a Task asks another service to do work. The state can receive JSON, a text format with named values such as an order ID, and pass a result to the next step. Draw the ID entering the stock check and available: true leaving it. At a Choice state, use that flag to pick the next step.

WordMeaningStreet picture
State machineThe whole flowchart you deployFull kitchen recipe
ASLJSON language of statesRecipe as JSON
TaskDo work (often Lambda ARN)One cooking step
Retry / CatchTry again or go to error pathBurnt roti: remake or call manager
Map / ParallelFan-out over a list / run branches togetherMany parcels at once
Standard / ExpressLong durable vs short high-volumeRegistered post vs bulk SMS

Separate a business decision from a task error

A stock check can successfully report “unavailable”, or it can fail to obtain a result. A workflow should handle these differently.

Separate a business decision from a task errorCheck stock task: Processes order O-42; Choice decision: Routes a successful stock result; Business path: Reserve stock or report unavailable; Error path: Retry selected errors; Catch if neededCheck stock taskProcesses order O-42Choice decisionRoutes a successful stock resultBusiness pathReserve stock or report unavailableError pathRetry selected errors; Catch ifneeded
Read all steps
  1. Pass the input

    The execution starts with order O-42 and runs a stock-check task. The task needs defined input and must return a result the following state understands.

  2. Route a valid result

    If the check succeeds and returns available=false, a Choice state can route to a normal unavailable outcome. The business cannot fulfil this order, but the stock-check task itself did not fail.

  3. Retry an appropriate error

    If the check fails because of a configured transient error, a Retry policy can attempt that task again. Restrict the matched errors and retry allowance; repeatedly retrying invalid input does not repair it.

  4. Handle an unresolved failure

    When the applicable retries are exhausted, a matching Catch handler can route to an error-handling state. Retried tasks must also handle repeated execution safely so a retry does not reserve the same stock twice.

3. Standard vs Express

Read Retry as “try the same step again for a selected error.” Read Catch as “take this separate path when the error matches after retries.” A temporary stock lookup timeout can be a candidate for retry. A result saying stock is empty is business data, so branch on it. In the execution history, look for which state received the input, whether the task returned or failed, and which step followed. That explains why two orders can start at the same step and finish in different places.

Wrong mode wastes money or loses the audit trail banks need.

NeedPickWhy
Loan, KYC, human approval, days-long waitStandardExactly-once workflow model, up to one year, execution history. Configured task retries can repeat a step.
IoT click stream, 100k short pipes per secExpressAsynchronous: at-least-once. Synchronous: at-most-once. Both: up to 5 minutes.
Need console replay for supportStandardExecution history is the support ticket

Ravindra Bagale's Tip

Start every student lab on Standard. Move to Express only when metrics prove volume.

4. Industries using it

  • Fintech (Pune/Bengaluru): KYC → bureau → offer → e-sign.
  • Healthcare: intake → insurance check → appointment SMS.
  • Ecommerce: order → fraud → warehouse → shipping label.
  • Media: upload → transcode Map state → CDN invalidate.
  • SaaS onboarding: create tenant → seed DB → welcome email.

5. How to sketch your first machine

  1. Write the happy path on paper with 3 to 5 boxes.
  2. Circle which box is Lambda vs wait vs choice.
  3. Add one Retry on the flaky call (payment, SMS).
  4. Add one Catch that writes failure to DynamoDB and notifies SNS.
  5. Translate to ASL JSON; start execution with a tiny input.
{
  "Comment": "Tiny charge flow",
  "StartAt": "Validate",
  "States": {
    "Validate": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:ap-south-1:123456789012:function:validate",
      "Next": "Charge"
    },
    "Charge": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:ap-south-1:123456789012:function:charge",
      "Retry": [{"ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 2, "MaxAttempts": 3}],
      "Catch": [{"ErrorEquals": ["States.ALL"], "Next": "FailNotify"}],
      "End": true
    },
    "FailNotify": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:ap-south-1:123456789012:function:fail-notify",
      "End": true
    }
  }
}

6. Mini lab: console state machine

Before running the lab, write down a stock-available input and an out-of-stock input for your sketch. Use the history or graph to check the path taken by each. If the lab uses only Pass and Wait, change the starting sample value and confirm the final JSON still contains the intended ID. If the later task demo fails, inspect the state’s error and input before changing the Lambda code or the execution role.

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

  1. Open Step Functions → Create state machine → Write your workflow in code.
  2. Paste a 2-Task ASL that calls two existing Lambdas (or the sample).
  3. Start execution with {"orderId":"lab-1"}.
  4. Open Graph view; confirm green success path.
  5. Copy the execution ARN into your notes.

Cleanup (stop billing)

  1. Delete the state machine if it is only a lab.
  2. Delete lab Lambdas if you created them only for this.

7. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
States.Runtime / invalid ASLValidate ASL in Workflow Studio or aws stepfunctions validate-state-machine-definition.
Lambda not authorizedExecution role needs lambda:InvokeFunction on that ARN.
Task timed outRaise TimeoutSeconds or fix Lambda timeout; check cold start.
Infinite Retry stormCap MaxAttempts; send to Catch.
Express used but need auditMigrate that flow to Standard.
Payload larger than 256 KBStore blob in S3; pass s3 key in state.
Map concurrency thunders LambdaSet MaxConcurrency on Map.
Wrong region ARNAll ARNs must match the state machine region.
Catch never runsErrorEquals must match; use States.ALL while learning.
Billing surpriseStandard charges per state transition — trim Wait loops.

8. Troubleshooting checklist

  1. Confirm region equals ap-south-1 (or your org region).
  2. IAM execution role attached and trusted by states.amazonaws.com.
  3. Lambda allows invoke from the role.
  4. Open failed state → error cause JSON and read it fully.
  5. Test the Lambda alone with the same payload.
  6. Check CloudWatch Logs on the Task Lambda.

9. FAQ

Q. Is Step Functions only for Lambda?

No — direct SDK integrations hit many AWS APIs without Lambda glue.

Q. Step Functions vs SQS?

SQS is a queue; Step Functions is an orchestrator with branches and history.

Q. Can I wait 30 days?

Standard Wait state can wait up to one year.

Q. Does Express support all states?

Express lacks some integration patterns, such as Run a Job and Wait for Callback. Check workflow duration, execution history and retry semantics before migrating.

Q. How do I unit test ASL?

Prefer contract tests on Lambdas plus small integration executions.

10. Interview Q&A

Q. What is a state machine in AWS?

A deployed ASL flowchart Step Functions executes with retries and branches.

Q. Standard vs Express?

Standard supports long-running workflows and execution history. Express supports short, high-volume workflows. Async and sync Express have different execution guarantees.

Q. Why Catch and Retry?

Retry handles blips; Catch handles poison with a defined failure path.

Q. Map state use case?

Fan-out the same work over an array (resize 500 images).

Q. How do you pass large files?

S3 object key in the JSON; never the whole file.

Q. Idempotency tip?

Make Task Lambdas idempotent; use execution name or business key.

11. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Draw the flowchart before you open the console. Cheap paper beats expensive failed executions.

Ravindra Bagale's Tip (MR)

आधी कागदावर flowchart. स्वस्त कागद > महाग failed executions.

Tip (HI)

पहले कागज़ पर flowchart बनाओ — सस्ता कागज़ महंगे failed execution से बेहतर है।

Try at home

  1. Rewrite the Swiggy path as 4 boxes with one Catch.
  2. In console, open a sample project and press Start execution.
  3. List three workflows at your job or college that need orchestration.

In short

  1. Step Functions = state machine for AWS workflows.
  2. ASL JSON describes Task, Choice, Wait, Map, Parallel, Retry, Catch.
  3. Standard for durable business flows; Express for short high-volume.
  4. Always design failure paths and cleanup lab resources.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: What is AWS Step Functions?. A bank loan app needs many Lambdas in order: score → fraud → approve. Hand-written chaining is hard to watch and retry. Step Functions is a managed workflow: you draw or write states that call Lambda, wait, choose, and retry. Create a state machine (ASL JSON or Workflow Studio) → grant it invoke rights → start an execution with input JSON. Console graph shows each step green/red; failed step can retry without redoing the whole loan flow.
Revision card: What is AWS Step Functions? · Download PNG · Open card page
Revision card: Task, Choice, Wait, Parallel. Wrong state type makes the workflow hang or skip business rules. Task = do work (Lambda). Choice = if/else. Wait = pause. Parallel = run branches together. Fail/Succeed end the run. Map a happy path with Task + Choice; add Wait for human or timer; use Parallel only when branches are independent. Choice on $.status == APPROVED goes to disburse Task; else goes to reject Succeed.
Revision card: Task, Choice, Wait, Parallel · Download PNG · Open card page
Revision card: Retry and Catch. A flaky payment API should not fail the whole order on the first timeout. Retry repeats a Task on named errors with backoff. Catch routes failure to a cleanup or alert state. Add Retry for States.TaskFailed and Lambda.ServiceException; Catch unknown errors to a notify Fail state. Execution history shows three retries then Catch path when the API stayed down.
Revision card: Retry and Catch · Download PNG · Open card page
Standard vs Express. Choose for long-running workflows or callback-based approvals. Execution history is recorded. A task can still retry. Asynchronous Express is at-least-once. Synchronous Express is at-most-once. Both run for up to five minutes. A loan approval fits Standard. Short event enrichment can fit Express. Make writes idempotent when retries or redelivery are possible.
Revision card: Standard vs Express · Download PNG · Open card page
Revision card: IAM for the state machine. Execution fails with AccessDenied when the role cannot invoke Lambda or write logs. The state machine role needs lambda:InvokeFunction on target functions and permission for any service integration you call. Create a role trusted by states.amazonaws.com; attach least-privilege policy for each Task resource ARN. After fixing the role, a new execution reaches the Lambda Task instead of failing at schedule time.
Revision card: IAM for the state machine · Download PNG · Open card page
Standard vs Express workflows. Choose for long-running workflows or callback-based approvals. Execution history is recorded. A task can still retry. Asynchronous Express is at-least-once. Synchronous Express is at-most-once. Both run for up to five minutes. A loan approval fits Standard. Short event enrichment can fit Express. Make writes idempotent when retries or redelivery are possible.
Comparison: Standard workflow vs Express workflow · Download PNG · Open card page
Comparison: Task state vs Map state. Task state: Calls one resource once per entry (often Lambda). Map state: Runs the same processor over each array item.
Comparison: Task state vs Map state · Download PNG · Open card page
Interview card: Step Functions vs code orchestration?. Step Functions is a managed state machine for multi-step workflows with visual history, retries, and service integrations. You get retries/Catch, timeouts, and audit without maintaining a custom orchestrator server. Loan approval with Lambda tasks and Choice on score is a classic Step Functions fit.
Interview card: Step Functions vs code orchestration? · Download PNG · Open card page
Standard or Express?. Choose for long-running workflows or callback-based approvals. Execution history is recorded. A task can still retry. Asynchronous Express is at-least-once. Synchronous Express is at-most-once. Both run for up to five minutes. A loan approval fits Standard. Short event enrichment can fit Express. Make writes idempotent when retries or redelivery are possible.
Interview card: Standard or Express workflows? · Download PNG · Open card page
Interview card: How do you keep tasks idempotent?. Idempotent means retrying the same Task does not double-charge or double-insert. Use business keys, conditional writes, and Step Functions Retry only on safe errors. Payment Task keys on orderId so a retry after timeout does not bill twice.
Interview card: How do you keep tasks idempotent? · Download PNG · Open card page
Interview card: When do you use Map?. Map runs the same processing over an array of items, with concurrency limits. Use it for fan-out over orders/files; prefer Parallel only for fixed named branches. Process 500 invoice IDs with MaxConcurrency 10 so Lambda is not flooded.
Interview card: When do you use Map? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practise this chapter

Interview questions and answers

How would you model both an out-of-stock result and a temporary stock lookup failure?

For an out-of-stock response, use a Choice to route a valid task result. When looking up stock fails with a selected transient error, Retry can attempt the task again. Catch handles the configured failure path if appropriate after retries. Trace the order ID and result in the execution history.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What is one execution of a state machine?

Answer and explanation

B. One run through the stored workflow for its input

The saved state machine defines the steps. An execution is an individual run.

2. A stock check succeeds and returns available=false. What routes that normal result?

Answer and explanation

A. A Choice state

Choice checks input values and follows a configured branch. Catch handles matching errors.

3. Can a task run again inside a Standard workflow?

Answer and explanation

B. Yes, when configured retry behavior repeats it

Standard protects workflow execution semantics. A configured Retry can execute a task again.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Maple Leaf Books is a bookselling business in Toronto. Emily Tremblay looks after its IT and cloud work. They count money in CAD and run their AWS resources in the ca-central-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy List state machines

See which workflows exist.

List state machines in ca-central-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Describe a state machine

Check definition and role ARN.

Describe state machine arn:aws:states:ca-central-1:102932412000:stateMachine:mapleleafbooks-order.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Delete a state machine

Stop lab billing for unused machines.

Delete state machine arn:aws:states:ca-central-1:102932412000:stateMachine:mapleleafbooks-lab.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List executions

See running and failed runs.

List executions for arn:aws:states:ca-central-1:102932412000:stateMachine:mapleleafbooks-order.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Standard max duration (years)

Know the durable limit.

How many years can a Standard workflow run at most?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Express max minutes

Express is short.

Express workflows max duration in minutes?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Start an execution

Run the workflow with input.

Start execution on arn:aws:states:ca-central-1:102932412000:stateMachine:mapleleafbooks-order named run-1 with input file://input.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Get execution history

Debug which state failed.

Get history for execution arn:aws:states:ca-central-1:102932412000:execution:mapleleafbooks-order:run-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Stop an execution

Cancel a stuck run.

Stop execution arn:aws:states:ca-central-1:102932412000:execution:mapleleafbooks-order:run-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Validate a definition

Catch ASL errors early.

Validate the state machine definition in asl.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Trust policy for Step Functions

Who may assume the role.

Trust policy that lets states.amazonaws.com assume the role.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Allow SFN to invoke one Lambda

Least privilege for Task states.

Allow lambda:InvokeFunction on arn:aws:lambda:ca-central-1:102932412000:function:mapleleafbooks-charge only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Payload limit KB

Know when to use S3.

Max state payload size often cited in KB?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Create a state machine

Deploy ASL from a file.

Create state machine mapleleafbooks-order of type STANDARD with role arn:aws:iam::102932412000:role/mapleleafbooks-sfn and definition file://asl.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard ASL: Validate then Charge

State machines need a clear StartAt path.

Write ASL JSON: StartAt Validate; Validate Task Resource arn:aws:lambda:ap-south-1:123456789012:function:validate Next Charge; Charge Task Resource arn:aws:lambda:ap-south-1:123456789012:function:charge End true.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard ASL with Retry

Retries soften flaky payments.

ASL: StartAt Pay; Pay Task Resource arn:aws:lambda:ap-south-1:123456789012:function:pay with Retry MaxAttempts 3 on States.TaskFailed and End true.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.