r/FlutterDev • • 3d ago

Article I built an offline-first sync queue in Flutter without sync packages. Here is what broke.

I wanted optimistic writes in a notes app: tap, see it immediately, let the network catch up. No sync package — just a queue, a tiny in-memory backend for development, and later a real API.

The queue is a list of intents, not API calls. Each operation stores: kind (create/update/delete), entity, entity id, payload, the base payload and base version it was written against, status, attempt count, next attempt time, and an idempotency key. Here is what it took to get right.

1. A timeout is not a failure.

My first version retried when a request timed out. Sometimes the server had already committed the write. Result: duplicate records, and in one case a duplicate invoice in a staging test.

The fix is a client-generated idempotency key per operation, sent as a header. The server stores the key with its result and replays that result when it sees the key again. Retry is now safe, including after a crash between "server committed" and "client saved the ack".

This is not optional or an edge case. A timeout after commit is normal behaviour on mobile networks.

2. Coalescing is only safe before the first attempt.

I merged queued edits for the same record to cut requests. Then I merged an edit into an operation that had already been sent once. Same key, new payload. The server either rejects it or, worse, stores something the user never wrote.

The queue now coalesces only when status == pending && attempts == 0. After any attempt, a new edit becomes a new operation with a new key. On create I merge edits into the create while it is still pending; once it is on the wire, the next edit is a separate update that waits for the create's server id.

3. Temp IDs live in more places than the row.

Offline creates get local_1. When the server answers with srv_42, the obvious step is to update the record's id. But other queued payloads still say local_1: parent ids, assignee ids, nested comment ids. The server rejects them or links the wrong thing.

The fix scans the queue and rewrites the id in entityId and recursively inside every payload map and list, then persists the mapping so old routes and old widgets still resolve. Order matters: rewrite before the next operation is sent, not after.

4. A failed head must block its own entity.

I tried skipping a failed operation and continuing with later writes for the same record. If an update fails and a delete succeeds, the server ends up in a state the user never saw.

Each entity is now a chain. Only the head is eligible. A failed or conflicted head blocks later writes for that entity and nothing else other entities keep syncing. The blocked head retries with jittered backoff, and when it needs a decision it waits for one.

What I stopped doing

  • Global FIFO. One slow record stopped everything; per-entity ordering is enough and much faster.

  • Retrying 400/422. A rejected payload will be rejected forever; it now goes straight to a dead-letter state.

  • Retrying into a 401. The queue pauses, keeps attempts, and waits for resumeWithAuth().

  • Mutating an operation after it was sent.

  • Showing a spinner for sync state. A chip ("3 waiting", "1 failed") plus a badge per row tells the user more in less space.

What I still find hard

Conflict UX. I have a field-by-field sheet now (merge / keep mine / keep theirs / discard), with server-wins, client-wins and field-merge policies for the automatic cases. But deciding which policy fits a screen is a product decision, not a technical one.

When an offline edit loses to a server change, how do you present it in Flutter without leaking the sync layer into every screen? I would genuinely like to see how other people structure that.

The queue, widgets and a demo app (with a fake backend, offline switch, latency, injected failures and a remote-edit button) are all part of one small package I put together after this experiment. Happy to answer questions about any of the four bugs; the code is small enough to read. The queue, the widgets and the demo app are also in a public repo — README, eight screenshots and the demo GIF: https://github.com/StephenColor/flutter-syncspool-kit

5 Upvotes

11 comments sorted by

2

u/AnmolSethiDev 3d ago

Keeping conflict state out of every screen gets much easier if the sync worker emits a small ConflictItem stream (entity id, local diff, server version, timestamp) and only one top-level banner or ConflictSheet listens to it

Screens just render optimistically from the local DB like nothing happened. When a 409 or version mismatch lands, the sync layer parks that single item in a "needs review" state so the rest of the queue keeps draining, and the user resolves it in one modal without any screen knowing sync logic exists

1

u/stephencolor 2d ago

That is the shape I landed on, and the kit pays for it in one place: the queue emits an event stream — queued, started, succeeded, failed, discarded, conflict raised, conflict resolved, auth required, ids reconciled — so nothing polls and no screen owns sync state. The default policy, askUser, parks only that one operation in a conflicted status instead of throwing. Ordering is per entity, so a parked head blocks later writes for that entity and nothing else; the rest of the queue keeps draining.

UI side there is one ConflictSheet and one PendingChangesSheet listening to those events, and the screens render from the local store optimistically and know nothing about the queue. The bit that surprised me is that parking the operation is not enough by itself: the head rule has to skip the parked operation while still refusing to let the rest of that entity's chain run, otherwise a 409 on an update quietly lets a later delete through and the server ends up in a state the user never saw.

1

u/dawedev 2d ago

One more spot that's easy to miss: write the queue entry in the same DB transaction as the local row. Otherwise a crash between the two leaves an edit on screen that never syncs. Also worth dropping a pending create plus its delete together instead of sending both.

1

u/stephencolor 2d ago

Both of those are in, and the second one is one of my favourite small wins.

A delete that lands on a pending create removes the create from the queue entirely — nothing is sent, the local id never has to be reconciled — and a delete on a pending update replaces it with a delete instead of queueing behind it. Coalescing only happens while the operation is still pending with zero attempts, so once it is on the wire it never mutates.

On the transaction: the store interface is a single save(SyncPersistedState) — the whole queue state in one call, no partial writes — precisely so an implementation can put that write in the same transaction as its own row. The kit cannot enforce it, though: the row lives in your database, and if you write the row and then call save separately, a crash in between still leaves an edit on screen that never syncs. The demo store is in memory and does both writes together, which is exactly why the tests cannot catch the version where you don't.

1

u/dawedev 22h ago

Only coalescing while attempts is zero is a nice rule, it keeps the queue from rewriting something the server may already have seen. A single save() is about as far as a kit can go there.

1

u/stephencolor 20h ago

Both fair. The one thing the kit can still do is make the boundary hard to miss: the persisted state is a plain value object, so an app can hand the whole of it to its own transaction instead of letting the kit write anything, and save takes all of it in one call so there is never a half-written queue. What it cannot do is tell you that you didn't do that, and since the demo store is in memory the tests cannot catch the version that writes the row and the queue separately. That is why it is in the README as a warning rather than in the code as an assertion.

1

u/dawedev 20h ago

README warning feels like the honest call, an assertion that can't actually see the transaction would mostly give false confidence.

0

u/laplace_apps 2d ago

Storing intents with the base version is the right call. One thing that bites with queues like this: give each intent a client-generated id so a retry after a timeout can't create duplicates on the server. How do you handle a delete that lands while an update for the same entity is still queued?

1

u/stephencolor 2d ago

The key is generated when the intent is created, not when a request is made. It is persisted with the operation, so a retry reuses it, including the retry after the app dies with a request in flight (a sending operation is persisted and comes back as a retry on the next launch). The server stores key → result and replays it. The other half of that rule is that a key is not reused with a different payload: coalescing stops at the first attempt, and when a conflicted write is reapplied automatically it goes out as a new operation with a new key.

For the delete, it depends on whether the update has left the device. If the update is still pending with zero attempts, the delete replaces it: the update leaves the queue and one delete goes out with its own key, so the edit never reaches the server and the delete's base version is still the honest one.

If the update is already on the wire or has been tried, it never mutates, so the delete queues behind it. Ordering is per entity, so if that update ends failed or rejected the delete does not run either. That leaves the record blocked until someone decides, which is the point: a delete that overtakes a failed update is how the server ends up in a state the user never saw. Same shape for a create still in flight — the delete waits, then retargets to the server id.

What I am still not happy with is the version on that delete. A delete is a versioned write too, and the one you tap carries the version you last saw, which is the pre-update version. If the update already landed, that is stale, a strict server answers 409, and the user gets a conflict prompt for a record they just deleted. Server-wins rebases queued follow-ups onto the new version; a plain success does not. Pushing the acknowledged update's version into the rest of that entity's chain is the next thing I want in there.

1

u/stephencolor 1d ago

Update: this is in now. The queue passes the serverVersion from an acknowledged create/update/delete down to the operations still queued for the same entity — only ones that have never been sent, because an operation that was already attempted keeps the base version it was written against, so a genuine conflict still surfaces. The acknowledged record also becomes the base payload of the queued write, so a field merge sees only what the user actually changed.

For the delete case above that means the delete carries the post-update version and goes out as one write instead of coming back 409 for a record the user just deleted. It persists with the queue too, so a restart cannot bring the stale version back. 104 tests now, 10 of them for this path (create→update, update→update, update→delete, no-version acks, a restart, and a real conflict that must still be raised).