|
| 1 | +# Human-in-the-Loop Approval Workflow with AWS Lambda durable functions |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +**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. |
| 6 | + |
| 7 | +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-hitl-approval-sam |
| 8 | + |
| 9 | +## Architecture |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +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. |
| 14 | + |
| 15 | +### Workflow Steps |
| 16 | + |
| 17 | +1. **User submits approval request** via Amazon API Gateway |
| 18 | +2. **Durable Function validates request** and creates a callback |
| 19 | +3. **UUID mapping stored in Amazon DynamoDB** (callback ID → UUID) |
| 20 | +4. **Email notification sent via SNS** with approve/reject links |
| 21 | +5. **Function pauses execution** (no compute charges during wait) |
| 22 | +6. **Approver clicks link** in email |
| 23 | +7. **Callback Handler retrieves callback ID** from DynamoDB |
| 24 | +8. **Callback sent to Lambda** using `SendDurableExecutionCallbackSuccess` |
| 25 | +9. **Durable Function resumes** and processes the decision |
| 26 | + |
| 27 | +## Key Features |
| 28 | + |
| 29 | +- ✅ **24-Hour Wait Time** - Can wait up to 24 hours for approval |
| 30 | +- ✅ **No Compute Charges During Wait** - Function suspended during wait period |
| 31 | +- ✅ **Email Notifications** - Sends approval requests with clickable links |
| 32 | +- ✅ **Short, Clean URLs** - Uses UUID instead of long callback IDs |
| 33 | +- ✅ **DynamoDB Mapping** - Stores UUID → callback ID mapping with TTL |
| 34 | +- ✅ **Automatic Timeout** - Auto-rejects after 24 hours |
| 35 | +- ✅ **HTML Response Pages** - Beautiful approval/rejection confirmation pages |
| 36 | + |
| 37 | +## Prerequisites |
| 38 | + |
| 39 | +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured |
| 40 | +* [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed |
| 41 | +* Python 3.14 runtime (automatically provided by Lambda) |
| 42 | + |
| 43 | +## Deployment |
| 44 | + |
| 45 | +1. Navigate to the pattern directory: |
| 46 | + ```bash |
| 47 | + cd lambda-durable-hitl-approval-sam |
| 48 | + ``` |
| 49 | + |
| 50 | +2. Build the SAM application: |
| 51 | + ```bash |
| 52 | + sam build |
| 53 | + ``` |
| 54 | + |
| 55 | +3. Deploy the application (must use us-east-2 region): |
| 56 | + ```bash |
| 57 | + sam deploy --guided --region us-east-2 |
| 58 | + ``` |
| 59 | + |
| 60 | + During the guided deployment, provide the required values: |
| 61 | + - **ApproverEmail**: Enter your email address to receive approval notifications |
| 62 | + - Allow SAM CLI to create IAM roles when prompted |
| 63 | + |
| 64 | +4. **Confirm SNS subscription**: Check your email and click the confirmation link from Amazon SNS |
| 65 | + |
| 66 | +5. Note the `ApiEndpoint` from the outputs |
| 67 | + |
| 68 | +## Testing |
| 69 | + |
| 70 | +### Submit an Approval Request |
| 71 | + |
| 72 | +```bash |
| 73 | +curl -X POST https://YOUR-API-ID.execute-api.us-east-2.amazonaws.com/prod/requests \ |
| 74 | + -H "Content-Type: application/json" \ |
| 75 | + -d '{ |
| 76 | + "requestId": "REQ-001", |
| 77 | + "amount": 5000, |
| 78 | + "description": "New server purchase" |
| 79 | + }' |
| 80 | +``` |
| 81 | + |
| 82 | +Response: |
| 83 | +```json |
| 84 | +{ |
| 85 | + "message": "Request accepted" |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +### Check Your Email |
| 90 | + |
| 91 | +You'll receive an email with: |
| 92 | +- Request details (ID, amount, description) |
| 93 | +- **APPROVE** link |
| 94 | +- **REJECT** link |
| 95 | +- Expiration time (24 hours) |
| 96 | + |
| 97 | +### Click Approve or Reject |
| 98 | + |
| 99 | +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. |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | +## How It Works |
| 104 | + |
| 105 | +### Callback Creation |
| 106 | + |
| 107 | +The durable function creates a callback and stores the mapping: |
| 108 | + |
| 109 | +```python |
| 110 | +from aws_durable_execution_sdk_python import DurableContext, durable_execution |
| 111 | +from aws_durable_execution_sdk_python.config import CallbackConfig, Duration |
| 112 | + |
| 113 | +@durable_execution |
| 114 | +def lambda_handler(event, context: DurableContext): |
| 115 | + # Create callback with 24-hour timeout |
| 116 | + callback = context.create_callback( |
| 117 | + name='wait-for-approval', |
| 118 | + config=CallbackConfig(timeout=Duration.from_hours(24)) |
| 119 | + ) |
| 120 | + |
| 121 | + # Generate short UUID and store mapping in DynamoDB |
| 122 | + request_uuid = str(uuid.uuid4()) |
| 123 | + table.put_item(Item={ |
| 124 | + 'uuid': request_uuid, |
| 125 | + 'callbackId': callback.callback_id, |
| 126 | + 'ttl': int(time.time()) + 86400 # 24 hours |
| 127 | + }) |
| 128 | + |
| 129 | + # Send email with UUID-based URLs |
| 130 | + approve_url = f"{api_base_url}/approve/{request_uuid}" |
| 131 | + |
| 132 | + # Wait for callback result |
| 133 | + approval = callback.result() |
| 134 | +``` |
| 135 | + |
| 136 | +### Callback Handler |
| 137 | + |
| 138 | +When user clicks approve/reject: |
| 139 | + |
| 140 | +```python |
| 141 | +def lambda_handler(event, context): |
| 142 | + # Get UUID from URL path |
| 143 | + request_uuid = event['pathParameters']['uuid'] |
| 144 | + |
| 145 | + # Fetch callback ID from DynamoDB |
| 146 | + response = table.get_item(Key={'uuid': request_uuid}) |
| 147 | + callback_id = response['Item']['callbackId'] |
| 148 | + |
| 149 | + # Send callback to durable function |
| 150 | + lambda_client.send_durable_execution_callback_success( |
| 151 | + CallbackId=callback_id, |
| 152 | + Result=json.dumps({'decision': 'approved'}) |
| 153 | + ) |
| 154 | +``` |
| 155 | + |
| 156 | + |
| 157 | +## Configuration |
| 158 | + |
| 159 | +### Adjust Timeout Duration |
| 160 | + |
| 161 | +To change the timeout duration, you need to update both the Lambda function configuration and the callback configuration: |
| 162 | + |
| 163 | +Modify in `template.yaml`: |
| 164 | + |
| 165 | +```yaml |
| 166 | +DurableConfig: |
| 167 | + ExecutionTimeout: 86400 # 24 hours in seconds |
| 168 | +``` |
| 169 | +
|
| 170 | +And in `src/lambda_function.py`: |
| 171 | + |
| 172 | +```python |
| 173 | +config=CallbackConfig(timeout=Duration.from_hours(24)) |
| 174 | +``` |
| 175 | + |
| 176 | +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. |
| 177 | + |
| 178 | +### Change Email Address |
| 179 | + |
| 180 | +Update during deployment or redeploy with new email: |
| 181 | + |
| 182 | +```bash |
| 183 | +sam deploy --parameter-overrides ApproverEmail=new-email@example.com |
| 184 | +``` |
| 185 | + |
| 186 | +## Use Cases |
| 187 | + |
| 188 | +- **Expense Approvals** - Wait for manager approval on spending requests |
| 189 | +- **Document Reviews** - Pause workflow while documents are reviewed |
| 190 | +- **Deployment Approvals** - Require human approval before production deployments |
| 191 | +- **Access Requests** - Pause while security team reviews access requests |
| 192 | +- **Contract Approvals** - Wait for legal team approval on contracts |
| 193 | + |
| 194 | +## Monitoring |
| 195 | + |
| 196 | +### CloudWatch Logs |
| 197 | + |
| 198 | +Monitor the durable function: |
| 199 | +```bash |
| 200 | +aws logs tail /aws/lambda/lambda-durable-hitl-approval-ApprovalFunction-XXXXX \ |
| 201 | + --region us-east-2 \ |
| 202 | + --follow |
| 203 | +``` |
| 204 | + |
| 205 | +Monitor the callback handler: |
| 206 | +```bash |
| 207 | +aws logs tail /aws/lambda/lambda-durable-hitl-approv-CallbackHandlerFunction-XXXXX \ |
| 208 | + --region us-east-2 \ |
| 209 | + --follow |
| 210 | +``` |
| 211 | + |
| 212 | + |
| 213 | + |
| 214 | +## Cleanup |
| 215 | + |
| 216 | +```bash |
| 217 | +sam delete --stack-name lambda-durable-hitl-approval --region us-east-2 |
| 218 | +``` |
| 219 | + |
| 220 | + |
| 221 | +## Learn More |
| 222 | + |
| 223 | +- [Lambda durable functions Documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) |
| 224 | +- [Durable Execution SDK (Python)](https://github.com/aws/aws-durable-execution-sdk-python) |
| 225 | +- [Callback Operations](https://docs.aws.amazon.com/lambda/latest/dg/durable-callback.html) |
| 226 | +- [SendDurableExecutionCallbackSuccess API](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda/client/send_durable_execution_callback_success.html) |
| 227 | + |
| 228 | +--- |
| 229 | + |
| 230 | +Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 231 | + |
| 232 | +SPDX-License-Identifier: MIT-0 |
0 commit comments