A user taps "Place order" on a train, the request hangs for ten seconds, the response never arrives, and your Dio retry interceptor quietly fires the same POST again. The first request had already committed. Now there are two orders. Idempotency keys in Flutter apps are the standard fix for this, but only if the key's lifecycle is right on both the client and the server, and most implementations get one half wrong.
This post covers the three ways duplicate writes happen in a Flutter client, a server-side table design that makes retries safe, and the trade-offs in its TTL and concurrency handling.
Where duplicate POSTs actually come from
A timeout tells you the client stopped waiting. It does not tell you the server stopped working. That gap produces duplicates through three common paths:
- Dio retry interceptors. A
RetryInterceptorthat retries onconnectionTimeout,receiveTimeoutor a 5xx is correct for GETs. On a POST it assumes the first attempt failed, when often only the response was lost. - Backgrounded apps. iOS and Android can suspend the process mid-request. On resume, the socket is dead, Dio raises an error, and either your retry logic or the user's second tap re-sends the write.
- Double taps. A button that disables itself on the next frame still lets two
onPressedcallbacks through if the handler is async and sets state after anawait.
Disabling buttons and tuning retry policy reduces the rate but cannot remove the bug. The only complete fix is making the write itself safe to repeat.
The server side: an idempotency key table
The client sends an Idempotency-Key header (a UUID v4 works). The server stores the outcome of the first request under that key and replays it for any repeat. A minimal Postgres shape:
CREATE TABLE idempotency_keys (
key text NOT NULL,
user_id uuid NOT NULL,
request_hash text 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)
);
Three design choices matter here:
- Scope the key to the user. A global unique key lets one client's collision, or a malicious guess, replay another user's response. The composite primary key closes that off.
- Store a hash of the request. If the same key arrives with a different body, that is a client bug. Return 422 rather than silently replaying an unrelated response.
- Store the response, not just the key. A retry must receive the original status and body, otherwise the client sees a confusing 409 for a write that actually succeeded.
The race condition
The nasty case is two identical requests arriving concurrently, which is exactly what a double tap or an aggressive retry produces. A check-then-insert pattern (SELECT, then INSERT if missing) fails here because both requests see nothing.
Let the primary key arbitrate instead. Run INSERT ... ON CONFLICT DO NOTHING with status in_progress, in the same transaction as the business write where you can. Whoever inserts the row wins and does the work. The loser sees zero rows affected and has two options: return 409 with a Retry-After header, or block briefly until the row flips to completed. Returning 409 is simpler and avoids holding connections. Waiting gives a nicer client experience but needs a timeout and careful handling of crashed owners.
Which brings up the failure mode people skip: the winner crashes after inserting but before completing. You now have a permanent in_progress row. The simplest safeguard is to treat an in_progress row older than a short threshold (say, longer than your request timeout) as abandoned and let a new request take it over. If your business write and the key insert share one transaction, this problem mostly disappears because a crash rolls both back. That is the strongest argument for keeping the key table in the same database as the data it protects.
TTL trade-offs
Keys cannot live forever, so you need a TTL, and the right value comes from your clients' worst-case retry window rather than from a convention. A 24-hour TTL is common and covers a phone that sat offline overnight with a queued write. Shorter TTLs keep the table small but risk a duplicate when a very late retry arrives after expiry. Longer TTLs cost storage, mostly in the stored response bodies.
Two practical notes. First, expire with a scheduled delete on created_at and an index on it, not on every request. Second, if you store large responses, consider storing only the created resource ID and re-reading it on replay. That keeps rows small and returns current state, at the cost of the replay not being byte-identical.
The client side: key lifecycle in Flutter
Most client bugs come from generating the key at the wrong moment. The rule: one key per user intent, not per HTTP attempt.
- Generate the key when the user commits to the action, such as when the checkout screen's "Place order" handler first runs, and hold it in that screen's state or controller.
- Do not generate it inside the Dio interceptor's
onRequest. That runs again on every retry and defeats the purpose, because each attempt gets a fresh key. - Reuse the same key for every retry of that intent, including retries after the app resumes from the background.
- Discard the key only on a definitive result: a 2xx, or a 4xx that means the request was rejected. On a 5xx or a network error, keep it.
- If the intent can survive process death (an order submitted, app killed, relaunched), persist the key alongside the pending action locally so the relaunch resends it rather than minting a new one.
In Dio, pass the key through options.headers or options.extra from the call site, and have the retry interceptor clone the original request options, which preserves the header. Restrict automatic retries of non-GET methods to requests that carry an idempotency key. That one condition is the gate that makes aggressive retry safe.
For double taps, guard the handler with an in-flight flag set synchronously before the first await. With a stable key, even a guard failure becomes harmless, since the server collapses both calls into one write.
What to test
Two tests catch most regressions. Fire two identical requests concurrently and assert exactly one row is created and both callers get the same result. Then send the same key with a different body and assert a 422. Add a chaos check on the client: kill the connection after the server commits but before the response lands, and confirm the retry returns the original outcome.
At orithLabs, this pattern is part of how we approach backend development and mobile app development together, since the bug lives in the seam between a Flutter client and the API behind it. It is also a frequent find in code audits of existing apps. If you are chasing duplicate records you cannot explain, a short look at your retry policy and write endpoints is often where the answer is.