Why Offline-First Is a Business Requirement, Not a Feature

For many businesses in Syria and across the region, an internet connection is not a given — it is a variable. Field sales reps in rural Aleppo governorate, delivery drivers crossing coverage gaps, clinic staff during outages, and factory floor workers on spotty Wi-Fi all share the same pain: an app that freezes or loses data the moment connectivity drops is an app nobody trusts.

Offline-first architecture inverts the assumption. Instead of asking "how do we gracefully degrade when offline?", it asks "how do we sync efficiently when back online?". The local device becomes the primary store; the server is authoritative but eventually consistent.

This guide walks through the key design decisions, data models, and implementation patterns you need to build a production-grade offline-first mobile app — with illustrative code in React Native / Expo (applicable concepts carry to Flutter and native iOS/Android).

---

1. Picking the Right Local Store

Three local-storage options dominate mobile offline-first development:

| Store | Best for | Limitations | |---|---|---| | SQLite (via expo-sqlite / react-native-quick-sqlite) | Relational data, complex queries, large datasets | Requires a schema migration strategy | | MMKV / AsyncStorage | Small key-value config and user preferences | Not suitable for structured relational data | | WatermelonDB | High-performance reactive queries on top of SQLite | Heavier setup; uses lazy hydration | | Realm / Atlas Device SDK | Embedded object store with built-in Atlas sync | Vendor lock-in; licence considerations |

For most line-of-business apps (ERP, field ops, delivery, clinic management), SQLite is the right foundation. It is ACID-compliant, supports indexes and foreign keys, and pairs cleanly with hand-rolled or ORM-driven sync.

> Important: Whichever store you choose, isolate all database access behind a repository layer. Direct SQL scattered across components makes schema migrations and sync logic nearly impossible to maintain.

---

2. Data Model Design for Offline-First

The single most important decision is how every row tracks its lifecycle. Add these four columns to every synced table:

-- Illustrative schema; adapt data types to your SQL dialect
CREATE TABLE orders (
  id          TEXT PRIMARY KEY,   -- client-generated UUID (not server auto-increment)
  created_at  INTEGER NOT NULL,   -- Unix ms timestamp
  updated_at  INTEGER NOT NULL,   -- updated on every local write
  sync_status TEXT NOT NULL DEFAULT 'pending',
                                  -- 'pending' | 'synced' | 'conflict'
  server_rev  TEXT,               -- server-side revision token or ETag
  deleted_at  INTEGER             -- NULL = alive; set for soft-delete
  -- ... business columns ...
);

Why client-generated UUIDs? Auto-increment IDs require a round-trip to the server before you can reference the row in child tables. UUIDs let the client create the full object graph instantly and sync later.

Why sync_status? The sync engine needs a cheap way to find dirty rows without a full table scan. A filtered index on sync_status = 'pending' makes the outbox query O(dirty rows) rather than O(all rows).

Why server_rev? Each successful server write returns a revision token (a timestamp, sequence number, or ETag). Storing it locally lets you detect conflicts: if the server's current revision differs from what you last stored, another writer changed the record while you were offline.

---

3. The Outbox Pattern

An outbox serialises every local mutation into a queue of pending operations before attempting network delivery. This prevents partial sync and makes retry logic straightforward.

// Illustrative — not production-ready without error handling and transactions
interface OutboxEntry {
  id: string;           // local UUID
  table_name: string;
  row_id: string;
  operation: 'INSERT' | 'UPDATE' | 'DELETE';
  payload: string;      // JSON blob of changed columns
  created_at: number;   // Unix ms
  attempts: number;     // retry counter
  last_error?: string;
}

// Called inside the same SQLite transaction as the business write
async function enqueue(entry: Omit<OutboxEntry, 'attempts'>): Promise<void> {
  await db.runAsync(
    `INSERT INTO outbox (id, table_name, row_id, operation, payload, created_at, attempts)
     VALUES (?, ?, ?, ?, ?, ?, 0)`,
    [entry.id, entry.table_name, entry.row_id, entry.operation, entry.payload, entry.created_at]
  );
}

> Note: The business write and the outbox insert must be in the same atomic transaction. If the app crashes between the two, you will either have a dirty row with no outbox entry (silent data loss) or an outbox entry with no matching row (phantom sync).

---

4. The Sync Engine

The sync engine runs on a schedule (every 30–60 seconds), on AppState returning to foreground, and on NetInfo detecting reconnection. It has three phases:

Phase 1 — Upload (local → server)

// Illustrative sync upload phase
async function uploadPending(): Promise<void> {
  const rows = await db.getAllAsync<OutboxEntry>(
    `SELECT * FROM outbox WHERE attempts < 5 ORDER BY created_at ASC LIMIT 50`
  );

  for (const entry of rows) {
    try {
      const response = await apiClient.post('/sync/apply', {
        table: entry.table_name,
        operation: entry.operation,
        payload: JSON.parse(entry.payload),
        client_rev: entry.id,
      });

      await db.runAsync(
        `UPDATE ${entry.table_name} SET sync_status = 'synced', server_rev = ?
         WHERE id = ?`,
        [response.data.server_rev, entry.row_id]
      );
      await db.runAsync(`DELETE FROM outbox WHERE id = ?`, [entry.id]);
    } catch (err) {
      await db.runAsync(
        `UPDATE outbox SET attempts = attempts + 1, last_error = ? WHERE id = ?`,
        [String(err), entry.id]
      );
    }
  }
}

Phase 2 — Download (server → local)

The client sends a watermark — the highest server sequence or timestamp it has already applied. The server returns only rows changed after that point.

// Illustrative download phase
async function downloadChanges(watermark: number): Promise<number> {
  const { data } = await apiClient.get('/sync/changes', {
    params: { since: watermark },
  });

  for (const change of data.changes) {
    const local = await db.getFirstAsync<{ server_rev: string; sync_status: string }>(
      `SELECT server_rev, sync_status FROM ${change.table} WHERE id = ?`,
      [change.id]
    );

    if (!local) {
      // New row from another device — insert
      await applyRemoteInsert(change);
    } else if (local.sync_status === 'pending') {
      // We have unsent changes — conflict!
      await markConflict(change);
    } else {
      // Safe to overwrite
      await applyRemoteUpdate(change);
    }
  }

  return data.new_watermark;
}

Phase 3 — Conflict Resolution

Conflicts occur when the same row is modified on two devices before either syncs. There are four common strategies:

| Strategy | When to use | |---|---| | Last-write-wins (LWW) | Low-stakes fields: status labels, notes | | Server wins | Master data like price lists or product catalogues | | Client wins | User-generated content the server must accept | | Merge / CRDT | Counters, sets, collaborative text |

For most field-ops apps, a simple LWW on updated_at works well: whichever timestamp is newer becomes authoritative. Set conflicted rows to sync_status = 'conflict' and surface them in a UI review queue for the cases that require human judgment.

---

5. Networking — Handling Syria's Connectivity Realities

Syria's mobile data environment includes frequent drops, high latency on 3G/4G, and asymmetric up/down throughput. A few patterns help:

Exponential back-off with jitter. On failure, wait min(base * 2^attempts, cap) + random(0, jitter) milliseconds before retrying. This prevents a fleet of devices all hammering the server the moment connectivity returns.

function backoffDelay(attempts: number, base = 1000, cap = 60_000): number {
  const exp = Math.min(base * Math.pow(2, attempts), cap);
  return exp + Math.random() * 1000; // add up to 1s of jitter
}

Payload compression. Enable gzip or Brotli on the server and set Accept-Encoding on the client. For large sync payloads, this typically cuts transfer size by 60–80%.

Delta sync, not full sync. The watermark-based download in Phase 2 above already implements this. Never fetch the entire dataset on every sync cycle.

Background fetch (iOS) / WorkManager (Android). Platform background tasks run sync even when the app is in the background, so the user opens to already-fresh data.

---

6. Schema Migrations

Every time you change your SQLite schema, devices in the field may be on any previous version. Use a migration table:

CREATE TABLE IF NOT EXISTS schema_migrations (
  version  INTEGER PRIMARY KEY,
  applied_at INTEGER NOT NULL
);

On app start, run all unapplied migrations in order. Keep migrations additive (add columns, never remove or rename without a compatibility shim). Libraries like drizzle-orm with its migrate utility or Knex.js for React Native handle this automatically.

---

7. Testing Offline Behaviour

Offline-first code is notoriously undertested because developers work on fast Wi-Fi. Build these test scenarios into your CI pipeline:

  • No connectivity from first launch — the app should onboard with cached/seeded data.
  • Connectivity drops mid-upload — outbox entries should remain and retry.
  • Same row edited on two clients — conflict flags appear correctly.
  • Large initial sync — 10,000+ rows should not block the UI thread (use runAsync, not runSync).
  • Migration from version N to N+2 — all intermediate migrations apply correctly.

Expo and React Native Testing Library let you mock NetInfo and inject controlled SQLite databases. Write integration tests that run the full sync cycle against a local Express server.

---

8. Architecture Summary

┌─────────────────────────────┐
│          UI Layer           │
│  (React Native components)  │
└──────────────┬──────────────┘
               │ hooks / store
┌──────────────▼──────────────┐
│       Repository Layer      │
│  (typed SQLite access only) │
└──────────────┬──────────────┘
               │ read / write
┌──────────────▼──────────────┐
│      SQLite Local Store     │
│  orders, outbox, watermark  │
└──────────────┬──────────────┘
               │ upload / download
┌──────────────▼──────────────┐
│        Sync Engine          │
│  NetInfo → upload → dl →    │
│  conflict resolution        │
└──────────────┬──────────────┘
               │ HTTPS + gzip
┌──────────────▼──────────────┐
│      Backend REST API       │
│  /sync/apply  /sync/changes │
└─────────────────────────────┘

---

Common Pitfalls to Avoid

Running sync on the main thread. SQLite writes on the UI thread freeze animations. Use expo-sqlite's async API or move sync to a background service.

Using auto-increment server IDs as primary keys. The app cannot create related rows without first saving the parent to the server and getting its ID back. Use UUIDs everywhere.

Syncing entire rows instead of changed columns. Sending all columns makes conflict detection harder and wastes bandwidth. Send only the columns that changed, plus the row ID and revision token.

Forgetting to sync deletions. A soft-delete column (deleted_at) ensures the server learns about removed rows. Hard-deleting locally means those rows reappear on the next download.

Not handling server-side validation failures. The server may reject a payload (e.g., a duplicate SKU or an invalid status transition). The outbox entry should not be retried indefinitely — cap retries and surface failures to the user.

---

Conclusion

Offline-first architecture is not exotic — it is the responsible choice for any mobile app deployed in environments where connectivity cannot be guaranteed. The patterns in this guide — a local SQLite store, client-generated UUIDs, an outbox queue, watermark-based delta sync, and explicit conflict resolution — form a solid foundation that scales from a single field team to hundreds of concurrent devices.

If you are building a delivery management app, a clinic EMR, a field audit tool, or a sales order system and need this architecture designed and implemented correctly, Dragonfly Soft can help.

Talk to our team about your mobile project →