Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
267 changes: 267 additions & 0 deletions lambda-durable-human-approval-sam/README.md
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.

**Important:** Lambda Durable Functions are currently available in the **us-east-2 (Ohio)** region only.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-hitl-approval-sam

## Architecture

![Architecture Diagram](architecture.png)

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 API Gateway
2. **Durable Function validates request** and creates a callback
3. **UUID mapping stored in 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:
- 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

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:
- ✓ 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

**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))
```

### 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

### 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

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.
62 changes: 62 additions & 0 deletions lambda-durable-human-approval-sam/example-pattern.json
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 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/"
}
]
}
Loading