Skip to content
Blog

← All articles

A Thread-Safe Token Bucket Without Timers: Lazy Refill, Lock-Free GCRA, and 8 Bytes per Client

How to implement a rate limiter that refills tokens from timestamps instead of a background timer: a mutex token bucket, a lock-free GCRA in one atomic int64, and a sharded per-client map that cleans itself up, in Go, with Java and Python ports. Measured against timer-based refill and golang.org/x/time/rate, and tested with the race detector.

By 15 min read

The textbook picture of a token bucket has a faucet: something adds a token every few milliseconds, and requests take them out. Implemented literally, that is a timer per bucket, or a background loop over every bucket, running whether or not anyone is sending requests. For one bucket it doesn’t matter. For a hundred thousand API clients, it costs more than a whole CPU core to do nothing.

This article builds the alternative step by step: a bucket that works out its refill from timestamps when it is used, made safe for concurrent use, then shrunk to a single lock-free 64-bit number per client, then scaled to millions of clients in a map that cleans itself up. The main code is Go, with ports to Java and Python. Every example was run before publishing, and the Go code passes the race detector. For the math behind rate and burst, see our token bucket math article.

The short answer#

Why not refill on a timer#

Here is the literal implementation: each bucket gets a goroutine and a ticker that adds one token per tick.

ticker.go
// ticker.go: what not to do. Every bucket gets a goroutine and a ticker that adds a token per tick,
// whether or not anyone is using the bucket.
package ratelimit

import (
	"sync"
	"time"
)

type TickerBucket struct {
	mu            sync.Mutex
	tokens, burst int
	stop          chan struct{}
}

func NewTickerBucket(perSecond float64, burst int) *TickerBucket {
	b := &TickerBucket{tokens: burst, burst: burst, stop: make(chan struct{})}
	go func() {
		t := time.NewTicker(time.Duration(float64(time.Second) / perSecond))
		defer t.Stop()
		for {
			select {
			case <-t.C:
				b.mu.Lock()
				b.tokens = min(b.tokens+1, b.burst)
				b.mu.Unlock()
			case <-b.stop:
				return
			}
		}
	}()
	return b
}

func (b *TickerBucket) Allow() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens == 0 {
		return false
	}
	b.tokens--
	return true
}

func (b *TickerBucket) Close() { close(b.stop) }

It is correct, and it is how many first implementations look. We created 100,000 of these buckets at 10 tokens a second and then sent no requests at all for five seconds. The process used 1.1 CPU cores the whole time, and each bucket took about 3.2 KB of memory, mostly its goroutine’s stack. The same 100,000 clients in the lazy limiter below used no measurable CPU while idle, and about 35 bytes each.

A single background loop that walks every bucket on each tick avoids the goroutines, but the work is the same: it touches every client on every tick, idle or not, and it has to take each bucket’s lock while doing it, competing with real requests. And a timer can only add whole tokens on its own schedule, so rates that don’t divide evenly into ticks need extra bookkeeping.

Refill on access#

The key observation is that nobody needs to know how many tokens a bucket holds until someone asks. A bucket that remembers when it was last updated can calculate its refill at that moment:

tokens = min(b, tokens + (now − last) × r)

The answer is exactly what a timer would have produced, without the timer: no work while idle, no rounding to ticks, and any rate, even 0.3 requests a second, works the same way. The cost moves to the request path, where it is a subtraction, a multiplication, and a comparison.

A mutex token bucket in Go#

bucket.go
// bucket.go: a token bucket that refills from timestamps. No timer and no goroutine:
// a bucket that nobody uses costs no CPU at all.
package ratelimit

import (
	"sync"
	"time"
)

var epoch = time.Now()

// Now returns nanoseconds since the process started. time.Since uses Go's monotonic clock,
// so the result never jumps when the system clock is adjusted. Tests replace it.
var Now = func() int64 { return int64(time.Since(epoch)) }

type Bucket struct {
	mu     sync.Mutex
	rate   float64 // tokens per nanosecond
	burst  float64
	tokens float64
	last   int64 // when tokens was last brought up to date
}

func NewBucket(perSecond float64, burst int) *Bucket {
	return &Bucket{rate: perSecond / 1e9, burst: float64(burst), tokens: float64(burst), last: Now()}
}

// AllowN takes n tokens if the bucket has them, and reports whether it did.
func (b *Bucket) AllowN(n int) bool {
	now := Now() // read the clock before locking, to keep the critical section short
	b.mu.Lock()
	defer b.mu.Unlock()
	// The refill: everything that dripped in since the last call, capped at the bucket size.
	// Another goroutine may have locked first with a later reading; never refill backward.
	if now > b.last {
		b.tokens = min(b.burst, b.tokens+float64(now-b.last)*b.rate)
		b.last = now
	}
	if b.tokens < float64(n) {
		return false
	}
	b.tokens -= float64(n)
	return true
}

func (b *Bucket) Allow() bool { return b.AllowN(1) }

Three details in that code are easy to get wrong:

  • The clock is monotonic. A rate limiter measures intervals, and the wall clock is not a good ruler: NTP corrections, daylight-saving bugs and manual changes can move it backward or forward by seconds or hours. Go’s time.Since uses the monotonic clock built into time.Time. Java has System.nanoTime, and Python has time.monotonic.
  • The clock is read before the lock. That keeps the critical section to a few arithmetic operations. The price is that a goroutine can take the lock with a reading older than one already applied. The now > b.last check handles it: an older reading adds nothing, instead of moving last backward and later refilling the same interval twice.
  • Everything happens under one lock. Refill, check, and take must be one step, or two goroutines can both see the last token.

What the lock prevents#

To see what happens without it, our tests include the same bucket with no lock at all: check tokens < 1, then tokens--. Thirty-two goroutines made 5,000 calls each at a moment when the bucket held 100 tokens. In one test of 50 runs, the worst run let 183 requests through; in another test, no run went over 100. That is the dangerous part: a race like this passes many tests and fails under real load.

Go’s race detector (go test -race) reported the unlocked version as a data race on the first run, every time, whatever the count. All the limiters in this article pass under it.

Lock-free: GCRA in one atomic int64#

The mutex bucket stores three changing values (tokens, last update, and the mutex itself) plus its settings: 40 bytes. The Generic Cell Rate Algorithm stores one: the theoretical arrival time (TAT), when the client’s next request would be due at exactly the average rate. Our math article shows that it accepts exactly the same requests as a token bucket. Because the state is one number, it fits in an atomic.Int64, and the lock can be replaced by compare-and-swap:

gcra.go
// gcra.go: the same limit in 8 bytes of state, without a lock. The state is the theoretical
// arrival time (TAT); a compare-and-swap loop replaces the mutex.
package ratelimit

import "sync/atomic"

// Limit is shared by every client with the same plan, so it isn't stored per client.
type Limit struct {
	Interval  int64 // T: nanoseconds per request at the average rate
	Tolerance int64 // tau = (burst - 1) * T: how far ahead of schedule a client may get
}

func NewLimit(perSecond float64, burst int) Limit {
	t := int64(1e9 / perSecond)
	return Limit{Interval: t, Tolerance: int64(burst-1) * t}
}

// GCRA is one client's state. The zero value is a full bucket.
type GCRA struct{ tat atomic.Int64 }

// Allow reports whether a request may go ahead. If not, wait is the nanoseconds until one may.
func (g *GCRA) Allow(l Limit) (ok bool, wait int64) {
	now := Now()
	for {
		old := g.tat.Load()
		tat := max(old, now) // an idle client restarts from now: the bucket can't overfill
		if tat-now > l.Tolerance {
			return false, tat - l.Tolerance - now
		}
		if g.tat.CompareAndSwap(old, tat+l.Interval) {
			return true, 0
		}
		// Another goroutine changed the TAT between Load and CompareAndSwap: try again.
	}
}

CompareAndSwap writes the new TAT only if nobody changed it since the Load; if someone did, the loop reads the new value and decides again. The decision and the update are therefore one atomic step, without a lock. The classic weakness of compare-and-swap, the “ABA problem” where a value changes and changes back, can’t happen here: every successful update moves the TAT strictly forward.

Two properties make GCRA a good fit for production code. Its zero value is a full bucket, so a slice or map of GCRA values needs no initialization. And a rejection comes with an exact wait time, the Retry-After to send back with an HTTP 429.

Millions of clients in one map#

Real limiters track a bucket per client: per API key, per user, or per IP address. That raises two new problems: many goroutines updating one map, and a map that grows forever as new clients appear.

keyed.go
// keyed.go: one limit for many clients. Each client is a single int64 in a sharded map, and a
// client whose bucket has refilled completely is deleted, because a missing entry means the same.
package ratelimit

import (
	"hash/maphash"
	"sync"
)

const shards = 64 // independent locks, so goroutines serving different clients rarely wait

type Keyed struct {
	limit  Limit
	seed   maphash.Seed
	shards [shards]shard
}

type shard struct {
	mu    sync.Mutex
	tat   map[string]int64
	calls uint32
}

func NewKeyed(l Limit) *Keyed {
	k := &Keyed{limit: l, seed: maphash.MakeSeed()}
	for i := range k.shards {
		k.shards[i].tat = make(map[string]int64)
	}
	return k
}

func (k *Keyed) Allow(key string) (ok bool, wait int64) {
	s := &k.shards[maphash.String(k.seed, key)%shards]
	now := Now()
	s.mu.Lock()
	defer s.mu.Unlock()
	tat := max(s.tat[key], now) // a missing key reads as 0: a full bucket
	if tat-now > k.limit.Tolerance {
		return false, tat - k.limit.Tolerance - now
	}
	s.tat[key] = tat + k.limit.Interval
	// Cleanup without a background goroutine: after as many calls as the shard has entries,
	// sweep the shard once. That is at most one entry looked at per call, on average.
	if s.calls++; int(s.calls) >= len(s.tat) {
		s.calls = 0
		for key, t := range s.tat {
			if t <= now { // the bucket is full again: same as a client never seen
				delete(s.tat, key)
			}
		}
	}
	return true, 0
}

// Len counts the clients currently stored.
func (k *Keyed) Len() (n int) {
	for i := range k.shards {
		k.shards[i].mu.Lock()
		n += len(k.shards[i].tat)
		k.shards[i].mu.Unlock()
	}
	return n
}
  • Sharding splits the map into 64 parts with their own locks, chosen by a hash of the key. Two requests only wait for each other if their clients land in the same shard.
  • The value is just the TAT, an int64 stored directly in the map: no pointer, no per-client struct, no per-client copy of the limit’s settings.
  • Cleanup is done by the traffic. A client whose TAT is in the past has a full bucket, which is exactly what a missing entry means, so it can be deleted without changing any decision. Each shard sweeps itself after it has handled as many calls as it holds entries, so the cleanup costs at most one entry checked per call on average, and no goroutine is needed.

In our test, 100,000 clients each made one request and went quiet. Ten seconds later, when all their buckets were full again, ordinary traffic from 1,000 other clients removed every one of them within 2,000 calls. The sweep does cause an occasional slower call, one that scans a whole shard; if that matters, a hierarchical timing wheel or a min-heap ordered by TAT can expire clients exactly on time, at the cost of more code and more memory per client.

Speed and memory, measured#

We compared the three designs with each other and with golang.org/x/time/rate (v0.16.0), the rate limiter most Go projects use, on Go 1.26 and a 32-thread Intel Core i9-13900K. The settings were chosen so every call succeeds, which means every call updates the state: the worst case for contention.

One client, shared by all goroutines1 goroutine8 goroutines32 goroutines
Mutex token bucket25–27 ns45–46 ns58–59 ns
GCRA, atomic compare-and-swap19–20 ns30 ns20 ns
x/time/rate53–54 ns85–87 ns98–100 ns
100,000 clients, spread over all goroutines1 goroutine8 goroutines32 goroutines
Keyed, 64 shards75–77 ns41 ns28–29 ns

The times are per call, across all goroutines together, from two runs. When every goroutine hammers the same client, no design scales, because they all write the same memory; the atomic version wastes the least time doing it, and never blocks. With many clients, the sharded map spreads the work: 32 goroutines handled about 35 million decisions a second.

Memory per clientBytes
Timer-based bucket (goroutine and ticker), measured with 100,000 clientsAbout 3,200
map[string]*rate.Limiter136
map[string]*Bucket (this article’s mutex bucket)104
Keyed: map[string]int64 of TATs, sharded56
A plain []GCRA, the state alone8

The other rows were measured with 1 million clients. The key strings themselves are not included, since every design needs them. Most of the keyed map’s 56 bytes are the map’s own overhead and the string header; the limiter state is the last 8.

The same design in Java and Python#

The lock-free GCRA translates directly to Java’s AtomicLong. The clock is injectable, which is what makes it testable:

Gcra.java
// Gcra.java: the lock-free limiter for the JVM. One AtomicLong per client.
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;

public final class Gcra {
    private final long interval, tolerance; // nanoseconds
    private final LongSupplier clock;
    private final AtomicLong tat = new AtomicLong(Long.MIN_VALUE); // far in the past: a full bucket

    public Gcra(double perSecond, int burst) {
        this(perSecond, burst, System::nanoTime); // monotonic, unlike System.currentTimeMillis
    }

    public Gcra(double perSecond, int burst, LongSupplier clock) {
        this.interval = (long) (1e9 / perSecond);
        this.tolerance = (burst - 1) * interval;
        this.clock = clock;
    }

    /** Returns 0 if the request may go ahead, otherwise the nanoseconds to wait. */
    public long tryAcquire() {
        long now = clock.getAsLong();
        while (true) {
            long old = tat.get();
            long t = Math.max(old, now);
            if (t - now > tolerance) return t - tolerance - now;
            if (tat.compareAndSet(old, t + interval)) return 0;
        }
    }
}

In Python, a threading.Lock is the straightforward choice. The interpreter lock does not make the refill, the check, and the decrement one step: a thread can be switched out between any two of them, and free-threaded builds of Python 3.13 and later have no interpreter lock at all.

bucket.py
# bucket.py: the lazy token bucket for Python threads. The lock makes "refill, check, take" one step.
import threading
import time


class TokenBucket:
    __slots__ = ("_lock", "_clock", "_rate", "_burst", "_tokens", "_last")  # no __dict__ per bucket

    def __init__(self, per_second, burst, clock=time.monotonic):  # monotonic: immune to clock changes
        self._lock = threading.Lock()
        self._clock = clock
        self._rate = per_second
        self._burst = self._tokens = float(burst)
        self._last = clock()

    def allow(self, n=1):
        with self._lock:
            now = self._clock()
            if now > self._last:
                self._tokens = min(self._burst, self._tokens + (now - self._last) * self._rate)
                self._last = now
            if self._tokens < n:
                return False
            self._tokens -= n
            return True

__slots__ stops each bucket from carrying its own attribute dictionary. On Python 3.14, the saving is modest, because the interpreter already stores instance attributes compactly: 168 bytes per bucket against 184, measured with tracemalloc over 100,000 buckets. For millions of clients, store a single number per client in a dictionary, as the Go keyed limiter does, instead of an object per client.

Testing a concurrent limiter#

A rate limiter that depends on the real clock is hard to test exactly, because the number of requests accepted depends on how fast the test runs. The fix is the injectable clock: our tests freeze it, so the answer is exact.

  • Exactness under contention. With the clock frozen, 32 goroutines (or Java and Python threads) make 160,000 calls against a bucket of 100. Every implementation accepted exactly 100. After the clock moved forward one second at 50 per second, every implementation accepted exactly 50 more.
  • The bound with a real clock. 32 goroutines hammered a limiter of 1,000 a second with a burst of 100 for one second: 1,099 accepted in Go and 1,098 in Java, against the bound of b + r·t ≈ 1,100.
  • Edge cases. A rejected request was told to wait exactly 100 ms at 10 a second; a clock reading from a minute in the past didn’t refill the bucket.
  • The race detector, on every Go test run.

Pitfalls checklist#

  • Using the wall clock. Use a monotonic clock; a limiter on wall time can freeze or open up completely when the system clock is corrected.
  • Refilling backward. With the clock read outside the lock, an older reading must not move the last-update time back.
  • Check, then take, in two steps. Both must happen under the same lock or the same compare-and-swap.
  • Storing settings per client. Rate and burst belong to the plan, not to each client.
  • Never deleting anything. A per-client map without cleanup is a memory leak with a public interface: anyone can add entries by inventing new client IDs.
  • Charging a request that was rejected. With several limits, check them all before charging any; see the layered limiter in our math article.
  • One process, many servers. An in-memory limiter only sees its own process’s traffic. For a limit shared across servers, keep the TAT in Redis; the math article has a tested Lua script.

FAQ#

Should I just use golang.org/x/time/rate?

For a handful of limiters, yes. It is well tested and has features this article skips, such as Wait, which blocks until a token is available, and Reserve. It uses a mutex and 80 bytes per limiter, which only starts to matter with very many clients or very hot paths.

Is floating-point drift a problem in the token bucket?

Not in practice: a float64 token count has about 15 significant digits, far more than a rate limit needs. GCRA avoids the question entirely by working in integer nanoseconds, which is one more reason to prefer it.

Do I need lock-free code?

Rarely. The whole mutex bucket took about 25 ns per call without contention, and with a sharded map, contention is low anyway. The atomic GCRA is worth it mostly for its 8 bytes and its simplicity: one number, one loop, no lock to forget.

What about a limiter shared by many processes on one machine?

The same CAS loop works on an int64 in shared memory, but at that point most teams use Redis or the limiter built into their proxy (NGINX, Envoy), which saves writing the cleanup and the configuration.