Cloud & Backend Engineer Guide: Reliable SNS-to-SQS Event Fan-Out, Filter Policies & DLQ Redrive
When an e-commerce checkout or fintech ledger emits an OrderPaid event, multiple downstream domains—invoicing, inventory reservation, loyalty points, and fraud analytics—need to react independently. Having the checkout API call four downstream services synchronously creates a fragile availability chain, while having four consumers poll a single shared SQS queue causes competing-consumer message theft. As a cloud engineer and backend engineer, I architect decoupled event fan-out pipelines using Amazon SNS topic filter policies, dedicated per-consumer SQS queues, and automated Dead-Letter Queue (DLQ) redrives.
1. SNS Subscription Filter Policies & Isolated SQS Queues in Terraform
Publishing domain events to an Amazon SNS topic with attribute-based filter_policy rules routes copies of each event only to the SQS queues that care about that event type—isolating backpressure so a slow PDF invoice generator never delays real-time inventory reservation:
# terraform/sns_sqs_fanout.tf
resource "aws_sns_topic" "domain_events" {
name = "prod-domain-events-topic"
}
resource "aws_sqs_queue" "invoicing_dlq" {
name = "prod-invoicing-events-dlq"
message_retention_seconds = 1209600 # 14 days
}
resource "aws_sqs_queue" "invoicing_queue" {
name = "prod-invoicing-events-queue"
visibility_timeout_seconds = 180 # 6x Lambda 30s timeout
receive_wait_time_seconds = 20 # Long polling
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.invoicing_dlq.arn
maxReceiveCount = 4
})
}
resource "aws_sns_topic_subscription" "invoicing_sub" {
topic_arn = aws_sns_topic.domain_events.arn
protocol = "sqs"
endpoint = aws_sqs_queue.invoicing_queue.arn
raw_message_delivery = true
filter_policy = jsonencode({
event_type = ["order.paid", "order.refunded"]
})
}
2. Visibility Timeout Sizing & Controlled DLQ Replay
Always set the SQS visibility_timeout_seconds to at least 6x the consumer Lambda function's timeout plus maximum batching window. When a downstream dependency recovers from an outage, replay messages from the DLQ using `StartMessageMoveTask` with a throttled `MaxNumberOfMessagesPerSecond` rate so redriven messages do not overwhelm the primary database.