Guides · App patterns
Offline caches & reconnect sync
Mirror permitted rows into local SQLite or IndexedDB, queue idempotent mutations while offline and resolve version conflicts on reconnect.
- In the schema
ext::auth::Identity
What you’ll build#
You will add a synced local store, instant offline reads and an ordered mutation outbox to a mobile or web app. Screens render immediately without signal and synchronize pending edits when connectivity returns. Every read and write still runs through your deployed EdgeQL queries and schema access policies on the server, so client code never repeats permission checks.
Local store and outbox
Local storage caches permitted rows and replays queued writes on reconnect.
Napalm compiles access rules and constraints inside PostgreSQL on your cluster. Durable commits occur over the network rather than inside a device database. A local store and idempotent outbox give phones, tablets and field browsers instant cold starts and offline drafts while PostgreSQL stays authoritative.
| Layer | Where data lives | Responsibility |
|---|---|---|
| Synced store | SQLite or IndexedDB on device | ResponsibilityCaches permitted rows for one deployed query alongside the latest commit bookmark so lists render without a network round trip. |
| Mutation outbox | SQLite or IndexedDB on device | ResponsibilityQueues offline creates, edits and archives in commit order and overlays pending drafts onto local reads. |
| Deployed queries | PostgreSQL on your project | ResponsibilityEnforces access policies, deduplicates retried inserts by UUID and checks expected row versions on reconnect. |
| Live stream | POST /subscribe | ResponsibilityStreams changes since the stored bookmark on reconnect and applies live commit patches into the local store. |
Model idempotent writes and versions#
Reliable offline sync starts in dbschema/default.gel. A mobile connection frequently drops after PostgreSQL commits a statement and before the HTTP response reaches the phone. Without an idempotency key and a row version on the type, replaying an outbox entry would duplicate inserts or silently overwrite a teammate’s newer edit.
using extension auth;using extension napalm; module default { global caller := global ext::auth::ClientTokenIdentity; type Note { required owner: ext::auth::Identity { default := global caller; readonly := true; } # Client-chosen idempotency key so replaying an outbox entry never duplicates a note. required client_mutation_id: uuid { constraint exclusive; } required title: str { constraint max_len_value(200); } required body: str; # Monotonic version checked on offline edits so stale drafts never overwrite newer commits. required version: int64 { default := 1; } required updated_at: datetime { default := datetime_of_statement(); } # Soft-delete timestamp so archived notes leave listNotes and sync out of device storage. deleted_at: datetime; # Composite keyset index used by the notesSince watermark query. index on ((.updated_at, .id)); access policy owner_all allow all using (.owner ?= global caller); }}client_mutation_id- Generated on the device with
crypto.randomUUID()when the person taps Save. Theexclusiveconstraint guarantees that replaying the outbox entry returns the existing row instead of inserting a copy. version- Starts at
1and increments on every update. Offline edits send the version the user started editing so concurrent server commits are detected deterministically. deleted_at- Soft-delete timestamp. Archiving a note excludes it from
listNotes, sonapalm.syncremoves the row from local storage while the watermark query below still sees the deletion. ((.updated_at, .id))- Composite keyset index for the
notesSincewatermark query below. Standardnapalm.syncsubscriptions do not need this index.
Save these four queries under dbschema/queries/ and deploy the catalog with napalm queries push notes. listNotes backs the synced read store, while the three write queries replay queued creates, edits and archives.
# dbschema/queries/listNotes.edgeql# Synced read query returning active notes permitted for the caller, newest first.select Note { id, client_mutation_id, title, body, version, updated_at,}filter not exists .deleted_atorder by .updated_at desc then .id desc# dbschema/queries/createNoteOffline.edgeql# Replaying the same $mutation_id after a dropped cellular response returns the existing row.select ( insert Note { client_mutation_id := <uuid>$mutation_id, title := <str>$title, body := <str>$body, } unless conflict on .client_mutation_id else (select Note)) { id, client_mutation_id, title, body, version, updated_at, deleted_at,}# dbschema/queries/saveNoteVersioned.edgeql# Returns zero rows when another device committed a newer version while this device was offline.select ( update Note filter .id = <uuid>$id and .version = <int64>$expected_version and not exists .deleted_at set { title := <str>$title, body := <str>$body, version := .version + 1, updated_at := datetime_of_statement(), }) { id, client_mutation_id, title, body, version, updated_at, deleted_at,}# dbschema/queries/archiveNoteVersioned.edgeqlselect ( update Note filter .id = <uuid>$id and .version = <int64>$expected_version and not exists .deleted_at set { deleted_at := datetime_of_statement(), version := .version + 1, updated_at := datetime_of_statement(), }) { id, version, updated_at, deleted_at,}Sync permitted rows to the device#
napalm.sync mirrors the result of a deployed query into local device storage. Because the subscription references the deployed query by name, offline sync works under --passthrough none and renders cached rows immediately on cold launch.
The local store persists the commit bookmark alongside cached rows. On reconnect, the subscription sends that bookmark so the project returns only updated rows plus the current list of permitted IDs. Any note archived, deleted or hidden by an access policy while the device was offline is absent from that ID list and removed from local storage. Subsequent patch frames update rows by id and advance the bookmark, while an empty store fetches the full initial snapshot.
// src/offline/store.tsimport { sqliteSyncStore } from 'napalm-client/expo'import * as SQLite from 'expo-sqlite' export const localDb = SQLite.openDatabaseSync('napalm-offline.db') // Persists cached listNotes rows and their latest commit bookmark in SQLite.export const notesStore = sqliteSyncStore(localDb, 'notes') localDb.execSync(` CREATE TABLE IF NOT EXISTS mutation_outbox ( seq INTEGER PRIMARY KEY AUTOINCREMENT, mutation_id TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, target_id TEXT NOT NULL, expected_version INTEGER, title TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', error_message TEXT ); CREATE TABLE IF NOT EXISTS local_owner ( id INTEGER PRIMARY KEY CHECK (id = 1), identity_id TEXT NOT NULL );`) export type SyncedNote = { id: string title: string body: string version: number} export type VisibleNote = SyncedNote & { syncState: 'synced' | 'pending' | 'conflict' errorMessage: string | null} /** Overlays pending outbox mutations onto synced rows so offline edits appear immediately. */export function readVisibleNotes(synced: readonly SyncedNote[]): VisibleNote[] { const queued = localDb.getAllSync<{ kind: string target_id: string title: string body: string expected_version: number | null status: 'pending' | 'conflict' error_message: string | null }>("SELECT kind, target_id, title, body, expected_version, status, error_message FROM mutation_outbox ORDER BY seq ASC") const byId = new Map<string, VisibleNote>( synced.map((row) => [row.id, { ...row, syncState: 'synced', errorMessage: null }]), ) for (const entry of queued) { if (entry.kind === 'archive' && entry.status === 'pending') { byId.delete(entry.target_id) continue } byId.set(entry.target_id, { id: entry.target_id, title: entry.title, body: entry.body, version: entry.expected_version ?? 1, syncState: entry.status, errorMessage: entry.error_message, }) } return [...byId.values()]}// src/NotesScreen.tsximport { deployed } from 'napalm-client'import { useSyncedQuery } from 'napalm-client/react'import { FlatList, Text, View } from 'react-native'import { notesStore, readVisibleNotes, type SyncedNote } from './offline/store' const listNotes = deployed<SyncedNote>('listNotes') export function NotesScreen() { // Renders cached SQLite rows immediately, then streams and persists live updates. const { rows = [], isStored, error } = useSyncedQuery(listNotes, {}, notesStore) const notes = readVisibleNotes(rows) return ( <View> {isStored && <Text>Showing saved notes</Text>} {error && <Text>{error.message}</Text>} <FlatList data={notes} keyExtractor={(note) => note.id} renderItem={({ item }) => <Text>{item.title}</Text>} /> </View> )}isStored- True while the UI renders cached rows from disk before the first live frame arrives from the server. Use this flag to display an offline or cached badge.
napalm.sync- Subscribes outside React via
napalm.sync(query, variables, store, { onRows, onError }). Callclose()on the returned handle to stop syncing. - Storage adapters
sqliteSyncStore(db, name)fromnapalm-client/expopersists rows innapalm_sync_rowsandnapalm_sync_stores.indexedDbSyncStore(name)uses IndexedDB in browsers, andmemorySyncStore()backs unit tests.- One store per query
- Multiple components syncing the same query and variables share one subscription and one local store. Binding two different stores to the same query or sharing one store across two queries throws an error.
- Object ID requirement
- Synced queries must return objects with
idfields. Scalar or aggregate queries fail withids_requiredand leave existing cached rows untouched.
Flutter#
napalm_client syncs into any SyncStore implementation without bundling a specific SQLite package, so your app supplies a small adapter. The adapter below persists rows in sqflite, and a Drift adapter implements the same four methods.
// lib/services/sqflite_sync_store.dartimport 'dart:convert'; import 'package:napalm_client/napalm_client.dart';import 'package:sqflite/sqflite.dart'; /// Persists one synced query's rows and bookmark in SQLite under [name].class SqfliteSyncStore implements SyncStore { SqfliteSyncStore(this.db, this.name); final Database db; final String name; /// Creates the shared sync tables during openDatabase onCreate. static Future<void> createTables(Database db) async { await db.execute( 'CREATE TABLE sync_rows (store TEXT NOT NULL, id TEXT NOT NULL, row TEXT NOT NULL, PRIMARY KEY (store, id))', ); await db.execute( 'CREATE TABLE sync_stores (store TEXT PRIMARY KEY NOT NULL, bookmark TEXT NOT NULL, ids TEXT NOT NULL)', ); } @override Future<StoredRows?> read() async { final kept = await db.query('sync_stores', where: 'store = ?', whereArgs: [name]); if (kept.isEmpty) return null; final order = (jsonDecode(kept.single['ids'] as String) as List).cast<String>(); final places = {for (final (index, id) in order.indexed) id: index}; final rows = [ for (final stored in await db.query('sync_rows', where: 'store = ?', whereArgs: [name])) jsonDecode(stored['row'] as String) as Map<String, Object?>, ]..sort((a, b) => (places[a['id']] ?? order.length).compareTo(places[b['id']] ?? order.length)); return (rows: rows, bookmark: kept.single['bookmark'] as String); } @override Future<void> apply({ required List<Map<String, Object?>> changed, required List<String> removed, List<String>? order, required String bookmark, }) => db.transaction((txn) async { final batch = txn.batch(); for (final id in removed) { batch.delete('sync_rows', where: 'store = ? AND id = ?', whereArgs: [name, id]); } for (final row in changed) { _put(batch, row); } batch.update( 'sync_stores', {'bookmark': bookmark, if (order != null) 'ids': jsonEncode(order)}, where: 'store = ?', whereArgs: [name], ); await batch.commit(noResult: true); }); @override Future<void> replace(List<Map<String, Object?>> rows, String bookmark) => db.transaction((txn) async { final batch = txn.batch()..delete('sync_rows', where: 'store = ?', whereArgs: [name]); for (final row in rows) { _put(batch, row); } batch.insert('sync_stores', { 'store': name, 'bookmark': bookmark, 'ids': jsonEncode([for (final row in rows) row['id']]), }, conflictAlgorithm: ConflictAlgorithm.replace); await batch.commit(noResult: true); }); @override Future<void> clear() => db.transaction((txn) async { final batch = txn.batch() ..delete('sync_rows', where: 'store = ?', whereArgs: [name]) ..delete('sync_stores', where: 'store = ?', whereArgs: [name]); await batch.commit(noResult: true); }); void _put(Batch batch, Map<String, Object?> row) => batch.insert('sync_rows', { 'store': name, 'id': row['id'], 'row': jsonEncode(row), }, conflictAlgorithm: ConflictAlgorithm.replace);}// lib/pages/notes_page.dart (inside State<NotesPage>)late final StreamSubscription<SyncedRows<ListNotesDataItem>> _notes;SyncedRows<ListNotesDataItem>? _synced; @overridevoid initState() { super.initState(); // Emits cached SQLite rows immediately, then streams and persists live updates. _notes = widget.napalm .sync( const LiveQuery.deployed('listNotes'), widget.notesStore, decode: (row) => ListNotesDataItem.fromJson(row as Map<String, dynamic>), ) .listen((synced) => setState(() => _synced = synced));} @overridevoid dispose() { unawaited(_notes.cancel()); super.dispose();}Watermark pages for a large mirror#
Use a watermark query when a local mirror exceeds one subscription’s 16 MiB result limit, or when the project’s cluster keeps no change log and each reconnect sends the whole result. notesSince pages forward from a persisted (since_time, after_id) cursor and transfers only rows updated after that position. Because notesSince is an ordinary deployed query, it works under --passthrough none.
A watermark query returns only rows the caller may still read. Archive removed notes with deleted_at rather than hard-deleting rows so deletions appear in the delta page. Rows newly hidden by an access policy change remain in local storage until the next full resync.
# dbschema/queries/notesSince.edgeql# Keyset watermark page across active and soft-deleted rows permitted for the caller.select Note { id, client_mutation_id, title, body, version, updated_at, deleted_at,}filter (.updated_at, .id) > (<datetime>$since_time, <uuid>$after_id)order by .updated_at asc then .id asclimit <int64>$limit// src/offline/watermarkMirror.tsimport { isGap } from 'napalm-client'import { db, napalm } from '../lib/napalm'import { localDb } from './store' // Dedicated SQLite tables and keyset cursor for large watermark-synced mirrors.localDb.execSync(` CREATE TABLE IF NOT EXISTS mirror_notes ( id TEXT PRIMARY KEY NOT NULL, client_mutation_id TEXT UNIQUE NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS sync_cursor ( feed TEXT PRIMARY KEY NOT NULL, since_time TEXT NOT NULL, after_id TEXT NOT NULL, log_bookmark TEXT );`) const ZERO_TIME = '1970-01-01T00:00:00Z'const ZERO_UUID = '00000000-0000-0000-0000-000000000000' /** Pulls committed inserts, edits and soft-deletes using deployed queries under passthrough: none. */export async function pullNotesWatermark() { const cursor = localDb.getFirstSync<{ since_time: string; after_id: string }>( "SELECT since_time, after_id FROM sync_cursor WHERE feed = 'notes'", ) ?? { since_time: ZERO_TIME, after_id: ZERO_UUID } let sinceTime = cursor.since_time let afterId = cursor.after_id for (;;) { const { data, error } = await db.POST('/query/notesSince', { body: { variables: { since_time: sinceTime, after_id: afterId, limit: 250 } }, }) if (error) throw new Error(error.error.message ?? error.error.code) const batch = data.data if (batch.length === 0) break const last = batch[batch.length - 1] localDb.withTransactionSync(() => { for (const row of batch) { if (row.deleted_at) { localDb.runSync('DELETE FROM mirror_notes WHERE id = ?', [row.id]) } else { localDb.runSync( `INSERT INTO mirror_notes (id, client_mutation_id, title, body, version, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET title = excluded.title, body = excluded.body, version = excluded.version, updated_at = excluded.updated_at`, [row.id, row.client_mutation_id, row.title, row.body, row.version, row.updated_at], ) } } localDb.runSync( `INSERT INTO sync_cursor (feed, since_time, after_id) VALUES ('notes', ?, ?) ON CONFLICT(feed) DO UPDATE SET since_time = excluded.since_time, after_id = excluded.after_id`, [last.updated_at, last.id], ) }) sinceTime = last.updated_at afterId = last.id }} /** Optional tail over GET /changes when endpoint passthrough permits authenticated callers. */export async function tailChangeLog() { const saved = localDb.getFirstSync<{ log_bookmark: string | null }>( "SELECT log_bookmark FROM sync_cursor WHERE feed = 'notes'", ) const start = saved?.log_bookmark ? { after: saved.log_bookmark } : { since: new Date(Date.now() - 60_000).toISOString() } for await (const page of napalm.changes({ types: ['Note'], ...start, limit: 250 })) { let needsFullPull = false for (const item of page.items) { if (isGap(item) || !item.has_every_row) { needsFullPull = true continue } for (const row of item.rows) { if (row.op === 'delete') { localDb.runSync('DELETE FROM mirror_notes WHERE id = ?', [row.id]) } } } if (needsFullPull) await pullNotesWatermark() if (page.next) { localDb.runSync("UPDATE sync_cursor SET log_bookmark = ? WHERE feed = 'notes'", [page.next]) } }}Queue and replay offline writes#
When the person creates or edits a note, write an entry to mutation_outbox first and render the merged list immediately. Trigger flushOutbox() right away when online, and again whenever network reachability or foreground state returns.
// src/offline/outbox.tsimport { db } from '../lib/napalm'import { localDb } from './store' export function enqueueNoteCreate(mutationId: string, title: string, body: string) { localDb.runSync( `INSERT INTO mutation_outbox (mutation_id, kind, target_id, expected_version, title, body) VALUES (?, 'create', ?, NULL, ?, ?)`, [mutationId, mutationId, title, body], )} export function enqueueNoteEdit(mutationId: string, noteId: string, expectedVersion: number, title: string, body: string) { localDb.runSync( `INSERT INTO mutation_outbox (mutation_id, kind, target_id, expected_version, title, body) VALUES (?, 'update', ?, ?, ?, ?)`, [mutationId, noteId, expectedVersion, title, body], )} /** Replays pending offline mutations in commit order and isolates policy or version conflicts. */export async function flushOutbox(): Promise<void> { const pending = localDb.getAllSync<{ seq: number mutation_id: string kind: 'create' | 'update' | 'archive' target_id: string expected_version: number | null title: string body: string }>("SELECT seq, mutation_id, kind, target_id, expected_version, title, body FROM mutation_outbox WHERE status = 'pending' ORDER BY seq ASC") for (const item of pending) { if (item.kind === 'create') { const { data, error } = await db.POST('/query/createNoteOffline', { body: { variables: { mutation_id: item.mutation_id, title: item.title, body: item.body } }, }) if (error) { if (error.error.code === 'query_failed' || error.error.code === 'invalid_request') { markConflict(item.seq, error.error.message ?? error.error.code) continue } // Network or 503 availability error: leave pending and retry on the next reconnect. return } const committed = data.data[0] localDb.withTransactionSync(() => { // Rewrite any queued follow-up edits that targeted the temporary offline UUID. localDb.runSync('UPDATE mutation_outbox SET target_id = ? WHERE target_id = ?', [ committed.id, item.mutation_id, ]) localDb.runSync('DELETE FROM mutation_outbox WHERE seq = ?', [item.seq]) }) continue } if (item.kind === 'update') { const { data, error } = await db.POST('/query/saveNoteVersioned', { body: { variables: { id: item.target_id, expected_version: item.expected_version!, title: item.title, body: item.body, }, }, }) if (error) { if (error.error.code === 'query_failed' || error.error.code === 'invalid_request') { markConflict(item.seq, error.error.message ?? error.error.code) continue } return } if (data.data.length === 0) { markConflict(item.seq, 'Another device saved a newer version while this device was offline.') continue } localDb.runSync('DELETE FROM mutation_outbox WHERE seq = ?', [item.seq]) } } // Active sync subscriptions receive each committed write as an SSE patch, and // napalm.bookmark advances so any subscription opened later includes replayed writes.} function markConflict(seq: number, message: string) { localDb.runSync("UPDATE mutation_outbox SET status = 'conflict', error_message = ? WHERE seq = ?", [ message, seq, ])}- Sequential replay
- Replay outbox entries one at a time in
seqorder rather than withPromise.allso an offline create finishes before a queued edit to that same note runs. - Temporary IDs
- Offline creates use
mutation_idas the temporary local note ID. OncecreateNoteOfflinereturns the serverid, rewritetarget_idon any later queued edits in the same local transaction. - Read-your-writes
dbusesnapalm.fetch, so every replayed write movesnapalm.bookmarkforward. The open sync receives each committed note as a patch. A sync opened later starts at or past the last write.
Resolve conflicts and refused writes#
Offline writes run against the current server state when replayed, which may be minutes or hours after the person drafted the change. Separate transient network drops from deterministic server refusals so one stale draft never blocks newer items behind it in the outbox.
| Replay outcome | Cause | Outbox action |
|---|---|---|
| Network error or 503 | Device entered an elevator, tunnel or brief cluster failover. | Outbox actionKeep status = pending and stop flushOutbox(). Retry with backoff or on the next connectivity event. |
400 query_failed | An access policy revoked write permission (for example, workspace admin removed the member) or a schema constraint failed. | Outbox actionMark the entry status = conflict with error.message and continue replaying unrelated items. |
| Empty update result | Another device committed a newer version or archived the row while this device was offline. | Outbox actionMark the entry status = conflict. The synced store already holds the server version. Let the person keep the local draft or accept the server version. |
401 invalid_session | The user’s session expired and refresh token was revoked while offline. | Outbox actionPause outbox replay without deleting pending drafts until the same identity_id signs back in. |
Clear local storage on sign-out#
NapalmClient clears open sync stores automatically when the active session changes or signs out. Closed sync stores and custom tables such as mutation_outbox remain on disk until your app deletes those rows. Route sign-out through signOut() below to wipe local tables first, and call bindLocalOwner() on startup so a shared device clears prior data whenever a different identity_id signs in.
// src/offline/localOwner.tsimport { signIn } from '../lib/napalm'import { localDb, notesStore } from './store' /** Clears cached sync rows, pending outbox mutations and the recorded owner from SQLite. */export async function wipeLocal() { localDb.execSync('DELETE FROM mutation_outbox; DELETE FROM local_owner;') await notesStore.clear()} /** Wipes local SQLite tables before revoking the session on the server. */export async function signOut() { await wipeLocal() await signIn.signOut()} /** Clears local data when a different account signs in while preserving drafts for the same user. */export function bindLocalOwner() { return signIn.onChange((session) => { if (!session) return const owner = localDb.getFirstSync<{ identity_id: string }>('SELECT identity_id FROM local_owner') if (owner?.identity_id === session.identity_id) return void wipeLocal().then(() => localDb.runSync('INSERT OR REPLACE INTO local_owner (id, identity_id) VALUES (1, ?)', [session.identity_id]), ) })}Recording local_owner preserves unsent drafts if a session expires and the same person signs back in, while wiping local tables immediately when a different user signs in on a shared tablet.
Check offline sync in airplane mode#
Cold-launch the app in airplane mode
Sign in once while online so the sync fills
napalm_sync_rows. Force-quit the app, enable airplane mode and reopen the app. The notes list renders from SQLite with zero network requests, andisStoredis true.Archive a note on the web while the phone is offline
Take the phone offline, archive a note on the web app and reconnect the phone. The reconnect frame omits the archived note’s ID from
order, removing the note from both the screen and SQLite.Create and edit the same note while offline
Add a note and edit that note’s body while airplane mode stays on.
readVisibleNotes(rows)shows the note withsyncState: 'pending'. Disable airplane mode and watchflushOutbox()create the note, rewritetarget_id, apply the follow-up edit and clear the pending badge.Replay an already-committed create
Call
createNoteOfflinetwice with the samemutation_idfromnapalm call. Both calls return the singleNoteUUID without duplicating the row.Trigger a version conflict across two devices
Take the phone offline, edit a note on the web app so
versionadvances to2, then edit the same note on the offline phone atexpected_version: 1and reconnect.saveNoteVersionedreturns zero rows, and the phone surfaces the conflict state instead of overwriting the web edit.Sign out and inspect local SQLite
Call
signOut()fromlocalOwner.ts. Confirmnapalm_sync_rows,napalm_sync_storesandmutation_outboxall report zero rows.
Next steps#
- React Native
- Pair Expo Keychain sessions, foreground live queries and resumable disk uploads with SQLite caching.
- Flutter
- Wire generated Dart Chopper clients, lifecycle-aware streams and local SQLite mirrors on iOS and Android.
- Realtime & collaboration
- Combine optimistic UI updates, fractional list ordering and live presence rooms while online.
- Warehouse sync
- Run server-to-server change-log replication with read-only service keys and webhook wakeups.