JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeTopicssystem-designReal-Time System Architecture
PrevNext
system-design
advanced
20 min read

Real-Time System Architecture

websocket
sse
real-time
collaborative-editing
crdt
ot
presence
notifications
event-driven

Real-time frontend architecture enables instant data updates without page refreshes — choosing between WebSockets, Server-Sent Events, and long polling depends on whether your communication is bidirectional, and building features like presence indicators, notifications, and collaborative editing requires understanding event-driven patterns and conflict resolution.

Key Points

1Transport Selection

WebSockets for bidirectional communication (chat, collaboration), Server-Sent Events for server-to-client streams (notifications, feeds), long polling as a universal fallback.

2Presence and Heartbeats

Presence indicators require periodic client heartbeats and server-side timeouts — efficient broadcasting sends updates only to users who can see the presence change.

3OT vs CRDTs

Operational Transformation resolves concurrent edits via a central server (Google Docs approach); CRDTs merge without conflicts by mathematical design and work peer-to-peer (Yjs, Automerge).

4Notification Architecture

Real-time notifications need priority levels, batching/grouping for rapid-fire events, offline persistence with sync-on-reconnect, and deduplication across reconnections.

5Event-Driven Decoupling

Decouple transport (WebSocket/SSE) from business logic using event emitters and pub/sub patterns — components subscribe to events they care about, not to raw connection messages.

What You'll Learn

  • Compare WebSockets, Server-Sent Events, and long polling and select the appropriate transport for a given use case
  • Design a real-time notification system with priority levels, batching, and offline support
  • Explain the difference between Operational Transformation and CRDTs for collaborative editing conflict resolution
  • Implement presence indicators using heartbeat and timeout patterns
  • Apply event-driven architecture patterns (pub/sub, event emitter) to decouple real-time transport from UI components

Deep Dive

Real-time features transform static web pages into living, interactive applications. Chat messages appear instantly, cursors move in collaborative documents, stock prices update continuously, and notifications pop up without refreshing. Implementing these features requires understanding the transport mechanisms, architectural patterns, and conflict resolution strategies that make real-time work reliably.

Transport Mechanisms

WebSockets

WebSockets provide full-duplex, persistent connections between client and server. After an HTTP upgrade handshake, both sides can send messages at any time over a single TCP connection.

JavaScript
const ws = new WebSocket('wss://api.example.com/ws');
 
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', channel: 'chat' }));
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // Handle incoming message
};
ws.onclose = () => { /* Reconnect logic */ };

When to use: Bidirectional communication — chat, multiplayer games, collaborative editing, live trading. The client needs to both send and receive messages frequently.

Trade-offs: Requires WebSocket server infrastructure (not all load balancers/proxies handle WebSocket well), more complex connection management (reconnection, heartbeats), doesn't benefit from HTTP caching.

Server-Sent Events (SSE)

SSE provides a unidirectional stream from server to client over standard HTTP. The browser's EventSource API handles reconnection automatically.

JavaScript
const source = new EventSource('/api/notifications');
 
source.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // Handle notification
};
 
source.onerror = () => { /* Auto-reconnects by default */ };

When to use: Server-to-client updates only — notifications, live feeds, stock tickers, build status, real-time dashboards. The client doesn't need to send messages back through the same channel (it can use regular HTTP requests for that).

Trade-offs: Simpler than WebSockets (regular HTTP, works with all proxies, auto-reconnect), but limited to text data, unidirectional, and limited concurrent connections per domain (6 in HTTP/1.1, unlimited in HTTP/2).

Long Polling

Long polling simulates real-time by keeping an HTTP request open until the server has new data:

  1. Client sends request
  2. Server holds the connection open (up to a timeout)
  3. When new data is available, server responds
  4. Client immediately sends a new request

When to use: Fallback when WebSocket and SSE aren't available (restrictive corporate proxies, legacy infrastructure). Also acceptable for low-frequency updates where the complexity of persistent connections isn't justified.

Trade-offs: Higher latency and overhead (new HTTP connection per update), but works everywhere and requires no special server infrastructure.

Real-Time Notification Systems

A notification system requires several architectural components:

  • Transport: SSE or WebSocket to push notifications from server to client
  • Priority levels: Urgent (toast/banner), normal (notification center), silent (badge count only)
  • State management: Unread count, read/unread status, grouping (3 people liked your post)
  • Persistence: Store in server database for offline users; sync when they reconnect
  • Rate limiting: Batch rapid-fire notifications (10 likes in 5 seconds → "10 people liked your post")
  • Deduplication: Prevent showing the same notification multiple times across reconnections

Presence Indicators

Showing who's online (green dot, "typing..." indicator, live cursors) requires:

  • Heartbeat: Client sends periodic signals (every 15-30 seconds) to indicate it's still active
  • Timeout: Server marks a user as offline if no heartbeat received within the threshold
  • Efficient broadcasting: Only send presence updates to users who can see them (same chat room, same document)
  • Debouncing: For typing indicators, debounce keystrokes and auto-clear after a timeout

Collaborative Editing

Collaborative editing (Google Docs, Figma, Notion) is one of the hardest real-time problems because multiple users can edit the same content simultaneously, creating conflicts.

Operational Transformation (OT)

OT transforms concurrent operations so they can be applied in any order and produce the same result. If user A inserts "x" at position 5 and user B deletes character at position 3, OT adjusts A's operation to insert at position 4 (since B's deletion shifted the text). Google Docs uses OT.

Pros: Battle-tested, works well for text editing. Cons: Complex algorithm, requires a central server to order operations, hard to implement correctly.

CRDTs (Conflict-free Replicated Data Types)

CRDTs are data structures that can be merged without conflicts by mathematical design. Each user edits their local copy, and all copies converge to the same state when synced — no central server needed for conflict resolution.

Pros: Works peer-to-peer, handles offline editing naturally, mathematically guaranteed convergence. Cons: Higher memory overhead (metadata for each character/operation), newer technology with fewer production-proven implementations.

Popular CRDT libraries: Yjs, Automerge, Liveblocks.

Event-Driven Architecture

Real-time systems are inherently event-driven. On the frontend, this means:

  • Event bus/emitter: Decouple producers from consumers. A WebSocket message handler emits events; multiple UI components subscribe to events they care about.
  • Event sourcing: Store a log of events rather than current state. Replay events to reconstruct state (useful for undo/redo, audit trails).
  • Pub/Sub: Clients subscribe to channels/topics. Server publishes messages to channels. Subscribers receive only messages for their subscriptions.

Key Interview Distinction

Choose WebSockets for bidirectional real-time (chat, collaboration), SSE for server-to-client streams (notifications, feeds), and long polling as a fallback. Presence requires heartbeats with timeouts. Collaborative editing needs conflict resolution — OT for server-centric text editing, CRDTs for peer-to-peer or offline-first scenarios. Real-time systems are event-driven: decouple message transport from business logic using pub/sub patterns.

Fun Fact

Google Docs originally used Operational Transformation (OT) for collaborative editing, but when Google built their next-generation collaboration system, they explored CRDTs. The Yjs CRDT library can handle documents with over 100,000 concurrent characters while maintaining sub-millisecond merge times.

Learn These First

Data Layer Architecture

intermediate

Promises & Async/Await

intermediate

Continue Learning

Frontend Scalability Patterns

advanced

Practice What You Learned

Design a real-time notification system for a web application
mid
real-time
A real-time notification system uses Server-Sent Events (SSE) or WebSockets for delivery, a priority queue for ordering, toast UI for immediate alerts, a notification center for history, and the Notifications API for browser-level alerts when the tab is not focused.
Design a food delivery tracking page with real-time updates
senior
real-time
A food delivery tracking page uses WebSocket connections for real-time driver location updates on a live map, a state machine to model order lifecycle (placed through delivered), and Server-Sent Events or polling as fallbacks, with careful attention to mobile battery optimization, offline resilience, and animated map transitions.
Design a real-time chat application like Slack or Messenger
senior
chat
A real-time chat application uses WebSocket connections with heartbeat and exponential backoff reconnection for message delivery, optimistic UI for instant message display, virtualized message lists for performance, and features like typing indicators (debounced broadcasts), read receipts (intersection observer), and file uploads (presigned URLs with progress tracking).
Previous
Data Layer Architecture
Next
Rendering Strategy Architecture
PrevNext