Limit goroutines with buffered channels
I was cobbling together a long-running Go script to send webhook messages to a system when some events occur. The initial script would continuously poll a Kafka topic for events and spawn worker goroutines in a fire-and-forget manner to make HTTP requests to the destination. This had two problems: It could create unlimited goroutines if many events arrived quickly (no backpressure) It might overload the destination system by making many concurrent requests (no concurrency control) In Python, I’d use just asyncio.Semaphore to limit concurrency. I’ve previously written about limiting concurrency with semaphores. Turns out, in Go, you could do the same with a buffered channel. Here’s how the naive version without any concurrency control looks: ...