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 3 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,267 @@ | ||
| # Human-in-the-Loop Approval Workflow with 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. | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| **Important:** Lambda Durable Functions are currently available in the **us-east-2 (Ohio)** region only. | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| 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. | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### Workflow Steps | ||
|
|
||
| 1. **User submits approval request** via API Gateway | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 2. **Durable Function validates request** and creates a callback | ||
| 3. **UUID mapping stored in DynamoDB** (callback ID → UUID) | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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: | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - Stack Name: `lambda-durable-hitl-approval` | ||
| - AWS Region: `us-east-2` | ||
| - Parameter ApproverEmail: `your-email@example.com` | ||
| - Confirm changes: `N` | ||
| - Allow SAM CLI IAM role creation: `Y` | ||
| - Disable rollback: `N` | ||
| - Save arguments to config file: `Y` | ||
|
|
||
| 4. **Confirm SNS subscription**: Check your email and click the confirmation link from AWS SNS | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| 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 with: | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - ✓ or ✗ icon | ||
| - "Request Approved!" or "Request Rejected!" message | ||
| - Confirmation that the workflow has been notified | ||
|
|
||
| ### Monitor the Workflow | ||
|
|
||
| ```bash | ||
| # View durable function logs | ||
| aws logs tail /aws/lambda/lambda-durable-hitl-approval-ApprovalFunction-XXXXX \ | ||
| --follow \ | ||
| --region us-east-2 | ||
| ``` | ||
|
|
||
| Look for: | ||
| - `Starting approval workflow for request: REQ-001` | ||
| - `Approval request sent. UUID: <uuid>` | ||
| - `Approval workflow completed: approved` (or `rejected`) | ||
|
|
||
| ## 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'}) | ||
| ) | ||
| ``` | ||
|
|
||
| ### Cost Efficiency | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| **Traditional Lambda approach:** | ||
| - Cannot wait more than 15 minutes (Lambda max timeout) | ||
| - Would need Step Functions or polling mechanism | ||
| - Complex state management | ||
|
|
||
| **Durable Functions approach:** | ||
| - Wait up to 24 hours | ||
| - No compute charges during wait | ||
| - Simple, clean code | ||
| - Automatic state management | ||
|
|
||
| ## Configuration | ||
|
|
||
| ### Adjust Timeout Duration | ||
|
|
||
| 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)) | ||
agawanea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ``` | ||
|
|
||
| ### 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 | ||
| ``` | ||
|
|
||
| ### DynamoDB Table | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Check the callback mappings: | ||
| ```bash | ||
| aws dynamodb scan \ | ||
| --table-name lambda-durable-hitl-approval-callbacks \ | ||
| --region us-east-2 | ||
| ``` | ||
|
|
||
| ## 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", | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "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 are currently available in us-east-2 (Ohio) region only.", | ||
| "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": "https://www.linkedin.com/in/agawabhi/" | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| ] | ||
| } | ||
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.