skip to content

Offline-First & Sync

An offline-first app writes locally, queues the change and syncs it later through an outbox, optimistic state, conflict rules and incremental pull. Interviewers use it to separate senior candidates.

on this pageshow

explore

questions

22

In a household app synced across two offline phones, what must each edit carry so the server can tell it used a stale copy?

level: juniorimportance: must knowfreq 50%

answer

  1. the version the edit started from
  2. issued by the server, not the phone
  3. a conditional write: apply only if unchanged
  4. send changed fields, not the whole record
  5. the next edit takes the returned revision

basics

~20 s

The revision it was made from: the server-assigned version number or entity tag the phone stored with its copy. The server applies the edit only if that base still matches; otherwise it merges or rejects instead of silently overwriting.

solid answer

~50 s

Every shared record carries a revision the server assigns: a counter bumped on each accepted write, or an entity tag. The phone stores it beside its local copy and sends it as the edit's `baseRevision`, which makes the edit a conditional write. If the base matches the server's current revision, the server applies the edit and returns the new revision, which the phone stores. If it does not, another write landed in between, and the server runs that data type's conflict policy: merge, keep one, or reject with its current copy so the phone can resolve. Without a base, whichever phone syncs second silently overwrites the first, the classic lost update. Two details trip people up: send only the fields the user changed, and give the next queued edit the revision returned for the previous one, or the phone conflicts with itself.

code

json · 12 lines
json
{
  "request": {
    "record": "item-7f3a",
    "baseRevision": 41,
    "changes": { "quantity": 2 }
  },
  "responseWhenStale": {
    "outcome": "conflict",
    "currentRevision": 43,
    "current": { "name": "oat milk, barista", "quantity": 1, "checked": false }
  }
}

go deeper

for a junior

Recall that every edit names the version it was made from, and that a mismatch means someone else wrote in between.

for a middle

Explain the loop: store the server's revision with the row, send it as the base, store the revision that comes back, and send only the changed fields.

for a senior

Show the traps: queued edits that must chain revisions, a pulled change moving the base, and a replay whose first response was lost.

for a principal

Decide where revisions live as the app grows, per record or per field, and which data types justify the bookkeeping at all.

## The problem: a blind overwrite Picture a **shared household app**: two partners keep shopping lists, chore checklists and notes on their own phones, and both phones often work offline. Alex changes the quantity of "oat milk" from 1 to 2 on the train; meanwhile Sam, at home and online, renames it to "oat milk, barista". Alex's phone reconnects an hour later and sends the item. If the server simply stores whatever arrives, it has no way to know that Alex's edit was made on a copy that is now out of date. Depending on what Alex's phone sends, Sam's rename either disappears or survives by luck. The HTTP specification calls this the **lost update** problem: two clients act on the same resource in parallel and the second write erases the first without anyone being told. ## The revision: what it is and who assigns it The fix is to make every edit say which version of the record it was made from. That version label is the **base revision**. - **A revision** is a value the server changes on every accepted write to a record: an integer counter (`41`, `42`, ...) or an opaque **entity tag** (ETag), often derived from the stored content. - **The server issues it.** Only the server sees every write in one order, so only its label means the same thing to both phones. The phone's clock or a counter kept on the phone cannot play this role. - **The phone stores it with the row.** When the phone pulls a record, or gets a write accepted, it saves the revision next to its local copy. - **The edit sends it back** as `baseRevision`. This turns a plain write into a **conditional write**: apply it only if the record is still at that revision. ## The conditional write, step by step 1. The phone loads the item at revision 41 and stores `rev = 41` with it. 2. The user edits offline. The phone records the change and its base, 41. 3. On sync, the phone sends the changed fields plus `baseRevision: 41`. 4. The server compares 41 with the record's current revision. 5. **Match:** it applies the change, sets the revision to 42, and returns 42. The phone stores 42 as the row's new base. 6. **Mismatch** (say the record is at 43): another write landed in between. The server does not blindly apply the edit. It runs the policy chosen for that data type: merge the fields, keep one value, or reject with its current copy so the phone (and maybe the user) can resolve it. Over plain HTTP the base often travels as a precondition, and a mismatch is typically reported as 412 Precondition Failed; a sync API may instead return a conflict answer with the current state in its body, which is what a 409 Conflict is meant to carry. The header mechanics are not the point here. The point is that the server receives a base and compares it. ## What breaks the scheme in practice - **Sending the whole record.** If the phone sends every field, the untouched ones carry old values. Sam's rename looks like something Alex changed back, so it is either overwritten or flagged as a conflict that never happened. Send only the fields the user changed. - **Not chaining revisions.** If two edits to one item are queued offline, the second must use the revision returned for the first. Sending the original base again makes the phone conflict with its own earlier write. - **Forgetting pulled changes.** When the phone pulls a partner's change to a row, the stored base must move to the new revision, or the next local edit is judged stale. - **A lost response.** The write succeeded but the reply never arrived, so the replay's base now looks stale. The server must recognise the repeat, through the idempotency key the queue stored with the write, or because HTTP allows a success answer when the requested change has already been applied, rather than reporting a conflict. - **Treating a mismatch as failure.** A stale base is a signal, not an error. For most fields the server can still merge; only some cases need a person. ## Choosing the label | Label | How it is made | Good for | Watch out for | |---|---|---|---| | Revision counter | Server increments it per record on each write | Easy to log, compare and debug | Must be per record, not one global number | | Entity tag | Server derives it, often from content | Fits HTTP conditional requests | Opaque: the phone can only compare it for equality | | Phone timestamp | Phone's clock at edit time | Nothing, as a base | Says when, not which version was seen | A stale base is detected the same way for every data type in the app. What happens next, whether that is a merge, last-write-wins or the user's choice, is decided per data type, and that is where the real design work starts.

  • The phone's write succeeded but the response was lost. On replay its base looks stale. What should happen?
    The server already applied this exact change, so a conflict here would make the phone fight itself. Either the replay carries the same idempotency key the queue stored with the write, and the server returns the recorded outcome, or the server sees the requested change is already in place and answers success, which HTTP explicitly allows for a conditional state-changing request. The conflict policy must not fire on it.
  • Should the phone store a revision counter or an entity tag?
    Either works if the server issues it and changes it on every accepted write to that record. A counter is easy to log and reason about; an entity tag is opaque and only compared for equality. What fails is a label the phone makes up, such as its clock time or its own counter, because it names nothing the server issued.

Marking up a printed copy stamped 'version 41': the office accepts your changes only if the master is still version 41; otherwise someone compares your page with the newer master before anything is filed.

  • Without a base revision the server can still tell that a partner edited first.
  • The phone's clock time at the edit tells the server which version it saw.
  • Sending the whole record is harmless because the untouched fields did not change.
  • A stale base means the edit must be thrown away.
  • The stored base only needs updating after a full resync.
open as a page

In an offline community-events mobile app, where must an optimistic RSVP live so it still shows, marked pending, after the app is killed and relaunched?

level: juniorimportance: must knowfreq 52%

basics

~20 s

In the app's persistent local store, written in the same transaction as the RSVP's queued request, with a pending marker on the record itself. Screens observe the store, so the RSVP and its pending badge reappear after any relaunch.

open as a page

In an offline field-inspection mobile app, why must a checklist change and its outbox entry be written to disk in one local transaction?

level: juniorimportance: must knowfreq 55%

basics

~20 s

A backgrounded app can be killed with no shutdown code, so an in-memory queue dies with it. Committing the record change and its outbox entry in one transaction means no kill leaves a change shown but unsent, or queued but not shown.

open as a page

In a household app where partners edit shared lists offline, which conflict policy fits a checked flag, a note body, item order and a counter?

level: middleimportance: must knowfreq 52%

basics

~20 s

Choose per data type by what losing an edit costs: last-write-wins for a checked flag or a title, per-field merge for items, increments for counters, a sort key per item for order, and the user's choice for a note body.

open as a page

In a mobile mail client that pulls changes by sync token, when should it save the new token, and why then?

level: middleimportance: must knowfreq 47%

basics

~20 s

Save the new token only in the same local transaction that commits the changes it covers. Saved earlier, a kill skips those changes for good; saved with them, a kill at worst repeats a pull the client applies idempotently.

open as a page

In a community-events mobile app where the server assigns ids, how do you replace an offline-created event's temporary id everywhere once the create is acknowledged?

level: middleimportance: must knowfreq 48%

basics

~20 s

Swap it in one local transaction across the event row, every row that references it and still-queued requests, and keep an old-to-new mapping so open screens and saved links resolve. A device-minted UUID the server accepts avoids the swap.

open as a page

In an offline field-inspection mobile app, what does each outbox entry hold, and in what order must the entries replay?

level: middleimportance: must knowfreq 52%

basics

~20 s

Each entry holds the operation, the target record's device-minted id, the payload, its dependencies, a stored idempotency key and delivery state. Edits to one record replay in creation order and a child never precedes its parent; independent jobs drain separately.

open as a page

A mobile mail client returns after 60 days and the server rejects its sync token; how should it resync without losing unsent writes or re-downloading unchanged mail?

level: seniorimportance: must knowfreq 44%

basics

~20 s

Treat the rejection as "cannot compute changes", not "delete everything". List server messages with version tags, fetch only new or changed ones, delete local ones absent from the complete listing, and keep the outbox to replay on top.

open as a page

Hours after a member of a community-events mobile app creates an event offline and invites friends to it, the server rejects the create; how do you roll back and tell the user?

level: seniorimportance: must knowfreq 46%

basics

~20 s

Undo what claimed success — the event shown as published, the invitations shown as sent — but keep the member's work as an unpublished draft with the reason, offering fix-and-resend or discard; never revert silently.

open as a page

In a mobile mail client that syncs incrementally, why must deleted messages arrive as tombstones rather than simply being left out?

level: juniorimportance: should knowfreq 40%

basics

~20 s

An incremental pull returns only what changed, so a message missing from it is simply unchanged. The server must name each deleted message's id as a tombstone; otherwise the phone keeps showing mail that is gone everywhere else.

open as a page

In a household app resolving offline edits by last-write-wins, why is the phone's clock a weak way to pick the winner, and what is safer?

level: middleimportance: should knowfreq 46%

basics

~20 s

A phone's clock can drift or be set by hand, so a phone whose clock runs ahead wins ties it should lose. Let the server decide order by arrival or by the revision it assigns, which every device sees the same way.

open as a page

On first launch of a mobile mail client with 40,000 messages, what should it sync first, and how should it backfill the rest?

level: middleimportance: should knowfreq 38%

basics

~20 s

Fetch the folder list and the newest page of inbox headers first, capture a change token, and show the inbox. Then backfill older mail in resumable pages, fetching bodies on demand, while delta pulls from that token keep it current.

open as a page

In a community-events mobile app, an event edit is acknowledged while a later edit is still queued; how should the response update the local copy?

level: middleimportance: should knowfreq 40%

basics

~20 s

Store the response as the record's confirmed copy, so server-computed fields replace the device's guesses, then re-apply the still-queued later edit on top and keep the record marked pending until that edit is acknowledged too.

open as a page

In a field-inspection app's offline outbox, when is a queued write's idempotency key created, and how does that limit merging later edits into it?

level: middleimportance: should knowfreq 48%

basics

~20 s

The key is minted once with the entry and stored in it, so every replay, even after a relaunch, sends the same key. Since a key stands for one payload, later edits may be merged only into an entry never attempted.

open as a page

In an offline field-inspection mobile app, what app-wide sync status should technicians see, and what must happen to unsent outbox entries at sign-out?

level: middleimportance: should knowfreq 42%

basics

~20 s

Show counts derived from the outbox itself: changes waiting, sending, needing attention, and when it last synced. At sign-out, warn about unsent entries, try to send them, never send them under another account, and discard only on explicit confirmation.

open as a page

In a household app, when one partner deletes a shopping item while the other edits it offline, what should happen once the edit syncs?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Decide by what the edit carries: a small change to a deleted item, such as a tick, is dropped and the editor told; a substantive one restores the record or asks. A server tombstone makes the case recognisable.

open as a page

In a household app syncing two partners' phones, why should conflict rules run on the server, and when must a phone still resolve one with the user?

level: seniorimportance: should knowfreq 42%

basics

~20 s

The server sees every write in one order, so both phones get one verdict and rules change without a release. A phone settles only what needs a person, keeping the user's text, showing both and sending the choice as a new write.

open as a page

In a mobile mail client, a push nudge, a reconnect and an app foreground arrive within seconds; how should sync triggers be designed so they cause one pull?

level: seniorimportance: should knowfreq 41%

basics

~20 s

Route every trigger to one sync coordinator per account that allows one pull in flight. A trigger during a pull only sets a rerun flag, so a burst costs at most one more pull; a push nudge is a hint, not data.

open as a page

In a mobile mail client, how should an incoming sync pull be merged so it never hides the user's own unsent changes?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Keep the server's last-confirmed state apart from pending outbox operations. A pull updates only the server layer; the screen shows it with pending operations replayed on top, so an offline flag stays set until confirmed or rejected.

open as a page

In a community-events mobile app, how should an RSVP to a capacity-limited event be shown while the server has not yet confirmed a seat?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Not as "going". Record the request durably but show a distinct "requested — seat not confirmed" state, hold back anything that assumes a seat, and when online simply wait briefly for the server's answer.

open as a page

In an offline field-inspection mobile app, the server rejects a queued finding with 422 on every attempt and later entries depend on it; how should the outbox keep draining, and what does the technician see?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Classify the response: temporary failures retry later with backoff, but a 422 will fail again unchanged. Park that entry with its error, hold everything that depends on it, keep draining unrelated entries, and show the technician a fix-or-discard choice.

open as a page

In a household app with shared lists and notes, when does a CRDT or operational transform earn its cost, and for which data?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Only for free text two people really edit at once, such as a note written together. Lists, ticks and counters are covered by item ids, per-field merge and increments, without the history and server work a text-merging type adds.

open as a page