Prompt
How do I build offline-first data sync for iOS and Android apps?
Latest observation
Building offline-first sync for iOS and Android usually means designing your app so it works from local storage first, then reconciles with a server when connectivity returns.
Core idea
Your app should:
- Read/write locally immediately
- Queue changes locally
- Sync changes to the backend later
- Pull remote changes and merge them safely
- Handle conflicts predictably
1) Pick a sync model
There are a few common patterns:
A. Simple last-write-wins
- Each record has an
updated_attimestamp or version. - Client sends updates with version.
- Server accepts the latest write.
Pros: easy
Cons: can overwrite user changes silently
Good for:
- notes
- simple forms
- non-critical data
B. Optimistic concurrency with version checks
- Each row/document has a
version. - Update must include the version the client last saw.
- If version mismatch, server rejects and client resolves conflict.
Pros: safer than LWW
Cons: requires conflict handling
C. Operation-based sync
- Instead of syncing full records, sync actions:
- “create task”
- “rename task”
- “delete task”
- Server replays operations in order.
Pros: good for collaboration and auditability
Cons: more complex
D. CRDT/OT-based sync
- For real-time collaborative editing.
- Automatically merges concurrent edits.
Pros: best for shared editing
Cons: highest complexity
Most mobile apps should start with optimistic concurrency + local queue.
2) Store data locally first
Use a local database on-device:
- SQLite / Room on Android
- Core Data / SQLite on iOS
- Or a cross-platform local DB:
- Realm
- SQLite
- WatermelonDB
- PouchDB/CouchDB-style sync
- Drift (Flutter)
- SQLDelight (Kotlin Multiplatform)
Typical local tables:
Example records
itemsoutboxorpending_mutationssync_state
Example fields for items
idserver_iddata...versionupdated_atdeleted_atoris_deletedsync_status
Outbox table
Store unsynced operations:
mutation_identity_typeentity_idoperation_typepayloadcreated_atretry_countstatus
This is the backbone of offline-first.
3) Use the outbox pattern
When user edits something:
- Update local DB immediately
- Insert a mutation into the outbox
- Mark the entity as dirty/pending sync
Later, a sync worker:
- Reads queued mutations
- Sends them to server
- Marks them synced on success
- Retries or resolves conflicts on failure
This gives instant UX even when offline.
4) Design your server API for sync
Your backend should support:
Push endpoint
Send local changes to server:
POST /sync/push
Request may include:
- client/device ID
- sync token or cursor
- list of mutations
- entity versions
Response may include:
- accepted mutations
- conflicts
- new server state
- next sync cursor
Pull endpoint
Fetch changes since last sync:
GET /sync/pull?cursor=...
Return:
- changed records
- tombstones for deletions
- next cursor
Better: one sync endpoint
Many systems use a single:
POST /sync
with both:
- client mutations
- last known cursor
and the server returns:
- authoritative updates
- conflicts
- next cursor
5) Track changes with sync cursors
To avoid fetching the entire dataset each time, use a cursor or change log.
Example:
Server keeps a changelog:
change_identity_typeentity_idoperationpayloadtimestamp
Client stores:
last_sync_cursor
On next sync:
- client asks for changes after cursor
- server returns incremental updates
This is much more scalable than full reloads.
6) Handle deletes explicitly
Never rely only on “missing = deleted.”
Use:
deleted_at- or tombstones in changelog
Why:
- clients need to know a record was deleted
- prevents deleted items from reappearing after sync
7) Conflict resolution
Conflicts happen when:
- user edits same record on two devices
- user edits offline while server changed same item
Common strategies:
A. Last write wins
Simple, but data can be lost.
B. Field-level merge
Merge non-overlapping fields:
- user A changes title
- user B changes notes
- both can survive
C. User-facing conflict resolution
If same field changed:
- keep both versions
- ask user to choose
D. Domain-specific rules
Example:
- inventory count uses server authority
- note content merges
- status transitions follow business rules
You should decide conflict policy per entity type.
8) Make sync idempotent
Mobile networks fail. Requests may be retried.
Your server should safely accept duplicate sync requests.
Use:
mutation_idas an idempotency key- unique client-generated IDs for new objects
- deduplication on server
This prevents duplicate records from retries.
9) Use robust IDs
Generate IDs on the client so objects can exist offline before server assignment.
Options:
- UUIDv4
- ULID
- KSUID
Best practice:
- create client-side IDs
- server can keep same ID or map to server IDs
This avoids “temporary local object, later replace with server ID” complexity.
10) Background sync
Mobile apps should sync in the background when possible.
iOS
BGAppRefreshTaskBGProcessingTask- limited background execution
- use silent push carefully
Android
WorkManager- periodic and constraint-based jobs
- network/battery conditions
Rules:
- never depend solely on foreground sync
- queue work
- retry with backoff
- respect OS limits
11) Sync lifecycle example
User creates a task offline
- App writes task to local DB
- App adds mutation to outbox
- UI shows task immediately
Later, network returns
- Sync worker starts
- Pushes outbox mutations
- Server saves task, returns authoritative version
- App updates local row with server version
- App pulls remote changes since last cursor
- App merges updates and clears synced mutations
12) Recommended architecture
A good structure is:
- UI layer
- Repository
- Local database
- Sync engine
- Remote API client
The UI reads only from local DB.
The repository writes to local DB and enqueues sync.
The sync engine handles push/pull.
This keeps your app responsive and testable.
13) Practical tech choices
Native iOS
- Core Data or SQLite
- URLSession
- BackgroundTasks framework
Native Android
- Room/SQLite
- Retrofit/Ktor client
- WorkManager
Cross-platform
- Flutter: Drift + WorkManager + background tasks
- React Native: SQLite/WatermelonDB + background sync
- Kotlin Multiplatform: SQLDelight + shared sync logic
14) Important edge cases
Plan for:
- app killed mid-sync
- partial success
- network timeout
- duplicate retries
- schema version changes
- clock skew
- large datasets
- attachment/file syncing
- auth token expiration
- account switching
15) A simple sync algorithm
- Load local pending mutations
- Send them to server with idempotency keys
- Server applies what it can
- Server returns conflicts and updated records
- Client writes server truth to local DB
- Client updates
last_sync_cursor - Repeat until outbox empty
16) When to use a sync framework
If you want less custom work, consider:
- Realm Sync
- Couchbase Lite + Sync Gateway
- Firebase/Firestore offline support
- AWS AppSync + DataStore
- Replicache for certain web/mobile use cases
These can reduce custom sync logic, but you trade flexibility and sometimes lock-in.
17) Best practices summary
- Make local DB the source of truth for UI
- Use an outbox for pending mutations
- Use client-generated IDs
- Sync incrementally with cursors
- Make endpoints idempotent
- Handle deletes explicitly
- Define conflict rules up front
- Use background jobs
- Test offline, flaky network, and conflict scenarios
If you want, I can also give you:
- a reference architecture diagram,
- a sample sync schema/API design, or
- a concrete implementation example for iOS + Android.