Day 4 of 5
⏱ ~60 minutes
WebSockets in 5 Days — Day 4

Live Notifications & Dashboards

Push notifications, live data feeds, reconnection handling.

Push Notifications for Live Dashboards

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.

Server — Pushing Live Data
// 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);

Handling Reconnection

Networks drop. Socket.io handles reconnection automatically, but you need to handle the state that was missed while the client was disconnected.

Client — Reconnection Handling
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.');
});
💡
Missed event strategy: When a client reconnects, send it a snapshot of current state rather than replaying every event it missed. Replaying events is complex and usually unnecessary for dashboards.
📝 Day 4 Exercise
Live Metrics Dashboard
  1. Build a dashboard page that displays: active users, requests/sec, error rate — updated every second from the server.
  2. Add a chart using Chart.js that shows the last 30 seconds of data.
  3. Simulate a disconnect by blocking your network for 5 seconds (DevTools Network tab). Verify reconnection works and the dashboard catches up.
  4. Add a notification banner that shows "Reconnecting..." during the disconnect.

Day 4 Summary

  • Push architecture: server broadcasts to subscribed clients when data changes.
  • Socket.io handles reconnection automatically with configurable delay and attempts.
  • On reconnect, send a state snapshot rather than replaying all missed events.
  • Show reconnecting UI state to users — don't silently display stale data.
Finished this lesson?