offline_courier 0.2.0
offline_courier: ^0.2.0 copied to clipboard
Offline-first outbox for Flutter. Persists failed HTTP requests and replays them with exponential backoff and jitter when the network returns, even after the app is killed. Zero dependencies: native J [...]
offline_courier #
Offline-first outbox for Flutter. Send HTTP requests as usual; when there is no network (or the server hiccups) they are persisted, encrypted if you want, and replayed with exponential backoff + jitter as soon as connectivity returns, even if the app was killed.
Zero dependencies. Only the Flutter SDK. Storage, network monitoring and background scheduling are implemented natively inside the plugin, so you never write Kotlin or Swift, and you don't inherit anyone else's versions.
await OfflineCourier.initialize(); // 1. setup
final result = await OfflineCourier.instance.post( // 2. send
Uri.parse('https://api.shop.com/orders'), json: order,
);
Features #
| π¦ 0 dependencies | dependencies: flutter: sdk: flutter, nothing else |
| πΎ Durable outbox | Platform SQLite with transactions, WAL, and a pluggable PayloadCipher for URL/headers/body |
| πΆ Network aware | Drains the queue when connectivity returns; on Android "online" means a validated network |
| β± Smart retries | Exponential, fixed or custom schedules Β· full/equal jitter Β· Retry-After Β· TTL |
| π Background sync | Native one-off job (network-constrained) + periodic safety net, run in a headless engine |
| π Foreground service | CourierService runs your callback every N seconds with the screen off, survives swipe-away and reboots, with a notification you configure from code (Android) |
| β οΈ Dead-letter queue | 4xx and exhausted tasks are kept for inspection, retry or discard |
| π Idempotent replays | Every attempt carries Idempotency-Key: <taskId> |
| 𧬠Dedupe | dedupeKey makes the newest request win (e.g. profile edits), even over an older version that is being sent right now |
| β‘ Shorthands | post / put / patch / delete return an exhaustive CourierResult |
| π§ͺ Testable | Pure-Dart SyncEngine, in-memory store, injectable clock/connectivity/scheduler |
How it works #
ββββββββββββββ online? ββββββββββββββ
send(req) βββ€ β
β yes β no
βΌ βΌ
HTTP attempt ββββββββββββ
2xx ββΌβ 4xx ββΌβ 5xx/429/timeout ββββββββΆβ OUTBOX β (native SQLite)
β β ββββββ¬ββββββ
βΌ βΌ β triggers:
Delivered Rejected β β’ connectivity regained
(UI shows (UI shows β β’ foreground timer (next retry)
receipt) error) β β’ native OS job (app closed)
β β’ syncNow() / pull-to-refresh
βΌ
claimDue() ββ lease ββ execute()
β β β
2xx ββΆ delete + TaskDelivered β
5xx / network ββΆ backoff+jitter ββΆ pending ββββ
4xx / attempts or TTL exhausted ββΆ DEAD LETTER + TaskDeadLettered
Under the hood #
| Concern | Android | iOS | Dart |
|---|---|---|---|
| Storage | android.database.sqlite |
system libsqlite3 |
NativeCourierStore |
| Connectivity | ConnectivityManager (INTERNET + VALIDATED) |
NWPathMonitor |
NativeConnectivityMonitor |
| Background jobs | JobScheduler (persisted, network constraint) |
BGTaskScheduler (processing + app refresh) |
NativeBackgroundScheduler |
| Background runtime | headless FlutterEngine in a JobService |
headless FlutterEngine |
offlineCourierBackgroundMain |
| HTTP | β | β | dart:io HttpClient (IoRequestExecutor) |
All Dart isolates (UI and background engine) share one native SQLite connection, and the queue is protected on three levels:
- Single drainer. A drain lock (with expiry) lets only one engine work on the queue at a time. While the app is visible the UI isolate drains it: the one-off OS job is not even scheduled and the periodic safety net steps aside. When the app goes to the background the one-off job is armed as a backup, and the UI isolate keeps draining for as long as its process stays alive (for example under a foreground service). If an engine dies holding the lock, the next background run frees it.
- Owned tasks. Each task is claimed right before it is sent, by one engine, with a lease. Results are written only if that engine still owns the task, so a slow or dead engine can never overwrite another one.
- Write-ahead.
send()stores the request before the first network attempt. If the process dies mid-request, the lease expires and the task is retried automatically with the sameIdempotency-Key.
Platform status (0.2.0) #
| Android | iOS | |
|---|---|---|
| Outbox, retries, ordering, events | β Verified on emulator (API 37) and a physical device (Xiaomi, Android 12 / MIUI 14) | β Verified on simulator |
| Native SQLite store and migrations | β | β Simulator |
| Connectivity monitoring | β | β Simulator |
CourierService (periodic work with the screen off) |
β Foreground service with its own engine, verified on emulator (API 37) and Xiaomi (Android 12 / MIUI 14): screen off, swipe-away, reboot | β Not available |
| Background sync with the app closed | β JobScheduler + headless engine, verified on emulator and Xiaomi (see manufacturer restrictions) | β οΈ Implemented (BGTaskScheduler), not yet verified on a physical iPhone; planned for a later release. BGTaskScheduler does not run on the simulator. |
Installation #
dependencies:
offline_courier: ^0.2.0
Android #
Nothing to do. The plugin manifest already declares INTERNET,
ACCESS_NETWORK_STATE, RECEIVE_BOOT_COMPLETED (jobs survive reboots) and
its JobService. Requires minSdk 24.
iOS #
In ios/Runner/Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>offline_courier.sync.processing</string>
<string>offline_courier.sync.refresh</string>
</array>
iOS decides when background tasks run. While the app is alive the courier uses its own timers and connectivity events, so foreground sync is instant.
BGTaskSchedulerdoes not run on the simulator; scheduling errors there are logged and ignored.
Quick start #
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await OfflineCourier.initialize();
runApp(const MyApp());
}
Send and handle every outcome #
final result = await OfflineCourier.instance.post(
Uri.parse('$api/orders'),
json: {'sku': 'A1', 'qty': 2},
tag: 'orders',
metadata: {'localOrderId': order.id},
);
switch (result) {
case CourierDelivered(:final response):
showReceipt(response.json);
case CourierQueued():
showSnack('Saved. It will be sent when you are back online.');
case CourierRejected(:final response):
showError(response.body); // e.g. 422 validation error, not queued
case CourierFailed(:final error):
reportBug(error); // non-network failure, moved to the dead-letter queue
}
Full control with CourierRequest #
await OfflineCourier.instance.send(
CourierRequest(
method: 'PUT',
url: Uri.parse('$api/avatar'),
headers: {'content-type': 'image/jpeg'},
body: jpegBytes,
),
dedupeKey: 'avatar:$userId', // only the newest pending upload survives
);
Only POST/PUT/PATCH/DELETE are accepted. Reads should come from your local
cache, not from a replay queue. Requests that could never be sent are
rejected with an ArgumentError before anything is stored: a non-http(s) or
relative URL, invalid header names, header values with line breaks or
non-ASCII characters, or a body larger than maxBodyBytes (5 MB by default).
Once a request is persisted, send/enqueue never throw because of a later
failure (for example the OS refusing to schedule a job). Those failures are
published as CourierError events.
React to sync events #
OfflineCourier.instance.events.listen((event) => switch (event) {
TaskEnqueued() => null,
TaskDelivered(:final task) => markSynced(task.metadata['localOrderId']),
TaskRetryScheduled(:final delay) => log('retry in $delay'),
TaskDeadLettered(:final task, :final reason) => showConflict(task, reason),
SyncProgress(:final completed, :final total) => progress(completed / total),
CourierError(:final operation, :final error) => log('$operation: $error'),
});
// Events include what the background job delivers while the app is alive,
// so `markSynced` above also runs for background deliveries.
// "3 changes pending" badge
StreamBuilder<int>(
stream: OfflineCourier.instance.watchPendingCount(),
builder: (_, s) => Badge(label: Text('${s.data ?? 0}')),
);
Configuration #
config is a top-level (or static) function annotated with
@pragma('vm:entry-point'). The plugin stores its callback handle and calls
the same function inside the background engine, so foreground and background
behave identically. Without the pragma the compiler removes or hides the
function and background sync cannot find it.
@pragma('vm:entry-point')
CourierConfig buildCourierConfig() => CourierConfig(
retryPolicy: const RetryPolicy(
maxAttempts: 10,
initialDelay: Duration(seconds: 5),
maxDelay: Duration(hours: 1),
jitter: JitterStrategy.full,
maxAge: Duration(days: 3), // give up after 3 days
),
headersResolver: (_) async => { // fresh token at delivery time
'authorization': 'Bearer ${await tokenStore.read()}',
},
classifier: (status) => status == 409
? DeliveryOutcome.deadLetter
: defaultResponseClassifier(status),
storeBuilder: () => NativeCourierStore(cipher: MyAesGcmCipher()),
ordering: OrderingMode.strictPerTag, // see "Ordering"
periodicSyncInterval: const Duration(minutes: 15),
onError: (error, stack, operation) => // also runs in the background
crashReporter.record(error, stack, reason: operation),
);
await OfflineCourier.initialize(config: buildCourierConfig);
initialize checks this up front: a closure or a builder without the pragma
throws an ArgumentError at startup instead of failing silently in a
background job hours later.
Ordering #
| Mode | Guarantee |
|---|---|
OrderingMode.bestEffort (default) |
Oldest due task first, but a task waiting for its backoff does not hold back the ones behind it, and an online send can overtake queued tasks. |
OrderingMode.strictPerTag |
Strict FIFO within each tag (untagged tasks form one group). A task only goes out after every older task of its group was delivered or dead-lettered; an online send queues behind them. |
CourierConfig(ordering: OrderingMode.strictPerTag)
courier.post(createOrder, tag: 'order-42');
courier.post(payOrder, tag: 'order-42'); // never before the create
A failing head delays its whole group until it succeeds or is dead-lettered, so use distinct tags for independent flows.
| Retry schedule | Code |
|---|---|
| Exponential (default) | RetryPolicy() β 5s, 10s, 20sβ¦ β€ 1h, full jitter |
| Fixed | RetryPolicy.fixed(Duration(minutes: 1), maxAttempts: 20) |
| Custom | RetryPolicy.intervals([Duration(seconds: 10), Duration(minutes: 5)]) |
| Never retry | RetryPolicy.none |
When a request to a server succeeds, tasks that were waiting for a retry on
that same server (same scheme, host and port) are sent right away: the server
is evidently back, so there is no point in sleeping through the rest of the
backoff. A 429 keeps its wait, because the server asked for it.
Default classification: 2xx delivers Β· 408/425/429/5xx and network
(IOException) or timeout errors retry Β· any other status, and any other
exception (for example a headersResolver that throws StateError), goes to
the dead-letter queue.
Background execution #
When a job fires with the app closed, the plugin starts a headless Flutter
engine, runs the package's offlineCourierBackgroundMain, rebuilds your
config through buildCourierConfig, drains the queue and re-arms the next
job. You write no dispatcher.
Android: every plugin of the app is auto-registered on the headless
engine, so a headersResolver can use secure storage or similar.
iOS (optional): if your headersResolver uses other plugins, register
them for the background engine in AppDelegate.swift:
import offline_courier
OfflineCourierPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}
Periodic sends with the screen off: CourierService (Android) #
OS jobs are deferred: Android runs them in maintenance windows that can be
many minutes apart, so they cannot send a point every 10 seconds from a
phone in a pocket. That needs a foreground service (a persistent
notification). CourierService is one, with its own Flutter engine: every
interval it runs your callback, where OfflineCourier.instance is ready.
Whatever cannot be sent stays in SQLite until the network or the server is
back.
It keeps going with the screen off (it holds a wake lock while running),
after Back, after the app is swiped away from Recents, after the system
kills the process (it is restarted) and, with resumeAfterReboot, after a
reboot or an app update. If the system did not restart it (some
manufacturers), it resumes the next time the app opens.
@pragma('vm:entry-point')
Future<void> sendLocation() async {
final p = await Geolocator.getCurrentPosition();
await OfflineCourier.instance.post(
Uri.parse('https://api.example.com/locations'),
json: {'latitude': p.latitude, 'longitude': p.longitude,
'date': DateTime.now().millisecondsSinceEpoch},
tag: 'tracking',
);
await CourierService.updateNotification(text: 'Last point: now');
}
await CourierService.requestNotificationPermission(); // Android 13+
await CourierService.start(
notification: const CourierNotification(
title: 'Tracking active',
text: 'Sending your location every 10 s',
icon: 'ic_tracking', // res/drawable/ic_tracking.xml (optional)
stopActionLabel: 'Stop', // optional action button
),
interval: const Duration(seconds: 10),
onTick: sendLocation,
resumeAfterReboot: true,
);
await CourierService.pause(); // keeps the notification, stops ticking
await CourierService.resume();
await CourierService.stop();
CourierService.watchState().listen(print); // stopped / running / paused
Manifest #
The plugin does not declare the service, so apps that only use the
outbox inherit no foreground-service permissions or Play Console
declarations. Declare it with the
foreground service type
that matches your work (location for a tracker; dataSync is limited to
6 hours a day on Android 15+):
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application>
<service
android:name="com.offlinecourier.offline_courier.CourierForegroundService"
android:foregroundServiceType="location"
android:exported="false" />
<!-- Only with resumeAfterReboot: true -->
<receiver
android:name="com.offlinecourier.offline_courier.CourierBootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
</application>
start checks the declaration and the permissions and throws a
StateError that says what is missing. Grant the location permission
before starting a location service.
After a reboot, Android 10+ only gives location to a service started in
the background if the app has ACCESS_BACKGROUND_LOCATION ("Allow all the
time"), and recent versions refuse to start it at all without it. Without
that permission the service resumes when the user opens the app.
Back: the service has its own engine, so Back does not stop it. If you also keep work in the UI isolate, note that Back on Flutter's root route destroys the UI engine; the example app sends the task to the background instead:
class MainActivity : FlutterActivity() {
override fun popSystemNavigator(): Boolean {
moveTaskToBack(true)
return true
}
}
The example app's Tracking tab runs this end to end with
geolocator (an example-only
dependency), posting {id, idUser, latitude, longitude, date, uid} every
10 seconds. iOS has no equivalent: CourierService throws
UnsupportedError there.
Android manufacturer restrictions (Xiaomi, Huawei, Oppoβ¦) #
Some Android skins block background work far beyond stock Android. On Xiaomi (MIUI / HyperOS), observed on a Redmi 9T with MIUI 14:
- Autostart was off by default for the app (installed over USB; check
it on your own builds too). With Autostart off and the process gone (swiped from
Recents, killed for memory), MIUI refuses to start the plugin's
JobServiceand silently deletes its jobs. Nothing is lost, since the queue stays in SQLite and is sent the next time the user opens the app, but nothing is sent in the meantime. - With Autostart on, background delivery works after a swipe, a force stop and a reboot (a few seconds after the network returns, or at the scheduled retry time).
- While the process is still alive in the background, jobs run even with Autostart off.
- "Restrict background activity" (battery saver per app) stops jobs until it is lifted.
- After a reboot with a lock screen, delivery waits for the first unlock.
CourierServicesurvives a swipe from Recents even with Autostart off, but after a reboot MIUI discards the boot broadcast unless Autostart is on; the service then resumes when the user opens the app.
What to tell your users (an in-app hint on these devices helps): Settings β Apps β Manage apps β your app β Autostart: on, and Battery saver: No restrictions. dontkillmyapp.com documents the equivalent settings for other manufacturers.
Dead-letter queue #
final failed = await OfflineCourier.instance.deadLetters(tag: 'orders');
for (final task in failed) {
print('${task.request.method} ${task.request.url} β ${task.lastError}');
}
await OfflineCourier.instance.retry(failed.first.id); // fresh retry budget
await OfflineCourier.instance.discard(failed.last.id);
Encryption #
Queued requests often contain tokens and personal data. Implement
PayloadCipher with your crypto of choice (keep the key in the platform
keystore) and pass it to NativeCourierStore. Method, URL, headers and body
are serialized into one blob and encrypted in Dart, so the native layer
and the database file only ever see ciphertext.
Server-side best practice #
Delivery is at least once. Replays can happen (e.g. the process died
after the server committed but before the app saw the response).
Make your endpoints honor the Idempotency-Key header. The courier sends the
same key on every attempt of a task.
Testing #
final engine = SyncEngine(
store: InMemoryCourierStore(),
executor: FakeExecutor(),
config: CourierConfig(clock: () => fakeNow),
);
OfflineCourier.initialize also accepts connectivity: and scheduler:
fakes. The example app ships an integration_test/ that exercises the real
native SQLite store and connectivity on a device or simulator.
Limitations #
- Request bodies are buffered in memory and capped by
maxBodyBytes; not intended for large file uploads. - On iOS
NWPathMonitorreports a usable path, not backend reachability. A captive portal leads to a retry with backoff, and the request is not lost. - Android and iOS only (
dart:io, platform SQLite, OS schedulers). - Android's JobScheduler writes jobs to disk asynchronously: a job scheduled a couple of seconds before a reboot can be lost. The queue itself is safe in SQLite and is picked up by the periodic job or the next app start.
- If the app dies while in the foreground without passing through the background (a crash), no one-off job is armed; the periodic job or the next app start resume the queue.
- Leases and the drain lock use the device's wall clock. Moving the clock
backwards by hours can delay the queue until that time passes again (or
until the app is reopened); moving it forward can produce duplicate
attempts, which the
Idempotency-Keyabsorbs. - Keep
CourierConfig.lease(2 minutes by default) longer than the slowest attempt (IoRequestExecutor.timeoutper phase plus yourheadersResolver), or a slow attempt can be re-claimed and sent twice.
License #
MIT. See LICENSE.