Day 04 Advanced Patterns

Live Notifications & Dashboards

Push notifications, live data feeds, reconnection handling. Part of the free WebSockets in 5 Days course at Precision AI Academy.

~1 hour Hands-on Precision AI Academy

Today's Objective

Push notifications, live data feeds, reconnection handling. Part of the free WebSockets in 5 Days course at Precision AI Academy.

01

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
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);
02

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
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.

Supporting References & Reading

Go deeper with these external resources.

Docs
Live Notifications & Dashboards Official documentation for websockets.
GitHub
Live Notifications & Dashboards Open source examples and projects for Live Notifications & Dashboards
MDN
MDN Web Docs Comprehensive web technology reference

Day 4 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 5
Day 5 of the WebSockets in 5 Days course