Designing Concurrent Rate Limiters in Go

10 minute read

Every backend service has a finite capacity.

A service might handle thousands of requests per second under normal conditions, but a sudden traffic spike, misbehaving client, or automated retry storm can overwhelm its resources.

Rate limiting provides a mechanism to control how frequently clients can access a service.

It protects application resources, prevents individual clients from monopolizing capacity, and helps maintain predictable service behaviour under load.

But implementing a rate limiter in a concurrent Go application introduces several interesting challenges:

  • How do we track request rates safely across goroutines?
  • Which rate-limiting algorithm should we use?
  • How do we enforce limits per client or tenant?
  • What happens when the application runs across multiple instances?

In this article, we’ll build a token-bucket rate limiter in Go and explore how the design evolves from a single process to a distributed system.

1. Understanding rate-limiting algorithms

Before implementing a rate limiter, we need to understand the available algorithms.

There are several common approaches.

Fixed window counter

Counts requests within a fixed time interval.

For example, a client can make 100 requests per minute.

The implementation is simple, but it has a boundary problem. A client could make 100 requests just before a window expires and another 100 immediately after it resets.

This can result in nearly twice the intended request volume over a short period.

Sliding window

Tracks requests over a rolling time interval rather than resetting at fixed boundaries.

This provides smoother enforcement but requires more bookkeeping, depending on the implementation.

Token bucket

Maintains a bucket of tokens that refill at a configured rate.

Each incoming request consumes one token. If no tokens are available, the request is rejected.

The bucket also has a maximum capacity, allowing controlled bursts of traffic.

Leaky bucket

Processes incoming requests at a controlled rate, smoothing bursts into a more consistent output flow.

Each algorithm solves a slightly different problem.

For this article, we’ll focus on the token bucket algorithm because it provides a useful balance between burst tolerance, implementation complexity, and throughput control.

2. Understanding the token bucket

Imagine a bucket with a capacity of 10 tokens.

  • The bucket starts with 10 tokens.
  • Every request consumes one token.
  • Tokens are replenished at a configured rate.
  • The bucket cannot hold more than its maximum capacity.
  • Requests are rejected when no tokens remain.

Suppose we configure:

  • Capacity: 10 requests.
  • Refill rate: 5 requests per second.

A client can immediately make 10 requests. After exhausting the bucket, it can make additional requests as tokens become available.

This allows short bursts while controlling the average request rate over time.

The important distinction is that the bucket capacity controls burst size, while the refill rate controls sustained traffic.

3. Implementing a token bucket in Go

Let’s start with a basic implementation.

We need to maintain three pieces of state:

  • Current token count.
  • Maximum bucket capacity.
  • Last time the bucket was updated.

We’ll also maintain the refill rate.

package main

import (
    "sync"
    "time"
)

type Limiter struct {
    mu     sync.Mutex
    rate   float64
    burst  float64
    tokens float64
    last   time.Time
}

func NewLimiter(rate float64, burst int) *Limiter {
    if rate <= 0 || burst <= 0 {
        panic("rate and burst must be positive")
    }

    now := time.Now()

    return &Limiter{
        rate:   rate,
        burst:  float64(burst),
        tokens: float64(burst),
        last:   now,
    }
}

func (l *Limiter) Allow() bool {
    l.mu.Lock()
    defer l.mu.Unlock()

    now := time.Now()

    elapsed := now.Sub(l.last).Seconds()

    l.tokens += elapsed * l.rate

    if l.tokens > l.burst {
        l.tokens = l.burst
    }

    l.last = now

    if l.tokens < 1 {
        return false
    }

    l.tokens--
    return true
}

Let’s understand what’s happening.

Token replenishment

elapsed := now.Sub(l.last).Seconds()
l.tokens += elapsed * l.rate

We calculate how much time has passed since the previous update and replenish tokens accordingly.

Burst protection

if l.tokens > l.burst {
    l.tokens = l.burst
}

The bucket cannot accumulate more tokens than its configured capacity.

Request admission

if l.tokens < 1 {
    return false
}

l.tokens--
return true

A request is accepted only if at least one token is available.

Concurrency safety

The mutex protects all mutable bucket state.

Without synchronization, two goroutines could read the same token count and both consume the same token, allowing more requests than intended.

The critical section ensures that token replenishment and consumption happen atomically from the application’s perspective.

This implementation is intentionally small, but it demonstrates the core algorithm.

4. Integrating the limiter into an HTTP service

A rate limiter becomes useful when it can control incoming requests.

Go’s HTTP middleware pattern provides a natural integration point.

func RateLimit(
    limiter *Limiter,
    next http.Handler,
) http.Handler {
    return http.HandlerFunc(func(
        w http.ResponseWriter,
        r *http.Request,
    ) {
        if !limiter.Allow() {
            w.Header().Set("Retry-After", "1")

            http.Error(
                w,
                "rate limit exceeded",
                http.StatusTooManyRequests,
            )
            return
        }

        next.ServeHTTP(w, r)
    })
}

We can attach the middleware to an endpoint:

func main() {
    limiter := NewLimiter(5, 10)

    mux := http.NewServeMux()

    mux.HandleFunc("/api/payments", func(
        w http.ResponseWriter,
        r *http.Request,
    ) {
        w.Write([]byte("Request accepted"))
    })

    handler := RateLimit(limiter, mux)

    http.ListenAndServe(":8080", handler)
}

This example creates a single limiter shared by all incoming requests.

It allows a burst of 10 requests and replenishes tokens at 5 per second.

However, this implementation applies one global limit to the entire process.

In many applications, that isn’t what we want.

5. Per-client and per-tenant rate limiting

Consider a multi-tenant backend service.

If one tenant generates excessive traffic, we don’t necessarily want to reject requests from every other tenant.

Instead, each tenant should have an independent rate limit.

The architecture changes from one shared bucket to a collection of buckets:

              Incoming Request
                      |
                      v
                Identify Tenant
                      |
                      v
                Limiter Registry
                 /      |      \
                v       v       v
           Tenant A  Tenant B  Tenant C
           Bucket    Bucket    Bucket

A simple registry can maintain one limiter per tenant:

type LimiterRegistry struct {
    mu       sync.Mutex
    limiters map[string]*Limiter
    rate     float64
    burst    int
}

func NewRegistry(rate float64, burst int) *LimiterRegistry {
    return &LimiterRegistry{
        limiters: make(map[string]*Limiter),
        rate:     rate,
        burst:    burst,
    }
}

func (r *LimiterRegistry) Get(
    tenantID string,
) *Limiter {
    r.mu.Lock()
    defer r.mu.Unlock()

    limiter, exists := r.limiters[tenantID]

    if !exists {
        limiter = NewLimiter(r.rate, r.burst)
        r.limiters[tenantID] = limiter
    }

    return limiter
}

The middleware can now retrieve the appropriate limiter based on the authenticated tenant:

func TenantRateLimit(
    registry *LimiterRegistry,
    next http.Handler,
) http.Handler {
    return http.HandlerFunc(func(
        w http.ResponseWriter,
        r *http.Request,
    ) {
        tenantID := authenticatedTenantID(r)

        limiter := registry.Get(tenantID)

        if !limiter.Allow() {
            http.Error(
                w,
                "tenant rate limit exceeded",
                http.StatusTooManyRequests,
            )
            return
        }

        next.ServeHTTP(w, r)
    })
}

Here, authenticatedTenantID represents application-specific authentication middleware that supplies a trusted tenant identity.

In a real service, we must also consider the lifecycle of these limiters.

A map that creates a new limiter for every tenant can grow indefinitely if tenant identifiers are unbounded.

Production implementations need an eviction strategy, expiration, or a bounded registry.

The registry mutex can also become a contention point under heavy traffic. More sophisticated implementations may use sharded registries or carefully designed concurrent maps.

6. Why an in-memory rate limiter isn’t enough

So far, we’ve built a concurrency-safe rate limiter.

But concurrency safety within one process doesn’t guarantee consistency across multiple service instances.

Imagine a service running behind a load balancer:

                 API Gateway
                      |
             +--------+--------+
             |        |        |
             v        v        v
          Service  Service  Service
          Node 1   Node 2   Node 3
             |        |        |
          Local    Local    Local
          Bucket   Bucket   Bucket

Suppose a tenant is allowed 100 requests per second.

If each service instance maintains its own bucket, the tenant may effectively receive a limit of 300 requests per second when traffic is distributed evenly across three instances.

Each instance is enforcing its own local limit, not a global limit.

This is a fundamental distributed-systems problem.

We need shared state or another coordination mechanism if the limit must apply across the entire service.

7. Distributed rate limiting with Redis

One common approach is to use Redis as a shared rate-limiting store.

Instead of maintaining independent token buckets in application memory, service instances coordinate through Redis.

Conceptually:

              API Gateway
                   |
          +--------+--------+
          |        |        |
          v        v        v
       Service  Service  Service
       Node 1   Node 2   Node 3
          |        |        |
          +--------+--------+
                   |
                   v
                Redis
             Shared Bucket

However, simply reading a token count, updating it, and writing it back is unsafe.

Two service instances could read the same value and both consume the same token.

We need the entire token-bucket operation to execute atomically.

Redis Lua scripts provide one way to achieve this.

A simplified token-bucket script looks like this:

local key = KEYS[1]

local rate = tonumber(ARGV[1])
local burst = tonumber(ARGV[2])

local time = redis.call("TIME")
local now = tonumber(time[1]) * 1000
    + math.floor(tonumber(time[2]) / 1000)

local values = redis.call(
    "HMGET", key, "tokens", "last"
)

local tokens = tonumber(values[1]) or burst
local last = tonumber(values[2]) or now

local elapsed = math.max(0, now - last)

tokens = math.min(
    burst,
    tokens + elapsed * rate / 1000
)

local allowed = 0

if tokens >= 1 then
    tokens = tokens - 1
    allowed = 1
end

redis.call(
    "HSET", key,
    "tokens", tokens,
    "last", now
)

redis.call(
    "PEXPIRE", key,
    math.ceil(burst / rate * 2000)
)

return { allowed, tokens }

The script uses Redis server time, replenishes the bucket, consumes a token when available, and stores the updated state.

Because Redis executes the script atomically, concurrent requests cannot interleave their individual read and update operations.

The key can be scoped to a tenant:

rate-limit:tenant-123

This gives all service instances access to the same bucket.

This is an illustrative implementation. A production Redis integration also needs input validation, error handling, connection management, script loading or execution strategy, and appropriate expiry and precision decisions.

There is also an important trade-off: every request now depends on a shared network service.

Redis adds network latency and becomes part of the request admission path. Its availability, capacity, and failure behaviour must be considered.

For some systems, a hybrid approach works better: a local limiter protects each instance, while a distributed limiter enforces the global tenant quota.

8. Production considerations

A rate limiter is more than an algorithm. Its behaviour under failure and load matters just as much as its normal operation.

Choose the right limiting scope

Limits can be applied per IP address, authenticated user, API key, tenant, endpoint, or globally.

The identity should come from a trusted source. Client-supplied headers must not be blindly trusted for authentication or tenant identification.

Return meaningful responses

HTTP APIs should normally return 429 Too Many Requests when a request exceeds its quota.

Where appropriate, include Retry-After or rate-limit metadata so clients can adapt.

Avoid synchronized retry storms

Clients that retry immediately after being rejected can make an overloaded service worse.

Exponential backoff with jitter helps spread retries over time.

Define failure behaviour

What happens when Redis is unavailable?

  • Fail open: allow requests and preserve availability, potentially exceeding quotas.
  • Fail closed: reject requests and preserve strict admission control, potentially making the service unavailable.

The correct choice depends on the endpoint and business requirements.

Measure rate-limiting behaviour

Useful metrics include:

  • Requests allowed and rejected.
  • Rejection rate by tenant or endpoint.
  • Current limiter usage.
  • Redis latency and errors.
  • Rate-limiter execution latency.

Avoid using unbounded tenant identifiers as metric labels, since that can create excessive metric cardinality.

Keep rate limiting separate from business correctness

Rate limiting controls traffic volume. It does not guarantee that an operation is executed exactly once.

For example, a payment API may need both rate limiting and idempotency protection. One limits request frequency; the other protects against duplicate business operations.

These mechanisms solve different problems.

Conclusion

Rate limiting is an important part of building resilient backend services.

The token-bucket algorithm provides a practical way to control request rates while allowing limited bursts of traffic.

In Go, mutexes make in-memory limiter state safe under concurrent access. Per-tenant registries provide isolation between clients, while shared stores such as Redis allow multiple service instances to enforce a common quota.

The deeper engineering challenge is choosing the right scope, consistency model, and failure behaviour.

A rate limiter should protect the system without becoming a bottleneck or an unnecessary single point of failure.

What’s next?

In Part 6, we’ll look at a problem that can quietly undermine even well-designed Go services:

Preventing Goroutine Leaks in Production Systems

We’ll explore how goroutines become permanently blocked, how to identify leaks using profiling and runtime diagnostics, and how to design cancellation and lifecycle management into concurrent applications.


Further reading:

Comments