Implement bounded concurrent processing
Implement bounded concurrent processing
An HTTP server may run many handlers concurrently. A semaphore is a limited number of permits for active work. A buffered channel of capacity N can represent N permits. For this synchronous service, try to acquire a slot without waiting; if full, return 503 and let the caller retry according to its policy. This bounds admitted processing, not the number of network connections or request goroutines. Also configure connection limits, request timeouts and body limits as appropriate for the deployment.
package main
import ( "fmt")
func acquire(slots chan struct{}) bool { select { case slots <- struct{}{}: return true default: return false }}func main() { slots := make(chan struct{}, 2) fmt.Println(acquire(slots), acquire(slots), acquire(slots)) <-slots fmt.Println(acquire(slots))}Only release a permit that was acquired. The channel is not closed while handlers may use it. A defer immediately after acquisition covers early returns. The nonblocking policy avoids an unbounded waiting queue; it intentionally rejects overload instead of guaranteeing FIFO fairness. Store capacity is a separate bound. A production admission policy may reserve capacity per tenant, but the example has no tenant model.
Expected output:
true true falsetrueJoin admitted work before shutdown
package main
import ( "fmt" "sync")
func run(slots chan struct{}, wg *sync.WaitGroup, done chan<- int, n int) { defer wg.Done() defer func() { <-slots }() done <- n * n}func main() { slots := make(chan struct{}, 2) done := make(chan int, 2) var wg sync.WaitGroup for _, n := range []int{2, 3} { slots <- struct{}{} wg.Add(1) go run(slots, &wg, done, n) } wg.Wait() close(done) sum := 0 for n := range done { sum += n } fmt.Println(sum, len(slots))}The result channel has room for all two results; otherwise waiting before consuming could deadlock. A general worker pool should consume concurrently and use cancellation-aware sends. WaitGroup joins accepted work but does not stop new arrivals; stop admission before waiting. For net/http, Server.Shutdown stops listeners and waits for active handlers within a context, but it does not join arbitrary background goroutines. Keep those lifetimes explicit.
Expected output:
13 0Try it locally
Write a tryRun helper that acquires one permit, defers its release and calls a function returning an error. Test error release and overload without sleeps.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capstone engineering 03: Implement bounded concurrent processing
Check the lesson objective before moving on.
A permit channel is full. What does nonblocking admission do?
Why defer permit release immediately after acquisition?