How do you design for idempotency in serverless functions?

Answer

Idempotency means processing the same event multiple times produces the same result without side effects — critical for serverless where retries are automatic and unavoidable. Implementation patterns: (1) Idempotency keys — the caller provides a unique key with each request (UUID). The function stores the key + result in DynamoDB with a TTL. On subsequent calls with the same key, return the cached result without re-executing: const existing = await dynamodb.get({ Key: { idempotencyKey } }); if (existing) return existing.response; (2) AWS Lambda Powertools Idempotency — the Python/Java/TypeScript utility automatically handles this with DynamoDB persistence, configurable TTL, and in-progress handling (prevents concurrent execution of duplicate events); (3) Natural idempotency — design operations to be naturally idempotent: SET balance = 100 (idempotent) vs SET balance = balance + 10 (not idempotent); use DynamoDB conditional expressions (attribute_not_exists(orderId)) for "create if not exists" patterns; (4) Database-level deduplication — unique constraint on order_id in the database prevents duplicate inserts; catch the constraint violation and return the existing record; (5) SQS message deduplication — FIFO queues support MessageDeduplicationId for exactly-once delivery within a 5-minute window.