A user taps "Place order" in an elevator. The request reaches your server, the order commits, and the response dies somewhere between the cell tower and the phone. Your Flutter client times out, retries, and the user ends up with two orders. You added idempotency keys last quarter, so this shouldn't be possible. It still happens, and it usually happens because idempotency keys alone are only half of the contract.
Idempotency keys are a two-party protocol. The server can deduplicate only the requests that carry a key it recognises as the same operation. Most duplicate-write bugs we see in audits are client-side or schema-side faults that the server's key check cannot catch. This post covers the failure modes, in the order they tend to bite.
Where Flutter idempotency keys must be generated
The most common mistake is generating the key inside the HTTP layer. A Dio interceptor that stamps Idempotency-Key: uuid.v4() on every outgoing request looks tidy, and it is wrong. When the retry interceptor re-sends the request, the stamping interceptor may run again. Depending on interceptor order, every retry gets a fresh key, and the server correctly treats each one as a new operation.
The key identifies a user intent, not an HTTP attempt. It must be created at the moment of intent, which is the tap handler or the use-case object, and then passed down as data. In Flutter terms:
- Create the key when the command object is constructed (
PlaceOrderCommand(key: uuid.v4(), items: ...)), not when the request is built. - Treat the command as immutable. A retry re-sends the same command with the same key and the same body.
- Make the retry interceptor unable to mutate the key header. Read it from the command, never regenerate it.
There is a related trap: double taps. If the button handler builds a new command per tap, two taps produce two keys. Disable the control on first tap, but also keep the key in the view-model state so a rebuilt widget doesn't mint a second one.
Persisting keys across app kills
In-memory keys survive flaky networks but not process death. On Android, the OS kills backgrounded apps constantly. A user submits, switches to a messaging app while the request hangs, and returns to a cold start. The in-flight command is gone, the screen is back at the form, and the user submits again with a new key. The first request may well have committed.
The fix is to persist the command before sending it. We use a small local outbox table (SQLite via drift, though anything transactional works) with roughly this shape:
key(primary key),endpoint,body_hash,payloadstate:pending,in_flight,succeeded,failed_permanentattempts,next_retry_at
The write to the outbox happens in the same step as the user's intent, before any network call. On cold start, the app scans for pending and in_flight rows and resumes them with their original keys. An in_flight row after a restart means "outcome unknown", and replaying with the same key is exactly what resolves that ambiguity safely.
Two details matter. First, only mark a row failed_permanent on a definitive 4xx (other than 408 and 429), never on a timeout. Second, expire rows deliberately. Server-side key retention is finite, so a replay after the window closes becomes a fresh write. Pick a client retry horizon that is shorter than the server's retention.
The backend schema that makes replays safe
The common server implementation is "check the cache for the key, if absent, do the work, then store the response." That has a race: two concurrent attempts both see no key, and both do the work. A retry that arrives while the original is still executing is not an edge case on a flaky network. It is the default case, because the client timed out while the server was still working.
The key must be claimed atomically, before the work, using a database constraint instead of application logic:
- A table such as
idempotency_records(user_id, key, request_hash, status, response_code, response_body, created_at)with a unique constraint on(user_id, key). Scope by user so one client's key can never collide with or read another's. - Insert the row as
in_progressfirst. If the insert hits the unique violation, you know another attempt owns the key. - Do the business write and flip the record to
complete, storing the response, in the same database transaction. If they commit separately, a crash between them leaves a committed order with no record, and the replay duplicates it.
What to do on a conflict
Three cases need distinct behaviour. If the record is complete and the request_hash matches, return the stored response verbatim, with the same status code and body. If the record is in_progress, return 409 with a Retry-After header so the client backs off instead of hammering. If the hash does not match, the client reused a key with a different body. That is a client bug, and it should return 422 rather than silently serving the old result.
Be careful about side effects outside the transaction. A payment-provider call or an email send inside your handler can fire twice if the process dies after the call but before commit. Pass the same idempotency key downstream where the provider supports it, or push the side effect through a transactional outbox so it is emitted only after commit.
A checklist for your own code review
If you are reviewing a mobile client and API pair, these are the questions that find the bugs fastest:
- Is the key created at the point of user intent, and is it identical across every retry of that intent?
- Is the pending command durably stored before the first network attempt?
- Does the server claim the key with a unique constraint before doing any work?
- Is the business write committed atomically with the stored response?
- Is the request body hashed and compared on replay?
- Does the client's retry horizon sit inside the server's key retention window?
If any answer is "not sure", that is where the duplicates are coming from. At orithLabs, we build the Flutter client and the backend together, so the key lifecycle is designed once across both sides, and we run code audits on existing mobile and API codebases where the two halves were built separately. If you have a retry bug you can't quite pin down, we're happy to look at it with you.