Introduction
A customer taps “Pay”. The network is slow, so the app times out and tries again. The first request did reach your server, so now there are two payments. The same thing happens with orders, bookings, and text messages. The customer only asked once, but your API did the work twice.
Retries are normal. Mobile networks drop, load balancers time out, and good client libraries retry on purpose. The answer is not to stop retries. The answer is to make them safe. That is what an idempotency key does.
In this guide, we explain what API idempotency keys are, and how to add them to your API in seven simple steps, with PHP and MySQL examples you can adapt to any stack.
On This Page
What Is an Idempotency Key?
An operation is idempotent when doing it many times has the same effect as doing it once. An idempotency key is a unique value that the client sends with a request, usually in an Idempotency-Key header. The server remembers the key. If the same key arrives again, the server returns the saved result instead of doing the work a second time.
POST /v1/payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 7f3c91ab-44e2-4c8e-9a0b-2f6d1c3e8b17
{"amount": 4999, "currency": "INR", "customer_id": 314}
Why API Idempotency Keys Matter
- No double charges. A retried payment request returns the first payment, not a new one.
- No duplicate messages. A retried send does not text the same person twice.
- Safe automatic retries. Clients can retry timeouts and 5xx errors without fear.
- Simpler client code. The client does not need to check “did that work?” before it retries.
Which HTTP Methods Need Idempotency Keys?
Some HTTP methods are already idempotent by design. POST is the one that usually needs help.
| Method | Idempotent by default? | Needs a key? |
|---|---|---|
| GET | Yes | No |
| PUT | Yes, it replaces the whole resource | Usually no |
| DELETE | Yes, deleting twice leaves it deleted | Usually no |
| POST | No, each call can create something new | Yes |
| PATCH | Not always | Sometimes |
How to Add API Idempotency Keys in 7 Steps
1. Let the Client Create the Key
The client creates a new random key for each new action, and reuses the same key only when it retries that action. A UUID v4 is the easiest choice. The key must come from the client, because only the client knows that two requests are “the same”.
// Client side (JavaScript)
const key = crypto.randomUUID();
await fetch('/v1/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify(payment),
});
2. Create a Table to Store Keys
Store each key with the account that sent it, a hash of the request body, and the saved response. The unique index is the most important part. It is what stops two copies of the same request from both running.
CREATE TABLE idempotency_keys (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
account_id BIGINT UNSIGNED NOT NULL,
idem_key VARCHAR(255) NOT NULL,
request_hash CHAR(64) NOT NULL,
status ENUM('processing','done') NOT NULL DEFAULT 'processing',
response_code SMALLINT NULL,
response_body MEDIUMTEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_account_key (account_id, idem_key)
);
3. Scope Keys to Each Client
Always store the key together with the account or API client ID. Two different customers could send the same key by chance. They must never see each other’s responses.
4. Claim the Key Before Doing the Work
Insert the key first, before you charge the card or send the message. If the insert fails because of the unique index, another request with the same key already exists. This makes the database do the hard work of handling two requests that arrive at the same moment.
<?php
$hash = hash('sha256', $rawBody);
try {
$stmt = $pdo->prepare(
'INSERT INTO idempotency_keys (account_id, idem_key, request_hash)
VALUES (:account, :idem_key, :hash)'
);
$stmt->execute(['account' => $accountId, 'idem_key' => $key, 'hash' => $hash]);
} catch (PDOException $e) {
if ($e->errorInfo[1] === 1062) { // duplicate key
return replayOrReject($pdo, $accountId, $key, $hash);
}
throw $e;
}
5. Save the Response and Replay It
After the work is done, save the status code and body. When the same key comes back, return exactly the same response. Many APIs also add a header such as Idempotent-Replayed: true, which helps when debugging.
<?php
function replayOrReject(PDO $pdo, int $accountId, string $key, string $hash): void
{
$stmt = $pdo->prepare(
'SELECT request_hash, status, response_code, response_body
FROM idempotency_keys
WHERE account_id = :account AND idem_key = :idem_key'
);
$stmt->execute(['account' => $accountId, 'idem_key' => $key]);
$row = $stmt->fetch();
if ($row['request_hash'] !== $hash) {
jsonResponse(422, ['error' => 'Idempotency key reused with a different request']);
}
if ($row['status'] === 'processing') {
jsonResponse(409, ['error' => 'A request with this key is still in progress']);
}
header('Idempotent-Replayed: true');
http_response_code((int) $row['response_code']);
echo $row['response_body'];
exit;
}
6. Reject the Same Key with a Different Body
If a client sends the same key with a different amount or a different phone number, something is wrong in the client. Do not guess. Return an error, such as 422, and do nothing. That is why we store a hash of the request body.
7. Expire Old Keys
Keys do not need to live forever. Most APIs keep them for 24 hours to a few days, which covers any normal retry window. A small cron job keeps the table small:
DELETE FROM idempotency_keys
WHERE created_at < NOW() - INTERVAL 24 HOUR
LIMIT 10000;
Idempotency Responses at a Glance
| Situation | What the API does | Status code |
|---|---|---|
| New key | Runs the request and saves the result | 201 or 200 |
| Same key, same body, finished | Returns the saved response | Same as the first |
| Same key, still processing | Asks the client to wait and retry | 409 Conflict |
| Same key, different body | Rejects the request | 422 |
| No key on a POST that requires one | Rejects the request | 400 |
Common Idempotency Mistakes to Avoid
- Checking before inserting. A
SELECTfollowed by anINSERThas a race window. Use a unique index and let the insert decide. - Global keys. Always scope keys to the account, or customers may see each other’s data.
- Saving the key after the work. If the server crashes in the middle, the retry runs the work again. Claim the key first.
- Caching 5xx errors forever. If the first attempt failed because of a temporary error, remove the key or let the client retry with the same key.
- Generating keys on the server. The server cannot tell two retries apart from two real requests. The client must send the key.
Conclusion
Networks fail, and clients will retry. Idempotency keys turn those retries from a risk into a safety net. With one table, one unique index, and a few lines of code, your API can stop double charges, duplicate orders, and repeated messages. Pair them with clear REST API status codes, and clients will always know what happened.
FAQs
1. What is an idempotency key in an API?
It is a unique value the client sends with a request, usually in the Idempotency-Key header. The server uses it to recognise a retry and return the first result instead of doing the work again.
2. Which header should I use for idempotency keys?
Idempotency-Key is the common choice. It is used by major payment APIs and is being standardised by the IETF HTTP API working group.
3. How long should I keep idempotency keys?
24 hours is a common default. Keep them at least as long as your clients might retry a request.
4. Do GET requests need idempotency keys?
No. GET, PUT, and DELETE are idempotent by design. Idempotency keys are mainly for POST requests that create something.
5. What should happen if two requests with the same key arrive at the same time?
Only one should run. A unique database index makes the second insert fail, and the API returns 409 Conflict until the first request finishes.
Related Articles
- REST API Status Codes: 12 HTTP Codes Every Backend Developer Should Use Right
- Designing a Cashfree Payment Integration Module for a Web Application
- Understanding GraphQL: A Beginner’s Guide to Modern API Design
Official Documentation
- IETF Draft: The Idempotency-Key HTTP Header Field
- RFC 9110: Idempotent Methods
- Stripe API: Idempotent Requests
Talk to Our API Experts
Duplicate payments and repeated orders cost money and trust. At Pheonix Solutions, our backend developers build APIs that handle retries, high traffic, and failures safely.
We can help you with:
- Web and API development, including payment and messaging APIs with safe retries.
- DevOps and cloud services to run your APIs reliably at scale.
- Software maintenance and support to find and fix duplicate-request bugs in existing systems.
Seeing duplicate orders or double charges? Talk to our API experts and make every retry safe.
