5/10
Technical Architecture & AI Engineering · 7 min read

System Design: Real-Time Collaborative Document and State Sync Engine (CRDT vs. OT)

Architect a 50,000-room collaborative editing platform with sub-100ms sync latency, sticky WebSocket routing, CRDT offline merge support, and compacted snapshot storage.

Why This Matters at Engineering Leadership Scale

Enterprise SaaS users increasingly expect live multiplayer editing, presence cursors, and seamless offline-to-online merge across specs, boards, and documents. Naive last-write-wins overwrites silently destroy coworkers' edits, while custom centralized locking engines choke under concurrency and break when mobile clients reconnect after hours offline.

At Staff Engineer or EM level, your architectural job is choosing cleanly between CRDTs and OT, bounding WebSocket fanout memory, preventing O(N^2) presence storms, and compacting long-term edit history cheaply.

Core Mental Model & Architecture

Start with concrete concurrency, memory, and storage math:

  • Concurrency & SLO: 50,000 concurrent active rooms, up to 50 editors/doc (~5 avg users/room = 250,000 concurrent WebSockets), ~20,000 ops/sec globally, <100ms p95 sync latency.
  • Pod Sizing Math: At 5,000 WebSockets per Sync Pod (~450 MB RAM for socket buffers + hot CRDT state), steady-state needs 50 active pods (~65 pods with headroom).
  • Op-Log & Compaction Math: 20,000 ops/sec * ~150 bytes binary frame = 3 MB/sec = ~260 GB/day raw. Compacting active docs into binary snapshots every 60s or 500 ops (~50 KB/doc) cuts durable storage >85% and keeps cold doc opens under 40ms.
Sync ModelOffline Reconnect MergeCentral BottleneckMetadata OverheadBest Fit
Last-Write-Wins (LWW)Poor (drops concurrent edits)LowMinimalSimple settings forms
Operational Transformation (OT)Hard (strict server transform order)High (single serializer)Low (~5%)Always-online rich text
CRDT (Yjs / Automerge) - ChosenNative & deterministic (commutative)Low (order-independent)Moderate (~15% to 20%)Multiplayer docs, offline mobile, multi-pod sync

We choose CRDTs (Yjs binary encoding): accepting ~20% metadata overhead removes central serialization bottlenecks and makes offline reconnect merges deterministic.

Step-by-Step Implementation Tutorial

1. Map Sticky WebSockets, Redis Pub/Sub, and Compacted Persistence

Route editors of the same doc_id to one sticky Sync Pod via consistent hashing for local speed, backed by Redis Pub/Sub for multi-pod scaling and viewer fanout.

text
CLIENTS (Browser / Mobile + Local IndexedDB CRDT Store)
  <-- WebSocket (Binary CRDT State Vectors + Throttled Presence) -->
ENVOY L7 PROXY (Consistent Hash on `doc_id`)
  -> Sticky Sync Pod (Hot Yjs Doc in RAM):
       1. Verify JWT + Document ACL on handshake
       2. Apply binary CRDT delta in memory (<0.5ms)
       3. Broadcast delta to local room + Redis Pub/Sub `doc:{id}`
       4. Async batch append to Postgres/DynamoDB Op-Log (every 200ms)
       5. Background Compactor: Every 500 ops or idle -> Flush binary snapshot to S3 + prune old op-log

2. Model the Hybrid Snapshot + Append-Only Op-Log Schema

Pair a short-lived op-log (zero data loss on pod crash) with compacted S3 binary snapshots (fast loads and named Version History).

sql
CREATE TABLE document_snapshots (
  tenant_id          UUID NOT NULL,
  doc_id             UUID NOT NULL,
  snapshot_version   BIGINT NOT NULL,
  s3_binary_uri      TEXT NOT NULL,
  state_vector_bytes BYTEA NOT NULL, -- Compact logical clock for delta sync
  is_named_version   BOOLEAN NOT NULL DEFAULT FALSE,
  created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (tenant_id, doc_id, snapshot_version)
);

CREATE TABLE document_op_log (
  doc_id             UUID NOT NULL,
  seq_id             BIGSERIAL NOT NULL,
  snapshot_base_ver  BIGINT NOT NULL, -- Pruned once compacted snapshot > base_ver
  update_payload     BYTEA NOT NULL,
  created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (doc_id, seq_id)
);

3. Handle the Minute-25 Curveball: 2,000-Viewer Viral Doc + 4-Hour Offline Flight Merge

"A company-wide strategy doc attracts 2,000 concurrent viewers and 50 editors simultaneously, while a VP edits offline on a 4-hour flight and reconnects."

  1. 2,000-Viewer Hot Room: Separate write pods from read-only fanout pods. Keep the 50 editors on the primary sticky Sync Pod and route viewers to stateless Edge Fanout Pods subscribed to doc:{id} via Redis Pub/Sub. Throttle cursor presence to 5 Hz and suppress viewer cursors automatically when room size exceeds 30 users so O(N^2) traffic never melts sockets.
  2. 4-Hour Offline Reconnect: The VP's browser persisted edits in IndexedDB. On reconnect, it sends a ~200-byte State Vector (syncStep1); the server replies with only missing binary deltas (syncStep2), and the client pushes its offline delta. CRDT commutativity merges every edit cleanly with zero lock modals.

4. Split Multi-Squad Ownership

  • Realtime Sync Infrastructure Squad (6 engineers): Owns Envoy consistent-hash routing, Sync Pods, Redis Pub/Sub fanout, op-log durability, S3 compaction, and jittered connection draining.
  • Collaborative Editor SDK Squad (6 engineers): Owns client Yjs bindings, IndexedDB offline storage, throttled presence cursors, undo/redo, and Version History diff UI.

Worked Production Scenario: Before vs. After

A SaaS product-spec tool initially polled Postgres every 3 seconds with optimistic locking (version check). Concurrent editors constantly hit 409 Conflict overwrite modals and abandoned the tool for Google Docs. Moving to Yjs CRDTs on sticky WebSocket pods with Redis Pub/Sub and S3 snapshot compaction eliminated save conflicts and cut DB write IOPS by 91%.

MetricBefore (REST Poll + Optimistic Lock)After (CRDT + Sticky WS + S3)Net Impact
Edit Sync Latency (p95)3,100ms48ms (binary WS delta)64x faster multiplayer
Save-Conflict Errors / Week1,850 (409 Conflict)0 (deterministic CRDT)Zero overwritten work
Offline Reconnect Merge0% (manual copy-paste)99.98% automatic syncReliable travel editing
Postgres Active-Doc Write Load4,200 full-doc JSON writes/sec350 batched op-log writes/sec-91% DB write IOPS

Common Failure Modes & Anti-Patterns

1. Unbounded O(N^2) Cursor/Presence Broadcasts

The trap: Broadcasting mouse coordinates from 200 users at 60 FPS generates 2.4M messages/sec for one room, starving real edits. The structural fix: Separate ephemeral presence from CRDT edits, throttle cursors to 200ms intervals, and suppress viewer cursors above 30 participants.

2. Reconnect Thundering Herds on Rolling Pod Deploys

The trap: Killing a pod with 5,000 open WebSockets triggers 5,000 simultaneous reconnects onto neighboring pods. The structural fix: On SIGTERM, flush dirty snapshots to S3 and send a RECONNECT_JITTER frame spreading client reconnects randomly over 15 to 45 seconds.

3. Unbounded CRDT Tombstone Bloat on Living Docs

The trap: Multi-year docs accumulate millions of deleted-character tombstones, bloating opens to 40 MB. The structural fix: Enable CRDT garbage collection (gc: true) during compaction and cut periodic epoch snapshot checkpoints.

How to Handle Pushback in the Room

Staff Frontend Engineer: "CRDTs add 20% metadata overhead. Why not write a custom Operational Transformation server?"

Calm Executive Response: "Proving a custom OT transform matrix for nested rich-text blocks and offline mobile merges is a multi-year reliability trap. Proven CRDT engines like Yjs give us deterministic offline merges and effortless multi-pod failover out of the box, while binary encoding and background S3 compaction keep the 20% metadata cost trivial."

Security Lead: "If a user's document permission is revoked mid-session, do they keep receiving live edits on their open WebSocket?"

Calm Executive Response: "No. Permission revocations publish an immediate doc_acl_revoked control message to Redis Pub/Sub; every Sync Pod drops the revoked user_id socket within 100 milliseconds and invalidates the session."

Key Takeaways & This Week's Action Rep

  • Default to CRDTs for multiplayer + offline sync: Trade ~20% metadata overhead for zero central serialization bottlenecks and deterministic offline merges.
  • Pair sticky WebSocket pods with Redis Pub/Sub: Keep hot edits local while scaling read-only viewers to stateless fanout pods.
  • Combine a fast op-log with compacted S3 snapshots: Protect against pod crashes while bounding long-term storage and cold-load speed.
  • Throttle presence and jitter pod drains: Prevent O(N^2) cursor storms and rolling-deploy reconnect floods.
  • This Week's Action Rep: Sketch the exact binary sync handshake (syncStep1 -> syncStep2), op-log compaction trigger, and live ACL-revocation disconnect path for a collaborative feature in your stack.