Lambda orchestration example - Amazon Step Functions
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Lambda orchestration example

This sample project demonstrates how to integrate Amazon Lambda functions in Step Functions state machines.

In this project, Step Functions uses Lambda functions to check a stock price and determine a buy or sell trading recommendation. The user is then provided this recommendation and can choose whether to buy or sell the stock. The result of the trade is returned using an SNS topic.

For more information about Step Functions service integrations, see the following:


This sample project may incur charges.

For new Amazon users, a free usage tier is available. On this tier, services are free below a certain level of usage. For more information about Amazon costs and the free tier, see Pricing.

Step 1: Create the state machine and provision resources

  1. Open the Step Functions console and choose Create state machine.

  2. Type Orchestrate Lambda functions in the search box, and then choose Orchestrate Lambda functions from the search results that are returned.

  3. Choose Next to continue.

  4. Step Functions lists the Amazon Web Services used in the sample project you selected. It also shows a workflow graph for the sample project. Deploy this project to your Amazon Web Services account or use it as a starting point for building your own projects. Based on how you want to proceed, choose Run a demo or Build on it.

    This sample project deploys the following resources:

    • Five Lambda functions

    • An Amazon Simple Queue Service queue

    • An Amazon Simple Notification Service topic

    • An Amazon Step Functions state machine

    • Related Amazon Identity and Access Management (IAM) roles

    The following image shows the workflow graph for the Orchestrate Lambda functions sample project:

            Workflow graph of the Orchestrate Lambda functions sample project.
  5. Choose Use template to continue with your selection.

  6. Do one of the following:

    • If you selected Build on it, Step Functions creates the workflow prototype for the sample project you selected. Step Functions doesn't deploy the resources listed in the workflow definition.

      In Workflow Studio's Design mode, drag and drop states from the States browser to continue building your workflow protoype. Or switch to the Code mode that provides an integrated code editor similar to VS Code for updating the Amazon States Language (ASL) definition of your state machine within the Step Functions console. For more information about using Workflow Studio to build your state machines, see Using Workflow Studio.


      Remember to update the placeholder Amazon Resource Name (ARN) for the resources used in the sample project before you run your workflow.

    • If you selected Run a demo, Step Functions creates a read-only sample project which uses an Amazon CloudFormation template to deploy the Amazon resources listed in that template to your Amazon Web Services account.


      To view the state machine definition of the sample project, choose Code.

      When you're ready, choose Deploy and run to deploy the sample project and create the resources.

      It can take up to 10 minutes for these resources and related IAM permissions to be created. While your resources are being deployed, you can open the CloudFormation Stack ID link to see which resources are being provisioned.

      After all the resources in the sample project are created, you can see the new sample project listed on the State machines page.


      Standard charges may apply for each service used in the CloudFormation template.

Step 2: Run the state machine

After all the resources are provisioned and deployed, the Start execution dialog box is displayed.

  1. On the State machines page, choose your sample project.

  2. On the sample project page, choose Start execution.

  3. In the Start execution dialog box, do the following:

    1. (Optional) To identify your execution, you can specify a name for it in the Name box. By default, Step Functions generates a unique execution name automatically.


      Step Functions allows you to create names for state machines, executions, and activities, and labels that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch. To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

    2. (Optional) In the Input box, enter input values in JSON format to run your workflow.

      If you chose to Run a demo, you need not provide any execution input.


      If the demo project you deployed contains prepopulated execution input data, use that input to run the state machine.

    3. Choose Start execution.

    4. The Step Functions console directs you to a page that's titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete.

      To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution Details page – Interface overview.

About the state machine and its execution

The state machine in this sample project integrates with Amazon Lambda by passing parameters directly to those resources, uses an Amazon SQS queue to manage the request for human approval, and uses an Amazon SNS topic to return the results of the query.

A Step Functions execution receives a JSON text as input and passes that input to the first state in the workflow. Individual states receive JSON data as input and usually pass JSON data as output to the next state. In this sample project, the output of each step is passed as input to the next step in the workflow. For example, the Generate Buy/Sell recommendation step receives the output of the Check Stock Price step as input. Further, the output of the Generate Buy/Sell recommendation step is passed as input to the next step, Request Human Approval, which mimics a human approval step.


To view the output returned by a step and the input passed on to a step, open the Execution Details page for your workflow execution. In the Step details section, view the input and output for each step you select in the View mode.

To implement a human approval step, you typically pause the workflow execution until a task token is returned. In this sample project, a message is passed to an Amazon SQS queue, which is used as a trigger to the Lambda function defined to handle callback functionality. The message contains a task token and the output returned by the preceding step. The Lambda function is invoked with the payload of the message. The workflow execution is paused until it receives the task token back with a SendTaskSuccess API call. For more information about task tokens, see Wait for a Callback with the Task Token.

The following code for the StepFunctionsSample-HelloLambda-ApproveSqsLambda function shows how it is defined to automatically approve any tasks submitted by the Amazon SQS queue through the Step Functions state machine.

exports.lambdaHandler = (event, context, callback) => { const stepfunctions = new aws.StepFunctions(); // For every record in sqs queue for (const record of event.Records) { const messageBody = JSON.parse(record.body); const taskToken = messageBody.TaskToken; const params = { output: "\"approved\"", taskToken: taskToken }; console.log(`Calling Step Functions to complete callback task with params ${JSON.stringify(params)}`); // Approve stepfunctions.sendTaskSuccess(params, (err, data) => { if (err) { console.error(err.message); callback(err.message); return; } console.log(data); callback(null); }); } };

Browse through this example state machine to see how Step Functions controls Lambda and Amazon SQS.

For more information about how Amazon Step Functions can control other Amazon services, see Using Amazon Step Functions with other services.

{ "StartAt": "Check Stock Price", "States": { "Check Stock Price": { "Type": "Task", "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLam-CheckStockPriceLambda-444455556666", "Next": "Generate Buy/Sell recommendation" }, "Generate Buy/Sell recommendation": { "Type": "Task", "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-Hello-GenerateBuySellRecommend-123456789012", "ResultPath": "$.recommended_type", "Next": "Request Human Approval" }, "Request Human Approval": { "Type": "Task", "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken", "Parameters": { "QueueUrl": "", "MessageBody": { "Input.$": "$", "TaskToken.$": "$$.Task.Token" } }, "ResultPath": null, "Next": "Buy or Sell?" }, "Buy or Sell?": { "Type": "Choice", "Choices": [ { "Variable": "$.recommended_type", "StringEquals": "buy", "Next": "Buy Stock" }, { "Variable": "$.recommended_type", "StringEquals": "sell", "Next": "Sell Stock" } ] }, "Buy Stock": { "Type": "Task", "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLambda-BuyStockLambda-000000000000", "Next": "Report Result" }, "Sell Stock": { "Type": "Task", "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLambda-SellStockLambda-111111111111", "Next": "Report Result" }, "Report Result": { "Type": "Task", "Resource": "arn:aws:states:::sns:publish", "Parameters": { "TopicArn": "arn:aws:sns:us-west-1:111122223333:StepFunctionsSample-HelloLambda1111-2222-3333-ReportResultSnsTopic-222222222222", "Message": { "Input.$": "$" } }, "End": true } } }

For information about how to configure IAM when using Step Functions with other Amazon services, see IAM Policies for integrated services.

IAM Examples

These example Amazon Identity and Access Management (IAM) policies generated by the sample project include the least privilege necessary to execute the state machine and related resources. We recommend that you include only those permissions that are necessary in your IAM policies.

{ "Statement": [ { "Action": [ "lambda:InvokeFunction" ], "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLam-CheckStockPriceLambda-444455556666", "Effect": "Allow" } ] }
{ "Statement": [ { "Action": [ "lambda:InvokeFunction" ], "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-Hello-GenerateBuySellRecommend-123456789012", "Effect": "Allow" } ] }
{ "Statement": [ { "Action": [ "lambda:InvokeFunction" ], "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLambda-BuyStockLambda-777788889999", "Effect": "Allow" } ] }
{ "Statement": [ { "Action": [ "lambda:InvokeFunction" ], "Resource": "arn:aws:lambda:us-west-1:111122223333:function:StepFunctionsSample-HelloLambda-SellStockLambda-000000000000", "Effect": "Allow" } ] }
{ "Statement": [ { "Action": [ "sqs:SendMessage*" ], "Resource": "arn:aws:sqs:us-west-1:111122223333:StepFunctionsSample-HelloLambda4444-5555-6666-RequestHumanApprovalSqs-111111111111", "Effect": "Allow" } ] }
{ "Statement": [ { "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:us-west-1:111122223333:StepFunctionsSample-HelloLambda1111-2222-3333-ReportResultSnsTopic-222222222222", "Effect": "Allow" } ] }

For information about how to configure IAM when using Step Functions with other Amazon services, see IAM Policies for integrated services.