Design an Offline-First Note Sync Application
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a browser-based note-taking application where users author, edit, and delete text documents. Edits must appear instantaneously in the local interface even when internet access is degraded or completely unavailable, and local changes must automatically synchronize with a REST backend whenever connectivity permits.
Your design must operate under the following conditions and quality targets:
- Core authoring & sync: Users create, modify, and remove notes locally with immediate UI feedback, while background workers push pending mutations to the server, pull remote updates from other devices, and recover cleanly if the network drops or the server rejects a request.
- Offline-first continuity: Full reading and writing remain available with zero network connectivity, backed by persistent browser storage (such as IndexedDB).
- Flaky backend resilience: The remote REST service intermittently fails with
5xxstatus codes or ambiguous network timeouts; failed mutations must retry automatically using backoff without duplicating notes or corrupting state. - No silent data loss: Concurrent edits to the same note across devices must never silently overwrite one another. Character-level CRDTs or Operational Transformation are out of scope for the baseline design, provided you specify a clear mechanism to detect and reconcile conflicting versions.
Scope & Expectations
- Client state & offline queue: How data flows between in-memory UI state and durable browser storage, and how offline creates, edits, and deletes are queued and coalesced before transmission.
- Idempotent REST protocol & retry strategy: Request identifiers, API contracts, and backoff policies that keep retries safe across network drops and
5xxtimeouts. - Conflict detection & reconciliation: How divergent client and server versions are detected and merged or surfaced without silently discarding user edits.
- Edge cases & operational trade-offs: Handling multi-tab browser concurrency, permanent validation rejections, storage quotas, and key consistency vs. complexity trade-offs.
Step-by-step walkthrough
Clarify requirements and define "no silent data loss"
Storing notes in a database is straightforward; the real design challenge here is building an offline-first client-server sync protocol that feels instant locally, survives weeks without internet, tolerates an API that randomly returns
500errors or times out, and never silently loses user edits. Let's lock down explicit assumptions first.Scope and baseline assumptions
- Note structure & size: a note contains
title,body(Markdown text),tags, andfolder_id. Average size is4 KB,p99is100 KB, hard cap is1 MB(binary attachments are out of scope for v1). - Clients & ownership: web browsers on desktop and mobile (
~2devices per user, potentially multiple open tabs per browser). v1 focuses on single-owner multi-device sync (for example, editing on a flight on your laptop while an earlier edit synced from your phone); real-time multi-user keystroke co-editing is covered in the follow-ups. - Offline window: typically minutes to hours, supported cleanly up to 30 days offline.
- Ambiguous API failures: intermittent
5xxerrors and network timeouts. Crucially, a timeout is ambiguous — the server may have committed the write right before the response packet dropped! - Exact definition of "no silent data loss": every edit committed locally into IndexedDB (the browser's built-in transactional disk database) must end up either merged cleanly into the live note or preserved as a recoverable conflict version flagged with a visible banner — never silently overwritten by another device.
Functional & non-functional targets
- Local responsiveness: keystrokes update the editor within
1animation frame (< 16 ms) and flush to local IndexedDB within300 ms(plus immediately on tab hide/close). - Cross-device sync latency: when online and healthy, an edit appears on the user's other open devices within
5 s(p95) after a1 styping pause. - Idempotent retries: retrying a timed-out create, update, or delete never creates duplicate notes and never applies an edit twice.
- Note structure & size: a note contains
Estimate scale and client/server storage
Let's check traffic, storage, and why client-side edit coalescing matters:
Users & devices 10M registered users, 1M daily active users (DAU), ~2 devices/user Total notes 300 notes/user avg -> 3B notes * 4 KB = 12 TB live note data -> 16 PostgreSQL shards (by user_id) * ~750 GB per shard Typing vs. API calls ~30 min active writing/DAU/day at ~3 keystrokes/s = 5,400 keystrokes/day Coalescing policy Push after 1 s of typing pause (or at most once every 5 s of continuous typing) -> ~60 API writes/DAU/day (90x reduction vs. per-keystroke!) Write throughput 1M DAU * 60 = 60M writes/day -> ~700 writes/s avg, ~2,100 writes/s peak (3x) -> ~130 peak writes/s per Postgres shard; ~2.8 MB/s average write bandwidth Auxiliary server data Revision history (30 days, <=1 edit snapshot per 5 min + all conflicts): ~10M snapshots/day * 4 KB = 40 GB/day -> ~1.2 TB total Idempotency keys (7-day retention): 60M/day * 7 days * ~100 B ~= 42 GB total (~2.6 GB per shard!) Live notifications 30% of DAU online at peak = 300k open Server-Sent Events (SSE) streams (~15 stateless notify servers * 20k connections) + 60 s fallback poll (5k RPS) Client IndexedDB Average user: 300 notes * 4 KB * 2 (local + base copy) = ~2.4 MB Power user: 20,000 notes * 4 KB * 2 = ~160 MBTwo takeaways stand out: 1. Server throughput (
~130 writes/sper shard) is modest; client state machines carry the real complexity. 2. Coalescing edits locally cuts API load by90xand bounds how many requests accumulate during an outage.Design the REST sync API
Four golden rules make every REST mutation safe over an unreliable network:
- Client-generated
note_id(UUID v4/v7):POST /v1/notessends the note's primary key from the client so retrying a timed-out create can never mint a second note with a new ID. - Per-mutation
Idempotency-Key(op_idUUID) vs. per-attemptX-Attempt-Id:Idempotency-Keystays identical across all retries of one logical operation so the server deduplicates replays;X-Attempt-Idis generated fresh on each HTTP attempt so logs distinguish attempt #1 from retry #3. - Optimistic concurrency via
If-Match: "<base_version>": every update or delete names the integer server version the client started from — a compare-and-set (CAS) check where the server applies the write only if the note is still at that exact version. - Full-state replacement (
{title, body, tags, folder_id}): sending the complete note state (rather than unguarded"append 'hello'"deltas) guarantees applying a payload is self-contained and mergeable.
POST /v1/notes Create note Headers: Idempotency-Key: <op_id>, X-Attempt-Id: <uuid> Body: {id: <client_uuid>, title, body, tags, folder_id} -> 201 {id, version: 1, change_seq} | 409 {current} (if id already modified) PUT /v1/notes/{id} Update note Headers: Idempotency-Key: <op_id>, If-Match: "7" Body: {title, body, tags, folder_id, conflict_with_version?} -> 200 {version: 8, change_seq} -> 409 Conflict {current: {id, version, title, body, tags, folder_id, deleted}} -> 404 (purged) | 413 (>1 MB) | 422 (validation error) DELETE /v1/notes/{id} Soft-delete to 30-day trash Headers: Idempotency-Key: <op_id>, If-Match: "7" -> 200 {version: 8, deleted: true, change_seq} | 409 {current} POST /v1/notes/{id}/restore Restore trashed note (Idempotency-Key, If-Match) POST /v1/sync/batch Up to 50 operations after long offline sessions GET /v1/changes?cursor=<seq>&limit=500 Delta pull -> 200 {changes, next_cursor, has_more} | 410 Gone GET /v1/notes/manifest Compact [{id, version, deleted}] list for 410 full resync GET /v1/events SSE stream pushing lightweight {latest_seq} pokes POST /v1/client-telemetry Batched sync health metrics (never note text!)Returning the server's
currentnote directly inside the409 Conflictresponse body saves an extraGETround trip before merging!- Client-generated
Design the server and client data models
Server schema (PostgreSQL sharded by
user_id)notes PK (user_id, note_id) version INT monotonic integer (+1 per accepted write; never uses client clocks!) title, body, tags[], folder_id deleted_at NULL when live; timestamp when soft-deleted to trash conflict_with_ver NULL, or version number saved in note_revisions from an overlapping conflict change_seq BIGINT user-scoped sequence number of latest mutation (INDEX (user_id, change_seq)) user_seq PK (user_id) db_epoch INT incremented only if DB is ever restored from backup last_seq BIGINT incremented under row lock inside every write tx -> gap-free cursor! note_revisions PK (user_id, note_id, version, created_month) [monthly partitions, >=30d] title, body, tags, device_id, op_id, reason ('EDIT' | 'CONFLICT' | 'DELETE'), created_at idempotency_keys PK (user_id, op_id) [~2.6 GB/shard; indexed expires_at swept hourly] request_hash BYTEA, http_status INT, response_json JSONB, expires_at TIMESTAMPTZ purged_tombstones PK (user_id, note_id) [retained 90 days after 30-day trash purge] version_at_purge INT, change_seq BIGINTWhy two details here prevent classic production bugs: - Per-user
user_seqinstead of a globalBIGSERIAL: with a global auto-increment sequence, transaction101can finish committing before transaction100. A phone pulling in that millisecond savescursor = 101and permanently skips change100! Locking the single user'suser_seqrow serializes that user's commits cleanly with zero gaps. - UnpartitionedPK (user_id, op_id)on each shard: at~2.6 GBper shard for 7 days of keys, a single primary key enforces uniqueness across midnight boundaries without scanning multiple daily partitions.Client schema (one IndexedDB database
notebook_<user_id>per signed-in account)notes keyPath: note_id local: {title, body, tags, folder_id, deleted} <-- what the UI renders right now base: {title, body, tags, folder_id} | null <-- snapshot at base_version (for 3-way merge!) base_version: INT | null <-- null until initial CREATE succeeds sync_state: 'SYNCED' | 'PENDING' | 'CONFLICT' | 'ERROR' outbox keyPath: seq (auto-increment FIFO) op_id: UUID, note_id: UUID, kind: 'CREATE' | 'UPDATE' | 'DELETE' status: 'QUEUED' (unsent, coalesces edits) | 'FROZEN' (sent >=1x; immutable payload!) frozen_payload, frozen_base_version, attempts, next_retry_at, last_error meta cursor ('<db_epoch>:<seq>'), device_id, last_sync_at sync_log 500-entry ring buffer of {ts, op_id, attempt_id, note_hash, status, latency_ms}Sketch the end-to-end architecture
Browser Client (all tabs render UI; Web Lock elects ONE tab to run Sync Engine) ┌───────────────────────────────────────────────────────────────────────────────┐ │ Editor UI ◄──(<16 ms)──► In-Memory Store (open note, note list, badges) │ │ │ │ │ debounce 300 ms│(or immediate on pagehide / tab blur) │ │ ▼ │ │ IndexedDB: [ notes (local + base) ] + [ outbox (FROZEN + QUEUED) ] │ │ ▲ │ │ Sync Leader Tab (holds navigator.locks "sync:<user_id>"; BroadcastChannel) │ │ • Push Worker: outbox -> REST (Idempotency-Key, If-Match, jitter backoff) │ │ • Pull Worker: GET /v1/changes?cursor -> 3-way merge -> IndexedDB │ └──────────────────────┬───────────────────────────────────────────▲────────────┘ │ HTTPS REST │ SSE poke {latest_seq} ▼ │ (+ 60 s poll fallback) ┌────────────────────┐ ┌──────────┴──────────┐ │ API Gateway │ │ SSE Notify Service │ │ Authn, Rate Limits │ └──────────▲──────────┘ └──────────┬─────────┘ │ Redis Pub/Sub ▼ ┌──────────┴──────────┐ ┌────────────────────┐ │ Redis Cache │ │ Notes Service │─────────────────────►│ last_seq:<user_id> │ │ (stateless) │ update after commit └─────────────────────┘ └──────────┬─────────┘ │ single-shard ACID tx ▼ ┌──────────────────────────────────────┐ │ PostgreSQL Shards (by user_id) │ │ notes, user_seq, idempotency_keys, │ │ note_revisions, purged_tombstones │ └──────────────────────────────────────┘Deep dive 1: Client state layers and the coalescing outbox
To keep typing instant (
< 16 ms) while surviving reloads, tab crashes, and 30-day offline trips, state lives in three tiers with strict responsibilities:- In-memory UI store (ephemeral): absorbs every keystroke synchronously so typing never stutters when disk or network I/O stalls.
- IndexedDB (client source of truth): after
300 msof typing inactivity — and synchronously triggered onvisibilitychange/pagehide— a single atomic IndexedDBreadwritetransaction writes both the updatednotesrecord and theoutboxentry together. Because both stores update in one transaction, a crash can never leave an edited note missing from the outbox! On app startup, the UI hydrates straight from IndexedDB in< 50 msbefore touching the network. - PostgreSQL (global source of truth): durable across lost laptops and phones.
The Outbox Pattern with
QUEUEDvs.FROZENcoalescingAn outbox is a local durable queue of pending mutations written to disk before any network call is attempted. However, appending a brand-new queue item on every 300 ms save would queue thousands of operations during a long flight — and conversely, mutating an operation while its HTTP request is already in flight breaks idempotency (because retry #2 would send different text under the same
op_id!).We solve both problems by maintaining at most two outbox entries per note: - At most one
FROZENentry: already transmitted at least once; itsop_id,frozen_payload, andfrozen_base_versionare locked in stone until the server responds. - At most oneQUEUEDentry: sits behind anyFROZENentry and absorbs all new local edits via coalescing (merging multiple rapid edits into a single pending state).def enqueue_local_mutation(outbox, notes, note_id: str, kind: str) -> None: """Coalesce a local CREATE, UPDATE, or DELETE inside the same IndexedDB tx as the note save.""" queued = outbox.find(note_id=note_id, status="QUEUED") frozen = outbox.find(note_id=note_id, status="FROZEN") if queued is None: outbox.insert(note_id=note_id, kind=kind, status="QUEUED", op_id=new_uuid()) return # CREATE followed by offline edits stays a single CREATE carrying the latest text. if queued.kind == "CREATE" and kind == "UPDATE": return # CREATE followed by DELETE before the server ever heard of the note cancels out completely! if queued.kind == "CREATE" and kind == "DELETE" and frozen is None: outbox.delete(queued) notes.hard_delete_local(note_id) return # Otherwise (e.g. UPDATE -> DELETE, or Undo DELETE -> UPDATE), update the queued kind. queued.kind = kind outbox.save(queued) def next_operation_to_send(outbox, notes, note_id: str): """Return the in-flight FROZEN op for retry, or freeze the QUEUED op before its first send.""" frozen = outbox.find(note_id=note_id, status="FROZEN") if frozen is not None: return frozen # Retry MUST send the exact same op_id and frozen_payload! queued = outbox.find(note_id=note_id, status="QUEUED") if queued is None: return None note = notes.get(note_id) queued.frozen_payload = dict(note.local) queued.frozen_base_version = note.base_version queued.status = "FROZEN" # Persist FROZEN state to IndexedDB BEFORE opening the network socket. outbox.save(queued) return queuedWatch out for a subtle acknowledgment bug: when the
FROZENrequest returns200 {version: 8}, the user might have typed three more sentences while the request was on the wire (now sitting inQUEUED). Inside one IndexedDB transaction, delete theFROZENentry, setnote.base_version = 8, and setnote.base = frozen.frozen_payload(notnote.local!). Settingnote.base = note.localwould trick a later three-way merge into thinking those three unsent sentences were already on the server!Multi-tab safety & storage persistence: multiple open browser tabs coordinate via the Web Locks API (
navigator.locks.request("sync:<user_id>", ...)), ensuring exactly one leader tab runs the push/pull loop while notifying sibling tabs viaBroadcastChannel. On first login, callnavigator.storage.persist()to protect IndexedDB from automatic browser disk eviction, and warn if a user clicks Sign Out whileoutboxis non-empty.Deep dive 2: Idempotency and resilient retries against an unreliable API
Let's trace what happens on an ambiguous timeout when
PUT /v1/notes/90commits on the server, the Wi-Fi drops the200 OKresponse, and the client retries 4 seconds later:Client (Note 90, base_version = 7) Server (Note 90 at v7) ----------------------------------------------- --------------------------------------------------- Attempt 1: PUT /v1/notes/90 Locks Note 90 (v7 == 7); writes v8; saves op_id=K1 Idempotency-Key: K1, If-Match: "7" -> with response {version: 8}; COMMITS! X <--- 200 OK lost in network timeout! Attempt 2: PUT /v1/notes/90 (exact retry) Idempotency-Key: K1, If-Match: "7" -> • Without op_id (If-Match only): Sees v8 != 7 -> returns false 409 Conflict! • Without op_id OR If-Match: Overwrites blindly -> v9 + duplicate revision! • With idempotency_keys (our design): Finds K1 -> replays stored 200 {version: 8}!Server-side atomic transaction (
CREATE,UPDATE, andDELETEall recordop_id):def handle_update(db, user_id: str, op_id: str, note_id: str, base_ver: int, body: dict, req_hash: bytes): """Execute idempotent compare-and-set update inside a single PostgreSQL shard transaction.""" with db.transaction(): # 1. Lock user_seq / note in consistent order so concurrent retries serialize cleanly. note = db.select_note_for_update(user_id, note_id) # 2. Check idempotency table FIRST so retries after commit return the exact original 200. saved = db.get_idempotency_key(user_id, op_id) if saved is not None: if saved.request_hash != req_hash: return 422, {"code": "IDEMPOTENCY_PAYLOAD_MISMATCH", "retryable": False} return saved.http_status, saved.response_json if note is None: return 404, {"code": "NOTE_PURGED", "retryable": False} # 3. Compare-and-set check: reject if another device updated or trashed this note! # Do NOT cache 409 in idempotency_keys; conflict resolution sends a fresh op_id. if note.version != base_ver or note.deleted_at is not None: return 409, {"current": note.to_dict()} # 4. Advance gap-free per-user cursor and note version, then persist mutation + op_id. seq = db.increment_user_seq(user_id) new_ver = note.version + 1 db.update_note(user_id, note_id, body, version=new_ver, change_seq=seq) db.save_revision_if_due(user_id, note_id, new_ver, body, op_id) resp = {"version": new_ver, "change_seq": seq} db.insert_idempotency_key(user_id, op_id, req_hash, 200, resp, ttl_days=7) return 200, respRecording
op_idonCREATEas well solves a sneaky edge case: if Laptop createsN9, times out after server commit (v1), and Tablet editsN9tov2before Laptop retriesPOST, Laptop's retry hitsidempotency_keys, receives its original201 {version: 1}, anchorsbase = v1, and cleanly three-way merges Tablet'sv2! Even if Laptop stayed offline for 20 days past the 7-dayop_idexpiry,POSTfalls back toON CONFLICT (user_id, note_id)andPUTfalls back to409merge wherelocal == remoteresolves cleanly with zero duplicates.Client retry policy: exponential backoff with full jitter + per-note isolation
When 300,000 clients recover from a 5-minute server outage simultaneously, fixed delays (
1 s, 2 s, 4 s) make every browser retry in lockstep — a thundering herd that knocks the recovering API right back down. Exponential backoff with full jitter randomizes each wait across[0, cap]:import random def next_backoff_seconds(attempt: int, base_s: float = 1.0, max_s: float = 300.0) -> float: """Full jitter: pick uniformly from [0, min(max_s, base_s * 2 ** attempt)].""" ceiling = min(max_s, base_s * (2 ** attempt)) return random.uniform(0.0, ceiling)- Error classification: retry network errors,
10 stimeouts,500/502/503/504, and429(honoringRetry-After) forever without pop-up modals (showing subtle"Saved on this device"status). On401, pause the sync engine, refresh the auth token once, and resume. On permanent400/413/422(for example, a pasted text exceeding1 MB), park only that note's queue (sync_state = 'ERROR') so all other notes keep syncing! - Client circuit breaker: while notes are independent (up to 4 notes syncing in parallel), 5 consecutive
5xx/timeout failures trip a half-open mode sending just 1 probe request per backoff interval until the API recovers.
- Error classification: retry network errors,
Deep dive 3: Conflict detection, three-way merge, and offline deletes
Let's compare the main conflict-handling candidates:
Strategy How it works Why we reject or adopt it Client timestamps + Last-Write-Wins (LWW) Highest client_updated_atoverwrites the whole noteRejected for whole notes: mobile clocks drift by minutes, and LWW silently deletes the losing device's paragraphs! Version vectors ( {devA: 4, devB: 2})Per-replica counter map tracking causal history Overkill here: essential for peer-to-peer sync without a central server, whereas our server already serializes every note's writes in a single total order. Server version(If-Match) + Client 3-way merge + Conflict history (chosen)Server detects concurrent edits via integer version; client mergesbase,local, andremoteAdopted: zero clock reliance, automatic merging of non-overlapping edits, and zero silent data loss on true overlaps! How three-way merging resolves
409 Conflictautomatically Because IndexedDB savedbase(version7) alongsidelocal, receivingremote(version8) in the409body lets the client see who changed what: - Scalar fields (title,folder_id): if onlylocalchanged (remote == base), keeplocal; if onlyremotechanged (local == base), adoptremote; if both changed identically, keep it; only when both changed to different values is it a true conflict. - Tags: set merge(base_tags union added_local union added_remote) - removed_local - removed_remote. - Markdown body: line-level diff3 three-way merge (the same algorithmgit mergeuses).Clean merge trace (no user prompt needed!): base (v7): "Packing List\n- Passport\n- Charger\n" Tablet (v8): "Packing List\n- Passport\n- Charger\n- Adapter\n" (added bottom line online) Laptop: "Packing List\n- Passport (packed)\n- Charger\n" (edited line 2 on train) 1. Laptop reconnects -> PUT /v1/notes/N9 (If-Match: "7", op_id: K8) -> 409 {current: v8} 2. Laptop runs diff3(base=v7, local, remote=v8) -> edits touch disjoint lines -> clean merge! merged = "Packing List\n- Passport (packed)\n- Charger\n- Adapter\n" 3. Laptop sends NEW op (If-Match: "8", op_id: K9) -> 200 {version: 9}. Both edits preserved!What if both devices rewrote the exact same line (a true conflict)? Never inject ugly
<<<<<<< HEADmarkers into a user's prose, and never stall sync until the user clicks a modal (stalling breeds even bigger conflicts!). Instead: 1. Keep the local user's overlapping lines in the active body (so text never vanishes under their cursor) while merging any non-conflicting lines cleanly. 2. Push the merged result withIf-Match: "8"andconflict_with_version: 8. 3. The server snapshotsv8intonote_revisions(reason = 'CONFLICT') and setsnotes.conflict_with_ver = 8, lighting up a non-blocking"Conflicting edit saved from Phone — Compare side-by-side"banner on all devices!Pulling remote changes (
GET /v1/changes?cursor=), tombstones, and offline deletes - Pull triggers: app launch, tab focus,onlineevent, SSE{latest_seq}poke, and a60 sfallback poll. Save the updatedcursorinside the same IndexedDB transaction as the applied notes: synced notes update cleanly,QUEUEDnotes rebase via three-way merge immediately, and notes with an in-flightFROZENrequest wait~1 sfor their own response to settle. - Soft deletes, tombstones, and resurrection:DELETEmoves a note to 30-day trash (deleted = truein/v1/changes). After 30 days, purging the row writes a tombstone (a tiny deletion marker{note_id, version_at_purge, change_seq}) kept for 90 days. A device offline> 90days receives410 Goneand runs amanifestresync (deleting localSYNCEDnotes absent from the manifest while re-uploading any locallyPENDINGnotes). If a purged note is ever recreated, its server version resumes atversion_at_purge + 1so stale devices never ignore it as an older version! - Edit always beats a blind delete: if Device A deletesv7offline (DELETE If-Match: "7") while Device B editedv7 -> v8, the server returns409 {current: v8}and Device A restoresv8with a banner"Updated on another device after you deleted it [Delete anyway]". Re-clicking Delete takes 1 second; losing newly written paragraphs would be irreversible.Scaling, bottlenecks, and failure handling
Scaling & hot-path optimizations - Absorb idle polling with Redis: cache
last_seq:<user_id>in Redis (5 minTTL so a missed cache update heals within 5 minutes). When5,000 polls/sarrive withcursor >= last_seq, return{changes: [], has_more: false}in< 1 mswithout touching PostgreSQL! - Large-note optimization (> 64 KBup to1 MB): send compact diff patches anchored toIf-Match: "<base_version>"instead of re-uploading500 KBevery 5 seconds, and offload cold note bodies> 64 KBto object storage while keeping metadata in PostgreSQL. - Partitioned append-only history: drop expired monthlynote_revisionspartitions inO(1)metadata operations rather than running expensiveDELETEtable scans.End-to-end failure matrix
Failure scenario Graceful recovery behavior Intermittent 500s or10 stimeoutsRetries with identical op_id+ full-jitter backoff; UI stays snappy with"Saved on this device"badgeMulti-day outage / airplane mode Outbox coalesces to <= 2items/note; reconnect drains via/v1/sync/batch(50 ops/call) + jitterValidation rejection ( 413>1 MB,422)Parks only that note ( Couldn't sync — exceeds 1 MB); all other notes continue syncing normallyAuth token expires while offline 401pauses sync engine -> silent refresh -> resumes; if refresh expired, local editing stays unlocked until re-loginShared computer account switch Separate notebook_<user_id>IndexedDB per user prevents cross-account outbox leakageBrowser disk quota full ( QuotaExceededError)Evict cached bodies of old SYNCEDnotes (re-fetchable from server); never evictPENDINGnotesServer database restored from older backup Restore increments user_seq.db_epoch; mismatched client cursor<epoch>:<seq>triggers410manifest resync + re-uploads newer client notes!
Intuition & how it works
Imagine writing in a physical desk notebook (IndexedDB, the browser's built-in persistent transactional database) while an assistant sits beside an outgoing mail tray (the outbox — a durable local queue of changes waiting to reach the server). Every word you type appears on your page instantly from fast RAM (< 16 ms) and is saved into your desk notebook every 300 ms, so choppy hotel Wi-Fi or a crashed browser tab never interrupts your thoughts. Whenever you pause typing for a second, your assistant photocopies the current page, stamps the envelope with a permanent receipt number (idempotency key op_id — a client-generated UUID ensuring retries never apply the same change twice) and the server edition number you started editing from (If-Match: base_version, a compare-and-set check), and mails it to the server using randomized retry delays (exponential backoff with jitter). If your phone already published edition 8 while your laptop was offline editing edition 7, the server replies 409 Conflict with edition 8 attached; your assistant lays your original photocopy of edition 7 (base), your laptop page (local), and your phone's edition 8 (remote) side by side in a three-way merge, combining edits on different lines automatically and preserving both versions in history with a visible "Compare" banner whenever the exact same line changed!
Why do obvious shortcuts break an offline-first app? Calling PUT /notes/90 directly from in-memory React state loses unsent paragraphs on page reload and freezes the UI when requests time out. Retrying a timed-out POST /notes without a client-generated note_id UUID and Idempotency-Key creates duplicate copies of the same note, while mutating a queue item after its first HTTP attempt sends different text under the same receipt ID. Worst of all, resolving conflicts with client Date.now() timestamps (last-write-wins) lets a tablet with a clock skewed two minutes ahead silently erase an hour of offline writing on a laptop, and storing only local without base makes it impossible to tell whether a missing paragraph was newly added on the tablet or intentionally deleted on the laptop.
Let's trace a concrete 6-step scenario across a user's Tablet (on spotty cafe Wi-Fi) and Laptop (on an underground train), both starting from synced Note N9 at version = 7 ("Packing List:\n- Passport\n- Charger"):
Step Event Tablet / Laptop / Server state
---- --------------------------------------- ---------------------------------------------------------
1 Tablet adds bottom line "- Adapter"; Tablet freezes op K1 (base_v=7); Server commits v8 & saves
sends PUT If-Match: "7", op_id: K1, K1 -> {version: 8}; Tablet times out and backs off.
but cafe Wi-Fi drops the 200 OK reply!
2 Laptop (offline on train) edits line 2 Laptop saves local + QUEUED op K2 (base_v=7) in one
to "- Passport (packed)" IndexedDB tx; UI badge shows "Saved on this device".
3 Tablet retries exact frozen op K1 Server finds K1 in idempotency_keys -> replays stored
(If-Match: "7", op_id: K1) 200 {version: 8}! Tablet sets base = v8, badge = "Synced".
4 Laptop reconnects & sends frozen op K2 Server sees v8 != 7 -> returns 409 Conflict with v8 body.
(If-Match: "7", op_id: K2)
5 Laptop runs diff3(base=v7, local, v8) Laptop changed line 2; Tablet added line 4 -> no overlap!
Merged: "Packing List:\n- Passport (packed)\n- Charger\n- Adapter"
6 Laptop sends fresh op K3 (If-Match: "8") Server commits v9, pokes Tablet via SSE -> both at v9!
Key trade-offs
- IndexedDB as client source of truth vs. in-memory state only: Persisting
local,base, andoutboxin one atomic IndexedDB transaction (300 msdebounce +pagehideflush) adds client schema management and multi-tab coordination, but survives tab crashes, reloads, and 30-day offline sessions where memory-only apps lose work. - Coalescing
FROZEN+QUEUEDoutbox vs. full edit-operation log: Capping the outbox at two entries per note (1immutable in-flight request +1coalescing pending update) bounds queue size and replay time regardless of offline duration, giving up fine-grained keystroke replay that single-user Markdown sync doesn't need. - Full-state payloads vs. delta patches: Sending the whole
4 KBnote state makes mutations self-contained and simple to validate or merge; diff patches againstbase_versionare reserved for large notes (> 64 KB) to save upload bandwidth. - Server
idempotency_keys(7-dayTTL) +If-Matchvs.If-Matchalone:If-Matchalone already prevents applying an update twice, but turns every ambiguous timeout into a confusing409extra round trip (and fails onCREATEif another device edited the new note before the retry arrived). A~2.6 GB/shardkey table replays the exact200/201cleanly. - Server integer
version+ clientdiff3merge vs. timestamps or version vectors: A single monotonic integer per note detects every concurrent edit without trusting skewed client clocks or carrying peer-to-peer version vectors (maps of per-device counters needed only when devices sync directly without a central server), while savingCONFLICTrevisions guarantees zero silent data loss on same-line collisions. - Edit beats blind delete: Rejecting an offline
DELETE If-Match: "7"when the server is already atv8occasionally asks the user to confirm[Delete anyway], trading one extra click for never vaporizing unseen edits written on another device. - SSE
{latest_seq}poke +60 scursor polling: Server-Sent Events (SSE) (a lightweight unidirectional HTTP stream) delivers sub-second wake-ups to online tabs without carrying confidential note text, while Redis-cached60 scursor polling ensures dropped pokes never cause permanent drift.
Common mistakes
- Minting
note_idon the server duringPOST /notes: If the response times out after the database commits, the client's retry has no way to reference the first row and creates a duplicate note! Always generate UUIDnote_ids on the client. - Mutating an in-flight outbox entry when the user keeps typing: Folding new keystrokes into an already-transmitted
op_idviolates idempotency (422hash mismatch or silent loss of the newly typed words when the server replays the first response). Freezefrozen_payloadbefore sending! - Setting
note.base = note.localupon200 OK: Any words typed while thePUTwas in flight were not part offrozen_payload; settingbasetolocalinstead offrozen_payloadtricks the next three-way merge into treating unsent edits as already synced. - Ordering
/v1/changesby timestamps or a global auto-increment sequence: Clock skew and out-of-order transaction commits cause advancing cursors to permanently skip slightly slower concurrent transactions; lock and increment a per-useruser_seqcounter instead. - Retrying
4xxvalidation errors at the head of a single global FIFO queue: One oversized1.2 MBnote (413) blocks every other note from syncing forever unless queues are isolated pernote_idand non-retryable4xxerrors are parked. - Running independent sync loops in every browser tab: Two tabs read the same outbox row and fire duplicate concurrent requests; elect a single leader tab with
navigator.locksand broadcast updates overBroadcastChannel. - Hard-deleting database rows immediately: Without soft deletes and tombstones (lightweight deletion records retained after purge), a returning offline device cannot tell a deleted note apart from a new note and resurrects it or silently drops state.
Follow-up questions
- What architectural changes are required if multiple people must co-edit the same note live with sub-second keystroke updates? Whole-note
If-Matchpushes every1–5seconds break down when two people type in the same paragraph simultaneously, triggering non-stop409conflicts. Replace the Markdown body field's sync mechanism with character-level CRDTs (Conflict-free Replicated Data Types) — data structures like Yjs or Automerge where every insertion/deletion carries causal IDs so concurrent edits commute mathematically into the exact same text in any arrival order — or server-sequenced Operational Transformation (OT). Keep IndexedDB and the local outbox (buffering binary CRDT update frames offline with idempotent client batch IDs), add a stateful WebSocket room per activenote_idto relay sub-100 ms deltas and live cursor presence, and periodically compact the server's append-only CRDT update log into snapshots so document metadata overhead stays small. - Which client-side telemetry metrics and local diagnostic logs would you collect to investigate sync bugs reported by real users without exposing note content? Batch privacy-safe telemetry to
POST /v1/client-telemetry(never logging note titles or bodies!): track age of the oldest unsynced outbox entry (our #1 user-pain SLI — page oncall if> 1%of online clients exceed1 hour), outbox depth, end-to-end local-save-to-ack latency (p50/p95), status-code rates (5xx, timeout,409clean merge vs. true conflict, parked4xx), retry counts, IndexedDBQuotaExceededErrorrates,navigator.storage.persist()grant rate, and410full-resync frequency segmented by app version and browser. Locally, maintain a 500-entrysync_logring buffer recording{timestamp, op_id, attempt_id, hashed_note_id, base_version, http_status, latency_ms}auto-uploaded on parked errors or via a"Copy Sync Diagnostics"button so engineers can joinop_idandX-Attempt-Idstraight to server logs, plus a periodic(note_count, xor_hash_of_id_and_version)digest check to catch silent state drift. - Suppose one device deletes a note without internet access while another device edits that same note online—how should the system reconcile those actions upon reconnect? Because the offline
DELETE /v1/notes/{id}carriesIf-Match: "7"(the last version that device saw) while the server is now atversion = 8from the other device's update, the server atomically rejects the delete with409 Conflictand returns version8in the response body. Following our "an edit never loses to a blind delete" invariant, the client cancels the local deletion, writes version8into IndexedDB so the newly added text is immediately visible, and displays a clear banner: "This note was edited on another device while you were offline — [Keep note] [Delete anyway]" (where clicking Delete anyway issues a freshDELETEwithIf-Match: "8"). Conversely, if a device edits version7offline while another device soft-deleted the note to trash (version = 8, deleted_at != null), thePUTreceives409and automatically sendsrestore+PUTso offline writing is never silently buried in the trash.
Follow-up questions
- What architectural changes are required if multiple people must co-edit the same note live with sub-second keystroke updates?
- Which client-side telemetry metrics and local diagnostic logs would you collect to investigate sync bugs reported by real users without exposing note content?
- Suppose one device deletes a note without internet access while another device edits that same note online—how should the system reconcile those actions upon reconnect?
Similar questions
- Design an Armrest In-Flight Entertainment System
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency