A customer taps "Place order" in a basement with one bar of signal. The spinner hangs, the request times out, and the app drops the order into the retry queue. The server, meanwhile, received the first request and committed it. The response just never made it back. When the phone reconnects, the queue replays the POST. Two orders, one tap. This is the failure mode of a naive Flutter offline sync queue, and we shipped exactly that design before we fixed it.
This post is the teardown: what the queue did wrong, the client-generated key scheme we moved to, the server-side dedupe table, and the TTL and race-condition decisions that were genuinely debatable.
What the Flutter offline sync queue actually did wrong
The original design was reasonable on paper. Every mutating call went through a local queue persisted in SQLite. A worker drained it on connectivity change, retried with exponential backoff, and deleted a row only on a 2xx response. That last rule is the bug. "Delete on 2xx" is at-least-once delivery, and at-least-once plus a non-idempotent endpoint equals duplicates.
The failure windows were more varied than the basement scenario:
- Response lost after commit. The server wrote the row, the TCP connection died before the response arrived. The client sees a timeout and cannot tell this apart from "never arrived."
- App killed mid-flight. The OS reclaims the process while the request is in the air. On next launch the row is still marked pending, so it replays.
- Two drain triggers. A connectivity event and an app-resume event both started the worker. Without a lock, two isolates picked up the same row.
- Load balancer retries. Some proxies retry upstream on a reset, which duplicates requests the client only sent once.
Backoff, jitter, and "smarter" connectivity detection don't fix any of these. Connectivity checks on mobile report link state, not whether your backend is reachable. The only real fix is making the replay safe.
The key scheme: generate once, persist with the intent
The rule we settled on: the idempotency key is created at the moment the user expresses intent, and it is stored in the same local transaction as the queued payload. Never generate it at send time. If the key is minted inside the retry loop, every retry gets a fresh key and you have built a very elaborate duplicate generator.
The shape of the client side, simplified:
- User taps submit. In one SQLite transaction, insert a queue row containing the payload, a UUIDv4 key, and a status of
pending. - The worker claims the row by flipping status to
in_flightwith a compare-and-set update (WHERE status = 'pending'). If zero rows change, another worker has it and this one moves on. - The request goes out with an
Idempotency-Keyheader carrying that stored key. - On 2xx, or on a 409/422 that says the key was already processed with the same payload, mark the row done. On network error or 5xx, reset to
pendingwith the same key. - On startup, any row stuck in
in_flightlonger than the request timeout goes back topending. Same key, so this is safe.
We use random UUIDs rather than a hash of the payload. A payload hash would wrongly collapse two legitimate identical orders placed minutes apart. The key identifies the user's intent, not the content.
Keep the key scoped to the user
On the server, the uniqueness constraint is on the pair of user ID and key, not the key alone. A bare global key lets one client's key collide with, or deliberately probe, another's. It is a small application security point, but it costs nothing to get right.
The server side: a dedupe table and the race you have to close
The backend gets a dedupe table with roughly these columns: user_id, key, request_hash, status (processing or complete), response_code, response_body, created_at, with a unique index on (user_id, key).
The naive implementation is "SELECT, and if absent, process and INSERT." That has a textbook race: two concurrent replays both see no row, both process, both insert, and one insert fails after the order is already written. The fix is to let the database arbitrate:
- Open a transaction and
INSERTthe dedupe row with statusprocessingfirst. The unique index means exactly one concurrent request wins. - The winner performs the order write in the same transaction, stores the response on the dedupe row, and commits. Because the dedupe row and the order commit atomically, you cannot end up with an order and no record of it, or the reverse.
- The loser hits a unique violation. It reads the existing row. If status is
complete, return the stored response verbatim. If it is stillprocessing, return 409 with aRetry-Afterheader and let the client's backoff handle it. - Compare
request_hashon replay. Same key with a different body is a client bug, and we reject it with 422 rather than silently returning the first result.
Doing the insert in the same transaction as the business write matters. If the dedupe write lives in a separate transaction or a separate store such as a cache, a crash between the two reintroduces the window you were closing. When the business data is in Postgres, keep the dedupe table in Postgres too.
The TTL trade-off
Dedupe rows can't live forever, but how long they live is a product decision disguised as a cleanup job. Too short, and a device that sat offline over a long weekend replays a key the server has already forgotten, creating the duplicate you built all this to prevent. Too long, and the table grows without bound and the index gets heavy.
Our reasoning: the TTL must exceed the longest period a queued item can plausibly sit on a device. So we capped the client side too. Queue items older than a fixed age are surfaced to the user as "this order may be stale, review it" instead of being auto-replayed. The server TTL is then that cap plus a safety margin, and a nightly job deletes expired rows in batches. The two limits are coupled, and changing one without the other quietly breaks the guarantee.
One more edge: don't store full response bodies forever. Store the status code and a reference to the created resource, and rebuild the response on replay. It keeps rows small and avoids retaining data you would otherwise have deleted.
What we would do on day one
None of this is exotic. It is a few hundred lines, and it is far cheaper to design in than to retrofit onto a live REST API with real orders in it. Our checklist for any mobile client that writes data:
- Treat every mutating endpoint as retryable, because the network will make it so.
- Mint the key at intent time, persist it atomically with the payload.
- Claim queue rows with compare-and-set, not hope.
- Let a unique index, not application code, decide the winner.
- Couple the client staleness cap to the server TTL.
orithLabs builds Flutter apps with native Swift and Kotlin where it matters, along with the backends behind them, and bugs like this one are the reason we care about the seams between the two. If you have a sync queue or a retry path you are uneasy about, we are happy to look at it as part of a code audit. You will be talking to the engineers who write the code.