Triamorph Systems

Mobile & Native · 13 min read · Sep 08, 2024

Offline-First Mobile App Architecture: Building High-Performance React Native Apps with WatermelonDB and SQLite Sync

Mastering offline-first mobile app development: React Native with WatermelonDB, SQLite JSI integration, two-way synchronization algorithms, and CRDT conflict resolution.

By Hammad Haider

Core Engineering Takeaways

  • WatermelonDB leverages SQLite lazy-loading and React Native JavaScript Interface (JSI) to query tens of thousands of records without freezing the UI thread.
  • Implement delta synchronization (push changes since last sync timestamp, pull modified records from server) to minimize mobile cellular battery and data consumption.
  • Handle concurrent data conflicts using deterministic Last-Write-Wins (LWW) with vector clocks or field-level CRDT merges.

Modern mobile users expect instant 60 FPS interactions regardless of subway tunnels, airplane mode, or rural cell dead zones. Applications that show full-screen loading spinners on every tap feel sluggish and abandon user trust. An offline-first mobile architecture reverses the traditional client-server paradigm: all UI reads and writes execute against a local SQLite database in under 2ms, while an asynchronous synchronization engine reconciles state with the cloud in the background.

1. Why Offline-First Architecture Dominates Mobile UX

Eliminating the loading spinner anti-pattern in enterprise mobile products

In traditional mobile architectures, pressing "Save" sends an HTTP POST request to a server. If the user loses network connectivity mid-request, the UI freezes or enters an inconsistent state.

In an offline-first architecture, pressing "Save" writes directly to local encrypted SQLite storage. The UI updates instantly (optimistic UI), and an immutable mutation record is queued in a persistent outbound sync table.

Local Read Latency
< 1.8ms
SQLite over React Native JSI
Cloud API Read Latency
250-900ms
Traditional HTTP round-trip
Offline Availability
100%
Full offline write & read capabilities

2. Setting Up WatermelonDB with High-Speed SQLite JSI

Schema definition, observable queries, and lazy relation loading

WatermelonDB avoids loading entire database records into JavaScript memory upfront. Instead, it utilizes native SQLite C++ bindings (JSI) and RxJS observables to render only visible list items.

src/database/syncEngine.ts (typescript)
import { synchronize } from '@nozbe/watermelondb/sync';
import { database } from './schema';
import apiClient from '../services/apiClient';

export async function performAppSync(): Promise<void> {
  await synchronize({
    database,
    pullChanges: async ({ lastPulledAt, schemaVersion, migration }) => {
      const response = await apiClient.get('/api/v1/sync/pull', {
        params: { last_pulled_at: lastPulledAt, schema_version: schemaVersion }
      });

      const { changes, timestamp } = response.data;
      return { changes, timestamp };
    },
    pushChanges: async ({ changes, lastPulledAt }) => {
      await apiClient.post('/api/v1/sync/push', {
        changes,
        last_pulled_at: lastPulledAt,
      });
    },
    sendCreatedAsUpdated: false,
    conflictResolver: (table, localRecord, remoteRecord, resolved) => {
      // Deterministic field-level resolution: remote wins on status, local wins on draft notes
      return {
        ...remoteRecord,
        local_draft_notes: localRecord.local_draft_notes,
      };
    },
  });
}

3. Designing the Two-Way Delta Sync Engine

Minimal payload synchronization using server revision timestamps

The synchronization protocol sends only changed columns and deleted record IDs. On the backend (PostgreSQL), tables maintain an `updated_at` timestamp with an indexed trigger to quickly serve delta query ranges.

4. Resolving Conflicts & Background Sync with WorkManager

Executing friction-free background synchronization without draining battery

Using Android WorkManager and iOS BackgroundTasks framework, the mobile client awakens periodically in the background when Wi-Fi is detected to drain the outbound mutation queue and pull fresh updates.

Tags: offline first mobile app architecturereact native watermelondb syncsqlite local first mobile databasemobile sync conflict resolution crdtreact native offline first best practices

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Mobile App Development (iOS & Android) →

Cross-platform mobile applications with offline-first synchronization and native device bridges.

View Practice Blueprint & Capabilities →
Production Client System

Task Sync Kro AI Productivity App →

Contextual Android productivity application prioritizing tasks by time and geofenced physical location.

Read Deployed Case Study (4.8-star user rating with zero sync drops) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →