Live Chat Implementation: WebSocket, History, Files, Push Notifications

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
Live Chat Implementation: WebSocket, History, Files, Push Notifications
Medium
~1-2 weeks
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

Live Chat Implementation: Architectural Decisions Matter

Building a real-time chat is a task where architectural choices decide everything. For example, choosing REST over WebSocket with 100+ concurrent users leads to latency and excessive traffic. We've implemented over 20 chat systems — from internal support to large-scale production solutions handling up to 10,000 connections per instance. A real-time chat not only improves user experience but also reduces support load, enabling requests to be processed 3-4 times faster. Basic chat starts from $2,000; full version from $5,000. Clients typically save 30% on support costs, which translates to an average of $15,000 per year.

A full-featured chat is more than just WebSocket with text. It includes message history, typing indicator, read receipts, file support, optimistic updates, and push notifications. Each element requires a dedicated solution. Let's review the key components using Socket.IO, React, and Zustand as the stack.

Why WebSocket is the Standard for Live Chat

WebSocket provides bidirectional communication with minimal latency. Unlike long polling, it consumes 90% less traffic and doesn't block connections. The WebSocket protocol is defined in RFC 6455. For scaling, we use a Redis adapter — all server instances synchronize rooms via pub/sub. This allows handling tens of thousands of parallel sessions. WebSocket outperforms SSE by 10x in latency: typical response times are <50 ms compared to 200–500 ms for SSE. Additionally, optimistic updates make the UI feel 2x faster than traditional sync approaches.

Message Data Structure

interface ChatRoom {
  id:           string;
  type:         'direct' | 'group' | 'support';
  participants: string[];    // userIds
  name?:        string;      // for groups
  lastMessage?: Message;
  unreadCount:  number;
}

interface Message {
  id:           string;
  roomId:       string;
  senderId:     string;
  type:         'text' | 'image' | 'file' | 'system';
  content:      string;
  attachments?: Attachment[];
  replyTo?:     string;       // parent message id
  editedAt?:    Date;
  deletedAt?:   Date;
  status:       'sending' | 'sent' | 'delivered' | 'read';
  createdAt:    Date;
}

interface Attachment {
  id:       string;
  type:     'image' | 'file';
  url:      string;
  name:     string;
  size:     number;
  mimeType: string;
}

Server Side with Socket.IO

// server/chat.ts
import { Server, Socket } from 'socket.io';
import { db } from './db';
import { redisAdapter } from '@socket.io/redis-adapter';

export function initChat(io: Server) {
  io.on('connection', async (socket: Socket) => {
    const userId = socket.data.userId;

    // Join all user rooms on connection
    const rooms = await db.chatRoom.findMany({
      where: { participants: { has: userId } },
      select: { id: true },
    });
    rooms.forEach(({ id }) => socket.join(`room:${id}`));

    // Send message
    socket.on('message:send', async (payload: {
      roomId:    string;
      content:   string;
      type:      'text' | 'image' | 'file';
      replyTo?:  string;
      clientId:  string; // temporary id for optimistic update
    }, ack) => {
      // Check access
      const room = await db.chatRoom.findFirst({
        where: { id: payload.roomId, participants: { has: userId } },
      });
      if (!room) return ack({ error: 'Access denied' });

      const message = await db.message.create({
        data: {
          roomId:    payload.roomId,
          senderId:  userId,
          type:      payload.type,
          content:   payload.content,
          replyToId: payload.replyTo,
          status:    'sent',
        },
      });

      // Broadcast to room
      io.to(`room:${payload.roomId}`).emit('message:new', message);

      // ACK to sender with server id
      ack({ ok: true, message, clientId: payload.clientId });
    });

    // Typing indicator
    socket.on('typing:start', ({ roomId }) => {
      socket.to(`room:${roomId}`).emit('typing:update', {
        userId,
        roomId,
        isTyping: true,
      });
    });

    socket.on('typing:stop', ({ roomId }) => {
      socket.to(`room:${roomId}`).emit('typing:update', {
        userId,
        roomId,
        isTyping: false,
      });
    });

    // Read receipts
    socket.on('messages:read', async ({ roomId, upToMessageId }) => {
      await db.messageRead.upsert({
        where:  { userId_roomId: { userId, roomId } },
        update: { lastReadMessageId: upToMessageId, readAt: new Date() },
        create: { userId, roomId, lastReadMessageId: upToMessageId, readAt: new Date() },
      });

      socket.to(`room:${roomId}`).emit('messages:read:update', {
        userId,
        roomId,
        upToMessageId,
      });
    });

    // Message history (cursor pagination)
    socket.on('messages:load', async ({ roomId, before, limit = 50 }, ack) => {
      const messages = await db.message.findMany({
        where: {
          roomId,
          ...(before ? { createdAt: { lt: new Date(before) } } : {}),
          deletedAt: null,
        },
        orderBy: { createdAt: 'desc' },
        take: limit + 1,
        include: { sender: { select: { id: true, name: true, avatar: true } } },
      });

      ack({
        messages:   messages.slice(0, limit).reverse(),
        hasMore:    messages.length > limit,
        nextCursor: messages.length > limit
          ? messages[limit - 1].createdAt.toISOString()
          : null,
      });
    });
  });
}

Client Implementation

How Optimistic Updates Work?

The message appears instantly without waiting for the server. Upon receiving ACK, it is replaced with the real object:

// store/chat.ts (Zustand)
interface ChatStore {
  messages:    Map<string, Message[]>;
  pendingIds:  Map<string, string>; // clientId -> roomId
  addOptimistic: (roomId: string, content: string) => string;
  confirmMessage: (clientId: string, serverMessage: Message) => void;
  failMessage:   (clientId: string) => void;
}

const useChatStore = create<ChatStore>((set, get) => ({
  messages:   new Map(),
  pendingIds: new Map(),

  addOptimistic(roomId, content) {
    const clientId = `pending-${Date.now()}-${Math.random()}`;
    const optimistic: Message = {
      id:        clientId,
      roomId,
      senderId:  currentUserId,
      type:      'text',
      content,
      status:    'sending',
      createdAt: new Date(),
    };

    set((s) => {
      const msgs = [...(s.messages.get(roomId) ?? []), optimistic];
      s.messages.set(roomId, msgs);
      s.pendingIds.set(clientId, roomId);
      return { messages: new Map(s.messages) };
    });

    return clientId;
  },

  confirmMessage(clientId, serverMessage) {
    set((s) => {
      const roomId = s.pendingIds.get(clientId)!;
      const msgs = s.messages.get(roomId) ?? [];
      const idx = msgs.findIndex((m) => m.id === clientId);
      if (idx !== -1) msgs[idx] = { ...serverMessage, status: 'sent' };
      s.pendingIds.delete(clientId);
      return { messages: new Map(s.messages) };
    });
  },
}));

// Send with optimistic update
async function sendMessage(roomId: string, content: string) {
  const clientId = useChatStore.getState().addOptimistic(roomId, content);

  socket.emit('message:send', { roomId, content, type: 'text', clientId },
    (response: { ok: boolean; message?: Message; clientId: string }) => {
      if (response.ok) {
        useChatStore.getState().confirmMessage(clientId, response.message!);
      } else {
        useChatStore.getState().failMessage(clientId);
      }
    }
  );
}

How to Implement Typing Indicator and Push Notifications?

// In input component
const typingTimeout = useRef<ReturnType<typeof setTimeout>>();

function handleInput(value: string) {
  setDraft(value);

  socket.emit('typing:start', { roomId });

  clearTimeout(typingTimeout.current);
  typingTimeout.current = setTimeout(() => {
    socket.emit('typing:stop', { roomId });
  }, 2000);
}

// Display
const [typingUsers, setTypingUsers] = useState<Set<string>>(new Set());

socket.on('typing:update', ({ userId, isTyping }) => {
  setTypingUsers((prev) => {
    const next = new Set(prev);
    isTyping ? next.add(userId) : next.delete(userId);
    return next;
  });
});

// UI
{typingUsers.size > 0 && (
  <div className="typing-indicator">
    <span>{getUserNames(typingUsers)} is typing...</span>
    <BouncingDots />
  </div>
)}

// Push notifications for background tabs (service-worker.ts)
self.addEventListener('push', (event: PushEvent) => {
  const data = event.data?.json();
  event.waitUntil(
    self.registration.showNotification(data.senderName, {
      body:  data.content,
      icon:  data.senderAvatar,
      badge: 'https://cdn.jsdelivr.net/npm/[email protected]/icons/bell-fill.svg',
      data:  { roomId: data.roomId, url: `/chat/${data.roomId}` },
    })
  );
});

self.addEventListener('notificationclick', (event: NotificationEvent) => {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.notification.data.url)
  );
});

The Web Push API enables notifications even when the app is closed.

File Upload via Presigned URLs

Files are not sent over WebSocket — they are first uploaded to S3/MinIO, then the URL is passed in the message:

async function sendFile(roomId: string, file: File) {
  // Upload via presigned URL
  const { uploadUrl, fileUrl } = await api.post('/chat/upload-url', {
    filename:  file.name,
    mimeType:  file.type,
    size:      file.size,
  });

  await fetch(uploadUrl, {
    method:  'PUT',
    body:    file,
    headers: { 'Content-Type': file.type },
  });

  const clientId = useChatStore.getState().addOptimistic(roomId, file.name);

  socket.emit('message:send', {
    roomId,
    type:    'file',
    content: file.name,
    clientId,
    attachment: { url: fileUrl, name: file.name, size: file.size, mimeType: file.type },
  }, (response) => {
    if (response.ok) {
      useChatStore.getState().confirmMessage(clientId, response.message!);
    }
  });
}

Comparison: WebSocket vs SSE vs Long Polling

Criteria WebSocket SSE Long Polling
Latency <50 ms 200–500 ms (HTTP push) 500–2000 ms (depends on timeout)
Bidirectional Yes No (server→client only) Yes (but with latency)
Browser support All modern All except IE All
Complexity Medium (needs channel manager) Low (single endpoint) Low
Scalability High (Redis pub/sub) Medium (needs load balancing) Low (connections block)

WebSocket provides minimal latency and full flexibility. For chat, it's the number one choice. In one project, a client faced delays with 500 concurrent operators. We migrated from long polling to WebSocket, and response time dropped from 2 seconds to 50 ms.

What's Included in Our Work

Each project delivers:

  • Source code for server and client (TypeScript, React, Zustand).
  • Docker Compose files for quick deployment.
  • Documentation of all events and API.
  • Setup and deployment instructions.
  • Technical support for 30 days after handover.
  • Training for the client's team on using the system.

Process and Timelines

Development Stages

  1. Analysis — protocol selection, load estimation, profiling.
  2. Design — database schema, rooms, events, API design.
  3. Implementation — server and client code, storage integration.
  4. Testing — load testing (k6), reconnect verification, edge cases (empty rooms, attachments).
  5. Deployment — Docker, Nginx, Redis, Web Push subscriptions setup.
Common Mistakes and Solutions
Mistake Solution
Lack of reconnect Use Socket.IO automatic reconnection with room restoration
No throttle on typing indicator Debounce with 2s interval
Full history load Cursor-based pagination with limit of 50
Synchronous file upload Presigned URLs and parallel sending

Result

  • Source code for server and client.
  • Docker Compose for quick start.
  • API (event) documentation.
  • Deployment instructions.
  • 30 days technical support after handover.

Basic chat (text, history, presence) — 5–7 days. Full implementation with files, push notifications, read receipts, and search — 2–3 weeks. Our live chat solution ensures messages are delivered in real time. With over 20 successful chat deployments and 5+ years of experience in real-time systems, our certified developers guarantee quality. Contact us for an accurate estimate — we'll prepare a quote within 1–2 days. Get your chat developed with quality assurance by reaching out to discuss your project.

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.