Channels, select and cleanup

You coordinate goroutines with buffered channels and select, then close channels safely when a connection ends.

Learning outcomes

  • Explain how unbuffered channels synchronize goroutines and why a slow receiver can block a sender.
  • Use buffered channels to queue order updates independently for each WebSocket connection.
  • Close channels safely by assigning ownership to the goroutine responsible for their lifecycle.
  • Use range, select and ctx.Done() to process messages and stop goroutines when connections end.
Prerequisite conceptsGoroutines

A customer has an order open on their phone. When the order changes from ACCEPTED to PREPARING, the API needs to send an update to that customer's WebSocket connection. The problem starts when the phone stops reading: one slow connection must not stall every sender trying to deliver updates to other customers.

The hub needs a separate message queue for each connection. A writer goroutine consumes messages from that queue, while the rest of the API can enqueue updates without waiting for a network write. The difficult part is deciding what happens when the queue fills or the connection closes.

Channels as communication between goroutines

A Go channel allows one goroutine to send typed values to another goroutine. A goroutine can produce an order update while another goroutine handles the connection.

You create a channel with make:

go
messages := make(chan string)

The channel's type determines which values it carries. A chan string carries strings, while a chan []byte carries byte slices.

There are two basic operations:

  • Sending: ch <- value
  • Receiving: value := <-ch

Consider two goroutines communicating through a channel:

go
messages := make(chan string)

go func() {
    messages <- "order accepted"
}()

message := <-messages
fmt.Println(message)

The first goroutine sends a string. The main goroutine receives it and prints:

order accepted

The important detail is that sending and receiving coordinate with each other. A channel is not merely a container that stores values. Its operations can synchronize the goroutines using it.

This synchronization is useful when one goroutine produces work and another consumes it. In the WebSocket hub, the API produces messages and a connection's writer consumes them.

Unbuffered channels

An unbuffered channel has no storage capacity. You create one without specifying a capacity:

go
events := make(chan string)

A send blocks until another goroutine is ready to receive the value. A receive also blocks until a sender provides a value.

Consider this example:

go
events := make(chan string)

go func() {
    events <- "rider assigned"
}()

event := <-events
fmt.Println(event)

The sender cannot finish its send until the receiver is ready. Both operations meet at the same communication point.

This behaviour is useful when the sender should wait until another goroutine accepts a value. However, that requirement becomes a problem when the receiver is responsible for writing to a slow network connection.

The slow phone problem

Imagine that the hub sends an update directly through an unbuffered channel to each connection's writer goroutine.

go
client.send <- message

The send cannot complete until the writer receives the message. If the writer is busy with a previous network write, the hub must wait.

Now imagine that the customer's phone has a poor network connection. Its writer remains occupied while other customers' order updates are ready to be sent.

If the hub waits for the slow connection, other senders can experience unnecessary delays. The problem is the synchronization imposed by the unbuffered channel.

The hub should not have to wait for a writer to become available before it can enqueue an update. A queue between the producer and consumer solves this part of the problem.

Buffered channels

A buffered channel provides a fixed amount of storage for values waiting to be received.

You specify the capacity when creating it:

go
updates := make(chan string, 3)

This channel can hold three strings without requiring a receiver to be ready for each send.

Consider:

go
updates := make(chan string, 2)

updates <- "order confirmed"
updates <- "rider assigned"

fmt.Println(<-updates)
fmt.Println(<-updates)

Both sends complete before a receiver consumes either value.

The output is:

order confirmed
rider assigned

A buffered channel changes when a sender blocks:

  • If the buffer has space, the send completes immediately.
  • If the buffer is full, the sender blocks until a receiver consumes a value.
  • If the channel is closed, a send causes a panic.

Receiving behaves similarly:

  • If the buffer contains values, the receiver gets the next value.
  • If the buffer is empty and the channel remains open, the receiver blocks.
  • If the channel is closed and the buffer is empty, the receiver gets the zero value and can detect closure using the two-value receive form.

A buffered channel is still a finite queue. It does not make communication asynchronous without limits.

Buffering order updates

For the WebSocket hub, each connection needs an independent send channel. The writer goroutine consumes messages from that connection's channel and writes them to the client.

The exercise uses a capacity of exactly 32 messages per connection.

go
updates := make(chan []byte, 32)

The []byte type allows the queue to carry encoded order-update messages.

Suppose a customer's phone temporarily stops reading. The API can still enqueue messages while the connection's writer is processing earlier updates, provided the buffer has available capacity.

The queue separates message production from network delivery. The API does not need to wait for each write to finish before it can enqueue another message.

Each connection gets its own queue. A full queue for one customer does not consume the buffer capacity belonging to another customer.

A bounded queue needs a policy

Buffering postpones blocking, but it does not eliminate the problem of a slow consumer.

Suppose the API produces updates faster than a connection can consume them. The buffer gradually fills. Once it contains 32 messages, another ordinary send blocks until the writer receives something.

For a backend that needs to deliver updates to multiple connections, allowing one full queue to block a sender is undesirable.

You need an explicit policy for a full buffer. Possible policies include:

  • Block the sender until space becomes available.
  • Disconnect the slow client.
  • Drop a message and let the application handle the consequences.

The hub you build in Per-user WebSocket hub uses a non-blocking send. When a connection's buffer is full, it drops the new message and reports that the message was not queued.

This is a backpressure decision. The sender gets a result immediately instead of waiting for the client to recover.

Non-blocking sends with select

The select statement lets a goroutine wait on multiple channel operations.

It looks like a switch statement, but its cases represent channel sends and receives.

go
select {
case message := <-messages:
    fmt.Println(message)
case result := <-results:
    fmt.Println(result)
}

The goroutine waits until at least one communication operation can proceed. If multiple cases are ready, Go chooses one pseudo-randomly.

If no case is ready, the select blocks.

A default branch changes that behaviour. It executes immediately when none of the communication cases can proceed.

go
select {
case message := <-messages:
    fmt.Println(message)
default:
    fmt.Println("nothing available")
}

This makes the select non-blocking.

Dropping when the send buffer is full

You can use the same pattern for the connection's send channel:

go
select {
case client.send <- message:
    // The message was queued.
default:
    // The buffer is full.
}

There are two possible outcomes:

  1. If the send can proceed immediately, the message enters the buffer.
  2. If the buffer has no available space, the default branch executes.

The second outcome does not wait for the writer to catch up.

The exercise requires Send to return true when the message is successfully queued and false when there is no connection or the message is dropped. It also requires a warning to be logged when a full buffer causes a drop.

A non-blocking send is particularly useful for the hub because its callers should not inherit the network latency of a particular customer's phone.

Buffer capacity and burst handling

A buffer provides temporary room for bursts of messages.

For example, a capacity of 32 allows a writer to fall behind by up to 32 queued messages before new non-blocking sends start getting dropped.

Increasing the capacity can absorb a larger temporary burst, but it does not fix an indefinitely slow connection. It also increases the amount of memory available for queued messages.

For the exercise, the capacity is fixed by the contract. You should not treat it as a tuning parameter.

Channel ownership and closure

A channel must have a clear owner responsible for closing it.

You close a channel using the built-in close function:

go
close(events)

Closing a channel communicates that no more values will be sent through it.

The channel can still contain buffered values after closure. Receivers can consume those values before they observe that the channel is closed.

This distinction matters because closing a channel does not immediately discard its queued messages.

Detecting closure

A receive can return two values:

go
value, ok := <-events

if !ok {
    fmt.Println("channel is closed")
    return
}

fmt.Println(value)

The ok value is true when a value is received successfully. It is false when the channel is closed and no buffered values remain.

This lets a consumer distinguish between a real message and the end of its input.

Who closes a channel

The channel close ownership rule is important: the sender should normally close the channel after it has finished producing values.

The sender knows when it will no longer produce messages. A receiver generally cannot know whether another message might arrive.

Consider a producer:

go
events := make(chan string)

go func() {
    defer close(events)

    events <- "accepted"
    events <- "preparing"
    events <- "dispatched"
}()

The producer closes the channel when it returns. The defer ensures that closure happens after the send operations finish.

The receiver can consume every value using range:

go
for event := range events {
    fmt.Println(event)
}

The loop terminates after the channel closes and all buffered values have been received.

The danger of closing from multiple goroutines

Closing an already closed channel causes a panic. Sending on a closed channel also causes a panic.

This is particularly dangerous in the WebSocket hub because multiple goroutines participate in one connection's lifecycle.

Consider this situation:

  • The API calls Send and attempts to enqueue an order update.
  • The connection is closing.
  • Its cleanup code closes the send channel.
  • Another sender attempts to enqueue a message at the same time.

Without coordination, the sender may attempt to send to a closed channel.

The fact that the send uses select does not remove this risk. A send operation on a closed channel can still panic.

You need both ownership and synchronization.

The connection lifecycle owner is responsible for closing the send channel exactly once. The hub must also coordinate access to the connection registry and the enqueue operation so that a sender cannot race with channel closure.

Ranging over channels

The range keyword works with channels, slices and maps.

When you use it with a channel, Go repeatedly receives values until the channel is closed and its buffer is empty.

For example:

go
func printEvents(events <-chan string) {
    for event := range events {
        fmt.Println(event)
    }
}

Notice the parameter type <-chan string. This is a receive-only channel.

Go supports three channel directions:

  • chan T allows sending and receiving.
  • chan<- T allows sending only.
  • <-chan T allows receiving only.

Channel directions make function responsibilities clearer. A function that only consumes messages does not need the ability to close the channel or send values into it.

A producer-consumer example

A producer can return a receive-only channel:

go
func produce() <-chan int {
    results := make(chan int, 3)

    go func() {
        defer close(results)

        for i := 1; i <= 3; i++ {
            results <- i
        }
    }()

    return results
}

The caller only receives the results:

go
for result := range produce() {
    fmt.Println(result)
}

The output is:

1
2
3

The producer creates the channel, sends values and closes it after completing its work. The caller consumes values without taking ownership of channel closure.

Ranging over the send channel

The same pattern fits a WebSocket writer.

The connection has a send channel. Its writer consumes messages from that channel and writes each one to the WebSocket.

Conceptually, the writer's input can be expressed as a receive-only channel:

go
func writeMessages(send <-chan []byte) {
    for message := range send {
        fmt.Println("queued message:", len(message))
    }
}

The example prints message sizes instead of writing to a network connection. The important part is the receiving pattern.

The writer does not need to know who produced each message. It receives the next queued value and processes it.

When the connection owner closes the send channel, the writer can finish after consuming the remaining buffered messages.

A real WebSocket writer must also be able to exit when its connection ends. Channel closure is one termination mechanism, but connection cancellation is another.

Cancellation with ctx.Done()

A channel tells a goroutine that values are available or that no more values will arrive. It does not, by itself, tell a goroutine that the work it belongs to is no longer needed.

For that, Go provides context.Context.

A context can carry a cancellation signal through a chain of function calls. Its Done() method returns a receive-only channel that closes when the context is cancelled or its deadline expires.

You can use that channel inside a select statement.

go
func process(ctx context.Context, jobs <-chan string) {
    for {
        select {
        case <-ctx.Done():
            return
        case job, ok := <-jobs:
            if !ok {
                return
            }
            fmt.Println(job)
        }
    }
}

This loop has two termination paths:

  1. The context is cancelled, so ctx.Done() becomes ready.
  2. The jobs channel closes and has no remaining buffered values.

Without the cancellation case, the goroutine might remain blocked waiting for another job even after the application no longer needs it.

Connection lifetime

A WebSocket connection has a lifecycle of its own.

When a client disconnects, the API needs to stop the goroutines associated with that connection. Otherwise, a reader or writer might remain blocked after the connection is no longer useful.

A connection context provides a cancellation signal that the reader and writer can observe.

go
func processConnection(
    ctx context.Context,
    messages <-chan []byte,
) {
    for {
        select {
        case <-ctx.Done():
            return
        case message, ok := <-messages:
            if !ok {
                return
            }
            fmt.Println("received", len(message))
        }
    }
}

This example illustrates the termination conditions. It does not implement the WebSocket connection or its writer.

A production writer also needs to use bounded write operations. A network write should not hold a goroutine indefinitely if the client stops receiving data.

Per-user WebSocket hub uses coder/websocket for the actual connection. Its reader must detect when the client disconnects, while its writer consumes queued messages. The connection lifecycle must coordinate cancellation and cleanup so both goroutines eventually exit.

Cancellation does not close application channels

There is an important distinction between cancelling a context and closing a channel.

Calling a context's cancellation function closes its Done() channel. It does not automatically close the connection's send channel.

Similarly, closing a WebSocket does not automatically close every Go channel associated with it.

The connection lifecycle owner must coordinate these operations explicitly.

Combining select and cancellation

The select statement becomes more useful when it handles both incoming work and cancellation.

Consider a worker that processes messages until either its context is cancelled or its input channel closes:

go
func worker(ctx context.Context, messages <-chan string) {
    for {
        select {
        case <-ctx.Done():
            return
        case message, ok := <-messages:
            if !ok {
                return
            }
            fmt.Println(message)
        }
    }
}

The for loop allows the worker to process multiple messages. The select prevents it from waiting indefinitely for more work after cancellation.

This pattern applies to the WebSocket connection's reader and writer, although they perform different operations.

The reader monitors the connection and detects when it ends. The writer consumes outgoing messages. Both need a termination path connected to the same connection lifecycle.

There is one subtle detail: when both ctx.Done() and a message channel are ready, Go does not guarantee that the cancellation case runs first. The select chooses among ready cases.

If the application needs cancellation to take priority before starting more work, it must check the context at the appropriate processing boundary.

Common concurrency mistakes

The hub's contract is small, but its goroutines and channels interact in ways that can produce difficult failures.

Blocking on a full buffer

If you use an ordinary send to enqueue an update, the sender blocks when the buffer reaches capacity.

For the hub, this means the caller of Send could wait for a slow phone. The 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 non-blocking select is what prevents a full buffer from blocking the sender.

Assuming a buffered channel never blocks

A buffered channel can still block. It only allows a limited number of messages to wait for the receiver.

If your code uses a normal send when the buffer is full, the sender still waits.

A larger buffer changes how long it takes to reach this condition. It does not remove the condition.

Closing the channel from the wrong goroutine

If the writer closes the send channel while another goroutine is sending, the next send can panic.

The opposite mistake is allowing several cleanup paths to close the same channel. That can cause a panic when the second closure runs.

The lifecycle owner must control closure, and the hub must synchronize the enqueue operation with that closure.

Treating an empty channel as a closed channel

An empty but open channel is still waiting for future values.

A receive from it blocks. A range loop also waits for another value.

The loop exits only after closure and draining, not because the channel happens to be empty at one point in time.

Forgetting cancellation

A goroutine that waits only for a channel value can remain blocked after the connection has ended.

Include a cancellation case where the goroutine needs to stop with its connection. Make sure the operation it is waiting on can actually be released by the connection's cleanup.

Assuming cancellation always wins

A select does not prioritise ctx.Done() over other ready cases.

If both cancellation and an incoming message are ready, either case may run. Your processing logic must account for this instead of assuming cancellation always prevents another message from being selected.

Applying these ideas to the WebSocket hub

The per-user WebSocket hub uses the communication patterns from this lesson to isolate connected customers.

Each connection has a buffered send channel with capacity 32. A writer consumes queued messages and writes them to the corresponding WebSocket. The hub attempts non-blocking sends so a full queue does not stall the API.

Channel ownership becomes part of connection cleanup. The connection lifecycle owner must close the send channel exactly once, while synchronization prevents concurrent senders from sending to a closed channel.

The reader and writer also need clear exit conditions. Context cancellation and connection closure must release their work, including when a new connection replaces an older connection for the same user.

The next exercise, Per-user WebSocket hub, puts these rules together. You will build the connection registry and its lifecycle without allowing one slow phone to block message delivery to other users.

Check your understanding

Question 1 of 4

The hub has an unbuffered send channel for a customer's connection. The writer is currently busy with a network write. What happens when another goroutine tries to enqueue an order update?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from.

Finished Lesson 5.1?