Idempotency Is Like an Elevator Button: Meaning of Idempotency, How Idempotency-Key Works, and How to Prevent Double Transactions
By Tim APIPedia, Tim Engineering APIPedia · Published · Updated · 11 min read
Idempotency makes API requests safe to repeat without duplicate transactions. This is what idempotent means, how Idempotency-Key works, and a code example.

Idempotency is the property of an operation whose final result remains the same, whether it is executed once or many times. The easiest way to imagine it: idempotency is like an elevator button. You may press it five times because you're impatient, but there will still be one lift coming. In the API world, this property prevents the balance from being deducted twice when the "Pay" button is re-pressed or the connection is lost midway.
For developers and business owners, idempotency is important because networks are never perfect: a request may arrive but the answer is lost, and then the application tries again. This article discusses the meaning of idempotent, which HTTP methods are safe to repeat, how header Idempotency-Key works, code examples we've run, and things that are often misunderstood.
Quick summary: what do you need to know?
Idempotency makes requests safe to repeat, and for POST ways it is to include a unique key that the server recognizes. The following table summarizes the terms.
| Term | It means |
|---|---|
| Idempotent | The effect on the server is the same, sent once or ten times |
| Safe method (safe) | Read-only methods, for example GET and HEAD. All safe methods are idempotent |
| Retry | Resending the same request due to a timeout or connection loss |
| Idempotency key | A client-generated unique key, usually a random UUID, that marks a single transaction intent |
Header Idempotency-Key | Where the key was sent. Still has draft IETF standard status (draft-08, 22 October 2026) |
| Request fingerprint (fingerprint) | Summary of request contents, such as hashes, to ensure one key is not used for different contents |
| 409 and 422 | Draft suggested code: 409 if the first request is still being processed, 422 if the key is reused with different contents |
What is idempotency?
Idempotency is a guarantee that repeating the same operation does not add new effects. The HTTP standard (RFC 9110) defines it this way: a method is called idempotent if the intended effect on the server of many identical requests is the same as the effect of just one request.
Return to the elevator. The "up" button is idempotent: the first press makes the lights come on and the elevator is called, the second through fifth presses change nothing. Compare this with ordering meatballs by shouting "Bang, one bowl!". If you shout three times because your brother doesn't turn around, three bowls could come. The cry is not idempotent.
So that you can safely order meatballs again, you need a marker. For example, table number: "Table 7, one bowl." His brother takes notes, and if you repeat the same sentence, he simply replies "Already noted, Table 7." The table number is the role of the idempotency key in the API.
Why can the same request be sent twice?
Requests are sent twice because clients often don't know whether the first request was successful. There are three most common causes:
- Answers get lost along the way. The server has processed the payment, but the connection drops before the answer arrives. From the application side, this looks exactly the same as the failed request.
- User presses reset. Slow signal, screen doesn't change, "Pay" button pressed three times.
- Automatic retry. The HTTP library, message queue, or webhook sender retries itself when it times out.

For this reason, RFC 9110 reminds: clients should not automatically repeat requests with methods that are not idempotent, unless they know the operation is idempotent or can ensure that the first request is never processed.
Which HTTP method is idempotent?
According to RFC 9110, idempotent methods are PUT, DELETE, and all safe methods are GET, HEAD, and OPTIONS. Two methods that are not guaranteed to be idempotent are POST and PATCH.

| Method | Impotent? | Everyday examples |
|---|---|---|
GET, HEAD, OPTIONS | Yes, and safe at the same time | View balance. Viewed 100 times, balance has not changed |
PUT | Yes | Rewrite the address on the form with the same content |
DELETE | Yes | Cross names off the list. Crossed out again, still crossed out |
POST | Not guaranteed | Ordered meatballs without a table number |
PATCH | Not guaranteed | "Reduce stock 1". Repeated three times, stock reduced by three |
In the APIPedia catalog, most data endpoints use GET, for example GET /v1/wilayah/provinsi or GET /v1/kurs/latest, so it is safe to repeat during a timeout. What needs extra attention are endpoints POST that have real effects, such as POST /v1/sms/send which deduct SMS credits for every message sent.
How does Idempotency-Key work?
Idempotency-Key works by leaving a unique key in the request, then the server remembers that key and the answer. If a request with the same key comes again, the server does not reprocess it and simply returns the stored answer.
- The client creates a key once for one transaction intent, usually a random UUID, before the first request is sent.
- The key is sent via header
Idempotency-Keywith requestPOSTorPATCH. - The server processes and stores the key, fingerprint of the request content, and the answer.
- When retrying, the client uses the same key. The server recognizes it and replays the old answer.
Example of the request form (address and token below are just illustrations):
curl -X POST https://api.contoh.co.id/v1/bayar \
-H "Authorization: Bearer TOKEN_ANDA" \
-H "Content-Type: application/json" \
-H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' \
-d '{"dari": "budi", "jumlah": 25000, "untuk": "warung-bu-sri"}'What happens on the server side?
On the server side there are five possibilities, and the IETF draft standard suggests status codes for its three rejection cases.

| Condition | Draft suggested answer |
|---|---|
| Key required but not sent | 400 Bad Request |
| Retry comes while the first request is still being processed | 409 Conflict |
| Keys are reused with different request contents | 422 Unprocessable Content |
Code example: small idempotent server
The following Python simulation shows the logic without any framework. We ran it in Python 3 and included the output below.
import hashlib, json, uuid
simpanan = {} # idempotency key -> {"sidik": ..., "status": ..., "body": ...}
saldo = {"budi": 100_000}
def sidik_jari(payload):
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
def bayar(payload, key=None):
if key is None:
return 400, {"error": "Header Idempotency-Key wajib diisi"}
sidik = sidik_jari(payload)
lama = simpanan.get(key)
if lama:
if lama["sidik"] != sidik:
return 422, {"error": "Key sudah dipakai untuk isi request yang berbeda"}
if lama["status"] is None:
return 409, {"error": "Request pertama masih diproses"}
return lama["status"], lama["body"] # putar ulang jawaban lama
simpanan[key] = {"sidik": sidik, "status": None, "body": None}
saldo[payload["dari"]] -= payload["jumlah"] # efek samping terjadi SEKALI
body = {"id_transaksi": "trx_" + uuid.uuid4().hex[:8], "sisa_saldo": saldo[payload["dari"]]}
simpanan[key].update(status=201, body=body)
return 201, body
key = str(uuid.uuid4())
pesanan = {"dari": "budi", "jumlah": 25_000, "untuk": "warung-bu-sri"}
print("1.", bayar(pesanan, key)) # request pertama
print("2.", bayar(pesanan, key)) # retry setelah timeout
print("3.", bayar(pesanan, key)) # pengguna klik lagi
print("4.", bayar({**pesanan, "jumlah": 50_000}, key)) # key sama, isi beda
print("5.", bayar(pesanan)) # tanpa key
print("Saldo akhir:", saldo["budi"])Output when we run:
1. (201, {'id_transaksi': 'trx_f4df685f', 'sisa_saldo': 75000})
2. (201, {'id_transaksi': 'trx_f4df685f', 'sisa_saldo': 75000})
3. (201, {'id_transaksi': 'trx_f4df685f', 'sisa_saldo': 75000})
4. (422, {'error': 'Key sudah dipakai untuk isi request yang berbeda'})
5. (400, {'error': 'Header Idempotency-Key wajib diisi'})
Saldo akhir: 75000The first three requests produced the same id_transaksi and the balance only decreased by IDR 25,000. In production systems, simpanan should be shared storage such as a database or Redis with unique limits on key columns, because two requests can arrive at two different servers in the same second.
What is often misunderstood about idempotency?
The most common misconception is to think that idempotent means the server's answer is always the same. What is guaranteed to be the same is the effect on the server, not the status code. Here are five things that need to be straightened out.
- "Idempotent means the responses are identical." Not always. The first
DELETEcan answer 200, the second 404 because the data no longer exists. The effect remains the same: the data is lost. - "Idempotent equals safe." Different. The safe method does not change the data at all.
DELETEis idempotent, but clearly changes the data. - "As long as you send the Idempotency-Key header, it's definitely safe." Only if the server supports it. Unknown headers are usually ignored, and requests are still processed twice. Always check the documentation for the endpoint you use.
- "Idempotency-Key is the official standard." Not yet. Its status is still Internet-Draft in the IETF HTTPAPI working group (draft-08 dated October 22, 2026, expires April 25, 2027 if not updated). Therefore the details differ between providers, for example the length of the key and the length of time the key is stored.
- "Each retry, use a new key to make it unique." This actually turns off the protection. Keys are generated once per transaction intent and reused across all attempts. New keys mean new transactions.
What are some practical tips for implementing it?
The basic rule: create a key before the first request, save it, and use the same key until you get a definite answer. The details are different for client side and server side.
If you call someone else's API
- Create a key from a random UUID, not from personal data such as email or phone number.
- Save the key along with the order data in your database, so that after restarting the application you still use the same key.
- Do not change the contents of the request during retry. Changing the nominal with an old key will be rejected, and rightfully so.
- Pay attention to the key shelf life. One major payment provider says keys can be deleted after they are at least 24 hours old and have a maximum length of 255 characters. Retry after that time is considered a new request.
- If the endpoint does not support idempotency locks, check first before repeating. For example in the APIPedia SMS Gateway: before resending
POST /v1/sms/sendwhich has timed out, look at the history throughGET /v1/sms/messagesto make sure the first message has not been sent.
If you build an API or webhook receiver
- Store keys and record their effects in a single database transaction, with unique limits on key columns.
- Compare the fingerprints of the request contents, and reject the keys used for different contents.
- Determine the key shelf life and write it in the documentation. The IETF draft recommends publication of expiration policies.
- The recipient of the webhook must also be idempotent, because the sender of the webhook usually repeats the send when it does not receive a response. Use the event ID as the key. A complete explanation is in the article how webhooks work.
- Combine retry with a longer delay to avoid hitting the request limit. See the rate limit and error 429 articles.
Frequently asked questions
What is the difference between idempotent and safe?
Secure methods do not change data on the server, while idempotent methods can change data as long as repetition does not increase the effect. All safe methods are definitely idempotent, but not vice versa: PUT and DELETE are idempotent but not safe.
Does GET need Idempotency-Key?
No need. GET is already idempotent by the definition of the HTTP standard, so the lock doesn't provide any benefit. Idempotency keys are designated for POST and PATCH.
How long is the idempotency key stored?
Depends on the API provider. The IETF draft does not set a figure and only calls for expiration policies to be published. As an illustration, there are payment providers that store keys for at least 24 hours.
What happens if the same key is used for different request contents?
Servers following the IETF draft will reject it with 422 Unprocessable Content. One key only represents one request body, so for other transactions you have to create a new key.
Is an idempotency key the same as an API key?
No. The API key answers "who is calling", while the idempotency key answers "which request is this". Both are sent simultaneously via different headers. Regarding API keys, read API keys like boarding house access cards.
To continue learning the basic concepts of API and AI in the same style, also read that AI tokens are like pulses and the difference between MCP and regular API. If you want to try it straight away, create a key at console.apipedia.id and start from endpoint GET which is safe to repeat.
Source
Topics: #idempotency #idempotency key #api #explainer #http #retry
About the author
Tim APIPedia — Tim Engineering APIPedia
Tim engineering di balik APIPedia yang membangun dan memelihara API data Indonesia - ongkir, OCR KTP, data wilayah, BMKG, hingga server MCP - dan menulis panduan integrasinya dari pengalaman langsung.