AWS Builder Center

Provisioning Fault-Tolerant Event-Driven Serverless Pipelines on AWS with Terraformm

Learn how to codify an event-driven AWS architecture using Terraform, complete with Amazon EventBridge routing, SQS Dead-Letter Queues, DynamoDB idempotency state stores, and least-privilege IAM policies.

Designing a resilient, event-driven architecture on a whiteboard is one thing; deploying it consistently across staging and production environments without configuration drift is another. When building asynchronous pipelines with Amazon EventBridge, AWS Lambda, Amazon SQS, and Amazon DynamoDB, clicking through the AWS Management Console quickly leads to overly permissive IAM roles, mismatched queue timeouts, and unmonitored Dead-Letter Queues (DLQs).
In this guide, we will codify a complete, fault-tolerant serverless pipeline using Terraform. We will provision an EventBridge custom bus, wire up an SQS buffer queue with an automated redrive policy to a Dead-Letter Queue, deploy an idempotency state table in DynamoDB, and lock down our Lambda execution role using strict least-privilege IAM policies.

Architecture Overview

Our Infrastructure as Code (IaC) stack provisions five core layers:
  1. Ingestion Layer: A custom Amazon EventBridge bus and event rule that filters incoming domain events ( OrderCreated ).
  1. Buffering & Fault Tolerance Layer: A standard Amazon SQS queue acting as the EventBridge target, paired with a dedicated SQS Dead-Letter Queue via an explicit redrive policy.
  1. State & Idempotency Layer: An on-demand Amazon DynamoDB table with Time-to-Live (TTL) enabled to track processed event IDs and prevent duplicate execution.
  1. Compute Layer: An AWS Lambda worker configured with  ReportBatchItemFailures  so partial batch failures return only the failed message to the queue.
  1. Security Layer: Scoped resource-based policies allowing EventBridge to push to SQS, alongside a granular IAM execution role for the Lambda consumer.

1. Defining the Idempotency Store and Queues

When configuring SQS queues with Lambda, two parameters determine whether your pipeline handles traffic spikes gracefully or drops messages prematurely:
  •  visibility_timeout_seconds : Must be at least 6 times the timeout of your consuming Lambda function to prevent duplicate deliveries while a batch is still processing.
  •  maxReceiveCount : Defines how many times a message can fail processing before SQS automatically moves it to the Dead-Letter Queue.
Create a  main.tf  file and define the DynamoDB idempotency table alongside the primary and dead-letter SQS queues:
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}

provider "aws" {
region = "us-west-2"
}

# 1. DynamoDB Table for Idempotency Tracking
resource "aws_dynamodb_table" "idempotency_store" {
name = "order-pipeline-idempotency"
billing_mode = "PAY_PER_REQUEST"
hash_key = "id"

attribute {
name = "id"
type = "S"
}

ttl {
attribute_name = "expiration"
enabled = true
}
}

# 2. Dead-Letter Queue (DLQ) for Poison-Pill Messages
resource "aws_sqs_queue" "order_dlq" {
name = "order-processing-dlq"
message_retention_seconds = 1209600 # 14 days maximum retention for debugging
sqs_managed_sse_enabled = true
}

# 3. Primary Processing Queue
resource "aws_sqs_queue" "order_queue" {
name = "order-processing-queue"
visibility_timeout_seconds = 180 # 6x our 30-second Lambda timeout
message_retention_seconds = 345600 # 4 days
receive_wait_time_seconds = 20 # Enable long polling
sqs_managed_sse_enabled = true
}

# 4. Explicit Redrive Policy Attachment
resource "aws_sqs_queue_redrive_policy" "order_redrive" {
queue_url = aws_sqs_queue.order_queue.id
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.order_dlq.arn
maxReceiveCount = 3
})
}

Separating  aws_sqs_queue_redrive_policy  into its own resource block avoids circular dependency issues and ensures Terraform reliably detects drift if someone alters the DLQ settings in the console.

2. Configuring EventBridge Routing and Queue Policies

By default, an SQS queue rejects messages from other AWS services unless explicitly permitted by an  aws_sqs_queue_policy . To prevent cross-service confused deputy vulnerabilities, we restrict the policy using the  aws:SourceArn  condition key so only our specific EventBridge rule can enqueue messages.
Add the EventBridge bus, rule, target, and SQS resource policy to  events.tf :
resource "aws_cloudwatch_event_bus" "orders_bus" {
name = "orders-domain-bus"
}

resource "aws_cloudwatch_event_rule" "order_created_rule" {
name = "capture-order-created"
event_bus_name = aws_cloudwatch_event_bus.orders_bus.name
description = "Routes OrderCreated events to the SQS processing queue"

event_pattern = jsonencode({
source = ["com.ecommerce.orders"]
detail-type = ["OrderCreated"]
})
}

resource "aws_cloudwatch_event_target" "sqs_target" {
rule = aws_cloudwatch_event_rule.order_created_rule.name
event_bus_name = aws_cloudwatch_event_bus.orders_bus.name
target_id = "SendToOrderQueue"
arn = aws_sqs_queue.order_queue.arn

# Optional: Configure a target-level DLQ for EventBridge delivery failures
dead_letter_config {
arn = aws_sqs_queue.order_dlq.arn
}
}

data "aws_iam_policy_document" "eventbridge_to_sqs" {
statement {
sid = "AllowEventBridgeToSendMessage"
effect = "Allow"

principals {
type = "Service"
identifiers = ["events.amazonaws.com"]
}

actions = ["sqs:SendMessage"]
resources = [aws_sqs_queue.order_queue.arn]

condition {
test = "ArnEquals"
variable = "aws:SourceArn"
values = [aws_cloudwatch_event_rule.order_created_rule.arn]
}
}
}

resource "aws_sqs_queue_policy" "order_queue_policy" {
queue_url = aws_sqs_queue.order_queue.id
policy = data.aws_iam_policy_document.eventbridge_to_sqs.json
}

Notice the  dead_letter_config  inside  aws_cloudwatch_event_target . This protects the pipeline at two distinct stages: if EventBridge cannot reach SQS due to a permission error or service throttling, EventBridge routes the failed invocation to the DLQ; if SQS delivers the message to Lambda and the code throws an unhandled exception three times, SQS moves the message to the DLQ.

3. Enforcing Least-Privilege IAM for the Lambda Worker

A common anti-pattern in serverless deployments is attaching  AmazonSQSFullAccess  and  AmazonDynamoDBFullAccess  to a Lambda execution role. Instead, our worker only needs three specific capabilities:
  1. Poll and delete messages from  order_queue .
  1. Read, write, and update items in the  idempotency_store  DynamoDB table.
  1. Write structured execution logs to its dedicated CloudWatch Log Group.
Create  iam.tf  to define the execution role and scoped policy document:
data "aws_iam_policy_document" "lambda_assume_role" {
statement {
effect = "Allow"
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
actions = ["sts:AssumeRole"]
}
}

resource "aws_iam_role" "order_worker_role" {
name = "order-worker-lambda-role"
assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json
}

data "aws_iam_policy_document" "order_worker_permissions" {
# 1. SQS Consumer Permissions
statement {
sid = "ConsumeOrderQueue"
effect = "Allow"
actions = [
"sqs:ReceiveMessage",
"sqs:DeleteMessage",
"sqs:GetQueueAttributes"
]
resources = [aws_sqs_queue.order_queue.arn]
}

# 2. DynamoDB Idempotency Permissions
statement {
sid = "ManageIdempotencyState"
effect = "Allow"
actions = [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem"
]
resources = [aws_dynamodb_table.idempotency_store.arn]
}

# 3. CloudWatch Logging Permissions
statement {
sid = "WriteCloudWatchLogs"
effect = "Allow"
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents"
]
resources = ["${aws_cloudwatch_log_group.worker_logs.arn}:*"]
}
}

resource "aws_iam_role_policy" "order_worker_policy" {
name = "order-worker-least-privilege"
role = aws_iam_role.order_worker_role.id
policy = data.aws_iam_policy_document.order_worker_permissions.json
}


4. Deploying the Lambda Consumer and Event Source Mapping

Finally, we wire the Lambda function to the SQS queue using  aws_lambda_event_source_mapping . Critically, we enable  ReportBatchItemFailures  in  function_response_types . Without this flag, a single bad message in a batch of 10 forces the entire batch to retry, potentially causing duplicate downstream side effects or exhausting retry counts for healthy messages.
Add the compute configuration in  lambda.tf :
resource "aws_cloudwatch_log_group" "worker_logs" {
name = "/aws/lambda/order-processing-worker"
retention_in_days = 14
}

resource "aws_lambda_function" "order_worker" {
function_name = "order-processing-worker"
role = aws_iam_role.order_worker_role.arn
handler = "app.lambda_handler"
runtime = "python3.12"
timeout = 30
memory_size = 256

filename = "dist/worker.zip"
source_code_hash = filebase64sha256("dist/worker.zip")

environment {
variables = {
IDEMPOTENCY_TABLE_NAME = aws_dynamodb_table.idempotency_store.name
POWERTOOLS_SERVICE_NAME = "order-service"
}
}

depends_on = [aws_cloudwatch_log_group.worker_logs]
}

resource "aws_lambda_event_source_mapping" "sqs_trigger" {
event_source_arn = aws_sqs_queue.order_queue.arn
function_name = aws_lambda_function.order_worker.arn
batch_size = 10
maximum_batching_window_in_seconds = 5
function_response_types = ["ReportBatchItemFailures"]

scaling_config {
maximum_concurrency = 50 # Protects downstream databases from connection exhaustion
}
}


5. Adding Proactive DLQ CloudWatch Alarms

A Dead-Letter Queue is only useful if your engineering team knows when messages land in it. We can add a CloudWatch Metric Alarm directly in Terraform that triggers whenever  ApproximateNumberOfMessagesVisible  in the DLQ exceeds zero:
resource "aws_cloudwatch_metric_alarm" "dlq_depth_alarm" {
alarm_name = "order-dlq-messages-detected"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = 1
metric_name = "ApproximateNumberOfMessagesVisible"
namespace = "AWS/SQS"
period = 60
statistic = "Sum"
threshold = 0
alarm_description = "Triggers immediately when a poison-pill message enters the Order DLQ"

dimensions = {
QueueName = aws_sqs_queue.order_dlq.name
}
}

Key Takeaways for Production Serverless IaC

  • Decouple Redrive Policies: Use  aws_sqs_queue_redrive_policy  as a standalone resource so Terraform tracks state drift accurately.
  • Always Enable Partial Batch Responses: Pair  function_response_types = ["ReportBatchItemFailures"]  in Terraform with batch item failure reporting in your handler code so valid messages are deleted while failed ones retry independently.
  • Cap Event Source Concurrency: Use  scaling_config.maximum_concurrency  on SQS event source mappings to prevent runaway Lambda scaling during traffic bursts.
  • Lock Down Queue Policies: Always pair  events.amazonaws.com  service principals with an  aws:SourceArn  condition so only authorized EventBridge rules can publish to your queues.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article