Articles / Go

  • go
  • channels
  • concurrency
  • context
  • goroutines
  • design-patterns

Replying to a Go Request with a Channel Inside the Request

You can send a channel down a channel, and that is the neatest way I know to answer a request in Go without a mutex. The caller puts a private reply channel inside its request. The goroutine that owns the data replies on it. Nothing is shared except the message.

Here is the whole idea in a small in-memory store, then the three details that decide whether it behaves.

The shape: one owner, requests carry their own return address

A single goroutine owns a map. Nobody else touches it, so there is no lock. Everyone else sends it a request, and each request says where the answer should go.

package main

import (
	"context"
	"fmt"
)

type result struct {
	val string
	ok  bool
}

type getReq struct {
	key   string
	reply chan<- result
}

type setReq struct {
	key, val string
}

type Store struct {
	gets chan getReq
	sets chan setReq
}

func NewStore(ctx context.Context) *Store {
	s := &Store{gets: make(chan getReq), sets: make(chan setReq)}
	go s.run(ctx)
	return s
}

func (s *Store) run(ctx context.Context) {
	data := map[string]string{}
	for {
		select {
		case r := <-s.gets:
			v, ok := data[r.key]
			r.reply <- result{v, ok}
		case r := <-s.sets:
			data[r.key] = r.val
		case <-ctx.Done():
			return
		}
	}
}

The map never escapes run, so a data race is impossible by construction.

The caller makes the reply channel

Each Get creates a fresh channel, sends it inside the request, then waits on it. Because the channel belongs to one call, replies can never get crossed between callers.

func (s *Store) Get(ctx context.Context, key string) (string, bool, error) {
	reply := make(chan result, 1)

	select {
	case s.gets <- getReq{key: key, reply: reply}:
	case <-ctx.Done():
		return "", false, ctx.Err()
	}

	select {
	case res := <-reply:
		return res.val, res.ok, nil
	case <-ctx.Done():
		return "", false, ctx.Err()
	}
}

func (s *Store) Set(ctx context.Context, key, val string) error {
	select {
	case s.sets <- setReq{key, val}:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	s := NewStore(ctx)
	_ = s.Set(ctx, "colour", "teal")
	v, ok, err := s.Get(ctx, "colour")
	fmt.Println(v, ok, err)
}

Note the type chan<- result in the request. The owner can only send on it, which the compiler enforces. A small thing, but it documents the direction of the conversation.

Detail one: the reply channel must have a buffer of one

Look at make(chan result, 1). If the reply channel is unbuffered and the caller has given up, the owner blocks forever on its send, and now every other caller is stuck behind it.

The sequence goes like this:

  1. The caller sends its request and starts waiting.
  2. The caller's context times out, and it returns.
  3. The owner finishes the lookup and sends the reply.
  4. Nobody is receiving, so an unbuffered send never completes.

With a buffer of one, the owner's single send always succeeds immediately, whether or not anyone reads it. The abandoned channel is then garbage collected along with its one stale result. The owner sends exactly one reply per request, so the buffer needs to hold exactly one.

Detail two: both waits need the context

There are two places a caller can be stuck: handing over the request, and waiting for the answer. Each gets its own select with ctx.Done().

Skip the first one and a busy owner can hold callers indefinitely. Skip the second and a slow owner does the same. Most versions of this pattern I see guard only one of them.

Quick detour: why not just return the value?

Hang on, why does the reply need a channel at all? Because a send on s.gets has no return value. Channels carry data one way. A request/response over channels is really two messages, and the first one has to say where the second goes. Passing the channel in the request does exactly that. Go's own documentation of the language even uses this as the standard example for why channels are values you can pass around.

Detail three: the owner can vanish

When the store's context is cancelled, run returns. A later Get then blocks on s.gets until the caller's own context ends. If a caller might use context.Background(), that is a hang.

The fix is a done channel closed by run on exit, added as one more select case in Get and Set that returns an error such as ErrClosed. I left it out above to keep the example readable, but a real store needs it.

When a mutex is the better answer

This pattern serialises everything through one goroutine. That is fine for coordination, state machines and anything where ordering matters. For a hot read-mostly cache, a sync.RWMutex is simpler and faster, and the owner goroutine becomes a bottleneck.

Reach for the channel of channels when the owner does more than guard a map: it also reacts to timers, other channels or shutdown in the same loop. Then the single select is doing real work, and the private reply channel is the cheapest honest way to answer.