Implementing a rate limiter using the token bucket algorithm in Go is a great way to control the rate of requests in your application. Below is a simple implementation of a token bucket rate limiter.
Token Bucket Rate Limiter Implementation
package main
import (
"fmt"
"sync"
"time"
)
// TokenBucket represents a token bucket rate limiter.
type TokenBucket struct {
capacity int // Maximum number of tokens in the bucket
tokens int // Current number of tokens
rate int // Rate of token generation (tokens per second)
lastCheck time.Time // Last time tokens were added
mu sync.Mutex // Mutex for thread-safe access
}
// NewTokenBucket creates a new TokenBucket with the specified capacity and rate.
func NewTokenBucket(capacity, rate int) *TokenBucket {
return &TokenBucket{
capacity: capacity,
tokens: capacity, // Start with a full bucket
rate: rate,
lastCheck: time.Now(),
}
}
// Allow checks if a token can be consumed and consumes it if possible.
func (tb *TokenBucket) Allow() bool {
tb.mu.Lock()
defer tb.mu.Unlock()
// Refill tokens based on the elapsed time
now := time.Now()
elapsed := now.Sub(tb.lastCheck).Seconds()
tb.lastCheck = now
// Calculate the number of tokens to add
newTokens := int(elapsed * float64(tb.rate))
if newTokens > 0 {
tb.tokens += newTokens
if tb.tokens > tb.capacity {
tb.tokens = tb.capacity // Cap tokens to the bucket's capacity
}
}
// Check if we can allow a request
if tb.tokens > 0 {
tb.tokens-- // Consume a token
return true
}
return false // No tokens available
}
func main() {
rateLimiter := NewTokenBucket(5, 1) // 5 tokens capacity, 1 token per second
for i := 0; i < 10; i++ {
if rateLimiter.Allow() {
fmt.Println("Request allowed:", i)
} else {
fmt.Println("Request denied:", i)
}
time.Sleep(200 * time.Millisecond) // Simulate some delay between requests
}
}
Explanation
-
TokenBucket Struct: This struct holds the state of the token bucket, including its capacity, current number of tokens, the rate at which tokens are generated, and the last time tokens were added.
-
NewTokenBucket Function: This function initializes a new token bucket with a specified capacity and rate.
-
Allow Method: This method checks if a token can be consumed. It refills the bucket based on the elapsed time since the last check, and if there are tokens available, it consumes one and returns true. If no tokens are available, it returns false.
-
Main Function: In the main function, we create a token bucket with a capacity of 5 tokens and a rate of 1 token per second. We then simulate 10 requests, checking if each request is allowed or denied, with a small delay between requests.
Usage
You can run this code in a Go environment. It will print whether each request is allowed or denied based on the token bucket algorithm. Adjust the capacity and rate as needed for your specific use case.