> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Step Functions Demo

> Tutorial showing how to build, test, and troubleshoot an AWS Step Functions state machine that invokes Lambdas to detect and handle camera threats.

This lesson demonstrates how to build, test, and troubleshoot a simple AWS Step Functions state machine using the visual console. You'll create a workflow that processes a camera event, invokes a detector Lambda, and branches based on detection results.

Search for Step Functions in the AWS Console and select Create state machine. A state machine is where you author a workflow — the ordered set of steps and logic your application should perform. For this demo, choose the Blank template so we can build the workflow step-by-step.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-templates-dialog.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=51100b1ab7e8687c277fe2dc5cce6c0a" alt="A browser screenshot of the AWS Step Functions &#x22;Choose a template&#x22; dialog showing various workflow templates (Blank, Distributed Map to process CSV, Batch Job with Lambda, API Gateway callbacks, etc.), with a left navigation pane of categories and Cancel/Select buttons at the bottom." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-templates-dialog.jpg" />
</Frame>

## Authoring canvas overview

* Center: the visual workflow (Start → states → End). Execution flows top-to-bottom.
* Left pane: pre-built states and integrations you can drag into the canvas (Task for Lambda/SNS/ECS, Flow types for Choice/Parallel/Map, plus Wait, Pass, etc.).
* Right pane: configuration for the selected state (state name, integration type, payload mapping, retry/catch settings, etc.).

For this demo we'll implement a simple "camera event" workflow:

* When a camera detects motion, the state machine invokes a detector Lambda.
* The detector returns `THREAT` or `NO_THREAT`.
* A Choice state routes the execution to either a Threat handling Lambda or a False-Positive handler.

High-level workflow:

1. Start → receive event (camera metadata, S3 object key, etc.)
2. Invoke DetectThreat Lambda (returns `result = "THREAT"` | `"NO_THREAT"`)
3. Choice state: if `result == "THREAT"` → invoke ThreatFound Lambda; if `result == "NO_THREAT"` → invoke FalsePositive Lambda
4. End

## Lambda functions used in the demo

Below are minimal example Lambdas used in the tutorial. Keep these simple for demonstration — you can replace them with real implementations.

| Function | Purpose | Example (Node.js) |
| - | -: | - |
| DetectThreat | Simulates threat detection and returns `result` | `javascript\n// DetectThreat Lambda (Node.js)\nexport const handler = async (event) => {\n  // Simulate threat detection (50/50)\n  const result = Math.random() < 0.5 ? \"THREAT\" : \"NO_THREAT\";\n  return { result };\n};\n` |
| ThreatFound | Path executed when a threat is detected | `javascript\n// ThreatFound Lambda (Node.js)\nexport const handler = async (event) => {\n  // TODO: implement real threat handling (notifications, camera lock, etc.)\n  return \"threat_found\";\n};\n` |
| FalsePositive | Path executed when detection is a false positive | `javascript\n// FalsePositive Lambda (Node.js)\nexport const handler = async (event) => {\n  // TODO: implement false positive handling (logging, training data, etc.)\n  return \"false_positive\";\n};\n` |

<Callout icon="lightbulb" color="#1CB2FE">
  Use the minimal payload in the Lambda functions while prototyping. You can later expand payload mapping via `Parameters`, `InputPath`, `ResultPath`, and `OutputPath` to pass only the fields you need between states.
</Callout>

## Add the Detect Threat Task (Lambda invoke)

1. Drag a Lambda Invoke Task onto the canvas and name it "Detect Threat".
2. For Integration type choose **Optimized** (simplified invocation for common Lambda workflows).
3. Select your DetectThreat function from the FunctionName dropdown.

Payload configuration:

* Use `Use the state input as payload` so the initial event that triggered the state machine is passed into DetectThreat.
* Optionally narrow fields using JSON Path filters — for this tutorial we'll pass the full input.

Wait-for-callback:

* Leave "Wait for callback" disabled for this demo.

Retries and catches:

* Configure `Retry` (IntervalSeconds, MaxAttempts, BackoffRate) for transient failures.
* Add `Catch` handlers to redirect failed executions to error-handling states if needed.

Next state:

* After the Detect Threat task completes it will transition to the Choice node you will add next.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-detect-threat-lambda.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=672ecd1ba9c6cf539c4e583bc19e97c8" alt="A screenshot of the AWS Step Functions console showing a simple state machine diagram with a Lambda Invoke state labeled &#x22;Detect Threat&#x22; (Start and End nodes visible) and the retry configuration panel open on the right; the left sidebar lists common actions like AWS Lambda, SNS, and ECS." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-detect-threat-lambda.jpg" />
</Frame>

## Add a Choice state for branching logic

Drag a Choice state (Flow → Choice) after the Detect Threat Task. Choice states express if/then/else logic using JSON Path values from the state input or the previous state's output.

The detector returns `{"result":"THREAT"}` or `{"result":"NO_THREAT"}`. Create two rules:

* Rule 1: `Variable = $.result`, operator = `is equal to`, string constant = `THREAT`
* Rule 2: `Variable = $.result`, operator = `is equal to`, string constant = `NO_THREAT`

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-visual-lambda-choice.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=4b271b1ef4feb98b52814312140d7753" alt="A screenshot of the AWS Step Functions visual editor showing a state machine diagram with a &#x22;Start&#x22; node, a Lambda invoke step labeled &#x22;Detect Threat,&#x22; and a Choice state with empty branches. The left pane lists available state types (Choice, Parallel, Map, Pass, etc.) and the right pane shows configuration options for the selected Choice state." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-visual-lambda-choice.jpg" />
</Frame>

When you add a rule, the condition editor appears. Set the variable to `$.result`, the operator to `is equal to`, and the string constant as appropriate (`THREAT` or `NO_THREAT`).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-conditions-modal.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=ed4c2c2978def2231b596d3e20be6786" alt="A screenshot of the AWS Step Functions console showing a modal titled &#x22;Conditions for rule #1.&#x22; The dialog displays a simple conditional rule editor with Variable set to $.result, Operator &#x22;is equal to&#x22;, a &#x22;String constant&#x22; value field, and a &#x22;Save conditions&#x22; button." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-conditions-modal.jpg" />
</Frame>

Example conceptual rules:

```JSONPath theme={null}
$.result == "THREAT"
$.result == "NO_THREAT"
```

## Attach Lambda tasks to each branch

* For the `THREAT` branch, add a Lambda Invoke Task named **Threat Found** and select the ThreatFound Lambda.
* For the `NO_THREAT` branch, add a Lambda Invoke Task named **No Threat** and select the FalsePositive Lambda.

Each branch can end the execution or continue into additional states (for example, send notifications via SNS for threats or store misclassifications for training data).

After wiring the branches the workflow looks like:
Start → Detect Threat (Task) → Choice → (THREAT → ThreatFound Task) | (NO\_THREAT → FalsePositive Task) → End

## Passing data between states

Step Functions provides several JSON Path–based knobs for data flow:

* `InputPath` — filters the incoming state input to the state
* `Parameters` — builds the payload passed to the resource (Lambda, SDK, etc.)
* `ResultPath` — controls how the state's result is merged with the input
* `OutputPath` — filters the final output emitted by the state

Use these to limit payload size, shape data for downstream services, or persist only the fields you need.

## Testing the state machine

When you click Create, the builder will prompt to confirm or create an execution role that grants Step Functions permission to invoke Lambda (and optionally X-Ray for tracing). The console can create this role automatically — review the permissions before confirming.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-confirm-role-dialog.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=d401ad55b9ad943b8827b5eb6b5a0026" alt="A screenshot of the AWS Step Functions console showing a &#x22;Confirm role creation&#x22; dialog that says an execution role with full permissions will be created and lists role permissions for AWS Lambda and AWS X‑Ray. The dialog includes buttons for Cancel, View role configuration, and Confirm." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-confirm-role-dialog.jpg" />
</Frame>

<Callout icon="warning" color="#FF6B6B">
  Ensure the execution role grants least privilege. Allow only the Lambda functions and resources your state machine needs to invoke. Overly broad roles increase security risk.
</Callout>

If you misconfigure a catcher or other state property you may see an error. Fix the state configuration before recreating the state machine.

### Start an execution

An execution is a single run of your state machine. Click Start execution and provide the initial input — this simulates the event the camera or upstream system sends.

Example input:

```json theme={null}
{
  "camera_id": "ssldfjsikd-234-sdfs",
  "object_id": "video1.mp4"
}
```

Start the execution and watch the visual execution flow. The console highlights the path taken and you can click any state to inspect its input, output, and events.

### Example Task state (ASL) produced by the visual editor

Below is the Task state JSON the visual editor generates for invoking Detect Threat (shows common retry settings and how payload mapping works):

```json theme={null}
{
  "Type": "Task",
  "Resource": "arn:aws:states:::lambda:invoke",
  "OutputPath": "$.Payload",
  "Parameters": {
    "Payload.$": "$",
    "FunctionName": "arn:aws:lambda:us-west-1:841860927337:function:detect_threat:$LATEST"
  },
  "Retry": [
    {
      "ErrorEquals": [
        "Lambda.ServiceException",
        "Lambda.AWSLambdaException",
        "Lambda.SdkClientException",
        "Lambda.TooManyRequestsException"
      ],
      "IntervalSeconds": 1,
      "MaxAttempts": 3,
      "BackoffRate": 2.0
    }
  ]
}
```

## Inspecting events and logs

The Events pane lists state transitions and timestamps (TaskStarted, TaskSucceeded, ChoiceEvaluated, ExecutionSucceeded, etc.). Selecting any state displays:

* Input passed into the state (for example, the camera metadata)
* Output produced by the state (for example, `{ "result": "NO_THREAT" }` from DetectThreat)
* Duration and timestamp metadata
* Any Lambda response metadata or error details

You can also view the raw SDK / HTTP objects returned by Lambda:

```json theme={null}
{
  "HttpStatusCode": 200,
  "SdkResponseMetadata": {
    "RequestId": "098b50c8-ef8e-4a17-b2db-13a00cf6e81b"
  },
  "outputDetails": {
    "truncated": false
  }
}
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-stepfunctions-state-machine-events.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=7f088f291b4f0ec80332207f948093ad" alt="A screenshot of the AWS Step Functions console showing a state machine diagram and an Events pane. The Events table lists execution steps (e.g., Detect Threat, No Threat) with types, statuses (TaskSucceeded, ExecutionSucceeded), and timestamps." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-stepfunctions-state-machine-events.jpg" />
</Frame>

## Re-run executions

Because the DetectThreat Lambda is randomized, repeated executions will sometimes go to ThreatFound and other times to No Threat. Run multiple executions to validate both branches and inspect inputs, outputs, and events for each.

## State machine dashboard and history

From the State Machines page you can see a summary for each state machine including execution counts and status (Succeeded, Failed, Timed out). Click a state machine to view all executions and drill into historical runs for analysis or troubleshooting.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-console-state-machines.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=091bee012454c00e29890a71e2d95b6d" alt="Screenshot of the AWS Step Functions console showing a table of three state machines with their names, types, creation dates, statuses and execution counts. The top bar includes action buttons such as View details, Edit, Delete and Create state machine." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-console-state-machines.jpg" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/voEwdRiXa9hDn_dx/images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-state-machine-executions.jpg?fit=max&auto=format&n=voEwdRiXa9hDn_dx&q=85&s=57d48469be715b58b20f9aacbd6ec73f" alt="A screenshot of the AWS Step Functions console showing a state machine named &#x22;MyStateMachine-bd6inz729&#x22; with its details, ARN, and status (Standard, Active). The lower panel lists recent executions (two succeeded) and buttons for editing or starting an execution." width="1920" height="1080" data-path="images/AWS-Solutions-Architect-Associate-Certification/Services-Application-Integration/Step-Functions-Demo/aws-step-functions-state-machine-executions.jpg" />
</Frame>

## Summary and best practices

* AWS Step Functions provides a visual and stateful orchestration layer to coordinate AWS services (Lambda, SNS, ECS, SDK integrations) and model complex workflows.
* Use Choice states to branch logic; Retry and Catch to make workflows resilient; InputPath/Parameters/ResultPath/OutputPath to control data flow and keep payloads small.
* Test often: run multiple executions, inspect Events and state inputs/outputs, and adjust retry/catch policies as needed.
* Use least-privilege IAM roles for the state machine execution role.

## Links and references

* [AWS Step Functions Documentation](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)
* [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
* [ASL (Amazon States Language) reference](https://states-language.net/spec.html)

This completes the lesson.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/aws-solutions-architect-associate-certification/module/2a5c60f6-2d46-4dfe-a2e2-66c7eae45a70/lesson/7154ef92-2e72-475e-a385-8718a7ba3732" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.