Subscribe

A token bucket rate limiter in golang without Redis

How we added rate limiting to a golang API with no Redis in the stack: a small in-process token bucket, a fake clock for tests, and the part people forget, which is that every task keeps its own budget.

A token bucket rate limiter in golang without Redis

We needed rate limiting on a golang API and the usual answer is "put a counter in Redis". We had no Redis. The only shared store was the Postgres database the API was already leaning on, and writing a row on every request to protect the API would have hurt it more than the scraping we were worried about.

So we went with an in-process token bucket. It is about 80 lines, it has no dependencies, and the tests don't sleep. In this blog we will look at the limiter, the HTTP middleware around it, how to test it with a fake clock, and the one thing about in-process limits that you have to keep in your head when you pick the numbers.

How a token bucket works

Every key (an IP, a user) gets a bucket. The bucket holds up to Limit tokens and starts full. Each request takes one token. Tokens drip back in at Limit / Window per second, so a rule of 60 per minute refills one token every second.

That gives you two things at once. A client can burst up to the limit, which is what real apps do when a screen opens and fires five calls together. And over a long time it can't go faster than the refill rate.

I like this better than a fixed window counter. With a fixed window a client can send the full limit at 10:00:59 and again at 10:01:00, so it gets double the budget in two seconds. The bucket doesn't have that edge.

The limiter

Here is the whole package. The clock is a field so the tests can move time forward without waiting.

// Package ratelimit is an in-process token bucket limiter keyed by any string.
package ratelimit

import (
    "sync"
    "time"
)

// Rule allows Limit requests per Window, with bursts up to Limit.
type Rule struct {
    Limit  int
    Window time.Duration
}

func (r Rule) perSecond() float64 {
    if r.Limit <= 0 || r.Window <= 0 {
        return 0
    }
    return float64(r.Limit) / r.Window.Seconds()
}

type bucket struct {
    tokens   float64
    lastFill time.Time
}

// Limiter keeps one bucket per key. Safe for concurrent use.
type Limiter struct {
    mu      sync.Mutex
    buckets map[string]*bucket
    now     func() time.Time
}

func New() *Limiter {
    return &Limiter{buckets: map[string]*bucket{}, now: time.Now}
}

// Allow takes one token from key's bucket. When it says no, it also says
// how long until the next token.
func (l *Limiter) Allow(key string, rule Rule) (bool, time.Duration) {
    rate := rule.perSecond()
    if rate == 0 {
        return true, 0 // a broken rule fails open
    }

    l.mu.Lock()
    defer l.mu.Unlock()

    now := l.now()
    b, ok := l.buckets[key]
    if !ok {
        b = &bucket{tokens: float64(rule.Limit), lastFill: now}
        l.buckets[key] = b
    }

    if elapsed := now.Sub(b.lastFill).Seconds(); elapsed > 0 {
        b.tokens = min(b.tokens+elapsed*rate, float64(rule.Limit))
        b.lastFill = now
    }

    if b.tokens >= 1 {
        b.tokens--
        return true, 0
    }

    wait := time.Duration((1 - b.tokens) / rate * float64(time.Second))
    return false, max(wait, time.Second)
}

// Evict drops buckets that have not been touched for maxIdle.
func (l *Limiter) Evict(maxIdle time.Duration) int {
    l.mu.Lock()
    defer l.mu.Unlock()

    cutoff := l.now().Add(-maxIdle)
    n := 0
    for k, b := range l.buckets {
        if b.lastFill.Before(cutoff) {
            delete(l.buckets, k)
            n++
        }
    }
    return n
}

// Len is the number of keys being tracked.
func (l *Limiter) Len() int {
    l.mu.Lock()
    defer l.mu.Unlock()
    return len(l.buckets)
}

A few choices in there are deliberate.

The bucket doesn't refill on a timer. It refills lazily when the next request for that key arrives, from the time that passed since the last one. No goroutine per key, no ticker. Less moving parts.

A rule with a zero or negative limit fails open. If someone sets an env var to 0 by mistake, I would rather have no rate limiting for an hour than lock every client out of the API. You may decide the other way for a login endpoint, that's fine, but decide it on purpose.

Evict exists because the map grows by one entry for every new IP. Under the exact traffic this thing is meant to stop (a scraper rotating addresses) that map would grow without end. One mutex for the whole map is fine at our traffic. If it ever shows up in a profile, shard the map by key hash.

The middleware

We check two budgets. One per IP, which catches anonymous scraping. One per caller identity when there is a bearer token, so a single account can't spread its traffic across many addresses. The IP rule is the looser one, because mobile carriers put a lot of users behind one address with CGNAT and a tight IP limit punishes all of them.

package ratelimit

import (
    "crypto/sha256"
    "encoding/hex"
    "math"
    "net"
    "net/http"
    "strconv"
    "strings"
    "time"
)

// Middleware checks a per-IP budget, then a per-token budget when the
// request carries a bearer token.
func Middleware(l *Limiter, ipRule, userRule Rule, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "/healthz" {
            next.ServeHTTP(w, r) // never throttle the load balancer
            return
        }

        if ok, wait := l.Allow("ip|"+clientIP(r), ipRule); !ok {
            tooMany(w, wait)
            return
        }

        if id := tokenKey(r); id != "" {
            if ok, wait := l.Allow("user|"+id, userRule); !ok {
                tooMany(w, wait)
                return
            }
        }

        next.ServeHTTP(w, r)
    })
}

func tooMany(w http.ResponseWriter, wait time.Duration) {
    secs := max(int(math.Ceil(wait.Seconds())), 1)
    w.Header().Set("Retry-After", strconv.Itoa(secs))
    http.Error(w, "too many requests", http.StatusTooManyRequests)
}

// tokenKey hashes the bearer token so the map never holds live tokens.
func tokenKey(r *http.Request) string {
    tok := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
    if tok == "" {
        return ""
    }
    sum := sha256.Sum256([]byte(tok))
    return hex.EncodeToString(sum[:8])
}

// clientIP uses RemoteAddr. Behind a load balancer, read the client IP the
// way your proxy sets it, and only trust headers your own proxy writes.
func clientIP(r *http.Request) string {
    host, _, err := net.SplitHostPort(r.RemoteAddr)
    if err != nil {
        return r.RemoteAddr
    }
    return host
}

The health check is skipped on purpose. And the webhooks too, more on that in a second. If the load balancer's health check gets a 429, the task is marked unhealthy and pulled out. A traffic spike then turns into an outage, which is the opposite of what you wanted. Payment and partner webhooks are skipped in the real list. Those arrive in bursts we don't control, a dropped one is a lost event, and they are already checked by signature. Rate limiting is the wrong tool for them.

The token is hashed before it goes into the key. Otherwise the limiter map is a nice in-memory list of every live session token.

Testing it without sleeping

Because now is a field, a test can own the clock:

func testLimiter() (*Limiter, func(time.Duration)) {
    now := time.Date(2026, 11, 19, 10, 0, 0, 0, time.UTC)
    l := New()
    l.now = func() time.Time { return now }
    return l, func(d time.Duration) { now = now.Add(d) }
}

func TestRefill(t *testing.T) {
    l, advance := testLimiter()
    rule := Rule{Limit: 60, Window: time.Minute} // 1 token per second

    for range 60 {
        l.Allow("k", rule)
    }
    advance(time.Second)
    if ok, _ := l.Allow("k", rule); !ok {
        t.Fatal("no token after 1s")
    }
    if ok, _ := l.Allow("k", rule); ok {
        t.Fatal("more than one token after 1s")
    }
}

func TestIdleDoesNotOverfill(t *testing.T) {
    l, advance := testLimiter()
    rule := Rule{Limit: 10, Window: time.Minute}

    l.Allow("k", rule)
    advance(24 * time.Hour)

    got := 0
    for range 50 {
        if ok, _ := l.Allow("k", rule); ok {
            got++
        }
    }
    if got != 10 {
        t.Fatalf("allowed %d after a long idle, want 10", got)
    }
}

The second test is the one that catches the classic bug, where you forget the min and a client that was quiet for a day gets thousands of tokens saved up. There's also a concurrency test: 50 goroutines take 20 tokens each from a bucket of 1000, and the next call must be refused. It only passes if no decrement was lost, and it's worth running with -race.

func TestConcurrent(t *testing.T) {
    l := New()
    rule := Rule{Limit: 1000, Window: time.Hour}

    var wg sync.WaitGroup
    for range 50 {
        wg.Go(func() {
            for range 20 {
                l.Allow("shared", rule)
            }
        })
    }
    wg.Wait()

    if ok, _ := l.Allow("shared", rule); ok {
        t.Fatal("budget not used up, some requests were lost")
    }
}
go vet ./...
go test -race -count=1 ./...

I ran these on Go 1.27.3 and whole package finishes in about a second and a half with the race detector, since nothing sleeps.

Trying it with curl

The demo server wires everything up with an IP rule of 5 per minute and runs Evict every five minutes:

l := ratelimit.New()

go func() {
    for range time.Tick(5 * time.Minute) {
        l.Evict(15 * time.Minute)
    }
}()

ipRule := ratelimit.Rule{Limit: 5, Window: time.Minute}
userRule := ratelimit.Rule{Limit: 120, Window: time.Minute}
log.Fatal(http.ListenAndServe(":8080", ratelimit.Middleware(l, ipRule, userRule, mux)))
for i in 1 2 3 4 5 6; do
  curl -s -o /dev/null -w "%{http_code} %header{retry-after}\n" localhost:8080/v1/items
done
200
200
200
200
200
429 12

The first version of my demo printed 429 11. A rule of 5 per minute refills one token every 12 seconds, so 11 looked wrong for a second. It was the int() cast throwing away the fraction, 11.99 became 11. A client that waits exactly 11 seconds and retries just gets another 429. Rounding up with math.Ceil fixed it, and the minimum of one second stays so we never send Retry-After: 0.

Every task has its own budget

This is the part to remember. The limiter lives in the memory of one process. If you run two tasks behind a load balancer, each one keeps its own buckets, so the real ceiling is the limit times the number of tasks. During a rolling deploy we briefly run four tasks, so for a few minutes it's four times.

We wrote that into the package comment and set the numbers with it in mind. These limits are a guard against scraping and enumeration. They are not a billing quota. If you need "exactly 1000 calls per day per customer", you need a shared store, and that is a different post.

The load balancer's routing also matters a bit. With round robin a client's requests spread over the tasks, so each task sees roughly half of them. The numbers still work out to about limit times tasks, it just fills more evenly.

Two small things we added later

First, a kill switch. The middleware reads an env var and, when it's set to false, returns a handler that just calls next. If the limiter itself ever turns out to be the problem during an incident, we can turn it off with a config change and a restart, no code change.

Second, the background eviction goroutine got a recover. A panic in a plain goroutine takes down the whole process, and nobody wants the API to die because of a housekeeping loop. We wrapped the call in a small function with a deferred recover that logs the stack. And if you already run graceful shutdown like in graceful shutdown of a golang HTTP server on ECS Fargate behind an ALB, give the ticker a stop channel too so it ends cleanly.

On the client side, respect Retry-After and add some jitter, the same way I described in exponential backoff in go. Otherwise all your clients come back on the same second and get throttled together again.