A user taps "Place order" in a lift, the signal drops, and the request times out on the client. The server, meanwhile, already committed the write. The retry fires, and now there are two rows. Flutter idempotency keys are the fix for exactly this, but we didn't reach for them first. We found the bug because a backend unique constraint happened to trip on an unrelated field. If the schema had been slightly different, we would have shipped duplicates for months.

How optimistic UI and retries create duplicate writes

Each of these decisions was reasonable on its own:

  • The UI is optimistic. On submit, the repository inserts a local item into state immediately and fires the request in the background.
  • The HTTP layer retries on timeout and on connection errors, with exponential backoff, because mobile networks are flaky.
  • The backend treats every POST as a new write.

The failure is a timeout where the server did the work but the response never arrived. From the client's point of view, a timeout is ambiguous. It can mean "the server never saw this" or "the server finished and I never heard back." Retrying is only safe in the first case, and the client cannot tell the two apart.

Optimistic UI makes it worse in a way people tend to miss. The user already sees the item on screen, so they don't re-tap. The duplicate comes purely from the automatic retry, which means no user reports it and no one thinks to look for it. The only symptom is a count that is occasionally off by one.

The idempotency key contract between Flutter and the backend

The fix is a contract, and both sides have to honor it. The client generates a unique key per user intent, not per HTTP attempt. The server stores the key with the result of the first successful execution, and replays that stored result for any later request carrying the same key.

On the Flutter side, the key is created at the moment the intent is created, which is the same place the optimistic item is created. In our repository layer it looks roughly like this:

Future<Order> placeOrder(OrderDraft draft) async {
  final key = const Uuid().v4(); // one key per intent
  final pending = Order.pending(draft, clientKey: key);
  _state.add(pending); // optimistic insert

  try {
    final saved = await _api.post(
      '/orders',
      body: draft.toJson(),
      headers: {'Idempotency-Key': key},
      retry: RetryPolicy.onTimeoutAndNetworkError,
    );
    _state.reconcile(key, saved);
    return saved;
  } catch (e) {
    _state.markFailed(key);
    rethrow;
  }
}

Three details matter here. First, the key is generated before the first attempt and reused on every retry. A key generated inside the retry closure defeats the whole mechanism. Second, the key is stored on the optimistic item, so reconciliation matches the server response to the right local entry instead of appending a second one. Third, if the app is killed mid-flight, the pending intent and its key should be persisted. Otherwise a restart creates a fresh key and a fresh duplicate.

The backend half is a table keyed on (user, idempotency key), holding a request fingerprint, a status, and the stored response. The handler does an atomic insert-or-fetch of that row before doing any work.

Backend failure modes to design for

  • Concurrent duplicates. The retry can arrive while the original is still executing. The key row needs an "in progress" state, backed by a unique constraint, so the second request waits or gets a 409 rather than racing the first.
  • Key reuse with a different payload. Hash the request body and store it with the key. If the same key shows up with a different body, reject it. That is a client bug, and silently replaying the old response hides it.
  • Atomicity. Write the business row and the key record in the same transaction. If they commit separately, you recreate the original problem at a smaller scale.
  • Key expiry. Keys can expire eventually, but the window has to outlast your longest realistic client retry horizon, including offline queues.

Why the backend only caught it by accident

The original system had no key. What it had was a unique constraint on a business field that happened to be part of the payload. Most duplicates bounced off it, and the client saw an error on the retry. The optimistic item was already on screen, the original write had succeeded, and the error handler rolled the item back. The user then saw a flicker of an item disappearing even though the data was saved correctly.

That was the accident. The constraint masked the duplicate-write bug and created a different one, a UI that lied about server state. Any endpoint without such a field would have had no guard at all. This is the kind of thing a code audit surfaces quickly, because you read the retry policy and the schema side by side, which the mobile team and the backend team rarely do.

The lesson is that unique constraints are not idempotency. A constraint tells you a write was rejected. It doesn't tell the client that its earlier attempt succeeded, so the client can't reconcile correctly. An idempotency key lets the server answer "yes, this already happened, here is the result," and the client's optimistic state and the server's state converge on the same object.

A checklist before you ship retries

  1. Is every retried request either naturally idempotent (GET, PUT) or carrying a key?
  2. Is the key generated once per intent and persisted with any queued work?
  3. Does the optimistic item carry the key so reconciliation is a lookup, not an append?
  4. Does the server reject key reuse with a mismatched payload?
  5. Do the business write and key record share a transaction?

At orithLabs, we build the Flutter client and the backend together, which is why this contract gets designed as one piece instead of discovered across a team boundary. If you have a mobile app with retry logic you aren't fully sure about, or a backend that has been quietly absorbing duplicates, we're happy to look at it and tell you plainly what we find.