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:
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.HandlerA 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
Sendfor each user with[]byte("hello")queues a message that the corresponding client receives. - Calling
Send(999, []byte("x"))when user999has no connection returnsfalse. - Sending 400 messages of 256 KiB each to a client that never reads finishes in less than 2 seconds. At least one send returns
falsebecause the bounded buffer is full. - When user
7closes the client connection, the hub removes that connection within 3 seconds.Connected(7)returnsfalse, andSend(7, []byte("x"))returnsfalse. - Eight concurrent senders can send to user IDs
0through9while 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, andSend(5, []byte("to-second"))delivers exactlyto-secondto 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
401for a missing token at/, an empty token at/?token=, and an invalid token at/?token=bad. - When the handler verifies the valid token
goodand obtains user ID77, the WebSocket connection registers user77in the hub within 2 seconds. - Dialling
/v1/wsagainst the running API without a token fails with HTTP401.
Constraints
- Keep the hub implementation in
backend/internal/ws/hub.goand the HTTP handler inbackend/internal/ws/handler.go. Sendmust 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/wsinbackend/cmd/api/main.go, outside the bearer-auth group, using the Week 3 access-token verification function asverify.
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
Sendand cause a panic. - A slow consumer needs a dropped message, not a blocked API caller. Use a select statement with a
defaultbranch 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:
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=5B1The 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.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
WebSocket hub
3 items
- 5.1Channels, select and cleanupnot completed
- 5.2Managing WebSocket connectionsnot completed
- 5.3Per-user WebSocket hubnot completed
Up next · Module 2 · 2 items · about 1 h 45 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
cd backend && make test W=5B1passes.cd backend && go test -race ./internal/ws/ -run W5B1passes.- Connected users receive their queued messages, and unknown users return
false. - A slow client does not block
Send, and a full buffer causes a dropped message. - Closing or replacing connections removes the correct registry entry and releases goroutines.
- The handler rejects missing or invalid tokens and registers the user identified by a valid token.
Commands
cd backend && make test W=5B1cd backend && go test -race ./internal/ws/ -run W5B1cd backend && TEST_API_URL=http://localhost:8080 make test W=5B1Tests
TestW5B1_HubBroadcastsToEveryConnectedUserinbackend/internal/ws/hub_test.goTestW5B1_SendToUnknownUserIsFalseinbackend/internal/ws/hub_test.goTestW5B1_SlowClientNeverBlocksSendinbackend/internal/ws/hub_backpressure_test.goTestW5B1_ConnectionIsRemovedWhenTheClientClosesinbackend/internal/ws/hub_backpressure_test.goTestW5B1_SendersAndDisconnectsRaceSafelyinbackend/internal/ws/hub_backpressure_test.goTestW5B1_GoroutinesExitAfterConnectionsCloseinbackend/internal/ws/hub_backpressure_test.goTestW5B1_NewConnectionForTheSameUserReplacesTheOldOneinbackend/internal/ws/hub_backpressure_test.goTestW5B1_ReplacedConnectionReleasesItsGoroutinesinbackend/internal/ws/hub_backpressure_test.goTestW5B1_HandlerRejectsAMissingOrInvalidTokeninbackend/internal/ws/handler_test.goTestW5B1_HandlerRegistersTheUserFromTheTokeninbackend/internal/ws/handler_test.goTestW5B1_SocketWithoutTokenIsRejectedinbackend/e2e/w5_test.go