Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
46 changes: 46 additions & 0 deletions eventbridge-schedule-to-lambda-dlq-sam-python/.gitignore
Original file line number Diff line number Diff line change
@@ -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
166 changes: 166 additions & 0 deletions eventbridge-schedule-to-lambda-dlq-sam-python/README.md
Original file line number Diff line number Diff line change
@@ -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 <your-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 <your-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 <your-stack-name> \
--query 'Stacks[0].Outputs[?OutputKey==`ScheduleName`].OutputValue' \
--output text)

# Get scheduler role name
SCHEDULER_ROLE=$(aws cloudformation describe-stack-resources \
--stack-name <your-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 <your-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 <your-stack-name>
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'<your-stack-name>')].StackStatus"
```
----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
68 changes: 68 additions & 0 deletions eventbridge-schedule-to-lambda-dlq-sam-python/example-pattern.json
Original file line number Diff line number Diff line change
@@ -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: <code>sam delete --stack-name STACK_NAME</code>"
]
},
"authors": [
{
"name": "Sasidharan Ramasamy",
"bio": "Technical Account Manager @ AWS with over 10 years of industry experience",
"linkedin": "https://www.linkedin.com/in/sasidharan-ramasamy/"
}
]
}
106 changes: 106 additions & 0 deletions eventbridge-schedule-to-lambda-dlq-sam-python/src/scheduled/app.py
Original file line number Diff line number Diff line change
@@ -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))
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# No external dependencies required
# Using only Python standard library
Loading