go
52 lines · 8 steps
The fan-in pattern in Go channels
How to merge many channels into one and collect from several sources without leaks or deadlocks.
Explained by
highlit
1package pipeline
2
3import "sync"
4
5func mergeMetrics(sources ...<-chan Metric) <-chan Metric {
6 out := make(chan Metric)
7 var wg sync.WaitGroup
8
9 drain := func(src <-chan Metric) {
10 defer wg.Done()
11 for m := range src {
12 out <- m
13 }
14 }
15
16 wg.Add(len(sources))
17 for _, src := range sources {
18 go drain(src)
19 }
20
21 go func() {
22 wg.Wait()
23 close(out)
24 }()
25
26 return out
27}
28
29func collect(primary, fallback <-chan Metric, done <-chan struct{}) []Metric {
30 var collected []Metric
31 for {
32 select {
33 case m, ok := <-primary:
34 if !ok {
35 primary = nil
36 break
37 }
38 collected = append(collected, m)
39 case m, ok := <-fallback:
40 if !ok {
41 fallback = nil
42 break
43 }
44 collected = append(collected, m)
45 case <-done:
46 return collected
47 }
48 if primary == nil && fallback == nil {
49 return collected
50 }
51 }
52}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A WaitGroup that closes the output channel once all producers finish is the safe way to signal completion in a fan-in.
- 2Setting a channel variable to nil in a select disables that case, letting you wind down partial sources cleanly.
- 3Combining a done channel with drained-source detection gives you two independent ways to stop collecting.
Related explainers
go
package metrics import ( "sync"
A thread-safe sliding-window average in Go
concurrency
sliding-window
running-average
Intermediate
8 steps
go
package logging import ( "fmt"
Redacting secrets with Go reflection
reflection
recursion
struct-tags
Advanced
10 steps
java
public class RequestThrottler { private final Semaphore permits; private final long acquireTimeoutMillis;
Bounding concurrency with a Semaphore in Java
concurrency
semaphore
rate-limiting
Intermediate
6 steps
python
import time import threading from flask import Flask, request, jsonify, g
A token-bucket rate limiter in Flask
rate-limiting
token-bucket
middleware
Intermediate
7 steps
go
package middleware import ( "context"
Per-tenant daily rate limiting in Gin
rate-limiting
middleware
redis
Intermediate
8 steps
ruby
class Document < ApplicationRecord class StaleObjectError < StandardError def initialize(id) super("Document ##{id} was modified by another process")
Optimistic locking with retries in Rails
optimistic-locking
concurrency
transactions
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/the-fan-in-pattern-in-go-channels-explained-go-967f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.