TapCub is live — analytics, insights and live chat, free on one platform
Glossary

What is idempotency? Safe retries and idempotency keys

Idempotency means repeating an operation has the same effect as doing it once. HTTP methods, idempotency keys, a retry example that inflates revenue by 5% and how to de-duplicate events.

Chen Yu Reviewed by Xu An Also called idempotent Last updated Dec 3, 2026 Glossary

Quick answer

Idempotency is the property of an operation that can run once or many times with the same intended effect. In HTTP, PUT, DELETE and read-only methods such as GET are idempotent; POST is not. It is what makes retrying after a timeout safe, often with a unique idempotency key.

Formula: f(f(x)) = f(x); retry inflation = duplicate rows ÷ true rows

What is idempotency?

Idempotency is the property of an operation that can be applied once or many times with the same intended effect. In mathematics, a function is idempotent when f(f(x)) = f(x): taking the absolute value of a number twice gives the same answer as taking it once. In software the idea is about side effects: if the same request arrives three times, the system ends up in the state it would be in if it had arrived once.

The HTTP specification, RFC 9110 section 9.2.2, defines a request method as idempotent if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Two details in that definition are often missed:

  • It is about the intended effect, not the response. Deleting a record twice is idempotent even though the second call may answer "404 Not Found" instead of "204 No Content".
  • It covers what the client asked for. The same section says a server is free to log each request separately or keep a revision history. An extra line in an access log does not break idempotency; a second charge on a card does.

The practical reason to care is retries. Networks lose messages, and a sender that cannot tell whether its request was processed has two choices: give up and risk losing the action, or send it again and risk doing it twice. Idempotency removes the second risk.

Which HTTP methods are idempotent?

RFC 9110 states that PUT, DELETE and the safe methods are idempotent. The safe methods it defines are GET, HEAD, OPTIONS and TRACE: their semantics are essentially read-only. POST is not idempotent, and RFC 5789 says PATCH is neither safe nor idempotent, though a particular PATCH can be written so that repeating it does no harm.

MethodSafeIdempotentWhat a repeat does
GETYesYesReads again; nothing the client asked for changes
HEADYesYesSame as GET without the body
OPTIONSYesYesAsks about communication options again
TRACEYesYesLoops the request back again
PUTNoYesReplaces the resource with the same representation again
DELETENoYesThe resource stays deleted; the status code may differ
POSTNoNoMay create a second order, comment or payment
PATCHNoNoDepends on the patch: "set price to 20" repeats cleanly, "add 5 to price" does not

The table describes the contract, not your code. A DELETE handler that decrements a counter every time it is called violates the contract, and clients that retry it will corrupt the counter. RFC 9110 also sets two rules for senders: a client should not automatically retry a non-idempotent request unless it knows the request is in fact idempotent or can detect that the original was never applied, and a proxy must not automatically retry non-idempotent requests at all.

Why retries make idempotency matter

When a client sends a request and gets no usable answer, several different things may have happened on the other side. The client usually cannot tell them apart:

What happenedWhat the client seesResult of a blind retry without idempotency
The request never arrivedTimeout or connection errorCorrect: the action happens once
The server processed it, but the response was lostTimeout or connection errorWrong: the action happens twice
The server is still processing itTimeoutWrong or racing: two copies run at once
The server failed partway through500-class error or resetUnknown: partial work may be repeated
The server refused before doing anything (rate limit)429Correct if the client waits first

The first two rows look identical from outside. That is why "just retry on timeout" is only safe when the receiving side recognizes a repeat. Rate limiting adds more retries to the picture; the right waiting behavior for 429 and Retry-After is covered in rate limiting.

Worked example: retries that inflate revenue

Sample data. A shop's backend sends purchase events to an analytics system in batches. On one day there are 10,000 real purchases in 100 batches of 100, from 200,000 sessions, with an average order value of $50. Four batches time out after the receiver has already stored them. The sender resends three of them once and one of them twice.

Extra rows = 3 batches × 100 × 1 resend + 1 batch × 100 × 2 resends = 500.

MetricTrue valueStored without a keyError
Purchases10,00010,500+5.0%
Revenue at $50 per order$500,000$525,000+$25,000 (+5.0%)
Conversion rate over 200,000 sessions5.00%5.25%+0.25 points
Rows with a stable key per order10,00010,000none

Four timeouts out of 100 batches sounds minor, yet revenue is off by $25,000 for the day. Nothing fails loudly: every request eventually returned success, and the dashboard simply shows a good day. The usual symptom is that analytics revenue is higher than the order system's total for the same dates.

If each purchase carries a key derived from the order, such as the order ID, the receiver can drop the 500 repeats and both systems agree.

How an idempotency key works

For operations that are not idempotent by nature, such as creating an order with POST, the client attaches a unique idempotency key and the server remembers it. The IETF HTTPAPI working group is standardizing an Idempotency-Key request header. As of 3 December 2026 it is an Internet-Draft (revision 09, dated 21 November 2026), not yet an RFC, and many APIs use their own header or body field for the same job.

A request under the draft looks like this:

POST /orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"

{"cart_id": "c_5521", "total": 50.00}

The draft requires that a key is not reused with a different payload and recommends a UUID or similar random identifier. It lets the server store a fingerprint of the payload next to the key. The expected server behavior:

SituationWhat the draft says the server should do
Key not seen beforeProcess the request and answer normally
Retry after the original completedAnswer consistently with the request having been completed
Retry while the original is still runningReply 409 Conflict
Same key with a different payload (fingerprint mismatch)Reply 422 Unprocessable Content; do not return the first result
Required key is missingReply 400 Bad Request with a link to documentation

The server also decides how long keys live. The draft says a resource should define and publish its expiry policy. That number matters to clients: a retry sent after the key has been purged looks like a brand-new request.

How to make an operation idempotent

  1. Prefer natural idempotency. "Set status to shipped" or "PUT this profile" can be repeated freely. "Increment the shipment count" cannot. Often the operation can be rewritten as a set instead of an add.
  2. Create the key per action, not per attempt. Generate it when the user places the order or when the job is queued, store it with the job, and reuse it on every retry.
  3. Claim the key atomically. Insert the key under a unique constraint before doing the work. "Check whether it exists, then insert" lets two concurrent retries both pass the check.
  4. Store the outcome. Keep the status and response with the key, so a later retry gets the same answer instead of running again.
  5. Keep the effect and the record together. Write the business row and mark the key complete in one database transaction. If the side effect is in another system, pass the key downstream so that system can reject repeats too.
  6. Outlive the retry window. Key retention must be longer than the longest time any client, queue or manual replay might resend.

A minimal shape in SQL:

-- 1. claim: fails if another attempt already holds the key
INSERT INTO idempotency (key, fingerprint, state)
VALUES (:key, :hash_of_payload, 'running');

-- 2. do the work and finish in one transaction
BEGIN;
INSERT INTO orders (id, cart_id, total) VALUES (:order_id, :cart_id, :total);
UPDATE idempotency SET state = 'done', response = :body WHERE key = :key;
COMMIT;

When step 1 fails on the unique constraint, read the existing row: if the fingerprint differs, reject; if the state is running, answer 409; if it is done, return the stored response. Also decide what happens to a key stuck in running after a crash, for example by letting it expire and then checking whether the order exists.

Idempotency vs safe methods vs deduplication

TermQuestion it answersWho enforces itExample
Safe methodDoes the request ask for any state change?HTTP semanticsGET a product page
Idempotent operationDoes repeating it change anything beyond the first time?The operation's designPUT a new shipping address
Idempotency keyIs this a repeat of a request already received?Server that stores keysPOST an order with a key
DeduplicationWhich stored or arriving records are copies?Pipeline or databaseDrop two events with one ID
Data validationIs this record well formed and allowed?Schema and rulesReject a negative price

Validation and deduplication are different filters. A retried purchase is perfectly valid, so schema checks will pass it twice. Deduplication needs an identity for the action, which has to be created by whoever knows that two messages mean the same thing.

Idempotency also differs from "exactly-once delivery". Most delivery you can build is at-least-once: messages may arrive more than once. Making the receiver idempotent turns at-least-once delivery into an effectively-once result.

Event de-duplication in analytics

Event pipelines retry constantly, so they need an event identity. The CloudEvents specification, a CNCF standard for describing events, requires producers to make source + id unique for each distinct event, allows a re-sent duplicate to keep the same id, and lets consumers assume that events with identical source and id are duplicates.

Choosing what goes into the ID decides what counts as "the same event":

Key choiceWhat happensVerdict
New random value on every attemptEvery retry looks newNo deduplication at all
Timestamp onlyTwo different buyers in the same millisecond collideReal events get dropped
User ID + event nameA second genuine purchase is treated as a repeatToo coarse
Order ID (or order ID + event name)Retries match, separate orders stay separateGood for server-side facts
UUID created when the action happens and stored with itSame, even without a business numberGood for general events

Two limits apply to almost every deduplication scheme. The receiver only compares within some window, so a replay outside the window is stored again. And a key only matches copies that share it: if the browser reports a purchase with one ID and the server reports it with another, both rows stay. Deciding which side reports each fact is part of server-side tracking.

Common mistakes with idempotency

  • Minting the key inside the retry loop. The key must be created before the first attempt.
  • Treating idempotent as "same response". Compare the resulting state, not the status code.
  • Check-then-write without a constraint. Two parallel retries both see "not found".
  • Expiry shorter than the retry queue. A job replayed after three days against a 24-hour key store runs twice.
  • Retrying errors that will never succeed. A 400 or 401 needs a fixed request or credential, not another attempt.
  • Forgetting downstream effects. The order insert is protected but the confirmation email is sent on every attempt.
  • No test for it. Send the same request twice, then twice in parallel, and count rows and side effects.

How to retry server events safely in TapCub

Take the 500 extra purchases from the example. TapCub's server events API deduplicates on an insert_id field in each event (not on an HTTP header), up to 36 characters.

  1. Create a key. In Configuration › Settings › API keys, create a key with the Server track scope and keep it on your server.
  2. Send each purchase with a stable insert_id and its original time. The order ID works well. The server-side events guide shows the request. Browser track calls carry no insert_id, so report orders from the server only.
  3. Retry with the same body. On 429, wait at least retryAfter seconds; on 5xx and network errors, back off exponentially. Do not regenerate insert_id or time.
  4. Respect the window. Duplicates inside one batch are dropped, and so is an event whose insert_id is already stored with an event time within one day. A time more than 72 hours from the server clock is replaced with the current time, so replaying a three-day-old failure can store a second copy. Stop automatic retries before that and reconcile older gaps by hand.
  5. Verify in the report. Both attempts count as accepted in the response because deduplication happens at ingest. Open All-platform analytics › Behavior › Event analysis and filter by order number: there should be one row. Compare the day's revenue with your order system, as in revenue tracking.

TapCub does not process payments and does not make your own order API idempotent. It only deduplicates the events you send to it.

Sources

Was this explanation clear?

We use your answers to fix and expand this page.

Chen Yu

Technical Engineer

Focuses on tracking code, SDKs, and API integrations, with practical guidance on implementation checks and troubleshooting.

FAQ

Questions people ask

Short answers to the follow-up questions that come up most.

Still have a question?

Chat with the team behind TapCub — we usually reply within a few hours on business days.

What does idempotent mean in simple terms?

Doing it again changes nothing further. Setting a light switch to off is idempotent: pressing off five times leaves the light off. Pressing a toggle button is not, because every press flips the state. In APIs, an idempotent request can be repeated after a timeout without creating a second order or payment.

Is POST idempotent?

Not by definition. RFC 9110 lists PUT, DELETE and the safe methods as idempotent, and POST is not among them. A particular POST endpoint can be made idempotent by requiring a unique key per action and returning the original result when the same key arrives again.

What is an idempotency key?

A unique value the client creates for one action and sends with every attempt of it. The server stores the key, processes the first request and treats later ones as repeats. A UUID or a stable business ID such as an order number works; a new value per attempt does not.

How long should an idempotency key be kept?

Longer than the latest moment any client, queue or manual replay might resend. The IETF draft asks servers to define and publish an expiry policy. If keys expire after 24 hours but your job queue retries for three days, late retries are processed as new requests.

See this number on your own site

Add one script tag for web and apps, and the first reports fill in within minutes.

See your data clearly. Find your growth.

Every click, backed by data. Install one line of code and see your first numbers in a minute.

No credit card · Free plans for analytics and chat · Cookieless analytics