A user taps "Place order" on a train. The request reaches your server, the order gets written and the credits get deducted. Then the response dies in a tunnel. Your Flutter client sees a timeout, and the retry interceptor does what it was built to do and sends the request again. The server, which has no memory of the first call, creates a second order and deducts the credits again. Without idempotency keys, a mobile client on a bad network will turn every lost response into a duplicate side effect. On a mobile app this isn't a rare edge case. It happens whenever someone uses the app on a train, in a lift or in a basement.

We treat this as a day-one design decision on every mobile app development project we take on. Adding it after duplicates show up in production means reconciling ledgers by hand. Here is the shape of what we build.

Why retries make the problem worse

The root issue is that a timeout is ambiguous. When a POST times out, the client cannot tell which of three things happened:

  • the request never reached the server,
  • the server got it and failed partway through,
  • the server completed it and the response was lost.

A retry policy that treats all three as "try again" is only safe if the endpoint is idempotent. GET, PUT and DELETE can be made naturally idempotent. "Create order" and "spend credits" can't, because each call means "do this again". Packages like dio with a retry interceptor make retrying a one-line config change. That's fine for reads and dangerous for writes unless the backend can recognise a repeated attempt.

The most common client bug we find in code audits is subtle. The idempotency key does exist, but it is generated inside the interceptor, so every attempt gets a fresh UUID. That gives you idempotency in name only. The key has to represent the user's intent, not the HTTP attempt:

// Generated once, when the user commits the action
final pending = PendingOrder(
  idempotencyKey: const Uuid().v4(),
  cartSnapshot: cart.freeze(),
);
await pendingStore.save(pending); // survives app kill

// Every attempt, including after relaunch, reuses the same key
await api.post('/orders',
  data: pending.cartSnapshot.toJson(),
  options: Options(headers: {'Idempotency-Key': pending.idempotencyKey}),
);

Persisting the key matters. If the OS kills the app between the first attempt and the retry and the key only lived in memory, the next launch mints a new one and you're back to duplicates.

Designing the idempotency keys table

On the backend, the key is a row with a unique constraint. Our baseline schema in Postgres looks like this:

CREATE TABLE idempotency_keys (
  user_id        uuid        NOT NULL,
  key            text        NOT NULL,
  request_hash   bytea       NOT NULL,
  status         text        NOT NULL,  -- 'in_progress' | 'completed'
  locked_until   timestamptz,
  response_code  int,
  response_body  jsonb,
  created_at     timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, key)
);

Each column is there for a reason:

  • Scoped by user_id. Keys are client-generated, so you can't trust them to be globally unique. Scoping them to the authenticated principal also stops one user from replaying another user's key and reading the cached response.
  • request_hash. This is a hash of the canonicalised request body. If a request arrives with a known key but a different body, for example because the user edited the cart and a buggy client reused the key, we return a 422 instead of silently replaying the old result. Without this check you return a response that doesn't match what the client sent.
  • Stored response. A completed key replays the original status code and body exactly. The client can't tell a replay from the first success, and that's the point.

The request flow is: INSERT ... ON CONFLICT DO NOTHING. If the insert went through, you own the key, so do the work. If it didn't, read the existing row and branch on status and hash.

Race conditions and the in-progress state

The hard cases happen when two attempts overlap in time, which is exactly what a 10-second client timeout against a 12-second server operation produces.

Concurrent duplicates

The primary key settles this, not application code. Two inserts race and exactly one wins. The loser sees in_progress and gets a 409 with a Retry-After header. The Flutter client treats that as "keep waiting", not "failed". We don't use check-then-insert in application code here. A database constraint is the only lock we trust at this layer.

Crashed workers

If the process dies after claiming a key but before completing it, a naive design leaves the key stuck in in_progress forever, and the user can never finish that order. locked_until works as a lease. Once it expires, a later attempt can take the key over. That means the operation itself has to tolerate being resumed or re-run, which brings us to the next point.

Keep the side effect and the key in one transaction

Where the side effect is local, such as writing the order row and the credit ledger entry, it commits in the same database transaction that marks the key completed. Either both happen or neither does. When the side effect is external, like a payment provider, we pass a derived idempotency key downstream so the provider deduplicates too. We never assume our own table protects a call that has already left our system.

Choosing a TTL for idempotency keys

Keys can't live forever, because the table grows with every write. They can't be short either. The rule we use:

The server-side TTL must be longer than the longest window in which the client might still retry.

If your app has an offline queue that resends pending mutations on the next launch, that window could be days. A 24-hour TTL with a 3-day client queue means a user who reopens the app on day two gets a duplicate order. You can fix this from either side:

  • keep keys longer than the queue horizon and run a scheduled cleanup on created_at, or
  • have the client drop queued mutations older than the server TTL and show the user "this order wasn't confirmed, check your order history" rather than resending blindly.

We usually do both, with a margin between the two values. The client constant and the server constant are written down together in the API contract, because they're only correct as a pair. If someone changes one without the other, duplicates come back.

Storage cost is rarely the binding constraint. Response bodies are usually small, and if a response is large you can store a pointer to the created resource instead of the full payload.

Retries, ambiguous timeouts and lost responses are the everyday conditions a mobile client runs in, so the backend has to be designed for them from the start. At orithLabs, we build the Flutter client and the backend behind it together, and that's why we put the idempotency contract in place before the first write endpoint ships. If you're seeing unexplained duplicate records in an existing system, it's a good place to start an audit, and we're happy to compare notes.