generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 1k
Add Lambda Durable Functions with Human-in-the-Loop pattern #2954
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
4D54
wants to merge
8
commits into
aws-samples:main
Choose a base branch
from
4D54:lambda-durable-hitl-python-sam
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bebcea6
Add Lambda Durable Functions with Human-in-the-Loop pattern
4D54 e54b662
Add Lambda Durable Functions with Human-in-the-Loop pattern
4D54 7aac54f
feat: Add Lambda Durable Functions with Human-in-the-Loop pattern
4D54 5ed3a7a
Merge latest changes from upstream
4D54 5f9f3a9
Merge updated main into feature branch
4D54 6cf3423
fix: Implement callback pattern using Lambda durable execution APIs
4D54 2af7690
fix: Scope IAM permissions to specific function and restructure README
4D54 0531ff5
fix: Scope durable execution IAM permissions and break circular depen…
4D54 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| # Python | ||
| __pycache__/ | ||
| *.py[cod] | ||
| *$py.class | ||
| *.so | ||
| .Python | ||
| build/ | ||
| develop-eggs/ | ||
| dist/ | ||
| downloads/ | ||
| eggs/ | ||
| .eggs/ | ||
| lib/ | ||
| lib64/ | ||
| parts/ | ||
| sdist/ | ||
| var/ | ||
| wheels/ | ||
| *.egg-info/ | ||
| .installed.cfg | ||
| *.egg | ||
|
|
||
| # Virtual environments | ||
| venv/ | ||
| ENV/ | ||
| env/ | ||
| .venv | ||
|
|
||
| # Testing | ||
| .pytest_cache/ | ||
| .coverage | ||
| htmlcov/ | ||
| .hypothesis/ | ||
| *.cover | ||
| .tox/ | ||
|
|
||
| # IDEs | ||
| .vscode/ | ||
| .idea/ | ||
| *.swp | ||
| *.swo | ||
| *~ | ||
|
|
||
| # AWS SAM | ||
| .aws-sam/ | ||
| samconfig.toml | ||
|
|
||
| # Logs | ||
| *.log | ||
|
|
||
| # OS | ||
| .DS_Store | ||
| Thumbs.db | ||
|
|
||
| # Environment variables | ||
| .env | ||
| .env.local |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| # Lambda Durable Functions to DynamoDB with Human-in-the-Loop | ||
|
|
||
| This pattern demonstrates how to implement Lambda durable functions with Human-in-the-Loop (HITL) approval workflows. The workflow pauses execution, waits for human approval via callback, and resumes based on the decision while maintaining state across the pause/resume cycle. | ||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-hitl-python-sam | ||
|
|
||
| Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. | ||
|
|
||
| ## Requirements | ||
|
|
||
| * [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. | ||
| * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
| * [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
| * [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed | ||
| * [Docker](https://docs.docker.com/get-docker/) installed (for building Lambda container images) | ||
| * [Python 3.13](https://www.python.org/downloads/) or later | ||
|
|
||
| ## Deployment Instructions | ||
|
|
||
| 1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
| ``` | ||
| git clone https://github.com/aws-samples/serverless-patterns | ||
| ``` | ||
| 1. Change directory to the pattern directory: | ||
| ``` | ||
| cd lambda-durable-hitl-python-sam | ||
| ``` | ||
| 1. From the command line, use AWS SAM to build the application: | ||
| ``` | ||
| sam build | ||
| ``` | ||
| 1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yaml file: | ||
| ``` | ||
| sam deploy --guided | ||
| ``` | ||
| 1. During the prompts: | ||
| * Enter a stack name | ||
| * Enter the desired AWS Region | ||
| * Enter the ApprovalTimeoutSeconds parameter (default: 300 seconds) | ||
| * Allow SAM CLI to create IAM roles with the required permissions. | ||
|
|
||
| Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. | ||
|
|
||
| 1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. | ||
|
|
||
| ## How it works | ||
|
|
||
| This pattern implements a Human-in-the-Loop approval workflow using Lambda durable functions: | ||
|
|
||
| 1. **Workflow Lambda** creates an approval request in DynamoDB and sends an SNS notification to approvers | ||
| 2. The workflow pauses execution using `callback.result()` and waits for a callback | ||
| 3. **Approval API Lambda** processes the approval decision and calls the Lambda durable execution callback API | ||
| 4. The workflow resumes automatically when the callback is invoked and completes with the decision | ||
|
|
||
| The pattern uses the AWS Durable Execution SDK for Python with the `@durable_execution` decorator to maintain state across the pause/resume cycle. The callback pattern ensures no compute charges while waiting for human decisions. | ||
|
|
||
| ### Architecture Components | ||
|
|
||
| - **Workflow Lambda**: Orchestrates the approval workflow using Lambda durable functions SDK with callback pattern | ||
| - **Approval API Lambda**: Processes approval/rejection decisions and invokes the callback API to resume the workflow | ||
| - **DynamoDB Table**: Stores approval request state including callback tokens, document details, and timestamps | ||
| - **SNS Topic**: Sends notifications to approvers when new approval requests are created | ||
|
|
||
| ## Testing | ||
|
|
||
| ### Set Environment Variables | ||
|
|
||
| ```bash | ||
| export AWS_DEFAULT_REGION=us-east-1 | ||
| export STACK_NAME=<your-stack-name> | ||
|
|
||
| # Get function names from CloudFormation outputs | ||
| export WORKFLOW_FUNCTION=$(aws cloudformation describe-stacks \ | ||
| --stack-name $STACK_NAME \ | ||
| --query 'Stacks[0].Outputs[?OutputKey==`WorkflowFunctionName`].OutputValue' \ | ||
| --output text) | ||
|
|
||
| export APPROVAL_API_FUNCTION=$(aws cloudformation describe-stacks \ | ||
| --stack-name $STACK_NAME \ | ||
| --query 'Stacks[0].Outputs[?OutputKey==`ApprovalApiFunctionName`].OutputValue' \ | ||
| --output text) | ||
| ``` | ||
|
|
||
| ### Invoke the Workflow | ||
|
|
||
| ```bash | ||
| # Invoke workflow with a document approval request | ||
| aws lambda invoke \ | ||
| --function-name $WORKFLOW_FUNCTION \ | ||
| --cli-binary-format raw-in-base64-out \ | ||
| --payload '{"document_id":"doc-123","document_name":"Q4 Budget Proposal","requester":"user@example.com"}' \ | ||
| response.json | ||
|
|
||
| # Check response | ||
| cat response.json | ||
| ``` | ||
|
|
||
| ### List Pending Approvals | ||
|
|
||
| ```bash | ||
| # Scan DynamoDB for pending approval requests | ||
| aws dynamodb scan \ | ||
| --table-name $STACK_NAME-ApprovalRequests \ | ||
| --filter-expression "#status = :pending" \ | ||
| --expression-attribute-names '{"#status":"status"}' \ | ||
| --expression-attribute-values '{":pending":{"S":"pending"}}' \ | ||
| --max-items 10 | ||
| ``` | ||
|
|
||
| ### Submit Approval Decision | ||
|
|
||
| ```bash | ||
| # Get the approval_id from the DynamoDB scan output above | ||
|
|
||
| # Approve the request | ||
| aws lambda invoke \ | ||
| --function-name $APPROVAL_API_FUNCTION \ | ||
| --cli-binary-format raw-in-base64-out \ | ||
| --payload '{"action":"decide","approval_id":"<APPROVAL_ID>","decision":"approved","approver":"test-approver","comments":"Looks good"}' \ | ||
| approval_response.json | ||
|
|
||
| # Check response | ||
| cat approval_response.json | ||
| ``` | ||
|
|
||
| ### Verify Workflow Completion | ||
|
|
||
| ```bash | ||
| # Check DynamoDB to verify status changed to approved | ||
| aws dynamodb get-item \ | ||
| --table-name $STACK_NAME-ApprovalRequests \ | ||
| --key '{"approval_id":{"S":"<APPROVAL_ID>"}}' | ||
|
|
||
| # Check CloudWatch Logs for workflow completion | ||
| aws logs tail /aws/lambda/$WORKFLOW_FUNCTION --follow | ||
| ``` | ||
|
|
||
| Expected output: The workflow should complete and return the approval decision. The DynamoDB item should show status as "approved" with the approver's comments and timestamp. | ||
|
|
||
| ## Cleanup | ||
|
|
||
| 1. Delete the stack | ||
| ```bash | ||
| sam delete | ||
| ``` | ||
| 1. Confirm the stack has been deleted | ||
| ```bash | ||
| aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'$STACK_NAME')].StackStatus" | ||
| ``` | ||
|
|
||
| ---- | ||
| Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: MIT-0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| { | ||
| "title": "Lambda Durable Functions with Human-in-the-Loop", | ||
| "description": "Demonstrates Lambda durable functions with human approval workflow using Python 3.13, DynamoDB, and SNS", | ||
| "language": "Python", | ||
| "level": "300", | ||
| "framework": "SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern demonstrates how to pause Lambda execution, wait for human approval, and resume using the Lambda durable functions SDK.", | ||
| "The Workflow Lambda creates an approval request in DynamoDB and polls for decisions using durable waits (no compute charges during waits).", | ||
| "An SNS notification is sent to approvers, who can submit their decision via the Approval API Lambda function.", | ||
| "The Workflow Lambda detects the decision during polling and resumes execution with the approval result.", | ||
| "The pattern includes timeout handling, status tracking, and a complete audit trail of all approval decisions." | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-hitl-python-sam", | ||
| "templateURL": "serverless-patterns/lambda-durable-hitl-python-sam", | ||
| "projectFolder": "lambda-durable-hitl-python-sam", | ||
| "templateFile": "template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "Lambda Durable Functions Documentation", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" | ||
| }, | ||
| { | ||
| "text": "AWS SAM Documentation", | ||
| "link": "https://docs.aws.amazon.com/serverless-application-model/" | ||
| }, | ||
| { | ||
| "text": "DynamoDB Best Practices", | ||
| "link": "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html" | ||
| }, | ||
| { | ||
| "text": "Amazon SNS Documentation", | ||
| "link": "https://docs.aws.amazon.com/sns/" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "sam build", | ||
| "sam deploy --guided" | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "text": [ | ||
| "See the README in the GitHub repo for detailed testing instructions.", | ||
| "Test the approval workflow using AWS CLI:", | ||
| "1. Publish Lambda version: aws lambda publish-version --function-name <WorkflowFunction>", | ||
| "2. Invoke workflow: aws lambda invoke --function-name <WorkflowFunction>:<version> --invocation-type Event --payload '{...}' response.json", | ||
| "3. List approvals: aws dynamodb scan --table-name <ApprovalsTable>", | ||
| "4. Submit decision: aws lambda invoke --function-name <ApprovalApiFunction> --payload '{\"action\":\"decide\",...}' response.json" | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "text": [ | ||
| "Delete the stack: sam delete" | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Mian Tariq", | ||
| "bio": "Cloud Solutions Architect" | ||
| } | ||
| ], | ||
| "patternArch": { | ||
| "icon1": { | ||
| "name": "lambda", | ||
| "label": "Lambda Durable Functions" | ||
| }, | ||
| "icon2": { | ||
| "name": "dynamodb", | ||
| "label": "Amazon DynamoDB" | ||
| }, | ||
| "icon3": { | ||
| "name": "sns", | ||
| "label": "Amazon SNS" | ||
| } | ||
| } | ||
| } |
14 changes: 14 additions & 0 deletions
14
lambda-durable-hitl-python-sam/src/approval_api/Dockerfile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| FROM public.ecr.aws/lambda/python:3.13 | ||
|
|
||
| # Copy requirements file | ||
| COPY approval_api/requirements.txt ${LAMBDA_TASK_ROOT}/ | ||
|
|
||
| # Install dependencies | ||
| RUN pip install --no-cache-dir -r requirements.txt | ||
|
|
||
| # Copy function code | ||
| COPY approval_api/app.py ${LAMBDA_TASK_ROOT}/ | ||
| COPY shared/*.py ${LAMBDA_TASK_ROOT}/ | ||
|
|
||
| # Set the CMD to your handler | ||
| CMD ["app.lambda_handler"] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.