Limit concurrency and rates
Limit concurrency and rates
A concurrency limit bounds how many tasks are active at once. A rate limit controls how frequently tasks start. Two active tasks does not mean two tasks per second. A buffered channel acts as a counting semaphore: send to acquire, receive to release.
package main
import ( "fmt" "sync")
func main() { slots := make(chan struct{}, 2) var wg sync.WaitGroup var active, peak int var mu sync.Mutex for i := 0; i < 6; i++ { slots <- struct{}{} wg.Add(1) go func() { defer wg.Done() defer func() { <-slots }() mu.Lock() active++ if active > peak { peak = active } mu.Unlock() mu.Lock() active-- mu.Unlock() }() } wg.Wait() fmt.Println(active, peak <= 2, len(slots))}Acquire before launching so the caller experiences backpressure. The empty struct is a token, not job data. Deferred release returns capacity on exit. Peak may be one or two; only the upper bound is guaranteed. Use select with context Done for cancellable acquisition and reject nonpositive capacities.
Expected output:
0 true 0Pace starts with a ticker
package main
import ( "fmt" "time")
func main() { ticker := time.NewTicker(5 * time.Millisecond) defer ticker.Stop() for i := 1; i <= 3; i++ { <-ticker.C fmt.Println("start", i) }}Wait for a tick before each start. Tick delivery may be delayed or dropped for slow receivers; pending ticks may be received immediately. This is pacing, not an exact distributed rate limiter. A token bucket defines a refill rate and burst capacity; production limiters also need cancellation and clock policies.
Expected output:
start 1start 2start 3Try it locally
Acquire two slots, detect full with select default, release one and acquire again. Print full and true.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 04: Limit concurrency and rates
Check the lesson objective before moving on.
What does capacity two bound?
Why acquire before launching?