Design a Threaded Annotation Layer for a Live Collaborative Canvas
System DesignModel answerLast updated
Design the backend and real-time infrastructure for a threaded comment system that pins to canvas coordinates or live objects on a shared infinite whiteboard.
Context
Your team is building a collaborative diagramming tool where multiple users edit a shared infinite 2D canvas in real time. Users need to leave feedback directly on the canvas — either pinned to a fixed spatial position or attached to a specific diagram element (a shape, container, or label). When elements move or resize, their attached annotations should follow. When elements are deleted, the system must handle the resulting dangling references without losing the annotation content.
Design the backend and real-time delivery infrastructure to support this annotation system.
Requirements
Functional
- Anchor modes: An annotation thread can attach to either an absolute canvas coordinate
(x, y)or to a canvas element by ID, with a relative offset within that element. Annotations on moving elements must track the element's new position. Annotations on deleted elements must degrade gracefully — content is preserved and the annotation renders at its last known position with a visible indicator. - Thread operations: Users can create a thread, reply, edit or delete a comment, and mark a thread resolved or reopen it.
- Live delivery: All annotation activity — new comments, edits, resolution, and typing indicators — must reach active board viewers with sub-100 ms latency.
- Mentions: Inline
@mentionsin comment bodies must trigger async notifications via email, push, and in-app channels. - Offline resilience: Client retries after a network interruption must not create duplicate comments. Reconnecting clients must recover any missed events.
Non-Functional
- Scale: 10 million DAU, 50 million annotation operations per day. Peak scenario: a single "hot board" with up to 20,000 concurrent viewers.
- Ordering: Comments within a thread must be strictly ordered. Spatial position updates may be eventually consistent.
- Durability: Any annotation the server acknowledges must never be lost.
What to Cover
- Data model and anchor strategy — Schema for threads, comments, and anchors. How concurrent element transforms (move, resize, delete) are reconciled without coupling the comment service to geometry logic.
- API and transport — REST endpoints for durable writes and the real-time protocol (WebSocket or SSE) for live delivery, including reconnect and deduplication.
- End-to-end architecture — Flow from a client write through persistent storage, an outbox/CDC pipeline, a pub/sub layer, and the fan-out tier to connected clients.
- Hot-board problem — How the system stays healthy when tens of thousands of viewers are watching the same canvas simultaneously.
Hints
Hint 1
Start by separating the two fundamentally different traffic types: durable comment writes (low volume, must not be lost) and ephemeral signals like typing indicators (high frequency, can be dropped). They need different treatment throughout the stack.
Hint 2
For element-anchored pins, think about what coordinate space you store. Absolute pixel offsets become wrong every time the element moves or resizes. A normalized local offset — a fraction of the element's bounding box — stays correct through transforms and means the comment service never needs to recompute geometry.
Hint 3
The hot-board fan-out problem is not about write throughput; it is about delivery. One comment to 20,000 viewers is 20,000 pushes. The key is hierarchical fan-out: each edge gateway subscribes once per board, not once per connection, so the broker emits a small number of messages regardless of viewer count.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the Problem First
Before designing anything, run the numbers to find where the real pressure is.
- Write rate: 50M ops/day averages ~580 ops/s. At 5× peak that is ~3,000 ops/s. A sharded relational database handles this comfortably — this is not a write-heavy system.
- Storage: ~1 KB per comment × 50M/day = ~50 GB/day, ~18 TB/year. Shard by
board_id. - The real bottleneck is fan-out, not writes. A single comment on a board with 20,000 viewers produces 20,000 push deliveries. Typing indicators fire multiple times per second per active typist, which is far worse. Design around this.
Key scope decisions to confirm up front: the annotation service does not own geometry — it borrows position information from the document engine. Ordering only matters within a single thread. Typing and presence signals can be lossy.
2. Data Model and Anchor Strategy
threads(
thread_id PK,
board_id,
author_id,
created_at,
status ENUM(open, resolved),
resolved_by,
resolved_at,
next_seq INT,
version BIGINT
)
anchors(
thread_id PK,
kind ENUM(absolute, element),
x, y, -- absolute: canvas world coords
node_id, -- element anchor: target element ID
u, v, -- normalized offset within element bbox (0.0–1.0)
last_known_x,
last_known_y, -- world-space snapshot for fallback rendering
state ENUM(attached, detached, orphaned),
detached_at
)
comments(
comment_id PK,
thread_id,
seq INT,
author_id,
client_msg_id UUID,
body,
mentions JSONB,
created_at,
edited_at,
deleted_at,
UNIQUE(thread_id, client_msg_id),
UNIQUE(thread_id, seq)
)
The annotation service never recomputes positions. For element-anchored pins, store (node_id, u, v) — a normalized offset within the element's local bounding box. Each client already holds live document state from the multiplayer engine and computes the world position at render time as worldTransform(node) · (u·w, v·h). Concurrent moves and resizes are resolved once by the document engine's own conflict resolution; annotations inherit the result automatically. Moving a shape generates zero comment writes.
Normalized (u, v) also handles resizes gracefully — the pin stays at the "same relative spot" on the shape. A fixed pixel offset would drift every time the shape scales.
Handling deleted elements: When the document service emits a node-deletion event, a consumer marks the anchor state = detached and records detached_at. The anchor row is not deleted. Clients render the pin at last_known_x/y with a "detached" visual indicator. Content is preserved; the annotation is just unmoored.
3. API and Transport
REST for durable writes:
POST /boards/{b}/threads {anchor, body, mentions, client_msg_id}
POST /threads/{t}/comments {body, mentions, client_msg_id}
PATCH /comments/{c} {body, expected_version}
DELETE /comments/{c}
POST /threads/{t}/resolve
POST /threads/{t}/reopen
GET /boards/{b}/threads?since_version=V
Every write carries a client_msg_id (generated client-side at send time, reused on retries). The UNIQUE(thread_id, client_msg_id) constraint makes writes naturally idempotent — a retry returns the original row with its assigned seq rather than creating a duplicate. Edits use expected_version for optimistic concurrency.
Transport: WebSockets. The board already needs a bidirectional multiplayer socket for collaborative editing, and typing indicators are inherently bidirectional. SSE adds little in this context.
Server-pushed event shape:
{
"type": "annotation.created",
"board_version": 81234,
"thread_id": "t1",
"seq": 7,
"comment": { "..." },
"client_msg_id": "uuid-..."
}
board_version is a monotonic per-board counter. Clients track the last seen version; any gap triggers a GET ...?since_version= catch-up request before resuming the stream. Clients suppress echoes of their own optimistic writes by matching client_msg_id.
Ephemeral events (typing start/stop, cursor presence) use the same socket but are never persisted. They get shed first under load.
4. End-to-End Architecture
Client ──HTTPS──> API GW ──> Annotation Service ──> Postgres (sharded by board_id)
│ └── outbox table (same txn)
│ │ CDC
│ ▼
│ Kafka "annotation-events"
│ (partitioned by board_id)
│ ├─> Fan-out tier
│ │ └─> Edge gateways ──WS──> clients
│ ├─> Notification service ──> email/push/in-app
│ └─> Search indexer
Client ──WS──> Edge Gateway ──(typing/presence, lossy)──> Redis pub/sub ──> other gateways
Commit path: In a single transaction, increment threads.next_seq (row-locked per thread) and insert the comment with that value. This gives strict per-thread ordering without a global sequence. An outbox row and board_version bump are written in the same transaction. The client is acknowledged only after the transaction commits with synchronous replication to a standby replica — this is how the "never lost once acknowledged" guarantee is upheld.
Async path: CDC relays outbox rows to Kafka partitioned by board_id, preserving per-board order. Independent consumers handle fan-out, notifications, and search indexing. Kafka lag slows real-time delivery but loses nothing; clients reconcile via since_version.
Notifications: The mention consumer resolves @mentioned user IDs, checks mute/permission settings, debounces email sends (e.g., 5-minute quiet window), and deduplicates on (comment_id, recipient_id).
5. Hot-Board Fan-Out
The naive approach — one broker message per viewer connection — produces 20,000 broker sends for a single comment. This does not scale.
Hierarchical fan-out:
- Spread 20,000 viewer connections across ~20 edge gateway nodes (~1,000 connections each).
- Each gateway maintains a single board-level subscription to the broker, not one subscription per connection.
- One Kafka message → 20 broker deliveries → each gateway fans out locally in memory.
- For extremely hot boards, insert a regional relay tier: one Kafka consumer per region feeds N regional relays, which feed the gateways. One event becomes ~5 regional messages, not 20,000.
Separate durable from ephemeral:
- Comment events are infrequent and must be delivered; they use a durable Kafka-backed path.
- Typing indicators are frequent and lossy-acceptable; they use Redis pub/sub directly between gateways.
- Under load, shed ephemeral traffic first. Never let typing indicators crowd out comment delivery.
Aggregate presence at the gateway:
- Gateways coalesce typing signals into a per-thread summary every 250–500 ms: "Ana and 4 others are typing." Clients never receive raw per-user typing events at 20,000-viewer scale.
- Cap payload size and drop oldest events if a client's send buffer backs up.
Common Mistakes to Avoid
- Storing absolute pixel coords for element anchors. They become stale the moment the element moves. Normalized local offsets are the right choice.
- Routing typing indicators through the durable comment pipeline. This wastes Kafka throughput and adds latency to actual comments. Keep ephemeral traffic on a separate lossy channel.
- Per-connection broker subscriptions. This is the hot-board problem in disguise. Fan-out must be hierarchical.
- Deleting anchor rows on element deletion. You lose the ability to show the annotation at its last known position, which degrades the UX unnecessarily.
- Acknowledging writes before the replica confirms. If the primary crashes between commit and replication, you silently lose acknowledged data. Synchronous replication to at least one standby is non-negotiable for the durability guarantee.