Design Google Docs: collaborative editing

Master the design of real-time collaborative editors like Google Docs. Learn how to handle concurrency using Operational Transformation (OT) and CRDTs.

intermediate12 min readBy CureBugs EditorialUpdated 5 Nov 2026

Designing a real-time collaborative text editor like Google Docs or Notion is one of the most fascinating and challenging system design interview questions. It tests your ability to handle complex state synchronization, real-time communication, and distributed data consistency. In this article, we will break down the architecture required to support millions of users typing simultaneously without overwriting each other's work.

Requirements (functional and non-functional)

Before jumping into the architecture, we must define the scope of our system. In an interview, always clarify these requirements with your interviewer.

Functional Requirements

  • Document Management: Users can create, edit, delete, and share documents.
  • Real-time Collaboration: Multiple users can edit the same document simultaneously. Changes should be reflected on all clients in real-time.
  • Conflict Resolution: If two users edit the exact same part of the document at the same time, the system must resolve the conflict gracefully without data loss.
  • Cursor Tracking: Users should see where other collaborators are currently typing (presence).
  • Document History: The system should save the document state and allow users to view or revert to previous versions.

Non-functional Requirements

  • Low Latency: Keystrokes must appear on the local screen instantly and on collaborators' screens within milliseconds.
  • High Availability: The system must remain available even if individual servers fail.
  • Eventual Consistency: All users viewing a document must eventually see the exact same text, regardless of the order in which their messages reached the server.
  • Scalability: The system should handle millions of active users and highly concurrent edits on popular documents.

Capacity estimates

Let's establish some concrete numbers to understand the scale of our system. We will assume a moderately large user base, similar to a popular enterprise SaaS tool.

  • Daily Active Users (DAU): 50 million.
  • Concurrent Users: 5 million during peak hours.
  • Active Documents: Assume 10% of concurrent users are actively typing at any given second = 500,000 active documents.
  • Throughput (Operations): If an active user generates 2 operations (keystrokes/formatting) per second, we have 1 million operations per second (OPS) globally.
  • Storage:
    • An average operation payload is about 50 bytes.
    • 1 million OPS * 50 bytes = 50 MB/sec of operation data.
    • Over a 24-hour period, this is roughly 4.3 TB of raw operation data per day.
    • We will also need storage for document snapshots and metadata, bringing our estimated daily storage growth to ~5 TB.

These numbers tell us two things: we need a highly efficient real-time communication layer (WebSockets) to handle the 1M OPS, and we need an append-only, high-write-throughput database to store the operation history.

API design

Our system requires two types of APIs: a standard REST API for document management and a stateful WebSocket API for real-time collaboration.

REST API (Document Management)

Used for operations that do not require real-time streaming.

  • POST /api/v1/docs - Creates a new document.
  • GET /api/v1/docs/:id - Fetches document metadata and the initial state (snapshot).
  • POST /api/v1/docs/:id/share - Updates permissions.

WebSocket API (Real-time Collaboration)

Once a user opens a document, the client establishes a persistent WebSocket connection to the server: wss://api.example.com/ws/docs/:id.

The communication over this socket uses structured JSON messages:

Client -> Server (Apply Operation):

json
{
  "type": "edit",
  "docId": "doc-123",
  "userId": "user-456",
  "baseRevision": 105,
  "operation": {
    "action": "insert",
    "position": 12,
    "chars": "H"
  }
}

Server -> Client (Broadcast Operation):

json
{
  "type": "sync",
  "docId": "doc-123",
  "userId": "user-789",
  "newRevision": 106,
  "operation": {
    "action": "insert",
    "position": 45,
    "chars": "W"
  }
}

Data model

To support real-time editing and version history, we cannot simply store the final text of the document in a single database row. We must use Event Sourcing, storing every operation as an immutable event.

1. Relational Database (PostgreSQL)

Used for structured metadata where ACID properties and complex joins are necessary.

  • Users Table: user_id, name, email, password_hash.
  • Documents Table: doc_id, owner_id, title, created_at, latest_revision.
  • Permissions Table: doc_id, user_id, role (viewer, editor).

2. NoSQL Database (Cassandra or DynamoDB)

Used for storing the massive volume of operations. NoSQL is ideal here because we are performing high-frequency, append-only writes.

  • Operations Table:
    • Partition Key: doc_id
    • Sort Key: revision_number
    • Columns: user_id, operation_data, timestamp

3. Object Storage (Amazon S3)

Replaying 100,000 operations to load a document is too slow. We periodically squash operations into a text file (a snapshot) and store it in S3.

  • Snapshots: doc_id_rev_1000.json, doc_id_rev_2000.json.

High-level architecture

Here is the high-level flow of how components interact when users edit a document.

Architecture Walkthrough

  1. Connection: When Client A opens a document, they hit the API Gateway, which routes them to the Document Service to fetch the latest snapshot and metadata.
  2. WebSocket Upgrade: Client A then initiates a WebSocket connection. The WebSocket Load Balancer uses Consistent Hashing (based on doc_id) to ensure that all users editing the same document are routed to the same Collaboration Service node.
  3. Editing: Client A types a character. The operation is sent to the Collaboration Service.
  4. Conflict Resolution: The Collaboration Service applies Operational Transformation (OT) to resolve any conflicts, increments the document's revision number, and broadcasts the transformed operation to Client B.
  5. Persistence: The Collaboration Service asynchronously pushes the operation to a Kafka topic.
  6. Storage: A Persistence Worker consumes the Kafka topic, saves the operation to Cassandra, and periodically generates a new snapshot to save in S3.

Deep dives

Let's explore the most complex parts of this system in detail.

1. Concurrency Control: Operational Transformation (OT) vs CRDTs

The core challenge of collaborative editing is concurrency. Imagine the document text is CAT.

  • User A wants to insert S at index 0 (making it SCAT).
  • User B concurrently wants to insert S at index 3 (making it CATS).

If the server processes A's operation first, the document becomes SCAT. When B's operation arrives (insert at index 3), if applied naively, it will result in SCAS instead of SCATS, because A's insertion shifted the indices! We need a way to resolve this.

Approach A: Operational Transformation (OT) OT is the algorithm traditionally used by Google Docs. It relies on a central server as the source of truth. When the server receives B's operation, it notices that B's operation was based on an older revision of the document. The server transforms B's operation against A's operation. Since A inserted a character before B's target index, the server shifts B's target index from 3 to 4.

Here is a simplified example of how an OT transform function looks in code:

class InsertOp:
    def __init__(self, position, char):
        self.position = position
        self.char = char

def transform(op1, op2):
    # Transforms op1 against op2 assuming both originated from the same state
    if op1.position < op2.position:
        # op1 is before op2, no index shift needed for op1
        return op1
    else:
        # op2 happened before op1, so op1's position must shift right
        return InsertOp(op1.position + 1, op1.char)

Approach B: Conflict-free Replicated Data Types (CRDTs) CRDTs are a modern alternative used by tools like Figma and Apple Notes. Instead of using absolute integer indices (0, 1, 2), CRDTs assign unique, fractional identifiers to every character.

If C is at index 0.1 and A is at index 0.2, inserting a character between them simply assigns it an index of 0.15. Because indices are mathematically guaranteed to never conflict and never shift, operations commute. You don't need a central server to transform operations; clients can just merge incoming data.

FeatureOperational Transformation (OT)CRDTs
ComplexityExtremely complex server logicComplex data structures, simple server
CentralizationRequires a central server to order operationsDecentralized (works P2P)
Memory/PayloadSmall payloads (just index + char)Large payloads (metadata for every char)
Offline SupportHard to sync after long offline periodsExcellent offline merge capabilities

For an interview, OT is the classic answer for text editors, but mentioning CRDTs shows you are up-to-date with modern distributed systems literature.

2. WebSocket Routing and Consistent Hashing

In our high-level design, we mentioned routing all users on the same document to the same Collaboration Server. Why is this critical?

If User A connects to Server 1 and User B connects to Server 2, both servers would need to maintain the in-memory state of the document and constantly synchronize with each other over a Pub/Sub system (like Redis) to perform OT. This creates massive internal network traffic and race conditions.

Instead, we use a WebSocket Load Balancer configured with Consistent Hashing.

  1. The load balancer hashes the doc_id.
  2. The hash maps to a specific Collaboration Server on the hash ring.
  3. All WebSocket connections for that doc_id are routed to that single server.

This makes the Collaboration Server a single source of truth for that document. It holds the document state in RAM, serializes incoming operations, performs OT in memory, and broadcasts the results to all connected clients instantly. Redis Pub/Sub is only used as a fallback or for cross-server presence (e.g., global online status), not for resolving text edits.

3. Efficient Storage and Snapshots

Storing every keystroke is necessary for OT and version history, but it creates a massive read bottleneck. If a document has 500,000 operations, a user opening the document would have to download and apply all 500,000 operations to see the text.

To solve this, the Persistence Worker implements a snapshotting mechanism:

  1. As the worker pulls operations from Kafka and writes them to Cassandra, it keeps a counter.
  2. Every N operations (e.g., every 1,000 operations) or every T minutes, the worker compiles the operations into a static text representation (a snapshot).
  3. The snapshot is saved to S3 (e.g., doc_123_rev_5000.json), and the metadata database is updated to point to this new snapshot.

When a client opens the document, the flow is:

  1. Fetch the latest snapshot from S3 (Revision 5000).
  2. Fetch only the delta operations from Cassandra (Revision 5001 to current).
  3. Apply the deltas to the snapshot locally. This reduces document load times from seconds to milliseconds.

Bottlenecks and trade-offs

No system is perfect. Here are the trade-offs we made and potential bottlenecks:

  • Memory on Collaboration Servers: Because we route all users for a document to a single server, that server must hold the document's state in RAM. If a server is assigned too many large documents, it will OOM (Out of Memory).
    • Mitigation: We must monitor memory usage and dynamically rebalance the consistent hash ring. We can also evict inactive documents from memory after a few minutes of no edits.
  • The "Viral Document" Problem: What if a public document is shared on Reddit and 100,000 people open it simultaneously? Routing all 100,000 WebSocket connections to a single server will overwhelm its connection limit (typically ~65k ports) and CPU.
    • Mitigation: We must separate editors from viewers. Editors connect to the primary Collaboration Server. Viewers connect to read-only replica servers. The primary server broadcasts finalized operations to the read replicas via Redis Pub/Sub, which then fan out the updates to the viewers.
  • OT vs CRDT Trade-off: We chose OT (assuming a Google Docs-like model). The trade-off is that our server logic is highly complex, and offline editing is limited. If a user goes offline for 3 days and makes heavy edits, merging their OT state back into the live document is highly prone to failure. If offline-first was a primary requirement, CRDTs would be the better choice despite the memory overhead.

Questions an interviewer will ask next

1. How do you handle cursor tracking and presence? Cursor movements happen constantly and do not change the document text. Saving them to the database would destroy our storage. Instead, cursor positions are treated as ephemeral events. Clients send cursor coordinates over the WebSocket, the server broadcasts them to other clients, and they are immediately discarded. If a server crashes, cursor state is temporarily lost but instantly recovered as soon as users move their mice again.

2. What happens if a Collaboration Server crashes? Because we use WebSockets, the connection will drop.

  1. Clients are programmed to auto-reconnect.
  2. The Load Balancer detects the dead node and removes it from the consistent hash ring.
  3. Clients are routed to a new Collaboration Server.
  4. The new server fetches the latest snapshot from S3 and the latest operations from Cassandra, rebuilds the in-memory state, and resumes accepting edits. There will be a brief latency spike (a few seconds) for those users, but no data is lost because acknowledged edits were already in Kafka.

3. How do you implement "Undo" in a collaborative environment? Undo is notoriously difficult in OT. If User A types "X", User B types "Y", and User A presses Undo, A only wants to remove "X", not "Y". The system cannot just revert to the previous global state. Instead, the local client must generate an inverse operation (e.g., a Delete at the specific index where "X" ended up) and send it through the standard OT pipeline just like a normal edit.

Mock interview

Now design it with an interviewer in the room

Reading a design is the easy part. In the round you have to drive it yourself: ask the right questions, sketch it, and defend each choice when the interviewer pushes back.

  • Starts from this exact problem, on a shared whiteboard
  • Follow-ups on scale, failure and trade-offs
  • A scored report that quotes your answers and says what to fix
Run this as a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
Case studies•intermediate

Design WhatsApp: real-time chat at scale

13 min read
Case studies•intermediate

Design Uber: ride matching and live location

13 min read
Case studies•intermediateStart here

System design case studies: which to practise, in what order

4 min read
Case studies•intermediate

Design YouTube: video upload and streaming

11 min read