Prompt

How do I build an offline-first mobile app backend that syncs changes when users reconnect?

Technology / Cloud Infrastructure1 observationLast seen Nov 4, 2026

Latest observation

Nov 4, 2026OpenAI APIWeb search: off

To build an offline-first mobile backend that syncs reliably when users reconnect, design around local writes first, append-only change capture, and conflict-aware synchronization.

1) Core architecture

Use these layers:

  • Mobile app local store: SQLite / Realm / WatermelonDB / IndexedDB-style equivalent
  • Sync queue on device: stores user mutations while offline
  • Backend API: accepts batches of changes and returns server updates
  • Server-side source of truth: relational DB or document store
  • Change log / event store: records every write in order
  • Conflict resolver: determines how overlapping edits are merged

The main rule: the app always reads and writes locally first, then syncs later.


2) Data model for sync

Each record should carry metadata such as:

  • id: globally unique ID, usually UUID
  • updated_at: last modification time
  • version: monotonically increasing integer or revision token
  • deleted: soft delete flag
  • last_modified_by: optional for debugging/conflicts
  • sync_state: local-only state on device

For better syncing, keep a separate change log table on the server:

Example change record:

{
  "change_id": "chg_123",
  "entity_type": "note",
  "entity_id": "note_456",
  "operation": "update",
  "version": 17,
  "timestamp": "2026-11-04T12:00:00Z",
  "payload": {
    "title": "New title",
    "body": "Edited offline"
  }
}

3) Sync protocol

A solid sync flow usually has two phases:

A. Push local changes

The client sends all queued local mutations since the last successful sync.

Example request:

{
  "device_id": "dev_abc",
  "user_id": "user_1",
  "base_sync_token": "sync_9001",
  "changes": [
    {
      "client_change_id": "local_1",
      "entity_type": "task",
      "entity_id": "task_100",
      "operation": "update",
      "base_version": 4,
      "payload": { "done": true }
    }
  ]
}

The server should:

  • validate the user
  • check whether the client’s base_version matches current version
  • apply changes if possible
  • detect conflicts if not possible
  • store accepted changes
  • return results

B. Pull server changes

The server returns all changes since the client’s last sync token.

Example response:

{
  "new_sync_token": "sync_9002",
  "applied": [
    {
      "client_change_id": "local_1",
      "entity_id": "task_100",
      "server_version": 5
    }
  ],
  "conflicts": [],
  "server_changes": [
    {
      "entity_type": "task",
      "entity_id": "task_200",
      "operation": "create",
      "version": 12,
      "payload": { "title": "Remote update" }
    }
  ]
}

Use the sync token to support incremental sync and avoid full table downloads.


4) Conflict handling strategies

Conflicts happen when:

  • two devices edit the same object offline
  • one device edits an object that was deleted elsewhere
  • a stale client overwrites newer server data

Common strategies:

Option 1: Last write wins

Simplest approach. Server accepts the most recent write by timestamp/version.

Pros:

  • easy to implement

Cons:

  • can silently lose user changes

Option 2: Optimistic concurrency with merge

Reject writes if the base version is stale, then let the client merge and resubmit.

Pros:

  • safer
  • predictable

Cons:

  • more work in app and backend

Option 3: Field-level merge

Merge non-overlapping fields automatically.

Example:

  • Device A changes title
  • Device B changes priority
  • both can be merged

Option 4: CRDTs / operational transforms

Best for collaborative editing and complex real-time shared data.

Pros:

  • robust under concurrent edits

Cons:

  • significantly more complex

For most mobile apps, start with optimistic concurrency + field-level merge.


5) Client-side offline workflow

On device:

  1. User edits data
  2. Save immediately to local DB
  3. Add mutation to sync queue
  4. Mark item as pending sync
  5. When network returns, batch send queued mutations
  6. Update local records with server response
  7. Remove acknowledged queue entries

Important:

  • make local writes idempotent
  • retry safely
  • persist the queue across app restarts

6) Backend implementation tips

Use idempotency keys

Clients may retry the same mutation. Include a client_change_id so the server can detect duplicates.

Make endpoints batch-friendly

Prefer:

  • POST /sync/push
  • GET /sync/pull?since=token

Batching reduces network overhead and battery usage.

Store soft deletes

Hard deletes make sync harder. Use:

  • deleted_at
  • tombstone records

This helps other devices learn that something was deleted.

Return authoritative server state

After a sync, the client should receive:

  • server-assigned IDs
  • new versions
  • resolved fields
  • deletions

7) Schema example

For a table like notes:

CREATE TABLE notes (
  id UUID PRIMARY KEY,
  user_id UUID NOT NULL,
  title TEXT NOT NULL,
  body TEXT,
  version INTEGER NOT NULL DEFAULT 1,
  deleted BOOLEAN NOT NULL DEFAULT FALSE,
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

And a change log:

CREATE TABLE note_changes (
  change_id UUID PRIMARY KEY,
  note_id UUID NOT NULL,
  user_id UUID NOT NULL,
  operation TEXT NOT NULL,
  base_version INTEGER,
  payload JSONB,
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

8) Sync token design

Your sync token can be:

  • a timestamp
  • a monotonically increasing global sequence
  • a per-user cursor
  • a changelog offset

Best practical choice: a server-generated cursor/sequence.

Example:

  • client last synced at cursor 10234
  • server returns all changes after 10234
  • server returns new cursor 10480

This is safer than using timestamps alone, which can be ambiguous.


9) Handling deletions and restores

Use tombstones:

  • delete = mark as deleted, don’t immediately remove row
  • sync other devices about the deletion
  • optionally purge tombstones later after a retention window

If you permanently delete too soon, offline clients can resurrect stale records or fail to reconcile.


10) Security and correctness

  • authenticate every sync request
  • scope all data by user/tenant
  • sign or validate device sessions
  • rate-limit sync endpoints
  • validate payloads strictly
  • never trust client timestamps for ordering
  • keep an audit trail for conflict/debugging

11) Practical MVP approach

If you want something shippable fast:

  1. Local SQLite on device
  2. UUIDs for all entities
  3. version column on server rows
  4. POST /sync accepting batched mutations
  5. GET /sync returning changes since cursor
  6. Optimistic concurrency checks
  7. Soft deletes
  8. Simple conflict policy:
    • reject stale writes
    • client refetches and retries after merge

This is usually enough for notes, tasks, inventory, field apps, and many consumer apps.


12) When to use a managed sync framework

Consider a managed solution if you want less infrastructure work:

  • Firebase / Firestore
  • Supabase Realtime + Postgres
  • Couchbase Lite + Sync Gateway
  • Realm Device Sync
  • WatermelonDB + custom backend
  • PowerSync

These can save time, but evaluate:

  • conflict behavior
  • offline query support
  • cost
  • vendor lock-in
  • whether your data model fits their sync model

If you want, I can also provide:

  1. a reference API design for /sync/push and /sync/pull,
  2. a Postgres schema for offline sync,
  3. or a sample implementation in Node.js / FastAPI / Go.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.