Full Stack & Backend Engineer Guide: Real-Time Dashboards with WebSockets & Redis
Streaming 200+ market ticks, IoT telemetry readings, or fleet GPS updates per second directly into React component state via naive setState calls inside a websocket.onmessage handler will freeze the browser main thread at 100% CPU while exhausting backend file descriptors. As a full stack engineer and backend engineer, I architect scalable real-time telemetry dashboards combining Redis Pub/Sub fan-out, backpressure-aware WebSocket hubs, and requestAnimationFrame UI batching.
1. Backend Fan-Out with Bounded Client Send Buffers
A single slow mobile client on a 3G connection must never block broadcasts to 5,000 healthy dashboard subscribers. Every WebSocket connection gets an isolated, bounded outbound ring buffer that coalesces intermediate state snapshots when a slow consumer falls behind:
// ws/hub.go
package ws
import (
"context"
"sync"
)
type Client struct {
ID string
SendChan chan []byte
}
type TelemetryHub struct {
mu sync.RWMutex
clients map[string]*Client
}
func (h *TelemetryHub) BroadcastNonBlocking(payload []byte) {
h.mu.RLock()
defer h.mu.RUnlock()
for _, client := range h.clients {
select {
case client.SendChan <- payload:
default:
// Slow consumer: drop oldest queued frame and push freshest snapshot
select {
case <-client.SendChan:
default:
}
select {
case client.SendChan <- payload:
default:
}
}
}
}
2. Frontend 60fps Frame Coalescing in React & TypeScript
On the frontend, incoming WebSocket messages accumulate in a mutable useRef map outside React's render cycle and flush to state at most once per animation frame (16.6ms):
// hooks/useCoalescedTelemetry.ts
import { useEffect, useRef, useState } from "react";
export interface MetricTick {
sensorId: string;
value: number;
timestampMs: number;
}
export function useCoalescedTelemetry(wsUrl: string): Record<string, MetricTick> {
const [snapshot, setSnapshot] = useState<Record<string, MetricTick>>({});
const bufferRef = useRef<Record<string, MetricTick>>({});
const dirtyRef = useRef(false);
useEffect(() => {
const ws = new WebSocket(wsUrl);
ws.onmessage = (event: MessageEvent<string>) => {
const tick = JSON.parse(event.data) as MetricTick;
bufferRef.current[tick.sensorId] = tick;
dirtyRef.current = true;
};
let rafId: number;
const flushLoop = () => {
if (dirtyRef.current) {
dirtyRef.current = false;
setSnapshot({ ...bufferRef.current });
}
rafId = requestAnimationFrame(flushLoop);
};
rafId = requestAnimationFrame(flushLoop);
return () => {
cancelAnimationFrame(rafId);
ws.close();
};
}, [wsUrl]);
return snapshot;
}