100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Web Development

WebSockets with Redis Pub/Sub

How Redis Pub/Sub lets a cluster of WebSocket servers broadcast messages to clients connected to any instance, and where it falls short.

Scaling & ReliabilityIntermediate10 min readJul 10, 2026
Analogies

Why Redis Pub/Sub Fits WebSocket Fan-Out

Once a WebSocket application runs on more than one server instance, you hit the fundamental cross-instance delivery problem: a message received on server A might need to reach a client whose socket happens to be held by server B, and the two processes have no direct connection to each other. Redis Pub/Sub is a natural fit for solving this because it's simple (two commands, PUBLISH and SUBSCRIBE), fast (Redis processes pub/sub in-memory with sub-millisecond latency for most workloads), and most teams already run Redis for caching or session storage, so adding this responsibility introduces no new infrastructure. Every WebSocket server instance opens a subscriber connection to Redis and listens on one or more channels; when any instance's application code needs to broadcast a message, it calls PUBLISH on the relevant channel, and Redis pushes that message to every currently-subscribed instance, each of which then checks its own local socket table and delivers to any matching connected client.

🏏

Cricket analogy: It's like every stadium's scoreboard operator subscribing to a single shared BCCI feed rather than calling each other directly; when Mumbai's ground publishes a wicket update, Chennai's board receives it instantly through the shared feed without a dedicated line between the two grounds.

Architecture Pattern

The typical pattern has three moving parts working together on every server instance: a WebSocket server managing local client connections, a local in-memory map from user/room ID to socket for that instance's own connections, and a Redis client pair (Pub/Sub in Redis requires a dedicated connection for subscribing, since a connection in subscribe mode can't run other commands, which is why libraries like ioredis recommend using two separate client instances, one for publishing and one for subscribing). When a client sends a chat message, the receiving server writes it to the database if needed, then publishes it to a Redis channel scoped to that chat room (e.g., room:42); every server instance subscribed to room:42 receives the published payload and iterates its local socket map, delivering to any client in that room connected to that specific instance. This means a message touches Redis exactly once regardless of how many servers or how many total connected clients exist, which is what makes the pattern scale well even as the cluster grows.

🏏

Cricket analogy: It's like every stadium having a local ground announcer (the socket map) plus a shared radio link to the BCCI feed (Redis); when Kohli hits a six, the ground publishes it once to the shared feed, and every stadium's local announcer then relays it only to fans physically present in their own ground.

javascript
// Node.js: ws server fanning out chat messages via Redis Pub/Sub
const Redis = require('ioredis');
const pub = new Redis();          // dedicated publisher connection
const sub = new Redis();          // dedicated subscriber connection

const localSockets = new Map();   // userId -> WebSocket, this instance only

sub.subscribe('room:42');
sub.on('message', (channel, payload) => {
  const { targetUserIds, data } = JSON.parse(payload);
  for (const userId of targetUserIds) {
    const socket = localSockets.get(userId);
    if (socket && socket.readyState === socket.OPEN) {
      socket.send(JSON.stringify(data));
    }
  }
});

function broadcastToRoom(roomId, targetUserIds, data) {
  pub.publish(`room:${roomId}`, JSON.stringify({ targetUserIds, data }));
}

Limitations of Redis Pub/Sub

The simplicity of Redis Pub/Sub comes with an important trade-off: it's fire-and-forget, with zero persistence and zero delivery guarantees. If a server instance is disconnected from Redis, restarting, or simply not yet subscribed to a channel at the moment a message is published, that message is gone forever; Redis makes no attempt to buffer it for a late subscriber. This is fine for the WebSocket fan-out use case specifically, since the whole point is delivering to currently-connected clients (a disconnected client wouldn't have received it anyway, and reconnection-and-resync logic, as covered elsewhere, is what handles catching clients up), but it means Redis Pub/Sub is the wrong tool for anything that needs guaranteed delivery, ordering across a restart, or replay, which is what Redis Streams, Kafka, or a proper message queue like RabbitMQ are for. Teams sometimes conflate the two needs and are surprised when Pub/Sub 'loses' messages during a Redis failover or a brief network blip.

🏏

Cricket analogy: It's like a stadium's live PA announcement: if you stepped out to the concession stand exactly when the wicket was announced, you simply missed it, there's no replay button on the live PA, unlike the official scorecard archive which permanently records every ball for later lookup.

Redis Pub/Sub messages are not persisted anywhere and are not redelivered after a Redis restart, failover, or a brief subscriber disconnect. If your application needs guaranteed delivery, at-least-once semantics, or the ability to replay recent history to a client that reconnects, use Redis Streams (with consumer groups) or a dedicated message broker instead, and reserve plain Pub/Sub for the specific job of fanning out to currently-connected WebSocket clients.

Presence and Channel Design

Beyond message fan-out, Redis is also the natural home for presence tracking and channel/room membership in this architecture, using its data structures rather than Pub/Sub itself. A common pattern stores each online user as a key with a short TTL (e.g., presence:user:123 set to expire in 30 seconds) refreshed by a heartbeat from the client's connected server every 15-20 seconds; if the heartbeat stops (client disconnected, server crashed), the key simply expires on its own without any explicit cleanup logic needed, which is more resilient than trying to catch every possible disconnect path in application code. Channel design matters too: using one Redis channel per room (room:42) rather than one giant global channel keeps PUBLISH traffic scoped so a server only needs to subscribe to channels for rooms it actually has active connections in, which meaningfully reduces wasted message delivery once you have thousands of concurrent rooms and servers that only host a small fraction of them each.

🏏

Cricket analogy: It's like a stadium ticketing system marking a seat as 'occupied' with an auto-expiring hold that refreshes every time the turnstile scanner pings it; if a fan leaves early and stops triggering scans, the seat automatically frees up after a timeout without a steward having to manually check every seat.

For very large deployments (hundreds of thousands of rooms), consider Redis Cluster with channel-name-based sharding, since standard Redis Pub/Sub is single-threaded per node and all PUBLISH throughput for a given channel is bound to whichever node owns it. Also watch for the 'thundering subscribe' pattern where every server subscribes to every possible channel at startup; instead, subscribe dynamically only when a local client actually joins that room, and unsubscribe when the last local client in that room disconnects.

  • Redis Pub/Sub solves cross-instance WebSocket delivery: PUBLISH on one server reaches every SUBSCRIBEd server, which then delivers to its own locally-held sockets.
  • A dedicated subscriber connection is required per Redis client, since a connection in subscribe mode can't run other Redis commands.
  • Each message touches Redis exactly once regardless of cluster size, which is what makes the pattern scale.
  • Redis Pub/Sub is fire-and-forget: no persistence, no delivery guarantee, and messages are lost if no one is subscribed at publish time.
  • Use Redis Streams, Kafka, or a message queue instead of Pub/Sub when guaranteed delivery or replay is required.
  • Presence is best tracked with TTL-based keys refreshed by heartbeats, so stale presence expires automatically without explicit cleanup.
  • Per-room channels (rather than one global channel) reduce wasted delivery once a cluster hosts thousands of rooms.

Practice what you learned

Was this page helpful?

Topics covered

#WebDevelopment#WebSocketsStudyNotes#WebSocketsWithRedisPubSub#WebSockets#Redis#Pub#Sub#StudyNotes#SkillVeris#ExamPrep

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse