“Design a collaborative whiteboard” sounds friendly until you realize it is two hard problems wearing a trenchcoat. The first is a concurrency problem: two people grab the same rectangle, one drags it left while the other recolors it and a third deletes it, all within the same 50ms window, and the canvas has to end up in a state everyone agrees on without any of their intentions silently vanishing. The second is a spatial problem: the canvas is infinite, one board can hold a million shapes, and a client with a 1920x1080 viewport zoomed into one corner must not be forced to download or re-render the entire board to see its tiny slice. The interviewer is testing whether you can hold both at once - a merge strategy that never does naive last-write-wins on a shared object, and a spatial index that bounds every sync payload to what the eye can actually see.

Figma, Miro, Excalidraw, tldraw, FigJam - all the same shape. A shared 2D plane, shapes as first-class objects (not pixels), hundreds of cursors moving at once, and the brutal expectation that when you drag something it moves now, under your finger, with no server round-trip in the critical path. Sub-100ms perceived latency is not a nice-to-have; it is the entire product. A whiteboard that lags when you draw feels broken in a way that a chat app that lags does not.

The naive answer - “put the shapes in Postgres, broadcast every change over WebSocket, last write wins” - works beautifully in the demo with two users and dies the instant real people collide on the same object or a board grows past what fits in one render. This post builds the real thing: the CRDT shape store that merges concurrent move and delete operations cleanly, the quadtree viewport index that bounds sync traffic to the visible window, and the full read/write/ingestion path that ties them together.

This is adjacent to designing Google Docs, but a document is a linear sequence of characters where position is an ordering problem. A whiteboard is a bag of independent spatial objects where position is literally an (x, y) coordinate that two people fight over, and “what is visible” is a geometric query, not a scroll offset. The hard parts are different, so the data structures are different.

Functional Requirements (FR)

In scope:

  • Create shapes. A user draws a rectangle, ellipse, line, arrow, freehand stroke, sticky note, or text box. Each becomes a persistent object with an id, type, geometry (position, size, rotation), and style (color, stroke, fill, z-order).
  • Move / transform shapes. Drag to reposition, resize, rotate. This is the highest-frequency mutation and the one most likely to collide, because moving is what everyone does constantly.
  • Edit shape properties. Change color, stroke width, text content, z-order. Independent of position, and frequently concurrent with a move by someone else.
  • Delete shapes. Remove an object. Must interact sanely with a concurrent move on the same object (more on this below - it is the crux).
  • Infinite canvas. The coordinate plane is unbounded. Users pan and zoom freely. There is no “page.”
  • Live presence. Every user sees every other user’s cursor position and current selection in real time (the “who is here and what are they touching” layer).
  • Viewport-scoped sync. A client receives updates for the region it is looking at, not the whole board.
  • Persistence and reload. Close the tab, reopen, the board is exactly as you left it, including everyone else’s changes.
  • Offline-ish tolerance. A brief network blip should not lose your local edits; they reconcile when the connection returns.

Explicitly out of scope (own the scope):

  • Rich text editing inside a text box with its own concurrent cursors. A text box’s content can be a nested CRDT (a whole Google-Docs-shaped sub-problem); here the text box is one shape and we treat its text as a property. We mention the nesting and move on.
  • Pixel-level raster painting (Photoshop-style). We store vector shapes and strokes as objects, not a bitmap. A raster layer is a different storage model.
  • Full version history / branching. We keep an operation log and can implement time-travel on top of it, but a Git-style branch/merge UX is its own project.
  • Access control depth. We assume board-level permissions (who can open/edit). Fine-grained per-shape ACLs are a bolt-on.
  • Export / rendering to PDF/PNG server-side. A separate rendering service reads the shape store; not the core design.
  • Voice/video. Presence is cursors and selections, not a call.

The one decision that drives everything: shapes are independent objects, not a shared ordered sequence, and the hard part is merging concurrent mutations on the same object without last-write-wins loss while only ever syncing the visible subset. Everything below is machinery for those two sentences.

Non-Functional Requirements (NFR)

  • Scale: millions of boards total. A single hot board supports hundreds of concurrent editors (call it up to ~500 active cursors), and can hold up to ~1M shapes. The long tail of boards is small (a handful of users, a few hundred shapes), but the design must not fall over on the big ones.
  • Latency: sub-100ms perceived latency for your own actions - which in practice means 0ms, because your own edits apply optimistically to your local canvas before any server round-trip. Remote edits from other users should appear within ~50-150ms (one network hop plus fan-out). Cursor updates are even tighter and lossier - ~30-60ms, drop-on-stale.
  • Availability: 99.9%+ on the editing path. A board becoming read-only or momentarily unsyncable during a failover is a bad minute; losing committed shapes is unacceptable.
  • Consistency: strong eventual consistency - all clients that have received the same set of operations converge to the identical canvas, regardless of the order they arrived in. No central lock on shapes; no “someone is editing this, you can’t.” Concurrent edits merge by CRDT rules, not by rejecting one party.
  • Durability: an acknowledged shape mutation survives a server crash. We accept that the last few hundred ms of un-acked local edits live only on the client until confirmed (the client replays them on reconnect).
  • Correctness invariants:
    • Convergence: apply(ops, order_A) == apply(ops, order_B) for any permutation - the canvas is a function of the set of operations, not their arrival order.
    • No silent intent loss: a concurrent move and recolor of the same shape keep both the new position and the new color. A concurrent move and delete resolves deterministically and identically on every client (not “it depends who you ask”).
    • Visibility bound: a client’s inbound sync stream is proportional to the shapes in (and near) its viewport, never to the board’s total size.

Back-of-the-Envelope Estimation (BoE)

Real numbers, with the arithmetic, because they tell us where the pressure actually is - and for a whiteboard the pressure is per board, not fleet-wide.

Users and boards:

Say 10M daily active users, each active on ~3 boards/day => 30M board-sessions/day.
Average concurrent editors per active board is small (~3), but the design target
  is the hot board: up to 500 concurrent editors on one board.
Peak concurrent sessions fleet-wide: 10M DAU, ~5% online at peak => ~500,000 live WebSocket connections.

Write load (mutation ops) - the interesting part, and it is per-board:

An active user generates:
  - a DRAG is a stream of move ops. A 1-second drag at 60fps = 60 move ops,
    but we THROTTLE outbound to ~20-30 ops/sec per moving object. Call it 25 ops/sec while dragging.
  - most of the time a user is not dragging: idle, or clicking. Average ~2-5 mutation ops/sec sustained.
On a 500-user hot board, assume ~20% are actively manipulating at once => 100 active movers.
  100 movers * 25 ops/sec = 2,500 mutation ops/sec on ONE board.

That 2,500 ops/sec on a single board is the number that breaks naive designs. It is not a fleet problem; it is a single-room fan-out problem.

Fan-out (the real killer):

Every mutation op on a board must reach every OTHER client on that board (minus viewport filtering).
Naive broadcast on a 500-user board: 2,500 ops/sec * 500 recipients = 1,250,000 messages/sec
  out of the server for ONE board. That is the number that melts a single room.
Viewport filtering is what saves us: a typical client sees maybe 50-150 shapes in view,
  and most movers are working in regions it is NOT looking at.
With viewport filtering, a client receives only ops touching its visible region:
  realistically ~50-200 ops/sec per client instead of 2,500. A 10-25x reduction, and it SCALES
  with board size - the bigger and more spread-out the board, the more filtering helps.

Cursor/presence load (separate, lossy channel):

500 users moving cursors at ~20 updates/sec = 10,000 cursor msgs/sec inbound per board,
  fanned out = up to 5,000,000 msgs/sec if naive. Cursors are throttled, viewport-filtered,
  and DROP-ON-STALE (only the latest position matters), so this rides a separate cheap channel.

Storage:

Per shape record ~ 300 bytes (id, type, geometry, style, CRDT metadata, z-order).
1M shapes/board * 300 bytes = ~300 MB per large board of shape state.
Plus the operation log for history/replay: say each board sees 5M ops over its life,
  ~150 bytes/op = 750 MB of log per heavily-used board (compactable).
Fleet: 50M boards, but P50 board is tiny (<1 MB). Hot boards dominate storage;
  total is in the low petabytes, dominated by the op logs, which we compact and tier to cold storage.

Bandwidth:

A mutation op on the wire ~120 bytes (shape_id, field deltas, CRDT tags).
Per client inbound with viewport filtering: ~150 ops/sec * 120 B = ~18 KB/s. Trivial per client.
Initial board load (visible region): ~150 shapes * 300 B = ~45 KB. One snapshot fetch, then deltas.
The expensive thing is NOT bytes; it is connection count (500K live WebSockets) and
  per-board fan-out, both of which are CPU/memory on the realtime tier, not bandwidth.

The takeaways that set the budget: (1) the problem is per-board fan-out, not fleet throughput - a single hot room is the unit that breaks. (2) Viewport filtering is not an optimization, it is load-bearing - it turns an un-survivable 1.25M msgs/sec broadcast into ~150 ops/sec per client, and it gets better as boards grow. (3) State is small per board but there are many boards, so we partition by board and pin a board to one owner. (4) The scarce resource is live connections and per-board CPU, so the realtime tier is the thing we shard and scale, and the merge logic must be cheap per op.

High-Level Design (HLD)

The architecture pins each board to a single authoritative board server (a stateful realtime process that owns the room), fronts it with stateless WebSocket gateways, holds the board’s shapes in memory as a CRDT indexed by a quadtree, and persists the operation log and periodic snapshots to durable storage. Clients apply their own edits optimistically and reconcile against the authoritative stream.

   ┌───────────────┐   WebSocket (ops in, filtered ops out)   ┌────────────────────────┐
   │   Client A     │ ◀──────────────────────────────────────▶ │  Realtime Gateway       │
   │ - local canvas │                                           │  (stateless, sticky     │
   │ - local CRDT   │        presence (cursors) on a            │   by board_id)          │
   │ - optimistic   │        separate lossy channel             │  - authn, viewport msg  │
   │   apply        │                                           │  - routes to board owner│
   └───────────────┘                                           └───────────┬────────────┘
   ┌───────────────┐                                                        │
   │   Client B     │ ◀──────────────────────────────────────────────────▶ │
   └───────────────┘                                                        │
                                                   consistent hash(board_id)│
                                               ┌───────────────────────────▼──────────────────────┐
                                               │   Board Server (stateful, ONE owner per board)     │
                                               │  ┌──────────────────────────────────────────────┐ │
                                               │  │  In-memory CRDT shape store                    │ │
                                               │  │   shapes: id -> { geometry LWW-reg,            │ │
                                               │  │     style LWW-reg, deleted (OR-Set tombstone), │ │
                                               │  │     z-order fractional index }                 │ │
                                               │  └──────────────────────────────────────────────┘ │
                                               │  ┌──────────────────────────────────────────────┐ │
                                               │  │  Quadtree viewport index (shape bbox -> node)  │ │
                                               │  │   query(viewport_rect) -> visible shape ids    │ │
                                               │  └──────────────────────────────────────────────┘ │
                                               │  - merges incoming ops, assigns causal tags        │
                                               │  - fan-out: for each op, find subscribers whose    │
                                               │    viewport intersects the op's region, send       │
                                               │  - appends ops to log, snapshots periodically      │
                                               └──────┬───────────────────────────────┬─────────────┘
                                 append ops (durable) │                               │ snapshot every N ops / T secs
                                       ┌──────────────▼────────────┐      ┌───────────▼───────────────┐
                                       │  Op Log (append-only)      │      │  Snapshot store (object    │
                                       │  Kafka / WAL per board     │      │  store: compacted CRDT     │
                                       │  durable, ordered per board│      │  state blob per board)     │
                                       └──────────────┬─────────────┘      └───────────┬───────────────┘
                                                      │ replicate for failover          │ load on cold start
                                       ┌──────────────▼────────────┐      ┌───────────▼───────────────┐
                                       │  Standby board server /    │      │  Metadata DB (SQL):        │
                                       │  log replica (hot failover)│      │  boards, members, acls,    │
                                       └────────────────────────────┘      │  snapshot pointers         │
                                                                           └────────────────────────────┘

Write flow (you drag a shape) - the 0ms path:

  1. You grab a rectangle and drag. The client immediately updates its local canvas - the shape moves under your cursor with zero server involvement. This is the sub-100ms guarantee: your own edits never wait for the network.
  2. In parallel, the client emits throttled move ops (~25/sec) over the WebSocket: {shape_id, field: geometry, value: {x,y}, lamport_ts, actor_id}. Each op carries a logical timestamp and the actor’s id for CRDT merge.
  3. The op hits a stateless gateway, which routes it (by board_id) to the board’s authoritative board server.
  4. The board server merges the op into its in-memory CRDT (geometry is a last-writer-wins register keyed by the Lamport timestamp - details in the deep dive), appends it to the durable per-board op log, and updates the quadtree entry for that shape (its bounding box moved).
  5. The board server computes fan-out: it queries which connected clients have a viewport that intersects the shape’s old-or-new region, and sends the merged op only to those clients. A client looking at a different corner of the infinite canvas never receives it.
  6. Each recipient applies the op to its local CRDT and re-renders the affected region. Convergence is guaranteed because the merge is commutative.

Write flow, conflict case (two people move the same shape):

  • Both move ops carry Lamport timestamps and actor ids. The board server’s geometry register resolves them deterministically (higher timestamp wins, actor id breaks ties). Crucially this resolution is identical on every client, so everyone converges to the same final position with no round-trip negotiation. A concurrent recolor of the same shape lands in a different register (style), so it is not clobbered by the move - both survive.

Read flow (you open a board / pan the canvas):

  1. On open, the client fetches a viewport snapshot: “give me all shapes whose bounding box intersects this rectangle.” The board server answers from the quadtree - one geometric query, ~150 shapes, ~45 KB - not the whole million-shape board.
  2. The client subscribes to the live op stream for that viewport region. The board server records the client’s current viewport as a subscription filter.
  3. When you pan or zoom, the client sends a viewport_update with the new rectangle. The board server diffs old vs new region, ships a snapshot delta for the newly-revealed area, and updates the subscription filter so future ops are scoped to the new view.

The key insight: the board server is the single authority per board (so merge and fan-out are a local in-memory operation, not a distributed consensus), your own edits are optimistic (so latency is zero for you), the CRDT guarantees everyone converges regardless of op order (so no locks, no rejections), and the quadtree makes both the initial read and the live fan-out scale with visible shapes rather than total shapes.

Component Deep Dive

The hard parts, naive-first then evolved: (1) the CRDT shape store that merges concurrent moves and deletes without last-write-wins loss, (2) the quadtree viewport index that bounds sync payloads to the visible window, (3) the fan-out and connection model for a 500-user room, and (4) persistence, snapshots, and recovery.

1. The CRDT shape store: merging concurrent moves and deletes

This is the heart of the design and the thing the interviewer most wants to see you get right.

Naive approach: shapes in a database, last write wins on the whole object.

Store each shape as a row/document. On any edit, the client sends the full shape, the server overwrites the row, and broadcasts it. Order is decided by server arrival time.

shape = { id, x, y, w, h, color, ... }
on edit: UPDATE shapes SET (whole object) WHERE id = ?   -- last arrival wins
broadcast the new object to everyone.

Where it breaks:

  • Whole-object LWW destroys concurrent edits to different fields. User A drags shape S to a new position; at the same moment User B recolors S. Both send the full object. A’s write has the new position but the old color; B’s write has the new color but the old position. Whichever lands second wins the whole object, so one of the two intentions silently vanishes - either the move or the recolor is lost. This is the cardinal sin, and it happens constantly because moving and styling the same object at once is normal collaborative behavior.
  • No convergence guarantee under reordering. If A’s op reaches client X before B’s, and B’s reaches client Y before A’s, and the server itself saw a third order, three different “final” objects can briefly exist. With whole-object overwrite there is no math forcing them back together; you rely on the server’s arrival order being the one truth, which means every edit must round-trip to the server before it is “real” - killing the 0ms optimistic path.
  • Move vs delete is undefined. A deletes S while B is dragging it. Does B’s in-flight move resurrect a deleted shape? Does A’s delete win and B’s drag silently no-ops? With whole-object LWW the answer depends on millisecond arrival timing and differs per client. That is a correctness bug, not a UX quirk.

First evolution: per-field last-writer-wins registers (field-level, not object-level).

Model each shape not as one blob but as a bundle of independent LWW-Registers, one per field group, each with its own Lamport timestamp:

shape S = {
  geometry: LWW-Register{ value:{x,y,w,h,rot}, ts: lamport, actor: id }
  style:    LWW-Register{ value:{color,stroke,fill}, ts: lamport, actor: id }
  text:     LWW-Register{ value:"...", ts, actor }
  z_order:  fractional-index (see below)
}
merge(regA, regB) = regA.ts > regB.ts ? regA
                  : regB.ts > regA.ts ? regB
                  : regA.actor > regB.actor ? regA : regB   -- deterministic tie-break
  • A move touches only geometry; a recolor touches only style. They land in different registers, so they never clobber each other - both the new position and the new color survive. The silent-intent-loss bug is gone.
  • Each register merges by max(timestamp), tie-break on actor id. This is commutative, associative, and idempotent: apply the ops in any order on any client and you land on the identical register value. That is what makes the optimistic local apply safe - your client and the server will converge even if they saw ops in different orders.
  • Lamport timestamps (each actor keeps a counter, bumps it on every op, and sets it to max(seen)+1 on receiving a remote op) give a total order that respects causality without a central clock. The actor-id tie-break makes the “who wins a genuine tie” deterministic and identical everywhere.

Where the first evolution still breaks: concurrent move and delete on the same shape. If delete is just “remove the shape from the map,” then an in-flight move op that arrives after the delete will re-create the shape (the move op references a shape id the receiver no longer has, and a naive implementation re-inserts it). You get a zombie shape that reappears on some clients and not others. LWW registers alone do not solve existence.

Second evolution: deletion as a tombstone (OR-Set / add-wins or remove-wins), made explicit.

Model shape existence as its own CRDT, separate from its fields. The standard tool is an OR-Set (Observed-Remove Set) or, simpler and usually right for whiteboards, a remove-wins tombstone with a causal guard:

shape existence:
  created_tag:  unique id minted at creation (actor + lamport)
  deleted:      tombstone LWW-Register{ value: bool, ts: lamport, actor }
A shape is VISIBLE iff it was created AND (not deleted, decided by the tombstone register).
A move op on shape S does NOT re-create S; it only updates S.geometry IF S exists.
  If S is tombstoned with a LATER timestamp, the move is applied to the register
  (so state converges) but the shape stays invisible because the tombstone wins existence.
  • Delete wins over a concurrent move, deterministically and identically everywhere. The tombstone is a register with its own timestamp. A move op does not touch the tombstone, so it cannot resurrect the shape. If you want “move wins” (an edit un-deletes) you flip to add-wins semantics - but for a whiteboard, delete-wins is the intuitive choice: if someone deleted it, a stray in-flight drag should not bring it back. State the policy explicitly; that is the senior move.
  • Tombstones must be kept, not garbage-collected eagerly. If you drop the tombstone too soon and a late move op arrives, the receiver has no record that the shape was deleted and re-creates it. You keep tombstones until you are certain every actor has observed the delete (a causal stability threshold - all actors’ Lamport clocks have passed the delete’s timestamp), then compact them during snapshotting. This is the classic CRDT tombstone-GC trade-off: keep them for correctness, compact them for space.
  • Why not just OR-Set with per-element add/remove tags everywhere? You can, and it is fully general (it handles delete-then-re-add-same-logical-shape). But full OR-Set bookkeeping (a set of unique tags per element, remove tracking the observed tags) is heavier than a whiteboard needs, because a deleted shape is almost never re-added as the same id - a user draws a new shape instead. So a per-shape tombstone register is the right-sized CRDT. Name the OR-Set, then justify the simpler choice.

Z-order: the sneaky third conflict. Two users both “bring to front” two different shapes concurrently. If z-order is an integer index, they collide and you get reindex storms. The fix is a fractional index (a string/rational key, like LexoRank): to place a shape between two others you pick a key strictly between their keys, so an insert never renumbers anyone else, and two concurrent inserts just pick two different fractional keys that sort deterministically. Z-order becomes a conflict-free ordered field, merged like any other register but ordered by its fractional key.

The whole merge, in one frame: a shape is a bundle of independent CRDT fields - geometry (LWW-Register), style (LWW-Register), text (LWW-Register or nested sequence CRDT), existence (tombstone), and z-order (fractional index). Every field merges commutatively, so the canvas is a pure function of the set of operations, every client converges regardless of arrival order, concurrent move+recolor both survive, and concurrent move+delete resolves to delete-wins identically everywhere. No locks, no rejections, no round-trip before your own edit feels real.

2. The quadtree viewport index: syncing only what is visible

The second hard part, and the one that makes the infinite canvas tractable.

Naive approach: every client holds the whole board and gets every op.

Load all shapes on open; broadcast every mutation to every connected client; the client renders whatever is in its viewport by iterating all shapes.

Where it breaks:

  • Initial load is unbounded. A 1M-shape board forces a 300 MB download and a 1M-shape render before the user sees anything. The infinite canvas has no “page” to bound this. The app is unusable on a large board.
  • Fan-out is quadratic in the room and independent of attention. From the BoE: 2,500 ops/sec x 500 users = 1.25M msgs/sec out of one room, even though each client can only see ~150 shapes. You are shipping (and the client is discarding) ops for shapes thousands of pixels off-screen. The realtime tier melts, and the client burns CPU filtering a firehose.
  • It gets worse as the board grows, which is backwards - a bigger board should let people spread out and collide less, but naive broadcast punishes size.

First evolution: filter fan-out by the client’s viewport rectangle.

Each client reports its current viewport {x, y, w, h} (in canvas coordinates, adjusted for zoom). The server, for each op, checks whether the op’s shape intersects any subscriber’s viewport and only sends it to those whose view it touches.

on op touching shape S with bbox B:
  for each connected client C:
     if intersects(B, C.viewport): send op to C
  • This immediately kills the firehose: a mover working in the top-left corner generates ops that never reach a client zoomed into the bottom-right. From the BoE, ~150 ops/sec per client instead of 2,500 - and the reduction scales with board size, exactly the property we wanted.

Where it still breaks: the per-op loop is O(ops/sec x connected_clients). At 2,500 ops/sec x 500 clients = 1.25M intersects checks/sec on one board server - the filtering itself becomes the bottleneck. And the initial viewport query (“give me shapes in this rectangle”) is still a full scan of 1M shapes unless the shapes are spatially indexed.

Second evolution: a quadtree over shape bounding boxes.

Index every shape by its bounding box in a quadtree - a tree that recursively subdivides 2D space into four quadrants, so that a rectangle query touches only the nodes overlapping that rectangle instead of scanning everything.

QuadtreeNode = { bounds: rect, shapes: [ids whose bbox fits here], children: [NW,NE,SW,SE] or null }
insert(shape): descend to the smallest node whose bounds contain shape.bbox; split node if it
               holds > K shapes (e.g. K=8) and re-distribute.
query(viewport): starting at root, visit only children whose bounds INTERSECT viewport;
                 collect shapes; cost ~ O(log N + M) where M = shapes in the region, not N total.
remove/move(shape): remove from its node, re-insert at new bbox (a move is a delete+insert in the tree).
  • Initial load is now a geometric query, not a scan: query(viewport) returns the ~150 visible shapes in O(log N + M) - milliseconds on a 1M-shape board. Pan/zoom is the same query on the new rectangle, diffed against the old region so you only ship the newly-revealed slice.
  • Fan-out uses the tree in reverse. Instead of looping every client per op, maintain a second structure: the set of active viewports (one rectangle per connected client). When a shape at bbox B mutates, query which viewports contain B. Because viewports cluster (people collaborate in the same region), you index viewports too - or, more practically, bucket the canvas into a coarse grid of “regions,” map each client to the region(s) its viewport covers, and publish each op to the region bucket. Clients subscribe to region buckets; fan-out becomes “push op to region bucket R, delivered to the handful of clients subscribed to R.” This turns the per-op cost from O(clients) to O(clients actually in that region), which is small and bounded.
  • A move spans two regions (old position and new). The op is published to both the old and new region buckets so a client watching either side sees the shape leave or arrive. This is the spatial analog of the geometry-register merge: the tree/bucketing handles where, the CRDT handles what.

The margin detail (don’t pop shapes at the edge). If you filter exactly to the viewport, a shape one pixel outside your view that someone drags into view appears to teleport in late. So you subscribe to the viewport plus a margin (e.g. 1.5x the viewport, or one region-bucket ring around you), pre-loading just-off-screen shapes so panning is smooth and incoming shapes animate in rather than pop. You trade a little extra payload for a seamless edge - a deliberate, bounded over-fetch.

The whole spatial story: a quadtree indexes shapes by bounding box so initial load and pan/zoom are O(log N + visible) geometric queries instead of full-board scans, and a coarse region-bucket subscription model inverts the fan-out so each op reaches only the clients whose viewport (plus margin) covers the shape’s region. Together they make every sync payload - initial and live - proportional to what the client can see, never to the board’s total size, and the bound improves as the board grows and people spread out.

3. Fan-out and the connection model for a 500-user room

Naive approach: one server per board that does everything, all clients connect straight to it.

Where it breaks:

  • Connection management and merge compete for the same process. 500 raw WebSocket connections, TLS, heartbeats, backpressure - plus CRDT merge, quadtree updates, and fan-out - on one event loop. A slow client with a full send buffer can head-of-line block the room.
  • A deploy or crash of that process drops 500 users at once with no graceful path.

Evolution: split stateless gateways from the stateful board owner.

  • Stateless realtime gateways terminate WebSocket/TLS, authenticate, handle heartbeats and backpressure per connection, and relay ops to the board owner over an internal mux. They scale horizontally and are cheap to restart - a gateway crash drops its connections, which reconnect and are re-routed, without touching board state.
  • One stateful board server owns each board (consistent hashing on board_id, so every op for a board lands on the same owner). It holds the in-memory CRDT and quadtree, does the merge and fan-out, and never has to coordinate with peers for a single board because it is the sole authority. Fan-out is the gateway’s job on the egress side: the board server emits “op O to region bucket R,” and the gateways holding subscribers of R deliver it. This keeps the heavy per-connection work off the stateful process.
  • Presence/cursors ride a separate, lossy channel. Cursor positions are high-frequency and disposable - only the latest matters. They are throttled to ~20/sec, viewport-filtered like ops, and drop-on-stale (never queued; if a client is behind, skip to the newest). They never touch the op log or the CRDT. Mixing them into the durable op path would drown it; keeping them separate is what lets both the durable edit stream and the ephemeral cursor stream hit their very different latency/durability targets.
  • The hot-room limit. One board owner can handle a 500-user room (the merge is cheap, the fan-out is bucketed), but if a single board somehow needed more, you can shard the board spatially - assign different quadtree region subtrees to different owner processes, each authoritative for its spatial partition, with a thin coordination layer for shapes that straddle partitions. State this as the escape hatch; most boards never need it, and spatial sharding adds cross-partition complexity you only pay for when one room truly exceeds a single owner’s budget.

4. Persistence, snapshots, and recovery

Naive approach: write every shape mutation straight to a database row, read rows on load.

Where it breaks:

  • 2,500 writes/sec/board of tiny field deltas is a brutal random-write pattern for a row store, and it conflicts with the CRDT model (you would be serializing merges through the DB). Reading 1M rows on load is the scan problem again.
  • No clean recovery semantics - if the board server crashes mid-merge, what is the source of truth?

Evolution: append-only op log + periodic compacted snapshots.

Durable op log (per board): every merged op appended in order to a per-board partition
   (Kafka topic partition or a WAL). This is the source of truth and the replication/failover feed.
Snapshot: every N ops or T seconds, the board server serializes its compacted CRDT state
   (tombstones GC'd past causal stability, registers collapsed to current values + their ts)
   to the object store, and records the snapshot's log offset in the metadata DB.
Recovery / cold start: load latest snapshot, then replay the op log from the snapshot's offset
   forward. Board is reconstructed exactly, convergence preserved because replay is just more merges.
Failover: a standby board server tails the same op log; on owner death it takes ownership
   (it already has recent state), and gateways re-point to it. Clients replay their un-acked
   local ops on reconnect (each op is idempotent under CRDT merge, so replay is safe).
  • Idempotent replay is the superpower here too. Because every op is a commutative CRDT merge, replaying the log - or a client re-sending ops it was unsure got through - can never corrupt state. At-least-once delivery is fine; double-applying a move op lands on the same register value. This is what makes crash recovery and client reconnection simple instead of a dedup nightmare.
  • Snapshots bound replay cost. Without them, recovering a long-lived board means replaying millions of ops. A snapshot every ~10k ops keeps cold-start replay to a few seconds. The snapshot also compacts tombstones (dropping those past causal stability) and collapses superseded register values, so storage does not grow without bound.
  • The metadata DB (SQL) holds the slow-changing truth: boards, members, ACLs, the current snapshot pointer and log offset per board. It is read on board open to find the owner and the snapshot, and it is low-QPS - the hot path never touches it.

API Design & Data Schema

The realtime path is a WebSocket protocol; the control path is REST. The protocol declares ops explicitly so the server can merge and route.

Control plane (REST)

POST /api/v1/boards
  body: { name, team_id }
  -> 201 { board_id, created_at }

GET /api/v1/boards/{board_id}
  -> 200 { board_id, name, owner_gateway_hint, snapshot_offset, members }
  (tells the client which realtime endpoint to open and where state starts)

GET /api/v1/boards/{board_id}/viewport?x=&y=&w=&h=
  -> 200 { shapes: [ {id, type, geometry, style, z_order}, ... ] }   // initial visible-region load
  (served from the board server's quadtree; bounded to the rectangle, NOT the whole board)

POST /api/v1/boards/{board_id}/members   { user_id, role }   -> 200

Realtime plane (WebSocket, one connection per board session)

// client -> server
{ "t": "op", "shape_id": "s_8f3", "field": "geometry",
  "value": {"x": 120.5, "y": 44.0, "w": 80, "h": 60, "rot": 0},
  "lamport": 10427, "actor": "u_31" }

{ "t": "op", "shape_id": "s_8f3", "field": "existence", "value": {"deleted": true},
  "lamport": 10433, "actor": "u_12" }                      // delete = tombstone op

{ "t": "viewport", "x": -400, "y": 120, "w": 1920, "h": 1080, "zoom": 1.0 }
  // updates this client's subscription region (+margin applied server-side)

{ "t": "cursor", "x": 515, "y": 300, "selection": ["s_8f3"] }   // lossy presence channel

// server -> client
{ "t": "op", ... }                         // a merged op touching this client's region
{ "t": "snapshot_delta", "shapes": [...] } // newly revealed region after a pan/zoom
{ "t": "ack", "lamport": 10427 }           // confirms durability; client can drop the replay copy
{ "t": "presence", "actor": "u_12", "cursor": {...} }   // someone else's cursor (lossy)

The op is a field delta with CRDT tags (lamport, actor), never a whole-object overwrite - that is what makes per-field merge possible. The ack tells the client its op is durably logged so it can drop its optimistic replay copy; until then the client holds the op and re-sends on reconnect (safe, because merge is idempotent).

Shape state schema (in-memory CRDT, serialized into snapshots)

Shape (CRDT bundle):
  id            STRING            // globally unique, minted client-side (actor + counter)
  type          ENUM(rect, ellipse, line, arrow, path, text, sticky)
  geometry      LWW-Register      // { {x,y,w,h,rot}, lamport, actor }
  style         LWW-Register      // { {color,stroke,fill,opacity}, lamport, actor }
  text          LWW-Register      // { "...", lamport, actor }  (nested seq-CRDT if rich-text)
  existence     Tombstone-Register// { deleted:bool, lamport, actor }  delete-wins
  z_order       FRACTIONAL-INDEX  // string key (LexoRank); conflict-free ordering
  created_tag   STRING            // actor + lamport at creation

Durable stores

Op Log  (append-only, per board)  -- Kafka partition keyed by board_id, or a per-board WAL
  offset        BIGINT   (ordered within the board)
  shape_id      STRING
  field         ENUM
  value         BLOB     (field delta)
  lamport       BIGINT
  actor         STRING
  ts            TIMESTAMP
  -> source of truth; replicated for failover; replayed from snapshot offset on recovery.

Snapshot store  (object store: S3/GCS)  -- one compacted blob per board, versioned by offset
  key = board_id/{snapshot_offset}.crdt
  value = serialized CRDT shape map (tombstones GC'd past causal stability, registers collapsed)

Metadata DB  (SQL - Postgres)  -- slow-changing, relational, low QPS
  boards(board_id PK, name, team_id, created_at, current_snapshot_offset, owner_shard)
  board_members(board_id, user_id, role, PRIMARY KEY(board_id, user_id))
  INDEX on board_members(user_id)   -- "which boards am I on"

SQL vs NoSQL, and why a mix:

DataStoreWhy
Live shape stateIn-memory CRDT on board ownerNeeds microsecond merge + quadtree query; it is the hot path, not a DB workload
Op logAppend-only (Kafka/WAL) per boardOrdered, durable, replayable, high write throughput, keyed by board - perfect for a log, terrible for a row store
SnapshotsObject storeLarge opaque blobs, write-rarely read-rarely (cold start), cheap and durable
Boards/members/ACLsSQL (Postgres)Relational, transactional, low QPS, needs joins/queries (“my boards”) - the classic SQL fit

The decision in one line: the hot state lives in memory because it is a merge-and-query problem, not a query-a-database problem; durability is an append-only log (great at ordered high-write); and only the slow relational metadata earns a SQL database. Putting live shapes in SQL and syncing through it - the naive answer - fails on both write pattern and latency.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each:

1. Per-board fan-out (breaks first, always). 2,500 ops/sec x 500 users = 1.25M msgs/sec out of one room. Fix: viewport-scoped delivery via the quadtree + region buckets. Each op reaches only clients whose viewport (plus margin) covers the shape’s region, cutting per-client traffic ~10-25x and improving as the board grows. This is the single load-bearing technique.

2. Initial load / full-board scan. A 1M-shape board cannot be downloaded or scanned on open. Fix: quadtree rectangle query returns only the visible region in O(log N + visible); pan/zoom ships region diffs, not the whole board.

3. Concurrent-edit data loss (correctness, not throughput). Whole-object LWW drops a concurrent move or recolor. Fix: per-field CRDT registers + tombstone existence + fractional z-order. Independent fields merge independently; move+recolor both survive; move+delete is delete-wins everywhere; order-independent convergence.

4. Hot shape (everyone editing one object). A single shape with many concurrent movers serializes on its geometry register. Fix: the register merge is O(1) (max of timestamps), so even a hot shape is cheap; the real cost is fan-out of its op stream, which the region bucket already bounds. If a single shape is a genuine contention point (e.g. a shared frame being resized by many), throttle outbound move ops per object and coalesce - clients only need ~25 positions/sec, not 60.

5. The board owner as a single point of failure. One process owns the board. Fix: standby owner tailing the op log for hot failover; clients replay un-acked ops on reconnect (idempotent under CRDT merge); gateways re-route on owner change. The op log, not the process, is the source of truth.

6. Connection load (500K live WebSockets fleet-wide). Stateful merge and raw connections competing. Fix: stateless gateways terminate connections, heartbeat, and buffer per client; the stateful board owner only merges and routes. Gateways scale horizontally; a gateway crash reconnects its clients without touching state.

7. Cursor/presence firehose. 500 cursors x 20/sec x 500 recipients. Fix: separate lossy channel, throttled, viewport-filtered, drop-on-stale, never logged. Keeps the durable op path clean and lets presence hit its own tight latency target.

8. Unbounded op log / tombstone growth. Logs and tombstones grow forever. Fix: periodic compacted snapshots (every ~10k ops) bound replay cost; tombstone GC past causal stability (once every actor’s clock has passed the delete) bounds state size; old log segments tier to cold storage.

9. Recovery time on a long-lived board. Replaying millions of ops is slow. Fix: snapshot + replay-from-offset keeps cold start to seconds; the snapshot is the compacted state, the log is only the tail since the snapshot.

10. A single board exceeding one owner’s budget. The rare mega-room. Fix: spatial sharding - partition the quadtree into region subtrees owned by different processes, with a thin layer for straddling shapes. The escape hatch, paid for only when truly needed.

11. Sharding key, stated plainly. Boards are partitioned by board_id across board owners (consistent hashing), so a board is always one authority and merge/fan-out stay local; the op log is partitioned by board_id too; the metadata DB shards by board_id with a secondary index on user_id for “my boards.” The infinite canvas is partitioned within a board by quadtree region only in the mega-room case.

Wrap-Up

The trade-offs that define this design:

  • CRDT over locks, per field, not per object. We refuse both whole-object last-write-wins (which silently drops concurrent edits) and central locking (which kills the 0ms optimistic feel). Each shape is a bundle of independent conflict-free fields - geometry and style as LWW-Registers, existence as a delete-wins tombstone, z-order as a fractional index - so concurrent move+recolor both survive, concurrent move+delete resolves to delete-wins identically everywhere, and the canvas is a pure function of the op set, converging regardless of arrival order. The cost is tombstone bookkeeping and keeping deletes around until causal stability.
  • Quadtree + region buckets make visibility the unit of sync. Initial load, pan/zoom, and live fan-out are all bounded by the shapes a client can see, never by the board’s total size - a O(log N + visible) geometric query on the read, a region-bucket subscription on the fan-out. The bound improves as the board grows and people spread out, which is exactly the right scaling direction for an infinite canvas. The cost is a margin over-fetch and publishing moves to two region buckets.
  • Optimistic local apply buys 0ms, the CRDT makes it safe. Your own edits hit your canvas before any round-trip; convergence math guarantees you and the server land in the same place, so the optimism is never a lie that has to be rolled back visibly.
  • Stateful owner per board, stateless everything else. One authority per board_id keeps merge and fan-out a local in-memory operation (no distributed consensus per edit); stateless gateways absorb the 500K connections; a separate lossy channel carries cursors. The op log is the source of truth, so failover is “a standby tails the log and takes over.”
  • Append-only log + snapshots, not a row per edit. The write pattern is high-frequency tiny deltas that are really CRDT merges, so the hot state lives in memory, durability is an ordered log, recovery is snapshot-plus-replay (idempotent because merges are commutative), and only slow relational metadata earns a SQL database.

One-line summary: a real-time collaborative whiteboard where each board is owned by a single stateful server holding an in-memory CRDT shape store - per-field LWW-Registers for geometry and style, a delete-wins tombstone for existence, and a fractional index for z-order, so concurrent moves, edits, and deletes merge without last-write-wins loss and every client converges regardless of order - indexed by a quadtree so initial loads and live fan-out are scoped by region to only the shapes in each client’s viewport, with clients applying their own edits optimistically for 0ms latency, cursors on a separate lossy channel, and durability via an append-only op log plus periodic compacted snapshots for idempotent crash recovery and failover.