WebSocket vs SSE: Pilih Mana untuk Real-time App?

Visualisasi aliran data real-time antara server dan client

Written by

in

Waktu pertama kali membuat fitur notifikasi real-time, saya langsung buka tutorial WebSocket. Kelihatannya WebSocket itu “jawaban” untuk semua hal real-time. Ternyata tidak selalu begitu.

Setelah membuat beberapa project yang melibatkan real-time data — live dashboard, chat sederhana, streaming AI response — saya jadi lebih paham kapan harus pilih WebSocket dan kapan SSE (Server-Sent Events) adalah pilihan yang lebih tepat.

Bedanya dari Konsep Dasar

WebSocket adalah protokol komunikasi dua arah (bidirectional). Setelah koneksi terbentuk, client dan server bisa saling kirim data kapan saja, tanpa perlu request baru.

SSE (Server-Sent Events) adalah mekanisme komunikasi satu arah — dari server ke client. Client cukup buka koneksi HTTP biasa, dan server bisa push update kapanpun.

Analogi simpelnya:

  • WebSocket = telepon. Dua orang bisa ngomong bergantian kapan saja.
  • SSE = radio. Stasiun broadcast, pendengar terima. Pendengar tidak bisa reply lewat channel yang sama.

Cara Kerja WebSocket

  1. Client kirim HTTP request dengan header Upgrade: websocket
  2. Server setuju, koneksi “upgrade” jadi protokol WebSocket
  3. Sekarang ada koneksi persistent yang bisa dipakai dua arah
  4. Baik client maupun server bisa kirim “frame” data kapanpun
  5. Koneksi tutup kalau salah satu pihak menutupnya
// Client side

const ws = new WebSocket('wss://example.com/ws');

ws.onopen = () => {

ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));

};

ws.onmessage = (event) => {

const data = JSON.parse(event.data);

console.log('Received:', data);

};

// Bisa juga kirim dari client ke server kapanpun

ws.send(JSON.stringify({ type: 'ping' }));

Cara Kerja SSE

  1. Client buka HTTP GET request ke endpoint SSE
  2. Server balas dengan header Content-Type: text/event-stream
  3. Koneksi tetap buka, server bisa kirim event kapanpun
  4. Kalau koneksi putus, browser otomatis reconnect (built-in!)
// Client side — sesimpel ini

const eventSource = new EventSource('/api/updates');

eventSource.onmessage = (event) => {

const data = JSON.parse(event.data);

console.log('Received:', data);

};

eventSource.onerror = (error) => {

console.error('SSE error:', error);

// Browser otomatis reconnect, kamu tidak perlu handle manual

};

// Server side (Node.js/Express)

app.get('/api/updates', (req, res) => {

res.setHeader('Content-Type', 'text/event-stream');

res.setHeader('Cache-Control', 'no-cache');

res.setHeader('Connection', 'keep-alive');

const sendUpdate = (data) => {

res.write(data: ${JSON.stringify(data)}\n\n);

};

// Kirim data setiap 5 detik sebagai contoh

const interval = setInterval(() => {

sendUpdate({ time: new Date(), value: Math.random() });

}, 5000);

req.on('close', () => {

clearInterval(interval);

});

});

Perbandingan Head-to-Head

| Aspek | WebSocket | SSE |

|—|—|—|

| Arah komunikasi | Bidirectional | Server → Client only |

| Protokol | ws:// atau wss:// | HTTP biasa |

| Browser support | Semua modern browser | Semua kecuali IE |

| Auto reconnect | Harus implementasi sendiri | Built-in |

| Multiplexing (banyak channel) | Ya, tapi manual | Pakai event types |

| Load balancer friendly | Perlu sticky session | Yes (stateless HTTP) |

| Overhead | Lebih rendah setelah handshake | Header HTTP tiap batch |

| Kompleksitas setup | Lebih tinggi | Lebih rendah |

Kapan Pakai WebSocket?

Pilih WebSocket kalau:

Butuh komunikasi dua arah yang sering. Contoh paling klasik: aplikasi chat. User kirim pesan, server forward ke user lain. Kalau pakai SSE, kamu masih butuh endpoint POST terpisah untuk kirim pesan dari client — jadi awkward.

Online game atau collaborative editing. Google Docs-style editing, whiteboard kolaboratif, game multiplayer — semua butuh latensi rendah dan dua arah.

Banyak aksi dari client yang perlu real-time feedback. Kalau user sering trigger action dan butuh response cepat, WebSocket lebih natural.

Use case bagus untuk WebSocket:
  • Chat app
  • Multiplayer game
  • Collaborative editor (Figma, Google Docs)
  • Live trading/bidding platform
  • Video call signaling

Kapan Pakai SSE?

Pilih SSE kalau:

Server yang push, client yang dengarkan. Live dashboard dengan chart yang update otomatis, feed berita real-time, notifikasi, status monitoring — ini semua SSE territory.

Streaming AI response. Ini yang paling relevan sekarang. ChatGPT, Claude — mereka streaming response karakter per karakter. Itu SSE! Server push token satu-satu, browser tampilin seiring datang.

Mau simpel dan HTTP-native. SSE bekerja di atas HTTP biasa. Tidak perlu library khusus di server, tidak perlu handle upgrade protocol, lebih mudah di-debug.

Load balancer standar. WebSocket perlu sticky session atau konfigurasi khusus di load balancer. SSE cukup HTTP standar — lebih friendly di infrastructure yang sudah ada.

Use case bagus untuk SSE:
  • Live dashboard / analytics
  • Streaming AI output
  • Notifikasi real-time
  • Live score/update olahraga
  • Log streaming
  • Progress bar untuk long-running task

SSE untuk Streaming AI Response: Contoh Nyata

Ini pattern yang sekarang banyak dipakai:

// Endpoint streaming AI response

app.post('/api/chat', async (req, res) => {

const { message } = req.body;

res.setHeader('Content-Type', 'text/event-stream');

res.setHeader('Cache-Control', 'no-cache');

const stream = await openai.chat.completions.create({

model: 'gpt-4',

messages: [{ role: 'user', content: message }],

stream: true,

});

for await (const chunk of stream) {

const token = chunk.choices[0]?.delta?.content || '';

if (token) {

res.write(data: ${JSON.stringify({ token })}\n\n);

}

}

res.write('data: [DONE]\n\n');

res.end();

});

Clean, straightforward, dan tidak perlu maintain koneksi WebSocket yang stateful.

Mitos: “WebSocket Selalu Lebih Baik karena Lebih Powerful”

Powerful bukan berarti lebih cocok. Kalau kamu pakai WebSocket untuk use case yang sebetulnya cukup SSE, kamu nambah kompleksitas tanpa benefit:

  • Harus handle reconnection logic sendiri
  • Perlu manage WebSocket state di server
  • Load balancer jadi lebih ribet
  • Library/dependency tambahan

SSE itu “cukup” untuk banyak kasus, dan “cukup” sambil lebih simpel adalah pilihan yang bagus.

Hybrid Approach

Kamu juga bisa kombinasikan keduanya:

  • SSE untuk push dari server (update, notifikasi)
  • Regular HTTP POST/fetch untuk aksi dari client

Ini bahkan lebih sederhana dari WebSocket dalam beberapa kasus, karena request-response tetap familiar dan mudah di-debug.

Kesimpulan

  • WebSocket untuk komunikasi dua arah yang intens dan real-time (chat, game, collaborative tools)
  • SSE untuk server push yang satu arah (dashboard, notifikasi, AI streaming)

Mulai dari SSE kalau kamu belum yakin — lebih mudah diimplementasikan, lebih friendly di infrastructure, dan auto reconnect sudah built-in. Upgrade ke WebSocket hanya kalau kamu benar-benar butuh bidirectionality.


Lagi bangun fitur real-time dan bingung pilih mana? Atau ada arsitektur yang mau didiskusikan? Yuk ngobrol — hubungi mafadev.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *