Idempotency
Trace idempotence from algebra and fixed points to HTTP retries, request keys, and replicated state, with original sources.
· Last updated: 2026-11-07 · 14 min read
Overview
Press a button that sets the volume to 20 ten times in a row, and the volume stays at 20. Nudge it up by 1 instead? Every press changes the state. An operation whose first result holds steady when applied again and again has idempotence, or, in API design parlance, idempotency.
Backend engineers reach for the word when blocking duplicate card charges or storing idempotency keys, though mathematicians coined it more than a century earlier to classify repeated algebraic operations. One question cuts through pure functions, HTTP retries, and replicated state merges alike: what is being repeated, and which outcome are we comparing?
A name from powers
In §25 of Linear Associative Algebra, Benjamin Peirce, father of the philosopher Charles Sanders Peirce, introduced the term idempotent to mean unless noted otherwise, right alongside nilpotent for an element whose power vanishes to zero.

The image shows printed page 8 (PDF page 20) of the 1882 edition, whose preface records that lithographed copies were first distributed in 1870.1
Apply a function to its own result
Swap multiplication for function composition and the definition carries straight over: a function from a set to itself is idempotent when for every input . Feed the output of the first call right back into , and nothing changes.
Integer absolute value passes that test because the first call strips any minus sign, leaving nothing for the second call to do; squaring fails it, taking 2 to 4 and 4 to 16.
def square(x):
return x * x
assert abs(abs(-3)) == abs(-3)
assert square(square(2)) != square(2)
print(abs(-3), square(2), square(square(2))) # 3 4 16Calling square(2) ten times returns 4 every time, but that only shows determinism (same input, same output). Testing idempotence means feeding that 4 back in as the next input, so repeating a call with the original argument and reapplying an operation to its own result are two very different checks.
Fixed points sit right next door. Any value satisfying is a fixed point, and every output of an idempotent function is immediately a fixed point because .
Do not confuse idempotence with a loop that merely settles down after several steps. Repeated integer division h(n) = n // 2 walks 8 through 8 → 4 → 2 → 1 → 0 → 0 until it hits the fixed point 0, yet the first output (4) and the second output (2) differ, so h is not idempotent.
For a binary operator, you test what happens when both operands are identical: set union obeys , which looks syntactically different from but expresses the exact same immunity to repetition.
Which program state do we compare?
A volume-setting command transforms a state into another state. Write that command as , and we can ask whether .

Both rows start at volume 5 and apply the same command twice, showing how the resulting states diverge.
def set_volume(state):
return {**state, "volume": 20}
def increase_volume(state):
return {**state, "volume": state["volume"] + 1}
initial = {"volume": 5}
assert set_volume(set_volume(initial)) == set_volume(initial)
assert increase_volume(increase_volume(initial)) != increase_volume(initial)
print(set_volume(initial), increase_volume(increase_volume(initial)))Both Python functions above return fresh dictionaries rather than touching hardware registers, yet only set_volume is idempotent, and even a command that writes to a physical amplifier can be idempotent with respect to the volume state we care about.
Property | Relationship to check | Example |
|---|---|---|
Determinism | Does the same input give the same result? | Squaring an integer |
Purity | Does the result depend only on the input, with no observable side effect? | A function that computes a new squared value |
Idempotence | Does applying it to the first result leave that result unchanged? | Absolute value; setting volume to 20 |
Involution | Does applying it twice restore the original input? | Boolean negation |
- Property
Determinism
- Relationship to check
Does the same input give the same result?
- Example
Squaring an integer
- Property
Purity
- Relationship to check
Does the result depend only on the input, with no observable side effect?
- Example
A function that computes a new squared value
- Property
Idempotence
- Relationship to check
Does applying it to the first result leave that result unchanged?
- Example
Absolute value; setting volume to 20
- Property
Involution
- Relationship to check
Does applying it twice restore the original input?
- Example
Boolean negation
Flipping a boolean once (not x) and flipping it twice yield opposite answers, and squaring leaves 0 and 1 alone while failing on 2. Checking one output or a handful of lucky inputs never proves idempotence across the whole domain.
In real software, you also have to draw a boundary around which state counts. If your system appends an audit log entry on every button press alongside the volume setting, the volume stays at 20 while the log grows on every call: the exact reason HTTP specifications define idempotency around the intended effect on the server rather than every internal byte written.
When other commands intervene
Idempotence only governs repeating the same operation; reordering different operations is commutativity. Setting volume to 20 and setting it to 50 are each idempotent on their own, yet whichever command runs last wins.
Even more importantly, chaining two idempotent operations does not automatically yield an idempotent composite! On integer pairs, and are each idempotent alone, yet repeating the two-step sequence then marches upward on every pass:
Application | State |
|---|---|
Initial |
|
|
|
Run the same pair again |
|
- Application
Initial
- State
(0, 0)
- Application
FthenG- State
(1, 0)
- Application
Run the same pair again
- State
(2, 1)
Here is the table's example on integer pairs in Python 3. It applies each function repeatedly and then repeats the sequence of both functions.
def F(point):
x, _ = point
return x, x
def G(point):
_, y = point
return y + 1, y
start = (0, 0)
once = G(F(start))
twice = G(F(once))
assert F(F(start)) == F(start)
assert G(G(start)) == G(start)
print(once, twice) # (1, 0) (2, 1)If two idempotent operations also commute with each other, their composition is idempotent: expand two runs of the pair, swap the middle terms so identical operations sit side by side, and collapse each pair. Whenever a retry replays a multi-step workflow, you have to verify the combined sequence, not just its individual steps.
Concurrent updates from other users cut across retries too. If client A sets the volume to 20, client B raises it to 50, and a delayed retry from client A arrives afterward, the volume drops back to 20: the set command stayed idempotent, but protecting B's intervening edit requires a version precondition (If-Match) or concurrency control.
Retrying when no response arrives
Consider what happens when a client sends a POST /orders request and the connection drops before any reply arrives. Did the packet die before reaching the server, or did the server commit the order and lose the response on the way back? Retrying blindly rescues the first case and double-charges the customer in the second.
Birrell and Nelson tackled this in §3.2 of their 1984 classic Implementing Remote Procedure Calls, tagging packets with call identifiers and sequence numbers so the server could tell a retransmitted packet apart from a brand-new call.2
On the web, §9.1 of RFC 2068 (HTTP/1.1, 1997) drew a clear line between safe methods (read-only) and idempotent methods (safe to repeat without compounding side effects), giving browsers and proxies a rule for which interrupted requests can be retried automatically.3
RFC 7231 in 2014 and RFC 9110 in 2022 retain the distinction. The table describes method semantics; server implementers must make their code preserve those effects across repeated requests.4
Method | Safe? | Idempotent? | Why |
|---|---|---|---|
GET and HEAD | Yes | Yes | The client requests retrieval |
PUT | No | Yes | It specifies the state of the target resource |
DELETE | No | Yes | It removes the association with the target |
POST | No | No general guarantee | The resource and application define what creation or processing means |
PATCH | No | No general guarantee | Repeated effects depend on the change and its format |
- Method
GET and HEAD
- Safe?
Yes
- Idempotent?
Yes
- Why
The client requests retrieval
- Method
PUT
- Safe?
No
- Idempotent?
Yes
- Why
It specifies the state of the target resource
- Method
DELETE
- Safe?
No
- Idempotent?
Yes
- Why
It removes the association with the target
- Method
POST
- Safe?
No
- Idempotent?
No general guarantee
- Why
The resource and application define what creation or processing means
- Method
PATCH
- Safe?
No
- Idempotent?
No general guarantee
- Why
Repeated effects depend on the change and its format
When RFC 5789 standardized PATCH in 2010, it noted that PATCH is not inherently idempotent, setting a field to 20 is idempotent, whereas adding 1 to the current value is not, and recommended pairing version-sensitive patches with a strong ETag and If-Match5
Status codes can change across retries without breaking idempotency: the first DELETE might return 204 No Content and the second 404 Not Found, yet the intended server state: the resource is gone, remains identical.6
Conversely, two GET calls can return different bodies if someone edits the resource in between, and whether a response may be stored and reused is governed separately by cacheability and freshness headers, which is why HTTP keeps safety, idempotence, and cacheability as three distinct axes.7
Request keys distinguish attempts at one order
If a server creates a new order every time a client says to add one, a retry creates another order. The client and server first need a rule for which requests count as attempts at the same operation.

This diagram is from Malcolm Featonby's Making retries safe with idempotent APIs. The caller has not received the first response, so it retries with the same identifier while the service checks processing state in StateStore. (Original figure).
Because a customer might legitimately buy the same item twice in a row, hashing the request payload alone would swallow a real second order. Safe retries instead rely on a client-generated idempotency key: the client reuses the same key only when retrying an uncertain attempt, while the server namespaces keys by authenticated caller, rejects payload changes under an existing key, and enforces an explicit retention window.8
The Python 3 snippet below runs sequentially on a single thread, taking an authenticated caller ID in owner alongside validated key and item strings and keeping each order's payload and ID together in an in-memory dictionary for the duration of the run.
requests = {}
def create_order(owner, key, item):
identity = (owner, key)
if identity in requests:
previous_item, order_id = requests[identity]
if previous_item != item:
raise ValueError("KEY_REUSED_WITH_DIFFERENT_REQUEST")
return order_id
order_id = len(requests) + 1
requests[identity] = (item, order_id)
return order_id
first = create_order("alice", "request-1", "book")
retry = create_order("alice", "request-1", "book")
another = create_order("alice", "request-2", "book")
print(first, retry, another) # 1 1 2In the script above, repeating ("alice", "request-1", "book") returns the original order ID, whereas switching to a fresh key creates a second order, and sneaking a different item ("pen") under "request-1" raises ValueError immediately.
Because this example uses an in-memory dictionary, both orders and retry records vanish when the process exits. Production servers must also handle concurrent requests and crash recovery, which requires atomic commitment.
In production, concurrency and crashes test that logic hard. If a server checks “does this key exist?” in one query and inserts the order and key in a later step, two parallel retries can both pass the check and create duplicate orders, or a crash between the two writes can leave an unrecorded order; the idempotency record and the business write must commit in a single atomic transaction.
An idempotency key only protects retries while its record lives on disk. Purge the key too early, or let the client mint a new key on retry, and duplicate protection vanishes, so key TTLs and client retry windows must be sized together.
A local database commit binds only the rows inside that database; if the handler also calls an external payment gateway, it must pass an idempotency key downstream to that gateway too. Whenever a system claims “exactly-once” behavior, ask whether it means packet delivery, handler execution, or deduplicated business state.
The law also applies when replicas merge state
Finally, look at how distributed replicas merge state without a central coordinator: in their 2011 paper Conflict-free Replicated Data Types, Shapiro, Preguiça, Baquero, and Zawirski separated state-based CRDTs, which ship full state and rely on a merge operator that is commutative, associative, and idempotent, from operation-based CRDTs.9

Figures 1 and 2 on page 3 of the paper contrast the two models: on the left, a replica ships its full state for the receiver to merge, whereas on the right it ships an operation for the receiver to replay, and the set snippet below illustrates the state-merging side. (Original figure).
def merge(left, right):
return left | right
local = {"a"}
remote = {"b"}
combined = merge(local, remote)
assert merge(combined, remote) == combined
assert merge(local, remote) == merge(remote, local)
print(sorted(combined)) # ['a', 'b']Set union (|) in Python satisfies all three laws: merging the same remote set twice changes nothing (idempotence), arriving out of order changes nothing (commutativity), and grouping merges differently changes nothing (associativity), so as long as updates grow the state monotonically and eventually reach every peer, the replicas converge.
Operation-based CRDTs, by contrast, ship the mutation itself, and applying “add 1” twice adds 2, so they depend on the messaging layer to prevent duplicate delivery rather than absorbing duplicates in the merge function.10
What each context compares
Context | What repeats | Result compared |
|---|---|---|
Algebra | Multiplication of the same element | The element itself |
Function composition | Applying the same function to its previous result | The function value |
A program that changes state | Reapplying the same command | The state chosen for observation |
HTTP | Retransmitting the same request | Its intended effect on the server |
An API with request keys | Reprocessing the same operation identifier | Contracted business effect and returned result |
State-based replication | Merging the same state again | The merged state |
- Context
Algebra
- What repeats
Multiplication of the same element
- Result compared
The element itself
- Context
Function composition
- What repeats
Applying the same function to its previous result
- Result compared
The function value
- Context
A program that changes state
- What repeats
Reapplying the same command
- Result compared
The state chosen for observation
- Context
HTTP
- What repeats
Retransmitting the same request
- Result compared
Its intended effect on the server
- Context
An API with request keys
- What repeats
Reprocessing the same operation identifier
- Result compared
Contracted business effect and returned result
- Context
State-based replication
- What repeats
Merging the same state again
- Result compared
The merged state
Mathematicians compare algebraic values, API designers compare server effects across retries, and distributed-systems engineers compare replica state across duplicate merges. Pin down which state is under comparison, and request keys, PUT replacements, and semilattice merges all fall into place.
See also
Footnotes
- Benjamin Peirce, Linear Associative Algebra, 1882 (first lithographed in 1870), p. 8. Edition record, Preface PDF. ↩
- Andrew D. Birrell and Bruce Jay Nelson, "Implementing Remote Procedure Calls," ACM Transactions on Computer Systems 2(1), 1984, §3.2. Publication record, Paper PDF. ↩
- R. Fielding et al., Hypertext Transfer Protocol -- HTTP/1.1, RFC 2068, 1997, §§8.1.4 and 9.1. RFC 2068 §9.1. ↩
- R. Fielding and J. Reschke, Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, RFC 7231, 2014, §4.2. RFC 7231 §4.2. ↩
- L. Dusseault and J. Snell, PATCH Method for HTTP, RFC 5789, 2010, §2. RFC 5789 §2. ↩
- R. Fielding, M. Nottingham, and J. Reschke, HTTP Semantics, RFC 9110, 2022, §9.2.2 (Idempotent Methods). RFC 9110 §9.2.2. ↩
- R. Fielding, M. Nottingham, and J. Reschke, HTTP Semantics, RFC 9110, 2022, §§9.2.1 and 9.2.3. RFC 9110 §9.2.3. ↩
- Malcolm Featonby, "Making retries safe with idempotent APIs," Amazon Builders' Library. Article. ↩
- Marc Shapiro, Nuno Preguiça, Carlos Baquero, and Marek Zawirski, "Conflict-Free Replicated Data Types," SSS 2011, §§2.1–2.4. Paper PDF. ↩
- Marc Shapiro et al., "Conflict-Free Replicated Data Types," SSS 2011, §§2.3–2.4 (Operation-based replication). Paper PDF. ↩