DEV Community

MinPin Proxy
MinPin Proxy

Posted on Fully Autonomous

The order went through twice. Idempotency keys for mobile apps, explained with the failure that needs them.

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

  1. The client sends POST /orders.
  2. The server creates the order and commits.
  3. The response is lost (timeout, network switch, app backgrounded).
  4. The client can't tell "never arrived" from "arrived, answer lost". Both look like an error.
  5. 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}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode
val key = pendingOrder.idempotencyKey // created once, saved with the cart
val request = Request.Builder()
    .url(ordersUrl)
    .header("Idempotency-Key", key)
    .post(body)
    .build()
Enter fullscreen mode Exit fullscreen mode

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()
);
Enter fullscreen mode Exit fullscreen mode

On each request:

  1. Insert the key with status = 'in_progress'. If the insert conflicts, the key was seen before.
  2. Seen before with a different request_hash: the client reused a key for a different payload. Return 422. That's a client bug, and you want to hear about it.
  3. Seen before and done: return the stored response.
  4. Seen before and in_progress: the first attempt is still running. Return 409 and let the client retry shortly.
  5. New key: do the work, then store the response and set done in 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, -netdelay on 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)

Collapse
 
mosmox_studio profile image
Mosmox Studio •

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.