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

Live Chat Implementation: Architectural Decisions Matter

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.

Our competencies:

Frequently Asked Questions

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1281
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1237
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    977
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    1026
  • image_website-sbh_0.webp
    Website development for SBH Partners
    1103
  • image_website-_0.webp
    Website development for Red Pear
    550

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.