Video in progress
A mobile app works offline and syncs with the server later. How do you design the changes and conflicts in the server database?
The server gives every change a monotonically increasing sequence number, and the client asks "give me everything after the last number I saw". Deletes are stored as tombstones. Client writes arrive with an idempotency key and a base version; a conflict is resolved according to the business rule, often at the field level.
📖 Answer
There are two directions: server to client (pull) and client to server (push).
Pull. "Changes after this time" by updated_at is a widespread but wrong approach: clocks differ, rows have identical timestamps, and a transaction that was slow to commit ends up with an updated_at from a time the reader has already passed, so the change is lost.
A better way is a change log:
CREATE TABLE change_log (
seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL,
entity text NOT NULL,
entity_id uuid NOT NULL,
op text NOT NULL, -- UPSERT / DELETE
created_at timestamptz NOT NULL DEFAULT now()
);
The client asks for seq > :lastSeq. But identity isn't in commit order either, so the server hands out only up to a boundary where all older transactions have finished, or fills the log through CDC (in commit order).
Deletes: if a row is deleted, the client doesn't know. So a DELETE is also written to the log (a tombstone), and the log is cleaned after a certain period. A client that has been offline longer than that period does a full resync.
Push. The client gives each change a UUID (also so ids can be created offline) and sends a base_version:
- if the server version equals
base_version, it's applied; - if it differs, it's a conflict. The strategy depends on the domain: for a note's text, "last writer wins" is enough, while for warehouse stock you send not an absolute value but an operation (
-3 units) and the server applies it.
Push requests must be idempotent, because a mobile network resends requests. And I agree the conflict rule for each table with the product team up front, and document it.
Sign up to mark studied questions and save your progress.