C.W.K.
Stream
Lesson 01 of 07 · published

Protocol 설계

~12 min · protocol, envelope, type-field

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

type + data envelope

WebSocket 이 opaque message stream 줘. 구조 추가는 네 일. 업계 dominant 패턴 — Slack, Discord, GraphQL-WS, 모든 chat 라이브러리 — 가 type string + data object 의 작은 JSON envelope. type field 가 어느 schema 의 data 인지 알려줘. 모든 게 이 단일 결정에서 떨어져 나와.

Type namespace

Dot-notation 써: chat.message, chat.typing, user.joined, user.status, room.join, game.move. 첫 segment 가 domain; 두 번째가 동사나 event. sortable, greppable, 확장 자연스러움 유지.

Error 도 message

Error 응답이 그냥 다른 message: {type: 'error', code: 'rate_limited', message: '...', ref_id: 'xyz'}. 같은 envelope, 다른 schema. error 를 first-class 로 다뤄, 특별한 transport-level 개념으로 다루지 마.

Code

Protocol envelope 예시·json
// chat message
{
  "type": "chat.message",
  "data": {
    "room": "general",
    "text": "hello",
    "ts":   "2026-05-03T10:30:00Z"
  }
}

// system event
{
  "type": "user.joined",
  "data": { "user_id": "abc123", "username": "Alice" }
}

// error
{
  "type":    "error",
  "code":    "rate_limited",
  "message": "slow down — max 20 messages/sec",
  "ref_id":  "msg-xyz-123"
}
Type 별 서버 router·python
async def dispatch(ws, user, msg: dict):
    handlers = {
        'chat.message': handle_chat,
        'chat.typing':  handle_typing,
        'room.join':    handle_join,
        'room.leave':   handle_leave,
        'pong':         handle_pong,
    }
    fn = handlers.get(msg.get('type'))
    if fn is None:
        await ws.send_json({
            'type': 'error',
            'code': 'unknown_type',
            'message': f"unknown type: {msg.get('type')!r}",
        })
        return
    await fn(ws, user, msg.get('data', {}))

External links

Exercise

단순 chat 앱의 protocol 정의: 모든 message type 과 field 적어 (chat.message, chat.typing, user.joined, user.left, room.join, room.leave, error). AsyncAPI 3.0 문서로 적어. 코드 generate 안 해도 spec 적는 행위 자체가 빠진 field 잡아.

Progress

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

댓글 0

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

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