← Blog
API Fundamentals

Idempotency Keys: How to Make API Retries Safe

Idempotency Keys: How to Make API Retries Safe

An idempotency key is a unique identifier that a client includes in an API request so the server can recognize and safely ignore duplicate submissions of the same operation. If a POST request to charge a customer times out and the client retries it, an idempotency key lets the server return the original result instead of processing the charge a second time. Apidoke lets you document this behavior clearly in API Blueprint, so every developer consuming your API understands the contract before they write a single line of retry logic.

  • Idempotency keys are client-generated strings (usually a UUID) sent in a request header; the server stores the key and its result so retries return the cached response rather than re-executing the operation.
  • HTTP methods GET, HEAD, PUT, and DELETE are naturally idempotent; POST and PATCH are not, so they benefit most from explicit idempotency key support.
  • Servers typically return 200 OK or the original status code on a recognized duplicate, and 422 Unprocessable Entity or 409 Conflict when a key is reused with different parameters.
  • Documenting idempotency requirements in API Blueprint, including the header name, format, and error responses, is the clearest way to prevent costly bugs at integration time.

What does "idempotent" actually mean?

The word comes from mathematics: an operation is idempotent if applying it multiple times produces the same result as applying it once. In HTTP, the IETF HTTP Semantics specification (RFC 9110, section 9.2.2) defines idempotent methods as those where "the intended effect on the server of multiple identical requests is the same as the effect for a single such request." GET, HEAD, PUT, OPTIONS, and DELETE all qualify by definition. POST does not.

That gap is why idempotency keys exist. When a POST carries a mutation with real-world consequences, like creating an order, sending an email, or debiting an account, a network blip between the server sending its response and the client receiving it can leave the client unsure whether the operation succeeded. The safe choice for the client is to retry. Without a key, the server has no way to know it already did the work.

How an idempotency key works, step by step

  1. Client generates a key. Before sending the request, the client creates a unique string, most commonly a UUID v4 such as a3bb189e-8bf9-3888-9912-ace4e6543002. The key identifies this specific intended operation, not the client or the session.
  2. Client includes the key in a header. The request is sent with something like Idempotency-Key: a3bb189e-8bf9-3888-9912-ace4e6543002. Some APIs use X-Idempotency-Key instead; the name is part of the API contract and must be documented.
  3. Server stores the key and processes the request. On the first receipt, the server executes the operation, stores the result against the key, and responds normally, for example with 201 Created and the new resource.
  4. Client retries after a timeout. The client resends the identical request with the same key.
  5. Server recognizes the duplicate and replays the result. Instead of running the operation again, the server looks up the stored result and returns it. The status code is typically the same code as the original response, though some implementations return 200 OK regardless.
  6. Client receives a consistent response. From the client's perspective, the retry looks identical to a first-time success. No double charge, no duplicate record.
Sequence diagram showing client sending POST with Idempotency-Key, server storing result, client retrying, server returning cached result

Which HTTP methods need idempotency keys?

MethodNaturally idempotent?Needs idempotency key?Typical use case
GETYesNoFetching a resource; retrying is always safe
HEADYesNoChecking headers without a body
PUTYesNo (but can help with concurrent writes)Replacing a resource entirely
DELETEYesRarely; return 404 on second call if resource is goneRemoving a resource
POSTNoYes, for any mutation with side effectsCreating orders, payments, messages
PATCHNoYes, when the patch is not naturally repeatableIncrementing a counter, appending to a list

Real HTTP request and response examples

First request: creating a payment

POST /v1/payments HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Idempotency-Key: a3bb189e-8bf9-3888-9912-ace4e6543002

{
  "amount": 4999,
  "currency": "usd",
  "customer_id": "cus_01HXYZ"
}

Successful first response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "id": "pay_01HABC",
  "status": "succeeded",
  "amount": 4999,
  "currency": "usd",
  "created_at": "2026-11-04T10:22:31Z"
}

Retry with the same key

The client sends the exact same request again after a timeout. The server recognizes the key:

HTTP/1.1 200 OK
Content-Type: application/json
Idempotent-Replayed: true

{
  "id": "pay_01HABC",
  "status": "succeeded",
  "amount": 4999,
  "currency": "usd",
  "created_at": "2026-11-04T10:22:31Z"
}

Notice the Idempotent-Replayed: true response header. Including a signal like this is good practice: it tells the client explicitly that this was a replay, not a new operation. Some APIs use X-Idempotency-Replayed or similar; again, the name is a documentation decision.

Conflict: same key, different body

If a client sends the same idempotency key but with a different request body, the server should reject it:

HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "error": "idempotency_key_reused",
  "message": "The Idempotency-Key 'a3bb189e-...' was already used with different request parameters."
}

Returning 409 Conflict here is appropriate because the conflict is between the stored state (the original request) and the incoming one. Some APIs return 422 Unprocessable Entity instead; the choice should be documented and applied consistently. See the existing deep-dive on 401 vs 403 status codes for more context on choosing error codes deliberately.

Key format and lifetime: what to decide before you document

Before you write a single line of documentation, four decisions need to be made at the API design level:

  • Format. UUIDs (v4) are the most common choice because they are universally unique and easy to generate in any language. Some APIs accept any string up to a character limit (Stripe uses 255 characters). Define the format and enforce it.
  • Lifetime. How long does the server store a key? Common values are 24 hours or 7 days. After expiry, the same key could theoretically be reused by a different request, so document the window clearly.
  • Scope. Is the key scoped per customer, per API key, or globally? A collision between two customers using the same UUID is astronomically unlikely but the scoping rules should still be explicit.
  • In-flight handling. If two requests arrive simultaneously with the same key, the server should return 409 Conflict or a 423 Locked response while the first is still processing, then replay the result once it completes.

How to document idempotency in API Blueprint

API Blueprint (the Markdown-based format used by Apidoke) lets you document the idempotency key as a request header on each relevant action, alongside the expected response variants. The format is straightforward once you know the syntax. For a broader introduction to the format, the complete API Blueprint guide covers the full structure.

Here is a full example for a payment creation endpoint, showing the happy path and both error cases:

# Group Payments

## Payment Collection [/v1/payments]

### Create a Payment [POST]

Creates a new payment. This action is **not** idempotent by default.
Include an `Idempotency-Key` header with a UUID v4 to make the request
safe to retry. The server stores the result for 24 hours. Sending the
same key with a different request body returns `409 Conflict`.

+ Request (application/json)

    + Headers

            Authorization: Bearer {token}
            Idempotency-Key: a3bb189e-8bf9-3888-9912-ace4e6543002

    + Body

            {
              "amount": 4999,
              "currency": "usd",
              "customer_id": "cus_01HXYZ"
            }

+ Response 201 (application/json)

    + Body

            {
              "id": "pay_01HABC",
              "status": "succeeded",
              "amount": 4999,
              "currency": "usd",
              "created_at": "2026-11-04T10:22:31Z"
            }

+ Response 200 (application/json)

    Returned when the `Idempotency-Key` matches a previously completed
    request. The response body is identical to the original `201` response.

    + Headers

            Idempotent-Replayed: true

    + Body

            {
              "id": "pay_01HABC",
              "status": "succeeded",
              "amount": 4999,
              "currency": "usd",
              "created_at": "2026-11-04T10:22:31Z"
            }

+ Response 409 (application/json)

    Returned when the same `Idempotency-Key` is sent with different
    request parameters.

    + Body

            {
              "error": "idempotency_key_reused",
              "message": "The Idempotency-Key was already used with different request parameters."
            }

+ Response 422 (application/json)

    Returned when the `Idempotency-Key` header is missing or malformed.

    + Body

            {
              "error": "invalid_idempotency_key",
              "message": "Idempotency-Key must be a valid UUID v4."
            }

A few things to notice in this example. First, the description prose above the request block carries the semantic weight: it explains the rule, the key lifetime, and the conflict behavior in plain language. API Blueprint lets you put that prose anywhere before the request/response pairs, and Apidoke renders it in the center content column of the three-column viewer where developers actually read it. Second, all three non-happy-path response codes are documented: 200 for a replay, 409 for a key conflict, and 422 for a malformed key. Developers integrating your API need all four variants to write correct client code.

Testing idempotency behavior with Apidoke's try-it console

Once you have published your blueprint, Apidoke's live try-it console lets developers fire real HTTP requests directly from the documentation page. To test idempotency behavior, a developer can:

  1. Paste a UUID into the Idempotency-Key header field in the console.
  2. Fill in the request body and send the first request; observe the 201 Created response.
  3. Send the identical request again with the same key; confirm the server returns 200 OK with Idempotent-Replayed: true.
  4. Change the request body but keep the key; confirm the server returns 409 Conflict.

Because Apidoke's console fires requests directly from the browser to your API server, any Authorization header or bearer token the developer enters never passes through Apidoke's infrastructure. That matters when testing payment or financial endpoints where tokens have real access. The auth credentials stay in the browser tab and go straight to your server.

Idempotency keys versus request deduplication: what's the difference?

These terms are often used interchangeably, but there is a subtle distinction worth knowing when you are writing documentation. An idempotency key is a client-controlled mechanism: the client decides to include the key and the value. Request deduplication, in contrast, is sometimes used to describe server-side detection of duplicate submissions based on content hashing or timing windows, without any client-provided token. For documentation purposes, if your API uses an explicit client-supplied header, call it an idempotency key. If your server deduplicates silently based on fingerprinting, document that behavior separately and be clear that it has time limits and no client control.

What to include in idempotency documentation: a checklist

  • The exact header name (Idempotency-Key or your chosen variant).
  • The required format (UUID v4 recommended; maximum length if applicable).
  • Which endpoints require or accept the header; not every endpoint needs it.
  • The key lifetime: how many hours or days the server retains the result.
  • The behavior when the key is absent on a mutation endpoint (error or best-effort).
  • The status code returned on a successful replay versus a key conflict.
  • Whether a replay response includes a distinguishing header like Idempotent-Replayed: true.
  • Concurrency behavior: what happens if two requests with the same key arrive simultaneously.

That list maps directly to the prose and response blocks you write in your API Blueprint document. Each item that is undocumented is a support ticket waiting to happen. The API fundamentals category on this blog covers related concepts like rate limiting, status codes, and authentication that often appear alongside idempotency in the same endpoints.

Common mistakes in idempotency key implementation

Using the same key across different operations

A client library that generates one key per session and reuses it across multiple POST calls will cause the second operation to receive a replay of the first. Each distinct intended operation needs its own key, generated fresh before the request is sent.

Storing keys without locking

If the server does not apply a database-level lock or atomic check-and-set when storing a new key, two concurrent requests with the same key can both pass the "key not found" check and both execute the operation. The usual fix is an atomic upsert or a unique database index on the key column combined with a transaction.

Silently ignoring an unrecognized key format

Some implementations quietly proceed with the request if the key format is wrong, as though no key was provided. This is dangerous because the client believes it sent a valid key and may not retry safely. Return 422 Unprocessable Entity with a clear error body when the key is malformed.

Not documenting key expiry

Developers building retry logic need to know the key window. If they build an exponential backoff that could retry after 36 hours but the key expires after 24, they lose the safety guarantee without realizing it. Put the expiry prominently in the endpoint description, not buried in a general concepts page.

Try it live: open the JSONPlaceholder demo on Apidoke and send real GET, POST, PUT, PATCH and DELETE requests against a free fake REST API from your browser. Nothing passes through Apidoke; the request goes straight from your browser to the API.

Frequently asked questions

What is an idempotency key in simple terms?

It is a unique string, usually a UUID, that a client sends with a non-idempotent API request like a POST. The server uses it to recognize and suppress duplicate requests, returning the original result instead of executing the operation a second time. This makes retrying a failed request safe.

Should I use a UUID for my idempotency key?

UUID v4 is the most widely recommended format because it is globally unique, easy to generate in every major programming language, and familiar to developers. Some APIs accept any opaque string up to a character limit, but UUID v4 is a sensible default to both implement and document.

What HTTP status code should a server return when replaying an idempotent response?

Practice varies. Many APIs return the same status code as the original response (for example 201 Created), while others always return 200 OK on a replay and add a header like Idempotent-Replayed: true to distinguish it. Document whichever approach you choose so client developers can handle both cases correctly.

Do GET requests need idempotency keys?

No. GET is naturally idempotent by the HTTP specification: calling it multiple times returns the same resource without side effects. Idempotency keys are only needed for POST and PATCH requests (and occasionally DELETE) where repeated execution would cause unintended duplicate side effects.

How do I document an idempotency key in API Blueprint?

Add it as a named header in the + Request block of the relevant action, write the rules (format, lifetime, conflict behavior) as prose before the request block, and document all response variants including the replay response and the 409 Conflict case. Apidoke renders all of this in its three-column viewer so developers see the header, the prose explanation, and the try-it console side by side.


Ready to publish your idempotency documentation where developers can read the rules and test the behavior in one place? Sign in to Apidoke and start authoring your API Blueprint now. No credit card required, and your first published project is live in minutes.

Related reading: What Is CORS? Why Browser API Calls Fail and How to Fix It

Technically reviewed by the Apidoke engineering team.

Related reading: PUT vs PATCH vs POST: Which HTTP Method Should Your API Use?