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 5xx status 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 5xx timeouts.
  • 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

  1. 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 500 errors 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, and folder_id. Average size is 4 KB, p99 is 100 KB, hard cap is 1 MB (binary attachments are out of scope for v1).
    • Clients & ownership: web browsers on desktop and mobile (~2 devices 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 5xx errors 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 1 animation frame (< 16 ms) and flush to local IndexedDB within 300 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 a 1 s typing pause.
    • Idempotent retries: retrying a timed-out create, update, or delete never creates duplicate notes and never applies an edit twice.
  2. 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 MB
    

    Two takeaways stand out: 1. Server throughput (~130 writes/s per shard) is modest; client state machines carry the real complexity. 2. Coalescing edits locally cuts API load by 90x and bounds how many requests accumulate during an outage.

  3. Design the REST sync API

    Four golden rules make every REST mutation safe over an unreliable network:

    1. Client-generated note_id (UUID v4/v7): POST /v1/notes sends the note's primary key from the client so retrying a timed-out create can never mint a second note with a new ID.
    2. Per-mutation Idempotency-Key (op_id UUID) vs. per-attempt X-Attempt-Id: Idempotency-Key stays identical across all retries of one logical operation so the server deduplicates replays; X-Attempt-Id is generated fresh on each HTTP attempt so logs distinguish attempt #1 from retry #3.
    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.
    4. 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 current note directly inside the 409 Conflict response body saves an extra GET round trip before merging!

  4. 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 BIGINT
    

    Why two details here prevent classic production bugs: - Per-user user_seq instead of a global BIGSERIAL: with a global auto-increment sequence, transaction 101 can finish committing before transaction 100. A phone pulling in that millisecond saves cursor = 101 and permanently skips change 100! Locking the single user's user_seq row serializes that user's commits cleanly with zero gaps. - Unpartitioned PK (user_id, op_id) on each shard: at ~2.6 GB per 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}
    
  5. 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   │
                 └──────────────────────────────────────┘
    
  6. 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:

    1. In-memory UI store (ephemeral): absorbs every keystroke synchronously so typing never stutters when disk or network I/O stalls.
    2. IndexedDB (client source of truth): after 300 ms of typing inactivity — and synchronously triggered on visibilitychange / pagehide — a single atomic IndexedDB readwrite transaction writes both the updated notes record and the outbox entry 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 ms before touching the network.
    3. PostgreSQL (global source of truth): durable across lost laptops and phones.

    The Outbox Pattern with QUEUED vs. FROZEN coalescing

    An 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 FROZEN entry: already transmitted at least once; its op_id, frozen_payload, and frozen_base_version are locked in stone until the server responds. - At most one QUEUED entry: sits behind any FROZEN entry 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 queued
    

    Watch out for a subtle acknowledgment bug: when the FROZEN request returns 200 {version: 8}, the user might have typed three more sentences while the request was on the wire (now sitting in QUEUED). Inside one IndexedDB transaction, delete the FROZEN entry, set note.base_version = 8, and set note.base = frozen.frozen_payload (not note.local!). Setting note.base = note.local would 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 via BroadcastChannel. On first login, call navigator.storage.persist() to protect IndexedDB from automatic browser disk eviction, and warn if a user clicks Sign Out while outbox is non-empty.

  7. Deep dive 2: Idempotency and resilient retries against an unreliable API

    Let's trace what happens on an ambiguous timeout when PUT /v1/notes/90 commits on the server, the Wi-Fi drops the 200 OK response, 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, and DELETE all record op_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, resp
    

    Recording op_id on CREATE as well solves a sneaky edge case: if Laptop creates N9, times out after server commit (v1), and Tablet edits N9 to v2 before Laptop retries POST, Laptop's retry hits idempotency_keys, receives its original 201 {version: 1}, anchors base = v1, and cleanly three-way merges Tablet's v2! Even if Laptop stayed offline for 20 days past the 7-day op_id expiry, POST falls back to ON CONFLICT (user_id, note_id) and PUT falls back to 409 merge where local == remote resolves 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 s timeouts, 500/502/503/504, and 429 (honoring Retry-After) forever without pop-up modals (showing subtle "Saved on this device" status). On 401, pause the sync engine, refresh the auth token once, and resume. On permanent 400/413/422 (for example, a pasted text exceeding 1 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.
  8. 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_at overwrites the whole note Rejected 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 merges base, local, and remote Adopted: zero clock reliance, automatic merging of non-overlapping edits, and zero silent data loss on true overlaps!

    How three-way merging resolves 409 Conflict automatically Because IndexedDB saved base (version 7) alongside local, receiving remote (version 8) in the 409 body lets the client see who changed what: - Scalar fields (title, folder_id): if only local changed (remote == base), keep local; if only remote changed (local == base), adopt remote; 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 algorithm git merge uses).

    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 <<<<<<< HEAD markers 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 with If-Match: "8" and conflict_with_version: 8. 3. The server snapshots v8 into note_revisions (reason = 'CONFLICT') and sets notes.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, online event, SSE {latest_seq} poke, and a 60 s fallback poll. Save the updated cursor inside the same IndexedDB transaction as the applied notes: synced notes update cleanly, QUEUED notes rebase via three-way merge immediately, and notes with an in-flight FROZEN request wait ~1 s for their own response to settle. - Soft deletes, tombstones, and resurrection: DELETE moves a note to 30-day trash (deleted = true in /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 > 90 days receives 410 Gone and runs a manifest resync (deleting local SYNCED notes absent from the manifest while re-uploading any locally PENDING notes). If a purged note is ever recreated, its server version resumes at version_at_purge + 1 so stale devices never ignore it as an older version! - Edit always beats a blind delete: if Device A deletes v7 offline (DELETE If-Match: "7") while Device B edited v7 -> v8, the server returns 409 {current: v8} and Device A restores v8 with 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.

  9. Scaling, bottlenecks, and failure handling

    Scaling & hot-path optimizations - Absorb idle polling with Redis: cache last_seq:<user_id> in Redis (5 min TTL so a missed cache update heals within 5 minutes). When 5,000 polls/s arrive with cursor >= last_seq, return {changes: [], has_more: false} in < 1 ms without touching PostgreSQL! - Large-note optimization (> 64 KB up to 1 MB): send compact diff patches anchored to If-Match: "<base_version>" instead of re-uploading 500 KB every 5 seconds, and offload cold note bodies > 64 KB to object storage while keeping metadata in PostgreSQL. - Partitioned append-only history: drop expired monthly note_revisions partitions in O(1) metadata operations rather than running expensive DELETE table scans.

    End-to-end failure matrix

    Failure scenario Graceful recovery behavior
    Intermittent 500s or 10 s timeouts Retries with identical op_id + full-jitter backoff; UI stays snappy with "Saved on this device" badge
    Multi-day outage / airplane mode Outbox coalesces to <= 2 items/note; reconnect drains via /v1/sync/batch (50 ops/call) + jitter
    Validation rejection (413 >1 MB, 422) Parks only that note (Couldn't sync — exceeds 1 MB); all other notes continue syncing normally
    Auth token expires while offline 401 pauses sync engine -> silent refresh -> resumes; if refresh expired, local editing stays unlocked until re-login
    Shared computer account switch Separate notebook_<user_id> IndexedDB per user prevents cross-account outbox leakage
    Browser disk quota full (QuotaExceededError) Evict cached bodies of old SYNCED notes (re-fetchable from server); never evict PENDING notes
    Server database restored from older backup Restore increments user_seq.db_epoch; mismatched client cursor <epoch>:<seq> triggers 410 manifest 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, and outbox in one atomic IndexedDB transaction (300 ms debounce + pagehide flush) 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 + QUEUED outbox vs. full edit-operation log: Capping the outbox at two entries per note (1 immutable in-flight request + 1 coalescing 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 KB note state makes mutations self-contained and simple to validate or merge; diff patches against base_version are reserved for large notes (> 64 KB) to save upload bandwidth.
  • Server idempotency_keys (7-day TTL) + If-Match vs. If-Match alone: If-Match alone already prevents applying an update twice, but turns every ambiguous timeout into a confusing 409 extra round trip (and fails on CREATE if another device edited the new note before the retry arrived). A ~2.6 GB/shard key table replays the exact 200/201 cleanly.
  • Server integer version + client diff3 merge 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 saving CONFLICT revisions 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 at v8 occasionally 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 s cursor 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-cached 60 s cursor polling ensures dropped pokes never cause permanent drift.

Common mistakes

  • Minting note_id on the server during POST /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 UUID note_ids on the client.
  • Mutating an in-flight outbox entry when the user keeps typing: Folding new keystrokes into an already-transmitted op_id violates idempotency (422 hash mismatch or silent loss of the newly typed words when the server replays the first response). Freeze frozen_payload before sending!
  • Setting note.base = note.local upon 200 OK: Any words typed while the PUT was in flight were not part of frozen_payload; setting base to local instead of frozen_payload tricks the next three-way merge into treating unsent edits as already synced.
  • Ordering /v1/changes by 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-user user_seq counter instead.
  • Retrying 4xx validation errors at the head of a single global FIFO queue: One oversized 1.2 MB note (413) blocks every other note from syncing forever unless queues are isolated per note_id and non-retryable 4xx errors 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.locks and broadcast updates over BroadcastChannel.
  • 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-Match pushes every 1–5 seconds break down when two people type in the same paragraph simultaneously, triggering non-stop 409 conflicts. 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 active note_id to 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 exceed 1 hour), outbox depth, end-to-end local-save-to-ack latency (p50/p95), status-code rates (5xx, timeout, 409 clean merge vs. true conflict, parked 4xx), retry counts, IndexedDB QuotaExceededError rates, navigator.storage.persist() grant rate, and 410 full-resync frequency segmented by app version and browser. Locally, maintain a 500-entry sync_log ring 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 join op_id and X-Attempt-Id straight 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} carries If-Match: "7" (the last version that device saw) while the server is now at version = 8 from the other device's update, the server atomically rejects the delete with 409 Conflict and returns version 8 in the response body. Following our "an edit never loses to a blind delete" invariant, the client cancels the local deletion, writes version 8 into 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 fresh DELETE with If-Match: "8"). Conversely, if a device edits version 7 offline while another device soft-deleted the note to trash (version = 8, deleted_at != null), the PUT receives 409 and automatically sends restore + PUT so offline writing is never silently buried in the trash.

Follow-up questions

Similar questions

More Hex interview questions

All 2 Hex questions →