🌍 Networking

SSE

Server-Sent Events

A web technology that sends one-way real-time data from server to client. An HTTP-based alternative to WebSocket, it implements real-time notifications, feeds, stock price updates, and more through the EventSource API.

📖 Detailed Explanation

SSE (Server-Sent Events) is a web standard technology that allows a server to push real-time data to a client (browser) in one direction. It operates on top of the HTTP protocol and is characterized by "unidirectional communication," in which data flows only from the server to the client. It was first implemented in the Opera browser in 2004 and was later included in the HTML5 standard.

SSE can be used easily in the browser through the EventSource API. Unlike WebSocket, it works over plain HTTP without a separate protocol handshake, so it is fully compatible with existing infrastructure (load balancers, proxies, firewalls). Even if the connection is dropped, the browser automatically attempts to reconnect, and missed data can be recovered through the last event ID.

The SSE message format is very simple: it is a text stream composed of the fields "data:", "event:", "id:", and "retry:". The Content-Type is "text/event-stream". Thanks to this simplicity, server implementation is easy, and an SSE server can be built easily in any programming language.

In real-world services, SSE is widely used for real-time notifications (Facebook, Twitter), stock price/exchange rate updates, live sports coverage, AI response streaming such as ChatGPT, CI/CD build logs, news feeds, and more. If WebSocket is suitable for bidirectional communication, SSE is a simpler and more efficient choice for most real-time scenarios that only require server push.

⚖️ SSE vs WebSocket Comparison

Item SSE WebSocket
Communication Direction Unidirectional (server → client) Bidirectional (server ↔ client)
Protocol HTTP/HTTPS WS/WSS (proprietary protocol)
Automatic Reconnection Built-in browser support Must be implemented manually
Data Format Text only (UTF-8) Text + binary
Infrastructure Compatibility High (HTTP-based) May require separate configuration
Suitable Use Cases Notifications, feeds, AI streaming Chat, games, real-time collaboration

💻 Code Example

// SSE 클라이언트 - EventSource API
const eventSource = new EventSource('/api/events');

// 기본 메시지 수신
eventSource.onmessage = (event) => {
    console.log('데이터 수신:', event.data);
    const data = JSON.parse(event.data);
    updateUI(data);
};

// 연결 성공
eventSource.onopen = () => {
    console.log('SSE 연결 성공!');
};

// 에러 처리 (자동 재연결됨)
eventSource.onerror = (error) => {
    console.log('SSE 에러, 재연결 시도 중...');
    if (eventSource.readyState === EventSource.CLOSED) {
        console.log('연결 종료됨');
    }
};

// 커스텀 이벤트 타입 수신
eventSource.addEventListener('notification', (event) => {
    const notification = JSON.parse(event.data);
    showNotification(notification.title, notification.body);
});

eventSource.addEventListener('price-update', (event) => {
    const price = JSON.parse(event.data);
    updateStockPrice(price.symbol, price.value);
});

// 연결 종료 (컴포넌트 언마운트 시)
function cleanup() {
    eventSource.close();
    console.log('SSE 연결 종료');
}

// React/Vue에서 사용 예시
// useEffect(() => {
//     const es = new EventSource('/api/events');
//     es.onmessage = handleMessage;
//     return () => es.close();  // cleanup
// }, []);
// Express.js SSE 서버
const express = require('express');
const app = express();

app.get('/api/events', (req, res) => {
    // SSE 헤더 설정
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Allow-Origin', '*');

    // 연결 유지를 위한 heartbeat
    const heartbeat = setInterval(() => {
        res.write(':heartbeat\n\n');
    }, 30000);

    // 클라이언트 ID 추적
    const clientId = Date.now();
    console.log(`클라이언트 연결: ${clientId}`);

    // 데이터 전송 함수
    function sendEvent(data, eventType = null, id = null) {
        if (id) res.write(`id: ${id}\n`);
        if (eventType) res.write(`event: ${eventType}\n`);
        res.write(`data: ${JSON.stringify(data)}\n\n`);
    }

    // 초기 데이터 전송
    sendEvent({ message: '연결 성공!', clientId }, 'connected');

    // 예시: 1초마다 시간 전송
    const interval = setInterval(() => {
        sendEvent({
            time: new Date().toISOString(),
            random: Math.random()
        });
    }, 1000);

    // 연결 종료 처리
    req.on('close', () => {
        clearInterval(interval);
        clearInterval(heartbeat);
        console.log(`클라이언트 연결 해제: ${clientId}`);
    });
});

// 여러 클라이언트에게 브로드캐스트
const clients = new Set();

app.get('/api/stream', (req, res) => {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');

    clients.add(res);
    req.on('close', () => clients.delete(res));
});

function broadcast(data) {
    clients.forEach(client => {
        client.write(`data: ${JSON.stringify(data)}\n\n`);
    });
}

app.listen(3000);
# FastAPI SSE 서버
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from sse_starlette.sse import EventSourceResponse
import asyncio
import json

app = FastAPI()

# 간단한 SSE 엔드포인트
@app.get("/api/events")
async def events():
    async def event_generator():
        while True:
            # 데이터 생성
            data = {
                "timestamp": str(asyncio.get_event_loop().time()),
                "message": "Hello SSE!"
            }
            yield f"data: {json.dumps(data)}\n\n"
            await asyncio.sleep(1)

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
        }
    )

# sse-starlette 라이브러리 사용 (권장)
# pip install sse-starlette

@app.get("/api/notifications")
async def notifications(request: Request):
    async def event_stream():
        message_id = 0
        while True:
            if await request.is_disconnected():
                break

            message_id += 1
            yield {
                "event": "notification",
                "id": str(message_id),
                "retry": 5000,  # 재연결 대기 시간 (ms)
                "data": json.dumps({
                    "title": "새 알림",
                    "body": f"메시지 #{message_id}"
                })
            }
            await asyncio.sleep(2)

    return EventSourceResponse(event_stream())

# ChatGPT 스타일 AI 스트리밍 응답
@app.get("/api/chat")
async def chat_stream(prompt: str):
    async def generate_response():
        # AI 모델 응답 시뮬레이션
        response = "안녕하세요! SSE를 사용한 스트리밍 응답입니다."
        for char in response:
            yield f"data: {json.dumps({'token': char})}\n\n"
            await asyncio.sleep(0.05)  # 타이핑 효과
        yield f"data: {json.dumps({'done': True})}\n\n"

    return StreamingResponse(
        generate_response(),
        media_type="text/event-stream"
    )

🗣️ Say It Like This in Practice

💬 In a Technical Selection Meeting
"I think we can implement the real-time notification feature with SSE. Since we only need to push from the server to the client, there's no need to go as far as WebSocket. It's HTTP-based, so we don't need to touch the load balancer configuration either. The EventSource API also handles automatic reconnection, so the client code is simple too."
💬 In an Interview
"SSE is an HTTP-based unidirectional real-time communication technology. Compared with WebSocket, SSE only supports the server → client direction, but it is simple to implement and has good infrastructure compatibility. ChatGPT also uses SSE to stream its answers. The browser supports automatic reconnection, so it is stable even in unstable network environments."
💬 In a code review
"I think we should send a heartbeat every 30 seconds for SSE connections. Proxies or load balancers may drop idle connections. And if you set an event ID, you can recover missed events on reconnection via the Last-Event-ID header."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring browser connection limits

In HTTP/1.1, browsers allow only 6 connections per domain. If you open multiple SSE tabs, other requests may be blocked. Use HTTP/2 or share the connection.

❌
Keeping connections alive without a heartbeat

Proxies, load balancers, and firewalls may drop idle connections after 30–60 seconds. Send a comment (:heartbeat) or an empty event every 15–30 seconds.

❌
Ignoring buffering issues

If Nginx, Apache, etc. buffer the response, SSE does not work. You need to add the X-Accel-Buffering: no header or set proxy_buffering off.

✅
Correct SSE Implementation Pattern

Set the reconnection interval with the retry field, track events with the id field, clean up resources when the connection is closed, and implement appropriate error handling and reconnection logic.

🔗 Related Terms

📚 Learn More