Skip to main content

Mobile development · Advanced · 28 min

Sync Larkfield bookings offline first with an outbox queue

By Padding · Updated 18 Nov 2026
Expo SDK 58 · NetInfo 12.0.1 · expo-sqlite 58.0.18 · Node.js 26 (node:26)

You will have a Larkfield app that saves every booking to an SQLite outbox first, sends it to a mock clinic API with an idempotency key when the phone is online or back in the foreground, retries with capped backoff and jitter, and offers the next free slot when a time has gone, all proven by Jest tests.

On this page

A patient on a bus between two masts taps Book. If the app sends the request straight to the clinic and the signal drops, one of three things happened, and the app cannot tell which: the request never left, the clinic got it and the answer was lost, or the clinic is down. Retrying blindly can book the same slot twice. Giving up loses the booking.

The fix is an outbox. Part 3 already saves each booking in the phone's appointments table, so the patient sees it on the Appointments tab at once. In this part the same submit also writes an outbox row with the status pending and a random idempotency key, in one transaction. A separate sync function reads pending rows and sends them with that key in an Idempotency-Key header. The clinic remembers every key it has answered, so a repeat of the same request gets the same answer back instead of a second booking. The sync runs when NetInfo reports a connection, when the app comes back to the foreground, and on a timer that backs off after each failure.

The clinic's real system does not exist yet, so you also write a small Node 26 mock clinic API. Later parts reuse it.

Sequence diagram with four lanes, booking screen, outbox, sync function and clinic API. The booking is saved as pending with key k1, the first POST fails with no signal, the row waits 1 to 2 seconds, the sync runs again when the connection returns, the 201 reply is lost, the retry with the same key gets the replayed 201 for booking bk_1, and the row is marked confirmed
Every send carries the same key, so a lost reply never creates a second booking

Step 1 · Add NetInfo and expo-crypto

NetInfo tells the app when the phone has a connection. expo-crypto makes the random idempotency keys. npx expo install picks the versions that match Expo SDK 58, which for NetInfo is 12.0.1. The tests reuse better-sqlite3 and the in-memory database from part 3, so there is nothing else to add:

Bash
cd ~/larkfield-app-demo
npx expo install @react-native-community/netinfo expo-crypto

Check it worked

Bash
cd ~/larkfield-app-demo
npm ls @react-native-community/netinfo expo-crypto

The tree lists @react-native-community/netinfo@12.0.1 and an expo-crypto@58.0.x release. An UNMET or invalid line means the install did not finish; run it again.

Step 2 · Create the outbox as migration 3

The outbox is a table of things the app still owes the server. Each row holds the booking as JSON, its idempotency key, a status, how many sends have failed, and when it may be tried next. There is no sending status on purpose: if the app is killed halfway through a send, a row stuck in sending would never go out again. The row stays pending until the server answers, and the idempotency key makes a repeat harmless.

The booking carries appointmentId, the row in part 3's appointments table, so the sync can cancel that row if the clinic turns the booking down. It also carries the phone number and date of birth the clinic needs. Those are personal data, so once the clinic confirms a booking the sync removes them from the outbox row; the phone keeps only what the patient sees.

Everything goes through part 3's Db interface, with values always bound as parameters. The sync files import each other with relative paths, because Jest loads them too. Create src/sync/outbox.ts:

Bash
cd ~/larkfield-app-demo
mkdir -p src/sync
cat > src/sync/outbox.ts <<'TS'
import type { Db } from '../db/types'

export type BookingRequest = {
  appointmentId: number // the row in the appointments table on this phone
  serviceId: string
  practitionerId: string
  startsAt: string // ISO 8601 in UTC, from Date.toISOString()
  patientName: string
  phone: string // E.164, from the part 2 schema
  dateOfBirth: string // YYYY-MM-DD
  reason: string
}

export type OutboxStatus = 'pending' | 'confirmed' | 'rejected'

export type OutboxRow = {
  id: number
  idempotency_key: string
  payload: string
  status: OutboxStatus
  attempts: number
  next_attempt_at: number
  last_error: string | null
  server_id: string | null
  reject_reason: string | null
  suggested_slot: string | null
  created_at: number
  updated_at: number
}

// Migration 3. Runs once, inside the migration's transaction.
export async function createOutboxTable(db: Db) {
  await db.execAsync(`
    CREATE TABLE outbox (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      idempotency_key TEXT NOT NULL UNIQUE,
      payload TEXT NOT NULL,
      status TEXT NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'confirmed', 'rejected')),
      attempts INTEGER NOT NULL DEFAULT 0,
      next_attempt_at INTEGER NOT NULL DEFAULT 0,
      last_error TEXT,
      server_id TEXT,
      reject_reason TEXT,
      suggested_slot TEXT,
      created_at INTEGER NOT NULL,
      updated_at INTEGER NOT NULL
    );
    CREATE INDEX outbox_status_next_attempt ON outbox (status, next_attempt_at);
  `)
}

type Stamp = { idempotencyKey: string; now: number }

export async function enqueueBooking(db: Db, booking: BookingRequest, { idempotencyKey, now }: Stamp) {
  await db.runAsync(
    'INSERT INTO outbox (idempotency_key, payload, created_at, updated_at) VALUES (?, ?, ?, ?)',
    [idempotencyKey, JSON.stringify(booking), now, now],
  )
}

export function listOutbox(db: Db) {
  return db.getAllAsync<OutboxRow>('SELECT * FROM outbox ORDER BY id DESC', [])
}

export function getOutboxRow(db: Db, idempotencyKey: string) {
  return db.getFirstAsync<OutboxRow>('SELECT * FROM outbox WHERE idempotency_key = ?', [idempotencyKey])
}

// The patient accepts the slot the clinic suggested. It is a new request, so it gets a new key.
export async function rebookAtSuggestedSlot(db: Db, row: OutboxRow, stamp: Stamp) {
  if (row.status !== 'rejected' || !row.suggested_slot) {
    throw new Error('This booking has no suggested slot')
  }
  const booking: BookingRequest = { ...JSON.parse(row.payload), startsAt: row.suggested_slot }
  await db.withTransactionAsync(async () => {
    await db.runAsync('DELETE FROM outbox WHERE id = ?', [row.id])
    await db.runAsync("UPDATE appointments SET starts_at = ?, status = 'booked' WHERE id = ?", [
      booking.startsAt,
      booking.appointmentId,
    ])
    await enqueueBooking(db, booking, stamp)
  })
}
TS

Times in the outbox are milliseconds since 1970 from the phone's clock. They only decide when this phone tries again; the clinic never trusts them.

Now add the table to src/db/migrations.ts as entry 3, after the two entries from part 3. Do not change or reorder those: phones that already ran them have the number stored in PRAGMA user_version, and the position in the array is the version.

TypeScript
import { createOutboxTable } from '../sync/outbox'

export const migrations: Migration[] = [
  // 1 and 2 from part 3 stay exactly as they are
  // 3: the outbox for bookings waiting to reach the clinic
  createOutboxTable,
]

Check it worked

Bash
cd ~/larkfield-app-demo
grep -n "createOutboxTable" src/db/migrations.ts

The output shows the import line and the new array entry. The next time the app opens the database, part 3's migrate runs entry 3 once and sets user_version to 3.

Step 3 · Write the mock clinic API

The mock API does what the app depends on. It keeps one booking per practitioner and time, and answers 409 slot_taken with the next free half hour when a slot has gone. It stores the answer it gave for each Idempotency-Key: a repeat with the same key and the same body gets that answer back, marked replayed, and the same key with a different body is refused with 422, because that is a bug in the app, not a retry. It only stores final answers. A 503 is not stored, so a retry after the clinic recovers is processed for real.

There is no sign-in yet, so the patient is named by an X-Patient-Id header, demo-patient when it is missing. GET /appointments/:id answers 404 both for an unknown booking and for someone else's, which part 6 relies on. Two development routes, /__reset and /__fail-next, let the tests start clean and force one 503. Create mock-api/server.mjs:

Bash
cd ~/larkfield-app-demo
mkdir -p mock-api
cat > mock-api/server.mjs <<'JS'
import { createServer } from 'node:http'

const HOST = process.env.HOST ?? '127.0.0.1'
const PORT = Number(process.env.PORT ?? 4010)
const SLOT_MINUTES = 30

let bookings, slots, answers, failNext, nextId
function reset() {
  bookings = new Map() // booking id -> booking
  slots = new Map() // "practitioner|startsAt" -> booking id
  answers = new Map() // idempotency key -> { raw, status, payload }
  failNext = 0
  nextId = 1
}
reset()

function send(res, status, payload) {
  const body = JSON.stringify(payload)
  res.writeHead(status, {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type, Idempotency-Key, X-Patient-Id',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  })
  res.end(body)
}

async function readText(req) {
  let text = ''
  for await (const chunk of req) text += chunk
  return text
}

function nextFreeSlot(practitionerId, startsAt) {
  let time = Date.parse(startsAt)
  for (let i = 0; i < 48; i++) {
    time += SLOT_MINUTES * 60_000
    const iso = new Date(time).toISOString()
    if (!slots.has(`${practitionerId}|${iso}`)) return iso
  }
  return null
}

function book(patientId, body) {
  const { serviceId, practitionerId, startsAt, patientName } = body
  const required = [serviceId, practitionerId, startsAt, patientName]
  if (!required.every((v) => typeof v === 'string' && v.length > 0) || Number.isNaN(Date.parse(startsAt))) {
    return { status: 422, payload: { error: 'invalid_booking' } }
  }
  const at = new Date(startsAt).toISOString()
  const slotKey = `${practitionerId}|${at}`
  if (slots.has(slotKey)) {
    return { status: 409, payload: { error: 'slot_taken', nextSlot: nextFreeSlot(practitionerId, at) } }
  }
  const booking = { id: `bk_${nextId++}`, patientId, serviceId, practitionerId, startsAt: at, patientName }
  bookings.set(booking.id, booking)
  slots.set(slotKey, booking.id)
  return { status: 201, payload: booking }
}

createServer(async (req, res) => {
  const { pathname } = new URL(req.url, 'http://clinic.invalid')
  const patientId = req.headers['x-patient-id'] ?? 'demo-patient'
  if (req.method === 'OPTIONS') return send(res, 204, {})
  if (req.method === 'GET' && pathname === '/health') return send(res, 200, { ok: true })
  if (req.method === 'GET' && pathname === '/bookings') return send(res, 200, [...bookings.values()])
  if (req.method === 'GET' && pathname.startsWith('/appointments/')) {
    const booking = bookings.get(decodeURIComponent(pathname.slice('/appointments/'.length)))
    if (!booking || booking.patientId !== patientId) return send(res, 404, { error: 'not_found' })
    return send(res, 200, booking)
  }
  if (req.method === 'POST' && pathname === '/__reset') { reset(); return send(res, 200, { ok: true }) }
  if (req.method === 'POST' && pathname === '/__fail-next') { failNext += 1; return send(res, 200, { failNext }) }
  if (req.method !== 'POST' || pathname !== '/bookings') return send(res, 404, { error: 'not_found' })

  const key = req.headers['idempotency-key']
  if (typeof key !== 'string' || key.length < 8) return send(res, 400, { error: 'idempotency_key_required' })
  const raw = await readText(req)
  const seen = answers.get(key)
  if (seen) {
    if (seen.raw !== raw) return send(res, 422, { error: 'idempotency_key_reused' })
    return send(res, seen.status, { ...seen.payload, replayed: true })
  }
  if (failNext > 0) { failNext -= 1; return send(res, 503, { error: 'try_again' }) }
  let body
  try { body = JSON.parse(raw) } catch { return send(res, 400, { error: 'invalid_json' }) }
  const answer = book(patientId, body)
  answers.set(key, { raw, ...answer })
  send(res, answer.status, answer.payload)
}).listen(PORT, HOST, () => console.log(`Mock clinic API on http://${HOST}:${PORT}`))
JS

Start it in your second terminal, from ~/larkfield-app-demo, and leave it running:

Bash
cd ~/larkfield-app-demo
node mock-api/server.mjs

It prints Mock clinic API on http://127.0.0.1:4010. It keeps everything in memory, has no real authentication, and listens only on this machine. It is for development and nothing else.

Check it worked

Back in the first terminal, send the same booking twice with the same key, which is what a retry after a lost reply looks like, then ask for the booking as its patient and as someone else:

Bash
curl -s -X POST http://127.0.0.1:4010/bookings -H 'Content-Type: application/json' -H 'Idempotency-Key: demo-key-0001' -d '{"serviceId":"physio-30","practitionerId":"dr-okafor","startsAt":"2026-12-01T09:00:00.000Z","patientName":"Amina Bello"}'; echo
curl -s -X POST http://127.0.0.1:4010/bookings -H 'Content-Type: application/json' -H 'Idempotency-Key: demo-key-0001' -d '{"serviceId":"physio-30","practitionerId":"dr-okafor","startsAt":"2026-12-01T09:00:00.000Z","patientName":"Amina Bello"}'; echo
curl -s http://127.0.0.1:4010/bookings | grep -o '"id":"bk_[0-9]*"'
curl -s -o /dev/null -w '%{http_code}\n' -H 'X-Patient-Id: someone-else' http://127.0.0.1:4010/appointments/bk_1
curl -s -X POST http://127.0.0.1:4010/__reset; echo

Both POSTs answer with booking bk_1, and the second ends with "replayed":true. The list prints "id":"bk_1" once: one booking, not two. The request as someone-else prints 404. The last line clears the server for the tests.

Step 4 · Decide which failures are retried

Not every failure deserves a retry. No reply at all, 408, 429 and any 5xx mean try again later. 409 slot_taken and other 4xx answers are final: the same request will get the same answer, so the row is marked rejected and the patient is told.

Retries wait longer each time, up to a cap, with jitter. Without the doubling, a phone in a dead zone wakes the radio every few seconds and drains the battery and the data bundle. Without the cap, a row that failed twenty times would wait for weeks. Without jitter, every phone that lost signal when a mast went down retries at the same moment when it comes back, and the clinic's server takes the whole crowd at once.

The rule here: wait between half and all of 2 seconds × 2 to the power of the failures so far, and never more than 5 minutes. Create src/sync/backoff.ts:

Bash
cd ~/larkfield-app-demo
cat > src/sync/backoff.ts <<'TS'
export const BASE_DELAY_MS = 2_000
export const MAX_DELAY_MS = 5 * 60_000

// attempts is how many sends have already failed: 0 before the first retry.
export function retryDelayMs(attempts: number, random: () => number = Math.random): number {
  const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempts)
  return Math.round(ceiling / 2 + random() * (ceiling / 2))
}

export function isRetryableStatus(status: number): boolean {
  return status === 408 || status === 429 || status >= 500
}
TS

The sync code sends through a Transport: a function that takes a URL, headers and a body, and returns the status and the parsed JSON. The app's transport uses fetch with a 15-second timeout. The tests use Node's own http module instead, because jest-expo replaces the global fetch with Expo's native fetch, which has no native side to run on under Jest. Create src/sync/transport.ts and the API address in src/sync/config.ts:

Bash
cd ~/larkfield-app-demo
cat > src/sync/transport.ts <<'TS'
export type TransportRequest = { url: string; headers: Record<string, string>; body: string }
export type TransportResponse = { status: number; data: unknown }
export type Transport = (request: TransportRequest) => Promise<TransportResponse>

const TIMEOUT_MS = 15_000

export const fetchTransport: Transport = async ({ url, headers, body }) => {
  const controller = new AbortController()
  const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
  try {
    const response = await fetch(url, { method: 'POST', headers, body, signal: controller.signal })
    const text = await response.text()
    let data: unknown = null
    try {
      data = text ? JSON.parse(text) : null
    } catch {
      data = null
    }
    return { status: response.status, data }
  } finally {
    clearTimeout(timer)
  }
}
TS
cat > src/sync/config.ts <<'TS'
// Set EXPO_PUBLIC_CLINIC_API_URL when you start Expo. Expo builds it into the app bundle.
export const CLINIC_API_URL = process.env.EXPO_PUBLIC_CLINIC_API_URL ?? 'http://127.0.0.1:4010'
TS

The address is not a secret, and nothing secret belongs in an EXPO_PUBLIC_ variable: Expo inlines those values into the bundle, where anyone with the app can read them.

Check it worked

Bash
cd ~/larkfield-app-demo
ls src/sync

The folder holds backoff.ts, config.ts, outbox.ts and transport.ts. A later step proves the rules with tests.

Step 5 · Write the sync function

syncOutbox reads the rows that are due, sends them oldest first, and records each answer. Five details matter:

  • One sync at a time. NetInfo and AppState often fire together when a phone wakes up. A second call while a sync is running gets the running sync's promise instead of starting another.
  • Stop at the first failure that needs a retry. If one send got no reply, the next will not get one either; the rest stay due for the next trigger.
  • A rejection cancels the matching appointment on the phone in the same transaction, so the Appointments tab from part 3 never shows a booking the clinic refused.
  • The result includes nextAttemptAt, the earliest time a pending row may be tried again, so the app can set a timer.
  • A row scheduled further ahead than the 5-minute cap counts as due. That only happens when the phone's clock was wrong and has been put back; without this, the booking could wait for hours.

Create src/sync/sync-outbox.ts:

Bash
cd ~/larkfield-app-demo
cat > src/sync/sync-outbox.ts <<'TS'
import type { Db } from '../db/types'
import { isRetryableStatus, MAX_DELAY_MS, retryDelayMs } from './backoff'
import type { BookingRequest, OutboxRow } from './outbox'
import type { Transport, TransportResponse } from './transport'

export type SyncOptions = {
  baseUrl: string
  transport: Transport
  now?: () => number
  random?: () => number
}

export type SyncResult = {
  attempted: number
  confirmed: number
  rejected: number
  retrying: number
  nextAttemptAt: number | null
}

type Outcome =
  | { kind: 'confirmed'; serverId: string }
  | { kind: 'rejected'; reason: string; suggestedSlot: string | null }
  | { kind: 'retry'; error: string }

let inFlight: Promise<SyncResult> | null = null

export function syncOutbox(db: Db, options: SyncOptions): Promise<SyncResult> {
  if (!inFlight) {
    inFlight = runSync(db, options).finally(() => {
      inFlight = null
    })
  }
  return inFlight
}

function classify({ status, data }: TransportResponse): Outcome {
  const body = (data ?? {}) as { id?: unknown; error?: unknown; nextSlot?: unknown }
  if ((status === 200 || status === 201) && typeof body.id === 'string') {
    return { kind: 'confirmed', serverId: body.id }
  }
  if (status < 400 || isRetryableStatus(status)) return { kind: 'retry', error: `http ${status}` }
  return {
    kind: 'rejected',
    reason: typeof body.error === 'string' ? body.error : `http_${status}`,
    suggestedSlot: status === 409 && typeof body.nextSlot === 'string' ? body.nextSlot : null,
  }
}

async function record(db: Db, row: OutboxRow, outcome: Outcome, at: number, random: () => number) {
  if (outcome.kind === 'confirmed') {
    // The clinic has the booking: drop the personal details the phone no longer needs to send.
    await db.runAsync(
      `UPDATE outbox SET status = 'confirmed', server_id = ?, last_error = NULL, updated_at = ?,
         payload = json_remove(payload, '$.phone', '$.dateOfBirth')
       WHERE id = ?`,
      [outcome.serverId, at, row.id],
    )
  } else if (outcome.kind === 'rejected') {
    const booking = JSON.parse(row.payload) as BookingRequest
    await db.withTransactionAsync(async () => {
      await db.runAsync(
        "UPDATE outbox SET status = 'rejected', reject_reason = ?, suggested_slot = ?, updated_at = ? WHERE id = ?",
        [outcome.reason, outcome.suggestedSlot, at, row.id],
      )
      await db.runAsync("UPDATE appointments SET status = 'cancelled' WHERE id = ?", [booking.appointmentId])
    })
  } else {
    await db.runAsync(
      'UPDATE outbox SET attempts = attempts + 1, next_attempt_at = ?, last_error = ?, updated_at = ? WHERE id = ?',
      [at + retryDelayMs(row.attempts, random), outcome.error, at, row.id],
    )
  }
}

async function runSync(db: Db, { baseUrl, transport, now = Date.now, random = Math.random }: SyncOptions) {
  const result: SyncResult = { attempted: 0, confirmed: 0, rejected: 0, retrying: 0, nextAttemptAt: null }
  const start = now()
  const due = await db.getAllAsync<OutboxRow>(
    `SELECT * FROM outbox
     WHERE status = 'pending' AND (next_attempt_at <= ? OR next_attempt_at > ?)
     ORDER BY id`,
    [start, start + MAX_DELAY_MS],
  )

  for (const row of due) {
    result.attempted += 1
    let outcome: Outcome
    try {
      const response = await transport({
        url: `${baseUrl}/bookings`,
        headers: { 'Content-Type': 'application/json', 'Idempotency-Key': row.idempotency_key },
        body: row.payload,
      })
      outcome = classify(response)
    } catch (error) {
      outcome = { kind: 'retry', error: `network: ${error instanceof Error ? error.message : String(error)}` }
    }
    await record(db, row, outcome, now(), random)
    if (outcome.kind === 'retry') {
      result.retrying += 1
      break
    }
    result[outcome.kind] += 1
  }

  const next = await db.getFirstAsync<{ at: number | null }>(
    "SELECT MIN(next_attempt_at) AS at FROM outbox WHERE status = 'pending'",
    [],
  )
  result.nextAttemptAt = next?.at ?? null
  return result
}
TS

The network call happens outside any transaction. Part 3 explained why: expo-sqlite's transaction is not exclusive, and holding one open across a slow request would pull unrelated queries into it.

Why last write wins is fine here, and when it is not

Each outbox row has one writer, this patient on this phone, and the server's answer is final. Overwriting the row's status with whatever arrived last is the right rule for it. The contested thing, the slot, is never decided on the phone. Two patients can both see 09:00 as free while offline; the clinic keeps one booking per practitioner and time, accepts whichever request arrives first and answers 409 to the other. Last write wins would be wrong there, because it would silently push the first patient out.

It is also wrong for data that two people or two devices edit, such as a note changed on a phone and at the reception desk: the later save throws the other away. That needs a version number the server checks, or merges field by field, which this app does not need yet.

Clock skew is the other trap. A phone's clock can be minutes or days out, especially after the battery has run flat or when the owner sets the time by hand. So the phone's clock only schedules its own retries, the server never decides anything from a time the phone sends, and the sync treats a retry time beyond the cap as a sign that the clock has moved.

Check it worked

Bash
cd ~/larkfield-app-demo
grep -c "Idempotency-Key" src/sync/sync-outbox.ts

The count is 1: every send goes through the one place that sets the header.

Step 6 · Test offline, duplicate sends and a taken slot

The tests run the real sync function on part 3's in-memory SQLite database, with every migration applied, against the mock API in your second terminal. One helper is new: a transport built on Node's http module, plus a small getJson for asking the server what it holds. Put it in src/sync/testing, next to nothing that ships in the app:

Bash
cd ~/larkfield-app-demo
mkdir -p src/sync/testing
cat > src/sync/testing/node-transport.ts <<'TS'
import { get, request } from 'node:http'
import type { Transport } from '../transport'

// For tests only. The app uses fetchTransport.
function parse(text: string): unknown {
  return text ? JSON.parse(text) : null
}

export const nodeTransport: Transport = ({ url, headers, body }) =>
  new Promise((resolve, reject) => {
    const req = request(
      url,
      { method: 'POST', headers: { ...headers, 'Content-Length': String(Buffer.byteLength(body)) } },
      (res) => {
        let text = ''
        res.setEncoding('utf8')
        res.on('data', (chunk) => (text += chunk))
        res.on('end', () => resolve({ status: res.statusCode ?? 0, data: parse(text) }))
      },
    )
    req.on('error', reject)
    req.setTimeout(5_000, () => req.destroy(new Error('timed out')))
    req.end(body)
  })

export function getJson<T>(url: string): Promise<T> {
  return new Promise((resolve, reject) => {
    get(url, (res) => {
      let text = ''
      res.setEncoding('utf8')
      res.on('data', (chunk) => (text += chunk))
      res.on('end', () => resolve(parse(text) as T))
    }).on('error', reject)
  })
}
TS

"Offline" in these tests is a real refused connection: nothing listens on port 9 of your own machine. "Duplicate send" posts the request once by hand, as if the phone had sent it and lost the reply, and then lets the sync send it again. Write src/sync/backoff.test.ts and src/sync/sync-outbox.test.ts:

Bash
cd ~/larkfield-app-demo
cat > src/sync/backoff.test.ts <<'TS'
import { MAX_DELAY_MS, isRetryableStatus, retryDelayMs } from './backoff'

test('the first retry waits between 1 and 2 seconds', () => {
  expect(retryDelayMs(0, () => 0)).toBe(1_000)
  expect(retryDelayMs(0, () => 0.999)).toBeLessThanOrEqual(2_000)
})

test('the wait doubles and stops at the cap', () => {
  expect(retryDelayMs(3, () => 0)).toBe(8_000)
  expect(retryDelayMs(30, () => 0)).toBe(MAX_DELAY_MS / 2)
  expect(retryDelayMs(30, () => 0.999)).toBeLessThanOrEqual(MAX_DELAY_MS)
})

test('only temporary failures are retried', () => {
  expect([408, 429, 500, 503].every(isRetryableStatus)).toBe(true)
  expect([400, 404, 409, 422].some(isRetryableStatus)).toBe(false)
})
TS
cat > src/sync/sync-outbox.test.ts <<'TS'
import { addAppointment } from '../db/appointments'
import { migrate } from '../db/migrations'
import { openMemoryDb } from '../db/testing/memory-db'
import type { Db } from '../db/types'
import { enqueueBooking, getOutboxRow, rebookAtSuggestedSlot, type OutboxRow } from './outbox'
import { syncOutbox } from './sync-outbox'
import { getJson, nodeTransport } from './testing/node-transport'

const API = process.env.CLINIC_API_URL ?? 'http://127.0.0.1:4010'
const OFFLINE = 'http://127.0.0.1:9'
const NOW = Date.parse('2026-11-30T08:00:00.000Z')
const NINE = '2026-12-01T09:00:00.000Z'

const options = (baseUrl: string, now: number) => ({
  baseUrl,
  transport: nodeTransport,
  now: () => now,
  random: () => 0,
})

let db: Db

beforeEach(async () => {
  await nodeTransport({ url: `${API}/__reset`, headers: {}, body: '' })
  db = openMemoryDb()
  await migrate(db)
})

// What the booking screen does: the appointment and its outbox row, together.
async function book(idempotencyKey: string, startsAt = NINE) {
  await db.withTransactionAsync(async () => {
    const appointmentId = await addAppointment(db, {
      serviceId: 'physio-30',
      serviceName: 'Physiotherapy, 30 minutes',
      practitionerId: 'dr-okafor',
      practitionerName: 'Dr Okafor',
      startsAt,
      patientName: 'Amina Bello',
      reason: 'Knee pain',
    })
    await enqueueBooking(
      db,
      {
        appointmentId,
        serviceId: 'physio-30',
        practitionerId: 'dr-okafor',
        startsAt,
        patientName: 'Amina Bello',
        phone: '+2348031234567',
        dateOfBirth: '1990-04-23',
        reason: 'Knee pain',
      },
      { idempotencyKey, now: NOW },
    )
  })
}

async function row(key: string): Promise<OutboxRow> {
  const found = await getOutboxRow(db, key)
  if (!found) throw new Error(`no outbox row for ${key}`)
  return found
}

const appointmentStatus = async () =>
  (await db.getFirstAsync<{ status: string }>('SELECT status FROM appointments', []))?.status

test('a booking made offline stays pending, backs off, then confirms', async () => {
  await book('key-offline-01')

  const offline = await syncOutbox(db, options(OFFLINE, NOW))
  expect(offline).toMatchObject({ attempted: 1, retrying: 1, nextAttemptAt: NOW + 1_000 })
  expect(await row('key-offline-01')).toMatchObject({ status: 'pending', attempts: 1 })

  const tooSoon = await syncOutbox(db, options(API, NOW + 500))
  expect(tooSoon.attempted).toBe(0)

  const online = await syncOutbox(db, options(API, NOW + 1_000))
  expect(online).toMatchObject({ confirmed: 1, nextAttemptAt: null })
  const confirmed = await row('key-offline-01')
  expect(confirmed).toMatchObject({ status: 'confirmed', server_id: 'bk_1' })
  expect(JSON.parse(confirmed.payload)).not.toHaveProperty('phone')
  expect(JSON.parse(confirmed.payload)).not.toHaveProperty('dateOfBirth')
})

test('a request sent twice books the slot once', async () => {
  await book('key-duplicate-01')
  const pending = await row('key-duplicate-01')
  const first = await nodeTransport({
    url: `${API}/bookings`,
    headers: { 'Content-Type': 'application/json', 'Idempotency-Key': pending.idempotency_key },
    body: pending.payload,
  })
  expect(first.status).toBe(201)

  await syncOutbox(db, options(API, NOW))
  expect(await row('key-duplicate-01')).toMatchObject({ status: 'confirmed', server_id: 'bk_1' })
  expect(await getJson<unknown[]>(`${API}/bookings`)).toHaveLength(1)
})

test('a taken slot cancels the appointment, offers the next slot, and rebooking confirms', async () => {
  await nodeTransport({
    url: `${API}/bookings`,
    headers: { 'Content-Type': 'application/json', 'Idempotency-Key': 'another-patient-01' },
    body: JSON.stringify({ serviceId: 'physio-30', practitionerId: 'dr-okafor', startsAt: NINE, patientName: 'Kwame Mensah' }),
  })
  await book('key-taken-01')

  expect((await syncOutbox(db, options(API, NOW))).rejected).toBe(1)
  const rejected = await row('key-taken-01')
  expect(rejected).toMatchObject({
    status: 'rejected',
    reject_reason: 'slot_taken',
    suggested_slot: '2026-12-01T09:30:00.000Z',
  })
  expect(await appointmentStatus()).toBe('cancelled')

  await rebookAtSuggestedSlot(db, rejected, { idempotencyKey: 'key-taken-02', now: NOW })
  expect(await getOutboxRow(db, 'key-taken-01')).toBeNull()
  expect(await appointmentStatus()).toBe('booked')
  await syncOutbox(db, options(API, NOW))
  expect(await row('key-taken-02')).toMatchObject({ status: 'confirmed', server_id: 'bk_2' })
})

test('a server error is retried later, not rejected', async () => {
  await nodeTransport({ url: `${API}/__fail-next`, headers: {}, body: '' })
  await book('key-503-01')

  await syncOutbox(db, options(API, NOW))
  expect(await row('key-503-01')).toMatchObject({ status: 'pending', attempts: 1, last_error: 'http 503' })
  expect(await appointmentStatus()).toBe('booked')

  await syncOutbox(db, options(API, NOW + 2_000))
  expect(await row('key-503-01')).toMatchObject({ status: 'confirmed' })
})

test('two triggers at once share one sync', async () => {
  await book('key-together-01')
  const fromNetInfo = syncOutbox(db, options(API, NOW))
  const fromAppState = syncOutbox(db, options(API, NOW))
  expect(fromAppState).toBe(fromNetInfo)
  expect((await fromNetInfo).attempted).toBe(1)
})

test('a retry time pushed far ahead by a wrong clock is sent anyway', async () => {
  await book('key-clock-01')
  await syncOutbox(db, options(OFFLINE, NOW + 2 * 60 * 60_000))

  const corrected = await syncOutbox(db, options(API, NOW))
  expect(corrected.confirmed).toBe(1)
})
TS

Run them, with the mock API still running in the second terminal:

Bash
cd ~/larkfield-app-demo
npx jest src/sync

Check it worked

Jest reports two suites and Tests: 9 passed, 9 total. To see a test catch a real mistake, delete '$.phone', ` from the `json_remove call in src/sync/sync-outbox.ts and run npx jest src/sync again: the first sync test fails, because the confirmed row still holds the phone number. Put it back. If the sync tests fail with ECONNREFUSED 127.0.0.1:4010, the mock API is not running; start it again in the second terminal.

Step 7 · Run the sync from the app

Two events start a sync, and a timer covers the retries. NetInfo.addEventListener calls its listener soon after you subscribe and again whenever the connection changes, so it also covers the first run when the app opens. AppState reports active when the patient brings the app back to the foreground. The check is isConnected and isInternetReachable !== false, because reachability is null while NetInfo is still finding out.

Connected is not the same as online. A phone can sit on Wi-Fi behind a captive portal, or on mobile data whose prepaid bundle has just run out, which is a daily event for many patients on pay-as-you-go plans in Lagos or Nairobi. NetInfo may report a connection in both cases. That is why a failed send is treated as normal and simply rescheduled, and NetInfo is only a hint for when to try. Create src/sync/outbox-sync.tsx:

Bash
cd ~/larkfield-app-demo
cat > src/sync/outbox-sync.tsx <<'TSX'
import NetInfo from '@react-native-community/netinfo'
import { useSQLiteContext } from 'expo-sqlite'
import { useEffect } from 'react'
import { AppState } from 'react-native'
import { CLINIC_API_URL } from './config'
import { syncOutbox } from './sync-outbox'
import { fetchTransport } from './transport'

// Renders nothing. Mount it once, inside DatabaseProvider.
export function OutboxSync() {
  const db = useSQLiteContext()

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout> | undefined
    let stopped = false

    const run = async () => {
      if (timer) clearTimeout(timer)
      try {
        const result = await syncOutbox(db, { baseUrl: CLINIC_API_URL, transport: fetchTransport })
        if (!stopped && result.nextAttemptAt !== null) {
          timer = setTimeout(run, Math.max(1_000, result.nextAttemptAt - Date.now()))
        }
      } catch (error) {
        console.warn('Outbox sync failed', error)
      }
    }

    const stopNetInfo = NetInfo.addEventListener((state) => {
      if (state.isConnected && state.isInternetReachable !== false) void run()
    })
    const appState = AppState.addEventListener('change', (next) => {
      if (next === 'active') void run()
    })

    return () => {
      stopped = true
      stopNetInfo()
      appState.remove()
      if (timer) clearTimeout(timer)
    }
  }, [db])

  return null
}
TSX

Mount it once in src/app/_layout.tsx, as the first child of the DatabaseProvider from part 3. Keep everything else in the file as it is:

TSX
import { OutboxSync } from '@/sync/outbox-sync'

// inside RootLayout's return
<DatabaseProvider>
  <OutboxSync />
  <Stack>{/* your screens, unchanged */}</Stack>
</DatabaseProvider>

Then change the booking screen's onSubmit from part 3 so the appointment and its outbox row are written in one transaction: both or neither. The key is made once per booking, when the patient presses Book, never per send. addAppointment and its fields stay as part 3 wrote them; values.phone and values.dateOfBirth come from the part 2 schema, already normalised:

TSX
import * as Crypto from 'expo-crypto'

import { enqueueBooking } from '@/sync/outbox'

async function onSubmit(values: BookingRequest) {
  await db.withTransactionAsync(async () => {
    const appointmentId = await addAppointment(db, {
      // the same fields as in part 3
    })
    await enqueueBooking(
      db,
      {
        appointmentId,
        serviceId: service.id,
        practitionerId: practitioner.id,
        startsAt: slot.toISOString(),
        patientName: values.fullName,
        phone: values.phone,
        dateOfBirth: values.dateOfBirth,
        reason: values.reason,
      },
      { idempotencyKey: Crypto.randomUUID(), now: Date.now() },
    )
  })
  router.replace('/appointments')
}

Use the names your screen already has for service, practitioner and slot, as in part 3.

Last, a screen that shows what is waiting. It says "Saved on your phone" for pending rows and "Booked" for confirmed ones, and for a taken slot it offers the time the clinic suggested. Accepting it moves the appointment to that time, queues a new request and sends it at once. Create src/app/outbox.tsx:

Bash
cd ~/larkfield-app-demo
cat > src/app/outbox.tsx <<'TSX'
import * as Crypto from 'expo-crypto'
import { Stack, useFocusEffect } from 'expo-router'
import { useSQLiteContext } from 'expo-sqlite'
import { useCallback, useState } from 'react'
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native'
import { CLINIC_API_URL } from '@/sync/config'
import { listOutbox, rebookAtSuggestedSlot, type BookingRequest, type OutboxRow } from '@/sync/outbox'
import { syncOutbox } from '@/sync/sync-outbox'
import { fetchTransport } from '@/sync/transport'

function formatSlot(iso: string) {
  return new Date(iso).toLocaleString(undefined, {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function describe(row: OutboxRow) {
  if (row.status === 'confirmed') return 'Booked'
  if (row.status === 'rejected') {
    return row.reject_reason === 'slot_taken'
      ? 'Someone booked this time first'
      : 'The clinic could not accept this booking'
  }
  return row.attempts === 0 ? 'Saved on your phone, waiting to send' : 'Saved on your phone, will keep trying'
}

export default function OutboxScreen() {
  const db = useSQLiteContext()
  const [rows, setRows] = useState<OutboxRow[]>([])
  const [busy, setBusy] = useState(false)

  const reload = useCallback(async () => setRows(await listOutbox(db)), [db])
  useFocusEffect(
    useCallback(() => {
      void reload()
    }, [reload]),
  )

  const sendNow = async () => {
    setBusy(true)
    try {
      await syncOutbox(db, { baseUrl: CLINIC_API_URL, transport: fetchTransport })
    } finally {
      setBusy(false)
      await reload()
    }
  }

  const takeSuggested = async (row: OutboxRow) => {
    await rebookAtSuggestedSlot(db, row, { idempotencyKey: Crypto.randomUUID(), now: Date.now() })
    await sendNow()
  }

  return (
    <View style={styles.container}>
      <Stack.Screen options={{ title: 'Sent to the clinic' }} />
      <FlatList
        data={rows}
        keyExtractor={(row) => String(row.id)}
        contentContainerStyle={styles.list}
        ListEmptyComponent={<Text>No bookings yet.</Text>}
        renderItem={({ item }) => {
          const booking = JSON.parse(item.payload) as BookingRequest
          return (
            <View style={styles.row}>
              <Text style={styles.when}>{formatSlot(booking.startsAt)}</Text>
              <Text accessibilityLiveRegion="polite">{describe(item)}</Text>
              {item.status === 'rejected' && item.suggested_slot ? (
                <Pressable accessibilityRole="button" style={styles.button} onPress={() => takeSuggested(item)}>
                  <Text style={styles.buttonText}>Book {formatSlot(item.suggested_slot)} instead</Text>
                </Pressable>
              ) : null}
            </View>
          )
        }}
      />
      <Pressable
        accessibilityRole="button"
        accessibilityState={{ disabled: busy }}
        disabled={busy}
        style={styles.button}
        onPress={sendNow}
      >
        <Text style={styles.buttonText}>{busy ? 'Sending' : 'Send now'}</Text>
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, gap: 12 },
  list: { gap: 8 },
  row: { padding: 16, borderRadius: 12, borderWidth: 1, borderColor: '#d9dce1', gap: 4 },
  when: { fontSize: 17, fontWeight: '600' },
  button: {
    minHeight: 48,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 12,
    backgroundColor: '#0b0c0e',
    paddingHorizontal: 16,
  },
  buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
})
TSX

Link to it from wherever suits your design, for example a "Sent to the clinic" row on the Profile tab with <Link href="/outbox">. Cancellations from part 3 can go through the same outbox later as a second kind of row, with their own key; the sync loop does not change.

State diagram of an outbox row. A pending row loops back to pending with one more attempt and a backoff wait on no reply, 408, 429 or 5xx; it moves to confirmed on 200 or 201 with a booking id; it moves to rejected on 409 slot taken or another 4xx; and a rejected row returns to pending as a new row with a new key when the patient taps the suggested slot
The server's answer decides each row's next state

Check it worked

Bundle the app for the web, which compiles every route and every import, NetInfo and the new screen included:

Bash
cd ~/larkfield-app-demo
npx expo export --platform web
test -d dist && echo "web export built"

The export prints something like a list of bundles and routes, with outbox among them, and the last command prints web export built. A wrong import path stops the export and names the file.

Step 8 · Try it on a phone with the signal off

A phone cannot reach 127.0.0.1 on your computer, so run the mock API on your network address and tell the app where it is. Find your computer's address on the Wi-Fi, for example with ipconfig getifaddr en0 on macOS or hostname -I on Linux. The mock API has no real authentication, so do this only on a network you trust. In the second terminal, stop the server with Ctrl+C and start it again listening on every interface:

Bash
HOST=0.0.0.0 node mock-api/server.mjs

In the first terminal, start Expo with that address. Replace 192.168.1.20 with yours. The Android emulator reaches your computer at 10.0.2.2 instead:

Bash
EXPO_PUBLIC_CLINIC_API_URL=http://192.168.1.20:4010 npx expo start --clear

Open the app, switch the phone to airplane mode, and book an appointment. Open the outbox screen. Then switch airplane mode off, or put the app in the background and bring it back.

Check it worked

While offline, the appointment is on the Appointments tab and the outbox screen says "Saved on your phone, waiting to send". A few seconds after the connection returns, the outbox screen shows "Booked" when you open it again, and curl -s http://127.0.0.1:4010/bookings on your computer lists exactly one booking. Book the same time again from the app and that row says "Someone booked this time first", with a button for the next half hour.

When you have finished, stop the mock API with Ctrl+C. Keep ~/larkfield-app-demo and mock-api/server.mjs: part 5 adds reminders and cancels them when the outbox marks a booking rejected, part 6 relies on the mock API's 404 rule for appointment links, part 7 runs these sync tests against it, and part 8 cleans up the whole series.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.