A user taps "Pay" on a train. The request reaches your server, the charge succeeds, and the response dies in a tunnel. The app sees a timeout and shows "Something went wrong, try again". The user taps again. Now there are two orders.
Nothing here is a bug in the usual sense. Every component did what it was told. The fix is a small contract between client and server called an idempotency key.
The failure, step by step
- The client sends
POST /orders. - The server creates the order and commits.
- The response is lost (timeout, network switch, app backgrounded).
- The client can't tell "never arrived" from "arrived, answer lost". Both look like an error.
- Retrying is the right call for case one and the wrong call for case two.
Automatic retries make it worse: OkHttp retries some connection failures on its own, and many apps wrap requests in a retry helper. GETs are safe to repeat. A POST that creates something isn't.
The contract
The client generates a unique key per user action and sends it with the request:
POST /orders
Idempotency-Key: 6f1c2a9e-4b7d-4f0e-9a51-2d8c3e7b1f40
Content-Type: application/json
{"cart_id": "c_123", "total": 4200}
The server stores the key with the result. If the same key comes again, it returns the stored result instead of doing the work twice.
Two rules on the client:
- One key per intent, not per request. Create the key when the user taps "Pay", and reuse it for every retry of that tap. A new key on each retry defeats the point.
- Keep it until you get a definite answer. If the app is killed mid-request, persist the pending key with the cart so the next launch can retry with the same key.
struct PendingOrder: Codable {
let idempotencyKey: UUID
let cartID: String
}
func placeOrder(_ pending: PendingOrder) async throws -> Order {
var request = URLRequest(url: ordersURL)
request.httpMethod = "POST"
request.setValue(pending.idempotencyKey.uuidString, forHTTPHeaderField: "Idempotency-Key")
request.httpBody = try JSONEncoder().encode(["cart_id": pending.cartID])
let (data, _) = try await session.data(for: request)
return try JSONDecoder().decode(Order.self, from: data)
}
val key = pendingOrder.idempotencyKey // created once, saved with the cart
val request = Request.Builder()
.url(ordersUrl)
.header("Idempotency-Key", key)
.post(body)
.build()
The server side
A minimal version is one table and one transaction:
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
user_id bigint NOT NULL,
request_hash text NOT NULL,
status text NOT NULL, -- 'in_progress' | 'done'
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
On each request:
- Insert the key with
status = 'in_progress'. If the insert conflicts, the key was seen before. - Seen before with a different
request_hash: the client reused a key for a different payload. Return422. That's a client bug, and you want to hear about it. - Seen before and
done: return the stored response. - Seen before and
in_progress: the first attempt is still running. Return409and let the client retry shortly. - New key: do the work, then store the response and set
donein the same transaction as the order itself.
Scope keys to the user, so one user can't replay another user's key, and expire them after a day or so.
Payment providers already work this way. Stripe, for example, accepts an Idempotency-Key header on POST requests. If your server calls a provider, pass a key derived from yours, so a retry of your endpoint doesn't charge twice downstream either.
Testing it
You can't test this on office Wi-Fi, because the response never gets lost there. Ways to force it:
- Add a debug-only delay on the server after the commit and before the response, longer than the client timeout. Every request now fails on the client and succeeds on the server.
- Turn on a lossy network profile (Network Link Conditioner on macOS and iPhone,
-netdelayon the Android emulator) and tap through checkout. - Kill the app right after tapping "Pay", relaunch, and check that the retry uses the saved key.
Then count rows. One tap should mean one order, no matter how many requests it took.
Also do the cheap part
Disable the button while the request runs. It doesn't fix lost responses, but it stops the most common duplicate: two fast taps.
This article was created with the help of AI.
Top comments (1)
The "one key per intent" rule is the part that gets skipped most often. I've seen the key generated inside the retry helper, which quietly brings the duplicates back. One small addition for the 409 in_progress case: a Retry-After header helps the client avoid hammering the server while the first attempt is still running.