
Implementing Idempotency in Serverless APIs
Learn how to prevent duplicate transactions and ensure safe retries in AWS Lambda and API Gateway using DynamoDB conditional writes and TTLs.
In distributed systems, network timeouts and client retries are inevitable. When a client sends a
POST request to create an order or process a payment and the connection drops before a response arrives, the client safely assumes the request failed and retries. Without safeguards on the backend, that retry executes the business logic twice—charging a customer twice or creating duplicate records.Idempotency solves this by guaranteeing that making the same request multiple times produces the exact same outcome as making it once. Here is how to implement a lightweight, serverless idempotency layer using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
How the Idempotency Pattern Works
- Client Generates a Key: Before making a mutating API call (
POST,PATCH,DELETE), the client generates a unique UUIDv4 and sends it in a custom header, such asIdempotency-Key.
- Atomic Lock Acquisition: The Lambda function extracts the key and attempts to write a record to DynamoDB with status
IN_PROGRESSusing a conditional expression (attribute_not_exists).
- Branching Execution:
- New Key: The conditional write succeeds. Lambda executes the core business logic, updates the DynamoDB item with the final response and status
COMPLETED, and returns the result.
- Duplicate Key (
COMPLETED): DynamoDB rejects the conditional write. Lambda fetches the stored response from the previous run and returns it immediately without re-running the logic.
- Duplicate Key (
IN_PROGRESS): Another concurrent request is currently processing. Lambda returns a409 Conflictor429 Too Many Requestsstatus telling the client to retry shortly.
DynamoDB Table Configuration
Create a DynamoDB table named
IdempotencyKeys with the following configuration:- Partition Key:
idempotency_key(String)
- Time to Live (TTL): Enable TTL on the
expires_atattribute (Number). Setting an expiration window (e.g., 24 hours) automatically purges old keys at zero additional cost.
Lambda Implementation (Python / Boto3)
Below is a clean implementation using
boto3 and DynamoDB conditional expressions to prevent race conditions:import jsonimport osimport timeimport boto3from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table(os.environ["IDEMPOTENCY_TABLE"])TTL_SECONDS = 86400 # 24 hours
def lambda_handler(event, context): headers = {k.lower(): v for k, v in (event.get("headers") or {}).items()} idem_key = headers.get("idempotency-key")
if not idem_key: return response(400, {"error": "Missing Idempotency-Key header"})
now = int(time.time())
# 1. Attempt to acquire an atomic lock for this key try: table.put_item( Item={ "idempotency_key": idem_key, "status": "IN_PROGRESS", "expires_at": now + TTL_SECONDS, }, ConditionExpression="attribute_not_exists(idempotency_key)", ) except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": return handle_existing_key(idem_key) raise
# 2. Execute core business logic (only runs once per unique key) try: body = json.loads(event.get("body") or "{}") result_payload = process_transaction(body)
# 3. Save final response and mark COMPLETED table.update_item( Key={"idempotency_key": idem_key}, UpdateExpression="SET #s = :status, response_body = :resp", ExpressionAttributeNames={"#s": "status"}, ExpressionAttributeValues={ ":status": "COMPLETED", ":resp": json.dumps(result_payload), }, ) return response(200, result_payload)
except Exception as err: # Clean up failed lock so the client can safely retry table.delete_item(Key={"idempotency_key": idem_key}) return response(500, {"error": str(err)})
def handle_existing_key(idem_key): item = table.get_item(Key={"idempotency_key": idem_key}).get("Item") if not item: return response(409, {"error": "Key state unavailable, retry request"})
if item["status"] == "COMPLETED": return response(200, json.loads(item["response_body"]))
return response(409, {"error": "Request is currently being processed"})
def process_transaction(payload): # Replace with your payment, order creation, or database logic return {"transaction_id": "txn_987654321", "status": "processed", "input": payload}
def response(status_code, body): return { "statusCode": status_code, "headers": {"Content-Type": "application/json"}, "body": json.dumps(body), }Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article