Go rate limiting protects your API by limiting how many requests each client can send in a given time. In this post, you will learn what a token bucket is and why it works so well. Then we will build a per-client limiter as middleware, and we will test it with real output.
This lesson uses Go middleware examples, so read that post if middleware is new. We also use a mutex from Go sync package with WaitGroup and Mutex. In addition, the handler style comes from Go HTTP server basics.
What Is Go Rate Limiting?
In short, rate limiting means you allow only a fixed number of requests in a period of time. If a client sends too many, the server answers with status 429, which means “Too Many Requests”. Then the client has to wait.
Think of a water tap with a small bucket under it. The tap adds one drop per second. Each request takes one drop from the bucket. When the bucket is empty, the next request must wait for a new drop. Meanwhile, the bucket can hold only a few drops, so a long quiet time does not give unlimited credit.
This idea is called a token bucket. It is simple, fast and fair. As a result, most real systems use it, including many cloud APIs. For example, a free plan might allow 60 calls per minute, while a paid plan allows 600. Both plans can use the same Go rate limiting code with different numbers.
Why Go Rate Limiting Matters
Without limits, one noisy client can slow down everyone else. For example, a buggy script that retries in a tight loop can send thousands of calls per second. So here is what Go rate limiting gives you.
- Protection from overload: a burst of traffic cannot crush your database.
- Fair sharing: every client gets a similar share of your capacity.
- Defence against abuse: password guessing and scraping become much slower.
- Predictable costs: calls to paid services stay under control.
- Better uptime: your API keeps working during traffic spikes.
Because of this, rate limiting is a basic part of any public API. In fact, security reviews often ask about it first. However, it also helps internal services, because one broken service can otherwise flood another.
How Go Rate Limiting Works
In Go rate limiting, the token bucket has two numbers. First, the capacity is the largest burst the bucket allows. Second, the refill rate is how many tokens are added each second. When a request arrives, the code first adds the tokens earned since the last check. Then it tries to take one token. If a token is available, the request goes through. Otherwise, the request is rejected.

Notice that nothing needs a background timer. Instead, the bucket calculates the new tokens from the time that has passed. As a result, it uses almost no CPU, even with thousands of clients. That is why this design is popular in Go rate limiting libraries.
Burst and Rate
These two settings control how the limiter feels to a user. The table below explains them with examples.
| Setting | Meaning | Example |
|---|---|---|
| Capacity (burst) | Most requests allowed at once | 3 |
| Rate | Tokens added per second | 1 |
| Result | Fast start, then a steady pace | 3 quick calls, then 1 per second |
So a burst of 3 and a rate of 1 means a user can send three quick requests. After that, they get one new request every second. Choose the burst for how spiky normal users are, and choose the rate for how much load you can carry.
Where to Keep the Buckets
A fair limiter needs one bucket for each client, usually keyed by IP address or API key. Therefore, keep a map from key to bucket, and protect the map with a mutex. Otherwise, many requests could write to the map at the same time.
Go Rate Limiting: Token Bucket vs Fixed Window
There are two popular ways to count requests. The table below compares them.
| Feature | Token bucket | Fixed window |
|---|---|---|
| Idea | Tokens refill steadily | A counter resets every minute |
| Allows bursts | Yes, up to the capacity | Yes, and double bursts at window edges |
| Memory per client | Two numbers | One number |
| Smoothness | Smooth | Can feel jumpy |
| Best for | Most public APIs | Very simple daily or hourly quotas |

So when should you use which? Use a token bucket for most APIs, because it is smooth and fair. On the other hand, a fixed window is fine for simple quotas, such as “1000 calls per day”.
Go Rate Limiting Hands-On: Per-IP Middleware
Now let’s build a limiter with only the standard library. It allows a burst of 3 requests and refills 1 token per second for every IP address.
Step 1: The Token Bucket
First, here is the bucket. It stores the tokens, the capacity, the refill rate and the time of the last check.
type Bucket struct {
mu sync.Mutex
tokens float64
capacity float64
rate float64 // tokens added per second
last time.Time
}
func NewBucket(capacity, ratePerSec float64) *Bucket {
return &Bucket{tokens: capacity, capacity: capacity, rate: ratePerSec, last: time.Now()}
}
func (b *Bucket) Allow() bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
b.tokens += now.Sub(b.last).Seconds() * b.rate
if b.tokens > b.capacity {
b.tokens = b.capacity
}
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
Let’s walk through Allow. First, it adds the tokens earned since the last call. Then it caps the total at the capacity, so a long pause cannot save up unlimited tokens. Finally, it takes one token if there is at least one, and otherwise it returns false. Also, the mutex inside the bucket makes the method safe when many goroutines call it at once.
Step 2: One Bucket per Client
Next, the Limiter creates a bucket the first time it sees an IP address.
type Limiter struct {
mu sync.Mutex
buckets map[string]*Bucket
capacity float64
rate float64
}
func NewLimiter(capacity, rate float64) *Limiter {
return &Limiter{buckets: map[string]*Bucket{}, capacity: capacity, rate: rate}
}
func (l *Limiter) get(ip string) *Bucket {
l.mu.Lock()
defer l.mu.Unlock()
b, ok := l.buckets[ip]
if !ok {
b = NewBucket(l.capacity, l.rate)
l.buckets[ip] = b
}
return b
}
Step 3: The Middleware
Then the middleware reads the client IP, asks the bucket and either calls the next handler or returns 429.
func (l *Limiter) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
if !l.get(ip).Allow() {
w.Header().Set("Retry-After", "1")
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
The Retry-After header tells well-behaved clients how many seconds to wait. Also, net.SplitHostPort removes the port, so one user is not counted as many. Without that step, each new connection would get its own bucket, and the limit would never trigger.
Step 4: Try It
Finally, we send five requests from one IP, one from a second IP and one more after waiting. Here is the real output.
request 1 from 10.0.0.1: 200
request 2 from 10.0.0.1: 200
request 3 from 10.0.0.1: 200
request 4 from 10.0.0.1: 429
request 5 from 10.0.0.1: 429
request 1 from 10.0.0.2: 200
after 1.1s from 10.0.0.1: 200
The first three requests use the burst. After that, requests 4 and 5 get a 429. Meanwhile, the second IP has its own full bucket. After waiting 1.1 seconds, the first IP has earned one new token, so it succeeds again.
Step 5: Use the Official Package
In production, many teams use the golang.org/x/time/rate package instead of writing their own bucket. First, install it with go get golang.org/x/time/rate. Then the same limit looks like this.
limiter := rate.NewLimiter(rate.Limit(1), 3) // 1 token per second, burst of 3
if !limiter.Allow() {
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
This package also has Wait and Reserve, which let a request sleep until a token is ready. It is well tested, so it is a good default choice. Even so, writing the bucket yourself once is a great way to understand how Go rate limiting really works.
Common Mistakes with Go Rate Limiting
- One global limit for everyone: a single noisy client then blocks all others. So keep one bucket per client.
- **Trusting
X-Forwarded-Forblindly**: attackers can fake it. Therefore, read it only behind a proxy you control. - Never removing old buckets: the map then grows forever. Instead, delete buckets that have been idle for a while.
- Using a map without a lock: concurrent writes can crash the program. So protect it with a mutex.
- Limits in memory only: with many servers, each one counts alone. In that case, use a shared store such as Redis.
Best Practices for Go Rate Limiting
- **Return 429 with
Retry-After**, because clients can then back off politely. - Use different limits for different routes, since login needs stricter limits than reads. A login route might allow 5 tries per minute.
- Clean up idle buckets, so memory stays flat.
- Log rejected requests, because spikes often show an attack or a buggy client.
- Test with a fake clock, since sleeping in tests is slow.
- Document your limits, so API users know what to expect.
Practice Task
To practise Go rate limiting, add a cleanup goroutine to the Limiter. Every minute it should remove buckets that were not used in the last five minutes. Then test it with a short time, such as one second, so you do not wait.
Hint: store a lastSeen time in each bucket. After that, loop over the map with the lock held and delete old entries. Finally, stop the goroutine with a context.
Official Resources
These pages cover the rate package and the HTTP status code used in this lesson.
- golang.org/x/time/rate package documentation
- MDN: 429 Too Many Requests
- net/http package documentation
Quick Recap
- Go rate limiting caps how many requests a client can send.
- A token bucket has a capacity for bursts and a refill rate.
- The bucket works out new tokens from elapsed time, so it needs no timer.
- Keep one bucket per client and guard the map with a mutex.
- Return 429 with a
Retry-Afterheader when the bucket is empty. - Use
golang.org/x/time/ratein production and Redis for many servers.
What’s Next?
By now, you can protect an API from overload. Next, we will switch to the browser side and learn how to render safe HTML pages with Go templates.
Next up: Go HTML templates for web pages


