Front-End System Design for an Offline-First Document Platform
A deep dive into designing a block-based document editor with CRDT sync, real-time collaboration, offline support, and an extensible embed system.
Offline-FirstCRDTReal-TimeReactTypeScript
1. Requirements & Scoping
Building a Notion-like workspace means designing a platform that handles everything from a simple to-do list to a full engineering wiki. The core challenge is not the editor itself — it is making data available everywhere, instantly, even when the network is not.
Key Insight
The hardest part of a Notion clone is the offline-first architecture. The editor is well-understood technology, but syncing blocks across devices without conflicts requires CRDTs, and making it feel instant requires optimistic local writes backed by IndexedDB.
Functional
Block-based document editor with multiple block types (heading, text, todo, code, image)
Drag-and-drop block reordering with nested children
Slash command menu for inserting blocks (/heading, /todo, /code)
Real-time collaboration — multiple users editing the same document
Offline editing with automatic sync when reconnected
Extensible embed system — YouTube, Twitter, code sandbox
Non-Functional
Sub-100ms local operations — no loading spinners for local edits
Offline resilience — full CRDT merge without conflict windows
Bundle under 60KB gzipped for the core editor
Accessibility: WCAG 2.1 AA for rich text editing
Cross-browser: Chrome, Firefox, Safari, Edge
Tip
Offline-first is not a feature you add later. It has to be baked into the data model from day one. If your data model assumes a server round-trip for every write, retrofitting offline support will require a full rewrite of the sync layer.
2. Data Model — Everything Is a Block
The most important architectural decision in a Notion clone is the data model. Notion uses ablock-based model where every piece of content — a heading, a paragraph, a to-do item, an embedded video — is a Block. Documents are just ordered collections of blocks.
This might seem like overkill for a simple note, but it pays off enormously when you need to nest content, support embeds, or sync edits across devices. Each block has a unique ID, a type, and references to its children. The flat structure makes CRDT merging trivial — operations target individual blocks, not positions in a text string.
The children field is an array of block IDs, not inline blocks. This creates a tree structure without nesting objects. When you drag a block to indent it, you are just moving its ID into another block's children array. No deep cloning, no recursive updates.
Block-based data model — every content unit is a typed Block within a Document
Each block type stores its own properties in the props map. A heading stores { level: 2 }, a to-do stores { checked: false }, and an embed stores { url, provider, metadata }. This avoids a sprawling union type while keeping the door open for custom block types.
3. Interface Definition (API)
A collaborative editor needs a clear API contract — both for the server-client CRUD operations and for the real-time sync protocol. The key insight: the API design mirrors the block data model directly. Every endpoint operates on individual blocks, not whole documents.
REST Endpoints for Block CRUD
Documents are loaded once and cached in IndexedDB. After that, every edit is a single-block operation — the client sends only the changed block, not the entire document. This keeps payloads tiny and makes real-time sync trivial.
example.text
GET /api/documents/{docId}
→ Response: { id, title, blocks: Record<string, Block>, rootIds: string[] }
→ Cache: stale-while-revalidate (IndexedDB first, then network)
POST /api/documents/{docId}/blocks
→ Body: { type: "insert", blockId: string, data: Partial<Block>, parentId?: string }
→ Response: { success: true, blockVersion: number }
PUT /api/documents/{docId}/blocks/{blockId}
→ Body: { updates: Partial<Block> }
→ Response: { success: true, blockVersion: number }
DELETE /api/documents/{docId}/blocks/{blockId}
→ Response: { success: true, tombstone: true }
WebSocket wss://api.example.com/ws/documents/{docId}
→ Message: CRDTOperation (broadcast to all connected clients)
→ Auth: session token in connection params
WebSocket Sync Protocol
The sync server is a relay, not an authority. It receives CRDT operations from one client and broadcasts them to all other clients in the same document session. The server does not apply or validate the operation — it just distributes it. This keeps the server stateless and horizontally scalable, while clients do the merge work.
example.typescript
class SyncServer {
private sessions = new Map<string, Set<WebSocket>>();
join(docId: string, ws: WebSocket) {
if (!this.sessions.has(docId)) {
this.sessions.set(docId, new Set());
}
this.sessions.get(docId)!.add(ws);
ws.onclose = () => this.sessions.get(docId)?.delete(ws);
}
broadcast(docId: string, op: CRDTOperation, sender: WebSocket) {
for (const client of this.sessions.get(docId) ?? []) {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(op));
}
}
}
}
Key Insight
Keeping the sync server as a dumb relay is the right call for scale. It does not need to understand the CRDT logic — it only needs to fan out messages. The clients are the ones that resolve conflicts, keeping server CPU costs near zero per document.
4. CRDT Sync — Conflict-Free Replicated Data Types
Here is where things get interesting. Traditional collaborative editing uses Operational Transformation (OT), which requires a central server to resolve conflicts. CRDTs take a different approach: every client can make changes independently, and the data structure itself guarantees that all clients will converge to the same state — no server required.
For our workspace, each block edit generates a CRDTOperation with a Lamport timestamp and a unique client ID. When two clients edit the same block, the merge rule islast-writer-wins per field. Deleted blocks become tombstones (marked with a flag rather than removed) so that concurrent edits on a deleted block are silently ignored instead of resurrecting data.
example.typescript
interface CRDTOperation {
docId: string;
blockId: string;
type: "insert" | "update" | "delete" | "reorder";
data: unknown;
timestamp: number; // Lamport timestamp
clientId: string; // unique per device
seq: number; // monotonic per client
}
function merge(existing: Block, op: CRDTOperation): Block {
// CRDT merge rule: last-writer-wins per field
// with tombstones for deleted blocks
return { ...existing, ...op.data, updatedAt: op.timestamp };
}
Warning
CRDTs solve the consistency problem beautifully, but they come with a cost: tombstoned blocks accumulate over time. A document with thousands of deleted blocks still carries their tombstones in memory. You need a compaction strategy — either periodic garbage collection or a snapshot-based approach where you rebuild state from a checkpoint.
Why CRDT over OT?
Operational Transformation (used by Google Docs) requires a server to transform operations against each other. CRDTs are peer-to-peer by nature. For a workspace that needs offline support, CRDTs are the obvious choice — edits made on a plane are merged automatically when you land, without needing a central authority.
Key Insight
The rule of thumb: if you control the server and users are always online, OT works fine. If you want offline editing, peer-to-peer sync, or a decentralized architecture, pick CRDTs. Yjs and Automerge are the two mature CRDT libraries in the JavaScript ecosystem.
5. Sync Engine — Offline-First at Its Core
The sync engine is the heart of the workspace. Every user operation flows through a single pipeline:apply locally, persist to IndexedDB, queue for sync, send when online. The user never waits for the network.
CRDT sync engine architecture — operations flow locally before reaching the server
The sync engine maintains an operation log in IndexedDB. When the WebSocket connection drops, operations pile up in the queue. On reconnect, the engine flushes them in order. The server broadcasts each operation to all other connected clients.
example.typescript
class SyncEngine {
private queue: CRDTOperation[] = [];
private ws: WebSocket | null = null;
async apply(operation: CRDTOperation) {
// 1. Apply locally immediately
applyToLocalState(operation);
// 2. Persist to IndexedDB
await saveToIndexedDB(operation);
// 3. Queue for sync
this.queue.push(operation);
// 4. Send if online
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(operation));
this.queue = this.queue.filter(op => op !== operation);
}
}
onReconnect() {
// Flush all queued operations
for (const op of this.queue) {
this.ws?.send(JSON.stringify(op));
}
}
}
Conflict Resolution
Conflicts happen when two users edit the same block while offline. Our CRDT handles this: the last-writer-wins rule means the operation with the higher timestamp wins each field. If timestamps are equal (rare, but possible), the higher client ID breaks the tie. No data is lost — the losing write is stored as a conflict that can be reviewed.
Tip
Store conflicts, do not sweep them under the rug. Notion keeps a "version history" that lets users restore previous states. Every CRDT operation is immutable — you can reconstruct any previous document state by replaying operations up to a point in time.
6. Real-Time Collaboration
Real-time collaboration adds awareness — seeing where other users are typing, what they have selected, and which blocks they are editing. This is separate from the CRDT sync layer.
Multi-client collaboration through sync server with offline support
Awareness data (cursor positions, selections, active block) is ephemeral — it does not need CRDT guarantees. We broadcast it over a separate WebSocket channel as lightweight JSON messages. The sync server relays awareness to all clients in the same document session but does not persist it.
The Awareness Protocol
Each client sends an awareness message every 100ms while typing, containing the user's name, color, cursor position, and selected block IDs. Other clients render these as color-coded cursors and block highlights. When a user disconnects, their awareness data is removed after a 10-second timeout.
7. Block Editor Architecture
The editor itself is a deceptively complex piece of UI. Each block is a contenteditableelement, and the editor manages focus, selection, and input events across all blocks.
Input Handling
When the user presses Enter, the editor splits the current block and inserts a new one below. Backspace on an empty block removes it and moves focus to the previous block. Arrow keys at block boundaries navigate between blocks. Each key event is intercepted and translated into block operations.
Slash Command Menu
Typing / at the start of a block triggers the slash command menu. The menu shows available block types filtered by what the user has typed so far. Selecting an item transforms the current block into the chosen type.
Embeds are what transform a document editor into a workspace. A YouTube video, a Twitter thread, a CodeSandbox — these are all just Block instances withtype: "embed".
When a user pastes a URL, the editor extracts the provider from the URL pattern and fetches metadata via an /api/oembed endpoint. The embed block stores the URL, provider name, title, thumbnail, and an embeddable iframe URL. The block renders as a non-editable card with a preview thumbnail and a title.
Embeds are the number one security risk in a document platform. Every iframe must usesandbox="allow-scripts" — never allow-same-origin. External embeds should be rendered in a separate iframe process to prevent the embedded page from accessing your document data.
9. Performance Optimization
A workspace document can have hundreds of blocks. Naively rendering all of them would kill performance. Here are the key optimizations.
Virtual Scrolling
Only render blocks that are visible in the viewport, plus a buffer of 5 blocks above and below. As the user scrolls, blocks enter and exit the DOM. This keeps the DOM lean and the scroll experience smooth even with thousands of blocks.
Contenteditable Isolation
Each block is a separate contenteditable element. This prevents the browser from merging selections across blocks and limits re-renders to the block being edited. No virtual DOM diffing over the entire document on every keystroke.
IndexedDB Read Cache
Documents are loaded from IndexedDB first (instant), then refreshed from the server in the background. The cache uses stale-while-revalidate semantics. Navigating between recently opened documents is instant — no network request.
Key Insight
The single biggest performance win for a block editor is avoiding re-rendering the entire document on every keystroke. By isolating each block as its own contenteditable, editing one block only affects that block's DOM node. Everything else stays untouched.
10. Security Considerations
A document platform with embeds, collaboration, and user-generated content has one of the largest attack surfaces in frontend engineering. Here is how we lock it down.
Content Sanitization
Every block's rich text content passes through DOMPurify before rendering. We strip all HTML tags except a tiny allowlist (bold, italic, code, strikethrough) and remove all attributes. Links are validated with a URL sanitizer that rejects javascript:,data:, and unknown protocols. Embed URLs are checked against a domain allowlist — only trusted providers like YouTube, Twitter, and CodeSandbox are permitted.
Embeds are isolated in separate iframes with sandbox="allow-scripts"— no allow-same-origin. This means an embedded page cannot access cookies, localStorage, or the DOM of the workspace. Each embed iframe also gets aContent-Security-Policy header that restricts it to loading resources only from its own origin.
Collaboration Auth Boundaries
The WebSocket connection authenticates with a session token. The server validates the token and checks document-level permissions (view, comment, edit) before joining a client to a document session. Changes are broadcast only to clients with view access — commenters and editors never receive operations for documents they cannot see.
Warning
Never store un-sanitized user content. Even trusted collaborators can paste malicious HTML into a document. DOMPurify runs on both the client (for immediate feedback) and the server (for enforcement). Client-only sanitization is not security — it is UX.
11. Testing Strategy
A CRDT-based editor with offline support and real-time collaboration is one of the hardest systems to test. The state space is enormous — multiple clients, network conditions, timing — and nondeterministic bugs are the norm. Here is the testing strategy.
CRDT Merge Tests
CRDT merge logic is tested exhaustively with property-based tests. I generate random sequences of operations from multiple clients, apply them in different orders, and assert that the final state converges. This catches edge cases that manual test cases never would — like two clients simultaneously deleting and editing the same block.
I simulate network flakiness with a mock WebSocket that drops, reconnects, and reorders messages. Tests verify that: the offline queue grows while disconnected, flushes in order on reconnect, and correctly handles the case where the same block is edited online and offline simultaneously.
Accessibility Audits
Every PR runs axe-core on the editor in all three view states (empty document, single block, nested blocks). The slash menu, drag handles, and embed blocks are tested for keyboard operability — can a user reach and activate every interactive element using only Tab, Arrow keys, Enter, and Escape?
Tip
For CRDT systems, the most valuable tests are generative. A single handwritten test case for "two clients editing the same block" covers one scenario. A property-based test that generates 10,000 random operation sequences covers more than a human could ever write. Use fast-check or similar for this.
12. Accessibility
A block editor is one of the hardest components to make accessible. Unlike a regular text area, we have custom blocks, drag-and-drop, and slash commands — all of which need keyboard alternatives.
ARIA Roles: Each block uses role="article" witharia-label="Block: {''type{'}'}". The document container uses role="region".
Keyboard Navigation: Tab moves between blocks, Enter creates a new block, Ctrl+Shift+Arrow moves blocks up/down, and / opens the slash menu.
Focus Management: When a block is deleted, focus moves to the previous block. When a new block is inserted, focus lands in its editor.
Drag and Drop: A dedicated drag handle on each block is focusable. Use Space to pick up, Arrows to move, Enter to drop. No mouse required.
Live Regions: An aria-live="polite" region announces when collaborators join/leave and when blocks are added or removed.
Tip
Test your block editor with a screen reader at least once. You will be surprised at how much of the "intuitive" visual UI becomes completely unusable. The slash menu, for example, needsrole="listbox" with aria-activedescendantto be navigable by voice.
Live Demo
Here is a live demo of the block-based editor. Type markdown on the left and see it render as blocks on the right. Try the slash commands, to-do lists, and code blocks.
Type markdown in the left pane and watch blocks render on the right. The editor supports headings, tasks, code blocks, and more.