Real-Time Notifications (WebSocket/SSE) Integration

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
Real-Time Notifications (WebSocket/SSE) Integration
Medium
~3-5 days
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

Real-Time Notifications (WebSocket/SSE) Integration

An e-commerce site with 50,000 products: standard polling every 5 seconds generates 10,000 requests per minute — the database crashes, server time wasted. Switching to SSE (Server-Sent Events) cuts the load by 10x: one persistent connection instead of tens of thousands of short-lived ones. We integrate instant notification systems using WebSocket or SSE — alerts without page reload. In 2–3 days you get a turnkey solution stable under 10,000+ concurrent connections. Our team's experience — 10+ years in production highload projects. This not only reduces server load but also cuts infrastructure costs by up to 40%. Our company has delivered 50+ real-time notification projects over 5 years, helping clients save an average of $2000/month on server costs.

How to Choose Between WebSocket and SSE?

SSE — unidirectional stream from server to client over regular HTTP/2. Works with EventSource, auto-reconnects, no libraries needed. Ideal for: new messages, status updates, alerts, system notifications.

WebSocket — bidirectional channel on its own ws protocol. Needed when the client also sends data in real time: chat, games, collaborative editing. Implementation is more complex, requires libraries (Socket.IO, ws).

Criteria SSE WebSocket
Direction Server→Client Bidirectional
Protocol HTTP/2 ws://
Auto-reconnect Built-in Needs implementation
Client libraries EventSource (built-in) ws/socket.io
Use cases Notifications Chat, games

In practice, for notifications SSE is enough in 80% of projects. We add WebSocket when two-way logic (read receipts, typing indicator) is needed. SSE is 10x more efficient than polling in terms of server load and latency.

Implementing SSE on Node.js

// server/routes/notifications.ts
import { Router, Request, Response } from 'express';
import { authMiddleware } from '../middleware/auth';

const router = Router();

const clients = new Map<string, Set<Response>>();

router.get('/stream', authMiddleware, (req: Request, res: Response) => {
  const userId = req.user!.id;

  res.writeHead(200, {
    'Content-Type':  'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection':    'keep-alive',
    'X-Accel-Buffering': 'no',  // important for nginx
  });

  const heartbeat = setInterval(() => {
    res.write(':heartbeat\n\n');
  }, 30_000);

  if (!clients.has(userId)) clients.set(userId, new Set());
  clients.get(userId)!.add(res);

  getUnreadNotifications(userId).then((notifications) => {
    res.write(sseEvent('init', notifications));
  });

  req.on('close', () => {
    clearInterval(heartbeat);
    clients.get(userId)?.delete(res);
    if (clients.get(userId)?.size === 0) clients.delete(userId);
  });
});

function sseEvent(type: string, data: unknown, id?: string): string {
  let msg = '';
  if (id) msg += `id: ${id}\n`;
  msg += `event: ${type}\n`;
  msg += `data: ${JSON.stringify(data)}\n\n`;
  return msg;
}

export function pushNotification(userId: string, notification: Notification) {
  const userClients = clients.get(userId);
  if (!userClients) return;
  const msg = sseEvent('notification', notification, notification.id);
  userClients.forEach((res) => res.write(msg));
}

export default router;

Client side — native EventSource with exponential backoff on errors. We integrate with any toast library (sonner, react-hot-toast).

Scaling SSE with Redis Pub/Sub

When horizontally scaling (multiple instances), a user may be connected to instance A while a notification is generated by instance B. Solution — Redis Pub/Sub:

import { createClient } from 'redis';

const pub = createClient({ url: process.env.REDIS_URL });
await pub.connect();

async function emitNotification(userId: string, notification: Notification) {
  await db.notifications.create({ data: notification });
  await pub.publish(`notifications:${userId}`, JSON.stringify(notification));
}

Each instance subscribes to all channels and delivers only to its own clients. Nginx requires disabling buffering:

location /api/notifications/stream {
    proxy_pass http://app_backend;
    proxy_buffering       off;
    proxy_cache           off;
    proxy_read_timeout    3600s;
    proxy_set_header Connection '';
    chunked_transfer_encoding on;
}

Batching Notifications to Reduce Load

During mass sends (e.g., 100 notifications per second), the client gets a separate SSE event for each. More efficient: batch with a 200 ms debounce:

const pendingByUser = new Map<string, Notification[]>();

function bufferNotification(userId: string, notification: Notification) {
  if (!pendingByUser.has(userId)) {
    pendingByUser.set(userId, []);
    setTimeout(() => flushUser(userId), 200);
  }
  pendingByUser.get(userId)!.push(notification);
}

function flushUser(userId: string) {
  const batch = pendingByUser.get(userId) ?? [];
  pendingByUser.delete(userId);
  if (batch.length === 1) {
    pushToClient(userId, sseEvent('notification', batch[0]));
  } else {
    pushToClient(userId, sseEvent('notifications:batch', batch));
  }
}

This reduces client load (one event instead of many) and server load (fewer write calls). In practice, batching reduces the number of packets by up to 90%, saving network resources and budget.

What's Included in the Work

  • Requirements analysis and technology choice (SSE/WebSocket) based on project architecture.
  • Flow design: Redis, nginx, JWT-based authentication.
  • Server-side implementation (Node.js/Express) and client integration (React, Vue, any framework).
  • Load testing up to 10k+ connections with simulated 1000+ notifications per second.
  • Documentation (API, configs, deployment guide).
  • Post-launch support — 1 month free.
  • Team training session on system maintenance.

Estimated Timeline and Cost

SSE notification implementation with Redis: from 2 to 3 days, starting from $500. Adding WebSocket with two-way logic (read receipts, typing): additional 1 day, from $300. Contact us for a free, no-obligation quote.

Channel Security: JWT and Redis

We use JWT authentication: when establishing an SSE connection, the token is verified in middleware. For WebSocket — similarly. Redis Pub/Sub isolates channels by userId. Additionally, we configure rate limiting at the nginx level (50 requests per second per client). This scheme guarantees that only authorized users receive notifications.

Advantages of SSE over Polling

SSE uses HTTP/2, providing multiplexing and lower resource consumption compared to polling. Delivery latency is under 100 ms, and server load is 5–10 times lower. The client API is native EventSource, requiring no additional libraries. For 95% of projects (notifications, alerts, status updates), SSE is the optimal choice. SSE is 10x more efficient than polling in terms of server load.

Here's a case from practice: a client with 100,000 users switched from polling to SSE — database load dropped by 80%, and notification delivery time decreased from 5 seconds to 200 ms. This saved over 40% on server infrastructure budget, equivalent to $2000/month.

Stage Duration Result
Analysis and technology choice 0.5 day Architecture diagram
SSE + Redis implementation 1.5 days Working /stream endpoint
Client integration 0.5 day Toast notifications on site
Load testing 0.5 day 10k+ connections confirmed
Documentation 0.5 day README, configs, guide

Contact us for a consultation — we'll explain how to implement notifications without performance degradation. We'll assess your project for free.

Approach described in documentation EventSource and Redis Pub/Sub.

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.