Srijan Guchhait

Offline sync without a clock

Per-object sequence numbers, revision preconditions and field-level conflicts: how a workspace app lets you edit offline without last-write-wins.

  • sync
  • architecture
  • distributed-systems

A phone on a train and a laptop in an office disagree about the time, and they may edit the same note. The usual fix is last-write-wins by timestamp. It loses data whenever one clock is wrong. When I designed offline sync for a workspace product, I set one rule at the start: no wall clock appears anywhere in the protocol. Per-object sequence numbers and revision checks replaced it.

Three calls

Three HTTP calls carry the whole protocol: push, pull and bootstrap. Bootstrap tells a device which workspaces and objects it can see, with their current heads. Push uploads the queued changes. Pull fetches the operations after a cursor for each object. If the device fell too far behind, pull returns a snapshot.

Each queued change is a mutation. It holds an action name, the action input and a few fields that make it safe to send twice:

  • an opId that the client chooses, used for deduplication
  • a localSeq that grows with each change on the device
  • an optional precondition
  • optional dependencies on earlier operations

A push carries at most 100 mutations. A pull carries at most 50 cursors. The server checks the protocol version before it touches any object.

Receipts make retries exact

The server answers each mutation with a receipt. A receipt has one of five statuses: applied, replayed, conflict, forbidden or invalid. The replayed status is the useful one. If a device sends an opId that the server already applied, the server returns the original sequence number and result, and changes nothing. A connection that drops after the server applied a change is therefore harmless. The client sends the change again and gets the same answer.

The server keeps receipt payloads for 30 days. A small record for each actor and opId lasts until the object is deleted. An old retry cannot apply twice. It ends in a conflict, which is the safe result.

Revisions instead of timestamps

Every object has a head: the sequence number of its last operation. Some writes cannot merge automatically. These carry a baseHead, the head that the device saw when it made the change. If the head on the server moved on, the server refuses the write as stale and stores nothing. The client can retry with the current head under the same opId.

Whether a write needs a baseHead depends on whether it merges.

  • Document edits, stream posts and new table rows merge. They need no precondition, because two of them cannot collide in a harmful way.
  • Setting a cell, renaming or removing a column, and updating or deleting a row do not merge. Writes to projects and wallets do not merge either. They must name the head they were made against, so a stale overwrite is refused.

Field-level conflicts

People edit notes, task lists and calendars one field at a time. A check on the whole head would reject many harmless edits. For these types I use a compare-and-set on each field. Every write carries a base: the field values it last saw. If a field now holds neither the old value nor the new one, the server refuses the write. The field conflict names the field. Edits to different fields merge on their own.

When the client gets a field conflict, the person chooses. They can keep their version, which sends the same action again with the base rebuilt from the confirmed state. Or they can discard it. Every other conflict code allows only a discard, because nothing safe can be rebuilt.

Order without time

The order comes from the operations. The server checks a whole push before it applies any part of it. It refuses the batch in three cases. One is a duplicate opId. Another is a dependency that is neither earlier in the batch nor already acknowledged. The last is a localSeq that does not grow. A malformed batch fails loudly and never lands half applied.

The client chains dependent writes. A mutation depends on the last pending or accepted mutation that shares its original baseHead on the same object. It predicts that its own baseHead will be one higher, because each accepted write moves the head by exactly one. A concurrent write from someone else still fails the check, as it should.

If a dependency fails, the dependents get an invalid status with a dependency_failed message. That is a local record of the block, not a fake acknowledgement. The client fixes each envelope before the first upload. A restart then reuses the same ids, inputs and preconditions.

Rebase only when it is provably safe

For tables, the client can rebase a refused write. It does so only when the operations it kept show that no foreign operation touched the same row and cell. Inserts commute. Deletes and schema changes overlap. The client tries three times and saves the translated input before each request. If it cannot prove independence, it shows the conflict.

The browser side

The client keeps its outbox, receipts, conflicts, projections and cursors in one IndexedDB database for each user and workspace. It asks the browser for persistent storage. Each row shows Saved locally, Synced or Conflict, so a person always sees where a change stands. A cached profile can open the app offline, but it is never a credential. After a reconnect, the client checks the identity again before any push or pull.

What I would repeat

Make every write idempotent with an id the client chooses, before anything else. Use sequence numbers per object for the order. Decide for each operation type whether it merges, and make the unmergeable ones carry a precondition. A conflict that a person can see costs less than a silent overwrite they find next month.

← All posts