Managing WebSocket connections
You trace how coder/websocket handles slow consumers and heartbeats before building a hub that manages each user's connection.
Learning outcomes
- Explain how
coder/websocketestablishes and manages persistent WebSocket connections. - Trace how the chat hub uses per-subscriber buffered channels to isolate slow clients.
- Use non-blocking delivery,
CloseReadand write timeouts to manage connection failures. - Explain how ping and pong heartbeats detect unresponsive clients and how the chat architecture maps to the per-user order-tracking hub.
Your Week 4 orders tab uses Polling to request order status every 10 seconds. That works, but the phone keeps making HTTP requests even when nothing has changed. A WebSocket lets the Go API push an update when an order changes, but one phone with a poor network connection must not block messages for every other customer.
The connection needs its own lifecycle and outgoing message queue. The hub manages which customer owns each connection, while a separate writer handles network writes. The difficult cases are a client that stops reading, a connection that disappears without warning, and a replacement connection that arrives before the old one finishes cleaning up.
Persistent WebSocket connections
A WebSocket provides a persistent, bidirectional connection between a client and a server. Unlike polling, the client does not need to make another HTTP request every time it wants an update.
The client and server establish the connection through an HTTP handshake. The server accepts the upgrade, and both sides can then exchange messages over the established connection.
For order tracking, the server can send an order update when the backend receives a relevant event. The client can also send messages to the server, although the WebSocket hub primarily sends updates to clients.
A WebSocket connection supports:
- Server-to-client messages, such as order status changes.
- Client-to-server messages, such as application-level commands.
- Connection closure initiated by either side.
- Protocol-level control frames used to manage the connection.
The important difference from an ordinary HTTP handler is its lifetime. An HTTP handler normally writes a response and returns. A WebSocket handler can remain active until the connection ends.
The coder/websocket package
The course uses github.com/coder/websocket version v1.8.15. It handles the WebSocket protocol so you do not need to implement framing, control messages or the HTTP upgrade yourself.
The Accept function upgrades an incoming HTTP request:
func handleSocket(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer conn.CloseNow()
}The third argument configures the handshake. Passing nil uses the library's default acceptance options.
The example closes the connection when the handler returns. A real handler must remain active for the connection's lifetime and coordinate its reader, writer and cleanup.
Authentication before the upgrade
Accepting a WebSocket connection does not authenticate the customer.
Your API already has access tokens from Week 3. The WebSocket endpoint receives the access token through its token query parameter:
GET /v1/ws?token=<access token>The HTTP handler should verify the token before calling Hub.Serve. If the token is missing, empty or invalid, the handler returns HTTP 401 without upgrading the connection.
This is important because a successful WebSocket handshake only establishes communication. It does not establish the customer's identity or authorization.
The Week 5 endpoint is mounted outside the ordinary bearer-auth group. It uses its own token-verification function before accepting the connection.
Reading and writing messages
The coder/websocket library exposes Read and Write methods for application messages.
Both operations accept a context. This lets you bound the time an operation can remain active.
Writing a message
The server writes a location or order update using Write:
func writeText(
ctx context.Context,
conn *websocket.Conn,
data []byte,
) error {
writeCtx, cancel := context.WithTimeout(
ctx, 5*time.Second,
)
defer cancel()
return conn.Write(writeCtx, websocket.MessageText, data)
}The first argument is the write context. The second identifies the message type, and the third contains the payload.
Here, the message type is websocket.MessageText. The five-second timeout bounds how long the write can wait.
A bounded write matters because a mobile connection can become unresponsive while the server is still trying to send data. Without a deadline or cancellation path, the writer goroutine can remain occupied indefinitely.
Reading a message
The Read method waits for the next application message:
func readMessage(
ctx context.Context,
conn *websocket.Conn,
) ([]byte, error) {
_, data, err := conn.Read(ctx)
if err != nil {
return nil, err
}
return data, nil
}The method returns the message type, its payload and an error.
A read can fail when the connection closes or the operation's context is cancelled. The connection owner can use this failure to begin cleanup.
Reading and writing should have separate responsibilities. A reader monitors incoming activity, while a writer consumes outgoing messages.
The chat hub architecture
Before building the order-tracking hub, inspect the official chat example in internal/examples/chat.
A WebSocket hub manages multiple active connections. It coordinates registration, removal and message distribution rather than making each connection manage the other connections.
The chat example uses a subscribers map to track connected clients. A simplified representation looks like this:
type Hub struct {
mu sync.Mutex
subscribers map[*Client]bool
}
type Client struct {
conn *websocket.Conn
send chan []byte
}The map identifies active subscribers. The mutex protects it because multiple goroutines may register, remove or inspect connections concurrently.
Each client also owns a separate send channel. The hub can enqueue messages without performing network writes itself.
Separate connection responsibilities
The chat example separates connection handling into three responsibilities:
- The hub manages the subscriber collection.
- The client reader handles incoming WebSocket activity.
- The client writer sends queued messages to the connection.
The reader and writer operate independently. A reader can monitor the connection while the writer delivers queued messages.
This separation prevents a slow network write from becoming part of the hub's message-distribution operation.
Per-connection message queues
A buffered channel provides temporary storage for messages waiting to be consumed.
The chat example gives each client its own buffered send channel:
type Client struct {
conn *websocket.Conn
send chan []byte
}
func NewClient(conn *websocket.Conn) *Client {
return &Client{
conn: conn,
send: make(chan []byte, 64),
}
}The example uses a capacity of 64 messages. A writer consumes messages from the channel and sends them over the associated WebSocket.
This queue separates message production from network delivery.
Consider two customers:
- Customer A has a fast mobile connection.
- Customer B has a slow mobile connection.
The hub can enqueue messages independently for both customers. Customer A's writer can continue sending while Customer B's writer processes its own queue.
A per-connection queue does not provide unlimited storage. It only allows the writer to fall behind temporarily.
The order-tracking exercise needs a bounded send channel for each connection. A small fixed capacity, such as 32 messages per connection, is a reasonable default. The exercise does not prescribe an exact capacity.
The writer's role
The writer consumes queued messages and performs the actual network writes.
A simplified writer looks like this:
func writeLoop(send <-chan []byte) {
for message := range send {
fmt.Println("writing message:", len(message))
}
}This example prints the message size rather than performing a WebSocket write. Its purpose is to show how the writer receives messages independently of the producer.
The connection's writer should own its network-writing responsibility. The hub should not perform a network write while trying to distribute an update.
This distinction matters when a connection becomes slow. The hub should be able to continue processing other users' messages.
Slow consumers and backpressure
A slow consumer is a client that cannot receive messages as quickly as the server produces them.
Suppose a rider sends a location update every second. A customer's phone takes several seconds to receive each update.
Its writer cannot keep up with the incoming messages. Eventually, its send channel fills.
If the hub performs an ordinary blocking send, the caller must wait until the writer consumes another message. Other callers can then experience delays.
The chat example addresses this with non-blocking delivery.
func (c *Client) Send(message []byte) bool {
select {
case c.send <- message:
return true
default:
return false
}
}The select attempts to enqueue the message. There are two possible outcomes:
- If the send can proceed immediately, the message enters the buffer and the method returns
true. - If the buffer is full, the
defaultbranch runs immediately and the method returnsfalse.
The sender never waits for the slow client to make room.
The drop-the-slow-subscriber policy
The chat example can interpret a failed enqueue as a reason to remove a slow subscriber.
This is a policy decision. The hub chooses not to let one subscriber interfere with message delivery to the others.
For order tracking, dropping an individual location update can be acceptable because a newer location update can arrive shortly afterward.
However, not every application message has the same delivery requirements. An order-state transition should not be treated as interchangeable with a transient location update. A reliable delivery requirement needs an appropriate recovery mechanism.
The Per-user WebSocket hub exercise has a specific contract: Send returns false when a message is dropped or the user has no connection. The tests require non-blocking delivery and at least one dropped message when the buffer fills. Logging a dropped message is an implementation choice that can help diagnose slow consumers.
Buffer capacity and memory
A buffer only absorbs a limited burst of messages.
Choose a small fixed capacity for each connection. A capacity of 32 messages is a reasonable starting point, but the Per-user WebSocket hub exercise does not prescribe that number. Each slot holds a []byte message, so queued payloads also consume memory.
Increasing buffer capacity would delay the point at which the queue fills, but it would not solve an indefinitely slow connection.
The exercise requires non-blocking delivery and at least one dropped message when the buffer fills. The precise capacity and whether you log dropped messages are implementation choices.
Connection cleanup with CloseRead
A WebSocket connection must be removed from the hub when the remote client disconnects.
The server cannot rely only on outgoing writes to discover that a connection has ended. A client might disconnect while the server is waiting to send its next message.
The coder/websocket library provides CloseRead for connections that do not need to consume application messages but still need to monitor the connection.
CloseRead processes incoming control frames while discarding application data. It also provides a way to notice when the connection ends.
A simplified monitoring function looks like this:
func monitorConnection(
ctx context.Context,
conn *websocket.Conn,
) {
readCtx := conn.CloseRead(ctx)
<-readCtx.Done()
}The returned context is cancelled when the read side ends or the parent context is cancelled.
This approach is useful for the order-tracking hub because it primarily sends updates to the customer. It still needs to detect a disconnected client and process WebSocket control frames.
Connection ownership
Closing a WebSocket and closing a Go channel are different operations.
When a connection ends, the application needs to coordinate its cleanup:
- Stop the connection's reader.
- Stop the connection's writer.
- Remove the connection from the hub if it is still registered.
- Close its send channel exactly once.
- Wait for its goroutines to finish.
Channel ownership matters here. If one goroutine closes the send channel while another is sending, the sender can panic.
A single connection lifecycle owner should control send-channel closure. The hub must also synchronize registry access and enqueue operations so that concurrent senders cannot race with closure.
Replacing an existing connection
A customer might reconnect while their previous connection is still registered.
The hub allows one active connection per user. A replacement must close the old connection without allowing its cleanup to remove the new one.
Consider this sequence:
- User
5has an existing connection. - A second connection registers for user
5. - The hub replaces the old registry entry.
- The old connection begins cleanup.
- The new connection remains registered and continues receiving messages.
The old connection must clean up its own resources. It must not delete the replacement from the hub.
A safe design checks connection identity before removing an entry. The old connection can only remove the registry entry if that entry still points to itself.
This is why connection cleanup must be coordinated with the registry mutex.
Ping and pong heartbeats
A WebSocket can become unresponsive without either side immediately knowing.
For example, a customer enters a lift and temporarily loses network connectivity. The server might still have a connection object even though the phone cannot receive messages.
A WebSocket heartbeat helps detect this situation.
WebSocket supports control frames called ping and pong. One side sends a ping, and the other side responds with a pong.
The coder/websocket library supports ping operations. A ping can use a bounded context:
func sendPing(
ctx context.Context,
conn *websocket.Conn,
) error {
pingCtx, cancel := context.WithTimeout(
ctx, 5*time.Second,
)
defer cancel()
return conn.Ping(pingCtx)
}The timeout bounds the ping operation. If the remote endpoint stops responding, the operation can fail and the connection can be cleaned up.
The reader also matters. Processing incoming control frames allows the library to handle the corresponding protocol responses.
Heartbeats and write timeouts
A write timeout and a heartbeat solve related but different problems.
A write timeout limits how long one outgoing message can wait. A heartbeat checks whether the remote endpoint continues responding over time.
For the hub, an optional ping approximately every 20 seconds can help detect disconnected clients. The exact heartbeat behaviour is not covered by the Per-user WebSocket hub unit tests.
Do not treat heartbeat monitoring as a substitute for connection cleanup. The application still needs to stop its goroutines when the connection ends.
Common connection mistakes
Several mistakes can make a WebSocket implementation appear correct with one client but fail under concurrent connections.
Writing directly from the hub
If the hub writes directly to every WebSocket, a slow client can delay other message senders.
The symptom is that healthy clients receive updates late while another client is struggling with its network connection.
Use a per-connection send channel and let a dedicated writer handle network writes.
Using a blocking enqueue
A buffered channel still blocks when its capacity is exhausted.
If the hub uses an ordinary send, a full buffer can hold up the sender. The Per-user WebSocket hub slow-client test sends 400 messages of 256 KiB to a client that never reads. Those attempts must finish in less than 2 seconds, and at least one message must be dropped.
The symptom of a blocking implementation is that the test exceeds its time limit.
Treating a failed enqueue as a successful delivery
A successful enqueue means the message entered the connection's buffer. It does not prove that the remote phone received it.
Likewise, a false result means the message was not queued. The caller must not interpret it as successful delivery.
Failing to monitor the connection
If the server never notices that a client has disconnected, its connection can remain registered.
The symptom is that Connected(userID) remains true after the client closes, and Send continues to find a connection that is no longer useful.
Use the reader lifecycle to detect closure and begin cleanup.
Closing the channel from multiple goroutines
If the reader and writer both try to close the same send channel, the application can panic.
A different failure occurs when a sender attempts to write after cleanup has closed the channel.
Assign one owner to channel closure and synchronize the enqueue operation with cleanup.
Removing a replacement connection
If an old connection removes a user's registry entry after a newer connection has replaced it, the new connection disappears from the hub.
The symptom is that Connected(userID) returns false, or Send cannot reach the replacement.
Cleanup must compare connection identity before deleting a registry entry.
Applying the architecture to order tracking
The chat example provides the starting architecture for the Per-user WebSocket hub exercise.
The application needs one active connection per signed-in user, rather than a general chat subscriber collection. The hub uses user IDs to locate connections, while each connection has an independent send channel.
The exercise brings these responsibilities together:
- A mutex-protected registry manages connections.
- Each connection owns a buffered send channel.
- A reader detects client disconnections and handles WebSocket control frames.
- A writer consumes queued messages and uses bounded network writes.
- A non-blocking send drops messages when the buffer is full.
- Connection cleanup handles replacement without removing the new connection.
The HTTP handler verifies the access token before upgrading GET /v1/ws. This keeps unauthenticated clients from establishing connections.
The hub only manages connections within one api instance. The next module introduces Redis pub/sub fan-out so an event received by one api instance can reach the instance that holds the customer's connection.
Read the official coder/websocket README and inspect internal/examples/chat before implementing the exercise. Pay particular attention to how the example handles client registration, buffered delivery and connection cleanup.
Check your understanding
Your Week 4 orders tab polls every 10 seconds. The backend changes an order to PREPARING immediately after the customer's last poll. What is the main advantage of using a WebSocket for this update?
References
Everything above is explained on this page; these are where it comes from.