Implementing Rate Limiting

1. Using Token Bucket Algorithm

ParamMeaning
Rate (r/s)Sustained throughput
BurstMax bucket size; absorbs short spikes
TakeConsume token before allowing call

2. Implementing Rate Limit Interceptor

Example: Global rate limit

import "golang.org/x/time/rate"
limiter := rate.NewLimiter(rate.Limit(1000), 200) // 1000 r/s, burst 200
func RateLimit(ctx context.Context, req any, info *grpc.UnaryServerInfo,
    h grpc.UnaryHandler) (any, error) {
    if !limiter.Allow() {
        return nil, status.Error(codes.ResourceExhausted, "rate limit")
    }
    return h(ctx, req)
}

3. Using golang.org/x/time/rate Package

APIDetail
rate.NewLimiter(r, b)Create limiter
Allow()Non-blocking
Wait(ctx)Block until token (or ctx done)
Reserve()Returns delay until next allow

4. Setting Rate Limit per Client

Example: Per-API-key limiter

var limiters sync.Map // key → *rate.Limiter
func getLimiter(k string) *rate.Limiter {
    l, ok := limiters.Load(k)
    if !ok {
        l, _ = limiters.LoadOrStore(k, rate.NewLimiter(50, 10))
    }
    return l.(*rate.Limiter)
}

5. Returning ResourceExhausted Status

DetailValue
Status codecodes.ResourceExhausted
Hint headerInclude retry-after trailer
Error detailerrdetails.RetryInfo

6. Implementing Sliding Window

VariantDetail
Fixed windowCounter resets each interval
Sliding window logStore timestamps; precise but memory-heavy
Sliding window counterWeighted average of two windows — common balance

7. Using Redis for Distributed Limiting

Example: Redis token bucket (Lua)

EVAL "local n = redis.call('INCR', KEYS[1]) \
  if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end \
  return n" 1 user:u123:rl 60
LibraryDetail
go-redis/redis_rateBuilt-in algos
Envoy global RLSidecar pattern

8. Adding Rate Limit Headers

HeaderPurpose
x-ratelimit-limitMax in window
x-ratelimit-remainingRemaining tokens
x-ratelimit-resetSeconds until reset

9. Implementing Per-Method Limits

ApproachDetail
Method → limiter mapDifferent rate per RPC
Cost weightingExpensive methods consume more tokens

10. Configuring Burst Size

GuidelineDetail
Burst ≈ 10–25% of rateAbsorbs short spikes
High burstTolerates bursty workloads but risks overload