How-To Guide

How to Implement Channel-Based Communication

Move data between concurrent tasks with bounded channels instead of shared memory, so synchronisation is part of the data transfer.

On this page

  1. Introduction
  2. Channels as Ownership Transfer
  3. Buffered Versus Unbuffered
  4. Fan-Out and Fan-In
  5. Cancellation and Deadlines
  6. Observability of Channels
  7. Common Pitfalls and Conclusion

Introduction

Shared memory concurrency forces you to coordinate access with locks, and locks are where the subtle bugs live. Channel-based communication inverts the model: instead of sharing memory and locking it, concurrent tasks own their data and pass it to each other through channels. A channel is a queue with send and receive operations, and its buffering decides the synchronisation: an unbuffered channel hands data directly from sender to receiver, while a bounded buffer decouples them and provides backpressure when full. “Do not communicate by sharing memory; share memory by communicating” is the whole idea.

Channels as Ownership Transfer

When a value is sent on a channel, the sender should no longer use it; ownership passes to the receiver. That convention is what makes channels race-free: at any moment exactly one task owns a value, and the hand-off is synchronised by the channel rather than by a lock. In languages with ownership types this is enforced by the compiler; in others it is a discipline, but the discipline is simple: after sending, do not touch.

A channel is also a synchronisation point. Sending on a full bounded channel blocks until space frees; receiving on an empty channel blocks until data arrives. Those blocking points are the coordination, and they are local and visible rather than spread across locks and condition variables.

Compared with a lock, a channel also carries the data, so there is nothing to read out of a shared location after the hand-off. The unit of synchronisation and the unit of transfer are the same, which removes the gap where a value can be read without the lock that was meant to protect it.

class BoundedChannel<T> {
  private buf: T[] = [];
  private sendWaiters: Array<() => void> = [];
  private recvWaiters: Array<(v: T) => void> = [];

  constructor(private capacity: number) {}

  async send(value: T): Promise<void> {
    while (this.buf.length >= this.capacity) {
      await new Promise<void>((r) => this.sendWaiters.push(r)); // backpressure
    }
    this.buf.push(value);
    const recv = this.recvWaiters.shift();
    if (recv) recv(this.buf.shift()!);
  }

  async receive(): Promise<T> {
    const value = this.buf.shift();
    if (value !== undefined) {
      const s = this.sendWaiters.shift();
      if (s) s();                    // wake a blocked sender
      return value;
    }
    return new Promise<T>((r) => this.recvWaiters.push(r));
  }
}

Buffered Versus Unbuffered

An unbuffered channel is a rendezvous: the sender blocks until a receiver is ready, so every send is a synchronisation point and no data is ever queued. A buffered channel of size one decouples the two by exactly one message. Larger buffers decouple more, improve throughput when producers and consumers run at different speeds, and hide latency bursts.

The buffer size is a design decision about backpressure, not just performance. A large buffer means a fast producer and a slow consumer can diverge for a long time before the producer is forced to slow down, which increases memory use and the amount of work potentially lost on a crash. A small buffer keeps the two close and makes backpressure immediate.

# buffer size trade-offs
unbuffered (0)  synchronous hand-off, tightest coupling, no queuing
buffered (1)    one message of slack, common default
buffered (N)    throughput at the cost of memory + decoupling
# rule: start small; grow only when measured throughput demands it

Fan-Out and Fan-In

Channels compose into patterns. Fan-out sends each message to one of several workers, distributing load; fan-in collects results from several producers into one channel for a single consumer. A worker pool is fan-out plus fan-in: jobs on one channel, results on another, and N workers in between.

Closing a channel is how you signal that no more data is coming. Receiving from a closed channel returns immediately with an end marker, so consumers drain and exit. Deciding who closes is important: the sender closes, never the receiver, and a receiver that also sends must not close a channel it does not own, or a sender will write to a closed channel and fail.

async function workerPool<J, R>(
  jobs: Channel<J>,
  results: Channel<R>,
  run: (job: J) => Promise<R>,
  n: number,
): Promise<void> {
  await Promise.all(Array.from({ length: n }, async () => {
    for await (const job of jobs) {     // fan-in over the job channel
      await results.send(await run(job)); // fan-out over the result channel
    }
  }));
  results.close();
}

Cancellation and Deadlines

Every blocking channel operation must be cancellable, or a program can deadlock with no way out. Pass a cancellation signal or a context with the send and receive operations, so a blocked sender releases when the request is cancelled. A channel operation that ignores cancellation turns a slow consumer into a hung system.

Select-like behaviour, waiting on several channels at once, is how you add timeouts without blocking: race a receive against a deadline channel and take whichever fires first. Without it you cannot implement “wait for a result or time out” cleanly, and every such wait becomes a source of hangs.

async function receiveWithTimeout<T>(
  ch: Channel<T>,
  signal: AbortSignal,
  timeoutMs: number,
): Promise<T | undefined> {
  const timeout = AbortSignal.timeout(timeoutMs);
  const combined = AbortSignal.any([signal, timeout]);
  return Promise.race([
    ch.receive(),
    new Promise<undefined>((r) => combined.addEventListener('abort', () => r(undefined))),
  ]);
}

Observability of Channels

A channel is a queue, and a queue that grows is a producer outrunning a consumer. Export channel depth, send-block count, receive-block count and buffer utilisation. A rising depth or a growing count of blocked sends is the earliest signal that a downstream stage is falling behind, before latency or memory blows up.

Because blocked sends are backpressure working, an increase is not always bad, but a sustained increase means the consumer’s capacity is below the producer’s rate. Alert on depth approaching the buffer capacity and on the rate of dropped or cancelled sends, since those are where data is actually lost.

# channel metrics worth exporting
channel_depth{name="jobs"}            current queued items
channel_capacity{name="jobs"}         configured buffer
send_blocked_total{name="jobs"}       backpressure applied
receive_blocked_total{name="jobs"}    consumer waiting for work
send_cancelled_total{name="jobs"}     sends abandoned (possible loss)

Common Pitfalls and Conclusion

Do not use a channel as a general-purpose container you keep reading and writing after sending; ownership must transfer. Do not close from the receiver. Do not size buffers by guess; measure. Do not skip cancellation, or deadlocks become unrecoverable. And do not assume channels give parallelism in a single-threaded runtime; they give ordering and ownership, and true parallelism needs separate threads or processes.

Channels replace shared memory and locks with queues and ownership transfer. Bounded buffers provide backpressure, closing signals end of stream, fan-out and fan-in build worker pools, and cancellation keeps blocking operations escapable. Once you think in channels, the coordination that used to be scattered across locks becomes a visible, composable data flow.

Sources: Go: Effective Go — channels, Go: Share memory by communicating, Rust: std::sync::mpsc.

FAQ

When should a channel be buffered versus unbuffered?
Use unbuffered when you want a strict rendezvous and no queuing, and a small buffer when producer and consumer run at slightly different speeds. Grow the buffer only when measured throughput requires it, because a large buffer weakens backpressure and increases memory.
Who closes a channel?
The sender closes, because it knows when no more values will be sent. The receiver must never close, and a task that only receives should not close a channel it does not own, or senders will write to a closed channel.

Related Examples