Design a Real-Time Collaborative Spreadsheet Service
System DesignModel answerLast updated
Design a multi-user spreadsheet system where concurrent editors stay in sync, conflicts resolve correctly, and clients recover cleanly after disconnects.
The Problem
You're designing a cloud spreadsheet product — think of any tool where multiple people can edit the same grid simultaneously and see each other's changes in real time.
A workbook contains one or more sheets. Each sheet is a grid of cells that can hold raw values, formulas, or formatting. Any number of authenticated users can have the same workbook open at once, and edits from one user should appear on everyone else's screen within a fraction of a second.
What the system must support
- Create, open, and manage workbooks with multiple named sheets.
- Edit cell contents (values, formulas, formatting), and insert, delete, or reorder rows and columns.
- All clients editing concurrently converge to an identical final state — no silent divergence.
- Show live presence: where other users' cursors and selections are.
- Handle disconnects gracefully: a client that drops offline and reconnects should catch up on missed changes without losing its own pending edits.
- Maintain a version history with the ability to restore a prior state.
What the interviewer wants to see
Walk through your design end-to-end:
- Requirements — functional and non-functional, with rough scale estimates.
- API design — concrete endpoints and WebSocket messages, including the important request parameters and what they protect against.
- Data model — workbooks, sheets, cells, the operation log, and snapshots.
- Architecture — which services exist, how sessions are established, and how edits flow from client to all other clients.
- Conflict resolution — how two simultaneous edits to the same or related cells are handled correctly and deterministically.
- Row and column operations — why inserting a row mid-sheet is harder than it looks and how to solve it.
- Formula recalculation — where computation happens, what data structure drives it, and how cycles are caught.
- Persistence and recovery — durability guarantees, snapshotting strategy, and how a fresh server reloads a workbook.
- Scaling and observability — how the system handles hot workbooks, regional traffic, and failure of a document server.
Concrete trade-offs are expected throughout. Vague answers ("use a message queue") without justifying the choice are not enough.
Hints
Hint 1
Before anything else, nail down what 'consistent' means here. All clients must reach the same state at the same revision — not just eventually similar. That constraint drives almost every architectural choice downstream.
Hint 2
Rows and columns need stable internal IDs, not position indices. If you model a cell as (row 7, col 3) you'll spend the rest of the design fighting index-shift bugs in every concurrent-insert scenario. Make this decision early and explain why it simplifies your transform rules.
Hint 3
A central sequencer per workbook is the practical choice for conflict resolution. It gives you a total order of operations for free, which makes OT transforms straightforward, history trivial, and formula evaluation deterministic. Mention CRDTs and explain honestly why they're a worse fit here despite being fashionable.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Functional requirements
- Users create workbooks containing multiple sheets. Sheets hold cell values, formulas, and formatting.
- Insert, delete, and reorder rows, columns, and sheets.
- All concurrent editors converge to the same state at all times.
- Live presence: cursors and selections of other users are visible.
- Disconnected clients catch up on reconnect without dropping their pending local edits.
- Full version history with point-in-time restore.
Non-functional requirements
- Edits appear locally immediately (optimistic). Remote propagation under 200 ms p99 within a region.
- Durability: any acknowledged edit survives a server crash.
- Strong convergence: no two clients can permanently disagree on cell state.
- 99.95% availability — a single server failure pauses one workbook for seconds, not minutes.
Back-of-envelope
- 10M DAU × 200 ops/day ≈ 2B ops/day, or about 23K ops/s average, peaking near 100K ops/s.
- At ~200 bytes per op, the raw log grows roughly 400 GB/day before compaction.
- Typical workbook has 1–5 simultaneous editors; design for up to 100 editors and 1,000+ viewers on viral workbooks.
- Sheet size capped around 10M cells — load by viewport, never the whole sheet.
2. External API
POST /v1/workbooks/{wb_id}/sessions
body: { client_id, mode: "edit"|"view", last_known_revision? }
→ { session_id, ws_url, auth_token, current_revision, snapshot_revision }
GET /v1/workbooks/{wb_id}/sheets/{sheet_id}
?revision=&range=A1:Z200&include=values,formulas,formats
→ { revision, row_ids[], col_ids[], cells:[{row_id,col_id,raw,value,format}] }
POST /v1/workbooks/{wb_id}/ops
body: { session_id, client_id, client_seq, base_revision,
ops:[{type:"set_cell", sheet_id, row_id, col_id, raw},
{type:"insert_rows", sheet_id, after_row_id, new_row_ids[]}, ...] }
→ { applied_revision, transformed_ops[] } | 403 | 409 stale_session
WS subscribe: { type:"subscribe", wb_id, sheet_ids[], from_revision, viewport }
WS push: { type:"ops", revision, client_id, client_seq, ops[] }
{ type:"values", revision, cells[] } // server recalc results
{ type:"presence", user, selection }
GET /v1/workbooks/{wb_id}/ops?from_revision=N&limit=1000
→ { ops[], next_revision } | 410 snapshot_required
Why these fields matter
client_id+client_seqmake op submission idempotent — a retry after a dropped acknowledgement doesn't duplicate the edit.base_revisiontells the server exactly which ops the client had seen when it composed this edit, which is the input the transform function needs.range/viewportkeep fetch payloads tractable for large sheets.
3. Data Model
| Entity | Key fields |
|---|---|
| Workbook | wb_id, owner, acl, current_revision, latest_snapshot_rev |
| Sheet | sheet_id, wb_id, name, index, row_order[] (stable row IDs), col_order[] |
| Cell | (sheet_id, row_id, col_id) → raw, parsed_formula, computed_value, format, last_rev |
| Operation | (wb_id, revision) PK, client_id, client_seq, base_revision, type, payload, ts |
| Snapshot | wb_id, revision, blob_uri — full serialized workbook in object storage |
The most consequential decision here is stable row and column IDs. Display order lives in the row_order list; cells reference (row_id, col_id) permanently. This means:
- Inserting a row is a list append, not an index shift. No other cells need retransforming.
- Formulas are stored internally as ID references and rendered as A1 notation on the client.
- Two concurrent edits to different rows never conflict, even if one inserted a row between them.
4. Architecture
Client ⇄ WS Gateway (stateless, holds long-lived connections)
⇄ Document Server (one per workbook: sequencer, in-memory model, calc engine)
→ Op Log (strongly consistent DB, e.g. Spanner or CockroachDB)
→ Snapshot Worker → Object Storage + Cell Store
Coordination layer (etcd / ZooKeeper): workbook → document-server lease + epoch
Presence service: Redis pub/sub (ephemeral, never logged)
Session lifecycle
- Client opens a session → coordination layer resolves which document server owns this workbook (or assigns one).
- The gateway connects to that server and subscribes.
- Every op the server sequences is broadcast to all connected gateways for that workbook, which fan it out to their respective clients.
The lease carries an epoch number used as a fencing token. The op log rejects any append whose epoch is stale, preventing two document servers from both believing they own a workbook during a network partition.
5. Conflict Resolution: Server-Sequenced OT
One document server provides a total order for all ops on a workbook. This is the core design choice — it makes history, checksums, and recalculation deterministic at the cost of horizontal scaling per workbook (addressed below).
Server transform for an incoming op at base_revision = b:
- Pull all committed ops in the range
(b, current_revision]from memory. - Transform the incoming op against each of those ops in order.
- If the result is a no-op (e.g., edit targets a deleted row), record it as such but still assign a revision.
- Assign
revision = current + 1, append to log, then acknowledge and broadcast.
Client-side pending queue follows the Jupiter protocol:
- Apply ops locally immediately (optimistic).
- Keep at most one batch in-flight to the server.
- Transform incoming remote ops against the local pending queue before applying.
Key transform rules
- Two
set_cellops on the same cell: server order wins. The losing client sees their value overwritten; the UI can briefly highlight the cell. set_celltargeting a row or column that was concurrently deleted: becomes a no-op. The edit is preserved in history for potential restore.- Two
insert_rowsusing the same anchor: order the new rows by revision number, deterministically. - Move vs. edit: these never conflict because the edit references an ID, not a position.
Why not CRDTs? CRDTs are a better fit when clients need to stay offline for extended periods and merge independently. Here, a central authority is already required for ACL enforcement, formula evaluation, and validation. The added metadata overhead and trickier semantic invariants of CRDTs (especially for range formulas) aren't worth it.
6. Row and Column Insertions
Because rows and columns have stable IDs, insert_rows(after_row_id, new_ids[]) is a pure list mutation on row_order. Concurrent edits to cell contents require zero transformation.
Range formulas expand or contract correctly: a range is defined by its endpoint IDs evaluated over the current row_order, so inserting a row inside SUM(A1:A10) expands the sum automatically.
A1-style external API calls resolve letter/number notation to IDs at the base_revision the caller provided.
7. Formula Recalculation
The document server maintains an in-memory dependency graph: each cell maps to its precedents, with a reverse index of dependents. Range dependencies are stored as intervals rather than enumerating every cell, so SUM(A:A) doesn't create millions of edges.
On each committed op:
- Mark the cell as dirty and propagate dirtiness to all transitive dependents (DFS or BFS on the reverse index).
- Evaluate dirty cells in topological order.
- Detect cycles and mark them
#CIRCULAR!.
The document server is the source of truth for computed values. Clients may compute visible cells optimistically for instant feedback, but the server pushes authoritative values messages tagged with a revision that overwrite any local estimate.
8. Persistence and Recovery
- Every op is written to the durable op log before the server sends an acknowledgement. No ack = client retries.
- Snapshot workers periodically serialize the full in-memory workbook to object storage, recording the revision at which the snapshot was taken.
- On document server startup (or failover), load the latest snapshot, then replay the op log from
snapshot_revisiontocurrent_revisionto reconstruct in-memory state. For a well-tuned snapshot interval (e.g., every 5 minutes or 10K ops), replay takes seconds. - Clients requesting ops older than the oldest retained log entry receive a
410 snapshot_requiredresponse, instructing them to reload from the snapshot endpoint.
9. Scaling and Observability
Hot workbooks with many viewers are handled by separating read-only viewport delivery from the sequencer path. Viewers subscribe to a broadcast fan-out tier; they never submit ops, so they don't touch the sequencer.
Geographic distribution runs one document server per workbook in the region closest to the majority of editors. Cross-region editors pay the extra latency; this is an acceptable trade-off to keep a single sequencer.
Document server failure is detected via lease expiry (typically 10–30 seconds). A new server acquires the lease, replays from snapshot + log, and resumes. During that window clients buffer pending ops locally and resubmit once reconnected.
Key metrics to instrument
- Op end-to-end latency (submit → broadcast) at p50/p99/p999.
- Transform depth (how many ops does an incoming op need to transform against) — a spike here signals pathological concurrency.
- Snapshot lag (current_revision − latest_snapshot_revision) — predicts recovery time.
- Pending queue depth per client — detects stuck sessions.
Common mistakes to avoid
- Using row/column indices instead of stable IDs — every concurrent insert breaks every formula and transform.
- Skipping the epoch/fencing token — leads to split-brain where two sequencers both accept ops for the same workbook.
- Having the client apply server
valuesmessages at the wrong revision — causes computed value flicker or regression. - Forgetting idempotency on op submission — network retries create duplicate edits.