In-memory rate limiter middleware in Go
WHAT IT TESTS: rate limiting and middleware design. OUTLINE: use a token-bucket limiter (golang.org/x/time/rate), guard a per-client map with sync.Mutex, wrap http.Handler so requests over the limit get 429.
WHAT IT TESTS: building a concurrent rate limiter and wiring it as middleware. ANSWER OUTLINE: use the token-bucket Limiter from golang.org/x/time/rate, which allows a steady rate plus burst. Keep a map from client key, such as IP, to a limiter, protected by a sync.Mutex or sync.Map for concurrent access. The middleware wraps an http.Handler: on each request look up the client's limiter and call Allow; if false write 429 Too Many Requests, else call the next handler.
Read the original → interview
- #go
- #rate-limiting
- #middleware
- #concurrency
- #http
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.