Real-Time Multiplayer Canvas Architecture
System DesignModel answerLast updated
Build a backend and client sync strategy for a collaborative visual editor where many users edit shapes and objects simultaneously on a shared canvas.
Problem Statement
You're tasked with architecting a real-time collaborative visual editor—think of a tool where teams work together on a shared canvas containing shapes, frames, and text elements. Everyone sees changes as they happen.
Your system needs to handle:
Functional requirements:
- Files contain canvas objects (rectangles, circles, text boxes, groups)
- Multiple people edit the same file simultaneously
- Changes propagate to all active users with minimal delay
- Show who else is viewing or editing (presence)
- All edits must persist—users can close and reopen files
- Handle common collaboration scenarios: two people moving the same object, creating objects at the same time, reorganizing hierarchies
Performance and reliability:
- Editing latency should feel instant locally, with updates reaching others in under 200ms (p50)
- A typical file might have 2–5 concurrent editors; popular files could see 50+ simultaneous users
- Mobile and WiFi connections drop frequently. Your system must handle:
- Temporary disconnections (user goes through a tunnel)
- Clients editing offline then reconnecting
- Network packets arriving out of order or duplicated
What to cover:
- High-level architecture: major components and how they communicate
- Data model for canvas objects and edit operations
- Conflict resolution strategy when users edit simultaneously
- API design (WebSocket and REST endpoints)
- How the system behaves during network failures
- Storage strategy for both live editing and persistence
You don't need to design the rendering engine, plugin system, or version history UI.
Hints
Hint 1
Consider whether you need a central server or peer-to-peer architecture—what are the trade-offs?
Hint 2
Think about the granularity of conflicts: should two users editing different properties of the same object conflict?
Hint 3
How will you ensure that all clients eventually see the same state even if operations arrive in different orders?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Multiplayer Canvas Architecture
1. Scale and Requirements Refinement
Start by establishing concrete numbers to guide architectural decisions:
- User base: Around 10M daily active users managing 50M total files, with roughly 500K files open at any moment
- Typical concurrency: Most files have 1–5 editors; high-traffic files might reach 100 active users (mix of editors and viewers)
- Operation volume: Active editing (dragging objects) generates 10–30 operations per second per user. Client-side throttling reduces this. Global peak: roughly 1M ops/sec, each 100–500 bytes
- Document complexity: Files range from 1–50 MB of structural data (thousands of objects). Visual assets stored separately
- Durability: Once the server acknowledges an edit, it cannot be lost
Out of scope: rendering pipeline, asset processing, detailed permission models, version history UI.
2. Core Architectural Decision: Conflict Resolution Model
This choice fundamentally shapes the entire system.
Option A: Operational Transformation (OT)
- Originally designed for linear text editing
- Requires complex transform functions for tree-structured documents with many operation types
- Transform correctness is difficult to prove and debug
- Still needs a central server to establish operation ordering
Option B: Full Conflict-Free Replicated Data Types (CRDTs)
- Enables peer-to-peer synchronization without a central authority
- Requires significant metadata (vector clocks, tombstones, unique element IDs)
- Primary advantage (P2P) is unnecessary since we're building a server-backed system anyway
Recommended: Server-authoritative with per-property last-write-wins
This hybrid approach, inspired by production systems like Figma:
- Object identity: Each object has a globally unique ID generated as
(clientId, sequence), allowing clients to create objects without server coordination - Conflict granularity: Properties are independent. Two users changing different properties on the same object (one moves it, another changes its color) both succeed
- Tie-breaking: When users change the same property simultaneously, the server's ordering determines the winner. This creates deterministic convergence
- Hierarchy management: Objects reference parents by ID and use fractional indexing for ordering (e.g., "a0", "a0V", "b0"). Concurrent insertions between the same positions get unique fractional positions
- Cycle prevention: If operations would create a circular parent-child relationship, the server rejects the second operation and the client rolls back
- Text editing: Rich text within text objects uses a character-level CRDT or OT, since merge quality matters at this granularity
Rationale: Property-level LWW gives intuitive results for visual editing, the server provides total ordering without distributed consensus, and we avoid OT's complexity explosion.
3. System Components
Client Application:
- Maintains full document state in memory
- Applies local edits optimistically (instant feedback)
- Queues unacknowledged operations, persisted to IndexedDB
- Renders:
serverState + pendingLocalOps
API Gateway / Load Balancer:
- Validates authentication tokens (short-lived JWTs)
- Routes WebSocket connections by fileId to the appropriate server
- Terminates TLS
Multiplayer Coordination Service (Stateful):
- Each open file is assigned to exactly one server process (consistent hashing or coordinator-based assignment)
- That process holds the live document in memory
- Validates incoming operations, assigns sequential version numbers, writes to durable log
- Broadcasts operations to all connected clients only after successful persistence
- Single-process-per-file eliminates distributed locking while easily supporting hundreds of concurrent users
Operation Log (Append-Only Store):
- DynamoDB, Cassandra, or similar
- Key:
(fileId, serverVersion) - Value: operation payload, originating client, timestamp
- Provides durability boundary and enables time-travel
Checkpoint Storage (Object Store):
- S3 or equivalent, fronted by CDN
- Full serialized document at specific versions
- Generated every 1,000 operations or every 60 seconds
- Enables fast file opening without replaying entire history
Presence Service:
- Ephemeral data (cursor position, viewport, selection)
- Routed through the same multiplayer service but never persisted
- Throttled to 10–20 Hz
- For files with thousands of viewers, offload to dedicated pub/sub (Redis, NATS)
Supporting Services:
- Metadata API (REST): file listings, permissions, sharing
- Asset storage: content-addressed blobs in S3/CDN
- Comment system: standard CRUD service
4. API Design
REST Endpoints (Control Plane):
POST /files → {fileId}
GET /files/{fileId} → metadata, permissions
GET /files/{fileId}/checkpoint → {version, s3Url}
PUT /files/{fileId}/permissions
POST /files/{fileId}/comments
WebSocket Protocol (Data Plane):
Connection: wss://collab.example.com/files/{fileId}?token={jwt}
Messages:
// Client → Server
{
type: "init",
clientId: "abc",
lastKnownVersion: 1234
}
{
type: "operations",
clientId: "abc",
clientSequence: 56,
baseVersion: 1234,
ops: [
{objectId: "abc:1", property: "x", value: 150},
{objectId: "abc:2", property: "fill", value: "#ff0000"}
]
}
// Server → Client
{
type: "ack",
clientSequence: 56,
serverVersion: 1235
}
{
type: "broadcast",
serverVersion: 1236,
sourceClient: "def",
ops: [...]
}
{
type: "reject",
clientSequence: 57,
reason: "cycle_detected",
correctiveOps: [...]
}
// Bidirectional (ephemeral)
{
type: "presence",
cursor: {x: 100, y: 200},
selection: ["abc:5"],
viewport: {x: 0, y: 0, width: 1920, height: 1080}
}
5. Data Models
Files Table (SQL):
file_id, owner_id, team_id, name,
latest_checkpoint_version, created_at, updated_at
Operation Log (NoSQL):
partition_key: file_id
sort_key: server_version
attributes: {
client_id,
client_sequence,
timestamp,
operations_blob
}
In-Memory File State (Multiplayer Service):
{
version: 1250,
objects: {
"abc:1": {x: 100, y: 200, width: 50, height: 50, fill: "#blue"},
"abc:2": {parentId: "abc:1", position: "a0", type: "text", ...}
},
clientStates: {
"abc": {lastSequence: 58, connection: websocket},
"def": {lastSequence: 22, connection: websocket}
}
}
6. Critical Flows
Opening a File:
- Client fetches latest checkpoint URL and version from REST API
- Downloads checkpoint from CDN (contains document at version V)
- Establishes WebSocket connection with
lastKnownVersion: V - Server streams operations V+1 through current
- Client applies operations sequentially and enters live mode
Editing Flow:
- User drags object—client applies change immediately (optimistic)
- Client sends operation batch with monotonic
clientSequence - Server validates, checks for conflicts (e.g., parent cycles)
- Server appends to durable log, increments
serverVersion - Server broadcasts to all clients (including originator)
- Originating client receives ack, removes from pending queue
- Other clients apply remote operation
Conflict Resolution Example:
User A and User B both move rectangle R:
- A: sets
x: 100at baseVersion 50 - B: sets
x: 200at baseVersion 50
Server receives A's operation first:
- Assigns serverVersion 51, broadcasts
- B receives the broadcast, but has a pending local change to
x, so continues showingx: 200 - Server receives B's operation, assigns serverVersion 52, broadcasts
- A receives B's operation (serverVersion 52), applies it:
xnow 200 - B receives ack for serverVersion 52, final state converged:
x: 200
Result: Server's ordering (B arrived second) determines the winner. Both clients converge to the same state.
7. Network Failure Handling
Duplicate Detection:
- Each operation batch carries
(clientId, clientSequence) - Server tracks last applied sequence per client
- Duplicates (sequence ≤ lastSeen) receive re-ack but aren't reapplied
- Gaps trigger a buffer-and-request-resend flow
Out-of-Order Delivery:
- Client expects sequential serverVersions
- Gap detected → client stops applying, requests missing operations
- Server maintains recent operation buffer to serve catch-up requests
Temporary Disconnection:
- Client continues editing locally, operations queue in IndexedDB
- On reconnect, client sends queued operations with original sequence numbers
- Server's deduplication ensures idempotency
- Client receives and applies all operations that occurred during downtime
Offline Editing:
- Client persists pending operations to IndexedDB
- User closes tab/app while offline
- On next open (possibly days later), client reloads pending operations
- Establishes connection, sends operations with
baseVersionfrom before disconnect - Server may reject some operations (e.g., object was deleted)
- Client receives corrective operations and resolves conflicts
Extended Partition: If operations conflict after long offline period:
- Server applies remote changes that occurred during offline period
- Client's operations are rebased onto current state
- Property-level LWW: client's changes to properties others didn't touch succeed
- Conflicting property changes: server's ordering wins, client may need to discard
8. Scalability Considerations
Single file, many editors: One process handles 100+ concurrent users on a single file. Each operation is small (few hundred bytes), and in-memory processing is fast. Presence updates are throttled and dropped if clients can't keep up.
Many files: Files are distributed across processes via consistent hashing or coordinator assignment. A process handles 10–100 active files. Cold files are dropped from memory; reopening replays from checkpoint.
Operation log growth:
- Background compactor merges old operations into checkpoints every hour
- Truncate log after N days (keep longer for version history features)
- Archive old versions to cold storage
Presence at scale: For files with 1,000+ viewers (public presentation mode), presence updates:
- Sampled: only send updates for subset of users
- Aggregated: "145 viewers" instead of individual cursors
- Offloaded to separate pub/sub infrastructure
9. Common Mistakes
Mistake: Full object-level locking Locking entire objects causes false conflicts. Two users changing different properties should both succeed.
Mistake: Client-side merge without server ordering Leads to divergent states. Clients must converge on the same operation order.
Mistake: Synchronous writes per operation Writing every operation synchronously to durable storage bottlenecks throughput. Batch writes while maintaining ordering guarantees.
Mistake: Ignoring offline editing Users will edit on flaky connections. The system must handle stale baseVersions and queued operations gracefully.
Mistake: Not testing reordering Network conditions cause operations to arrive in unexpected orders. Test scenarios where server order differs from wall-clock order.
10. Extensions
Undo/Redo: Each client maintains local undo stack. Undo generates inverse operations sent to server.
Version History: Operation log naturally provides time-travel. Checkpoints enable fast jumping to historical versions.
Permissions: Validate edit permissions on the multiplayer service before applying operations.
Conflict notifications: When server rejects or reorders, optionally show user a toast: "Your change conflicted with [User]'s edit."
This architecture balances consistency, performance, and operational simplicity while gracefully handling the messy realities of distributed collaboration over unreliable networks.