Video in progress
A mobile app works in offline mode. How do you sync the changes a user made without internet to the server later?
The client stores the changes in a local database as a queue of operations and gives each a unique ID; when the connection returns they're sent idempotently. The server detects conflicts by version or updated_at and resolves them with a pre-agreed rule, and the client fetches what changed since its "last sync point".
📖 Answer
An example: a courier app. There's no internet in the basement, and the courier marked 5 orders as "delivered".
Client side:
- Data in a local database (SQLite/Room) and a separate
pending_opstable:op_id(UUID), type, payload, creation time. - The UI shows the local change immediately.
- When the network is back, the queue is sent in order. If there's no response, retry with the same
op_id.
Server side:
-- against duplicates
INSERT INTO applied_ops(op_id) VALUES (:opId) ON CONFLICT DO NOTHING;
-- optimistic check
UPDATE deliveries SET status = 'DELIVERED', version = version + 1
WHERE id = :id AND version = :expectedVersion;
If 0 rows are updated — a conflict: in the meantime someone (a dispatcher) changed this order.
The conflict resolution rule is a business decision, not a technical one:
- last-write-wins — simple, but some change silently disappears;
- field-level merge — if one person changed the address and another the phone, both stay;
- a rule on the server: a "cancelled" order can't be marked "delivered" — the client gets a rejection with the reason;
- show the user and let them choose (for documents).
The pull part: the client gets the changes on the server with GET /changes?since=<cursor>. As a cursor, a server-side monotonic sequence is better than a clock — you can't trust the device clock.
Don't forget deletions either: if the server just makes a deleted record "disappear", the client doesn't know. You need a tombstone (deleted = true and a timestamp).
Sign up to mark studied questions and save your progress.