Push notifications, live data feeds, reconnection handling.
Live dashboards need to push data updates without clients polling. The pattern is simple: a data source (database change, API call, queue message) triggers a server event, which the server broadcasts to all connected dashboard clients.
// Simulate a data source (replace with DB change stream, queue, etc.)
setInterval(() => {
const metrics = {
activeUsers: Math.floor(Math.random() * 1000),
requestsPerSec: Math.floor(Math.random() * 500),
errorRate: (Math.random() * 0.05).toFixed(3),
timestamp: new Date().toISOString()
};
// Push to all clients subscribed to the dashboard
io.to('dashboard').emit('metricsUpdate', metrics);
}, 1000);
Networks drop. Socket.io handles reconnection automatically, but you need to handle the state that was missed while the client was disconnected.
const socket = io({
reconnectionDelay: 1000,
reconnectionAttempts: 5
});
socket.on('connect', () => {
console.log('Connected:', socket.id);
// Rejoin rooms and request missed data
socket.emit('joinDashboard');
socket.emit('getLatestState'); // Catch up on missed events
});
socket.on('disconnect', (reason) => {
console.log('Disconnected:', reason);
if (reason === 'io server disconnect') {
// Server kicked us — reconnect manually
socket.connect();
}
});
socket.on('reconnect_failed', () => {
console.log('Could not reconnect. Show offline UI.');
});