What the realtime layer is for
Swappr has two delivery channels for chat:- REST (send-message, list-messages, mark-read, etc.) — request-response, works everywhere, the canonical history-of-record.
- WebSocket (this page) — Socket.IO bi-directional events for low-latency send, live receipt of new messages, typing indicators, and read receipts.
apps/realtime) deployed alongside the REST API. It scales horizontally via the Socket.IO Redis adapter so a chat:message:new emitted on one instance is delivered to a recipient connected to a different instance.
Connection lifecycle
Step 1 — fetch a ticket
POST /api/v1/auth/socket-ticket requires a Bearer access token and returns a single-use ticket valid for 60 seconds. The endpoint is documented under Auth — socket-ticket. Tickets are stored in Redis with SET ... EX 60 NX so the API never needs to consult Mongo on each socket connect.
Step 2 — connect
apps/realtime/src/auth.ts calls TicketConsumer.consume(ticket) — a Redis GETDEL in production — which is atomic: the ticket is consumed and deleted in one round-trip, so a replay attack with the same ticket fails. On success it attaches socket.data.userId and auto-joins user:<userId>.
If the ticket is missing, malformed, expired, or already-consumed, the middleware calls next(new Error('UNAUTHENTICATED')) and Socket.IO closes the underlying transport. The client sees a connect_error event.
Step 3 — open conversations
After connect, the socket is in exactly one room:user:<userId> (its personal room, used by future direct notifications). To receive chat:message:new for a conversation, the client MUST emit chat:open { conversationId } for that conversation. The server validates membership via ChatEventsPort.isParticipant and joins the socket to conversation:<id> iff the user is a participant. Non-participants are silently ignored (no error event) — there’s nothing to recover from.
The client should emit one chat:open per conversation it has open in UI (a single conversation screen typically opens one; an inbox screen may open zero or all of them depending on product choices — see reconnect strategy below).
Room model
Both prefixes live in
apps/realtime/src/rooms.ts so they cannot drift between the auth middleware, the message handler, and any future broadcasters.
All sockets connect to the root namespace (/). Phase 4 does not use multiple namespaces; the room model is sufficient for isolation.
Event catalog
Every event payload is documented below with its exact field types (matchingapps/realtime/src/events.ts), the ack shape (where applicable), the broadcast target, and the reasons the server may reject.
chat:open (client → server)
Subscribe the socket to a conversation’s broadcast room. The client MUST emit this for each conversation it wants live updates on. A socket that never emits chat:open only sees personal events on user:<userId>.
Ack: none. The client cannot tell directly whether the join succeeded — but it is safe to emit
chat:open redundantly (joining a room you’re already in is a no-op).
Server behaviour:
- Calls
chatEvents.isParticipant(conversationId, userId). - On
true:socket.join('conversation:<conversationId>'). - On
falseor thrown error: silently ignored (no ack, no error event). Probing for valid conversation ids viachat:openis therefore not a useful side channel.
chat:message:send (client → server, with ack)
Insert a new message into the conversation. This is the WebSocket mirror of POST /chat/conversations/:id/messages; both transports hit the same messageService.sendMessage. See REST ↔ WS parity.
Ack shape:
Broadcast:
- On
ok: trueANDdeduped: false: server emitschat:message:newtoconversation:<id>(every socket joined to that room, including the sender’s own socket — so a single client with multiple open tabs/devices sees the message land everywhere). - On
ok: trueANDdeduped: true: NO broadcast (the receivers already got the original). - On
ok: false: NO broadcast.
chat:message:new (server → room broadcast)
Emitted to every socket in conversation:<conversationId> when a message has been successfully inserted (deduped: false).
The sender’s socket ALSO receives
chat:message:new for messages they sent themselves — Socket.IO’s .to(room).emit(...) includes the sender by default. Use the ack to dedup against your optimistic local row, then ignore the matching broadcast OR use the broadcast to reconcile (both patterns work). Do NOT exclude the sender server-side — multi-device users rely on the broadcast to keep tabs in sync.chat:read (client → server, with ack)
Mark messages read up to a cursor. Mirror of POST /chat/conversations/:id/read.
Ack shape:
Broadcast: on
ok: true, server emits chat:message:read to conversation:<id> (yes, including the caller — same multi-device reasoning as chat:message:new).
chat:message:read (server → room broadcast)
Emitted after a successful chat:read. The sender’s UI uses this to update its read-receipt indicators in real time.
chat:typing:start / chat:typing:stop (client → server)
Debounced typing notifications. Phase 4 does NOT validate that the caller is a participant of the conversation — typing is purely cosmetic and the cost of a stricter check exceeds the abuse surface (the worst case is a non-participant sending a start event to a room they aren’t in, which is a no-op since the broadcast only reaches sockets in that room).
Ack: none — fire-and-forget.
Broadcast: server emits
chat:typing with phase: 'start' or phase: 'stop' to conversation:<id>, excluding the sender’s own socket (via socket.to(room).emit(...)). The typist doesn’t need to see their own typing indicator.
The client convention is:
- Emit
chat:typing:startwhen the user starts typing (e.g. first keystroke). - Emit
chat:typing:stopafter 3s of inactivity, when the user sends, OR when the screen loses focus. - Do not spam
chat:typing:starton every keystroke — the server forwards each one and the recipient’s UI will flicker.
chat:typing (server → room broadcast)
At-least-once delivery and dedup
The realtime layer is at-least-once, not exactly-once. A client retry on a flaky network can produce duplicatechat:message:send emits with the same clientMessageId. The server’s job is to make those retries safe — the contract is:
- A
(senderId, clientMessageId)unique index onmessagesmakes the second insert E11000. - The service’s
findByClientIdfast-path returns the existing row without a re-insert. - The race-recovery catch on E11000 re-reads after a duplicate-key error.
- The ack reports
deduped: trueso the client knows this was a retry, not a fresh send. - No
chat:message:newis broadcast on the dedup path — the original send already broadcast it, and replaying would cause UIs to render the same message twice.
Dedup race diagram
Two parallel retries firing at once can both miss thefindByClientId fast path. The catch on E11000 covers that case: the loser of the insert race re-reads and returns the winner’s row with deduped: true. No combination of retries can ever produce two messages rows or two chat:message:new broadcasts.
Client requirements
For the contract to hold, the client MUST:- Generate
clientMessageIdBEFORE the first attempt (ULID or UUID recommended). - Reuse the SAME
clientMessageIdon every retry of the same logical message. - Treat
ack.deduped === trueas success — the message landed (on the first attempt) and the broadcast already fired (other recipients have it). - NOT increment the optimistic row twice: when the ack arrives with
deduped: true, the local optimistic UI is already in the correct state.
Full send-flow sequence
REST and WS parity
BACKEND_PLAN §8.4 mandates that REST POST /chat/conversations/:id/messages and the WebSocket chat:message:send event hit the same messageService.sendMessage method. Consequences:
Take-aways:
- A client can send via REST and receive the broadcast via WebSocket — works.
- A client can send via WebSocket and read history via REST — works.
- Error codes are the same: a REST
403 CONVERSATION_BLOCKEDcorresponds to a WS ack withreason: 'CONVERSATION_BLOCKED'. - Mobile clients with intermittent connectivity should send via REST (which queues nicely at the OS layer) and use WebSocket purely for receiving live broadcasts. Mobile clients with a stable connection can send via either.
Ack error reasons
The server returns{ ok: false, reason: '...' } on failure. Two categories:
Payload validation (server-side guard rejection — no service call)
These are returned synchronously from the socket handler before any service is touched. They indicate a client bug — fix the payload, don’t retry.Service-level rejection (passed through from AppError.code)
These mirror the REST error catalog exactly — same conditions, same recovery paths. See Errors for the full catalog.
The client should surface ack failures to the UI like any other error — there is no “retry the socket event automatically” pattern except for the
clientMessageId dedup case described above.
Reconnect strategy
Sockets disconnect — flaky mobile networks, OS suspension, server deploys. The client MUST:-
Treat the ticket as exhausted on every reconnect. Tickets are single-use; the original was consumed at first connect. The reconnect path MUST fetch a fresh ticket via
POST /api/v1/auth/socket-ticketbefore re-emittingio({ auth: { ticket } }). Trying to reconnect with the old ticket fails withconnect_error('UNAUTHENTICATED'). -
Re-emit
chat:openfor every conversation it had open before the disconnect. Rooms are NOT remembered across socket lifecycles — a fresh socket starts in onlyuser:<userId>. The client should keep a local list of “currently open conversation ids” and emitchat:openfor each one afterconnect. -
Re-fetch history via REST. During the disconnect window, messages may have been sent that the client never saw via
chat:message:new. After reconnect, the client should call list-messages for each open conversation to catch up. The REST endpoint is the canonical history-of-record; the socket is the live channel.
reconnect_attempt handler that fetches a fresh ticket before each attempt:
Out-of-scope (intentionally)
Phase 4 deliberately does NOT ship the following — clients should not depend on them existing.- Per-conversation rate limiting on the socket transport. The REST send is documented to be subject to 60/min/user; the socket transport piggybacks on the same
messageServicebut the realtime layer does not yet wrap it in a rate limiter. Coming in Phase 5. - Delivered receipts (
chat:message:delivered). The data model has adeliveredTo[]field but Phase 4 does not yet populate it — the field is always[]. Receipts are emitted in Phase 5 once the push pipeline is wired (an APNs/FCM “delivered” callback flips it). - Edit / delete events (
chat:message:edited,chat:message:deleted). The data model haseditedAtanddeletedAtbut no API exposes them yet. - Presence (
user:online/user:offline). Socket.IO knows when a socket connects/disconnects but no broadcast fires today. Phase 5 may add this for the inbox UI. - Multiple namespaces. The MVP is single-tenant and uses the root namespace exclusively.
See also
- Send message — the REST mirror of
chat:message:send. - Mark conversation read — the REST mirror of
chat:read. - List messages — catch-up history; use after reconnect.
- Match → Conversation handshake — how a
conversation:<id>room gets created in the first place. - Socket ticket endpoint — how to get the
ticketused in theauthhandshake. - Errors — full code catalog; socket
reasonstrings map 1:1 to RESTcodestrings.