
Building a Resilient Event-Driven Processing Pipeline with Amazon EventBridge, SQS, and AWS Lambda
Learn how to design and build an enterprise event-driven architecture that decouples services using custom Amazon EventBridge buses, dead-letter queues (DLQ), Amazon SQS buffering, and Python-powered AWS Lambda workers.
Overview
Tight coupling between distributed microservices often introduces cascading failures, brittle deployments, and latency bottlenecks. An event-driven architecture (EDA) solves these challenges by treating state changes as asynchronous events.
In this tutorial, we will build a resilient event pipeline using:
- Amazon EventBridge: Central event router receiving custom domain events.
- Content Filtering Rules: Evaluating event payloads and dispatching only matching events.
- Amazon SQS (with Dead-Letter Queue): Buffering incoming tasks to protect downstream workers from traffic spikes.
- AWS Lambda (Python 3.12): Processing tasks with automatic batching and partial failure reporting.
Prerequisites
- AWS CLI v2 configured with administrator privileges.
- Python 3.12 installed locally.
- Basic understanding of IAM policies and event schemas.
Step 1: Create the Dead-Letter Queue (DLQ) and Primary Buffer
Always create your Dead-Letter Queue before provisioning primary processing queues to capture poisoned messages:
# 1. Create Dead-Letter Queue
aws sqs create-queue \
--queue-name order-processing-dlq \
--attributes MessageRetentionPeriod=1209600
# Retrieve DLQ ARN
DLQ_ARN=$(aws sqs get-queue-attributes \
--queue-name order-processing-dlq \
--attribute-names QueueArn \
--query 'Attributes.QueueArn' \
--output text)
# 2. Create Primary SQS Queue with Redrive Policy
RED_DRIVE_POLICY="{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":3}"
aws sqs create-queue \
--queue-name order-processing-queue \
--attributes "RedrivePolicy='$RED_DRIVE_POLICY',VisibilityTimeout=60"
Step 2: Provision Custom EventBridge Bus & Filtering Rule
Create a dedicated event bus to separate domain events from default AWS account traffic:
# Create custom event bus
aws events create-event-bus --name ecommerce-events
# Define a routing pattern (filter for paid orders only)
cat << 'EOF' > event-pattern.json
{
"source": ["ecommerce.orders"],
"detail-type": ["OrderCreated"],
"detail": {
"status": ["PAID"]
}
}
EOF
# Create rule attached to the bus
aws events put-rule \
--name ProcessPaidOrdersRule \
--event-bus-name ecommerce-events \
--event-pattern file://event-pattern.json
Grant EventBridge permissions to forward messages directly to your SQS queue, and attach the queue as a target:
QUEUE_ARN=$(aws sqs get-queue-attributes \
--queue-name order-processing-queue \
--attribute-names QueueArn \
--query 'Attributes.QueueArn' \
--output text)
aws events put-targets \
--rule ProcessPaidOrdersRule \
--event-bus-name ecommerce-events \
--targets "Id"="OrderQueueTarget","Arn"="$QUEUE_ARN"
Step 3: Serverless Worker with Partial Batch Response
By default, an uncaught exception in an SQS-triggered Lambda function forces the entire batch back into the queue. We use
ReportBatchItemFailures so that only failed message IDs are retried:
# lambda_function.py
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
batch_item_failures = []
for record in event.get('Records', []):
message_id = record['messageId']
try:
body = json.loads(record['body'])
# Extract EventBridge detail wrapper
order_data = body.get('detail', {})
logger.info(f"Processing Order: {order_data.get('order_id')}")
# Validation logic
if not order_data.get('items'):
raise ValueError("Missing items in order payload")
# Simulate fulfillment business logic
process_fulfillment(order_data)
except Exception as exc:
logger.error(f"Failed to process message {message_id}: {str(exc)}")
batch_item_failures.append({"itemIdentifier": message_id})
return {"batchItemFailures": batch_item_failures}
def process_fulfillment(order):
# Core processing logic goes here
pass
Configure your Lambda event source mapping with
ReportBatchItemFailures :aws lambda create-event-source-mapping \
--function-name OrderProcessorFunction \
--batch-size 10 \
--event-source-arn "$QUEUE_ARN" \
--function-response-types ReportBatchItemFailures
Step 4: Verification & Testing
Send a test event payload using the AWS CLI:
cat << 'EOF' > test-event.json
[
{
"EventBusName": "ecommerce-events",
"Source": "ecommerce.orders",
"DetailType": "OrderCreated",
"Detail": "{\"order_id\":\"ORD-9281\",\"status\":\"PAID\",\"items\":[{\"sku\":\"WIDGET-01\",\"qty\":2}]}"
}
]
EOF
aws events put-events --entries file://test-event.json
Check Amazon CloudWatch Logs for your Lambda function: you will see the payload processed in real time without any message dropped.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article