Feedback Form

Real-Time Updates: Server-Sent Events (SSE) and WebSocket Fallback

Real-Time Updates: Server-Sent Events (SSE) and WebSocket Fallback

Introduction

आज के web applications में real-time updates बहुत ज़रूरी हो गए हैं। चाहे वो live chat app हो, stock market dashboard हो, या online gaming server — हर जगह data को real-time में sync रखना जरूरी होता है। इसके लिए दो सबसे popular technologies हैं: Server-Sent Events (SSE) और WebSocket

इस blog में हम detail में समझेंगे कि SSE और WebSocket क्या होते हैं, कैसे काम करते हैं, और fallback mechanism की जरूरत क्यों पड़ती है।

What is Real-Time Updates?

Real-Time Updates का मतलब है कि जैसे ही server पर कोई नया data आता है, वो तुरंत client browser तक पहुँच जाए — बिना किसी manual refresh के।

Example के तौर पर मान लो आप एक cricket score tracking website चला रहे हैं। जैसे ही score server पर update होता है, वो automatically user के screen पर दिख जाना चाहिए। इसे ही real-time data delivery कहते हैं।

Traditional Approach: Polling

Real-time updates को achieve करने का सबसे पुराना तरीका है HTTP Polling। इसमें client बार-बार server को request भेजता है — “क्या नया data आया?”

Problems with Polling

  • बार-बार request भेजने से server load बढ़ता है।
  • Network bandwidth waste होती है।
  • Response में delay आ सकता है क्योंकि client हर बार wait करता है।

इन्हीं समस्याओं को solve करने के लिए modern web technologies जैसे Server-Sent Events (SSE) और WebSocket का use किया जाता है।

Server-Sent Events (SSE)

Server-Sent Events (SSE) एक unidirectional communication method है, जिसमें server continuously client को updates भेज सकता है, लेकिन client server को message नहीं भेज सकता।

How SSE Works

SSE में connection एक simple HTTP request के through establish होता है। जब browser connection open करता है, server उसी connection के माध्यम से लगातार events भेजता रहता है।

Example Code

मान लो हमारे पास एक server है जो live temperature data भेज रहा है।

// Client Side (JavaScript) const eventSource = new EventSource('/temperature'); eventSource.onmessage = function(event) { const data = JSON.parse(event.data); console.log('Current Temperature:', data.temp); }; // Server Side (Node.js Express Example) app.get('/temperature', (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); setInterval(() => { const temp = (20 + Math.random() * 5).toFixed(1); res.write(`data: {"temp": "${temp}"}\n\n`); }, 3000); });

Advantages of SSE

  • HTTP-based होने के कारण firewall और proxy friendly है।
  • Implementation आसान और lightweight है।
  • Automatic reconnection support करता है।

Limitations of SSE

  • Unidirectional है — सिर्फ server से client communication।
  • Binary data support नहीं करता (सिर्फ text-based)।
  • Older browsers में limited support है।

WebSocket

WebSocket एक full-duplex communication protocol है, जो client और server दोनों को real-time में एक-दूसरे से बात करने की सुविधा देता है।

How WebSocket Works

जब browser WebSocket connection बनाता है, तो HTTP connection को upgrade किया जाता है और उसके बाद दोनों तरफ data freely flow कर सकता है।

Example Code

// Client Side const socket = new WebSocket('ws://localhost:8080'); socket.onopen = () => { console.log('Connected to Server'); socket.send('Hello Server!'); }; socket.onmessage = (event) => { console.log('Message from server:', event.data); }; // Server Side (Node.js) const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 8080 }); server.on('connection', socket => { console.log('Client connected'); socket.on('message', message => { console.log('Received:', message); socket.send('Server received your message'); }); });

Advantages of WebSocket

  • Full-duplex communication — दोनों तरफ से data भेजा जा सकता है।
  • Low latency और fast updates।
  • Chat apps, games, collaborative tools के लिए ideal।

Limitations of WebSocket

  • Implementation थोड़ा complex होता है।
  • Proxy और firewall issues आ सकते हैं।
  • Scaling के लिए special infrastructure चाहिए।

SSE vs WebSocket Comparison

Feature Server-Sent Events (SSE) WebSocket
Communication Type Unidirectional (Server → Client) Bidirectional (Server ↔ Client)
Protocol HTTP Custom (ws / wss)
Complexity Low High
Browser Support Wide Modern only
Use Case Notifications, Feeds, Live Scores Chat, Gaming, Collaboration Tools

Fallback Mechanism

कई बार ऐसा होता है कि client के browser या network environment में WebSocket support नहीं होता। ऐसे में हमें fallback mechanism का use करना पड़ता है ताकि app real-time updates देना जारी रखे।

Common Fallback Approach

Fallback approach में सबसे पहले WebSocket connection try किया जाता है। अगर वो fail हो जाए तो system automatically SSE या Long Polling पर switch कर जाता है।

Example Implementation Logic

try { const socket = new WebSocket('ws://example.com/socket'); socket.onopen = () => console.log('WebSocket connected'); } catch (error) { console.log('WebSocket not supported, switching to SSE'); const eventSource = new EventSource('/events'); eventSource.onmessage = (e) => console.log('SSE data:', e.data); }

Libraries that handle Fallback Automatically

  • Socket.IO — Automatically handle WebSocket → SSE → Polling fallback।
  • SockJS — JavaScript library जो हर environment में real-time communication ensure करती है।

Real-Life Use Cases

  • Live Stock Updates: SSE का use real-time prices broadcast करने में।
  • Chat Applications: WebSocket का use दो users के बीच instant messaging के लिए।
  • Live Notifications: Social media sites SSE से new likes/comments दिखाती हैं।
  • Online Multiplayer Games: WebSocket से low latency gaming possible होती है।

Performance Considerations

Real-time systems को design करते समय performance और scalability पर ध्यान देना बहुत जरूरी है।

  • Server load control करने के लिए message throttling use करें।
  • Connection limit से बचने के लिए load balancers और distributed servers का use करें।
  • Data compress करें ताकि bandwidth कम use हो।

Security in Real-Time Communication

  • Always use WSS (WebSocket Secure) instead of plain WS।
  • Authentication tokens के साथ secure handshake करें।
  • Rate limiting implement करें ताकि DoS attacks से बचाव हो।

When to Use SSE or WebSocket

Scenario Recommended Technology
Real-time Notifications, Feeds Server-Sent Events (SSE)
Instant Messaging, Multiplayer Games WebSocket
Low Traffic + One-way Updates SSE
Heavy Bidirectional Communication WebSocket

Exam Notes (Quick Revision)

  • SSE → Server to Client one-way communication।
  • WebSocket → Full-duplex real-time protocol।
  • Fallback → Automatic switch to SSE or Polling जब WebSocket fail हो।
  • Socket.IO → Best library for real-time with fallback support।
  • SSE HTTP protocol use करता है जबकि WebSocket custom protocol।
  • SSE text-based होता है, WebSocket binary + text दोनों support करता है।
  • SSE simple implementation के लिए best है, WebSocket complex apps के लिए।