How do you handle data synchronization between a remote server and a local SQLite database in iOS?
Instruction: Discuss strategies for ensuring data consistency between the server and local storage.
Updated
Official answer
Define ownership and conflict semantics before choosing the transport. For each account, use stable record IDs, an explicit deletion representation and server-issued versions or a resumable change cursor. A client's wall clock can be skewed; comparing local and server last-modified timestamps alone can miss or overwrite changes.
Commit each local edit and its pending outbound operation in the same SQLite transaction. Store an operation ID, base server version and payload so a restart does not lose the intention. Retry only under a documented policy. The server must authorize the account, condition writes on the expected version and durably deduplicate the operation ID together with its effect. If the server commits but the acknowledgement is lost, retrying the same ID should recover the prior outcome rather than repeat the effect.
On download, apply a page of changes and advance its cursor in one local transaction. If that transaction fails, replay the page. Define pagination order and snapshot/cursor semantics on the server; an arbitrary timestamp query does not establish a complete change stream. Retain tombstones long enough for supported offline clients, and provide a full-resync path when a cursor expires.
For example, if both client and server edited version 7, a conditional upload based on 7 must not silently overwrite server version 8. Resolve by a domain-specific merge, server/client policy with understood data-loss consequences, or user review. Record the result before marking the pending operation acknowledged. Edits made during an in-flight sync need their own versions so a late acknowledgement cannot clear newer pending work.
Keep account data and queues isolated, serialize local database access appropriately, and make background work resumable because iOS does not guarantee continuous execution. Test lost acknowledgements, duplicate/reordered delivery, deletion, restart, cursor expiry and concurrent local edits. Measure pending age, conflict rate and convergence after recovery; DAU is not a consistency check. SQLite's local transaction does not atomically commit the remote server.