Design a Real-Time Collaborative Document Editing Service
System DesignModel answerLast updated
Design the backend for a multi-user document editor supporting concurrent edits, offline sync, conflict resolution, history, and per-note scaling.
Scenario
You are building the backend for a lightweight collaborative writing tool — think shared notes that multiple teammates can edit at the same time from different devices or locations.
Your focus is entirely on backend architecture and data flow. Assume the frontend is handled separately.
Functional Requirements
- Users can create, read, update, delete, and share documents.
- Multiple users may have a document open and actively typing at the same time.
- A user who loses connectivity briefly should be able to resume editing and have their changes merged cleanly when they reconnect.
- Users can view previous versions of a document and recover from unwanted changes.
- Documents can be shared with specific people or teams, with different permission levels.
Constraints and Assumptions
- Plain text or simple rich text is sufficient; you do not need to support spreadsheet-like structures.
- Assume tens of millions of documents and thousands of concurrent live sessions at peak.
- History retention and version recovery are required, but you can define a reasonable retention window.
- A simple last-write-wins approach at the full-document level is explicitly off the table — it loses edits under concurrent use.
Clarifying Questions to Consider
Before diving in, think about how you would clarify scope with an interviewer:
- Is rich-text formatting (bold, links, embedded media) required in v1, or just plain text?
- What collaboration latency is acceptable — under 500 ms, or closer to a few seconds?
- Do we need true offline editing (edits made with no connectivity, merged later), or just short reconnect tolerance?
- How long should version history be retained — 30 days, 90 days, indefinitely?
- Are permissions granted per user, per team, or via shareable links?
What to Cover
Part 1 — Architecture and Data Model
Describe the major services, how they interact, and the key data entities.
- What services exist and what does each own?
- How are documents, users, permissions, edit operations, and snapshots represented in storage?
- What APIs expose CRUD operations, and what protocol handles live editing?
Part 2 — Synchronization and Conflict Resolution
Explain how the system keeps all clients consistent when edits happen simultaneously or when a client reconnects after going offline.
- How are individual edits tracked and ordered?
- What strategy — Operational Transformation (OT) or CRDTs — would you use, and why?
- How does a reconnecting client catch up to the current document state?
- What makes full-document overwrites dangerous here, and how do you avoid it?
Part 3 — Scalability, Reliability, and Security
Describe how the system handles growth and protects data.
- How do you route and scale the real-time collaboration layer?
- How do you ensure an edit is not lost if a server crashes right after receiving it?
- How does pub-sub fit into the architecture?
- How do you manage history storage without it growing unbounded?
- What security controls (permissions, encryption, rate limiting, audit trails) are needed?
Hints
Hint 1
Start by separating concerns into at least three distinct services: one for document metadata and CRUD, one for managing live editing sessions and WebSocket connections, and one (or a component) for persistence of the operation log. Keeping these boundaries clear makes the rest of the design much easier to reason about.
Hint 2
For conflict resolution, compare OT and CRDTs on two axes: implementation complexity and suitability for your text model. OT requires a central server to sequence operations and transform them, which is simpler to reason about for plain text but adds a coordination bottleneck. CRDTs push the merge logic into the data structure itself and work better for fully peer-to-peer or heavily offline scenar…
Hint 3
Think about durability in two layers: the append-only operation log (every keystroke-level change, ordered by document version) and periodic snapshots (a full document state at a checkpoint). A client catching up after an offline gap replays the operation log from the last snapshot it holds — this is cheaper than replaying from the beginning of time.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifications Worth Establishing First
A strong answer opens by narrowing scope. Reasonable assumptions: plain text with light markdown formatting, offline tolerance of up to a few minutes (not full disconnection for days), history retained for 90 days, permissions granted per user or team with owner/editor/viewer roles, and a collaboration latency target under 300 ms for co-located users.
Part 1 — Architecture and Data Model
Services
Metadata Service owns document lifecycle — create, rename, delete, share, permission checks. It talks to a relational database (Postgres) for documents, users, teams, and permissions. This service is stateless and horizontally scalable.
Collaboration Service manages live editing sessions. Clients connect via WebSocket. This service receives edit operations, sequences them for a given document, broadcasts to other connected clients, and writes to the operation log. It is stateful per document session.
Operation Log / Storage Service provides durable append-only storage of every operation and periodic snapshots. A time-series-friendly store (Cassandra or DynamoDB with a composite key of (doc_id, version)) works well here.
Auth Service handles login, token issuance, and permission resolution. Other services call it or validate JWTs independently.
Pub-Sub Broker (Kafka or Redis Pub/Sub) fans out operations across Collaboration Service instances so a client on server A sees edits from a client on server B.
Data Entities
Document: doc_id, owner_id, title, created_at, updated_at, current_version
User: user_id, email, ...
Permission: doc_id, principal_id, role (owner|editor|viewer)
Operation: doc_id, version, client_id, idempotency_key, op_type, position, content, timestamp
Snapshot: doc_id, version, full_text, created_at
APIs
POST /documents— createGET /documents/{id}— fetch metadata + latest snapshotPATCH /documents/{id}— title/metadata editsDELETE /documents/{id}— soft deletePUT /documents/{id}/permissions— shareGET /documents/{id}/history— list versions
Live editing uses WebSocket messages with types: op (submit operation), ack (server confirms), broadcast (server pushes remote op), sync (catch-up bundle on reconnect).
Part 2 — Synchronization and Conflict Resolution
Operation Log and Versioning
Every edit is expressed as a discrete operation: insert N characters at position P, or delete N characters from position P. Each operation carries the document version it was based on. The server assigns a monotonically increasing version on commit. Clients track the last acknowledged version.
OT vs. CRDTs
For a centralized backend with a collaboration server acting as sequencer, Operational Transformation is the more practical choice. The server receives an operation tagged with the client's base version, transforms it against any operations that have been committed since that version, then applies and broadcasts the transformed op. This requires that the server never processes two ops for the same document concurrently — a per-document lock or single-threaded actor model enforces this.
CRDTs (e.g., LSEQ or RGA for sequences) are a better fit if you want true peer-to-peer sync or eventual consistency without a central sequencer. The tradeoff is a more complex data structure and larger memory footprint. For this design, OT on a sequenced log is the right call and easier to audit.
Why Full-Document Overwrites Fail
If two users edit simultaneously and both send the full document body, one write will overwrite the other. Op-based sync avoids this entirely — only the delta is sent, and the server's transformation step ensures both users' intent is preserved.
Offline Reconnect and Catch-Up
When a client reconnects, it sends its last known version. The server responds with all operations from that version to current, or — if the gap is large — a snapshot at a recent checkpoint plus the ops since that snapshot. The client replays them, then submits any locally queued ops (which are transformed against the catch-up ops). Idempotency keys on every op prevent double-application if the network drops mid-submit.
Part 3 — Scalability, Reliability, and Security
Scaling the Collaboration Layer
Route all WebSocket connections for a given document to the same Collaboration Service instance using consistent hashing by doc_id. This lets the OT sequencer work without distributed locking for the common case. A document with unusually high concurrent users (a "hot doc") can be handled by sharding at the block level if needed, though this is rare enough that a well-tuned single-node sequencer handles it.
Pub-sub handles cross-instance fan-out: when a sequencer commits an op, it publishes to a topic keyed on doc_id. All Collaboration Service instances subscribed to that topic (because they hold other sessions for the same doc) forward the broadcast to their clients.
Durability
The operation log is written and acknowledged by the storage layer before the server sends an ack to the client. A crash after the write but before the broadcast is recoverable — clients will catch up on reconnect. A crash before the write means the client retries (idempotency key prevents double-apply).
Snapshots are created asynchronously every N operations or every T minutes by a background job. Old ops before the oldest retained snapshot can be compacted away.
History and Compaction
Retain snapshots and ops for 90 days. After that, keep only the snapshots at day boundaries and drop the fine-grained op log. Users can restore to any snapshot within the window; fine-grained replay is only available for recent history.
Security
- Permission checks happen on every API call and on WebSocket connection upgrade.
- Documents can be encrypted at rest; encryption keys managed per-document via a KMS.
- Rate limiting on op submission (e.g., 100 ops/second per client) prevents abuse.
- All permission changes and deletes are written to an audit log.
- Soft deletes only — documents are marked deleted and purged after a grace period.
Common Mistakes to Avoid
- Sequencing operations globally instead of per-document — unnecessary bottleneck.
- Forgetting to transform client ops against concurrent server ops — the core of OT.
- Acknowledging an op before it is durable — leads to data loss on crash.
- No idempotency keys — causes duplicate operations on client retry.
- Unbounded operation log growth with no compaction strategy.