KB
Get in touch
All projects
Node.jsWebSocketsConcurrency

Real-Time Collaboration Engine

Low-latency multi-user session synchronization

Personal Project·2024·2 min read

WebSockets

Protocol

Low latency

Focus

Multi-user

Concurrency

Problem

Real-time collaborative applications need consistent state across concurrent users without noticeable lag. I built a backend server to handle multi-user sessions with efficient synchronization under load.

Constraints

  • Low latency — State updates must propagate in milliseconds
  • Concurrency — Multiple users editing shared state simultaneously
  • Consistency — All clients must converge to the same state
  • Load — System must handle concurrent sessions without degradation

Architecture

  1. WebSocket Server — Node.js server managing persistent connections per session
  2. Session State Manager — In-memory state with conflict resolution for concurrent updates
  3. Broadcast Layer — Efficient fan-out of state deltas to connected clients
  4. Concurrency Control — Locking and ordering strategies to prevent race conditions
ADR

Operational transformation over last-write-wins

Last-write-wins loses data when two users edit simultaneously. OT preserves intent and keeps all clients consistent.

Alternative considered: CRDTs — stronger theoretical guarantees but higher implementation complexity for a learning project

Key Implementation

// Broadcast state delta to session participants
function broadcastUpdate(sessionId, delta, excludeClientId) {
  const session = sessions.get(sessionId);
  if (!session) return;

  session.state = applyDelta(session.state, delta);
  for (const [clientId, ws] of session.clients) {
    if (clientId !== excludeClientId && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'delta', payload: delta }));
    }
  }
}

What I'd Do Differently

  • Add Redis for session persistence — In-memory state doesn't survive server restarts
  • Implement heartbeat and reconnection logic — Production clients disconnect frequently
  • Load test with simulated concurrent users earlier — Found bottlenecks late in development