The Question
FE Design

Real-time Collaborative Code Editor Design

Design a collaborative, web-based code editor similar to VS Code Web. The system must support multi-user real-time editing with cursor presence, syntax highlighting for multiple languages, and a robust offline-first experience. Explain your strategy for conflict resolution when multiple users edit the same line while disconnected, and how you would ensure the UI remains responsive (60FPS) during high-frequency updates and large file loads. Detail your choice of data persistence and the synchronization protocol used to bridge the client and server.
React
Monaco Editor
Yjs
CRDT
IndexedDB
WebSockets
Web Workers
TypeScript
LSP
Questions & Insights

Clarifying Questions

Concurrency & Scale: How many concurrent collaborators should a single session support for the MVP?
Assumption: We will support up to 10 simultaneous users per session to ensure high performance.
Language Support: Is the syntax highlighting limited to a few specific languages or should it be extensible?
Assumption: Support for 5-10 major languages (JS, TS, Python, HTML/CSS) using standard language definitions.
Conflict Resolution Strategy: Should we prioritize Operational Transformation (OT) or Conflict-free Replicated Data Types (CRDT)?
Assumption: Use CRDT (specifically Yjs) to simplify offline-to-online reconciliation and decentralized state.
File System: Is this a single-file editor or a full workspace with a folder tree?
Assumption: A workspace-based editor with a file tree and the ability to open multiple tabs.
Offline Scope: Does offline editing include running code or just text persistence?
Assumption: Only text persistence and state synchronization are required; code execution/terminals are out of scope for MVP.

Crash Strategy

Core Bottleneck: Harmonizing real-time remote updates with local offline changes without losing user intent.
Strategy:
Editor Integration: Leverage an established editor core (Monaco or CodeMirror) to handle rendering and syntax highlighting efficiently.
CRDT-based Shared Model: Use a CRDT library (Yjs) as the "Source of Truth" to automatically resolve merge conflicts between offline and online states.
Local-First Persistence: Bind the CRDT model to IndexedDB so every keystroke is immediately persisted locally before hitting the network.
Presence & Transport: Use WebSockets for low-latency updates and a signaling server to manage peer awareness (cursors/selections).

Elite Bonus Points

Differential Sync for Large Files: Implementing "chunking" for very large source files to avoid UI thread blocking during CRDT decoding.
Virtual File System (VFS): Abstracting the file system to allow seamless switching between LocalStorage, IndexedDB, and Remote Cloud Storage.
Optimistic UI for File Ops: Instant feedback for file creation/deletion with a "revert-on-failure" mechanism.
Web Workers for Language Services: Offloading heavy syntax analysis and linting to Background Workers to maintain 60FPS.
Design Breakdown

Requirements

Functional Requirements:
Multi-file workspace with a file explorer.
Real-time collaborative text editing with shared cursors.
Syntax highlighting for major programming languages.
Offline mode: Edit while disconnected, auto-sync upon reconnection.
Conflict resolution: No "Save" button; all changes are merged automatically.
Non-Functional Requirements:
Latency: Local typing must feel instantaneous (<16ms).
Reliability: Zero data loss during network transitions.
Scalability: Handle files up to 1MB smoothly.
Persistence: State must survive browser refreshes or crashes.

Design Summary

Concise Summary: A local-first collaborative editor using Monaco for the UI, Yjs for CRDT-based synchronization, and IndexedDB for persistent offline storage.
Major Components:
Monaco Editor: The heavy-lift UI component providing syntax highlighting and core text manipulation.
Yjs Shared Document: The domain-level CRDT engine that manages shared strings and awareness state.
Persistence Provider: Bridges the Yjs document to IndexedDB for local durability.
WebSocket Provider: Bridges the Yjs document to the network for real-time peer communication.
CUJ Walkthrough:
Editing: User types -> Monaco emits change -> Yjs updates local CRDT -> Persistence Provider saves to IndexedDB -> WebSocket Provider broadcasts update.
Offline Sync: Connection drops -> WebSocket Provider enters "retrying" -> User continues editing (updates saved to IndexedDB) -> Connection restores -> WebSocket Provider pushes local updates and pulls remote updates -> Yjs merges automatically.
Simplicity Audit: This is the simplest robust architecture because Yjs removes the need for complex manual conflict resolution logic or a central "truth" server that dictates state.
Architecture Decision Rationale:
Why CRDT?: Unlike OT, CRDTs allow for offline editing without a complex "transform" history that breaks when the client is disconnected for long periods.
Requirement Satisfaction: Monaco handles performance and highlighting; Yjs handles real-time and conflict resolution; IndexedDB handles offline persistence.

System Diagram

Architecture Deep Dive

Presentation Layer

Component Hierarchy: The App Shell provides the global context. The Workspace Layout splits the view into a File Explorer (sidebar) and the Editor Container (main). The Editor Container wraps the Monaco Editor instance.
Interaction Layer: Keystrokes are captured by Monaco. User cursors are rendered using "decorations" injected into the editor instance based on the Presence Manager data.
Rendering Layer: CSR is preferred to handle the high frequency of updates. Monaco uses its own internal virtualization to handle large files. We use requestAnimationFrame or built-in editor debouncing for rendering non-critical UI like the Sync Status Bar.
UI Frameworks / Tools: React for the shell/sidebar, Monaco Editor for the core, and Tailwind CSS for the layout.

Application Layer

Data Fetching Layer: Initial workspace state is pulled from the remote server via WebSocket or REST. Subsequent updates are purely delta-based via the CRDT stream.
State Management Layer: The primary state is held in the Yjs Shared Doc. We use "bindings" (e.g., y-monaco) to sync the editor's internal state with the CRDT model.
Routing & Navigation: URL-based routing (e.g., /project/:id/file/:path) determines which file is currently active in the Editor Container.

Domain Layer

Business Rules: The logic for "who wins" in a conflict is embedded in the Yjs CRDT algorithm (LWW - Last Writer Wins for registers, and sequence-based merging for text).
Entities / Models: We define SharedString for file content and SharedMap for file metadata/directory structures.
Inter-layer Contracts: The Collaboration Orchestrator acts as a facade, ensuring the Presentation layer doesn't need to know the specifics of CRDT binary formats.

Infrastructure Layer

API / Network: WebSocket Client handles binary CRDT updates. It implements an exponential backoff strategy for reconnections.
Storage: IndexedDB is used via the y-indexeddb provider. It stores the full document history locally, allowing for near-instant boot times on reload by reading from disk while the WebSocket connects.
Wrap Up

Wrap-up

Evaluation: The design effectively meets all MVP requirements. Using Yjs + Monaco reduces custom logic for the hardest parts (text diffing and conflict resolution).
Trade-offs: CRDTs can have a memory overhead over time as they store metadata for deleted characters. A periodic "compaction" or snapshotting on the server would be needed for long-lived projects.
Optimization: For the MVP, we assume a single-threaded UI, but moving the Yjs processing and WebSocket handling to a Web Worker would be the first optimization if typing lag is detected.