Server-Sent Events 완전 가이드: 실시간 웹의 이해와 구현

· web

들어가며

최근 Unschedule AI 프로젝트와 이전 회사에서 작업 상태를 실시간으로 보여줘야 하는 요구사항을 구현하면서 SSE(Server-Sent Events)를 깊이 있게 다룰 기회가 있었습니다.

처음에는 단순히 "실시간 데이터 전송"이라는 기능적 측면에만 집중했지만, 실제 구현 과정에서 여러 궁금증이 생겼습니다. "SSE는 내부적으로 어떻게 동작하는 걸까?", "왜 EventSource API로는 인증 헤더를 보낼 수 없을까?", "다른 실시간 통신 방식과는 어떤 차이가 있을까?" 같은 질문들 말입니다.

이 글에서는 SSE를 구현하면서 가졌던 이런 궁금증들을 해결하기 위해 찾아본 내용들을 정리했습니다. SSE의 내부 동작 원리부터 시작해서, 실제 구현할 때 마주쳤던 인증 관련 이슈들과 해결 방법까지 상세히 다루어보겠습니다.

SSE란 무엇인가?

개념과 특징

Server-Sent Events(SSE)는 서버에서 클라이언트로 단방향 실시간 데이터 스트리밍을 제공하는 웹 표준입니다. HTTP/1.1의 청킹 전송 인코딩(Chunked Transfer Encoding)을 기반으로 동작합니다.

Chunked Transfer Encoding이란?

Chunked Transfer Encoding은 HTTP/1.1에서 도입된 전송 방식으로, 전체 콘텐츠 크기를 미리 알 수 없을 때 데이터를 여러 개의 '청크(chunk)'로 나누어 전송하는 메커니즘입니다.

# 일반 HTTP 응답 (Content-Length 필요)
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 1234

[1234 bytes of data]

# Chunked Transfer Encoding 응답
HTTP/1.1 200 OK
Content-Type: text/event-stream
Transfer-Encoding: chunked

1a\r\n
data: first message\n\n\r\n
1b\r\n
data: second message\n\n\r\n
0\r\n
\r\n

Chunked Encoding의 특징:

  • 크기 미리 알림 불필요: Content-Length 헤더 없이 스트리밍 가능
  • 실시간 전송: 데이터가 준비되는 대로 청크 단위로 즉시 전송
  • 연결 유지: 청크 크기가 0이 될 때까지 연결 지속
  • 버퍼링 제어: 서버가 버퍼링 없이 즉시 데이터 플러시 가능

SSE는 이 Chunked Transfer Encoding을 활용하여:

  1. 연결을 계속 열어둔 채로 유지
  2. 서버에서 이벤트가 발생할 때마다 새로운 청크로 전송
  3. 클라이언트는 각 청크를 즉시 수신하여 처리
// 서버 측 구현 예시 - Chunked Encoding 활용
app.get("/api/sse/stream", (req, res) => {
  // Transfer-Encoding: chunked 자동 설정 (Node.js)
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    // Content-Length 헤더 없음 - Chunked 모드
  });

  // 각 write()가 하나의 청크로 전송됨
  res.write("data: message 1\n\n"); // 청크 1

  setTimeout(() => {
    res.write("data: message 2\n\n"); // 청크 2
  }, 1000);

  // 연결 종료 시 크기 0 청크 전송
  // res.end(); → "0\r\n\r\n" 전송
});
// 클라이언트 측 SSE 연결
const eventSource = new EventSource("/api/sse/stream");

eventSource.onmessage = (event) => {
  console.log("새로운 데이터:", event.data);
};

eventSource.onerror = (error) => {
  console.error("SSE 연결 오류:", error);
};

SSE vs Polling: 근본적인 차이점

실시간 데이터를 받는 방법은 크게 세 가지가 있습니다: Polling, Long Polling, 그리고 SSE. 각각의 동작 방식을 비교해보겠습니다.

Short Polling (단순 폴링)

// Polling - 클라이언트가 주기적으로 요청
function polling() {
  setInterval(async () => {
    // 매 3초마다 새로운 HTTP 연결 생성
    const response = await fetch("/api/data");
    const data = await response.json();

    if (data.hasUpdate) {
      updateUI(data);
    }
    // 연결 종료 → 3초 후 다시 연결
  }, 3000);
}

// 문제점:
// - 불필요한 요청 (데이터 없어도 계속 요청)
// - 높은 지연시간 (최대 3초)
// - 서버 부하 증가 (연결 생성/종료 반복)

Long Polling (긴 폴링)

// Long Polling - 서버가 데이터 있을 때까지 대기
async function longPolling() {
  while (true) {
    try {
      // 서버는 데이터가 있을 때까지 응답 보류 (최대 30초)
      const response = await fetch("/api/long-poll", {
        timeout: 30000,
      });
      const data = await response.json();

      updateUI(data);
      // 응답 받으면 즉시 다시 연결
    } catch (error) {
      // 타임아웃 또는 에러 시 재연결
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }
}

// 개선점: 즉시성 향상, 불필요한 요청 감소
// 문제점: 여전히 연결 재생성 오버헤드 존재

SSE (Server-Sent Events)

// SSE - 하나의 연결로 지속적 스트리밍
const eventSource = new EventSource("/api/sse/stream");

// 한 번 연결하면 서버가 계속 데이터 푸시
eventSource.onmessage = (event) => {
  updateUI(JSON.parse(event.data));
  // 연결 유지된 상태로 다음 메시지 대기
};

// 연결이 끊어지면 자동 재연결
// 서버는 필요할 때만 데이터 전송

네트워크 레벨 비교

# Polling (매번 새 연결)
→ GET /api/data HTTP/1.1
← HTTP/1.1 200 OK (no data)
[연결 종료]
... 3초 대기 ...
→ GET /api/data HTTP/1.1
← HTTP/1.1 200 OK (no data)
[연결 종료]
... 3초 대기 ...
→ GET /api/data HTTP/1.1
← HTTP/1.1 200 OK (has data!)
[연결 종료]

# Long Polling (대기 후 재연결)
→ GET /api/long-poll HTTP/1.1
... 서버 대기 중 (최대 30초) ...
← HTTP/1.1 200 OK (data available!)
[연결 종료]
→ GET /api/long-poll HTTP/1.1 (즉시 재연결)
... 서버 대기 중 ...

# SSE (지속 연결 + Chunked Streaming)
→ GET /api/sse/stream HTTP/1.1
← HTTP/1.1 200 OK
← Transfer-Encoding: chunked
← Content-Type: text/event-stream

← data: message1\n\n [청크 1]
... 연결 유지 ...
← data: message2\n\n [청크 2]
... 연결 유지 ...
← data: message3\n\n [청크 3]
... 계속 연결 유지 ...

성능 및 리소스 비교

특성Short PollingLong PollingSSE
연결 수매 요청마다 새 연결응답 후 재연결단일 지속 연결
실시간성폴링 주기만큼 지연거의 실시간실시간
서버 부하높음 (연속 요청)중간낮음 (연결 유지만)
네트워크 오버헤드높음 (헤더 반복)중간낮음 (초기 연결만)
CPU 사용량높음 (연결 생성/종료)중간낮음
배터리 소모 (모바일)높음중간낮음
프록시 호환성매우 좋음타임아웃 이슈 가능좋음

실제 사용 예시 비교

// 채팅 애플리케이션 구현

// 1. Polling 방식 - 비효율적
class ChatPolling {
  async pollMessages() {
    setInterval(async () => {
      const messages = await fetch("/api/messages?since=" + this.lastId);
      // 문제: 메시지 없어도 3초마다 요청
      // 1000명 사용자 = 초당 333개 요청
    }, 3000);
  }
}

// 2. Long Polling - 개선되었지만 복잡
class ChatLongPolling {
  async pollMessages() {
    while (true) {
      try {
        const messages = await fetch("/api/messages/long-poll");
        this.handleMessages(messages);
        // 재연결 오버헤드 여전히 존재
      } catch (e) {
        // 에러 처리, 재연결 로직 필요
      }
    }
  }
}

// 3. SSE - 간단하고 효율적
class ChatSSE {
  connect() {
    this.eventSource = new EventSource("/api/messages/stream");
    this.eventSource.onmessage = (e) => {
      this.handleMessage(JSON.parse(e.data));
      // 연결 유지, 서버가 푸시할 때만 처리
      // 1000명 사용자 = 1000개 연결 유지 (요청 없음)
    };
    // 자동 재연결 기본 제공
  }
}

핵심 차이점 요약:

  • Polling: 클라이언트가 능동적으로 계속 물어봄 ("데이터 있어?")
  • SSE: 서버가 능동적으로 알려줌 ("데이터 왔어!") + 연결 유지

이것이 바로 Chunked Transfer Encoding의 힘입니다. 연결을 끊지 않고 필요할 때마다 청크를 보내므로, 폴링의 비효율성을 완전히 제거할 수 있습니다.

WebSocket vs SSE

특징SSEWebSocket
통신 방향서버 → 클라이언트 (단방향)양방향
프로토콜HTTP/1.1, HTTP/2자체 프로토콜 (ws://)
자동 재연결기본 지원직접 구현 필요
이벤트 ID지원 (Last-Event-ID)미지원
프록시 친화성높음낮음
인증제한적유연함

SSE 연결의 상세 구조

HTTP 헤더와 연결 수립

SSE 연결 시 실제로 주고받는 HTTP 헤더를 살펴보겠습니다:

# 클라이언트 요청
GET /api/sse/stream HTTP/1.1
Accept: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

# 서버 응답
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
X-Accel-Buffering: no

메시지 포맷과 이벤트 스트림

SSE 메시지는 특정 형식을 따릅니다:

// 서버 측 구현 (Node.js + Express)
app.get("/api/sse/stream", (req, res) => {
  // SSE 헤더 설정
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
    "X-Accel-Buffering": "no", // Nginx 버퍼링 비활성화
  });

  // 초기 연결 확인
  res.write(":ok\n\n");

  // 데이터 전송
  const sendEvent = (data: any, eventType?: string) => {
    if (eventType) {
      res.write(`event: ${eventType}\n`);
    }
    res.write(`id: ${Date.now()}\n`);
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  };

  // 주기적 하트비트
  const heartbeat = setInterval(() => {
    res.write(":heartbeat\n\n");
  }, 30000);

  // 클라이언트 연결 종료 처리
  req.on("close", () => {
    clearInterval(heartbeat);
    console.log("SSE 연결 종료");
  });
});

재연결 메커니즘

SSE는 연결이 끊어지면 자동으로 재연결을 시도합니다:

class RobustSSEConnection {
  constructor(url, options = {}) {
    this.url = url;
    this.lastEventId = null;
    this.reconnectInterval = options.reconnectInterval || 3000;
    this.maxRetries = options.maxRetries || 5;
    this.retryCount = 0;

    this.connect();
  }

  connect() {
    this.eventSource = new EventSource(this.url);

    this.eventSource.onopen = () => {
      console.log("SSE 연결 성공");
      this.retryCount = 0; // 재연결 카운터 리셋
    };

    this.eventSource.onmessage = (event) => {
      this.lastEventId = event.lastEventId;
      this.handleMessage(event);
    };

    this.eventSource.onerror = (error) => {
      this.eventSource.close();

      if (this.retryCount < this.maxRetries) {
        this.retryCount++;
        console.log(`재연결 시도 ${this.retryCount}/${this.maxRetries}`);

        setTimeout(() => {
          this.connect();
        }, this.reconnectInterval * this.retryCount);
      }
    };
  }

  handleMessage(event) {
    // 메시지 처리 로직
    console.log("받은 메시지:", event.data);
  }
}

SSE와 인증: 왜 제한적인가?

EventSource API의 한계

SSE에서 인증이 제한적인 이유는 브라우저의 EventSource API 설계에 있습니다. 하지만 이는 단순한 구현 실수가 아니라, 의도적인 설계 철학에서 비롯됩니다.

왜 커스텀 헤더를 지원하지 않을까?

WHATWG HTML 스펙 작성자들의 공식 입장을 살펴보면:

"이 기능은 fetch()로 충분히 구현할 수 있다. 3명 정도에게서만 이 요청을 들었는데, 스펙을 수정할 만큼 충분하지 않다"
— Anne van Kesteren, WHATWG HTML 스펙 기여자

설계 철학: "한 가지 일을 잘하자"

EventSource는 의도적으로 단순하게 설계되었습니다:

  1. GET 요청만 지원 (POST, PUT 등 불가)
  2. 쿠키 기반 인증만 지원
  3. 커스텀 헤더 불가
  4. 단순한 스트리밍에 최적화
// ❌ EventSource는 헤더 설정을 지원하지 않음
const eventSource = new EventSource("/api/sse/stream", {
  headers: {
    Authorization: "Bearer token123", // 불가능!
  },
});

// ✅ 쿠키는 자동으로 포함됨
document.cookie = "auth-token=token123; path=/";
const eventSource = new EventSource("/api/sse/stream"); // 쿠키 자동 전송

보안과 단순성의 트레이드오프

이러한 제한은 몇 가지 보안상 이점을 제공합니다:

  • 헤더 인젝션 공격 방지
  • 개발자 실수 최소화 (토큰을 URL에 노출하는 실수 방지)
  • 단순한 인증 모델로 복잡성 감소

하지만 현실적으로는 개발자들의 강한 반발을 불러일으켰습니다. WHATWG HTML 이슈에는 171개의 👍 반응이 달렸지만, 스펙 변경은 이루어지지 않았습니다.

현대적 해결책: Fetch 기반 Polyfill

스펙이 변경되지 않자, 커뮤니티에서는 Fetch API 기반 대안들을 개발했습니다:

// @microsoft/fetch-event-source 사용 예시
import { fetchEventSource } from "@microsoft/fetch-event-source";

fetchEventSource("/api/sse/stream", {
  method: "POST", // POST도 가능!
  headers: {
    Authorization: "Bearer token123", // 커스텀 헤더 지원
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ userId: "12345" }),

  onmessage(event) {
    console.log("받은 메시지:", event.data);
  },

  onerror(err) {
    console.error("연결 에러:", err);
  },
});

// fetch 직접 사용하는 방법
async function customSSE() {
  const response = await fetch("/api/sse/stream", {
    headers: { Authorization: "Bearer token123" },
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    // SSE 메시지 파싱 로직...
  }
}

주요 Fetch 기반 라이브러리들:

네이티브 EventSource 인증 패턴

패턴 1: 쿠키 기반 인증

// 서버 측 (Express + JWT)
app.get("/api/sse/stream", (req, res) => {
  // 쿠키에서 토큰 추출
  const token = req.cookies["auth-token"];

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const userId = decoded.userId;

    // SSE 연결 수립
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      // ...
    });

    // 사용자별 이벤트 스트림
    userEventEmitter.on(`user:${userId}`, (data) => {
      res.write(`data: ${JSON.stringify(data)}\n\n`);
    });
  } catch (err) {
    res.status(401).send("Unauthorized");
  }
});

패턴 2: 쿼리 파라미터 (보안 주의)

// 클라이언트
const token = localStorage.getItem("auth-token");
const eventSource = new EventSource(`/api/sse/stream?token=${token}`);

// 서버
app.get("/api/sse/stream", (req, res) => {
  const token = req.query.token;
  // 토큰 검증...

  // ⚠️ 주의: URL에 토큰이 노출되므로 보안상 위험
  // - 서버 로그에 기록될 수 있음
  // - 브라우저 히스토리에 남을 수 있음
  // - Referer 헤더로 유출될 수 있음
});

패턴 3: 세션 ID 방식

// 더 안전한 접근: 임시 세션 생성
app.post("/api/sse/auth", authenticateUser, (req, res) => {
  // 인증된 사용자를 위한 임시 SSE 세션 생성
  const sseSessionId = generateSecureRandomId();

  // Redis에 세션 저장 (짧은 TTL)
  redis.setex(
    `sse:${sseSessionId}`,
    60,
    JSON.stringify({
      userId: req.user.id,
      createdAt: Date.now(),
    })
  );

  res.json({ sseSessionId });
});

app.get("/api/sse/stream/:sessionId", async (req, res) => {
  const session = await redis.get(`sse:${req.params.sessionId}`);

  if (!session) {
    return res.status(401).send("Invalid session");
  }

  // SSE 연결 수립
  // ...
});

실무 경험: 작업 상태 실시간 업데이트

Use Case: AI 작업 진행 상태

Unschedule AI에서 구현한 실시간 작업 상태 업데이트 시스템:

interface TaskProgress {
  taskId: string;
  status: "pending" | "processing" | "completed" | "failed";
  progress: number; // 0-100
  message: string;
  timestamp: number;
}

class TaskProgressStream {
  private clients: Map<string, Response> = new Map();

  addClient(userId: string, res: Response) {
    // SSE 헤더 설정
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    });

    this.clients.set(userId, res);

    // 연결 종료 처리
    res.on("close", () => {
      this.clients.delete(userId);
    });
  }

  sendProgress(userId: string, progress: TaskProgress) {
    const client = this.clients.get(userId);
    if (!client) return;

    // 이벤트 타입별 전송
    client.write(`event: task-progress\n`);
    client.write(`id: ${progress.timestamp}\n`);
    client.write(`data: ${JSON.stringify(progress)}\n\n`);

    // 작업 완료 시 특별 이벤트
    if (progress.status === "completed") {
      client.write(`event: task-complete\n`);
      client.write(`data: ${JSON.stringify({ taskId: progress.taskId })}\n\n`);
    }
  }
}

// 실제 사용
const progressStream = new TaskProgressStream();

// AI 작업 처리 중
async function processAITask(taskId: string, userId: string) {
  // 진행 상황 업데이트
  progressStream.sendProgress(userId, {
    taskId,
    status: "processing",
    progress: 0,
    message: "데이터 준비 중...",
    timestamp: Date.now(),
  });

  // 작업 진행
  for (let i = 0; i <= 100; i += 10) {
    await doSomeWork();

    progressStream.sendProgress(userId, {
      taskId,
      status: "processing",
      progress: i,
      message: `처리 중... ${i}%`,
      timestamp: Date.now(),
    });
  }

  // 완료
  progressStream.sendProgress(userId, {
    taskId,
    status: "completed",
    progress: 100,
    message: "작업 완료!",
    timestamp: Date.now(),
  });
}

클라이언트 구현 (React)

import { useEffect, useState } from "react";

interface TaskProgress {
  taskId: string;
  status: string;
  progress: number;
  message: string;
}

function useTaskProgress(taskId: string) {
  const [progress, setProgress] = useState<TaskProgress | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const eventSource = new EventSource(`/api/sse/task/${taskId}`);

    eventSource.addEventListener("task-progress", (event) => {
      const data = JSON.parse(event.data);
      setProgress(data);
    });

    eventSource.addEventListener("task-complete", (event) => {
      const data = JSON.parse(event.data);
      console.log("작업 완료:", data.taskId);
      eventSource.close();
    });

    eventSource.onerror = (error) => {
      console.error("SSE 오류:", error);
      setError("연결이 끊어졌습니다");
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, [taskId]);

  return { progress, error };
}

// 컴포넌트에서 사용
function TaskProgressBar({ taskId }: { taskId: string }) {
  const { progress, error } = useTaskProgress(taskId);

  if (error) {
    return <div className="error">{error}</div>;
  }

  if (!progress) {
    return <div>연결 중...</div>;
  }

  return (
    <div className="task-progress">
      <div className="progress-bar">
        <div
          className="progress-fill"
          style={{ width: `${progress.progress}%` }}
        />
      </div>
      <p>{progress.message}</p>
    </div>
  );
}

SSE vs 대안 기술

언제 SSE를 선택해야 하는가?

SSE가 적합한 경우:

  • 서버에서 클라이언트로의 단방향 통신만 필요
  • HTTP 인프라를 그대로 활용하고 싶을 때
  • 자동 재연결이 중요한 경우
  • 프록시/로드밸런서 환경에서 안정적인 동작이 필요

WebSocket이 더 나은 경우:

  • 양방향 실시간 통신이 필요
  • 바이너리 데이터 전송
  • 더 낮은 레이턴시가 중요
  • 복잡한 인증 메커니즘이 필요

HTTP/2와 SSE

HTTP/2에서 SSE를 사용하면 추가적인 이점이 있습니다:

// HTTP/2 Server Push와 SSE 결합
app.get("/api/sse/stream", (req, res) => {
  // HTTP/2 확인
  if (req.httpVersion === "2.0") {
    // 멀티플렉싱 활용 - 여러 스트림을 하나의 연결로
    res.stream.pushAllowed = true;

    // 우선순위 설정
    res.stream.priority({
      weight: 128,
      exclusive: false,
    });
  }

  // SSE 스트림 시작
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
  });

  // ...
});

마무리

SSE는 단순해 보이지만, 프로덕션 환경에서 안정적으로 운영하려면 고려해야 할 사항이 많습니다. 특히 인증 문제는 EventSource API의 한계로 인해 창의적인 해결책이 필요합니다.

제 경험상 SSE는 다음과 같은 상황에서 특히 유용했습니다:

  • 서버 주도의 실시간 알림
  • 작업 진행 상태 업데이트
  • 라이브 피드나 대시보드
  • 프록시 환경에서의 안정적인 스트리밍

WebSocket이 더 강력한 기능을 제공하지만, SSE의 단순함과 HTTP 친화적인 특성은 많은 경우에 충분하고 오히려 더 나은 선택이 될 수 있습니다.

참고 자료

공식 문서

기술적 비교

EventSource API 설계 철학

현대적 대안 라이브러리


이 글이 도움이 되었다면, GitHub에서 ⭐️를 눌러주세요!