C.W.K.
Stream
Lesson 04 of 08 · published

Server-Sent Events (SSE)

~14 min · foundations, sse

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

일방향 push, 옳은 방식으로

Server-Sent Events 는 long polling 의 modern, standardized 형태야. 클라는 특별한 endpoint 로 단일 HTTP request 열고, 서버는 Content-Type: text/event-stream 으로 응답하고 절대 닫지 않아. connection 영원히 열려있고 서버는 할 말 있을 때마다 data: ...\n\n chunk 를 써.

SSE 가 과소평가되는 이유

대부분의 팀이 'real-time 필요해' 에서 SSE 안 보고 WebSocket 으로 직진해. 근데 modern web 의 dominant real-time use case — AI 토큰 streaming — 에 대해선 SSE 가 옳은 답이야. 모든 주요 LLM API (OpenAI, Anthropic, Google) 가 chat completion streaming 에 SSE 써. 브라우저 EventSource 가 재연결 자동 처리. plain HTTP 라 모든 proxy 가 친절. SSE 건너뛸 유일한 이유는 클라도 자주 push 해야 할 때야.

cwkPippa 가 SSE 쓰는 방식

cwkPippa 의 chat endpoint (Claude, Codex, Gemini, Ollama) 다 SSE 위에서 stream — 턴마다 HTTP POST 한 번, 응답이 data: chunk 로 흘러나와. WebSocket 은 진짜로 full-duplex 가 필요한 use case 에만 남겨놨어. 피파가 배운 lesson: AI streaming 한다고 'WebSocket 이 더 멋있어 보여서' 고르지 마.

Code

브라우저 EventSource — 세 줄이면 끝·javascript
const source = new EventSource('/api/stream');

source.onmessage = (e) => {
  const data = JSON.parse(e.data);
  console.log('chunk:', data);
};

source.onerror = () => {
  // Browser will auto-reconnect with backoff.
  console.log('disconnected, will retry');
};
FastAPI SSE endpoint·python
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio, json

app = FastAPI()

async def event_generator():
    while True:
        data = await get_next_event()  # your source
        # SSE wire format: 'data: <payload>\n\n'
        yield f'data: {json.dumps(data)}\n\n'

@app.get('/api/stream')
async def stream():
    return StreamingResponse(
        event_generator(),
        media_type='text/event-stream',
    )

External links

Exercise

위 FastAPI SSE endpoint 짜서 1초마다 heartbeat tick ({ ts: ... }) 보내. 브라우저 탭 열고 devtools 에 EventSource snippet 붙여넣고 tick 이 real-time 으로 들어오는 거 확인. 노트북 lid 30초 닫았다가 열어 — 재연결 코드 한 줄도 안 짰는데 브라우저가 자동 재연결 하는 거 보고 끝.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.