DEV Community

Cover image for sync_outbox: a durable outbox for offline-first Dart and Flutter apps
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

sync_outbox: a durable outbox for offline-first Dart and Flutter apps

An offline-first app lets the user keep working without a network. They edit a note, delete another, create a third. The app applies each change locally and has to send it to the server later. The simple version is a list of pending requests and a loop that retries them, and it breaks in predictable ways.

The app is killed in the middle of a request: was it applied or not? Resend it and you may create a duplicate. A request fails with a 500: retry, but when, and how many times? One fails with a 400: retrying forever is pointless, but dropping it silently loses the user's work. The server answers 409 because someone else edited the same record. And two edits to the same note must arrive in the order they were made.

sync_outbox is a Dart package that handles this queue. Your app enqueues mutations while offline, and the outbox delivers them later, safely and in order. It is storage-agnostic, and the main library is pure Dart with no dependencies.

What it does

A durable queue with idempotency keys. Every entry carries a client idempotency key: a UUID v4 generated without extra packages, or your own generator. An entry is written to storage as in flight before it is sent. If the app is killed mid-request, the next start() puts the entry back to pending and resends it with the same key, so the server can deduplicate.

Typed send results. Your Sender function returns one of success, retryableFailure(retryAfter?), permanentFailure(reason) or conflict(serverState). If it throws, the outbox treats that as a retryable failure.

Ordering groups. Entries in the same group go out one at a time, in FIFO order. Different groups run in parallel, up to maxConcurrency (4 by default). A failing entry blocks only its own group: later entries in that group wait, and other groups keep going. An entry with no group is independent of every other entry. For a single global FIFO that stops at the first error, put every entry in one group.

Backoff. ExponentialBackoff with jitter and a cap, or a fixed schedule. The ScheduledBackoff.oneMinuteToOneDay preset (1 m, 5 m, 15 m, 1 h, 6 h, then daily) never gives up. Jitter only ever shortens a delay, so the cap always holds. A server retryAfter takes precedence over the policy.

Nothing is dropped silently. Rejected entries go to needs attention and stay there until you call retry(id), retryAllNeedingAttention() or discard(id). The same happens when maxAttempts is reached.

Coalescing. Optional and configured per operation type. Several edits to an unsent note can merge into one entry, and a create followed by a delete can cancel both. You supply the merge function. A coalescer is consulted only when the most recent entry for the same resourceKey and group is pending and has never been attempted, which guarantees the server has not seen it.

Conflict strategies. serverWins, clientWins, lastWriteWins, merge(callback) and manual (the default). You set a default and can override it per operation type. A resend after a conflict uses a fresh idempotency key, and maxConflictResolutions (3 by default) stops two writers from overwriting each other forever.

Streams for the UI. Stream<OutboxEvent> reports everything that happens, and Stream<OutboxCounts> drives badges such as "3 unsent" or "1 needs attention".

Triggers. The outbox takes a Stream<bool> of connectivity, so it does not depend on connectivity_plus. It can also flush on a periodic timer, when a retry comes due, right after enqueue, or when you call flush().

Deterministic tests. The clock, the random source and the id generator are all injectable, and it works with fake_async.

How to use it

Add it from GitHub:

dependencies:
  sync_outbox:
    git: https://github.com/AbdeldjalilChougui/sync_outbox
Enter fullscreen mode Exit fullscreen mode

Then write a sender that maps your HTTP client's answers onto SendResult, and create the outbox:

import 'package:sync_outbox/io.dart'; // JsonFileOutboxStore (not on the web)
import 'package:sync_outbox/sync_outbox.dart';

Future<SendResult> send(OutboxEntry e) async {
  // Send e.idempotencyKey (for example as an Idempotency-Key header) so the
  // server can recognise a resend of a request it already applied.
  final status = await fakeHttp(e.operation, e.resourceKey, e.payload,
      idempotencyKey: e.idempotencyKey);
  return switch (status) {
    >= 200 && < 300 => const SendResult.success(),
    409 => const SendResult.conflict({'title': 'server copy'}),
    429 || >= 500 => const SendResult.retryableFailure(error: 'server busy'),
    _ => SendResult.permanentFailure('HTTP $status'),
  };
}

Future<void> main() async {
  final outbox = Outbox(
    store: JsonFileOutboxStore('/path/to/app_dir/outbox.json'),
    sender: send,
    flushInterval: const Duration(minutes: 1),
    retryPolicy: ScheduledBackoff.oneMinuteToOneDay,
    defaultConflictStrategy: ConflictStrategy.lastWriteWins,
  );
  await outbox.start(); // Recovers interrupted sends, then flushes.

  await outbox.enqueue(
    operation: 'update',
    resourceKey: 'note:42',
    payload: {'title': 'Groceries'},
    group: 'notes', // FIFO with the other note mutations
  );

  outbox.counts.listen((c) => print('${c.outstanding} unsent, '
      '${c.needsAttention} need attention'));

  await outbox.dispose();
}
Enter fullscreen mode Exit fullscreen mode

Here fakeHttp stands for your own HTTP call. A complete runnable tour, with a simulated flaky server, is in example/main.dart.

Coalescers are a map from operation type to a function:

final coalescers = <String, Coalescer>{
  // Edits fold into the queued create/update; its position and key are kept.
  'update': (queued, incoming) =>
      Coalesce.merge({...queued.payload, ...incoming.payload}),
  // Create then delete: neither needs to reach the server.
  'delete': (queued, incoming) => queued.operation == 'create'
      ? Coalesce.cancelBoth
      : Coalesce.merge(const {}, operation: 'delete'),
};
Enter fullscreen mode Exit fullscreen mode

Storage

OutboxStore has two methods: loadAll(), which returns the entries ordered by sequence, and an atomic commit(upserts, removals). The outbox keeps its working set in memory and writes every change through commit before acting on it, and commit is never called concurrently.

Two stores are included. InMemoryOutboxStore is for tests and for queues that do not need to survive a restart. JsonFileOutboxStore writes <path>.tmp, flushes it, and renames it over the file on each commit, so a crash leaves either the old file or the new one, never a torn file. It suits queues of up to a few thousand entries.

For a database, the simplest schema is one row per entry: the id as primary key, the sequence for ordering, and jsonEncode(entry.toJson()) as the body. The README has a full drift implementation, which was compile-checked and run against drift 2.28 with an in-memory SQLite database, plus notes for sqflite and hive_ce. Hive has no transaction that spans a put and a delete, and the README explains how to work around that.

Things to know

  • Delivery is at-least-once. Exactly-once needs the server to deduplicate on idempotencyKey. Without that, an entry interrupted in flight can be applied twice.
  • One Outbox must own its store. Do not run two outboxes on the same storage, for example from two isolates at once.
  • The working set lives in memory and the scans are linear. That is fine for thousands of entries, not for millions.
  • Coalescing is narrow on purpose. It combines an entry only with the latest queued entry for the same resource in the same group, and merging moves the incoming change to that entry's position in the queue.
  • payload and serverState must be JSON-encodable for the bundled stores.
  • JsonFileOutboxStore needs dart:io, so it is not available on the web. There, implement OutboxStore on IndexedDB or a similar store.
  • The outbox does not detect connectivity or run background tasks. Feed it a connectivity stream, and call flush() from a background worker such as workmanager if you need that.
  • Offline behaviour. While the outbox is offline, flush() sends nothing. When connectivity drops during a flush, requests already on the wire are allowed to finish, but no new ones start.

Why I built it

The problem the README describes is the gap between "queue it and retry" and a queue you can trust. Each rule in the package answers one failure: the in-flight marker and the idempotency key answer the app being killed mid-request, typed results answer the difference between a busy server and a rejected request, groups answer ordering, needs attention answers silent data loss, and conflict strategies answer the 409.

I also wanted it to stay out of the rest of the app's choices. It does not pick your database, your HTTP client or your connectivity plugin: storage is a two-method interface, sending is one function, and connectivity is a Stream<bool>. And because retry logic is hard to test with real timers, the clock, the randomness and the ids can all be injected.

Get the code

The source, the runnable example, the lifecycle diagram and the storage recipes are on GitHub: https://github.com/AbdeldjalilChougui/sync_outbox. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)