Skip to main content

Concurrent streaming in Go with channels

· 6 min read
Yaroslav Grebnov
Golang developer, SDET

The previous exercises map a finite slice with sync.WaitGroup or errgroup. This version processes values as they arrive. The input size does not need to be known, and successful results can be consumed before the input channel closes.

Stream accepts a receive-only input channel and returns separate receive-only result and error channels. A fixed worker pool bounds concurrency.

Task​

Initial task​

Implement a generic Stream function that reads values from an input channel, applies fn, and publishes successful values and errors on two output channels.

Write main so it sends sample input and listens to both outputs, printing each value or error as soon as it arrives.

Follow-up 1: bounded concurrency​

Use a fixed number of workers. The stream may be large or unbounded, so the implementation must not create one goroutine per input value.

Follow-up 2: cancellation and channel lifecycle​

Stop workers through context.Context. Close both output channels after all workers exit without risking a send on a closed channel. The input producer must also stop when the context is canceled.

Follow-up 3: errors and panics​

Publish ordinary task errors on the error channel. Recover a panic around one task call so the worker can continue processing later values.

The code below is the final version after all follow-ups. It uses Go 1.25, as specified in the example module.

Solution​

package main

import (
"context"
"errors"
"fmt"
"runtime"
"sync"
)

func Stream[T, R any](
ctx context.Context,
input <-chan T,
concurrency int,
fn func(context.Context, T) (R, error),
) (<-chan R, <-chan error) {
if concurrency <= 0 {
// NumCPU is a reasonable CPU-work default. I/O workloads usually need a
// separately measured limit because they spend much of their time waiting.
concurrency = runtime.NumCPU()
}

// Small bounded buffers let workers finish a send during short consumer stalls.
// They do not provide unlimited storage: callers must drain both outputs or
// cancel ctx, otherwise every worker can eventually block on a full channel.
results := make(chan R, concurrency)
errs := make(chan error, concurrency)

// A channel-only API reports setup failures through the error stream. Only this
// producer closes these output channels; receivers must never close them.
if input == nil {
close(results)
errs <- errors.New("input must not be nil")
close(errs)
return results, errs
}
if fn == nil {
close(results)
errs <- errors.New("fn must not be nil")
close(errs)
return results, errs
}

var wg sync.WaitGroup
// A fixed worker count bounds goroutine and stack overhead. Unlike the slice
// versions, Stream can process an input whose size is unknown or unbounded.
wg.Add(concurrency) // Add before go; adding inside a worker can race with Wait.
for range concurrency {
go func() {
defer wg.Done()

for {
var item T
var ok bool
select {
case <-ctx.Done():
// Cancellation is a control signal, not one task error per worker.
// The context owner can inspect ctx.Err() after the streams close.
return
case item, ok = <-input:
if !ok {
return // the input owner closed the stream
}
}

// Cancellation can race with the receive above. Avoid starting new work
// after it is observed; fn must still check ctx if cancellation happens later.
if ctx.Err() != nil {
return
}

result, err := streamCall(ctx, item, fn)
if err != nil {
select {
case errs <- err:
case <-ctx.Done():
return
}
continue
}

select {
case results <- result:
case <-ctx.Done():
return
}
}
}()
}

// Workers send, so they cannot close shared outputs individually: one worker
// could close a channel while another is sending and cause a panic. One closer
// waits for every worker, then closes both channels exactly once.
go func() {
wg.Wait()
close(results)
close(errs)
}()

// Direction-only channels prevent callers from sending or closing by mistake.
// Results arrive in completion order. Preserving input order would require a
// sequence number plus reordering, which also requires buffering pending results.
// Separate result and error channels also lose item-to-error correlation; return
// one event struct containing identity, value, and error when that relation matters.
return results, errs
}

func streamCall[T, R any](
ctx context.Context,
item T,
fn func(context.Context, T) (R, error),
) (result R, err error) {
// Recover around one call rather than the whole worker so a panicking item does
// not kill that worker. recover must execute on the goroutine where the panic occurs.
defer func() {
if rErr := recover(); rErr != nil {
err = fmt.Errorf("execution panicked: %v", rErr)
}
}()
return fn(ctx, item)
}

var ErrTest = errors.New("ErrTest")

// task simulates success, an ordinary error, and a panic for the demo.
func task(ctx context.Context, i int) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
}

if i == 2 {
return 0, ErrTest
}
if i == 3 {
panic("panic")
}

return i * i, nil
}

The output channels contain completion order rather than input order. This lets the consumer handle fast results without waiting for earlier slow items. When ordering or item-to-error identity is required, send one event struct with a sequence number and reorder at the consumer.

Main​

main owns the input channel and therefore closes it. Stream owns and closes both output channels.

package main

import (
"context"
"fmt"
)

func main() {
ctx := context.Background()
input := make(chan int)

go func() {
defer close(input) // the sender owns and closes the input channel
for _, item := range []int{1, 2, 3, 4} {
// If Stream exits on cancellation, the producer must stop sending too,
// otherwise it can remain blocked forever with no receiver.
select {
case input <- item:
case <-ctx.Done():
return
}
}
}()

results, errs := Stream(ctx, input, 3, task)
for results != nil || errs != nil {
select {
case result, ok := <-results:
if !ok {
// Receiving from a closed channel is always ready. Set it to nil to
// disable this select case and avoid a busy loop.
results = nil
continue
}
fmt.Printf("result: %d\n", result)
case err, ok := <-errs:
if !ok {
errs = nil
continue
}
fmt.Printf("error: %v\n", err)
}
}
}

Assigning a closed channel variable to nil is important. A receive from a closed channel is always ready, while a receive from a nil channel is permanently disabled. The loop ends only after both outputs have closed.

Test​

The nominal test sends three successful inputs. Because output order depends on scheduling, it sorts the collected results before comparison.

package main

import (
"context"
"reflect"
"slices"
"testing"
)

func TestStream(t *testing.T) {
input := make(chan int, 3)
input <- 1
input <- 4
input <- 5
close(input)

results, errs := Stream(context.Background(), input, 3, task)
var actual []int
for results != nil || errs != nil {
select {
case result, ok := <-results:
if !ok {
results = nil
continue
}
actual = append(actual, result)
case err, ok := <-errs:
if !ok {
errs = nil
continue
}
t.Fatalf("unexpected error: %v", err)
}
}

// Stream emits completion order, so compare the nominal results as a set.
slices.Sort(actual)
expected := []int{1, 16, 25}
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("expected %v, got %v", expected, actual)
}
}

Run it with the race detector because workers publish concurrently:

$ go test -race -count=1 ./...
ok github.com/ygrebnov/test-concurrency6

Output example​

One possible run is:

$ go run .
result: 1
result: 16
error: ErrTest
error: execution panicked: panic

The two successful values and two errors are stable, but their order may change between runs. The burst-tolerant HTTP handler uses a related fixed-capacity idea at request admission rather than over an input stream.