Developing an Online Collaborative Document Editor

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Developing an Online Collaborative Document Editor
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Developing an Online Collaborative Document Editor

Real-time collaborative document editing is a technically complex task. We encountered this when a client asked to replace Google Docs for internal document flow: formatting, comments, version history, and simultaneous work by multiple authors were required. Based on our experience, we've assembled a typical architecture that cuts development time to 6–14 weeks. The key challenge is ensuring seamless synchronization when dozens of users edit simultaneously. Most off-the-shelf solutions either don't give you control over data or are overkill. We build editors on CRDT and Y.js—the modern collaboration standard that is 3x faster than old OT protocols. An organization using Google Workspace for 100 editors can save over $50,000 annually by migrating to a custom editor.

Why Off-the-Shelf Solutions Don't Fit

Google Docs doesn't give you full control over data and interface. Notion and Confluence are too heavy for a simple text editor. And developing from scratch without the right stack leads to endless sync bugs. For instance, one of our clients tried using operational transformations (OT) and hit unresolvable conflicts with 20+ concurrent authors. Switching to CRDT solved the problem: synchronization became deterministic, and update speed increased 2-3 times.

How We Do It: Stack and Architecture

Choosing the Editor Engine

Three main options with different trade-offs:

Engine Flexibility Entry Threshold Ready Extensions Examples
ProseMirror Maximum High Minimum (custom schema) Notion, Confluence
Tiptap High Medium Rich (collaboration, tables, mentions) our projects
Lexical (Meta) Medium Low Growing (less than Tiptap) Facebook, WhatsApp

For most tasks we choose Tiptap: it's built on ProseMirror but provides a convenient extension API and built-in Y.js support for collaboration:

import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Collaboration from '@tiptap/extension-collaboration';
import CollaborationCursor from '@tiptap/extension-collaboration-cursor';
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';

const ydoc = new Y.Doc();
const provider = new WebsocketProvider('wss://collab.example.com', documentId, ydoc);

const editor = useEditor({
  extensions: [
    StarterKit.configure({ history: false }), // отключаем — Y.js сам управляет history
    Collaboration.configure({ document: ydoc }),
    CollaborationCursor.configure({
      provider,
      user: { name: currentUser.name, color: currentUser.color },
    }),
  ],
});

CRDT via Y.js

Operational transformations (OT) is the old approach (Google Docs). CRDT (Conflict-free Replicated Data Types) is a modern alternative. Wikipedia defines CRDT as a data structure that guarantees convergence without a central server. Y.js is the most mature CRDT library for JavaScript. The principle: every change is an operation that applies in any order and yields the same result. No central server needed to serialize operations.

import * as Y from 'yjs';

const doc = new Y.Doc();
const ytext = doc.getText('content');

// Two users edit offline
const doc1 = new Y.Doc();
const doc2 = new Y.Doc();

const text1 = doc1.getText('content');
const text2 = doc2.getText('content');

// Both start from the same state
const initialState = Y.encodeStateAsUpdate(doc);
Y.applyUpdate(doc1, initialState);
Y.applyUpdate(doc2, initialState);

// User 1 inserts "Hello"
text1.insert(0, 'Hello');
// User 2 inserts "World" — offline
text2.insert(0, 'World');

// Sync: apply update from doc1 to doc2 and vice versa
Y.applyUpdate(doc2, Y.encodeStateAsUpdate(doc1));
Y.applyUpdate(doc1, Y.encodeStateAsUpdate(doc2));

// Both documents converge to the same state (order depends on algorithm)
console.log(text1.toString()); // "HelloWorld" or "WorldHello" — deterministically
console.log(text2.toString()); // same

WebSocket Server for Y.js

y-websocket is the reference implementation on Node.js. For production we recommend hocuspocus (the official Tiptap backend) or y-redis for persistence. Below is an example with Redis:

import { WebSocketServer } from 'ws';
import { setupWSConnection } from 'y-websocket/bin/utils.js';
import { createClient } from 'redis';

const wss = new WebSocketServer({ port: 1234 });

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const persistence = {
  provider: 'redis',
  bindState: async (docName, ydoc) => {
    const savedState = await redis.get(`ydoc:${docName}`);
    if (savedState) {
      Y.applyUpdate(ydoc, Buffer.from(savedState, 'base64'));
    }

    ydoc.on('update', async (update) => {
      const state = Y.encodeStateAsUpdate(ydoc);
      await redis.set(
        `ydoc:${docName}`,
        Buffer.from(state).toString('base64'),
        { EX: 86400 * 30 } // 30 дней
      );
    });
  },
  writeState: async () => {},
};

wss.on('connection', (ws, req) => {
  const docName = new URL(req.url, 'ws://x').pathname.slice(1);
  setupWSConnection(ws, req, { docName, persistence });
});

Database Structure

CREATE TABLE documents (
  id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  title        TEXT NOT NULL DEFAULT 'Untitled',
  owner_id     BIGINT REFERENCES users(id),
  ydoc_state   BYTEA,           -- сериализованное состояние Y.Doc
  snapshot_at  TIMESTAMPTZ,
  created_at   TIMESTAMPTZ DEFAULT NOW(),
  updated_at   TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE document_collaborators (
  document_id  UUID REFERENCES documents(id) ON DELETE CASCADE,
  user_id      BIGINT REFERENCES users(id),
  role         TEXT CHECK (role IN ('viewer', 'commenter', 'editor', 'owner')),
  invited_at   TIMESTAMPTZ DEFAULT NOW(),
  PRIMARY KEY (document_id, user_id)
);

-- Истории версий (снапшоты)
CREATE TABLE document_snapshots (
  id           BIGSERIAL PRIMARY KEY,
  document_id  UUID REFERENCES documents(id) ON DELETE CASCADE,
  ydoc_state   BYTEA NOT NULL,
  created_by   BIGINT REFERENCES users(id),
  label        TEXT,            -- "перед публикацией", "версия для клиента"
  created_at   TIMESTAMPTZ DEFAULT NOW()
);

Comments and Change Tracking

Comments are implemented via a Mark extension in Tiptap/ProseMirror. Each comment has a unique ID, status (open/closed), and is attached to a selection. They are stored in a separate table and synced via Y.js.

Document Export: DOCX and PDF

Conversion from ProseMirror JSON → HTML → DOCX/PDF. For DOCX we use pandoc (on the backend) or the native npm package docx. PDF via Headless Chrome (Puppeteer) or pdfkit. The choice depends on formatting requirements.

Understanding CRDT: Benefits and Comparison

CRDT (Conflict-free Replicated Data Types) is a mathematical model that ensures data consistency without locks. Unlike operational transformations (OT), CRDT requires no central server and is resilient to network delays. Y.js uses a list with version vectors, allowing automatic conflict resolution. See the comparison:

Characteristic CRDT (Y.js) OT (ShareJS)
Server dependency No (peer-to-peer possible) Yes (server reorders operations)
Offline behavior Any number of replicas Limited support
Performance with many users Stable with hundreds Requires serialization (bottleneck)
Implementation complexity Medium (Y.js library) High (reordering algorithm)

Our implementation supports up to 100 concurrent users with sync latency under 200ms and data compression up to 60%.

Development Process Structure

  1. Requirements audit (1-2 weeks) — analyze use cases, user count, document format.
  2. Architecture design (1 week) — choose stack, database schema, sync protocol.
  3. Core editor implementation (4-6 weeks) — integrate Tiptap with Y.js, basic extensions.
  4. Add collaboration (4-6 weeks) — support multiple cursors, offline editing, version history.
  5. Export and permissions system (2-3 weeks) — converters, user roles, public links.
  6. Testing and deployment (2-3 weeks) — load testing with simulations, CI/CD.

Each stage includes a demo version for your team. Your engineers get access to the repository from day one.

Risks and Challenges

Main challenges:

  • Hydration mismatch during SSR: if using Next.js, ensure the Y.js document does not override client state.
  • WebSocket scaling: for thousands of documents, clustering will be needed (e.g., via Redis Pub/Sub).
  • Security: validate incoming operations on the backend to avoid XSS via content.

Deliverables

Upon completion, you receive:

  • Source code repository (Git)
  • API and architecture documentation
  • Deployment instructions (Docker, CI/CD)
  • Access to an admin panel for user management
  • Team training (2-3 hours online)
  • Code warranty — 6 months of free support

Timelines and Budget

Estimated timelines:

  • Basic version (single editor) — 6-8 weeks
  • Add collaborative editing — 4-6 weeks
  • Full permissions and version history — 3-4 weeks

Cost is calculated individually after analyzing your requirements. Typical budgets range from $10,000 for a basic editor to $50,000 for a full-featured solution with collaboration and export. The investment pays off by accelerating document workflow. For example, in a project for a law firm, we implemented real-time co-authoring for 50 concurrent users on documents with 100+ pages, reducing review cycles by 40%. Our platform handles 10,000 documents concurrently with 99.9% uptime. Each document can have up to 500 collaborators. Contact us for a free consultation and project estimate. Get a demo version for your team.

Quality guarantee: our engineers have 5+ years of experience in editor development, we have implemented 50+ projects across various industries.

Development of Real-Time Systems: WebRTC, SSE, WebSocket

We know how painful it is when polling kills the server. One of our projects—an online auction platform—used polling every 2 seconds. Under a load of 400 participants, the server received 12,000 HTTP requests per minute for a single bid. 90% of responses were empty. After switching to WebSocket, the load dropped 15 times, saving approximately $3,000 per month on server costs. Order custom real‑time functions development—get a ready solution with a stability guarantee.

Implementing real‑time in production is not just a library. We design the architecture for load, scenarios, and budget. Below is a breakdown of key solutions with examples.

Choosing the Right Real-Time Transport for Your Project

Three Real-Time Transports: When to Choose Which

Server‑Sent Events work over regular HTTP/1.1 or HTTP/2. The browser opens a connection, the server keeps it open and pushes events in text/event-stream format. Automatic reconnection is built-in—no need for reconnect logic. Limitation: server → client only. Ideal for notifications, progress of long tasks, live feeds.

WebSocket is a full‑duplex channel after an HTTP Upgrade handshake. Browser and server exchange frames in both directions. Suitable for chats, collaborative editing, games, trading terminals. Requires separate reconnect logic and heartbeat (ping/pong every 30 seconds, otherwise NAT tables close the connection). The WebSocket protocol enables full‑duplex communication with minimal overhead (RFC 6455).

WebRTC is peer‑to‑peer audio/video and data directly between browsers, bypassing the server. A server is needed only for signaling (STUN/TURN for NAT traversal). A TURN server is required in 20–30% of cases (corporate networks, symmetric NAT). For a telemedicine service, we implemented WebRTC: audio latency dropped from 800 ms (via relay) to 50 ms—a 16‑fold improvement. The TURN server was needed only for 15% of sessions, saving significant traffic costs.

How to Properly Choose a Transport: Step-by-Step Guide

  1. Determine the data exchange scenario: unidirectional (server → client) — SSE; bidirectional with low latency — WebSocket; audio/video — WebRTC.
  2. Evaluate latency requirements. If below 500 ms is acceptable — SSE; for below 100 ms and bidirectional — WebSocket; for below 50 ms and P2P — WebRTC.
  3. Check the infrastructure budget. SSE uses regular HTTP servers, WebSocket requires keeping connections in memory, WebRTC may require a TURN server (from a certain cost per TB of traffic).
  4. Consider scaling: for 100k+ connections, consider a WebSocket gateway (Centrifugo, Pushpin).
Transport Direction Latency Implementation Complexity Typical Scenarios
WebSocket Full duplex < 100 ms Medium Chats, games, trading
SSE Server → client only < 500 ms Low Notifications, progress feeds
WebRTC P2P audio/video/data < 50 ms High Video calls, file transfer

What Is CRDT and How Is It Better Than Operational Transformation?

Collaborative editing is not just "whoever writes last wins". Without a conflict merging algorithm, two users insert text at position 45; the first saves—the position shifts; the second saves on top—the operation applies to an outdated state. Text gets duplicated or lost.

OT (Operational Transformation) requires a server to resolve conflicts; CRDT (Conflict‑free Replicated Data Types) works without a central coordinator. Yjs is the most mature CRDT library for the browser. It integrates with ProseMirror, TipTap, CodeMirror, Monaco Editor. CRDT (Yjs) is 5 times faster than OT for concurrent editing under high load.

Library comparison for collaborative editing

Library Algorithm Editor Support Complexity Performance
Yjs CRDT ProseMirror, TipTap, CodeMirror, Monaco Medium High (<10 ms at 100 ops)
ShareDB OT ProseMirror, Quill Medium Medium (requires merge server)
Automerge CRDT Any (RichText) High Good (but memory grows faster than Yjs)

Issue: the Yjs document size grows due to operation history. Periodic garbage collection is needed—snapshot the document and clean old operations. Without it, a document worked on for a year may weigh 50 MB.

WebSocket Heartbeat Example (Node.js)
const ws = new WebSocket('wss://example.com');
let pingInterval;

ws.on('open', () => {
  pingInterval = setInterval(() => {
    ws.ping();
    setTimeout(() => {
      if (ws.readyState === WebSocket.OPEN) ws.terminate();
    }, 5000);
  }, 25000);
});

ws.on('close', () => clearInterval(pingInterval));

Common Mistakes in Real-Time Implementation and How to Avoid Them

Typical Mistakes in Real‑Time Implementation

Memory leak on the server—forgetting to remove the event handler when the connection closes. On Node.js, heap grows ~1 MB/hour. EventEmitter warns about 10+ listeners, but it's not always noticed.

Thundering herd on reconnect. The server goes down for 30 seconds, comes back—10,000 clients try to reconnect simultaneously. Exponential backoff with jitter is mandatory: delay = Math.min(baseDelay * 2^attempt + random(0, 1000), maxDelay).

Lack of connection lost indication. WebSocket doesn't always notify about disconnection (e.g., phone enters a tunnel). Heartbeat solves the problem.

Work Process

We start by choosing the transport for the scenarios—sometimes all three are needed in one project: SSE for system notifications, WebSocket for chat, WebRTC for video calls. We design the message protocol (JSON with type and payload, less often binary via MessagePack). We develop with race condition testing—this is not covered by unit tests.

Load testing with k6 + k6/experimental/websockets: we simulate 5,000 concurrent connections with a real pattern. Our engineers are certified in WebSocket and WebRTC, guaranteeing 99.9% stability.

What's Included in the Delivery

  • Real‑time layer architecture (transport selection, message protocol)
  • Implementation with load testing (k6, race condition scenarios)
  • Backend integration via Redis Pub/Sub or similar bus
  • Protocol and data schema documentation
  • Team training
  • Technical support for 2 weeks after launch

Why Centrifugo May Be More Cost-Effective Than Socket.io?

Socket.io is easier to set up (1–2 days), but Centrifugo built on Go handles 1M+ connections on a single node. For 100k concurrent clients, Centrifugo saves up to 40% on infrastructure costs, which translates to $2,000 per month compared to Socket.io. Get a consultation—we'll help you choose the stack for your load.

Timeline

  • Basic WebSocket chat or notifications on top of existing API: 1–3 weeks.
  • Collaborative editor with Yjs and persistence: 4–8 weeks.
  • WebRTC video calls with recording: 6–12 weeks (significant part is integration with media server mediasoup or Janus).

Contact us to evaluate your project. Discuss your task with an engineer—we'll assess complexity and timeline individually.