# Designing Your Message Protocol — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-message-protocol

> Define typed JSON envelopes with ids, acknowledgements and timeouts on top of raw WebSocket messages.

## WebSocket gives you a pipe, not a protocol

A WebSocket delivers ordered messages, nothing more. It has no URLs, no methods, no status codes and no way to match a reply to a request. So every real app defines an **envelope**, usually JSON such as `{ "type": "chat", "id": 7, "payload": {...} }`. The `type` field routes the message to a handler, much like a URL route. An `id` on client requests lets the server answer with `{ "replyTo": 7, ... }`, so the client can resolve the right promise; this is how you build **acknowledgements** ("your message was saved") and request/response calls over a socket. Server pushes often carry a **sequence number** per room or stream so clients can detect gaps and resume after reconnecting. Add a `v` (version) field or negotiate a subprotocol early, because old mobile app builds will keep talking to your server for months. Keep payloads small; send ids and let the client fetch large objects over HTTP.

## From raw message to the right audience

Every incoming message is parsed into an envelope, routed by type, and its effect is broadcast to the clients who care.

![Four connected stages in order: client sends message, envelope is parsed, router picks a handler by type, result is broadcast to a room.](assets/figures/realtime-web/section-6-map.svg) — Figure 6.1: client message -> envelope -> type router -> room broadcast

## Request/acknowledgement over a socket

Each request gets an id and a pending promise with a timeout. When a reply with matching `replyTo` arrives, the promise resolves. A fake socket stands in for the server so the example runs on its own.

```js
let nextId = 1;
const pending = new Map(); // id -> { resolve, timer }

function request(socket, type, payload, timeoutMs = 5000) {
  const id = nextId++;
  socket.send(JSON.stringify({ id, type, payload }));
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      pending.delete(id);
      reject(new Error(`${type} #${id} timed out`));
    }, timeoutMs);
    pending.set(id, { resolve, timer });
  });
}

function onMessage(raw) {
  const msg = JSON.parse(raw);
  const waiter = pending.get(msg.replyTo);
  if (!waiter) return; // late or unknown reply: ignore
  clearTimeout(waiter.timer);
  pending.delete(msg.replyTo);
  waiter.resolve(msg.payload);
}

// Fake socket that replies like a server would, 10 ms later.
const fakeSocket = {
  send(text) {
    const { id, payload } = JSON.parse(text);
    const reply = { replyTo: id, payload: { saved: payload.text } };
    setTimeout(() => onMessage(JSON.stringify(reply)), 10);
  },
};

console.log(await request(fakeSocket, 'chat', { text: 'see you at 5' }));
console.log(await request(fakeSocket, 'chat', { text: 'bring notes' }));
```

Output:

```
{ saved: 'see you at 5' }
{ saved: 'bring notes' }
```

## Always time out pending requests

If the connection drops, replies never come. Without a timeout, the `pending` map grows forever and UI spinners never stop. Reject on timeout and on `close`, and let the caller decide whether to retry.

**Quiz:** Why does a request sent over a WebSocket usually carry an `id` field?

- [ ] The WebSocket protocol rejects messages without ids
- [ ] Browsers use it to order frames
- [ ] It is required for masking
- [x] So the client can match the server's reply to the request that caused it

*Answer:* So the client can match the server's reply to the request that caused it. Messages on a socket are not paired like HTTP request/response. An id echoed back as `replyTo` lets the client resolve the correct pending request.
