System Design Academy

Saving…

Lesson 5 of 10 in Module 40 of 45 lessons complete

Channels & select

Module 4, lesson 5Concept12 min

Definition

Channel

In plain English
A channel is a typed pipe that goroutines use to send values to each other safely.
Think of it like
It is like a pneumatic tube between offices: put a message in one end, it pops out the other.

select

In plain English
select lets a goroutine wait on several channel operations and run whichever is ready first.
Think of it like
It is like a receptionist watching several phone lines and answering whichever rings.

Why it exists

Kitchen stations need orders from several callers. Let one station own its queue and receive messages.

The callers pass values instead of editing that queue. You can also wait for work or a stop signal.

Panic

In plain English
A panic stops normal execution and ends the program unless code explicitly recovers.
Think of it like
Like an emergency stop that halts a machine.

How it works

Buffered vs unbuffered channel

In plain English
An unbuffered channel makes the sender wait until a receiver takes the value, while a buffered channel holds a few values so the sender can continue.
Think of it like
Like handing a parcel to someone in person versus dropping it in a mailbox with limited space.

Closing a channel

In plain English
Closing a channel tells receivers no more values will come, and only the sender should close it.
Think of it like
Like a shop flipping its sign to "closed".

Sender sends values through an Order channel to a receiver that owns its queue.

Pass orders to their single owner.

Sender sends values through an Order channel to a receiver that owns its queue.

ChannelSender waits whenUseful for
UnbufferedNo receiver is readyA direct handover
BufferedThe buffer is fullA bounded queue
  • A closed channel yields its buffered values first, then the zero value with ok equal to false.
  • Range receives until the closed channel is drained. Sending on a closed channel panics.
  • A nil channel has no channel assigned; its select case is disabled, while an ordinary send or receive blocks forever.
  • If several select cases are ready, Go chooses one pseudo-randomly; source order gives no priority.
After: 30 milliseconds stands in for a 30-second dispatch timeout.
Go
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	accepted := make(chan string, 1)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() { defer wg.Done(); time.Sleep(40 * time.Millisecond); accepted <- "ambulance 7" }()
	select {
	case id := <-accepted:
		fmt.Println(id)
	case <-time.After(30 * time.Millisecond):
		fmt.Println("escalate")
	}
	wg.Wait()
}

The buffer holds one late response, so the helper cannot get stuck sending after a timeout. Wait still joins it.

Examples

Give the station ownership

Orders arrive through one channel. Only the receiving station changes its queue.

After: the sending goroutine closes orders; main owns the station queue.
Go
package main

import (
	"fmt"
)

func main() {
	orders := make(chan int)
	go func() {
		defer close(orders)
		for id := 1; id <= 3; id++ {
			orders <- id
		}
	}()
	queue := []int{}
	for id := range orders {
		queue = append(queue, id)
	}
	fmt.Println(queue)
}

The range loop ends after the sender closes the channel. Nobody else touches queue.

The insight

One owner and a channel can replace shared-state locking.

Trade-offs

Pros

  • Make data ownership visible.
  • Combine work and stop signals.

Cons

  • Missing receivers can leave senders stuck.
  • Channels do not protect objects shared through pointers.

Use when

  • Transfer jobs or results between owners.
  • Wait for work and a stop signal.

Avoid when

  • One shared struct needs a short protected update.
  • Extra channels hide a straightforward operation.

Quick check

Who should close a channel?
How do you stop waiting after 30 seconds for a channel result?

Takeaways

  • Channels transfer values between goroutines.
  • Select waits on channel operations, including timer signals.
  • The sending side closes after all sends finish.

Try the quick check above whenever you feel ready.

Previous: Atomics & Read-Write Locks