In modern distributed systems, protecting APIs from abuse is non-negotiable. Without rate limiting, a single client or a malicious actor can exhaust server resources through denial-of-service attacks or excessive resource consumption. While cloud providers offer managed solutions like AWS WAF or Azure API Management, understanding the underlying mechanics allows you to build robust, self-hosted middleware. This guide walks you through implementing the Token Bucket algorithm in Go, a classic and effective strategy for smoothing traffic bursts while maintaining steady throughput.
The Token Bucket algorithm works by granting tokens at a fixed rate into a bucket with a specific capacity. Each request consumes one token. If the bucket is empty, the request is rejected or delayed. This approach is superior to simple fixed-window counters because it allows for short bursts of traffic up to the bucket’s capacity before throttling kicks in.
Prerequisites and Environment Setup
Before writing code, ensure your environment supports Go development. You need a working Go installation (version 1.20 or later is recommended) and a text editor or IDE like VS Code with the Go extension.
To start immediately, create a new project directory:
mkdir rate-limiter-demo
cd rate-limiter-demo
go mod init ratelimit-demo
Initialize a main.go file to hold your logic. We will build a standalone binary that simulates an API server with built-in rate limiting.
Core Logic: The Token Bucket Structure
In Go, we define the bucket as a struct containing the current token count and the refill rate. We also need a mechanism to handle time-based refills.
package main
import (
"fmt"
"sync"
"time"
)
// TokenBucket represents the state of our limiter
type TokenBucket struct {
tokens float64
maxTokens float64
refillRate float64 // tokens per second
mu sync.Mutex
}
// NewTokenBucket initializes a new bucket with specific constraints
func NewTokenBucket(maxTokens, refillRate float64) *TokenBucket {
return &TokenBucket{
tokens: maxTokens,
maxTokens: maxTokens,
refillRate: refillRate,
}
}
// Refill adds tokens based on elapsed time
func (tb *TokenBucket) Refill() {
now := time.Now().UnixNano()
tb.mu.Lock()
defer tb.mu.Unlock()
// Calculate tokens to add based on time passed since last refill logic would go here
// For simplicity in this demo, we assume a global clock or pass delta time
// In production, store 'lastRefillTime' inside the struct.
}
Note: The above snippet outlines the structure. A complete implementation requires tracking lastRefillTime to calculate the exact amount of tokens to add based on time.Since(lastRefillTime).
Implementing the Refill and Consumption Mechanism
A critical aspect of this algorithm is calculating how many tokens have accumulated since the last check. We must ensure thread safety using a mutex to prevent race conditions when multiple goroutines (simulating concurrent API calls) access the bucket.
Here is a more complete implementation logic within your main.go:
type TokenBucket struct {
tokens float64
maxTokens float64
refillRate float64 // tokens per second
lastRefill time.Time
mu sync.Mutex
}
func NewTokenBucket(maxTokens, refillRate float64) *TokenBucket {
return &TokenBucket{
tokens: maxTokens,
maxTokens: maxTokens,
refillRate: refillRate,
lastRefill: time.Now(),
}
}
func (tb *TokenBucket) Consume() bool {
tb.mu.Lock()
defer tb.mu.Unlock()
now := time.Now()
elapsed := now.Sub(tb.lastRefill).Seconds()
tokensToAdd := elapsed * tb.refillRate
tb.tokens = min(tb.tokens+tokensToAdd, tb.maxTokens)
tb.lastRefill = now
if tb.tokens >= 1.0 {
tb.tokens -= 1.0
return true
}
return false
}
func min(a, b float64) float64 {
if a < b {
return a
}
return b
}
Building the API Server Simulation
Let’s create a simple HTTP server that accepts requests and checks the token bucket before processing. We will use the standard net/http package. This simulates an API endpoint like /api/data.
import (
"net/http"
)
var limiter = NewTokenBucket(10, 2.0) // 10 tokens max, refilling at 2 per second
func handleRequest(w http.ResponseWriter, r *http.Request) {
if !limiter.Consume() {
http.Error(w, "Too Many Requests: Rate limit exceeded", http.StatusTooManyRequests)
return
}
// Simulate processing time
time.Sleep(100 * time.Millisecond)
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Request processed successfully")
}
func main() {
http.HandleFunc("/api/data", handleRequest)
fmt.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}
Testing and Verification Steps
To verify the rate limiter works, you can run the server in one terminal and send requests using curl or httpie.
- Start the server: Run
go run main.go. - Send rapid requests: Execute a loop to send 15 requests quickly.
for i in {1..15}; do curl -s http://localhost:8080/api/data; echo ""; done
Expected Output (Illustrative):
You should see the first ~10 requests return “Request processed successfully.” Subsequent requests will immediately return a 429 status code with the message “Too Many Requests: Rate limit exceeded” until tokens refill.
Common Errors and Debugging Tips
When implementing this in production, several pitfalls often arise:
- Race Conditions: If you forget the
sync.Mutex, two goroutines might read the token count simultaneously, both see it is > 0, and both decrement it, effectively allowing double consumption. Always lock before reading or writing shared state. - Time Skew: Relying on system time can be tricky if servers have unsynchronized clocks. In microservices architectures, use a consensus clock (like CRDTs) or ensure all nodes are on the same network domain with NTP synchronized.
- Memory Leaks in Custom Implementations: If you implement sliding windows using history arrays, remember to clear old entries periodically to prevent memory growth.
Student Practice Task: Adding Metrics
For students or junior engineers looking to expand their project, try adding Prometheus metrics. Create a new file metrics.go that increments counters every time Consume() is called successfully versus when it fails. Expose an /metrics endpoint using the prometheus/promhttp package. This transforms your simple demo into an observability-ready component suitable for industry deployment.
Industry Application Checklist
Before deploying a custom rate limiter in a production environment, verify the following:
- [ ] Define Limits: Calculate the
refillRatebased on server CPU/RAM capacity and business logic (e.g., 100 requests/minute per user). - [ ] Storage Strategy: Decide between in-memory buckets (fast but not stateless across restarts) and distributed storage (Redis) for stateful limits.
- [ ] Graceful Degradation: Ensure the application returns a clear JSON error body explaining the limit, rather than a generic 500 Internal Server Error.
- [ ] Testing: Run load tests using tools like
k6orwrkto confirm the limiter behaves as expected under stress.
Conclusion
Implementing a Token Bucket algorithm in Go provides a balanced approach to API protection, allowing bursts while preventing exhaustion. By following these steps—defining the struct, handling thread-safe refills, building the handler, and verifying with load tests—you can create a resilient middleware component. Remember that terms like “rate limit” vary by jurisdiction and service level agreement; always document your limits clearly for your API consumers. This foundational knowledge prepares you to tackle more complex challenges in distributed system design.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

