The bug report said "some users see their entry twice." The logs said every request had succeeded exactly once from the client's point of view. Both were true, and that gap is where most Flutter offline queue bugs live. We found this one during a code audit of an existing codebase, and it's worth walking through because the client code looked reasonable and so did the backend. The bug only existed in the space between them.

The shape of the bug

The client did what most Flutter apps do. A user action writes to a local store (sqflite or Drift), appends a row to a pending-operations table, and a sync worker drains that table whenever connectivity_plus reports a network. The drain loop was roughly:

for (final op in await queue.pending()) {
  final res = await api.post(op.path, op.body);
  if (res.ok) await queue.markDone(op.id);
}

The backend was a plain REST API: POST /entries inserted a row and returned 201 with the new ID. No uniqueness constraint other than the primary key, which the server generated.

Now consider the failure mode. The request reaches the server. The server commits the insert. The response is lost: the user walks into a lift, the radio drops, or a mobile carrier proxy times out. The client sees a SocketException or a timeout, treats it as failure, and leaves the op in the queue. On reconnect, it sends the same op again. The server, which has no way to know this is a replay, inserts a second row.

This is the core of it: a timeout is not a failure, it's an unknown. Retry logic that treats the two the same is only safe if the endpoint is idempotent. This one wasn't.

Why it got worse than one duplicate

Two amplifiers made the audit finding more than theoretical:

  • Reconnect events fire in bursts. Connectivity listeners on flaky networks flip several times in seconds. Each flip triggered a drain, and nothing prevented two drains from running concurrently over the same queue. Two workers, same pending rows, two POSTs each.
  • Retries were immediate and unbounded. No backoff, no jitter. When the server was slow (and slow servers are exactly when responses get lost), every client hammered it harder, which produced more timeouts, which produced more retries. A small retry storm, self-inflicted.

The fix: client-generated idempotency keys

The principle is simple: the identity of an operation must be decided once, on the client, at the moment the user acts, and must travel with every retry of that operation. Not generated per request. Not generated by the server.

On the client, the pending-operations row gets a UUID (v4 is fine; v7 is nicer because it sorts by time) at enqueue time:

CREATE TABLE pending_ops (
  id            TEXT PRIMARY KEY,   -- the idempotency key
  path          TEXT NOT NULL,
  body          TEXT NOT NULL,
  attempts      INTEGER NOT NULL DEFAULT 0,
  next_try_at   INTEGER NOT NULL,
  created_at    INTEGER NOT NULL
);

The key is sent as an Idempotency-Key header on every attempt. Because it's persisted in the same transaction as the local write, an app kill between "user tapped" and "request sent" can't lose or regenerate it.

On the server, the dedupe table looks like this (Postgres shown, but the idea ports to any database with unique constraints):

CREATE TABLE idempotency_keys (
  user_id        UUID        NOT NULL,
  key            TEXT        NOT NULL,
  request_hash   TEXT        NOT NULL,
  status_code    INT,
  response_body  JSONB,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, key)
);

Details that matter here:

  • Scope the key by user. A global key space lets one client's collision, or a malicious client's guess, replay into someone else's data.
  • Store a hash of the request. If the same key arrives with a different body, that's a client bug, and you want a 422, not a silently returned stale response.
  • Insert the key in the same transaction as the business write. The handler does INSERT ... ON CONFLICT DO NOTHING on the key first. If zero rows were inserted, the operation already ran (or is running): return the stored response. If one row was inserted, proceed, write the entry, then fill in status_code and response_body before commit. A crash rolls back both, so a retry is a clean first attempt.
  • Handle the in-flight case. Two concurrent requests with the same key: the second blocks on the primary key conflict until the first commits, then reads the stored response. The database does the locking for you. Don't build a mutex in application code.
  • Expire old keys. A retention window of a few days, enforced by a scheduled delete on created_at, covers realistic offline periods without growing the table forever. Pick the window based on how long your app can plausibly stay offline, and document it.

Fixing the client loop too

The server fix makes duplicates impossible, but the client should still stop misbehaving. Three changes, all small:

  1. A single drain at a time. A guard flag or a serialised queue so reconnect bursts coalesce into one drain, not five.
  2. Exponential backoff with jitter, stored in next_try_at so it survives restarts. Cap it, and add jitter so a thousand clients that reconnect after an outage don't synchronise.
  3. Classify errors. Timeouts and 5xx: retry with the same key. 4xx other than 408 and 429: the request is wrong, so retrying forever is pointless. Move it to a dead-letter state and surface it. Without this, one malformed op blocks the head of the queue permanently.

What we'd check in your codebase

If you have an offline-capable mobile app, this is a ten-minute audit. Find every endpoint your sync queue can call. For each one, ask: if this request is delivered twice, what happens? If the answer is "two rows" or "two charges" or "two notifications," you have this bug, and it will show up the first time a real user has a bad connection. PUT and DELETE are usually naturally idempotent; POST almost never is. Also check whether your drain loop can run concurrently with itself, because that alone is enough to reproduce it on a good network.

We've seen this pattern during audits and fixed it on the apps we ship, and it's the kind of problem that's cheap to design in and expensive to clean up once duplicate data is in production. At orithLabs, we build the Flutter client and the backend together for exactly this reason: the contract between them is where the bugs hide. If you're staring at a similar bug, or want a second pair of eyes on a sync layer, we're happy to look.