← Runtimes
Runtimes

Channels and message passing

Know who owns data as it travels, and what a full channel does.

Follow message ownership, bounded capacity, and task completion through a producer–consumer workflow.

Outcome

Explain what a send hands to the receiver in each language, make each message own its data, and use bounded channels without deadlocking.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Channel
A communication mechanism that transfers messages between senders and receivers. Buffered channels queue values; a zero-capacity channel instead requires a sender/receiver rendezvous.
Bounded channel
A channel with a fixed pending-message capacity. A blocking send waits for space, or for a receiver at capacity zero. This limits queued messages, not all process memory.
Close
Ending further sends while allowing already-queued messages to drain. Go closes explicitly; Rust receivers reach disconnection after every sender is dropped and queued values are consumed.
Ownership transfer
An exclusive handover of the data a message needs. Sending a shared handle transfers or copies that handle without giving exclusive ownership of its target.
Deadlock
Tasks each waiting for another to act, so none ever does.

Messages connect producers and consumers

A producer creates messages and sends them through a channel or queue; a consumer receives and processes them. The channel coordinates delivery, while the message type and ownership policy determine what data the consumer can safely use and for how long. Receiving a message and finishing its processing are separate events.

Capacity limits how many messages can wait in the channel. When a blocking send must wait for room, that pressure reaches the producer: backpressure. Reason about the flow in both directions, including results and completion signals, because a task waiting to send cannot also perform a later receive.

01What a send hands over

A message is a value, or a reference to one

An invoice contains the right line items, but the pricing worker sometimes totals later amounts in place of earlier ones. The job sends batches through a queue while reusing its records for the next batch. Fix that handover, and the month-end run exposes a second problem: both bounded queues fill while billing waits to read the subtotals.

Go provides language-level channels; Rust provides std::sync::mpsc. C++23 has no standard channel, so the lab declares a mutex/condition-variable queue. The message type determines what moves or copies. Copying a slice, pointer or shared handle preserves access to its target; copying a container of such handles still shares those targets.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func main() {
	pricing := make(chan []int, 1)

	batch := []int{1250, 400, 999}
	pricing <- batch
	batch[0] = 7500

	received := <-pricing
	fmt.Println("received:", received)
}
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run .
In this single-goroutine program, a capacity-1 channel accepts a batch, then batch[0] changes to 7500, then the same goroutine receives. What happens?

02Full channels

Capacity turns slow consumers into waiting producers

A producer that outruns its consumer can grow an unbounded queue until resources are exhausted. A blocking bounded channel makes it wait for space: backpressure. Go’s make(chan T, n), Rust’s sync_channel(n) and the supplied C++ queue support this pattern. Rust’s mpsc::channel() has no fixed message capacity. Even a two-message channel does not bound bytes if a message can retain a large object; the lab also limits each batch to three amounts.

Waiting creates a new failure. If the invoicing job sends every batch before reading any subtotal, and the pricing worker must send a subtotal before it takes the next batch, both bounded channels fill and every task waits for another: a deadlock that small invoices never reach.

Both channels hold 2 messages. The invoicing job sends 20 batches, then reads 20 subtotals; one pricing worker reads a batch and sends its subtotal. What happens?

03Practice

Run the invoicing job

The pricing worker runs on native threads or goroutines, but its business logic is an authored model: sum each batch and request a 1 ms sleep. A particular schedule can expose reused records; no sleep guarantees that observation. The watchdog reports stalled if the whole job misses a three-second completion deadline. Slow scheduling can miss that deadline too, so stalled alone does not prove deadlock.

The invoicing job

Send invoice batches, keep their line-item records stable for the receiver, then drain bounded queues and wait for pricing-session completion before reporting.

  1. easy · R-CHAN-V4-1 Send the batches
  2. medium · R-CHAN-V4-2 Hand over the data
  3. hard · R-CHAN-V4-3 Small buffers
Check this idea later
A Go producer reads lines into one reused []byte buffer and sends it on a channel after each read. Consumers see garbled lines. Why?
A log shipper’s producer is faster than its network consumer. With bounded-size messages and no other growing backlog, which queue bounds the queued-message memory?
Supported invoice sizes have no fixed upper bound, and the job still sends every batch before reading subtotals. Doubling its buffers makes the tests pass. Is the deadlock fixed?
Sources
In the frontend A response cannot drain a stream the handler has not returned yet. Optional

The billing team exposes a streamed invoice preview. This diagnostic makes 20 small encoded fragments and waits for every write before returning the readable side to the HTTP host. Both stream strategies count chunks with highWaterMark 2.

With no other reader, where can backpressure wait? Identify when a consumer first becomes able to read, and what memory the two-chunk bound actually covers. Web Streams use asynchronous promises here; this is not a Go channel or a native worker thread.

app/api/invoice-preview/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export async function GET() {
  const encoder = new TextEncoder();
  const chunks = Array.from({ length: 20 }, (_, i) =>
    encoder.encode(`line item ${i + 1}
`)
  );
  const stream = new TransformStream<Uint8Array, Uint8Array>(
    undefined,
    { highWaterMark: 2 },
    { highWaterMark: 2 }
  );
  const writer = stream.writable.getWriter();

  for (const chunk of chunks) await writer.write(chunk);

  await writer.close();

  return new Response(stream.readable);
}

The route handler is under review. A write promise can wait for readable-side capacity before the Response exists. The count strategies also leave this eager chunks array retained; two queued chunks do not bound the handler’s entire memory.

Sources: Streams standard: TransformStream backpressure.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.