DEV Community

Cover image for Four bugs I hit building an offline-first sync queue in pure Flutter
Stephen Color
Stephen Color

Posted on Edited on AI-assisted

Four bugs I hit building an offline-first sync queue in pure Flutter

Optimistic writes look easy until the app dies mid-request. I built an offline-first sync queue for Flutter with no sync package behind it, and these are the four bugs that cost me the most time — plus how I fixed each one.

The queue is a log of intent, not a list of API calls

Optimistic writes look easy: update the UI, fire the request, show an error if it
fails. The trouble starts when the app dies, the network flaps, or two devices
edit the same row.

I built SyncSpool Kit around one idea: the UI applies a change to local state and
appends an intent to a queue. The queue owns the network from then on. Each
intent carries:

class SyncOperation {
  final String id;              // also the idempotency key
  final SyncOpKind kind;        // create / update / delete
  final String entity;          // 'note'
  final String entityId;        // 'srv_42' or a temporary 'local_1'
  final Map<String, Object?> payload;
  final Map<String, Object?> basePayload; // what the client last saw
  final int baseVersion;
  // status, attempts, nextAttemptAt, lastError, conflict...
}
Enter fullscreen mode Exit fullscreen mode

That base payload and version are what make conflicts detectable and merges
possible. Everything below follows from taking them seriously.

1. Persist before you send, and before you emit

The naive order is: remove the operation from the queue, send it, then notify the
UI. Kill the app between the send and the save and the operation is gone, even
though the server may have applied it.

The queue now writes every transition to the store before the request leaves
and before the matching event is emitted. An operation persisted as sending
comes back as retrying on the next launch and is sent again with the same
idempotency key.

final sending = op.copyWith(status: SyncOpStatus.sending);
_operations[index] = sending;
await _persist();            // <- crash-safe from here
notifyListeners();
final response = await transport.send(sending);
Enter fullscreen mode Exit fullscreen mode

The store is one interface, so the kit never imports shared_preferences or a
file package:

final store = JsonStringSyncStore(
  read: () async => (await prefs).getString('sync.queue'),
  write: (json) async => (await prefs).setString('sync.queue', json),
);
Enter fullscreen mode Exit fullscreen mode

2. A timeout is not a failure

A request that times out may have committed. Retrying without protection writes
twice. The only correct answer is a client-generated idempotency key that the
server stores with the result and replays on a repeat.

The operation id is the key. It never changes, including across restarts. That
single rule turned a class of duplicate-write bugs into a non-issue — as long as
the server participates, which the README states plainly instead of hiding.

3. Coalescing has a hard boundary: the first attempt

Merging consecutive edits saves requests, and it is safe right up until the first
attempt leaves the device.

final index = _operations.lastIndexWhere((op) =>
    op.entity == entity &&
    op.entityId == resolvedId &&
    op.status == SyncOpStatus.pending &&
    op.attempts == 0);
Enter fullscreen mode Exit fullscreen mode

After an attempt, the outcome is unknown. Mutating that operation reuses an
idempotency key with a different payload: the server may reject it, replay the
old result, or apply something the user never wrote. A new edit becomes a new
operation with a new key.

The same reasoning applies to a create: edits merge into a pending create, but
once it is on the wire the next edit is an update that waits for the server id.

4. Temporary IDs hide in payloads

Offline creates need an id before the server has one. local_1 works until the
server answers srv_42 — and other queued operations still reference local_1.

Updating the row is not enough. The queue rewrites the id in entityId and
recursively inside every payload map and list, then persists the mapping so
widgets and routes that still hold the old id keep working:

Object? _rewriteValue(Object? value, String from, String to) {
  if (value is String) return value == from ? to : value;
  if (value is Map) { /* rewrite values, return a new map if changed */ }
  if (value is List) { /* same for items */ }
  return value;
}
Enter fullscreen mode Exit fullscreen mode

The ordering matters: reconcile before the next operation for that entity is
sent, or the server sees a dangling temp id.

Ordering: a failed head blocks its own entity, nothing else

Skipping a failed write and letting later writes through reorders state. If an
update fails and a delete succeeds, the server ends up somewhere the user never
saw.

Each entity is a chain; only the head is eligible. A failed or conflicted head
blocks later writes for that entity, and other entities keep moving. The head
retries with exponential backoff and jitter, dead-letters after a cap, and waits
for a decision when a conflict cannot be resolved automatically.

Conflicts: policy first, sheet second

Four policies cover most products:

Policy What happens
serverWins Drop the local edit, adopt the server record, rebase later writes
clientWins Reapply the local payload on the server version
fieldMerge Apply only the fields this edit changed
askUser Park the operation and open a field-by-field sheet

Automatic policies must change the operation id when they reapply, or a merge
loop can spin forever on the same key. The kit caps merge retries and parks the
operation for a decision if the server keeps moving.

The sheet shows only the fields that differ, plus the fields this edit touched —
everything else is noise at the moment a person has to choose.

Make the state visible

A spinner says nothing. The kit ships:

  • a status chip ("All changes saved", "Offline · 2 waiting", "1 failed");
  • an offline banner that explains changes are safe on the device;
  • a badge per row, with attempts in the tooltip;
  • a pending-changes sheet with a retry countdown, retry and discard;
  • a sync inspector with queue filters, the operation JSON, copy-to-clipboard and a timeline log.

That inspector turned support into a screenshot: "open the inspector and send me
the failed operation" is a complete bug report.

What the kit does not do

It is a client-side queue, deliberately. You provide authentication, connectivity
detection, a backend that honours idempotency keys, and one queue per isolate.
Payloads must be JSON-safe. Those limits are in the README, because a kit that
pretends otherwise costs buyers a week.

Try the demo

The package ships a notes app on a fake versioned server: switch it offline, add
latency, fail requests, or edit a record on "another device" and then locally to
produce a real conflict. Every surface in the kit is reachable from it.

The kit, with source, demo and docs, is here: SyncSpool Kit for Flutter

If you have hit a sync bug this article does not cover, I would like to hear how
you handled it.

The showcase repository is public — README, the eight screenshots and the demo GIF, no source: github.com/StephenColor/flutter-syncspool-kit

Top comments (0)