diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/.gitignore b/eventbridge-schedule-to-lambda-dlq-sam-python/.gitignore new file mode 100644 index 000000000..4debda36a --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/.gitignore @@ -0,0 +1,46 @@ +# SAM build artifacts +.aws-sam/ +samconfig.toml + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +env/ +venv/ +ENV/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log + +# Environment variables +.env +.env.local diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/README.md b/eventbridge-schedule-to-lambda-dlq-sam-python/README.md new file mode 100644 index 000000000..fbac88cff --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/README.md @@ -0,0 +1,166 @@ +# Amazon EventBridge Scheduler to AWS Lambda with Dual Dead Letter Queues + +This pattern demonstrates how to use Amazon EventBridge Scheduler to invoke AWS Lambda functions with comprehensive failure handling through dual Dead Letter Queues (DLQs). The pattern is deployed using the AWS Serverless Application Model (SAM). + +Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns](https://serverlessland.com/patterns) + +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 + +## 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 eventbridge-schedule-to-lambda-dlq-sam-python + ``` +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 + * 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 showcases EventBridge Scheduler's robust failure handling capabilities through two distinct failure paths: + +### Dual Dead Letter Queue Architecture + +**Lambda Execution DLQ**: Captures failures that occur during Lambda function execution (code errors, timeouts, out-of-memory errors). After Lambda's built-in async retry mechanism exhausts its attempts (default: 2 retries), failed events are sent to this queue. + +**EventBridge Scheduler DLQ**: Captures failures that occur at the invocation level before the Lambda function executes. This includes: +- IAM permission errors (scheduler role lacks lambda:InvokeFunction permission) +- Lambda service throttling (concurrent execution limits reached) +- Lambda function state issues (function being deleted, doesn't exist, invalid ARN) +- Resource not found errors (function deleted after schedule creation) +- Maximum event age exceeded (event couldn't be delivered within configured time window) +- Maximum retry attempts exhausted (all scheduler retries failed) + +### Workflow + +1. EventBridge Scheduler invokes the Lambda function asynchronously every 5 minutes +2. If invocation fails (permissions, throttling, etc.), EventBridge Scheduler retries up to 3 times +3. After scheduler retries are exhausted, the event is sent to the EventBridge Scheduler DLQ +4. If invocation succeeds but execution fails (code error), Lambda retries automatically +5. After Lambda retries are exhausted, the event is sent to the Lambda Execution DLQ + +This dual DLQ architecture provides complete visibility into both configuration-level and code-level failures, enabling appropriate remediation strategies for each failure type. + +## Testing + +### Test Normal Execution + +The function runs automatically every 5 minutes. View the logs: + +```bash +# Get function name from stack outputs +FUNCTION_NAME=$(aws cloudformation describe-stacks \ + --stack-name \ + --query 'Stacks[0].Outputs[?OutputKey==`ScheduledFunctionName`].OutputValue' \ + --output text) + +# Tail logs +aws logs tail /aws/lambda/${FUNCTION_NAME} --follow +``` + +### Test Lambda Execution Failure + +Enable failure simulation to test the Lambda Execution DLQ: + +```bash +# Update function to simulate failures +aws lambda update-function-configuration \ + --function-name ${FUNCTION_NAME} \ + --environment 'Variables={LOG_LEVEL=INFO,SIMULATE_FAILURE=true}' +``` + +Wait up to 5 minutes for the next scheduled execution. After Lambda retries are exhausted, check the Lambda Execution DLQ: + +```bash +LAMBDA_DLQ_URL=$(aws cloudformation describe-stacks \ + --stack-name \ + --query 'Stacks[0].Outputs[?OutputKey==`LambdaExecutionDLQUrl`].OutputValue' \ + --output text) + +aws sqs receive-message --queue-url ${LAMBDA_DLQ_URL} +``` + +Disable failure simulation: + +```bash +aws lambda update-function-configuration \ + --function-name ${FUNCTION_NAME} \ + --environment 'Variables={LOG_LEVEL=INFO,SIMULATE_FAILURE=false}' +``` + +### Test EventBridge Scheduler Invocation Failure + +Remove Lambda invoke permission to test the EventBridge Scheduler DLQ: + +```bash +# Get schedule name +SCHEDULE_NAME=$(aws cloudformation describe-stacks \ + --stack-name \ + --query 'Stacks[0].Outputs[?OutputKey==`ScheduleName`].OutputValue' \ + --output text) + +# Get scheduler role name +SCHEDULER_ROLE=$(aws cloudformation describe-stack-resources \ + --stack-name \ + --logical-resource-id SchedulerRole \ + --query 'StackResources[0].PhysicalResourceId' \ + --output text) + +# Remove Lambda invoke permission +aws iam delete-role-policy \ + --role-name ${SCHEDULER_ROLE} \ + --policy-name InvokeLambda +``` + +Wait up to 5 minutes for the next scheduled execution. After scheduler retries are exhausted, check the Scheduler DLQ: + +```bash +SCHEDULER_DLQ_URL=$(aws cloudformation describe-stacks \ + --stack-name \ + --query 'Stacks[0].Outputs[?OutputKey==`SchedulerDLQUrl`].OutputValue' \ + --output text) + +aws sqs receive-message --queue-url ${SCHEDULER_DLQ_URL} +``` + +Restore permissions by redeploying: + +```bash +sam deploy +``` + +## Cleanup + +1. Delete the stack + ```bash + sam delete --stack-name + ``` +1. Confirm the stack has been deleted + ```bash + aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'')].StackStatus" + ``` +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/example-pattern.json b/eventbridge-schedule-to-lambda-dlq-sam-python/example-pattern.json new file mode 100644 index 000000000..1cd5ea378 --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/example-pattern.json @@ -0,0 +1,68 @@ +{ + "title": "Amazon EventBridge Scheduler to AWS Lambda with Dual Dead Letter Queues", + "description": "Creates an EventBridge schedule to invoke a Lambda function with dual DLQs for comprehensive failure handling", + "language": "Python", + "level": "200", + "framework": "AWS SAM", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern demonstrates EventBridge Scheduler's failure handling capabilities through dual Dead Letter Queues. One DLQ captures Lambda execution failures (code errors, timeouts), while the other captures scheduler invocation failures (permissions, throttling, resource not found).", + "The pattern is deployed using the AWS Serverless Application Model (SAM) and includes a Python-based Lambda function that can simulate failures for testing both DLQ paths." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/eventbridge-schedule-to-lambda-dlq-sam-python", + "templateURL": "serverless-patterns/eventbridge-schedule-to-lambda-dlq-sam-python", + "projectFolder": "eventbridge-schedule-to-lambda-dlq-sam-python", + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Getting Started with EventBridge Scheduler", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/getting-started.html" + }, + { + "text": "EventBridge Scheduler Retry Policies", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule-retry.html" + }, + { + "text": "EventBridge Scheduler Dead Letter Queues", + "link": "https://docs.aws.amazon.com/scheduler/latest/UserGuide/configuring-schedule-dlq.html" + }, + { + "text": "Lambda Asynchronous Invocation", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html" + }, + { + "text": "SQS Dead Letter Queues", + "link": "https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html" + } + ] + }, + "deploy": { + "text": [ + "See the GitHub repo for detailed deployment instructions." + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: sam delete --stack-name STACK_NAME" + ] + }, + "authors": [ + { + "name": "Sasidharan Ramasamy", + "bio": "Technical Account Manager @ AWS with over 10 years of industry experience", + "linkedin": "https://www.linkedin.com/in/sasidharan-ramasamy/" + } + ] +} diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/app.py b/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/app.py new file mode 100644 index 000000000..5318c3612 --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/app.py @@ -0,0 +1,106 @@ +import json +import os +import time +import random +from datetime import datetime + + +def lambda_handler(event, context): + """ + Main scheduled Lambda function invoked by EventBridge Scheduler. + Simulates processing work and can simulate failures for testing. + """ + print('=' * 80) + print('SCHEDULED LAMBDA EXECUTION - Started') + print('=' * 80) + + log_info('Scheduled function invoked by EventBridge Scheduler', {'event': event}) + + execution_time = datetime.utcnow().isoformat() + 'Z' + simulate_failure = os.environ.get('SIMULATE_FAILURE', 'false').lower() == 'true' + + try: + print(f'\nExecution Time: {execution_time}') + print(f'Simulate Failure: {simulate_failure}') + + # Simulate failure if environment variable is set + if simulate_failure: + print('\nSIMULATING FAILURE') + print('This will trigger:') + print('1. Lambda async retry (up to 2 times)') + print('2. After all retries fail - Event sent to Lambda Execution DLQ') + raise Exception('Simulated failure for testing Lambda Execution DLQ flow') + + # Simulate some processing work + print('\nProcessing scheduled task...') + + # Example: Process data, call APIs, update databases, etc. + processing_result = { + 'tasksProcessed': random.randint(1, 100), + 'recordsUpdated': random.randint(0, 50), + 'apiCallsMade': random.randint(0, 10), + 'dataProcessedMB': round(random.uniform(0, 100), 2) + } + + print(f'Tasks processed: {processing_result["tasksProcessed"]}') + print(f'Records updated: {processing_result["recordsUpdated"]}') + print(f'API calls made: {processing_result["apiCallsMade"]}') + print(f'Data processed: {processing_result["dataProcessedMB"]} MB') + + # Simulate processing time + time.sleep(0.1 + random.random() * 0.4) + + result = { + 'statusCode': 200, + 'success': True, + 'executionTime': execution_time, + 'processingResult': processing_result, + 'message': 'Scheduled task completed successfully' + } + + log_info('Scheduled function completed successfully', {'result': result}) + + print('\n' + '=' * 80) + print('SCHEDULED LAMBDA EXECUTION - Completed Successfully') + print('=' * 80 + '\n') + + return result + + except Exception as error: + print('\n' + '=' * 80) + print('SCHEDULED LAMBDA EXECUTION - Failed') + print(f'Error: {str(error)}') + print('Lambda async retry will attempt this execution again') + print('After retries exhausted, event goes to Lambda Execution DLQ') + print('=' * 80 + '\n') + + log_error('Scheduled function failed', error, {'executionTime': execution_time}) + + # Re-raise to trigger retry and DLQ behavior + raise + + +def log_info(message, data=None): + """Log informational message in JSON format""" + log_entry = { + 'timestamp': datetime.utcnow().isoformat() + 'Z', + 'level': 'INFO', + 'message': message + } + if data: + log_entry.update(data) + print(json.dumps(log_entry)) + + +def log_error(message, error, data=None): + """Log error message in JSON format""" + log_entry = { + 'timestamp': datetime.utcnow().isoformat() + 'Z', + 'level': 'ERROR', + 'message': message, + 'error': str(error), + 'errorType': type(error).__name__ + } + if data: + log_entry.update(data) + print(json.dumps(log_entry)) diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/requirements.txt b/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/requirements.txt new file mode 100644 index 000000000..be5f87456 --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/requirements.txt @@ -0,0 +1,2 @@ +# No external dependencies required +# Using only Python standard library diff --git a/eventbridge-schedule-to-lambda-dlq-sam-python/template.yaml b/eventbridge-schedule-to-lambda-dlq-sam-python/template.yaml new file mode 100644 index 000000000..aa115f4b6 --- /dev/null +++ b/eventbridge-schedule-to-lambda-dlq-sam-python/template.yaml @@ -0,0 +1,162 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + EventBridge Scheduler with Lambda and Dual SQS DLQs + + This pattern showcases EventBridge Scheduler's robust failure handling capabilities + with separate DLQs for Lambda execution failures and EventBridge invocation failures. + +Globals: + Function: + Timeout: 30 + Runtime: python3.12 + Architectures: + - x86_64 + +Resources: + # Main Lambda Function (invoked by EventBridge Scheduler) + ScheduledFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: src/scheduled/ + Handler: app.lambda_handler + Description: Main function invoked by EventBridge Scheduler + Environment: + Variables: + LOG_LEVEL: INFO + SIMULATE_FAILURE: false + DeadLetterQueue: + Type: SQS + TargetArn: !GetAtt LambdaExecutionDLQ.Arn + Policies: + - SQSSendMessagePolicy: + QueueName: !GetAtt LambdaExecutionDLQ.QueueName + + # Dead Letter Queue for Lambda execution failures + LambdaExecutionDLQ: + Type: AWS::SQS::Queue + Properties: + QueueName: !Sub '${AWS::StackName}-lambda-dlq' + MessageRetentionPeriod: 1209600 # 14 days + VisibilityTimeout: 300 + Tags: + - Key: Pattern + Value: EventBridge-Scheduler-Lambda-DLQ + + # Dead Letter Queue for EventBridge Scheduler invocation failures + SchedulerDLQ: + Type: AWS::SQS::Queue + Properties: + QueueName: !Sub '${AWS::StackName}-scheduler-dlq' + MessageRetentionPeriod: 1209600 # 14 days + VisibilityTimeout: 300 + Tags: + - Key: Pattern + Value: EventBridge-Scheduler-Lambda-DLQ + + # Queue Policy to allow EventBridge Scheduler to send messages to DLQ + SchedulerDLQPolicy: + Type: AWS::SQS::QueuePolicy + Properties: + Queues: + - !Ref SchedulerDLQ + PolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: AllowEventBridgeSchedulerToSendMessage + Effect: Allow + Principal: + Service: scheduler.amazonaws.com + Action: sqs:SendMessage + Resource: !GetAtt SchedulerDLQ.Arn + Condition: + ArnEquals: + aws:SourceArn: !Sub 'arn:aws:scheduler:${AWS::Region}:${AWS::AccountId}:schedule/default/${AWS::StackName}-schedule' + + # IAM Role for EventBridge Scheduler + SchedulerRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: scheduler.amazonaws.com + Action: sts:AssumeRole + Policies: + - PolicyName: InvokeLambda + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - lambda:InvokeFunction + Resource: !GetAtt ScheduledFunction.Arn + - PolicyName: SendToDLQ + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - sqs:SendMessage + Resource: !GetAtt SchedulerDLQ.Arn + + # EventBridge Scheduler + EventSchedule: + Type: AWS::Scheduler::Schedule + Properties: + Name: !Sub '${AWS::StackName}-schedule' + Description: Invokes Lambda function every 5 minutes with retry and DLQ + ScheduleExpression: rate(5 minutes) + FlexibleTimeWindow: + Mode: 'OFF' + State: ENABLED + Target: + Arn: !GetAtt ScheduledFunction.Arn + RoleArn: !GetAtt SchedulerRole.Arn + RetryPolicy: + MaximumRetryAttempts: 3 + MaximumEventAgeInSeconds: 3600 # 1 hour + DeadLetterConfig: + Arn: !GetAtt SchedulerDLQ.Arn + +Outputs: + ScheduledFunctionArn: + Description: ARN of the scheduled Lambda function + Value: !GetAtt ScheduledFunction.Arn + + ScheduledFunctionName: + Description: Name of the scheduled Lambda function + Value: !Ref ScheduledFunction + + LambdaExecutionDLQUrl: + Description: URL of the Lambda Execution Dead Letter Queue + Value: !Ref LambdaExecutionDLQ + + LambdaExecutionDLQArn: + Description: ARN of the Lambda Execution Dead Letter Queue + Value: !GetAtt LambdaExecutionDLQ.Arn + + SchedulerDLQUrl: + Description: URL of the EventBridge Scheduler Dead Letter Queue + Value: !Ref SchedulerDLQ + + SchedulerDLQArn: + Description: ARN of the EventBridge Scheduler Dead Letter Queue + Value: !GetAtt SchedulerDLQ.Arn + + ScheduleName: + Description: Name of the EventBridge Schedule + Value: !Ref EventSchedule + + ScheduleArn: + Description: ARN of the EventBridge Schedule + Value: !GetAtt EventSchedule.Arn + + TestFailureCommand: + Description: Command to simulate a Lambda execution failure + Value: !Sub | + aws lambda update-function-configuration \ + --function-name ${ScheduledFunction} \ + --environment Variables={LOG_LEVEL=INFO,SIMULATE_FAILURE=true}