Golang / GoLang Concurrency Mastery Interview Questions
How do you implement backpressure in Go to prevent overloading downstream systems?
Backpressure is the mechanism by which a slow consumer signals a fast producer to slow down. Without it, producers overwhelm consumers, causing unbounded queue growth, OOM, or cascading failures. Go's channels provide natural backpressure — the most important property to communicate in interviews.
// Pattern 1: bounded channel — natural backpressure
func pipeline(ctx context.Context, input <-chan Item) {
output := make(chan ProcessedItem, 100) // backpressure kicks in at 100
go func() {
defer close(output)
for item := range input {
result := process(item)
select {
case output <- result: // blocks if consumer is slow
case <-ctx.Done(): return
}
}
}()
for item := range output {
writeToDatabase(item) // slow consumer — pressure propagates upstream
}
}
// Pattern 2: rate limiter (golang.org/x/time/rate — token bucket)
limiter := rate.NewLimiter(rate.Limit(100), 10) // 100 req/s, burst 10
func rateLimitedHandler(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
http.Error(w, "429 Too Many Requests", http.StatusTooManyRequests)
return
}
// ... handle request
}
// Pattern 3: blocking acquire with context
if err := limiter.Wait(ctx); err != nil {
return err // backpressure: context expired waiting for a token
}
// Pattern 4: non-blocking drop (best-effort)
select {
case queue <- item: // queue has space
default: // queue full — drop or return 429
log.Println("dropping item — queue full")
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
