Bounded Channel Backpressure
Connect a fast producer to a slow consumer through a small buffered channel, then stop the pipeline cleanly on deadline.
Code
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
func produce(ctx context.Context, out chan<- int, total int) error {
for i := 1; i <= total; i++ {
select {
case out <- i:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func consume(ctx context.Context, in <-chan int, delay time.Duration) ([]int, error) {
var seen []int
for {
select {
case value, ok := <-in:
if !ok {
return seen, nil
}
time.Sleep(delay)
seen = append(seen, value)
case <-ctx.Done():
return seen, ctx.Err()
}
}
}
func runPipeline(total, buffer int, delay, budget time.Duration) ([]int, error) {
ctx, cancel := context.WithTimeout(context.Background(), budget)
defer cancel()
queue := make(chan int, buffer)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
defer close(queue)
if err := produce(ctx, queue, total); err != nil && !errors.Is(err, context.DeadlineExceeded) {
fmt.Println("producer stopped:", err)
}
}()
seen, err := consume(ctx, queue, delay)
wg.Wait()
return seen, err
}
func main() {
start := time.Now()
seen, err := runPipeline(10, 2, 20*time.Millisecond, 5*time.Second)
fmt.Printf("consumed %d items in %s (err=%v)\n", len(seen), time.Since(start).Round(10*time.Millisecond), err)
short, err := runPipeline(10, 2, 20*time.Millisecond, 60*time.Millisecond)
fmt.Printf("budget run consumed %d items, deadline=%v\n", len(short), errors.Is(err, context.DeadlineExceeded))
}A tour of the logic
Everything that executes sits inside the functions produce, consume, runPipeline and main.
Iteration happens inside for i := 1; i <= total; i++ — everything outside it runs once. Error handling is inline: 1 place test err != nil and branch immediately. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
What to watch for
- Zero third-party dependencies — the runtime provides every API used here.
- There are no exceptions to catch —
errreturn values must be checked at each call site.
Using it
The main signature is written as func produce(ctx context.Context, out chan<- int, total int) error
The output comes back labeled — producer stopped:, consumed, budget run consumed — when the file runs.
Execute the file and main walks through runPipeline, in that order.
Key statements
func produce(ctx context.Context, out chan<- int, total int) error {
for i := 1; i <= total; i++ {
select {
case out <- i:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
if err := produce(ctx, queue, total); err != nil && !errors.Is(err, context.DeadlineExceeded) {
fmt.Println("producer stopped:", err)
}
return seen, ctx.Err()
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- By return value: each fallible call hands back an `error`, checked at 1 place here.
- What does Bounded Channel Backpressure print when run?
- Execute the whole file; each printed line is prefixed with a label like `producer stopped:`, `consumed`, `budget run consumed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.