Systemsfor Aravinda
0 / 78 core
Week 4 · Distributed systems

Idempotency and the exactly-once myth

2 hours · core path

Read first: Networking for request paths

In one sitting

An operation is idempotent when doing it twice has the same effect as doing it once, which a state-setting write already has and a charge does not until a client key stores the outcome. Exactly-once is a bounded protocol that stops at the edge of that protocol. A card network and an inbox sit outside it.

The client timed out. It will send the charge again. Idempotency is the property that makes the second send match the first, instead of billing twice and calling the extra bill a retry.

Core concepts

An operation is idempotent when doing it twice has the same effect as doing it once. The word is about the effect, not about the packet. Two requests can hit the server and still leave one outcome. Two requests can also hit the server and leave two charges, two emails, or a balance that moved twice. The network cannot see the difference. You design it.

There are two ways to get the property.

A natural idempotent write sets state. “The balance is 40.” Send it again and the balance is still 40. “The order status is shipped.” Send it again and the status is still shipped. A delete that treats “already gone” as success is the same shape. You can retry these without a key and the stored state does not drift. The response should be the same success, so the client does not treat the second call as a new kind of failure.

A write that adds, appends, or charges is not natural. “Add 40 to the balance” twice ends at plus 80. “Charge this order” twice can capture two payments. “Send the receipt” twice sends two receipts. Nothing in the handler’s body tells you the second call is a duplicate, because the second call is a perfectly legal request from a client that never saw the first response.

An imposed idempotent write uses a key the client generated. The server stores the key with the outcome. A retry that presents the same key returns the stored outcome and does not run the effect again. Stripe’s API takes an Idempotency-Key on mutating POST requests. The client generates it. A UUID is the usual advice. The server keeps the key with the result for a short time, on the order of 24 hours in the published guidance, not as a permanent archive. The Stripe idempotency page is the production writeup of the same pattern, including the parts that hurt.

The key is a contract with three clauses that people drop. The same key with the same parameters returns the stored outcome. The same key with different parameters is an error, because a fingerprint of the parameters is stored with the key. A bug that reuses a key for a different amount must not be answered with the previous receipt. Concurrent retries that present the key before the first attempt has finished must lock, so two workers do not both decide that no outcome exists yet and both run.

At least once is the delivery you actually have

Delivery guarantees are three words, and only two of them are strategies.

At most once means you send and forget, or you acknowledge before you do the work. A crash loses the operation. You do not apply it twice, and you also do not know that you applied it.

At least once means you acknowledge after the work. If you crash after the effect and before the ack, the sender delivers again. Duplicates happen. This is what a timeout forces on you even without a queue. The client’s clock expired. The request may still be running. The retry is a second delivery of work the server might already have done.

Exactly once is a bounded protocol, not a wish. Inside Kafka, the idempotent producer and transactions give effectively-once processing inside Kafka’s protocol. That sentence stops at the boundary of the protocol. It is not a universal guarantee once you send email or charge a card. Kafka can make the log contain the record once. The card network was not a party to that transaction. A checkbox labeled exactly once, on a consumer that then calls a bank, is a label on the log and a duplicate on the statement.

The practical shape is at least once delivery plus an idempotent handler. You accept that the request will arrive twice. You make twice equal once. Retries, backoff, and circuit breakers belong on a call that is idempotent or that carries a key. A retry of anything else is how you double-charge a customer who had a slow link.

Networking for request paths adds one more duplicate that is not a timeout. HTTP/3 on QUIC can send data in the first flight, and 0-RTT replays are a real concern for non-idempotent requests. A replayed 0-RTT charge is a second POST with no human in the loop. The key is what makes the replay harmless. A charge without a key should not be in that first flight.

The call you cannot roll back

A local database transaction can roll back. Transactions and isolation give you all-or-nothing for the rows in that database. The moment you have called another system, that call is not in the transaction. You cannot unsend the charge because your process crashed before the commit.

Recovery points are how you live with that. Record that you are about to perform the foreign call. Then do it. Then record that you did it, and store the outcome with the key. A retry reads the point and continues, instead of starting over. If the row says you have not called the card network, you may call it. If the row says you are in the middle of the call, you wait or you ask the network about the attempt you already named. If the row says the call finished, you return the stored outcome. You do not create a second charge to find out.

The outbox pattern is the same honesty aimed at a bus. You write the business row and the outbox row in one database transaction, so you do not commit the order and then fail to publish, or publish and then fail to commit. The consumer on the other side must still be idempotent. The outbox closed the dual write. It did not make the email exactly once.

A worked example

A shopper pays for one order. The handler charges a card and stores the result under a key the client chose. Assumptions, labeled as assumptions, because the race is made of times:

  • The client gives up after 2 seconds. That timeout is an assumption you would set from the user’s budget, not a law.
  • On this attempt the card network responds in 3 seconds. That is an assumption about one slow call, not a vendor SLA and not a number you should memorize.
  • The key K was generated by the client for this order. The amount and the customer are the parameters you fingerprint.
  • Two workers can pick up the two HTTP requests. They share one database.
assume client timeout = 2 s
assume this card response arrives at 3 s
the retry overlaps the first call by 1 s

t = 0.0   POST charge, Idempotency-Key K
t = 0.0   insert row K, state = about to charge, fingerprint = hash of the parameters
t = 0.1   submit the charge to the card network
t = 2.0   client times out and sends the same POST again
t = 2.0   second worker looks up K
          without a lock, both workers can pass "no outcome yet" and both submit
          with a lock, the second worker waits
t = 3.0   the card network approves the first submission
t = 3.1   first worker sets K to done and stores the approval
t = 3.1   second worker returns that stored approval
          one charge

keys kept on the order of 24 hours
24 hours = 86,400 seconds
a retry inside that window must find the row
a retry next week is outside the published guidance

The one-second overlap is the bug. The client did the reasonable thing. The server’s first attempt had not failed. It was slow. If the second worker also submits, the shopper pays twice and both calls can return success. The lock is what makes the second worker a reader of the outcome instead of a second charger.

Walk the crash next, because the lock does not cover a process that dies in the middle. The card network approves at 3.0 seconds. The worker dies at 3.05 seconds, before the row is marked done. The client’s retry arrives, takes the lock, and reads the row. The row says “about to charge,” not “done.” The worker must not submit a fresh charge. It continues from the recovery point: find out what happened to the attempt already named, then record the outcome, then return it. A database transaction around the row update can roll back. The approval cannot. The row you wrote before the call is the only reason the retry knows the call might have happened.

Compare that with a natural write so the key does not become a reflex.

PUT order 42 status = shipped
PUT order 42 status = shipped
stored status is shipped
no key required for the state to stay single-valued

POST balance 42 add 40
POST balance 42 add 40
stored balance moved by 80
the second add is a second effect

POST balance 42 add 40, key K
POST balance 42 add 40, key K
stored balance moved by 40
the second call returned the first result

The shipped status is idempotent because it names the resulting state. The add is idempotent only after you impose a key. If someone tells you the increment is safe to retry because “it is a small request,” they have confused the size of the packet with the effect.

A queue makes the same split. The consumer charges the card, then crashes before it acks. The broker redelivers. That is at least once, and it is a duplicate by design. The key makes the redelivery return the stored charge. If the consumer acks first and then crashes, the charge is lost. That is at most once. Pick the duplicate on purpose, and make the handler absorb it. Do not ack early to keep the lag chart pretty.

flowchart TB
  client[Client retries with key K]
  handler[Charge handler]
  row[Stored outcome for K]
  card[Card network]
  client --> handler
  handler --> row
  handler --> card

The row sits on the path to the card network for a reason. You write the intention before you call out. A diagram that goes from the handler straight to the card, and only then to the database, is the crash window.

Tradeoffs

Approach What twice does Where it fits
Set a field to a value Leaves that value Status, a balance you assign, a delete that may already be gone
Client key, stored outcome Returns the first result and skips the effect Charges, emails, anything that appends
At most once Maybe nothing A metric you can drop
At least once, no key Applies the effect again A bug, if the effect was a charge
At least once, with a key One effect, extra requests The practical shape
Kafka transactions Effectively once inside Kafka The log, not the card and not the inbox

A short key lifetime and a long one are both choices. On the order of 24 hours matches the published guidance: long enough for the slow client and the queue redelivery, short enough that you are not building an archive of every POST. Five minutes loses to a phone that retries from a tunnel. Forever turns a key-reuse bug into a permanent wrong receipt.

Pitfalls

  • Retrying a POST because the client library retries by default. The library does not know the charge is not idempotent.
  • Putting a non-idempotent charge in HTTP/3 0-RTT. A replay is a second charge that the shopper did not click.
  • Returning the stored success when the same key arrives with a different amount. That hides a client bug inside a 200.
  • Forgetting the lock. Two workers both read “no outcome yet” in the one-second overlap and both call the card network.
  • Treating Kafka’s exactly-once setting as a promise about the bank. The bound is the protocol. The charge is outside it.
  • Keeping keys for a few minutes, or forever. The published guidance is on the order of 24 hours. A retry outside the window is a new operation whether you meant it to be or not.
  • Acking the queue message before the handler finishes. A crash then loses the work, which is at most once wearing an at least once configuration.
  • Calling an increment idempotent because the request body is identical. Identical bytes that add are two additions.

In the interview

Draw the timeout in the first five minutes. “The client waits 2 seconds, I am assuming the card call takes 3 on this attempt, and the retry carries the same key. The handler inserted an ‘about to charge’ row before the call, takes a lock so the second worker cannot start another charge, and returns the stored approval.” The number is that 1 second of overlap, and the retention is on the order of 24 hours, which is 86,400 seconds. The bottleneck is the card network, because you cannot roll it back. The tradeoff is the stored key and the lock, against a double charge.

Skip a claim that the system is exactly once. Say the bound: Kafka can give you effectively-once inside its protocol, and the charge is not inside it. Skip a tour of UUID versions. The client generated a key. That is enough.

The question that usually follows is the crash after the bank said yes and before you recorded it. The answer is the recovery point. You already wrote that you were about to call. The retry continues from that row. It does not open a second charge to discover the first.

Check yourself

Setting the balance to 40 twice, and submitting a charge twice, are not the same kind of retry. Why?

Setting the balance names the resulting state, so the second write leaves 40. That is natural idempotency. A charge adds an effect outside your database. The second submission can capture a second payment. It becomes safe to retry only when a client key is stored with the first outcome and the retry returns that outcome instead of charging again.

The client times out at 2 seconds and the card call returns at 3 seconds, with the same key. What must the second worker do?

It must not submit a second charge. The first call is still in flight, which is the 1 second of overlap those two assumptions create. The second worker takes the lock, waits for the row, and returns the stored approval. Without the lock both workers can observe that no outcome exists yet and both call the card network. The times are assumptions about one slow attempt, not an SLA.

The handler uses Kafka transactions and also charges a card. Where does exactly-once stop?

Inside Kafka. The idempotent producer and transactions give effectively-once processing inside that protocol. The card network did not enroll in the transaction. A consumer retry can still charge twice unless the charge itself is idempotent under a key and a recovery point. Email is outside the same bound. The checkbox covers the log.

The same idempotency key arrives again with a different amount. What should the server return?

An error. The key was stored with a fingerprint of the parameters. Replaying a different request under a key that already has an outcome would hand the client the wrong receipt and might look like success. The match has to be the key and the parameters. A bare key with no fingerprint cannot tell a retry from a mix-up.

The process dies after the card network approves and before the row is marked done. Why is the earlier row the whole trick?

A local transaction can roll back the row update. It cannot roll back the approval. The row that says you were about to charge is what the retry reads. Continuing from that recovery point means finding the attempt you already started, recording the outcome, and returning it. Starting over submits a second charge for a payment that already happened.

Based on: Stripe idempotency, Brandur Leach; Kafka, Jay Kreps, Neha Narkhede, and Jun Rao; Designing Data-Intensive Applications, Kleppmann and Riccomini.