Search

Search papers and lessons

Idempotent Operation

Level 2 · 9 min read

An idempotent operation gives the same result when repeated as when run once, so a sender can safely retry it after a lost reply.

On this page

  • Colour = topic mix
  • Programming languages
  • Discrete math
  • Algorithms
  • Distributed systems
  • Systems
  • ReadReady to readNot yet

TL;DR

An idempotent operation is one you can repeat any number of times and end up in the same state as if you ran it once. Setting a balance to 50 is idempotent: doing it twice still leaves 50. Adding 5 to the balance is not: doing it twice adds 10. This matters because networks lose replies, so a sender often cannot tell whether an operation happened, and it retries.

Builds on: Function Composition, Side Effects · Leads to: Message Delivery Guarantees

Where it's used

Web APIs. The HTTP standard marks some request methods as idempotent. A GET that reads a user's profile, or a PUT that replaces a user's address with a given address, can be sent again without harm. A POST that creates an order is different: a client that retries a POST after a timeout may create two orders. Many payment APIs therefore ask the client to send an idempotency key with each charge. The server remembers the key and returns the first answer when the same key arrives again, so a 20 dollar charge happens once even if the request arrives three times.

Message queues. A queue that delivers each message at least once (see Message Delivery Guarantees) will sometimes hand a consumer the same message twice. A consumer that writes "set order 88 to shipped" is safe to run twice. A consumer that writes "add 1 to the shipment counter" is not, unless it records which messages it has already handled.

Data pipelines. A nightly job that is re-run after a crash should leave the same table behind as the first run. A job that replaces all rows for one day is idempotent. A job that appends that day's rows again is not, because every re-run adds duplicates.

How it works

Take one tiny instance: a server stores a number called balance, which starts at 10. The client can send two kinds of request, "set balance to a value" and "add a value to balance". Replies can be lost on the way back.

  1. The server stores balance = 10.
  2. The client sends "set balance to 50". The server writes 50 and sends back "ok". Check: balance = 50.
  3. The "ok" is lost on the network. The client does not know whether the write happened, so after a timeout it sends "set balance to 50" again. The server writes 50 again. Check: balance = 50, the same as after step 2. The repeat changed nothing. That is idempotence.
  4. Now try "add 5" instead. Balance is 50. The server computes 50 + 5 = 55 and replies "ok", but the reply is lost. The client retries "add 5". The server computes 55 + 5 = 60. Check: balance = 60, but the client only asked for one addition, so it should be 55. The repeat changed the result. Adding is not idempotent.
  5. The usual fix is to give each request a unique id. The server keeps a record of the ids it has applied, along with the reply. When a request arrives with an id it has seen, it returns the stored reply and does not apply the change again. Check: request 7 "add 5" applied once gives 55. Its retry with id 7 returns 55, and the balance stays 55.
sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: set balance to 50
  S-->>C: ok (reply lost)
  Note over C: no reply, so retry
  C->>S: set balance to 50 again
  S-->>C: ok, balance is still 50

The math

Definition: Idempotent operation

An operation f is idempotent when applying it twice gives the same result as applying it once: for every input x,

f(f(x))=f(x)f(f(x)) = f(x)

Here f(f(x)) means "apply f, then apply f again", which is the composition of f with itself (see Function Composition).

Step 2 in symbols

Let f(x) be "set the balance to 50, whatever it was". Then f(x) = 50 for any starting value x. So f(f(x)) = f(50) = 50 = f(x). The equation holds, so the operation is idempotent.

Step 4 in symbols

Let g(x) be "add 5 to the balance", so g(x) = x + 5. Then g(g(x)) = x + 10. The two sides differ for every x, because x + 10 is never equal to x + 5. So "add 5" is not idempotent. With x = 50: g(50) = 55 and g(g(50)) = 60.

Step 5 in symbols

Let the server keep a table T that maps each request id r to the reply it gave. A request with id r and current state x does this: if r is already in T, return T[r] and leave the state x unchanged. If not, compute the new state x + 5, store T[r] = the reply, and return it. Sending the same request twice therefore gives the same state the second time: the state after the first application, not one more addition.

Worked examples

Example
A number that does not change
  1. Let f(x) be the absolute value of x, written abs(x). So abs(-3) = 3.
  2. Compute f(-3). abs(-3) = 3.
  3. Compute f(f(-3)). The inner result is 3, so this is f(3) = abs(3) = 3.
  4. Compare: f(f(-3)) = 3 and f(-3) = 3. They are equal. Taking the absolute value again changes nothing, so abs is idempotent.
Example
Set versus add
  1. The balance starts at 10.
  2. Operation A is "set to 50". Apply it once: the balance is 50. Apply it again: the balance is still 50. The two results match, so A is idempotent.
  3. Operation B is "add 5". Apply it once: 10 + 5 = 15. Apply it again: 15 + 5 = 20. The results differ, so B is not idempotent.
  4. Interpretation: if a client retries B after a lost reply, the balance grows by 5 for every extra attempt. If it retries A, nothing changes. This is why many systems rewrite "add 5" as "set to 15", using the value the client last read, though that also needs care when two clients act at once (see Race Condition).
Example
A charge retried over an unreliable connection

A shop asks a payment service to charge a customer 20 dollars for order 1041. The request reaches the service and the charge succeeds, but the reply is lost. The shop gives up after two seconds and retries.

  1. Without a key, the retry is "charge 20 dollars" again. The service charges a second time. The customer pays 20 + 20 = 40 dollars for one order. The operation is not idempotent.
  2. With a key, the first request is "charge 20 dollars, key k-1041-a". The service charges the card once and stores the key with its result, "charged, id 9001".
  3. The retry arrives with the same key, k-1041-a. The service finds the key in its table and returns "charged, id 9001" without charging again.
  4. Result: the customer pays 20 dollars once, and the shop gets the answer it needed. The repeat did not change the state.

Try it: the shop's second retry also arrives with key k-1041-a, after the first retry already succeeded. How many dollars has the customer paid in total? Answer: 20 dollars. Each repeat with the same key returns the stored result, so the charge happens only once.

Common mistakes and tradeoffs

It is tempting to think a retry is safe because the first request probably never arrived. In fact the request may well have arrived and been applied, and only the reply was lost. A retry then repeats the work. Any operation with side effects needs a plan for repeats.

It is tempting to think idempotent means "does nothing the second time". In fact it means the state after the second run equals the state after the first. The reply can still differ. Deleting a file the second time may correctly return "not found", while the file system is in the same state.

It is tempting to think an HTTP PUT is idempotent because the standard says so. In fact the standard describes what the method is meant to do. A PUT handler that appends to a list when it runs is not idempotent in effect, whatever the method name says.

Tradeoffs: making an operation idempotent by design (set a value instead of adding to it) is cheaper than keeping a table of keys. Keys need storage and an expiry time, and the check for "have I seen this key" must be safe under concurrency. Writing the key and the effect in one Database Transaction keeps them consistent. Use keys when the operation cannot be rewritten as an absolute value, such as charging money or sending an email. Do not add them where a plain set would do.

History

The word "idempotent" was introduced in 1870 by the American mathematician Benjamin Peirce, for elements that give themselves back when multiplied by themselves. Computing borrowed the idea once networks could lose messages and senders had to retry. The HTTP specification of 1999 (RFC 2616) listed GET, HEAD, PUT, DELETE and some other methods as idempotent, and the later RFC 9110 keeps that idea. It caught on because it turns the question "did my request run?" into a question that does not need an answer: the sender can simply send it again.

Recap

  • An operation f is idempotent when f(f(x)) = f(x): repeats add nothing new.
  • Networks lose replies, so senders retry, and a retry repeats the operation.
  • "Set to a value" is idempotent. "Add a value" is not.
  • To make a non-idempotent operation safe, tag it with a unique key and store the first result.
  • Read next: Message Delivery Guarantees for what messaging systems promise about repeats, and Database Transaction for storing a key and its effect together.

Check yourself

QuestionIn your own words, what does it mean for an operation to be idempotent?Show answer

Running it once or several times leaves the system in the same state as running it once. The reply may still differ, for example a "not found" on a second delete.

QuestionLet g(x) = x + 5. Compute g(10) and g(g(10)). Is g idempotent?Show answer

g(10) = 15. Then g(g(10)) = g(15) = 20. Since 20 is not 15, g is not idempotent.

QuestionWhy can retrying a POST that creates an order produce two orders, even when the first request reached the server?Show answer

The client never received the reply, so it cannot tell whether the order was created. The retry is a new request, and the server creates a second order. A key that the server recognizes on the retry prevents this.

QuestionA balance is 100. The request 'set balance to 80' arrives three times with nothing else in between. What is the balance at the end, and why?Show answer
  1. Setting to a value is idempotent, so the second and third applications leave the state the same as the first.
QuestionA nightly job appends yesterday's rows to a table and is re-run after a crash. Is it safe, and what would make it safe?Show answer

Not as written: each run adds the rows again, so duplicates appear. It becomes safe if the job first deletes yesterday's rows and then inserts them again, or if it writes rows keyed by a primary key so that a repeated write replaces the same row. Either way the final table is the same however many times the job runs.

Sources