Senior Cloud Engineer Guide: Event-Driven AWS Serverless with Lambda, SQS & DynamoDB
Event-driven serverless architectures on AWS—combining AWS Lambda, Amazon SQS, Amazon EventBridge, and Amazon DynamoDB—can process tens of thousands of concurrent events per second while scaling infrastructure costs down to pennies during quiet periods. However, default AWS Lambda + SQS configurations contain subtle traps: a single poison-pill message can replay an entire batch of 10 messages repeatedly, and poorly chosen DynamoDB partition keys can throttle workloads under burst traffic. As a Senior Cloud Engineer and Backend Engineer, I design production-grade AWS serverless pipelines engineered for strict idempotency and observability.
1. Preventing Duplicate Batch Replays with ReportBatchItemFailures
By default, when an AWS Lambda function processes a batch of 10 SQS messages and throws an exception on message #7, all 10 messages become visible again in the queue—causing messages #1 through #6 to be processed a second time. By enabling FunctionResponseTypes: ["ReportBatchItemFailures"] on the event source mapping and returning only the failed message IDs, healthy messages are deleted immediately while only failed items retry toward the Dead-Letter Queue (DLQ):
import json
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
dynamodb = boto3.resource("dynamodb")
ledger_table = dynamodb.Table("OrderEventsLedger")
def lambda_handler(event: dict, context) -> dict:
batch_item_failures = []
for record in event.get("Records", []):
msg_id = record["messageId"]
try:
body = json.loads(record["body"])
process_order_event_idempotently(
event_id=body["event_id"],
order_id=body["order_id"],
amount_cents=int(body["amount_cents"]),
)
except Exception as exc:
logger.exception("Failed processing SQS messageId=%s: %s", msg_id, exc)
batch_item_failures.append({"itemIdentifier": msg_id})
return {"batchItemFailures": batch_item_failures}
def process_order_event_idempotently(event_id: str, order_id: str, amount_cents: int) -> None:
try:
ledger_table.put_item(
Item={
"PK": f"ORDER#{order_id}",
"SK": f"EVENT#{event_id}",
"AmountCents": amount_cents,
},
ConditionExpression="attribute_not_exists(PK) AND attribute_not_exists(SK)",
)
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
logger.info("Duplicate event_id=%s ignored safely", event_id)
return
raise
2. DynamoDB Single-Table Design & Write Sharding
Unlike relational databases where joins are cheap, DynamoDB excels when related entities (e.g., an Organization, its Users, and its APIKeys) share a single table keyed by composite PK (Partition Key) and SK (Sort Key) patterns, retrieving an entire hierarchical entity graph in a single sub-5ms Query call. For high-velocity status partitions, I append calculated write-shard suffixes (PK = STATUS#PENDING#SHARD_0..7) to prevent hot-partition throttling.
3. AWS Cost Hygiene & Multi-AZ Subnet Optimization
Beyond serverless functions, I optimize AWS networking and load balancing costs—such as pruning unused Availability Zone subnets on Application Load Balancers to minimize public IPv4 hourly charges while maintaining multi-AZ high availability, and replacing redundant NAT Gateways with VPC Gateway Endpoints for S3 and DynamoDB.
4. Hire a Senior Cloud & Backend Engineer for AWS Architectures
Need to architect, debug, or cost-optimize an AWS serverless or container platform? Explore my Cloud Engineer AWS & GCP Pillar Guide, read my Zero-Downtime Cloud Migration Playbook, or book a 1-Day Cloud Architecture Sprint.