HTTP


HTTP 1.0

  • Open TCP connection
  • Send GET Request
  • Receive Response
  • Close TCP connection

TCP 3-way handshake expensive

HTTP 1.1

  • Open TCP connection
  • Send GET Request
  • Receive Response
  • Close TCP connection if I want to

WebSockets


  • Open connection
  • GET 1.1 UPGRADE
  • 101 - Switching Protocols
  • No longer HTTP
  • Bidirectional no order

Server Sent Events


  • Open connection
  • Send GET text/event-stream
  • Respond : Content-Type = text/event-stream / Transfer-Encoding chunked
  • keep sending more chunks
  • Server or Client can close connection

SSE Example


SSE use cases

  • Live Feed
  • Showing client progress
  • Logging

Coding

res.setHeader("Content-Type", "text/event-stream")
res.write("data: " + "hello!\n\n")

SSE Pros and Cons


Pros

  • Lightweight
    • packets are small because there are no headers unlike the websocket
  • HTTP & HTTP/2 compatible
  • Firewall friendly (standard)

Cons

  • Proxying is tricky
  • L7 L/B challenging (timeouts)
    • client cannot keep connection alive
  • Stateful, difficult to horizontally scale

Do I have to use SSE?

  • WebSockets
    • sse is limited only purely server sent events
    • overhead to HTTP there are its own protocol headers
  • Long polling

์‹ค์‹œ๊ฐ„ ๊ธฐ์ˆ 


Polling

  • ํŠน์ • ์ฃผ๊ธฐ๋กœ ์š”์ฒญ์„ ๋ณด๋‚ธ๋‹ค.
  • ์„œ๋ฒ„์— ๋ณ€ํ™”๊ฐ€ ์—†์–ด๋„ ๊ณ„์†ํ•ด์„œ ์š”์ฒญ์„ ๋ณด๋‚ด๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํ•„์š”ํ•œ ํ†ต์‹ ์ด ๋งŽ์ด ์ด๋ฃจ์–ด์ง„๋‹ค.
  • ๊ธฐ์กด ์šฐ๋ฆฌ ์„œ๋ฒ„๋Š” 0.5์ดˆ ๊ฐ„๊ฒฉ์œผ๋กœ ์„œ๋ฒ„์—๊ฒŒ ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ์žˆ์—ˆ๋‹ค.

Long Polling

  • ์„œ๋ฒ„์—์„œ ์ ‘์†์„ ์—ด์–ด๋‘๊ณ  ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ ์‘๋‹ต์„ ๋ณด๋‚ธ๋‹ค.
  • ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ฆ‰์‹œ ์‘๋‹ต์ด ์ด๋ฃจ์–ด์ ธ ์‹ค์‹œ๊ฐ„ ์„ฑ๋Šฅ์ด ๋›ฐ์–ด๋‚˜๋‹ค.
  • ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋งŽ์€ ๊ฒฝ์šฐ ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ ๋™์‹œ์— Response ๋ฅผ ๋ณด๋‚ด๊ณ  Request ๋ฅผ ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ์ˆœ๊ฐ„์ ์œผ๋กœ ํ์— ๋งŽ์€ ์–‘์˜ ๋ช…๋ น์ด ์Œ“์—ฌ ์„œ๋ฒ„์— ๋ฌด๋ฆฌ๊ฐ€ ๊ฐ„๋‹ค.

Web Socket

  • ์„œ๋ฒ„์™€ ํด๋ผ์ด์–ธํŠธ๊ฐ€ TCP connection ์„ ์œ ์ง€ํ•˜์—ฌ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›๋Š” ์–‘๋ฐฉํ–ฅ ํ†ต์‹ ์ด๋‹ค.

Server Sent Event

  • ์„œ๋ฒ„์™€ ํด๋ผ์ด์–ธํŠธ๊ฐ€ TCP connection ์„ ์œ ์ง€ํ•˜์—ฌ ์„œ๋ฒ„ โ†’ ํด๋ผ์ด์–ธํŠธ ๋ฐฉํ–ฅ์œผ๋กœ๋งŒ ํ†ต์‹ ํ•˜๋Š” ๋‹จ๋ฐฉํ–ฅ ํ†ต์‹ ์ด๋‹ค.
  • Web Socket ์€ ๊ธˆ์ง€ ๊ธฐ์ˆ ์ด์—ˆ๊ณ  SSE ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์–ป์–ด๋‚ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋ผ ํŒ๋‹จํ•˜์—ฌ SSE ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

Spring SseEmitter


Polling

NginX ์„ค์ •

server {
    ...

    location / {
        ...

        # SSE through NginX
        proxy_set_header Connection '';
        proxy_http_version 1.1;
        chunked_transfer_encoding off;
        proxy_buffering off;
        proxy_cache off;

        ...
    }

    ...
}

ํ˜„์žฌ ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ์—์„  NginX ๋ฅผ ํ†ตํ•ด ๋ฐฑ์—”๋“œ ์„œ๋ฒ„์™€ ํ†ต์‹ ํ•˜๊ณ  ์žˆ๋‹ค.

SSE ๋ฅผ NginX ๋ฅผ ํ†ตํ•ด ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ๋ณด๋‚ด์ฃผ๊ธฐ ์œ„ํ•ด์„  location ๋‚ด๋ถ€์— ์œ„์™€ ๊ฐ™์€ ์„ค์ •์ด ์ถ”๊ฐ€๋˜์–ด์•ผ ํ•œ๋‹ค.

References