[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,114 +4,172 @@ title: WebSockets and Realtime
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-DEV-WEBSOCKETS, WebSocket, WebSockets, 실시간 통신, 양방향 통신, Socket.io, Full-duplex]
|
||||
aliases: [WebSockets, Realtime Communication, WS]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [API, WebSocket, Real-time, Communication, Event-Driven]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [websockets, realtime, low-latency, pubsub, full-duplex]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript / Go
|
||||
framework: Bun / uWebSockets.js / Centrifugo
|
||||
---
|
||||
|
||||
# [[WebSocket과 실시간 양방향 통신 (WebSockets & Real-time)]]
|
||||
# WebSockets and Realtime
|
||||
|
||||
## 1. 개요
|
||||
WebSocket은 단일 TCP 연결을 통해 클라이언트와 서버 간의 영구적이고 실시간인 양방향(Full-duplex) 통신 채널을 제공하는 프로토콜이다. 매번 연결을 맺고 끊는 오버헤드가 있는 HTTP와 달리, 한 번의 핸드셰이크 이후 연결을 유지하며 지연 시간을 최소화한 데이터 교환을 가능하게 한다.
|
||||
## 매 한 줄
|
||||
> **"매 single TCP connection over HTTP upgrade — 매 full-duplex, low-overhead binary/text framing 의 realtime 표준"**. 2011 RFC 6455, 2026 WebTransport (HTTP/3) 가 등장했지만 WS 는 여전히 ubiquitous. 매 chat, collaborative editing, live dashboards, gaming 의 backbone.
|
||||
|
||||
## 2. 주요 작동 원리
|
||||
- **핸드셰이크 (Handshake)**: 클라이언트가 HTTP 요청을 보내 서버에 프로토콜 전환(Upgrade: websocket)을 요청하고, 서버가 승인하면 연결이 성립됨.
|
||||
- **영구 연결 (Persistent Connection)**: 데이터 교환이 끝나도 연결이 닫히지 않고 유지되어, 추가적인 HTTP 헤더 전송 없이 메시지만 주고받음.
|
||||
- **양방향성 (Full-duplex)**: 서버가 클라이언트의 요청 없이도 데이터를 먼저 보낼 수 있으며(Server Push), 클라이언트와 서버가 동시에 메시지를 송수신 가능.
|
||||
- **프레임 기반 통신**: 데이터를 작은 프레임 단위로 나누어 전송하며, 텍스트(JSON 등)뿐만 아니라 바이너리 데이터도 효율적으로 처리.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 엔지니어링 가치
|
||||
- **초저지연(Low Latency) 달성**: HTTP 폴링(Polling)이나 롱 폴링(Long Polling) 방식에 비해 네트워크 부하와 지연 시간을 획기적으로 줄여 실시간성 확보.
|
||||
- **서버 리소스 효율화**: 반복적인 연결 생성 및 헤더 처리에 소모되는 CPU와 대역폭을 아끼고, 활성 연결 상태만 관리함으로써 효율적인 통신 지원.
|
||||
- **인터랙티브 경험 제공**: 채팅, 멀티플레이어 게임, 협업 도구(Google Docs 스타일), 금융 데이터 대시보드 등 즉각적인 반응이 필수적인 서비스 구현의 핵심 기술.
|
||||
### 매 Lifecycle
|
||||
1. HTTP `GET` + `Upgrade: websocket` + `Sec-WebSocket-Key`.
|
||||
2. Server 의 `101 Switching Protocols` + `Sec-WebSocket-Accept`.
|
||||
3. Frame-based (text=0x1, binary=0x2, ping=0x9, pong=0xA, close=0x8).
|
||||
4. Full-duplex 까지 매 connection 의 close.
|
||||
|
||||
## 4. 트레이드오프 및 주의사항
|
||||
- **연결 관리의 복잡성**: 수천, 수만 개의 동시 활성 연결을 유지하기 위해 서버의 메모리 자원 관리와 로드 밸런싱(Sticky Session 등) 전략이 중요함.
|
||||
- **상태 유지(Stateful) 서버**: 서버가 클라이언트의 상태를 계속 들고 있어야 하므로, 서버 확장(Scaling out) 시 Redis 등을 이용한 메시지 브로커 연동 필수.
|
||||
- **방화벽 및 프록시 이슈**: 일부 구형 방화벽이나 프록시 서버에서 WebSocket 프로토콜을 차단할 수 있으므로, HTTP/1.1 업그레이드 지원 여부 확인 필요.
|
||||
- **재연결 로직**: 네트워크 장애로 연결이 끊겼을 때 클라이언트 측에서의 자동 재연결(Backoff 등) 및 누락된 메시지 복구 로직 구현 필수.
|
||||
### 매 Scaling challenges
|
||||
- **Sticky session 또는 pub/sub fanout**: 매 connection 의 single node binding.
|
||||
- **Backpressure**: slow client → memory bloat. `bufferedAmount` watch.
|
||||
- **Reconnect + resume**: client state 의 server-side snapshot.
|
||||
- **Auth**: query token (logged in proxies) vs. first-message handshake (recommended).
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[API_Design_Principles]]: 실시간 통신을 위한 특수 목적 프로토콜.
|
||||
- [[Event-Driven_Architecture]]: 비동기 이벤트를 클라이언트에 실시간으로 전달하는 창구.
|
||||
- [[Nextjs_Framework]]: 서버 측에서 WebSocket 서버를 구축하거나 클라이언트에서 구독하는 환경.
|
||||
### 매 대안 매트릭스
|
||||
- **SSE**: server → client only, simpler, HTTP/2 multiplexed.
|
||||
- **WebTransport**: HTTP/3, datagrams + streams, 매 future.
|
||||
- **Long polling**: legacy fallback.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 지연 없는 실시간 데이터 교환을 통해 풍부한 사용자 상호작용과 기민한 시스템 반응성을 확보하기 위한 WebSocket 프로토콜 및 실시간 통신 표준 정립.
|
||||
### 매 응용
|
||||
1. Chat / collaborative docs (Yjs, Liveblocks).
|
||||
2. Trading / live odds / dashboards.
|
||||
3. Multiplayer game (low-tick) — 매 보통 UDP/WebTransport 가 더 좋음.
|
||||
4. AI streaming (token-by-token, 매 SSE 가 더 흔함).
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
## 💻 패턴
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Bun WebSocket server (high perf)
|
||||
```typescript
|
||||
Bun.serve<{ userId: string }>({
|
||||
port: 3000,
|
||||
fetch(req, server) {
|
||||
const userId = verifyJWT(new URL(req.url).searchParams.get('token'));
|
||||
if (!userId) return new Response('unauth', { status: 401 });
|
||||
if (server.upgrade(req, { data: { userId } })) return;
|
||||
return new Response('expected ws', { status: 400 });
|
||||
},
|
||||
websocket: {
|
||||
open(ws) { ws.subscribe(`user:${ws.data.userId}`); },
|
||||
message(ws, msg) {
|
||||
const { room, body } = JSON.parse(msg as string);
|
||||
ws.publish(`room:${room}`, JSON.stringify({ from: ws.data.userId, body }));
|
||||
},
|
||||
close(ws) { /* cleanup */ },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Client with auto-reconnect
|
||||
```typescript
|
||||
class RealtimeClient {
|
||||
private ws?: WebSocket;
|
||||
private retry = 0;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
connect() {
|
||||
this.ws = new WebSocket(`wss://api/rt?token=${this.token}`);
|
||||
this.ws.onopen = () => { this.retry = 0; this.flush(); };
|
||||
this.ws.onmessage = (e) => this.dispatch(JSON.parse(e.data));
|
||||
this.ws.onclose = () => {
|
||||
const delay = Math.min(30_000, 2 ** this.retry++ * 1000) + Math.random() * 500;
|
||||
setTimeout(() => this.connect(), delay);
|
||||
};
|
||||
}
|
||||
send(obj: unknown) {
|
||||
if (this.ws?.readyState === 1) this.ws.send(JSON.stringify(obj));
|
||||
else this.queue.push(obj);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Redis pub/sub fanout (multi-node)
|
||||
```typescript
|
||||
const sub = redis.duplicate();
|
||||
await sub.subscribe('room:*', (msg, channel) => {
|
||||
const room = channel.split(':')[1];
|
||||
server.publish(`room:${room}`, msg); // 매 local connections 만
|
||||
});
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// publisher (any node)
|
||||
await redis.publish(`room:${room}`, JSON.stringify(payload));
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Heartbeat + dead connection detection
|
||||
```typescript
|
||||
setInterval(() => {
|
||||
for (const ws of server.publishToSubscribers) {
|
||||
if (Date.now() - ws.data.lastPong > 60_000) ws.close(1011, 'stale');
|
||||
else ws.ping();
|
||||
}
|
||||
}, 30_000);
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Yjs collaborative doc
|
||||
```typescript
|
||||
import * as Y from 'yjs';
|
||||
import { WebsocketProvider } from 'y-websocket';
|
||||
|
||||
const doc = new Y.Doc();
|
||||
const provider = new WebsocketProvider('wss://yjs.example/sync', `doc:${docId}`, doc);
|
||||
const text = doc.getText('content');
|
||||
text.observe(e => render(text.toString()));
|
||||
text.insert(0, 'Hello'); // 매 CRDT-merged 매 모든 client
|
||||
```
|
||||
|
||||
### Backpressure
|
||||
```typescript
|
||||
ws.send(payload);
|
||||
if (ws.bufferedAmount > 1_000_000) {
|
||||
ws.close(1013, 'backpressure'); // drop slow client
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Server → client only stream | SSE (simpler, HTTP/2) |
|
||||
| Bidirectional, < 10k conn / node | WebSocket on Bun/Node |
|
||||
| 100k+ conn / node | uWebSockets.js, Go (gobwas/ws), Rust |
|
||||
| Managed pub/sub | Centrifugo, Ably, Pusher |
|
||||
| Collab editing | Yjs / Automerge over WS |
|
||||
| Low-latency game | WebTransport (HTTP/3) |
|
||||
|
||||
**기본값**: WSS + JWT in first message + Redis pub/sub fanout + 30s heartbeat + exponential reconnect.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Realtime-Communication]] · [[HTTP]]
|
||||
- 변형: [[Server-Sent-Events]] · [[WebTransport]] · [[Long-Polling]]
|
||||
- 응용: [[Chat-System]] · [[Collaborative-Editing]] · [[Live-Dashboard]]
|
||||
- Adjacent: [[Redis-PubSub]] · [[CRDT]] · [[WebHooks_and_Notifications]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: server scaffolding, reconnect logic, fanout pattern.
|
||||
**언제 X**: 매 production-scale tuning (kernel, ulimit, TLS termination) — empirical.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No heartbeat**: 매 NAT/proxy 의 silent close → zombie connections.
|
||||
- **Token in URL query**: 매 server log 의 leak. Use first-message handshake.
|
||||
- **Synchronous DB call in onmessage**: blocks event loop.
|
||||
- **Per-connection in-memory state w/o backup**: 매 node restart → data loss.
|
||||
- **No backpressure check**: slow client OOMs server.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (RFC 6455, Bun/uWS docs, Yjs/Centrifugo prod patterns).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Bun WS + reconnect + Redis fanout 패턴 |
|
||||
|
||||
Reference in New Issue
Block a user