☰ All patterns
Semaphore
Limit how many goroutines do something at the same time.
01
Explain it like I'm new
Real-life analogy
A nightclub bouncer
The club holds 3 people. The bouncer lets someone in only when someone else leaves. Everyone else waits in line.
😩 The problem
You start 1,000 goroutines that each hit an API allowing only 3 concurrent requests. You get rate-limited or crash the server.
💡 The pattern
Use a buffered channel with capacity N as a semaphore. Send a token to acquire (blocks when full) and receive to release.
02
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
03
When should I use it?
✅ Reach for it when…
- •Rate-limited APIs, limited connections, memory-heavy tasks.
🚫 Skip it when…
- •You also need a fixed set of reusable workers. A worker pool may be clearer.
🐹 Go tip
struct{} takes zero bytes, which makes it the idiomatic 'signal only' channel element.
🌍 You've already seen it in
golang.org/x/sync/semaphore (weighted) and errgroup.SetLimit use the same idea.
04
Quick check
One question. No pressure.
With `sem := make(chan struct{}, 3)`, what happens to the 4th goroutine that does `sem <- struct{}{}`?
Related: Worker Pool, Context Cancellation