Cloud & Backend Engineer Guide: Single-Table DynamoDB, SQS Partial Batch Failures & AWS Lambda

Serverless architectures built on AWS Lambda, Amazon SQS, and Amazon DynamoDB scale effortlessly when designed around single-table access patterns and partial batch failure semantics—but turn into expensive retry storms when treated like a relational database. As a cloud engineer and backend engineer, I architect DynamoDB single-table schemas, conditional write expressions, and SQS event-source handlers that guarantee zero duplicate processing under spike load.

1. SQS Partial Batch Response (`ReportBatchItemFailures`) in AWS Lambda

When an AWS Lambda function processes a batch of 25 SQS messages and message #24 fails due to a downstream timeout, raising an unhandled exception returns all 25 messages to the queue—re-executing 23 already-succeeded messages. Enabling FunctionResponseTypes: ["ReportBatchItemFailures"] and combining it with a DynamoDB conditional idempotency lock ensures only failed message IDs are retried:

# handlers/sqs_order_worker.py
import json
import os
import time
import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["DYNAMODB_TABLE_NAME"])

def acquire_idempotency_lock(message_id: str, ttl_seconds: int = 86400) -> bool:
    now = int(time.time())
    try:
        table.put_item(
            Item={
                "PK": f"IDEMPOTENCY#{message_id}",
                "SK": "LOCK",
                "status": "PROCESSING",
                "expires_at": now + ttl_seconds,
            },
            ConditionExpression="attribute_not_exists(PK) OR (#st = :failed)",
            ExpressionAttributeNames={"#st": "status"},
            ExpressionAttributeValues={":failed": "FAILED"},
        )
        return True
    except ClientError as exc:
        if exc.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return False
        raise

def lambda_handler(event: dict, context) -> dict:
    batch_item_failures = []
    for record in event.get("Records", []):
        msg_id = record["messageId"]
        if not acquire_idempotency_lock(msg_id):
            continue  # Already processed or in-flight
        try:
            payload = json.loads(record["body"])
            process_order_mutation(payload)
            table.update_item(
                Key={"PK": f"IDEMPOTENCY#{msg_id}", "SK": "LOCK"},
                UpdateExpression="SET #st = :done",
                ExpressionAttributeNames={"#st": "status"},
                ExpressionAttributeValues={":done": "COMPLETED"},
            )
        except Exception:
            table.update_item(
                Key={"PK": f"IDEMPOTENCY#{msg_id}", "SK": "LOCK"},
                UpdateExpression="SET #st = :failed",
                ExpressionAttributeNames={"#st": "status"},
                ExpressionAttributeValues={":failed": "FAILED"},
            )
            batch_item_failures.append({"itemIdentifier": msg_id})

    return {"batchItemFailures": batch_item_failures}

2. Single-Table Composite Sort Keys for Zero-Scan Queries

By encoding entity hierarchies into composite keys such as PK = TENANT#941 and SK = ORDER#2026-11-02#ORD_8821, a single Query operation retrieves a tenant's profile metadata and their latest 50 orders in 4 milliseconds without ever calling Scan.

3. Related AWS Serverless & Backend Engineering Resources


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs