Your API can successfully process a request, and your system can still end up in a failure scenario.
Consider a payment API. The server receives a request, charges the customer, and returns a response. But somewhere between the server and the client, the network connection breaks.
From the server’s perspective, the operation succeeded. From the client’s perspective, nothing happened.
So the client retries.
This is where a seemingly harmless retry can turn into a duplicate payment, a second order, or an unintended database operation. Retries are often essential for reliability, but without the right safeguards, they can introduce a completely different kind of failure.
The solution isn’t to stop retrying. It’s to design APIs that can safely handle retries.
The Request That Succeeded but Never Reached the Client
Imagine a customer purchasing a product from an online store. They click the checkout button, and the application sends a request to the server.
The server receives the request, validates the order, processes the payment, and saves the transaction in the database. Everything works as expected on the server.
However, before the response reaches the customer, the network connection times out.
The customer doesn’t know whether the payment was successful. All they see is a spinning loader or an error message. Naturally, they try again.
The server receives another request. Without any mechanism to identify that this is a retry of the original operation, it may process the payment again, creating another transaction.
The problem is that a timeout doesn’t necessarily mean the operation failed. It only means the client didn’t receive a response in time.
This is a fundamental challenge in distributed systems. Networks can fail, connections can be interrupted, and responses can get lost even when the server successfully completes the operation.
That’s why API retries need to be designed carefully. A reliable API must account for the possibility that the same request could reach the server multiple times.
Retries are one of the most common ways applications handle temporary failures. If a request fails because of a network interruption, a server temporarily becomes unavailable, or a connection times out, the client may attempt the request again.
This sounds reasonable, and in many situations, it is. Retries help applications recover from temporary problems without requiring users to manually repeat an action.
But there is a catch: the client doesn’t always know whether the previous request actually failed.
Consider a simple API endpoint:
POST /api/orders Every time this endpoint receives a valid request, it creates a new order in the database.
Now imagine the client sends the request, but the response gets lost. The client retries the request, and the server receives it again.
If the server treats both requests as independent operations, it may create two orders instead of one.
The same problem can occur in several situations:
- Payments: A customer could be charged twice because the payment request was retried.
- Order creation: A single checkout attempt could generate multiple orders.
- Database operations: A request could insert duplicate records.
- Notifications: A user could receive the same notification multiple times.
- Inventory: Stock could be deducted repeatedly for the same purchase.
The problem becomes even more interesting when retries are automatically handled by HTTP clients, mobile applications, API gateways or background workers. The developer may not even realize that the same request is being sent multiple times.
This doesn’t mean retries are bad. In fact, retries are often necessary for building resilient systems. The problem is retrying operations that aren’t designed to safely handle repeated execution.
Instead of assuming that every incoming request represents a new operation, an API needs a way to recognize when a request is actually a retry of something that has already been processed.
That’s where idempotency comes in.
What Idempotency Actually Means
Idempotency is a concept that sounds more complicated than it actually is.
An operation is idempotent if performing it multiple times produces the same intended result as performing it once.
Let’s understand this with a simple example.
Imagine you have a light switch that turns a light on. If you send a command saying “turn the light on” five times, the light remains on. The final state is the same as if you had sent the command once.
Now imagine a different command: “toggle the light.” Every time you execute it, the light changes its state. If the light is initially off, the first command turns it on, the second turns it off, and the third turns it on again.
The difference is that the first operation is idempotent, while the second is not.
APIs follow a similar principle.
Consider an API that updates a user’s profile:
PUT /api/users/101 { "name": "John", "city": "Delhi" } If this request is executed five times, the user’s profile still contains the same information. The operation doesn’t keep creating new changes each time it runs.
However, consider an API that creates a payment:
POST /api/payments Every time this request is processed, a new payment could be created. Sending the same request repeatedly might result in multiple payments.
This is why HTTP methods such as PUT are generally designed to be idempotent, while POST is not inherently idempotent. However, HTTP method semantics alone don’t guarantee that your application implementation is safe.
Idempotency is not about preventing requests from being sent multiple times. It’s about ensuring that repeating an operation doesn’t produce unintended additional effects.
And for APIs that perform operations such as payments, orders or resource creation, we need a practical way to achieve that.
Idempotency Keys — How APIs Recognize Repeated Requests
If retries are unavoidable, how can a server know whether an incoming request is a new operation or simply a retry of an operation it has already processed?
One common solution is an idempotency key.
An idempotency key is a unique identifier generated by the client for a particular operation. The client sends this key along with the request, allowing the server to recognize repeated attempts belonging to the same operation.
For example, a client making a payment request could send:
POST /api/payments Idempotency-Key: 8f4d7a21-92c1-4c1b-a821 Content-Type: application/json { "amount": 1500, "currency": "INR", "order\_id": "ORD-1042" } The key identifies the intended payment operation, rather than simply identifying the HTTP request.
If the client experiences a timeout, it can retry the same request using the same idempotency key.
The key must remain the same across retries of the same operation. Generating a new key for every retry defeats the purpose.
How the server uses the key
When the server receives the request, it checks whether the idempotency key has already been used.
- If the key is new: The server processes the operation and stores the key alongside the operation’s status and result.
- If the key has already been processed: The server returns the previously stored result instead of repeating the operation.
- If the original operation is still processing: The server needs a defined strategy for handling the repeated request, such as returning a processing response or coordinating with the existing operation.
This allows the client to retry without accidentally creating another payment.
The server isn’t relying on the client to behave perfectly. Instead, it maintains its own record of which operations have already been handled.
However, simply storing an idempotency key isn’t enough. The server must store it reliably, prevent concurrent requests from processing the same operation, and handle failures correctly.
That means the database design becomes an important part of building an idempotent API.
Building Idempotency Into Your API and Database
Understanding idempotency keys is easy. Implementing them correctly is where things become interesting.
A common mistake is to check whether a key exists, and if it doesn’t, process the request. While this sounds reasonable, it can fail when multiple requests arrive at the same time.
Before writing the code, let’s understand what our API needs to store.
We need a database table that keeps track of the idempotency key, the request status, and the result of the operation.
For example, we could create a table like this:
1. Create an idempotency table
Instead of relying on memory or a temporary variable, we can store idempotency keys in a database.
CREATE TABLE idempotency\_keys ( key TEXT PRIMARY KEY, request\_hash TEXT NOT NULL, status TEXT NOT NULL, response JSONB, created\_at TIMESTAMP DEFAULT NOW() ); 2. Understand the request flow
The key idea is that a request must claim its idempotency key before another request can independently process the same operation.
3. A simple implementation using Node.js and PostgreSQL
Let’s assume we have a payment API. For simplicity, we’ll demonstrate the database logic using Node.js, Express and PostgreSQL, while treating the payment operation as a database-backed example rather than an actual external payment gateway.
The following example illustrates the basic approach:
app.post("/api/payments", async (req, res) => { const key = req.headers\["idempotency-key"\];if (!key) { return res.status(400).json({ error: "Idempotency key required" }); } const requestHash = hashRequest(req.body); const client = await pool.connect(); try { await client.query("BEGIN"); // Try to reserve this key const inserted = await client.query( \`INSERT INTO idempotency\_keys (key, request\_hash, status) VALUES ($1, $2, 'processing') ON CONFLICT (key) DO NOTHING RETURNING key\`, \[key, requestHash\] ); // If the key was not inserted, it already exists if (inserted.rowCount === 0) { const existing = await client.query( \`SELECT request\_hash, status, response FROM idempotency\_keys WHERE key = $1\`, \[key\] ); const record = existing.rows\[0\]; if (record.request\_hash !== requestHash) { await client.query("ROLLBACK"); return res.status(409).json({ error: "Key used with a different request" }); } await client.query("COMMIT"); if (record.status === "completed") { return res.json(record.response); } return res.status(409).json({ error: "Operation is still processing" }); } // Perform the operation const result = await createPaymentInDatabase( client, req.body ); // Store the result await client.query( \`UPDATE idempotency\_keys SET status = 'completed', response = $2 WHERE key = $1\`, \[key, JSON.stringify(result)\] ); await client.query("COMMIT"); return res.json(result); } catch (error) { await client.query("ROLLBACK"); return res.status(500).json({ error: "Internal server error" }); } finally { client.release(); } }); This is an illustrative implementation. It assumes helper functions such as hashRequest, createPaymentInDatabase and a configured PostgreSQL connection pool. It also assumes the payment operation is transactional within the database.
4. What is actually happening in this code?
Let’s break the important parts down.
First, the server tries to reserve the key.
INSERT INTO idempotency\_keys (key, request\_hash, status) VALUES ($1, $2, 'processing') ON CONFLICT (key) DO NOTHING RETURNING key; This attempts to insert a new key. If the key already exists, PostgreSQL’s unique constraint prevents another row from being created.
Second, the server handles duplicate requests.
If the key already exists, the server retrieves the existing record. If the operation has already completed, it returns the previously stored response instead of performing the payment again.
It also compares the request hash. This matters because a client shouldn’t be able to reuse the same key for a different payment amount or another operation.
Third, the operation and its result are saved together.
In this example, the payment record and idempotency record are stored within the same database transaction. If the transaction commits, both the operation and its result are saved. If it rolls back, neither is committed.
This is important because we don’t want the payment to be successfully recorded while the idempotency result is lost.
However, database transactions alone cannot guarantee safety when the operation involves an external payment provider.
If an external payment provider charges a customer outside your database transaction, your database rollback cannot undo that charge. In such cases, you need additional safeguards, such as using the provider’s idempotency mechanism, durable operation states, reconciliation and carefully designed recovery logic.
This implementation demonstrates the core principle: reserve a key, process the operation, store the result, and return that result when the same operation is retried.
But there’s still a problem worth understanding. What happens when two identical requests arrive at almost exactly the same time?
The Edge Cases That Can Break Your Idempotency Design
Building an idempotent API isn’t just about storing a key and returning an old response. Real systems encounter concurrent requests, unexpected crashes, partial failures and changing data.
Let’s look at some of the situations your design needs to handle.
1. What happens when two requests arrive simultaneously?
Imagine a client sends a payment request. Because of a network issue, it retries almost immediately. Both requests reach your server at nearly the same time.
If your server simply checks whether the key exists and then processes the payment, both requests might check the database before either has inserted the key.
Both could conclude that the key is new.
This is a race condition.
That’s why a database-level unique constraint is essential. It allows the database to enforce ownership of the key, even when multiple requests arrive concurrently. Application-level checks alone are not sufficient.
2. What happens if the server crashes?
Suppose the server reserves the idempotency key, processes the operation, but crashes before returning a response.
The client retries, but the server needs to determine whether the operation completed, failed or is still being recovered.
This is why idempotency records should have meaningful states, and why the operation and its result must be stored reliably.
For external operations, recovery may require reconciliation or querying the external provider rather than blindly executing the operation again.
3. What happens if the same key is used with a different request?
Imagine a client sends a payment of ₹1,500 using an idempotency key.
Later, it sends ₹5,000 using that same key.
Should the server treat this as the original payment?
No. The key represents a particular operation, not a reusable identifier for arbitrary requests. The server should compare the request payload, or a normalized representation of it, against the original request and reject incompatible reuse.
4. Should idempotency keys expire?
Idempotency records don’t necessarily need to be stored forever. Depending on the system, they may be retained for a limited period.
However, deleting keys too early can be dangerous. If a client retries after a key has expired, the server may treat the request as a new operation.
The retention period should therefore reflect the expected retry window, the business risk, and any additional safeguards available for the operation.
5. Is idempotency enough to guarantee reliability?
Idempotency is a powerful tool, but it isn’t a complete solution to every distributed systems problem.
It helps prevent repeated requests from producing unintended duplicate effects, but it doesn’t automatically solve external service failures, inconsistent state, transaction coordination, message delivery problems or recovery after crashes.
Reliable systems combine idempotency with appropriate transaction boundaries, durable state, retries, monitoring and recovery mechanisms.
Conclusion
Retries are an important part of building reliable applications. Networks fail, clients lose connections, servers experience temporary problems, and requests don’t always receive the responses they expect.
But retrying a request doesn’t guarantee that the original operation failed.
That’s why designing idempotent APIs matters. By using idempotency keys, database constraints, reliable operation states and carefully designed transaction boundaries, we can allow clients to retry requests without unintentionally repeating the same business operation.
The goal isn’t to eliminate retries. It’s to make retries safe.
A reliable API doesn’t assume a request will arrive only once. It is designed to handle the possibility that it might arrive again.

