Idempotency: tap send twice, get charged only once
What idempotency is: why a flaky network makes apps retry and charge you twice, and how a small key lets the bank recognise a request it has already handled.

Mục lục
You are standing in a lift, open your banking app and send a friend 20 dollars. The spinner spins and spins, then shows “Something went wrong, please try again”. Has the money gone? If you tap again, will you be charged twice? If you do not, will your friend get paid? Anyone who has been in this situation knows the feeling.
The answer from well-built payment systems lies in a slightly awkward word: idempotency. An operation is idempotent if doing it once or doing it many times gives the same result. Press the lift call button five times and the lift still comes once: that button is idempotent. Sending money is naturally not like that; every time you do it, money leaves your account. This article explains why a flaky network turns the advice “just retry” into something dangerous, and how a tiny idempotency key lets the bank recognise “I have already done this one”. At the end there is a piece of code that simulates 10,000 transfers over a bad network.
When the app shows an error, what actually happened?
Between tapping “Send” and seeing the success screen, your request has to travel over the mobile network, the internet and several layers of servers, and the reply has to travel back. Engineers at Stripe, a large payment processing company, sort the failures into three kinds[1]:
- The request never arrived. The signal dropped just as it was sent. The bank received nothing, and no money moved. Retrying is safe.
- The server failed midway. The bank received it and was working on it when it crashed. Whether the money moved depends on how the system is written; usually an unfinished transaction is rolled back entirely.
- The work is done, but the reply was lost. The bank has taken the money and sent it to your friend, but the “done” message got lost on the way back. The app waits, times out and shows an error.
The hard part is this: from the phone’s side, the three cases look exactly the same. In each one the app waits, times out and gets no answer. It cannot tell whether it is in case 1 (it should resend) or case 3 (it must never do it again).
Retrying: a cure that makes things worse
If the app does not retry, in case 1 the customer gets an error and has to tap again. In case 3 the app shows an error while the money has already gone, and if the customer taps again thinking it did not go through, the money goes a second time.
If the app retries a few times automatically, case 1 is saved, but case 3 becomes a systematic disaster: every lost reply means one extra charge.
In the simulation at the end of the article, over a network that loses 5% of requests and 10% of replies (numbers chosen for illustration; real networks are usually much better), the outcome of 10,000 transfer taps is:
- No retry: the app shows an error 1,475 times. In 523 of them the money really did not go, but in 952 the money went and the app still showed an error.
- Automatic retry up to 3 times, no key: the app almost never shows an error (29 times), but 1,004 people are charged twice or more, about one in ten.
HTTP, the common language of the web, warns about exactly this. The RFC 9110 standard says some kinds of request (such as reading data, PUT to overwrite and DELETE to remove) are idempotent and can be retried automatically when a connection fails, while for others (such as POST, the kind usually used to create a new transaction) the sender should not retry automatically unless it has some way to know the original request was not applied[3]. Delete a file twice and it is still gone only once. Create a transaction twice and you have two transactions.
Idempotency keys: numbering every tap
The solution is very simple. The moment you tap “Send”, the app generates a long random string, such as 7f3a9c1e-…, called an idempotency key, and sends it with the request. When it has to retry, the app sends that same key, not a new one.
The bank keeps a ledger: which keys it has seen, and what the result was last time.
- A new key: process it normally, take the money, then record the key and the result in the ledger.
- A key already in the ledger: do not do it again, just return exactly the recorded result.
As in the diagram at the top of the article: the first “done” is lost, the app resends with the same key 7f3a…, the bank looks it up, finds it, and replies “done” without taking another cent. From then on you can retry as often as you like. Sending money is not idempotent in itself, but “sending money with a key” is.
In the same simulation, when the app retries with a key: 9,998 out of 10,000 people are charged exactly once, and nobody is charged twice. The app still shows an error 32 times (all three attempts ran into trouble), but that is no longer frightening: just resend later, still with the old key, and you get a definite answer with no risk of an extra charge.
One important detail: a key belongs to one tap, not to an amount or a recipient. If you deliberately send your friend 20 dollars twice in one day, that is two taps, two keys and two valid transactions. The system does not guess your intentions; it only recognises the same request being sent again.
Who uses idempotency keys?
- Stripe. Every
POSTrequest to the Stripe API accepts a key in theIdempotency-Keyheader. Stripe recommends version 4 UUIDs (a random string long enough to almost never collide), keys up to 255 characters, and not using personal information such as an email address as a key. Stripe saves the status code and body of the first response; a retry with the same key gets that exact response back, even if it was an error. Keys may be removed once they are at least 24 hours old. If a request is resent with the same key but different parameters, Stripe returns an error to prevent accidental misuse[2]. - An IETF draft standard, from the body that writes internet standards, describes an
Idempotency-Keyheader so that other APIs can work the same way[4]. The draft recommends UUIDs as keys; a request resent while the original is still in progress gets a conflict error (status 409); reusing a key for a different payload gets status 422. The draft has since expired without becoming an official standard, but the practice is already widespread. - Payment, ordering and messaging systems in general. The name varies (“request reference”, “request ID”, “client transaction ID”), but the idea is the same: the sender numbers its own requests so the receiver can filter out duplicates.
Design questions
The idea is simple, but there are a few places where it is easy to slip.
- Recording the key and taking the money must go together. If the bank takes the money and only then records the key, and crashes in between, the retry will not find the key and will charge again. The safe way is to record the key and take the money in the same database transaction: either both happen or neither does.
- Two requests arriving at once. The app retries while the first attempt is still being processed. If both look up the ledger at the same time and both find no key, both take the money. You need a lock per idempotency key (only one request per key is processed at a time), and a later request is told “still processing, try again later”, exactly the 409 status above.
- How long to keep the ledger? The ledger cannot grow forever. Stripe chose at least 24 hours. The period must be longer than the time during which the app might still retry, including when the user closes the app and reopens it the next day.
- A key only means something for one customer. Two customers who happen to send the same key must not get mixed up, so the ledger is usually looked up by the pair (account, key).
- Retry politely. If a million phones all retry the instant a server stumbles, they will knock it over again. Stripe recommends waiting longer after each failure (in proportion to , where is the number of failures so far) and adding a little random time so that clients do not all retry at once[1]. It is also why large systems put a rate limiter at the door.
If the system spreads its data over many machines, the key ledger must be split the same way, so that every retry of a key finds its way to one single place, for example with consistent hashing. And to be sure a request really comes from your app rather than an attacker replaying it, you need another layer: digital signatures and tokens.
Simulate it yourself: 10,000 transfers over a bad network
The Python below simulates a bank and 10,000 taps of the transfer button. On each attempt, the request has a 5% chance of being lost on the way; if it arrives, the bank takes the money, and then the reply has a 10% chance of being lost on the way back. It compares three approaches: no retry, retry up to 3 times without a key, and retry with an idempotency key, then counts how many times each transfer was charged. It also draws the diagram at the top of the article. You only need matplotlib.
import randomimport uuid
import matplotlib.pyplot as plt
plt.rcParams.update({"figure.facecolor": "#16181c", "axes.facecolor": "#16181c", "text.color": "#d4d7dc", "axes.edgecolor": "#2a2e35", "xtick.color": "#878d97", "ytick.color": "#878d97", "font.size": 12})random.seed(2026)
LOST_REQUEST = 0.05 # 5% of requests are lost on the way; the server never receives themLOST_REPLY = 0.10 # 10% of the time the server has moved the money but the reply is lost on the way backMAX_TRIES = 3 # the app tries at most 3 times when it waits too long
class Bank: def __init__(self, use_key): self.use_key = use_key self.done = {} # idempotency key → result returned the first time self.debits = {} # the user's payment ID → how many times money was taken
def transfer(self, payment_id, key): if self.use_key and key in self.done: return self.done[key] # already done: return the same old result, do not take money again self.debits[payment_id] = self.debits.get(payment_id, 0) + 1 result = "ok" if self.use_key: self.done[key] = result return result
def run(retry, use_key, n=10_000): bank = Bank(use_key) unsure = 0 # the user sees "error" but the money may already be gone for pid in range(n): key = str(uuid.UUID(int=random.getrandbits(128))) # one key for ONE tap of the transfer button for attempt in range(MAX_TRIES if retry else 1): if random.random() < LOST_REQUEST: continue # request lost, wait for the timeout bank.transfer(pid, key) if random.random() < LOST_REPLY: continue # money moved, but the app does not know break else: unsure += 1 counts = [bank.debits.get(pid, 0) for pid in range(n)] return {"not charged": counts.count(0), "charged once": counts.count(1), "charged 2+ times": sum(c >= 2 for c in counts), "app shows error": unsure}
policies = {"no retry": run(False, False), "retry,\nno key": run(True, False), "retry\n+ idempotency key": run(True, True)}for name, r in policies.items(): print(f"{name.replace(chr(10), ' '):<26}", " ".join(f"{k}: {v:>5}" for k, v in r.items()))
# Figure 1: the outcome of 10,000 transfer taps, for three approaches.fig, ax = plt.subplots(figsize=(10, 5))names = list(policies)parts = [("charged once", "#8fa9c9"), ("charged 2+ times", "#c98f8f"), ("not charged", "#4a4e57")]bottom = [0] * len(names)for label, color in parts: vals = [policies[n][label] for n in names] ax.bar(names, vals, bottom=bottom, color=color, label=label, width=0.55) for i, v in enumerate(vals): if v > 250: ax.text(i, bottom[i] + v / 2, f"{v:,}", ha="center", va="center", color="#16181c", fontsize=11) bottom = [b + v for b, v in zip(bottom, vals)]for i, n in enumerate(names): ax.text(i, 10_150, f"app shows error: {policies[n]['app shows error']:,}", ha="center", color="#a4a9b2", fontsize=10)ax.set_ylim(0, 10_800)ax.set_ylabel("transfer taps (out of 10,000)", color="#a4a9b2")ax.set_title("Flaky network: retrying with a key means nobody is charged twice", color="#d4d7dc", fontsize=12)ax.legend(frameon=False, labelcolor="#a4a9b2", fontsize=10, ncol=3, loc="upper center", bbox_to_anchor=(0.5, -0.16))ax.grid(axis="y", color="#22262c")ax.set_axisbelow(True)fig.savefig("ba-cach-thu-lai-en.png", dpi=150, bbox_inches="tight")
# Figure 2 (cover image): the reply is lost, the app resends with the SAME key, the bank does not charge twice.fig, ax = plt.subplots(figsize=(10, 5.6))ax.set_xlim(-0.5, 10.5)ax.set_ylim(-0.3, 10.6)ax.axis("off")for x, name in [(1.5, "phone"), (8.5, "bank")]: ax.text(x, 10.1, name, ha="center", color="#d4d7dc", fontsize=13) ax.plot([x, x], [0, 9.6], color="#2a2e35", lw=2)steps = [ # (start y, direction: 1 = out, -1 = back, text, colour, lost on the way or not) (8.8, 1, "send $20 · key 7f3a…", "#8fa9c9", False), (6.9, -1, "done", "#4a4e57", True), (4.4, 1, "waited too long, resend · key 7f3a…", "#8fa9c9", False), (2.5, -1, "done (saved result)", "#8fa9c9", False),]for y, d, label, color, lost in steps: x0, x1 = (1.5, 8.5) if d == 1 else (8.5, 1.5) if lost: ax.annotate("", xy=(5.0, y - 0.6), xytext=(x0, y), arrowprops=dict(arrowstyle="-", color=color, lw=2, ls="--")) ax.text(5.0, y - 0.6, "✕", ha="center", va="center", color="#c98f8f", fontsize=22) ax.text(5.0, y - 1.25, "signal lost", ha="center", color="#c98f8f", fontsize=11) else: ax.annotate("", xy=(x1, y - 1.2), xytext=(x0, y), arrowprops=dict(arrowstyle="-|>", color=color, lw=2)) xm = (x0 + 5.0) / 2 if lost else (x0 + x1) / 2 # middle of the segment actually drawn ym = y - (0.3 if lost else 0.6) ax.text(xm, ym + 0.35, label, ha="center", color="#d4d7dc", fontsize=11, rotation=-d * 9.7, rotation_mode="anchor")ax.text(8.75, 7.55, "take money,\nremember key", ha="left", va="center", color="#8fa9c9", fontsize=10.5)ax.text(8.75, 3.15, "key seen before:\nno new charge", ha="left", va="center", color="#8fa9c9", fontsize=10.5)ax.text(1.25, 4.9, "has the money\ngone or not?", ha="right", va="center", color="#a4a9b2", fontsize=10.5)fig.savefig("gui-lai-cung-khoa-en.png", dpi=150, bbox_inches="tight")no retry not charged: 523 charged once: 9477 charged 2+ times: 0 app shows error: 1475retry, no key not charged: 1 charged once: 8995 charged 2+ times: 1004 app shows error: 29retry + idempotency key not charged: 2 charged once: 9998 charged 2+ times: 0 app shows error: 32
The numbers match a calculation by hand. A single attempt fully succeeds with probability , so without retries about 14.5% of taps end in an error (simulation: 14.75%). Most of those are lost replies, meaning the money has gone: those are the 952 people who “saw an error but still lost the money”. With retries and no key, every lost reply produces an extra charge, so the share of people charged twice is roughly the reply loss rate, 10%.
You can raise LOST_REPLY to 0.3 to simulate a very bad network, or raise MAX_TRIES to 5, and watch the middle column turn redder while the right column still has no red at all.
Asking again is fine; doing it again is the problem
Networks will always be flaky and servers will always crash now and then. Idempotency does not prevent that. It does something more modest: it turns the frightening question “is it safe to do this again?” into the harmless question “is this done yet?”. Thanks to a random string generated the moment you tap the button, the bank can answer that question as many times as you like without taking another cent. Next time a transfer app shows an error, if it is a well-built app, you can tap again with peace of mind.
Free geometry illustrations for students and teachers: EyeViz.
Tài liệu tham khảo
- [1]Brandur Leach. Designing robust and predictable APIs with idempotency. Stripe Blog, 2017.
- [2]Stripe. Idempotent requests (API reference). Stripe Docs, 2026.
- [3]Roy Fielding, Mark Nottingham and Julian Reschke (editors). RFC 9110: HTTP Semantics, section 9.2.2 Idempotent Methods. IETF, 2022.
- [4]Jayadeba Jena and Sanjay Dalal. The Idempotency-Key HTTP Header Field (draft-ietf-httpapi-idempotency-key-header-07). IETF, Internet-Draft, 2025.


