Your Lambda Function Ran Twice. Is Your Architecture Ready?
Retries are essential to building reliable cloud applications, but they can also create duplicate payments, repeated database writes, and unexpected side effects. Learn how to design idempotent serverless applications using AWS Lambda, Amazon SQS, and DynamoDB.
Your Lambda Function Ran Twice. Is Your Architecture Ready?
Imagine building a serverless application on AWS.
A customer clicks the Pay button. Your API receives the request, triggers an AWS Lambda function, and processes the payment.
Everything works perfectly.
But then something unexpected happens.
The Lambda function gets invoked again for the same request.
Maybe there was a timeout. Maybe the event was delivered again. Maybe the application retried the operation because it didn't receive a response.
Now imagine the consequences:
- A customer gets charged twice.
- An order is created more than once.
- An email notification is sent repeatedly.
- Inventory is reduced twice.
This is not necessarily an AWS failure. It is a distributed systems problem.
And one of the most important concepts for solving it is idempotency.
1. What Is Idempotency?
Idempotency means that performing the same operation multiple times produces the same intended result as performing it once.
For example:
Consider an operation that updates a customer's order status to
CONFIRMED .Executing it once:
CONFIRMED Executing it five times:
CONFIRMED The final state remains unchanged.
However, consider an operation that adds ₹500 to an account balance.
Executing it five times adds ₹2,500.
That operation is not idempotent.
In distributed applications, this distinction matters because retries are a normal part of system behavior.
2. Why This Matters in AWS Serverless Architectures
AWS serverless services make it easy to build event-driven applications.
A common architecture looks like this:
API Gateway → Lambda → SQS → Lambda → DynamoDB
Each component has its own delivery, timeout, and retry behavior.
For example:
- AWS Lambda can retry asynchronous invocations.
- Amazon SQS can deliver a message again when it is not successfully processed and deleted.
- A client may retry an API request after a timeout.
- A downstream service may process a request even when the original caller never receives its response.
This means your application should not assume that every event will be processed exactly once.
Instead, design your business operations to handle repeated requests safely.
3. A Practical Solution Using DynamoDB
Let's build a simple idempotency mechanism.
Imagine an order-processing Lambda function receives this event:
{ "orderId": "ORD-1001", "customerId": "CUST-101", "amount": 500}We can use the order ID as an idempotency key.
Before processing an order, the Lambda function checks whether that order has already been processed.
Amazon DynamoDB supports conditional writes, which help us prevent multiple executions from claiming the same idempotency key.
Example Python implementation
import boto3from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table("ProcessedOrders")
def process_order(event):
order_id = event["orderId"]
try: table.put_item( Item={ "orderId": order_id, "status": "PROCESSING" }, ConditionExpression="attribute_not_exists(orderId)" )
except ClientError as error:
if error.response["Error"]["Code"] == "ConditionalCheckFailedException": return { "statusCode": 200, "message": "Order already being processed or processed" }
raise
# Perform the business operation here.
table.update_item( Key={"orderId": order_id}, UpdateExpression="SET #status = :status", ExpressionAttributeNames={ "#status": "status" }, ExpressionAttributeValues={ ":status": "COMPLETED" } )
return { "statusCode": 200, "message": "Order processed successfully" }Important: This is a simplified example of claiming an idempotency key. A production implementation should also handle stale PROCESSING records, failures after claiming a key, concurrent requests, and recovery.
For financial operations, use appropriate transactional or provider-supported idempotency mechanisms rather than relying on a simple database flag.
4. What Happens When the Same Event Arrives Again?
Let's say the same order event arrives three times.
Attempt | What happens |
|---|---|
First request | Creates the idempotency record |
Second request | Conditional write fails |
Third request | Conditional write fails |
The application avoids starting the same business operation again.
This is the basic idea behind idempotent processing.
5. Improve the Architecture With SQS and Lambda
For event-driven workloads, Amazon SQS can help decouple producers and consumers.
A useful architecture is:
API Gateway → Lambda → SQS → Processing Lambda → DynamoDB
Consider adding:
- SQS Dead-Letter Queues for messages that repeatedly fail.
- Visibility timeout configured appropriately for processing duration.
- Partial batch responses for SQS-triggered Lambda functions.
- CloudWatch metrics and alarms to detect processing failures.
- Idempotency keys for operations that must not be repeated.
Remember that an SQS message can be delivered more than once. A dead-letter queue helps isolate problematic messages, but it does not replace idempotency.
6. Five Best Practices for Production Systems
1. Use stable idempotency keys
Choose a unique business identifier, such as an order ID or payment request ID. Avoid generating a new key for every retry.
2. Use conditional writes
DynamoDB conditional expressions can prevent multiple workers from successfully claiming the same key.
3. Handle incomplete operations
A PROCESSING record does not automatically mean an operation succeeded. Define how your application recovers from abandoned or failed processing attempts.
4. Monitor retries and failures
Use Amazon CloudWatch metrics, logs, and alarms to understand how often your application retries operations.
5. Design external API calls carefully
If your Lambda function calls an external payment or notification provider, use that provider's idempotency support where available. A DynamoDB record alone cannot guarantee exactly-once execution across independent systems.
7. The Bigger Lesson: Design for Failure, Not Just Success
When developers first learn AWS Lambda, they often focus on making the function execute successfully.
But production engineering requires a different mindset.
Ask yourself:
- What happens if the function executes twice?
- What happens if the database write succeeds but the response times out?
- What happens if the application crashes halfway through processing?
- What happens if two Lambda instances receive the same event simultaneously?
These questions help transform a working serverless application into a reliable system.
Conclusion
AWS provides powerful building blocks for serverless architectures, including Lambda, SQS, DynamoDB, API Gateway, and CloudWatch.
But reliability doesn't come from choosing the right services alone.
It comes from designing your application to handle retries, duplicate events, partial failures, and unexpected behavior.
Your Lambda function may run twice. Your business operation shouldn't happen twice.
That is the real value of idempotency.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article