Offline-First Architecture

Article · 3:00

An app that works on the underground - a local database as the source of truth, and a queue that syncs later.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

A mobile app runs on a network that disappears. The usual design - fetch on mount, show a spinner, show an error - produces an app that is useless in a lift and loses whatever the reader typed in a tunnel. Offline-first inverts it: the local database is the source of truth, the interface only ever reads from it, and the network is a background process that reconciles.

The change this forces on the interface is that a write must succeed immediately. Saving a note writes to the local store, the screen updates, and the row is marked as not yet synced. The reader never waits for a server.

SQLite through expo-sqlite is the straightforward option, and drizzle gives you typed queries over it. WatermelonDB is built for this pattern specifically - lazy loading, observable queries, and a sync protocol with the pull-and-push shape already defined.

The hard part is not storage, it is conflict. Two devices edit the same record offline and both come back. Last-write-wins is simple and silently loses data. Keeping a changed-fields list merges better. A per-record version number lets the server detect the conflict and refuse. Choose deliberately, and write down what happens when two people edit the same thing - because it will happen, and the answer should not be an accident.

TS Example 1 58 lines
import * as SQLite from 'expo-sqlite';
import NetInfo from '@react-native-community/netinfo';

const db = await SQLite.openDatabaseAsync('app.db');

await db.execAsync(`
  CREATE TABLE IF NOT EXISTS notes (
    id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    updated_at INTEGER NOT NULL,
    version INTEGER NOT NULL DEFAULT 0,
    pending INTEGER NOT NULL DEFAULT 0
  );
  CREATE INDEX IF NOT EXISTS notes_pending ON notes (pending);
`);

// A write NEVER waits for the network. It lands locally and is queued.
export async function saveNote(note: { id: string; title: string; body: string }) {
  await db.runAsync(
    `INSERT INTO notes (id, title, body, updated_at, pending)
     VALUES (?, ?, ?, ?, 1)
     ON CONFLICT(id) DO UPDATE SET
       title = excluded.title, body = excluded.body,
       updated_at = excluded.updated_at, pending = 1`,
    [note.id, note.title, note.body, Date.now()],
  );
}

// The queue drains whenever a connection appears.
export function startSync() {
  return NetInfo.addEventListener(async (state) => {
    if (!state.isConnected) return;

    const queued = await db.getAllAsync<Note>('SELECT * FROM notes WHERE pending = 1');

    for (const note of queued) {
      try {
        // The version lets the SERVER detect a conflict and refuse, rather
        // than one device silently overwriting the other.
        const saved = await api<Note>(`/notes/${note.id}`, {
          method: 'PUT',
          body: { ...note, version: note.version },
        });
        await db.runAsync(
          'UPDATE notes SET pending = 0, version = ? WHERE id = ?',
          [saved.version, note.id],
        );
      } catch (error) {
        if (error instanceof ApiError && error.status === 409) {
          // Conflict. Decide here - and decide it deliberately.
          await markForManualMerge(note.id);
        }
        break;    // stop draining; try again on the next connection
      }
    }
  });
}

Open this example in the editor and change it. Nothing you type is saved.