A user taps "Place order" on a train, the request leaves the phone, the tunnel swallows the response, and your Flutter HTTP client times out after 10 seconds. The retry interceptor fires. The server, meanwhile, had already committed the first request. Now there are two orders. Nothing crashed, nothing logged an error, and both requests returned 2xx from the server's point of view. This is the bug that idempotency keys exist to prevent, and if your mobile app retries anything, you almost certainly have it somewhere.

How Flutter retry logic creates the duplicate

The usual setup is a Dio interceptor (or an http client wrapper) that retries on connectionTimeout, receiveTimeout, and 5xx responses, with exponential backoff. It's reasonable code, and it's usually copied from a blog post. The problem is that a timeout is not a failure. It's an unknown. From the client's side, "the server never got it" and "the server processed it but the response died on the way back" look identical.

For GET, PUT, and DELETE this is fine, since those are idempotent by definition. POST is where it breaks: POST /orders, POST /payments, POST /messages. A naive retry turns "at most once" into "at least once", and the second write has no way to know it's a duplicate.

Mobile makes this worse than server-to-server traffic in three ways:

  • Radio handoffs. Wi-Fi to cellular transitions drop in-flight responses without dropping the request.
  • OS backgrounding. iOS and Android can suspend your app mid-request; on resume, the interceptor sees a timeout and retries.
  • User retries. Impatient users tap again. Disabling the button helps, but it doesn't survive an app restart with a persisted offline queue.

Removing client retries is the wrong fix. Retries are what make the app usable on bad networks. The correct fix is to make the endpoint safe to retry.

The idempotency key contract

The client generates a UUID v4 once per user intent, not per HTTP attempt, and sends it as an Idempotency-Key header. Every retry of that intent reuses the same key. In Flutter this means generating the key when the user taps the button (or when the action is enqueued) and storing it alongside the pending operation, not inside the interceptor's retry callback where a fresh one would be minted each time.

On the server, the contract is: same key and same request means same outcome. The first request does the work; later ones get the stored result instead of re-executing.

Key table design

A minimal Postgres shape:

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

A few decisions here are deliberate:

  • Scope the key by user. A global unique key lets one client's UUID collide with, or probe, another's. (user_id, key) as the primary key also keeps lookups on a single index.
  • Store a request hash. If the same key arrives with a different body, that's a client bug. Return 422 rather than silently replaying an unrelated response.
  • Insert before doing work. The unique constraint is your concurrency control. Do INSERT ... ON CONFLICT DO NOTHING with status in_progress; if zero rows were inserted, someone else owns this key.

The race that checking first doesn't solve

A "SELECT, then INSERT if missing" check fails exactly when you need it: the original request and its retry can be in flight at the same time, since the client gave up waiting while the server was still working. Both SELECTs see nothing, both proceed. Claiming the key with an insert closes that window. A concurrent duplicate that hits an in_progress row should get a 409 with Retry-After, and the client's backoff handles the rest.

Ideally the key insert and the business write share one transaction, so a crash can't leave a completed order with an orphaned in_progress key. If the business logic touches external systems (a payment provider, say), you can't get atomicity from a transaction alone. Pass the key downstream where the provider supports it, and treat stale in_progress rows as a recovery case rather than assuming they never happen.

Expiry window and response replay trade-offs

Two design choices carry most of the real trade-offs.

How long to keep keys

The window must outlast your longest realistic retry horizon. For a client that retries within seconds, minutes would do, but mobile apps with persisted offline queues can replay hours or days later. Many teams settle on 24 hours as a default and extend it for flows with offline queuing. Shorter windows keep the table small; longer windows protect against the slow replay. A scheduled job deleting rows by created_at is enough, and partitioning by day makes the cleanup a cheap DROP instead of a large delete. The failure mode of too short a window is silent: the duplicate simply succeeds as a new request, so pick the window from your client's actual queue behavior, not from a guess.

Replaying the stored response

When a completed key comes back, return the original status code and body, byte-for-byte where practical. This is what makes the retry invisible to the client: its interceptor gets the 201 it was waiting for. The trade-offs:

  • Storage. Large response bodies inflate the table. Store a reference (the created resource ID) and re-render the response from current state if bodies are big, accepting that the replay may differ slightly from the original.
  • Sensitive data. Stored responses can contain tokens or personal data. Treat the table with the same retention and access rules as the underlying data, and keep expiry strict.
  • Failed requests. Cache deterministic failures (validation errors, 4xx) but not transient ones (5xx, timeouts). Otherwise a momentary database blip becomes a permanent failure for that key.

Finally, apply this only where it matters: creation endpoints and anything that moves money or sends something irreversible. Idempotent-by-design operations don't need the table.

Where this fits

This is a small amount of server code that removes a class of bugs that are expensive to diagnose after the fact, because duplicate rows look like legitimate data. It also ties the mobile client and the backend together: the Flutter app has to generate and persist keys correctly, and the server has to honor them. That cross-boundary work is a lot of what orithLabs does, whether it's designing a new backend alongside a Flutter app or auditing an existing one where retries and writes have quietly drifted out of agreement. If you're seeing unexplained duplicates and want a second set of eyes on the code, we're happy to talk it through.