Real-Time Multi-User Spreadsheet Service

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a cloud-hosted, multi-user spreadsheet platform where dozens of collaborators can open the same workbook at once and modify cell values, formulas, rows, and columns with live synchronization across browsers.

Your architecture must keep concurrent editors converged on an identical grid state, tolerate temporary disconnects and offline catch-up cleanly, and expose concrete client and automation APIs with explicit request and response parameters (for instance, handling a scenario where one collaborator inserts a row above row 2 while a teammate simultaneously updates cell C4 to 250 and a dependent formula =C4*1.15 in D4 recalculates).

Scope & Expectations

  • Requirements, APIs, and data model: Define latency, durability, and convergence guarantees; specify concrete endpoints and payloads for session bootstrap, viewport reads, edit submission, live event streaming, and reconnect catch-up; and model workbooks, sheets, sparse cells, revisions, and operation logs.
  • Session sequencing and structural concurrency: Explain how active workbooks are routed and sequenced, how simultaneous cell writes and row/column insertions or deletions converge without coordinate-shift corruption, and how formula references adapt.
  • Formula engine, persistence, and recovery: Detail incremental dependency-graph recalculation, durable log replication, periodic snapshots, bounded crash replay, and idempotent client resynchronization.
  • Scaling and observability: Address memory sizing for large workbooks, broadcast fan-out batching, failover fencing, and runtime divergence detection.

Step-by-step walkthrough

  1. Clarify requirements and assumptions

    A spreadsheet behaves very differently from a plain text document, and four differences shape every part of the design: 1. Users edit whole cells (committed when they press Enter), not individual characters mid-typing. 2. The grid itself changes shape whenever someone inserts, deletes, or moves rows and columns. 3. Formulas (expressions like =SUM(A1:A3)) make one cell's value depend on many other cells across sheets. 4. Sheets can hold millions of cells, which is far too large to download into a browser tab all at once.

    Functional requirements

    • A workbook contains an ordered list of sheets, and each sheet is a 2D grid of cells. Every cell stores raw user input (a literal value or a formula), a computed result, and formatting metadata.
    • Users can edit cells; insert, delete, and move rows or columns; sort cell ranges; and add, rename, or delete sheets.
    • Everyone viewing the workbook sees other users' committed edits, active cell selections, and recalculated formula values in real time.
    • Users who lose network connectivity for seconds to hours can keep editing locally and sync automatically upon reconnect.
    • Full version history lets owners view or restore any earlier revision.
    • Role-based permissions per workbook (owner, editor, commenter, viewer) apply identically to browser sessions and external REST API scripts.

    Non-functional requirements

    • Instant local feedback, low remote latency: A user's own edit appears immediately (0 ms perceived wait). Collaborators in the same region see the edit within 200 ms p99 (meaning 99% of updates arrive in under 200 milliseconds).
    • Convergence: Any two clients that have received the same set of server updates must display identical cell contents and values.
    • Durability (no lost acknowledged edits): Once the server confirms an edit, that edit survives any single machine or availability-zone crash.
    • Fast failover: If the server hosting an active workbook crashes, users keep editing locally and resynchronize within ~15 seconds.

    Clarifying assumptions to state upfront

    • Conflict granularity: Whole-cell level. Two simultaneous edits to the exact same cell resolve by server arrival order ("last committed edit wins"), without character-by-character text merging inside a cell.
    • Delete vs. concurrent edit: If Dan deletes row 4 while Elena edits a cell in row 4, the deletion wins; Elena's edit is discarded and the UI notifies her so data never vanishes silently.
    • Workbook limits: Up to 10 million cells per workbook, with up to 100 concurrent editors and 1,000 concurrent viewers. Beyond 100 editors, additional users open in view-only mode.
    • Formula authority: The server is the single source of truth for calculated values; browsers compute a local preview for instant feedback and overwrite it if the server's authoritative result differs.
  2. Back-of-the-envelope numbers

    Before picking databases or network protocols, estimate traffic and memory step by step so we see where the real bottlenecks live.

    Assumed global usage
      Daily active users (DAU)              20,000,000
      Open workbooks at peak                2,000,000
      Average clients per open workbook     3
      Concurrent WebSocket connections      2M workbooks x 3 clients = 6,000,000 sockets
    
    Write throughput (operations)
      Active editors at peak                50% of 6M clients = 3,000,000 editing clients
      Commit frequency per active editor    1 edit every 5 seconds = 0.2 ops/s
      Global peak write rate                3,000,000 x 0.2 ops/s = 600,000 ops/s
      Average operation payload             ~200 bytes (sheet/row/col IDs, input, metadata)
      Peak operation-log write bandwidth    600,000 x 200 B = 120 MB/s
      Daily log storage (avg = 1/3 peak)    40 MB/s x 86,400 s/day = ~3.46 TB/day (~104 TB / 30 days)
    
    Per-workbook load
      Typical workbook                      1.5 editors x 0.2 ops/s = ~0.3 ops/s
      Hottest allowed workbook              100 editors x 1 op/s = 100 ops/s
      Naive broadcast (hottest workbook)    100 ops/s x 1,100 clients (100 editors + 1,000 viewers)
                                            = 110,000 outgoing messages/s for ONE workbook
      Batched broadcast (every 50 ms =      100 editors x 20 batches/s = 2,000 msgs/s
       20/s for editors; 200 ms = 5/s       + 1,000 viewers x 5 batches/s = 5,000 msgs/s
       for viewers)                         = 7,000 msgs/s total (a ~16x reduction)
    
    Memory for open workbooks
      Typical workbook (10K populated       10,000 cells x ~100 B (input + parsed formula + edges)
       cells; empty cells cost 0 bytes)     = ~1 MB in RAM
      All 2M open workbooks                 2,000,000 x 1 MB = 2 TB total RAM
      Session servers needed                2,000 GB / 32 GB usable RAM per host = ~63 hosts
                                            (~100 hosts with failover headroom)
      Largest allowed workbook (10M cells)  10,000,000 x ~100 B = ~1 GB -> gets a dedicated host
    

    Three architectural decisions fall directly out of this math: 1. Per-workbook write rate is tiny (≤ 100 ops/s): A single server thread can easily place every edit for one workbook into a strict 1, 2, 3... sequence. We do not need complex cross-server consensus on every edit; we just partition workbooks across ~100 stateful session servers by workbook_id. 2. Fan-out, not ingestion, stresses hot workbooks: Sending 110,000 individual WebSocket frames per second for one popular sheet would saturate CPU, so we batch outgoing updates every 50–200 ms. 3. Clients must load viewports, not full sheets: A 10M-cell workbook takes ~1 GB in memory, so browsers fetch only the visible screen window (say 200 rows × 26 columns) on demand.

  3. API design

    Clients authenticate with a standard user bearer token, exchange it for a short-lived workbook session token, fetch their visible cell window over HTTPS, and stream live edits over a WebSocket (a persistent two-way TCP connection between client and server). External automation scripts use the same operation format over HTTPS.

    1. Open a workbook session
    POST /v1/workbooks/{workbook_id}/sessions
      Request:  { client_id: "tab-9b2e",        # unique per browser tab or API worker
                  mode: "edit" | "view",
                  protocol_version: 3 }
      Response: 201 { session_token,            # 1-hour JWT scoped to workbook_id + role
                      role: "editor",
                      ws_url: "wss://rt.example.com/v1/stream",
                      revision: 4124,           # latest committed workbook revision
                      client_number: 19,        # prefix for generating offline-unique row/col IDs
                      sheets: [ { sheet_id, title, row_count, col_count, frozen_rows } ] }
    
    2. Fetch a viewport (visible slice of a sheet)
    GET /v1/workbooks/{wid}/sheets/{sheet_id}/cells?rows=0:200&cols=0:26&revision=4124
      Response: 200 { revision: 4124,
                      row_ids: ["r-1", "r-2", ...],   # maps 0-based screen row index -> stable row_id
                      col_ids: ["c-1", "c-2", ...],   # maps 0-based screen col index -> stable col_id
                      cells: [ { r: "r-4", c: "c-4", input: "=C4*1.15", value: 287.5, fmt: 3 } ],
                      formats: { "3": { number_format: "0.00", bold: true } } }
    
    3. Submit edits (REST fallback for scripts; identical payload sent over WebSocket)
    POST /v1/workbooks/{wid}/ops
      Request:  { client_id: "tab-9b2e",
                  client_seq: 31,               # strictly increasing 1, 2, 3... per client_id
                  base_revision: 4120,          # last server revision this client saw before editing
                  ops: [
                    { type: "set_cell", sheet_id: "s-1", row_id: "r-4", col_id: "c-4",
                      input: "=C4*1.15",
                      refs: { "C4": ["s-1", "r-4", "c-3"] } },
                    { type: "insert_rows", sheet_id: "s-1",
                      after_row_id: null,       # null = insert at top (before row 0); else anchor ID
                      new_row_ids: ["r-19-1"] }
                  ] }
      Response: 200 { client_seq: 31, revision: 4125,
                      dropped: [ { op_index: 0, reason: "ROW_DELETED" } ] }
    
    4. Real-time WebSocket stream
    WSS {ws_url}?workbook_id={wid}&session_token={tok}&since_revision=4120
      Client -> Server:
        { t: "submit", client_seq, base_revision, ops }
        { t: "presence", sheet_id, selection: { row_id, col_id } }    # ephemeral cursor highlight
      Server -> Client:
        { t: "ops", revision, author_id, client_id, client_seq, ops, positions }
        { t: "values", as_of_revision, cells: [ { sheet_id, r, c, value } ] }
        { t: "presence", user_id, sheet_id, selection }
        { t: "resync", reason: "REVISION_TOO_OLD" }
    
    5. HTTP catch-up after reconnect (for REST clients or initial sync)
    GET /v1/workbooks/{wid}/ops?since_revision=4120&limit=1000
      Response: 200 { ops: [...], current_revision: 4125, has_more: false }
      Response: 410 SNAPSHOT_REQUIRED           # behind > 10,000 ops; refetch viewport instead
    

    Why each parameter is essential: - client_id + client_seq guarantee idempotency (an idempotent operation produces the exact same result whether sent once or retried five times after a timeout). If client_seq <= last_applied_seq for that client_id, the server recognizes a retry and returns the earlier acknowledgement without applying the edit twice. - Stable row_id and col_id instead of "C4": Every row and column gets an immutable ID for life (after_row_id: null inserts above the very first row). Screen coordinates (0:200) appear only when fetching a viewport. - Client-bound refs inside formulas: When a user types =C4*1.15, "C4" is a screen coordinate on their screen right now. The browser immediately records refs: {"C4": ["s-1", "r-4", "c-3"]} so if someone else inserts a row at the top a millisecond earlier, the formula stays attached to (r-4, c-3). - Offline-safe ID generation: Combining the server-assigned client_number (high 32 bits) with a local counter (low 32 bits) lets clients create rows offline and immediately edit cells inside those new rows without waiting for a server round trip.

  4. Data model

    We store an append-only operation log (the authoritative history of every committed change) in a partitioned database, periodic snapshots (compressed checkpoints so recovery never replays millions of old edits) in object storage, and active ownership leases in a coordination service.

    Persistent storage
      workbooks         workbook_id PK, owner_id, title, home_region,
                        current_revision, snapshot_revision, created_at, deleted_at
      workbook_acl      PK (workbook_id, principal_id), role
    
      op_log            partition key = workbook_id
                        header record: { epoch, last_revision, next_client_number }
                        op rows:       PK (workbook_id, revision), epoch, author_id,
                                       client_id, client_seq, base_revision, ops_blob, created_at
    
      snapshots         PK (workbook_id, revision) -> manifest_url in object storage
                        manifest contains:
                          - per sheet: ordered list of row-block hashes, column order, format table
                          - client_progress map: client_id -> { client_number, last_client_seq }
                            (active clients from the past 7 days, so deduplication survives failover!)
                        row block: ~1,000 consecutive rows keyed by row_id (split > 2,000, merge < 500),
                                   immutable and named by SHA-256 content hash so unchanged blocks
                                   are reused across snapshots without rewriting the whole workbook
    
      session_leases    workbook_id PK -> { owner_server, epoch, expires_at }
    

    Inside the active session server's RAM, the live workbook uses sparse structures so empty cells take zero memory:

    In-memory document model
      Workbook  { revision, client_progress: map client_id -> last_client_seq,
                  sheets: ordered list of Sheet }
      Sheet     { sheet_id, title,
                  rows: OrderStatisticTree of (row_id, is_tombstone),
                  cols: OrderStatisticTree of (col_id, is_tombstone),
                  cells: HashMap (row_id, col_id) -> Cell }
      Cell      { input_raw: "=SUM(A1:A3)",
                  formula_ast: tree referencing (sheet_id, row_id, col_id) or corner IDs,
                  computed_value: 42,
                  format_id: 7 }
    

    Two data-structure choices keep every edit fast even on a million-row sheet: - Order-statistic tree for rows and cols: An order-statistic tree is a balanced binary search tree where every node stores how many live items and how many tombstones (markers kept temporarily for deleted rows so concurrent or offline edits can still find where a deleted row used to sit) live in its subtree. Looking up "which row_id is at screen row 5,000?" or inserting a row in the middle of 1,000,000 rows takes O(log N) (~20 pointer hops) instead of shifting a million-element array. - Workbook-wide revision counter: Revisions increment across the whole workbook (1, 2, 3...), not separately per sheet, because formulas like =Sheet2!A1 * 2 span sheets and need a single unambiguous timeline.

  5. High-level architecture

    Separating stateless connection handling from stateful workbook sequencing keeps socket failovers painless and reduces internal message fan-out.

      Browsers / Scripts
         | HTTPS (open session, viewport)           | WebSocket (submit ops, live updates)
         v                                          v
     +------------------+                  +--------------------------+
     |   API Servers    |                  |     Edge Gateways        |
     |   (stateless)    |                  | (stateless, 6M sockets)  |
     +--------+---------+                  +------------+-------------+
              | lookup / assign owner                   | 1 multiplexed stream
              v                                         | per (gateway, workbook)
     +------------------+   10s lease + epoch   +-------v---------------------------------+
     | Session Registry |<--------------------->|        Session Servers (~100 hosts)     |
     | (etcd / ZooKeeper|                       |  1. Sequencer thread (1 per workbook):  |
     |  coordination)   |                       |     dedupe -> validate -> apply -> rev  |
     +------------------+                       |  2. In-memory Workbook state            |
                                                |  3. Calc Engine worker pool (off-thread)|
                                                +-------+-----------------------+---------+
                                                        | conditional quorum    | async every 1,000 ops
                                                        | append (5-10 ms)      | or 10 minutes
                                                        v                       v
                                                +---------------+       +-----------------+
                                                |    Op Log     |       | Object Storage  |
                                                | (partitioned) |       | (row blocks)    |
                                                +---------------+       +-----------------+
    

    Follow one cell edit end to end: 1. Optimistic local apply (0 ms): Alice types 100 into a cell and presses Enter. Her browser immediately updates her screen, pushes the op onto her local pending queue, and sends submit over her WebSocket. 2. Routing (~1 ms): Her Edge Gateway looks up which Session Server owns workbook_id (cached locally) and forwards the op over a shared internal RPC stream. 3. Sequencing (< 1 ms): The workbook's single-threaded sequencer checks client_progress to ignore duplicate retries, validates permissions, applies the op to the in-memory model, updates client_progress[client_id] = client_seq, and assigns revision = R + 1. 4. Durable log write (~5–10 ms): The sequencer appends revision R + 1 to the op_log across a quorum (a majority, such as 2 out of 3 replicas in separate availability zones, guaranteeing the write survives a zone outage). 5. Broadcast (~20–40 ms to browsers): Only after the quorum write succeeds does the Session Server send revision R + 1 once to each subscribed Edge Gateway, which fans it out to connected browsers (including Alice's, serving as her acknowledgement). 6. Formula recalculation (async): Background calc workers evaluate affected formulas and emit {t: "values", as_of_revision: R + 1, ...} messages.

    Why put Edge Gateways in front of Session Servers? One Session Server holds ~20,000 open workbooks (~60,000 client sockets). If clients connected directly to the Session Server, a crash or deploy would drop 60,000 TCP connections at once and trigger a reconnection storm. With stateless Edge Gateways, browser WebSockets stay open while the gateway quietly re-routes traffic to the new Session Server owner.

  6. Deep dive: single-owner ordering and fencing

    Because a workbook receives at most 100 ops/s, one thread on one Session Server can sequence all edits without breaking a sweat. The hard distributed-systems problem is guaranteeing at most one active sequencer during crashes or freezes.

    Why a lease alone is unsafe: Suppose Server A holds a 10-second lease (a time-limited ownership lock stored in the Session Registry, renewed every 3 seconds) with epoch = 4. Suddenly Server A freezes for 12 seconds in a garbage-collection pause. Its lease expires! The Registry hands ownership to Server B with epoch = 5. A millisecond later, Server A wakes up, does not realize 12 seconds passed, and tries to write revision 101 while Server B is also writing revision 101. That split-brain (two servers acting as leader at the same time) would corrupt the workbook's history.

    We prevent split-brain completely using epoch fencing (attaching a monotonically increasing ownership number to every storage write so storage automatically rejects stale leaders):

    Timeline of a GC pause + failover on workbook W (currently at revision 100):
    
    1. Server A owns W with epoch = 4.
    2. Server A pauses for 12s -> lease expires in Session Registry.
    3. Server B acquires lease with epoch = 5:
         a) Conditional write on W's op_log header:
            SET epoch = 5 WHERE epoch < 5          -> succeeds! Header now has (epoch=5, last_rev=100).
         b) Loads latest snapshot (including client_progress) + replays op_log up to rev 100.
         c) Starts accepting client submits.
    4. Server B appends a new edit as revision 101:
         IF header.epoch == 5 AND header.last_revision == 100:
            INSERT op_row(rev=101, epoch=5); SET header.last_revision = 101   -> succeeds!
    5. Server A wakes up from pause and tries to append its stale edit with epoch = 4:
         IF header.epoch == 4 AND header.last_revision == 100:                -> FAILS (5 != 4)!
         Server A immediately halts its sequencer for W and closes its gateway streams.
    

    Because the header record and the op_row live in the exact same workbook_id storage partition, checking header.epoch and inserting revision = r + 1 executes as one fast atomic single-partition transaction—completely immune to clock skew or pauses. To keep disk latency low when multiple edits arrive within a few milliseconds, the sequencer uses group commit (flushing a tiny micro-batch of queued ops in one quorum write), keeping end-to-end same-region broadcast latency around 60–100 ms—comfortably inside our 200 ms p99 budget.

  7. Deep dive: concurrent edits, row/column shifts, and formulas

    Both the server and every browser run the exact same deterministic function apply(state, op). Why don't we need Operational Transformation (OT)—the classic collaborative-editing technique that rewrites an incoming edit's coordinates against every concurrent edit (for example turning "B5" into "B6" after an insert)? Because pairwise OT rules across cell edits, row inserts, row deletes, moves, and range sorts explode into dozens of error-prone combinations. Using stable row and column IDs eliminates coordinate shifting at the root.

    Trace what happens when Elena and Dan edit concurrently starting from revision 400:

    Initial state at rev 400:
      Screen rows:  Row 1 (r1), Row 2 (r2), Row 3 (r3), Row 4 (r4)
      Cell (r4, cC) currently holds 200; Cell (r4, cD) holds "=C4*1.15" bound to (r4, cC) -> 230.
    
    Concurrent user actions (both at base_revision = 400):
      - Dan inserts a new row (r88) above Row 2 -> op: insert_rows(after_row_id="r1", new=["r88"])
      - Elena types 250 into C4                 -> op: set_cell(row_id="r4", col_id="cC", input="250")
    
    Elena's screen immediately (optimistic local state):
      confirmed = state@400
      pending   = [ set_cell(r4, cC, "250") ]
      display   = apply(confirmed, pending)  -> shows 250 at C4 instantly.
    
    Server sequences Dan first (rev 401), then Elena second (rev 402):
      1. Elena receives rev 401 (Dan's insert):
         confirmed = apply(state@400, insert_rows(after="r1", new=["r88"]))
           -> Row order is now [r1, r88, r2, r3, r4]. Notice r4 is now Screen Row 5!
         display   = apply(confirmed, pending)
           -> Re-running pending set_cell(r4, cC, "250") puts 250 in r4 (now Screen Cell C5)!
      2. Elena receives rev 402 (her own op echoed back with client_id + client_seq):
         confirmed = apply(confirmed, set_cell(r4, cC, "250"))
         pending.pop_front()                 -> pending is now []
         display   = confirmed               -> every client shows 250 in C5 and "=C5*1.15" (287.5) in D5!
    

    How each tricky structural case behaves deterministically inside apply: - Inserting next to a deleted row: If Dan inserted r88 after r1 while Marco concurrently deleted r1, r1 still sits in the order-statistic tree as a tombstone, so r88 still has an unambiguous insertion spot right after r1. - Delete vs. edit: If Marco deletes r4 at rev 401 (r4 becomes a tombstone and its cells are cleared) and Elena's set_cell(r4, ...) arrives at rev 402, apply sees r4 is a tombstone, drops the cell write, and returns dropped: [{reason: "ROW_DELETED"}] so Elena's UI alerts her. - Formulas survive structural shifts: Because =SUM(A1:A3) was bound on the client to corner IDs (r1, cA) .. (r3, cA): - Inserting a row above r1 changes neither r1 nor r3; when rendered back to text, the UI looks up their new positions and displays =SUM(A2:A4) automatically without mutating the stored formula! - Inserting a row between r1 and r3 naturally falls inside the [r1 .. r3] span in the tree, expanding the sum just like Excel and Google Sheets. - Deleting a corner row (r1) immediately snaps that formula's corner inward to the next live row inside [r1 .. r3] (using the dependency index), or marks it #REF! if every row in the range was deleted. Snapping corners on delete ensures that garbage-collecting tombstones older than 7 days never breaks old formulas. - Sorting a range: Sorting is value-dependent, so clients do not re-sort independently. The server evaluates sort_range at sequencing time and logs the resulting deterministic op: move_rows when sorting across all columns of a sheet, or explicit set_cell writes when sorting only a subset of columns (so unselected columns stay in place). - Partial viewports on huge sheets: For sheets over 100K rows where browsers haven't loaded the full row_id tree, the server attaches resolved screen-index deltas (positions: {inserted_at_index: 4127, count: 1}) to broadcast ops so scrollbars and row headers stay accurate.

  8. Deep dive: formula recalculation, snapshots, and reconnect

    Incremental formula recalculation

    Re-evaluating all 10M cells on every edit would freeze the server. Instead, the Calc Engine maintains a directed acyclic graph (DAG) (a one-way dependency network where an arrow A1 -> B1 means formula B1 reads A1). To avoid creating 100,000 individual graph edges for =SUM(A1:A100000), each column holds an interval tree (an index of [start_row_id, end_row_id] ranges) queried in O(log N + K) time when a cell in that column changes.

    When cell X is edited at revision R:
      1. Parse X's new formula (if any) and update X's incoming dependency edges.
      2. Cycle check: walk dependents reachable from X; if X itself is reached, mark cells on
         that loop as #CYCLE! instead of looping forever.
      3. Collect dirty set = all transitive dependents of X.
      4. Evaluate dirty cells in topological order (parents before children so every formula
         runs at most once with fresh inputs):
           Example: A1 edited -> B1 (=A1+1) and C1 (=A1*2) run first -> D1 (=B1+C1) runs once after both.
      5. Broadcast { t: "values", as_of_revision: R, cells: [only changed results] }.
    

    Recalculation runs on worker threads off the sequencer in ~10 ms slices so incoming edits are never blocked. Every values packet carries as_of_revision: R, so browsers ignore out-of-order stale calculation packets. Volatile functions (NOW(), TODAY(), RAND()) execute exclusively on the server so two coworkers never see two different random numbers or timestamps in the same cell.

    Background snapshots and crash-safe reconnect

    Every 1,000 ops or 10 minutes, the Session Server takes a copy-on-write view (sharing unchanged memory pages so live edits don't pause), serializes any dirty ~1,000-row blocks by content hash to object storage, includes the 7-day client_progress map in the snapshot manifest, and updates snapshot_revision. Recovering a crashed workbook loads the snapshot manifest plus active viewport blocks and replays at most 1,000 log entries (~5–20 ms).

    When a disconnected browser (or reloaded tab reading from IndexedDB) reconnects:

    1. Client connects with since_revision = 4120 and local pending = [seq 31, seq 32].
    2. If (current_revision - 4120) <= 10,000 ops:
         Server streams missed ops (4120, current_revision] in order.
       Else (offline too long):
         Server sends { t: "resync" }; client refetches its visible viewport at current_revision.
    3. Client removes any pending op whose (client_id, client_seq) already appeared on the server,
       then re-submits remaining pending ops with their ORIGINAL client_seq.
    4. Server checks client_progress[client_id].last_client_seq (preserved across snapshots!):
       any already-applied client_seq is acked as a harmless no-op; new ones apply cleanly.
    

    Deduplicating in step 4 is critical: if Elena set C4 = 250 (applied at rev 4121, ack lost in a tunnel) and Dan later set C4 = 300 (rev 4122), re-applying Elena's retry as rev 4123 would silently overwrite Dan's newer 300 with Elena's stale 250.

  9. Scaling, failure handling, observability, and trade-offs

    Scaling and multi-region placement - Load-aware placement, not static hashing: Because one workbook takes 100 KB while another takes 1 GB and 100 ops/s, the Session Registry places newly opened workbooks onto the Session Server with the most free RAM and CPU headroom. Workbooks idle for 10 minutes are snapshotted and evicted from memory. - Regional locality: A workbook's active session server and op_log partition live in home_region (near the majority of editors). Cross-region collaborators still get 0 ms optimistic local edits and pay ~100–150 ms extra RTT only on the server ack.

    Failure modes and recovery

    Failure System response
    Client Wi-Fi drops / tab reloads Edits queue in browser IndexedDB and apply locally; since_revision + client_seq sync cleanly on reconnect.
    Edge Gateway crashes Stateless; browsers auto-reconnect via load balancer to another gateway with since_revision and lose zero edits.
    Session Server crashes 10s lease expires; new owner bumps epoch (fencing old host), loads snapshot + ≤ 1,000 ops + client_progress; ~10–15s pause in remote sync while local editing continues uninterrupted.
    Poison workbook crashes server After 3 consecutive crashes on load, registry quarantines the workbook into read-only snapshot mode and pages on-call.
    Subtle bug in apply(state, op) Periodic state-hash checks (clients hash their confirmed viewport cells at rev R and compare with the server) catch divergence immediately, force a clean resync, and log the exact ops around R.

    Summary of core design trade-offs - Single-owner server sequencer vs. CRDT (a Conflict-free Replicated Data Type is a decentralized data structure allowing replicas to merge concurrent edits in any order without a central coordinator): A single sequencer requires a 10–15s lease/fencing failover, while CRDTs work peer-to-peer; however, spreadsheets already need an authoritative server for permissions, 10M-cell storage, and formula evaluation, and a central revision log keeps history, range sorts, and memory footprint dramatically simpler than CRDT metadata. - Stable row/col IDs vs. coordinate OT: Requires an order-statistic tree (O(log N)) and 7-day tombstones, in exchange for eliminating brittle coordinate-transform bugs across cells and formulas. - Edge Gateway tier vs. direct connections: Adds ~1 ms internal hop, in exchange for zero dropped browser sockets during Session Server deploys/crashes and ~16x smaller fan-out from the sequencer.

Intuition & how it works

Think of a collaborative spreadsheet like a restaurant kitchen where one head expediter manages each table (workbook_id), stamping every incoming change with a single strictly increasing ticket number (revision 1, 2, 3...), while every row and column wears a permanent name badge (r4, cC) instead of being identified as "the 4th row from the top." When you type a value or a formula like =C4*1.15, your browser immediately displays your change locally for instant feedback, translates "C4" into its permanent badge (r4, cC), and sends that badge-based operation to the workbook's expediter. Because every collaborator applies the exact same numbered ticket stream to the exact same permanent row and column badges, everyone's grid converges to the identical state even when rows are inserted or deleted mid-flight.

Why does the naive approach fail? If clients send grid coordinates like "set C4 = 250" while another user inserts a new row above row 2 a millisecond earlier, row 4 shifts down to row 5 and your "250" silently overwrites the wrong item. Sending full-sheet snapshots on every edit is far too slow because a 10-million-cell workbook can weigh hundreds of megabytes, and allowing multiple servers to accept writes for the same workbook simultaneously without a single sequence creates conflicting histories and inconsistent formula totals.

Walk through a tiny concrete trace of two concurrent edits starting from revision 400:

Initial sheet (rev 400):  Row 1 (id=r1), Row 2 (id=r2), Row 3 (id=r3), Row 4 (id=r4)
                          Cell (r4, cC) = 200; Cell (r4, cD) has formula "=C4*1.15" bound to (r4, cC) -> 230

1. Dan inserts a new row above Row 2   -> sends insert_rows(after_row_id="r1", new_ids=["r88"])
2. Concurrently, Elena edits C4 to 250 -> sends set_cell(row_id="r4", col_id="cC", input="250", seq=1)
3. Sequencer orders Dan as rev 401:   row order becomes [r1, r88, r2, r3, r4] (r4 is now visually Row 5!)
4. Sequencer orders Elena as rev 402: set_cell(r4, cC, "250") lands on r4 (now displayed at C5)
5. Calc engine re-evaluates (r4, cD): reads (r4, cC)=250 -> broadcasts value 287.5; UI renders "=C5*1.15"

Key trade-offs

  • Single-owner server sequencer vs. CRDT: A CRDT (Conflict-free Replicated Data Type, a data structure that lets decentralized replicas merge edits in any order without a central coordinator) enables peer-to-peer offline merges, whereas a single-owner sequencer (one server process assigning a strict 1, 2, 3... order to a workbook's edits) requires lease management (a time-limited ownership lock) and epoch fencing (attaching an increasing generation number to log writes so a frozen old server cannot corrupt the log after failover), pausing confirmations for ~10–15 seconds on crash. For spreadsheets, the central sequencer wins because an authoritative server is already required for access control, 10M-cell viewport serving, and formula evaluation, and one total order makes version history and range sorts dramatically simpler.
  • Stable row/column IDs vs. coordinate-based Operational Transformation (OT): Operational Transformation (rewriting an operation's index coordinates against concurrent inserts and deletes, such as shifting "B5" to "B6") requires complex pairwise transform rules across cell edits, inserts, deletes, moves, and sorts. Stable IDs eliminate coordinate transforms and reduce client rebase (updating unconfirmed local edits when new server revisions arrive) to simply re-running pending ops on top of the latest confirmed state, at the cost of maintaining an order-statistic tree (a balanced tree storing subtree counts so index-to-ID lookups take O(log N) time) and keeping tombstones (temporary markers for deleted rows) for 7 days.
  • Whole-cell last-writer-wins vs. intra-cell text merging: Resolving simultaneous edits to the same cell by server revision order matches how users commit spreadsheet cells with Enter, avoiding character-level merge complexity; tagging edits with base_revision lets the UI politely notify a user if they overwrote a value written after they last looked.
  • Delete wins over concurrent edit: Discarding an edit to a row that was concurrently deleted (and notifying the author) matches the deleter's expectation rather than mysteriously resurrecting deleted rows.
  • Server-authoritative recalculation with local preview: Evaluating the DAG (directed acyclic graph, the one-way web of formula dependencies) in topological order (computing input cells before the formulas that depend on them) on the server guarantees API readers, partial-viewport browsers, and volatile functions (formulas like NOW() or RAND() whose output changes without cell edits) all see one consistent answer, while running the same engine locally on the author's machine preserves 0 ms responsiveness.
  • Periodic block snapshots (every 1,000 ops or 10 minutes): Copy-on-write snapshots (taking a point-in-time memory view without pausing live edits) split into content-hashed ~1,000-row blocks bound crash replay to ≤ 1,000 log entries while rewriting only modified row blocks in object storage.
  • Stateless WebSocket gateway tier: Adding a lightweight WebSocket (persistent two-way browser-to-server connection) gateway hop (~1 ms) keeps 6M client sockets alive across session-server restarts and lets the sequencer send one batched stream per gateway instead of fanning out to 1,100 individual browsers.

Common mistakes

  • Sending screen coordinates like "C4" without binding to stable IDs: A concurrent row insert above row 4 shifts the grid and causes in-flight edits to overwrite the wrong row.
  • Using stable IDs for cell writes while parsing formula strings like "=C4*1.15" on the server: "C4" inside a formula string is also a screen position; the browser must bind "C4" to (sheet_id, row_id, col_id) when typed, or concurrent structural edits will corrupt formula references.
  • Forgetting client_id + client_seq idempotency across snapshots and failovers: Without idempotency (ensuring repeated retries of the same request take effect only once) and persisting client_progress inside snapshots, reconnecting after a dropped acknowledgement can re-apply an old edit on top of a coworker's newer value.
  • Relying on a lease TTL without storage-level epoch fencing: A session server frozen in a long garbage-collection pause can wake up after its lease expired and append conflicting revisions unless the op_log enforces a conditional epoch check.
  • Broadcasting an edit to collaborators before the quorum log write succeeds: If the server crashes before disk persistence (a quorum is a majority of replicas across zones), other users briefly see "phantom" data that vanishes after recovery.
  • Expanding =SUM(A1:A100000) into 100,000 individual dependency edges: Large range formulas blow up memory and CPU unless stored as single range intervals in a per-column interval index.
  • Persisting cursor/selection highlights in the durable op_log: Cursor presence changes several times per second and has zero historical value; send it as throttled, ephemeral gateway messages instead.

Follow-up questions

  • How should per-user undo and redo behave when teammates have made intervening edits on the same worksheet? Each client maintains a personal undo stack containing only its own operations along with the inverse captured when each op was created (the previous cell input for set_cell, delete_rows for an insert, or a tombstone-restore op for delete_rows). Pressing Ctrl+Z submits that inverse as a brand-new forward revision in the op_log, so history never rewinds and Ctrl+Y (redo) is just the inverse of the undo. Before applying a cell undo, we check whether a teammate modified that cell in a later revision; if so, we skip overwriting their newer work (or prompt the user) rather than silently erasing a collaborator's edit.
  • Walk through what happens when someone edits a workbook offline during a long flight and reconnects hours later. Because pending ops are saved in browser IndexedDB with client-generated 64-bit row/column IDs and stable row_id/col_id targets, the client first catches up on missed revisions (or refetches its viewport if more than 10,000 ops elapsed) and then replays its pending queue in client_seq order. Most edits land cleanly even if teammates inserted or moved dozens of rows in the meantime. Edits targeting rows deleted during the flight return ROW_DELETED, and same-cell overwrites where base_revision predates a teammate's edit surface in a conflict summary banner so the user can review any clashes.
  • How do you keep a single popular 10-million-cell workbook responsive when 1,000 people are viewing and editing it live? The Session Registry isolates that workbook onto a dedicated high-memory Session Server (~1 GB RAM), and clients fetch only ~200-row viewports backed by cached 1,000-row snapshot blocks rather than downloading the whole workbook. Outgoing updates are batched every 200 ms for the 1,000 viewers and sent once per Edge Gateway to cap fan-out CPU. Formula recalculation runs asynchronously in 10 ms time slices using column interval indexes so only dirty downstream cells recompute, keeping the sequencer thread responsive under heavy viewing and editing load.

Follow-up questions

Similar questions

More Grammarly interview questions

All 11 Grammarly questions →