
Modern applications often need to display live information without requiring users to refresh the page. Examples include analytics dashboards, live order tracking, monitoring systems, notification panels, and financial applications.
Traditional HTTP requests work well for fetching data, but repeatedly polling a server for updates can introduce unnecessary requests and delays.
WebSockets provide a persistent, bidirectional connection between a client and a server. Redis Pub/Sub complements this by distributing messages between multiple backend instances, making it easier to build real-time applications that can grow beyond a single server.
In this guide, you'll learn how to build a real-time dashboard using Node.js, Express, Socket.IO, Redis, and React.
1. Understanding the Architecture
Our application will contain four main components:
React: Displays live metrics and dashboard updates.
Node.js and Socket.IO: Manages client connections and delivers events.
Redis Pub/Sub: Distributes events between backend instances.
Data source: Produces metrics, notifications, or other updates.
The architecture looks like this:
React Dashboard
|
| WebSocket
v
Node.js Server A
|
v
Redis Pub
|
Redis Channel
|
v
Node.js Server B
|
v
Connected ClientsWhen an event occurs, the backend publishes it to Redis. Other backend instances subscribed to the channel receive the event and send it to their connected clients.
This architecture is useful when clients connect to different application instances.
2. Why Use WebSockets?
WebSockets allow a client and server to exchange messages over a persistent connection.
Unlike traditional polling, the server can send updates as soon as new information becomes available.
Key benefits include:
Low-latency communication
Reduced repeated HTTP requests
Bidirectional messaging
Support for live notifications and metrics
Efficient updates for interactive dashboards
We'll use Socket.IO, a library that provides WebSocket communication along with reconnection handling and additional features. Socket.IO is not the same protocol as a raw WebSocket connection, so clients should use a compatible Socket.IO client.
3. Why Redis Pub/Sub?
Imagine your application runs on three Node.js servers behind a load balancer.
A user connected to Server A needs to receive an update generated by Server B. Without a shared messaging mechanism, Server A might never know that the update occurred.
Redis Pub/Sub solves this by allowing one process to publish a message to a channel while other processes subscribe to it.
For example:
Server A publishes an event
|
v
Redis Channel
/ \
v v
Server B Server C
| |
v v
Clients ClientsRedis Pub/Sub has an important limitation: messages are not stored for disconnected subscribers. If a subscriber is offline when a message is published, it won't receive that missed message later.
For durable event delivery, consider Redis Streams, a message queue, or a persistent event log.
4. Create the Node.js Project
Create a project directory:
mkdir realtime-dashboard
cd realtime-dashboard
npm init -yInstall the required packages:
npm install express socket.io redis @socket.io/redis-adapter cors dotenvInstall the Socket.IO client separately in your React frontend:
npm install socket.io-clientConfigure your backend's package.json to use ES modules:
{
"type": "module",
"scripts": {
"start": "node server.js"
}
}5. Configure Redis and the Socket.IO Server
Create a file named server.js:
import express from "express";
import http from "node:http";
import cors from "cors";
import { Server } from "socket.io";
import { createClient } from "redis";
import { createAdapter } from "@socket.io/redis-adapter";
import "dotenv/config";
const app = express();
const server = http.createServer(app);
app.use(cors({
origin: process.env.FRONTEND_URL || "http://localhost:5173",
}));
app.use(express.json());
const io = new Server(server, {
cors: {
origin: process.env.FRONTEND_URL || "http://localhost:5173",
},
});
const redisUrl = process.env.REDIS_URL || "redis://localhost:6379";
const pubClient = createClient({ url: redisUrl });
const subClient = pubClient.duplicate();
pubClient.on("error", (error) => {
console.error("Redis publisher error:", error.message);
});
subClient.on("error", (error) => {
console.error("Redis subscriber error:", error.message);
});
await Promise.all([
pubClient.connect(),
subClient.connect(),
]);
io.adapter(createAdapter(pubClient, subClient));
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
});
});
app.get("/health", (_req, res) => {
res.json({ status: "ok" });
});
app.post("/api/metrics", async (req, res) => {
const { activeUsers, totalOrders, revenue } = req.body;
if (
!Number.isFinite(activeUsers) ||
!Number.isFinite(totalOrders) ||
!Number.isFinite(revenue)
) {
return res.status(400).json({
error: "Invalid metric values",
});
}
const metrics = {
activeUsers,
totalOrders,
revenue,
updatedAt: new Date().toISOString(),
};
await pubClient.publish(
"dashboard:metrics",
JSON.stringify(metrics)
);
res.json({
success: true,
metrics,
});
});
const subscriber = subClient.duplicate();
subscriber.on("error", (error) => {
console.error("Dashboard subscriber error:", error.message);
});
await subscriber.connect();
await subscriber.subscribe("dashboard:metrics", (message) => {
try {
const metrics = JSON.parse(message);
io.emit("metrics:update", metrics);
} catch (error) {
console.error("Invalid dashboard message:", error.message);
}
});
const PORT = Number(process.env.PORT || 3000);
server.listen(PORT, "0.0.0.0", () => {
console.log(`Dashboard server running on port ${PORT}`);
});This example uses the Socket.IO Redis adapter to coordinate Socket.IO events across instances. A separate Redis subscriber listens for dashboard metric messages and broadcasts them to connected clients.
The metric endpoint is a demonstration. In production, protect it with authentication, validate values against business rules, and ensure clients cannot submit arbitrary trusted metrics.
6. Configure Environment Variables
Create a .env file:
PORT=3000
REDIS_URL=redis://localhost:6379
FRONTEND_URL=http://localhost:5173For a hosted Redis service, replace REDIS_URL with its connection URL. Use TLS when required by the provider.
Never commit credentials or production Redis URLs to Git.
7. Run Redis Locally with Docker
If Docker is installed, start a local Redis instance:
docker run -d \
--name dashboard-redis \
-p 127.0.0.1:6379:6379 \
redis:7-alpineCheck that the container is running:
docker psThe port is bound to localhost to avoid exposing Redis directly to the network.
Start your Node.js backend:
npm startYour server should now connect to Redis and listen for dashboard events.
8. Build the React Dashboard
Create a React component that listens for live metric updates.
Create Dashboard.jsx:
import { useEffect, useState } from "react";
import { io } from "socket.io-client";
const SOCKET_URL = "http://localhost:3000";
export default function Dashboard() {
const [metrics, setMetrics] = useState({
activeUsers: 0,
totalOrders: 0,
revenue: 0,
});
useEffect(() => {
const socket = io(SOCKET_URL);
socket.on("metrics:update", (data) => {
setMetrics(data);
});
return () => {
socket.off("metrics:update");
socket.disconnect();
};
}, []);
return (
<main>
<h1>Real-Time Dashboard</h1>
<section>
<article>
<h2>Active Users</h2>
<p>{metrics.activeUsers}</p>
</article>
<article>
<h2>Total Orders</h2>
<p>{metrics.totalOrders}</p>
</article>
<article>
<h2>Revenue</h2>
<p>
{Number(metrics.revenue).toLocaleString()}
</p>
</article>
</section>
<small>
Last updated: {metrics.updatedAt || "Waiting for data"}
</small>
</main>
);
}The component connects to the Socket.IO server and updates its state whenever a metrics:update event arrives.
For production, use your deployed backend URL and configure the correct frontend origin.
9. Test Real-Time Updates
With Redis and the backend running, submit sample metrics:
curl -X POST http://localhost:3000/api/metrics \
-H "Content-Type: application/json" \
-d '{
"activeUsers": 125,
"totalOrders": 48,
"revenue": 25000
}'The backend publishes the metrics to Redis. Its subscriber receives the message and broadcasts the event through Socket.IO.
Connected React dashboards should display the updated values without refreshing the page.
You can submit different values to simulate incoming analytics data.
10. Production Best Practices
Before deploying a real-time dashboard, consider the following practices:
Authenticate WebSocket connections: Verify user identity and permissions during connection establishment.
Use rooms for targeted updates: Send organization-specific or user-specific metrics only to authorized rooms instead of broadcasting everything with io.emit().
Validate incoming data: Never assume that events received from clients or external services are trustworthy.
Monitor Redis connections: Track connection failures, memory usage, message volume, and latency.
Handle reconnects: Clients may temporarily lose connectivity. Fetch a fresh dashboard snapshot after reconnecting.
Secure the deployment: Use TLS, protect Redis with appropriate authentication and network controls, and avoid exposing internal services publicly.
Avoid relying on Pub/Sub for persistence: Since messages can be missed, retrieve authoritative metrics from a database or another persistent source when a client reconnects.
Control message frequency: Aggregate or throttle high-volume updates to prevent excessive network traffic and unnecessary React renders.
11. Common Use Cases
This architecture can power several types of applications:
E-commerce order dashboards
Live website analytics
Logistics and delivery tracking
Monitoring and alerting systems
Collaborative applications
Admin panels showing background job status
Real-time notifications
For high-volume systems, measure throughput and latency under realistic load before choosing instance sizes and scaling strategies.
Conclusion
Building a real-time dashboard with WebSockets and Redis Pub/Sub provides a flexible way to deliver live updates to users.
Socket.IO handles client connections and event delivery, while Redis Pub/Sub distributes messages between backend components. React makes it easy to render new information without repeatedly fetching the entire dashboard.
The most important production consideration is that Pub/Sub does not provide durable message history. Combine real-time events with an authoritative data source, authentication, monitoring, and appropriate recovery logic to build a reliable dashboard.
Start with a small implementation, test it across multiple backend instances, and optimize the architecture as your application's traffic grows.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


