generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 1k
New Serverless Pattern - Add Lambda Durable Functions - Human Approval Pattern #2874
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
agawanea
wants to merge
7
commits into
aws-samples:main
Choose a base branch
from
agawanea:lambda-durable-human-approval-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
7 commits
Select commit
Hold shift + click to select a range
f849738
Add Lambda Durable Functions - Human Approval Pattern
agawanea 71e56b5
Fix example-pattern.json to match serverless-patterns standard format
agawanea 8bbcb78
Remove incorrect callback operations link from resources
agawanea 4a76eaf
Merge branch 'aws-samples:main' into lambda-durable-human-approval-sam
agawanea f6282ad
Address PR review comments: fix service naming, remove duplicates, im…
agawanea 6a2a751
Add final pattern file
bfreiberg d0d1dc9
Fix feature naming to use correct 'AWS Lambda durable functions' format
agawanea 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,232 @@ | ||
| # Human-in-the-Loop Approval Workflow with AWS Lambda durable functions | ||
|
|
||
| This pattern demonstrates a human-in-the-loop approval workflow using AWS Lambda durable functions. The workflow pauses execution for up to 24 hours while waiting for human approval via email, automatically handling timeouts and resuming when decisions are received. | ||
|
|
||
| **Important:** Please check the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) for regions currently supported by AWS Lambda durable functions. | ||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-hitl-approval-sam | ||
|
|
||
| ## Architecture | ||
|
|
||
|  | ||
|
|
||
| The pattern uses Lambda durable functions to implement a cost-effective approval workflow that can wait up to 24 hours without incurring compute charges during the wait period. | ||
|
|
||
| ### Workflow Steps | ||
|
|
||
| 1. **User submits approval request** via Amazon API Gateway | ||
| 2. **Durable Function validates request** and creates a callback | ||
| 3. **UUID mapping stored in Amazon DynamoDB** (callback ID → UUID) | ||
| 4. **Email notification sent via SNS** with approve/reject links | ||
| 5. **Function pauses execution** (no compute charges during wait) | ||
| 6. **Approver clicks link** in email | ||
| 7. **Callback Handler retrieves callback ID** from DynamoDB | ||
| 8. **Callback sent to Lambda** using `SendDurableExecutionCallbackSuccess` | ||
| 9. **Durable Function resumes** and processes the decision | ||
|
|
||
| ## Key Features | ||
|
|
||
| - ✅ **24-Hour Wait Time** - Can wait up to 24 hours for approval | ||
| - ✅ **No Compute Charges During Wait** - Function suspended during wait period | ||
| - ✅ **Email Notifications** - Sends approval requests with clickable links | ||
| - ✅ **Short, Clean URLs** - Uses UUID instead of long callback IDs | ||
| - ✅ **DynamoDB Mapping** - Stores UUID → callback ID mapping with TTL | ||
| - ✅ **Automatic Timeout** - Auto-rejects after 24 hours | ||
| - ✅ **HTML Response Pages** - Beautiful approval/rejection confirmation pages | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
| * [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed | ||
| * Python 3.14 runtime (automatically provided by Lambda) | ||
|
|
||
| ## Deployment | ||
|
|
||
| 1. Navigate to the pattern directory: | ||
| ```bash | ||
| cd lambda-durable-hitl-approval-sam | ||
| ``` | ||
|
|
||
| 2. Build the SAM application: | ||
| ```bash | ||
| sam build | ||
| ``` | ||
|
|
||
| 3. Deploy the application (must use us-east-2 region): | ||
| ```bash | ||
| sam deploy --guided --region us-east-2 | ||
| ``` | ||
|
|
||
| During the guided deployment, provide the required values: | ||
| - **ApproverEmail**: Enter your email address to receive approval notifications | ||
| - Allow SAM CLI to create IAM roles when prompted | ||
|
|
||
| 4. **Confirm SNS subscription**: Check your email and click the confirmation link from Amazon SNS | ||
|
|
||
| 5. Note the `ApiEndpoint` from the outputs | ||
|
|
||
| ## Testing | ||
|
|
||
| ### Submit an Approval Request | ||
|
|
||
| ```bash | ||
| curl -X POST https://YOUR-API-ID.execute-api.us-east-2.amazonaws.com/prod/requests \ | ||
| -H "Content-Type: application/json" \ | ||
| -d '{ | ||
| "requestId": "REQ-001", | ||
| "amount": 5000, | ||
| "description": "New server purchase" | ||
| }' | ||
| ``` | ||
|
|
||
| Response: | ||
| ```json | ||
| { | ||
| "message": "Request accepted" | ||
| } | ||
| ``` | ||
|
|
||
| ### Check Your Email | ||
|
|
||
| You'll receive an email with: | ||
| - Request details (ID, amount, description) | ||
| - **APPROVE** link | ||
| - **REJECT** link | ||
| - Expiration time (24 hours) | ||
|
|
||
| ### Click Approve or Reject | ||
|
|
||
| Click one of the links in the email. You'll see a confirmation page that displays a checkmark or X icon along with either a "Request Approved!" or "Request Rejected!" message. The page will also confirm that the workflow has been notified of your decision. | ||
|
|
||
|
|
||
|
|
||
| ## How It Works | ||
|
|
||
| ### Callback Creation | ||
|
|
||
| The durable function creates a callback and stores the mapping: | ||
|
|
||
| ```python | ||
| from aws_durable_execution_sdk_python import DurableContext, durable_execution | ||
| from aws_durable_execution_sdk_python.config import CallbackConfig, Duration | ||
|
|
||
| @durable_execution | ||
| def lambda_handler(event, context: DurableContext): | ||
| # Create callback with 24-hour timeout | ||
| callback = context.create_callback( | ||
| name='wait-for-approval', | ||
| config=CallbackConfig(timeout=Duration.from_hours(24)) | ||
| ) | ||
|
|
||
| # Generate short UUID and store mapping in DynamoDB | ||
| request_uuid = str(uuid.uuid4()) | ||
| table.put_item(Item={ | ||
| 'uuid': request_uuid, | ||
| 'callbackId': callback.callback_id, | ||
| 'ttl': int(time.time()) + 86400 # 24 hours | ||
| }) | ||
|
|
||
| # Send email with UUID-based URLs | ||
| approve_url = f"{api_base_url}/approve/{request_uuid}" | ||
|
|
||
| # Wait for callback result | ||
| approval = callback.result() | ||
| ``` | ||
|
|
||
| ### Callback Handler | ||
|
|
||
| When user clicks approve/reject: | ||
|
|
||
| ```python | ||
| def lambda_handler(event, context): | ||
| # Get UUID from URL path | ||
| request_uuid = event['pathParameters']['uuid'] | ||
|
|
||
| # Fetch callback ID from DynamoDB | ||
| response = table.get_item(Key={'uuid': request_uuid}) | ||
| callback_id = response['Item']['callbackId'] | ||
|
|
||
| # Send callback to durable function | ||
| lambda_client.send_durable_execution_callback_success( | ||
| CallbackId=callback_id, | ||
| Result=json.dumps({'decision': 'approved'}) | ||
| ) | ||
| ``` | ||
|
|
||
|
|
||
| ## Configuration | ||
|
|
||
| ### Adjust Timeout Duration | ||
|
|
||
| To change the timeout duration, you need to update both the Lambda function configuration and the callback configuration: | ||
|
|
||
| Modify in `template.yaml`: | ||
|
|
||
| ```yaml | ||
| DurableConfig: | ||
| ExecutionTimeout: 86400 # 24 hours in seconds | ||
| ``` | ||
|
|
||
| And in `src/lambda_function.py`: | ||
|
|
||
| ```python | ||
| config=CallbackConfig(timeout=Duration.from_hours(24)) | ||
| ``` | ||
|
|
||
| Both values must match: `ExecutionTimeout` sets the maximum runtime for the durable function, while `CallbackConfig.timeout` sets how long the callback will wait before timing out. | ||
|
|
||
| ### Change Email Address | ||
|
|
||
| Update during deployment or redeploy with new email: | ||
|
|
||
| ```bash | ||
| sam deploy --parameter-overrides ApproverEmail=new-email@example.com | ||
| ``` | ||
|
|
||
| ## Use Cases | ||
|
|
||
| - **Expense Approvals** - Wait for manager approval on spending requests | ||
| - **Document Reviews** - Pause workflow while documents are reviewed | ||
| - **Deployment Approvals** - Require human approval before production deployments | ||
| - **Access Requests** - Pause while security team reviews access requests | ||
| - **Contract Approvals** - Wait for legal team approval on contracts | ||
|
|
||
| ## Monitoring | ||
agawanea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| ### CloudWatch Logs | ||
|
|
||
| Monitor the durable function: | ||
| ```bash | ||
| aws logs tail /aws/lambda/lambda-durable-hitl-approval-ApprovalFunction-XXXXX \ | ||
| --region us-east-2 \ | ||
| --follow | ||
| ``` | ||
|
|
||
| Monitor the callback handler: | ||
| ```bash | ||
| aws logs tail /aws/lambda/lambda-durable-hitl-approv-CallbackHandlerFunction-XXXXX \ | ||
| --region us-east-2 \ | ||
| --follow | ||
| ``` | ||
|
|
||
|
|
||
|
|
||
| ## Cleanup | ||
|
|
||
| ```bash | ||
| sam delete --stack-name lambda-durable-hitl-approval --region us-east-2 | ||
| ``` | ||
|
|
||
|
|
||
| ## Learn More | ||
|
|
||
| - [Lambda durable functions Documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) | ||
| - [Durable Execution SDK (Python)](https://github.com/aws/aws-durable-execution-sdk-python) | ||
| - [Callback Operations](https://docs.aws.amazon.com/lambda/latest/dg/durable-callback.html) | ||
| - [SendDurableExecutionCallbackSuccess API](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda/client/send_durable_execution_callback_success.html) | ||
|
|
||
| --- | ||
|
|
||
| Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: MIT-0 | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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,62 @@ | ||
| { | ||
| "title": "Human-in-the-Loop Approval Workflow with Lambda durable functions", | ||
| "description": "Approval workflow that pauses execution while waiting for human decisions, with automatic timeout handling and callback-based resumption", | ||
| "language": "Python", | ||
| "level": "300", | ||
| "framework": "AWS SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern demonstrates a human-in-the-loop approval workflow using Lambda durable functions with callback operations.", | ||
| "The workflow pauses execution using create_callback() while waiting for human approval, incurring no compute charges during the wait period.", | ||
| "If no decision is received within 24 hours, the workflow automatically times out and rejects the request.", | ||
| "When an approver submits a decision via API, the durable function resumes from its checkpoint and processes the result.", | ||
| "The pattern uses DynamoDB to map short UUIDs to callback IDs for clean approval URLs, and SNS to send email notifications with approve/reject links." | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-human-approval-sam", | ||
| "templateURL": "serverless-patterns/lambda-durable-human-approval-sam", | ||
| "projectFolder": "lambda-durable-human-approval-sam", | ||
| "templateFile": "template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "Lambda durable functions Documentation", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" | ||
| }, | ||
| { | ||
| "text": "Durable Execution SDK for Python", | ||
| "link": "https://github.com/aws/aws-durable-execution-sdk-python" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "Note: Lambda durable functions have limited regional availability. Please check the AWS documentation for current regional support.", | ||
| "sam build", | ||
| "sam deploy --guided --region us-east-2" | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "text": [ | ||
| "See the GitHub repo for detailed testing instructions." | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "text": [ | ||
| "Delete the stack: <code>sam delete --region us-east-2</code>." | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Abhishek Agawane", | ||
| "image": "https://drive.google.com/file/d/1E-5koDaKEaMUtOctX32I9TLwfh3kgpAq/view?usp=drivesdk", | ||
| "bio": "Abhishek Agawane is a Security Consultant at Amazon Web Services with more than 8 years of industry experience. He helps organizations architect resilient, secure, and efficient cloud environments, guiding them through complex challenges and large-scale infrastructure transformations. He has helped numerous organizations enhance their cloud operations through targeted optimizations, robust architectures, and best-practice implementations.", | ||
| "linkedin": "agawabhi" | ||
| } | ||
| ] | ||
| } |
92 changes: 92 additions & 0 deletions
92
lambda-durable-human-approval-sam/lambda-durable-human-approval-sam.json
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,92 @@ | ||
| { | ||
| "title": "Human-in-the-Loop Approval Workflow with Lambda durable functions", | ||
| "description": "Approval workflow that pauses execution while waiting for human decisions, with automatic timeout handling and callback-based resumption", | ||
| "language": "Python", | ||
| "level": "300", | ||
| "framework": "AWS SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern demonstrates a human-in-the-loop approval workflow using Lambda durable functions with callback operations.", | ||
| "The workflow pauses execution using create_callback() while waiting for human approval, incurring no compute charges during the wait period.", | ||
| "If no decision is received within 24 hours, the workflow automatically times out and rejects the request.", | ||
| "When an approver submits a decision via API, the durable function resumes from its checkpoint and processes the result.", | ||
| "The pattern uses DynamoDB to map short UUIDs to callback IDs for clean approval URLs, and SNS to send email notifications with approve/reject links." | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-human-approval-sam", | ||
| "templateURL": "serverless-patterns/lambda-durable-human-approval-sam", | ||
| "projectFolder": "lambda-durable-human-approval-sam", | ||
| "templateFile": "template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "Lambda durable functions Documentation", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" | ||
| }, | ||
| { | ||
| "text": "Durable Execution SDK for Python", | ||
| "link": "https://github.com/aws/aws-durable-execution-sdk-python" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "Note: Lambda durable functions have limited regional availability. Please check the AWS documentation for current regional support.", | ||
| "sam build", | ||
| "sam deploy --guided --region us-east-2" | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "text": [ | ||
| "See the GitHub repo for detailed testing instructions." | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "text": [ | ||
| "Delete the stack: <code>sam delete --region us-east-2</code>." | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Abhishek Agawane", | ||
| "image": "https://drive.google.com/file/d/1E-5koDaKEaMUtOctX32I9TLwfh3kgpAq/view?usp=drivesdk", | ||
| "bio": "Abhishek Agawane is a Security Consultant at Amazon Web Services with more than 8 years of industry experience. He helps organizations architect resilient, secure, and efficient cloud environments, guiding them through complex challenges and large-scale infrastructure transformations. He has helped numerous organizations enhance their cloud operations through targeted optimizations, robust architectures, and best-practice implementations.", | ||
| "linkedin": "agawabhi" | ||
| } | ||
| ], | ||
| "patternArch": { | ||
| "icon1": { | ||
| "x": 15, | ||
| "y": 50, | ||
| "service": "apigw", | ||
| "label": "Amazon API Gateway" | ||
| }, | ||
| "icon2": { | ||
| "x": 50, | ||
| "y": 50, | ||
| "service": "lambda", | ||
| "label": "AWS Lambda durable functions" | ||
| }, | ||
| "icon3": { | ||
| "x": 85, | ||
| "y": 50, | ||
| "service": "dynamodb", | ||
| "label": "Amazon DynamoDB" | ||
| }, | ||
| "line1": { | ||
| "from": "icon1", | ||
| "to": "icon2", | ||
| "label": "" | ||
| }, | ||
| "line2": { | ||
| "from": "icon2", | ||
| "to": "icon3", | ||
| "label": "" | ||
| } | ||
| } | ||
| } |
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.