
Preventing Duplicate Requests in AWS Serverless Applications with Idempotency Keys
Learn how to build reliable serverless APIs using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB. This hands-on tutorial demonstrates how idempotency keys, request validation, and persistent execution records help prevent duplicate operations when clients retry timed-out requests.
Preventing Duplicate Requests in AWS Serverless Applications with Idempotency Keys
1. Introduction
Serverless computing makes application development easier by eliminating the need to manage traditional server infrastructure. AWS Lambda and Amazon API Gateway are commonly used together to build scalable APIs and backend applications.
However, one important challenge in distributed applications is handling request retries safely.
Consider a payment application. A customer clicks the Pay button, and the application sends a request to an API. The Lambda function processes the payment successfully, but the response takes too long to reach the client. The client assumes the request failed and sends it again.
Without proper protection, the application might process the same payment twice.
This problem is known as duplicate request processing.
In this tutorial, we will explore how idempotency keys, AWS Lambda, Amazon API Gateway, and Amazon DynamoDB can work together to prevent duplicate operations and improve serverless application reliability.
2. Understanding the Retry Problem
A retry occurs when a client sends a request again because it did not receive the expected response.
Retries can happen because of:
- Network interruptions.
- Client-side timeouts.
- Temporary service failures.
- Slow application responses.
- Uncertain request completion.
An important point is that a timeout does not always mean the original operation failed.
The server may have completed the operation even though the client never received its response.
Example Scenario
Imagine a user placing an order worth ₹1,000.
- The client sends an order request.
- API Gateway forwards the request to Lambda.
- Lambda successfully creates the order.
- The response is delayed or lost.
- The client times out.
- The client retries the same request.
- Lambda receives another invocation.
Without idempotency protection, the application might create two orders.
This is why retry handling must be considered during API design.
3. What Is Idempotency?
Idempotency is a property that ensures performing the same operation multiple times with the same request identity does not create additional side effects.
For example, submitting the same order request five times should ideally produce one order rather than five separate orders.
An idempotent API can return the previously stored result when it receives a repeated request.
What Is an Idempotency Key?
An idempotency key is a unique identifier generated by the client for a particular operation.
The client sends this identifier along with its API request.
Example:
POST /ordersContent-Type: application/jsonIdempotency-Key: order-request-12345The server uses this key to identify repeated requests.
If the same key is received again with the same request payload, the application can return the previously stored result instead of performing the operation again.
Important Rules
- Generate a new key for every new logical operation.
- Reuse the same key when retrying the same operation.
- Do not reuse a key for a different request.
- Validate the request payload associated with the key.
- Store the result so that repeated requests can receive the original response.
4. AWS Services Used in This Implementation
We will use three AWS services.
4.1 Amazon API Gateway
Amazon API Gateway receives HTTP requests and forwards them to the appropriate backend integration.
In this example, it receives the client's order request and invokes an AWS Lambda function.
4.2 AWS Lambda
AWS Lambda executes the application logic.
It checks the idempotency key, processes the order, and returns the result.
4.3 Amazon DynamoDB
Amazon DynamoDB provides persistent storage for idempotency records.
These records can contain:
- Idempotency key.
- Request payload hash.
- Execution status.
- Previous response.
- Expiration timestamp.
DynamoDB helps Lambda identify previously processed requests and coordinate concurrent invocations.
5. Understanding the Architecture
The request flow is:
- The client generates an idempotency key.
- The client sends an HTTP request to API Gateway.
- API Gateway invokes Lambda.
- Lambda checks the idempotency record in DynamoDB.
- If the request was already completed, the stored result is returned.
- If the request is new, Lambda processes it.
- The result is stored for future retries.
- The response is returned to the client.
Architecture Diagram
CLIENT APPLICATION | | POST /orders + KEY | v AMAZON API GATEWAY | v AWS LAMBDA | v AMAZON DYNAMODB | Check request key | ----------------- | | Existing New | | Return stored Process order response | | v | Save result | | ----------------- | v HTTP RESPONSE | v CLIENT6. Hands-On Tutorial: Implementing Idempotency
Let's build a simplified order-processing API using AWS Lambda, API Gateway, and DynamoDB.
Prerequisites
Before starting, you need:
- An AWS account.
- Basic knowledge of Python.
- An Amazon API Gateway HTTP API.
- An AWS Lambda function.
- An Amazon DynamoDB table.
- AWS Lambda Powertools for Python.
Review the current AWS pricing before creating resources.
Step 1: Create a DynamoDB Table
- Open the AWS Management Console.
- Search for Amazon DynamoDB.
- Select Create table.
- Enter the table name as
IdempotencyRecords.
- Configure the partition key as
idwith type String.
- Create the table.
The table will store idempotency records.
When using AWS Lambda Powertools' DynamoDB persistence layer, configure the required expiration attribute according to its documentation.
Step 2: Configure the Lambda Function
- Open AWS Lambda.
- Create a function named
OrderProcessingFunction.
- Select Python as the runtime.
- Configure an execution role.
- Grant the role the required DynamoDB permissions.
- Configure the environment variable:
IDEMPOTENCY_TABLE=IdempotencyRecordsInstall AWS Lambda Powertools for Python as a deployment dependency or include it in an appropriate Lambda layer.
Step 3: Implement the Idempotent Function
We can use AWS Lambda Powertools instead of implementing the entire idempotency mechanism manually.
It provides an idempotency utility with a DynamoDB persistence layer.
Example:
import os
from aws_lambda_powertools.utilities.idempotency import ( DynamoDBPersistenceLayer, IdempotencyConfig, idempotent_function,)
persistence_layer = DynamoDBPersistenceLayer( table_name=os.environ["IDEMPOTENCY_TABLE"])
config = IdempotencyConfig( event_key_jmespath="idempotency_key", payload_validation_jmespath="body", expires_after_seconds=86400, raise_on_no_idempotency_key=True,)
@idempotent_function( data_keyword_argument="request", config=config, persistence_store=persistence_layer,)def create_order(request: dict) -> dict:
body = request["body"]
# Replace this with your actual # transactional order-processing logic.
result = { "order_id": body["order_id"], "status": "ORDER_ACCEPTED" }
return resultIn this example:
-
DynamoDBPersistenceLayerstores idempotency records.
-
event_key_jmespathidentifies the unique request key.
-
payload_validation_jmespathchecks the associated request payload.
-
expires_after_secondsdefines the idempotency validity window.
-
idempotent_functionmanages repeated execution and stored results.
The same key and payload can return the previous successful result instead of processing the operation again.
Step 4: Handle the API Gateway Request
The Lambda handler can extract the idempotency key from the incoming HTTP request.
Example:
import json
def lambda_handler(event, context):
headers = event.get("headers") or {}
idempotency_key = next( ( value for name, value in headers.items() if name.lower() == "idempotency-key" ), None )
if not idempotency_key: return { "statusCode": 400, "body": json.dumps({ "error": "Idempotency-Key is required" }) }
try: body = json.loads(event.get("body") or "{}")
except json.JSONDecodeError: return { "statusCode": 400, "body": json.dumps({ "error": "Invalid JSON request" }) }
request = { "idempotency_key": idempotency_key, "body": body }
result = create_order(request=request)
return { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps(result) }This example illustrates request extraction and the idempotent business function. A production handler should also map payload conflicts, in-progress requests, and infrastructure errors to deliberate HTTP responses.
Step 5: Configure API Gateway
- Open Amazon API Gateway.
- Select your HTTP API.
- Create a route:
POST /orders- Configure AWS Lambda as the integration.
- Select
OrderProcessingFunction.
- Deploy the API.
- Copy the generated endpoint URL.
API Gateway will now forward order requests to Lambda.
Step 6: Test the API
Send an initial request:
curl -X POST \ https://YOUR_API_ENDPOINT/orders \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-request-12345" \ -d '{"order_id":"ORD1001","amount":1000}'The application processes the order and stores its result.
Now send the same request again with the same idempotency key and payload.
The expected behavior is that the application returns the previously stored result without creating another order.
For a different order, generate a new idempotency key.
7. Handling Concurrent Requests and Failure Scenarios
Preventing duplicates requires more than checking whether a key exists.
Consider two identical requests arriving at almost the same time.
Both Lambda invocations might check DynamoDB before either has completed processing.
To handle this situation, the application needs atomic record creation and execution-state management.
Recommended Execution States
1. IN_PROGRESS
The request has been accepted and processing has started.
2. COMPLETED
The operation has finished successfully, and the response has been stored.
3. FAILED or RECOVERABLE
Processing failed or needs controlled recovery.
A reliable implementation should use conditional writes to prevent two requests from claiming the same new idempotency key.
AWS Lambda Powertools provides mechanisms for handling concurrent requests, execution timeouts, and stored responses.
What Happens When Lambda Times Out?
Consider this situation:
- Lambda begins processing an order.
- The business operation succeeds.
- Lambda times out before recording the completed result.
- The client retries the request.
This is a particularly important failure scenario.
The idempotency system must account for in-progress records and possible recovery.
For external side effects such as payment processing, use the same idempotency key with a downstream provider that supports idempotency, or use a durable transactional workflow such as an outbox pattern.
A DynamoDB idempotency record alone cannot guarantee exactly-once execution across an unrelated external payment system.
8. Important Difference: Synchronous and Asynchronous Retries
Not every Lambda invocation uses the same retry behavior.
For a typical API Gateway synchronous Lambda integration, the client may retry after a timeout or lost response. API Gateway's integration timeout and client timeout are separate concerns.
Asynchronous Lambda invocation has its own retry behavior and event-delivery considerations.
Therefore, developers should distinguish between:
- Client retries after an API timeout.
- Asynchronous Lambda invocation retries.
- Duplicate event delivery from event-driven systems.
Idempotency is useful across all these scenarios, but retry configuration and failure handling depend on the invocation model.
9. Best Practices for Production Applications
To implement reliable idempotency, consider the following practices:
- Require idempotency keys for operations that create important side effects.
- Generate unique keys for individual logical operations.
- Reuse the original key during client retries.
- Validate that the same key is not reused with a different request payload.
- Use conditional DynamoDB writes for atomic record creation.
- Maintain clear IN_PROGRESS and COMPLETED states.
- Store successful responses for subsequent requests.
- Define suitable expiration windows.
- Use downstream idempotency support for payment and external service operations.
- Monitor failed and in-progress operations using Amazon CloudWatch.
- Apply least-privilege IAM permissions.
- Test concurrent requests and timeout scenarios.
DynamoDB TTL can help clean up expired records, but deletion is asynchronous. Application logic must check record expiration rather than assuming that an expired item has already been deleted.
10. Monitoring and Observability
Amazon CloudWatch can help monitor the reliability of serverless APIs.
Useful metrics include:
- Lambda invocation count.
- Lambda error count.
- Lambda duration.
- Lambda throttles.
- API Gateway 4XX responses.
- API Gateway 5XX responses.
- Idempotency conflict count.
- Requests currently in progress.
Developers can also use structured logging to track request identifiers and execution outcomes.
Avoid logging sensitive information such as payment details, authentication tokens, or personal data.
11. Real-World Applications
Idempotency is especially useful in applications where repeated requests must not create repeated side effects.
Payment Processing
Prevents the same payment request from being charged multiple times.
E-commerce Applications
Prevents duplicate order creation during checkout retries.
Booking Systems
Prevents duplicate reservations when a client resubmits a request.
Banking Applications
Helps protect financial transactions against repeated submissions.
Inventory Management
Prevents duplicate stock deductions caused by repeated requests.
12. Conclusion
Building serverless applications is not only about deploying functions and connecting APIs. It is also about designing systems that behave reliably when failures, timeouts, and retries occur.
In this tutorial, we explored the importance of idempotency keys and how Amazon API Gateway, AWS Lambda, Amazon DynamoDB, and AWS Lambda Powertools can work together to prevent duplicate request processing.
We also examined concurrent requests, execution states, timeout recovery, and production security practices.
Idempotency is an essential reliability pattern for serverless applications, particularly when handling payments, orders, bookings, and other operations that produce important side effects.
Design for retries, protect against duplicates, and build reliable serverless applications!
13. References and Further Learning
- AWS Lambda Powertools – Idempotency: https://docs.aws.amazon.com/powertools/python/latest/utilities/idempotency/
- AWS Lambda Developer Guide: https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
- Amazon API Gateway Documentation: https://docs.aws.amazon.com/apigateway/
- Amazon DynamoDB Documentation: https://docs.aws.amazon.com/dynamodb/
- AWS Serverless Applications: https://aws.amazon.com/serverless/
Author: Mary Raisa
Topic: AWS Serverless Computing and Application Reliability
Level: Intermediate
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article