Semaphore Pattern
Limiting concurrency with a channel semaphore
What is a semaphore?
A semaphore limits the number of goroutines performing an operation concurrently. It prevents resource exhaustion (e.g., too many open DB connections or outbound HTTP requests).
Buffered channel as semaphore
A buffered channel of capacity N acts as a counting semaphore. Acquiring sends to the channel (blocks when full); releasing receives from it.
sem := make(chan struct{}, 10)
func withSem(f func()) {
sem <- struct{}{} // acquire
defer func() { <-sem }() // release
f()
}