Video in progress
You need request/response (RPC) style operations over WebSocket, for example "add to cart" and a reply. How do you design the protocol?
The client gives each request a correlation ID, the server returns the response with that ID, and the client keeps pending requests in a map with a timeout. On top of that you need an error format, an idempotency key (for resending after a drop) and an envelope that tells requests apart from events.
📖 Answer
In WebSocket there's no notion of a "response": the client sends a message, and then whatever arrives on the stream arrives. Responses to three parallel requests can come back in a mixed order. So the envelope exists from day one:
{"kind":"req","id":"c-1842","op":"cart.add","idem":"7f3e...","body":{"sku":"A1","qty":2}}
{"kind":"res","id":"c-1842","ok":true,"body":{"cartSize":3}}
{"kind":"res","id":"c-1843","ok":false,"error":{"code":"OUT_OF_STOCK"}}
{"kind":"evt","type":"price-changed","body":{...}}
On the client side:
const pending = new Map();
function call(op, body, timeoutMs = 10000) {
const id = `c-${++seq}`;
return new Promise((resolve, reject) => {
const t = setTimeout(() => { pending.delete(id); reject(new Error('timeout')); }, timeoutMs);
pending.set(id, { resolve, reject, t });
ws.send(JSON.stringify({ kind: 'req', id, op, idem: crypto.randomUUID(), body }));
});
}
The hardest question is a drop. The request went out, the connection dropped before the response arrived. Did the server execute it? You don't know. So:
- every mutation carries an
idemkey, the server stores the result under that key for a while, and when the request comes again it returns the old response without executing it; - on a drop the client marks everything in
pendingas "unknown" and resends it with the sameidemonce it reconnects.
The timeout works both ways too: the client has a wait limit, and the server may refuse to execute a request that arrives too late (say, older than 30 s).
STOMP doesn't give this ready-made, but you can build it with the same idea: the client does SEND with a request-id header, and the server puts that ID on the reply with @SendToUser(broadcast = false). For errors, @MessageExceptionHandler.
And the question itself: do these operations have to go over WebSocket at all? Leaving mutations on plain REST and using WebSocket only for events is often simpler: in HTTP, status codes, retries, tracing and rate limiting are all ready. I move RPC onto WebSocket only when latency really matters (games, collaborative editing).
Sign up to mark studied questions and save your progress.