Polling vs SSE vs WebSocket — Realtime

Perbandingan Teknologi Real-time Short Polling // Client request setiap N detik setInterval(async () => { const res = await fetch("/api/messages?since=" +…

Perbandingan Teknologi Real-time

Short Polling

// Client request setiap N detik
setInterval(async () => {
  const res = await fetch("/api/messages?since=" + lastTimestamp);
  const messages = await res.json();
  if (messages.length) updateUI(messages);
}, 3000); // setiap 3 detik

// Pro: Simple, works everywhere
// Con: Latency (up to 3s), wasteful (banyak empty response)

Long Polling

// Server hold request sampai ada data baru
async function longPoll() {
  const res = await fetch("/api/messages/subscribe");
  const data = await res.json();
  updateUI(data);
  longPoll(); // immediately reconnect
}

// Server side
app.get("/api/messages/subscribe", async (req, res) => {
  // Wait until new message or timeout
  const message = await waitForNewMessage(30000); // 30s timeout
  if (message) res.json(message);
  else res.status(204).end(); // timeout, client reconnects
});

// Pro: Lower latency than polling
// Con: Complex server-side, connection overhead

Server-Sent Events (SSE)

// Server → client stream (HTTP)
const source = new EventSource("/api/events");
source.onmessage = (event) => {
  updateUI(JSON.parse(event.data));
};

// Pro: Native browser API, auto-reconnect, HTTP/2 multiplexing
// Con: Server → client only (no client → server)

WebSocket

// Bidirectional, full-duplex
const ws = new WebSocket("wss://api.example.com/ws");
ws.onmessage = (event) => updateUI(JSON.parse(event.data));
ws.send(JSON.stringify({ type: "typing", user: "Budi" }));

// Pro: Bidirectional, low latency, efficient
// Con: Needs special server, no HTTP caching, connection management

Decision Matrix

NeedBest Choice
Server → client updates onlySSE
Bidirectional (chat, gaming)WebSocket
Simple, low frequencyShort polling
Browser compatibility criticalLong polling (fallback)
Peer-to-peer (video/audio)WebRTC

Yang akan kamu pelajari