skip to content

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%

answer

  1. invalidate, don't wipe
  2. the outbox is never part of the reset
  3. compare versions, fetch only differences
  4. sweep only after the complete listing
  5. replay pending writes on top

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.

solid answer

~50 s

An expired token means the server no longer has the change history needed to answer "what changed since then". The local data is suspect, not worthless: the screen stays on it and the outbox is never touched. Then I run a **reconciling resync**: page through the server's full listing of ids with a version tag for each, taking the new token it returns at the start. Ids I lack, or whose version differs, go on a fetch list; matching versions keep their cached headers and bodies, so nothing unchanged is downloaded. I mark every local row unseen at the start and seen as pages arrive, and only after the last page do I delete what stayed unseen — except messages created locally that are still queued. Pending edits are re-applied over the refreshed base; one whose message vanished goes to the conflict policy. Delta pulls then resume from the new token.

code

pseudocode · 27 lines
pseudocode
function full_resync(folder):
  store.transaction:
    store.mark_all_unseen(folder)
  page = server.list(folder, fields = ["id", "version"])
  new_token = page.token
  loop:
    store.transaction:
      for item in page.items:
        local = store.find(item.id)
        if local == none or local.version != item.version:
          store.add_to_fetch_list(item.id)
        store.mark_seen(item.id)
      store.save_listing_cursor(folder, page.next)
    if page.next == none:
      break
    page = server.list(folder, after = page.next)
  store.transaction:
    for id in store.unseen_ids(folder):
      if outbox.has_pending_create(id):
        continue
      if outbox.has_pending_edit(id):
        conflicts.edit_versus_delete(id)
      else:
        store.delete_with_content(id)
    store.write_token(folder, new_token)
  fetch_in_batches(store.fetch_list(folder))
  outbox.reapply_pending_on_top(folder)

go deeper

for a junior

Recall that an expired token means the server cannot list changes any more, so the client compares its whole copy with the server's while keeping its unsent writes.

for a middle

Explain listing ids with version tags, fetching only new or changed messages, and deleting local ones only after the complete listing has arrived.

for a senior

Demonstrate the safety rules: outbox untouched, local-only creates spared, pending edits replayed or routed to the conflict policy, screen usable, new token taken at the start.

for a principal

Own the contract with the backend: retention window, per-folder scoping and listing cost decide how often phones away for weeks pay for this path.

## What the rejection means A sync token names a point in the server's change history. To answer "what changed since this token", the server needs every change after that point, including the **tombstones** that record deletions. History costs storage, so servers keep it for a bounded window — a few weeks of changes, or a cap on their number. This scenario assumes the server keeps about 30 days; a phone away for 60 days has a token older than anything the server can still compute from. The server rejects it with an explicit "cannot calculate changes" or "invalid token" error. That error is a statement about the server, not about the phone's data. Most local messages are probably still correct. The client must stop trusting its copy as a whole and **reconcile** it — not throw it away. ## What must survive - **The outbox.** Writes queued on the phone — flags, moves, sent replies, drafts — are user intent the server has not seen. They are never part of a reset. - **Local-only creates.** A message composed offline and still queued is absent from the server because it has not been sent, not because it was deleted. - **Unchanged cached content.** Bodies and attachments whose server version still matches stay; downloading them again wastes data and battery. - **A usable screen.** The mailbox stays readable and writable throughout, with a quiet "updating" state. ## The reconciling resync, step by step 1. In one transaction, mark every local message in the scope **unseen**. 2. Request the server's full listing for the scope: ids plus a **version tag** for each, such as an entity tag or revision — no bodies. Keep the new sync token it returns at the start. 3. For each listed id, compare with the local row (table below), add anything new or changed to a durable **fetch list**, and mark the row **seen**. Commit each page with a listing cursor so a kill resumes mid-listing. 4. After the **last** page, sweep: delete rows still unseen, except those with a pending create in the outbox; rows still unseen that carry a pending edit go to the conflict policy rather than being deleted. 5. Write the new token, fetch the fetch list in batches, re-apply pending outbox operations over the refreshed base, and resume normal delta pulls from the new token. ## Comparing by version | Local copy | Server listing | Action | |---|---|---| | absent | present | fetch it | | present, same version tag | present | keep header and body as they are | | present, different version tag | present | refetch the changed record | | present, created locally, still queued | absent | keep; the outbox will create it | | present, pending edit | absent | edit-versus-delete: hand to the conflict policy | | present | absent after the full listing | delete with its cached content | Comparing version tags is what keeps a full resync from becoming a full download: for a mailbox that mostly did not change, the cost is one pass over ids and versions plus the few messages that actually moved. ## Why the sweep waits for the end The listing arrives in pages. A message missing from page 3 may be on page 7. Deleting as pages arrive would remove mail the client had simply not been told about yet, then download it again. Only the **complete** enumeration proves absence, which is why the sweep runs once, at the end, over the rows still marked unseen. Taking the token at the start of the listing also closes a gap: messages deleted or changed on the server while the listing pages through are reported by the first delta pull from that token, and applying them is idempotent. ## Keeping the fallback rare - **Scope tokens per folder** where the server allows it, so one stale scope does not force all of them to resync. - **Pull whenever the app runs** or is given background time, so a token is refreshed well inside the window; how much background time the operating system grants is a separate question. - **Agree the retention window** with the backend team as part of the contract. None of these guarantees the fallback never fires, so it must always work and must always be safe. ## Summary - Expired token: reconcile, do not wipe. - The outbox and local-only creates are outside the reset. - Version tags decide what to fetch; only the complete listing decides what to delete. - Pending writes are replayed over the refreshed base, then delta sync resumes.

  • Why not simply wipe the local database and run the first-launch bootstrap again?
    A wipe deletes or orphans the outbox's pending writes, loses messages composed offline, and re-downloads thousands of unchanged messages and attachments over a mobile network. The listing-and-compare path costs one pass over ids and version tags plus only the messages that actually changed, and the mailbox stays usable throughout.
  • How would you keep this fallback rare for a phone that is often away for weeks?
    Scope tokens per folder so one stale scope does not reset all of them, pull whenever the app runs or is granted background time so tokens refresh inside the server's window, and agree that window with the backend team as part of the contract. The fallback must still work, because none of these guarantees it never fires.
  • What does the user see while the resync runs?
    The mailbox as it was, readable and writable, with a quiet updating state instead of an empty screen. New writes go to the outbox as usual. Messages appear or change as fetched pages land, and nothing is removed until the complete listing has been seen.

  • An expired token can be retried until the server accepts it again.
  • Wipe the local database and download the whole mailbox again.
  • Clear the outbox, since the resync brings back the server's truth anyway.
  • Delete local messages as soon as one listing page does not contain them.
  • A full resync necessarily re-downloads every message body.