Per-user WebSocket hub

You build a per-user WebSocket hub that authenticates /v1/ws connections and queues messages for connected users. A full send buffer drops messages without blocking Send.

Ticket

Build the internal/ws hub and the authenticated GET /v1/ws handler. The hub keeps one WebSocket connection per user and lets the API queue messages for that user's connection.

The tests in internal/ws call these declarations directly:

go
func NewHub() *Hub
func (h *Hub) Serve(w http.ResponseWriter, r *http.Request, userID int64)
func (h *Hub) Send(userID int64, msg []byte) bool
func (h *Hub) Connected(userID int64) bool
func Handler(hub *Hub, verify func(token string) (int64, error)) http.Handler

A slow phone must not block other parts of the API from sending messages. The next module adds Redis pub/sub fan-out so an event can reach the api instance holding the user's connection.

Acceptance criteria

  • With 50 connected users, calling Send for each user with []byte("hello") queues a message that the corresponding client receives.
  • Calling Send(999, []byte("x")) when user 999 has no connection returns false.
  • Sending 400 messages of 256 KiB each to a client that never reads finishes in less than 2 seconds. At least one send returns false because the bounded buffer is full.
  • When user 7 closes the client connection, the hub removes that connection within 3 seconds. Connected(7) returns false, and Send(7, []byte("x")) returns false.
  • Eight concurrent senders can send to user IDs 0 through 9 while five rounds of ten connections are opened and closed. The operations complete without panics or data races.
  • After 20 connections close, the goroutine count returns to no more than four above its starting count within 5 seconds.
  • When a second connection registers for user 5, the first connection closes. The replacement remains registered after 100 milliseconds, and Send(5, []byte("to-second")) delivers exactly to-second to the second client.
  • After ten successive replacements for user 9, closing the final connection removes the user from the hub. The goroutine count returns to no more than four above its starting count within 5 seconds.
  • The handler returns HTTP 401 for a missing token at /, an empty token at /?token=, and an invalid token at /?token=bad.
  • When the handler verifies the valid token good and obtains user ID 77, the WebSocket connection registers user 77 in the hub within 2 seconds.
  • Dialling /v1/ws against the running API without a token fails with HTTP 401.

Constraints

  • Keep the hub implementation in backend/internal/ws/hub.go and the HTTP handler in backend/internal/ws/handler.go.
  • Send must never block while attempting to deliver a message, and it must not perform a network write.
  • Only the connection lifecycle owner may close its send channel, and it must close that channel exactly once.
  • Mount GET /v1/ws in backend/cmd/api/main.go, outside the bearer-auth group, using the Week 3 access-token verification function as verify.

Design direction

Keep the connection registry and its synchronization in internal/ws/hub.go. Give each connection its own Go channel with a bounded send buffer, plus the state needed to coordinate its reader and writer goroutines. Keep the registry protected by a Mutex.

Keep the HTTP handler in internal/ws/handler.go. Read the token query parameter and verify it with the Week 3 JWT signer before calling the hub. Mount GET /v1/ws in backend/cmd/api/main.go.

Think about these trade-offs:

  • Hold the hub mutex while looking up a connection and attempting a non-blocking enqueue. Do not hold it while performing a network write.
  • Let one owner handle send channel closure. Closing it from another goroutine can race with Send and cause a panic.
  • A slow consumer needs a dropped message, not a blocked API caller. Use a select statement with a default branch for the enqueue.
  • A replacement must stop the old connection without allowing its cleanup to remove the new registry entry. Coordinate cancellation and cleanup so the goroutine lifecycle remains tied to the connection that started each goroutine.

Any package layout that meets the contract passes.

How to check your work

Run the package tests, then the race-detector tests, then the end-to-end tests against the running API:

bash
cd backend && make test W=5B1
cd backend && go test -race ./internal/ws/ -run W5B1
cd backend && TEST_API_URL=http://localhost:8080 make test W=5B1

The race detector checks concurrent sends and disconnects for data races. When a test fails, start with its first failing assertion: it identifies the observed behavior and the exact value or timing limit that your implementation missed.

Finished Exercise 5.3?

WebSocket hub

3 items

  • 5.1Channels, select and cleanupnot completed
  • 5.2Managing WebSocket connectionsnot completed
  • 5.3Per-user WebSocket hubnot completed

Redis event fan-out

Up next · Module 2 · 2 items · about 1 h 45 min

Start module 2

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. cd backend && make test W=5B1 passes.
  2. cd backend && go test -race ./internal/ws/ -run W5B1 passes.
  3. Connected users receive their queued messages, and unknown users return false.
  4. A slow client does not block Send, and a full buffer causes a dropped message.
  5. Closing or replacing connections removes the correct registry entry and releases goroutines.
  6. The handler rejects missing or invalid tokens and registers the user identified by a valid token.

Commands

terminal
cd backend && make test W=5B1
terminal
cd backend && go test -race ./internal/ws/ -run W5B1
terminal
cd backend && TEST_API_URL=http://localhost:8080 make test W=5B1

Tests

  • TestW5B1_HubBroadcastsToEveryConnectedUser in backend/internal/ws/hub_test.go
  • TestW5B1_SendToUnknownUserIsFalse in backend/internal/ws/hub_test.go
  • TestW5B1_SlowClientNeverBlocksSend in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_ConnectionIsRemovedWhenTheClientCloses in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_SendersAndDisconnectsRaceSafely in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_GoroutinesExitAfterConnectionsClose in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_NewConnectionForTheSameUserReplacesTheOldOne in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_ReplacedConnectionReleasesItsGoroutines in backend/internal/ws/hub_backpressure_test.go
  • TestW5B1_HandlerRejectsAMissingOrInvalidToken in backend/internal/ws/handler_test.go
  • TestW5B1_HandlerRegistersTheUserFromTheToken in backend/internal/ws/handler_test.go
  • TestW5B1_SocketWithoutTokenIsRejected in backend/e2e/w5_test.go