Rate Limiting in Go: Token Bucket, Fixed Window, Leaky Bucket, x/time/rate
"It implements a "token bucket" of size b, initially full and refilled at rate r tokens per second." —
golang.org/x/time/rate, doc comment ofLimiter(source of v0.12.0)
Summary: A rate limiter answers one question, "may this event happen now?", with a small piece of state per caller; in Go the token bucket in golang.org/x/time/rate is the default answer, and every other algorithm (windows, leaky bucket, GCRA) is a different trade between memory, smoothness and burst. Focus: rate.Limiter and its calls (Allow, Reserve, Wait, SetLimit), own implementations of fixed window, sliding window and GCRA with tests on a fake clock, per-key maps with eviction and sharding, concurrency limits with semaphore.Weighted, HTTP and gRPC enforcement, outbound limiting that respects Retry-After, and a Redis Lua limiter for many replicas. Learning goal: Pick the right limiter for a Go service, wire it into middleware with correct headers and trusted-proxy handling, test it without sleeping, and know exactly which Go error text and which status code each failure produces.
This page owns the Go mechanics. The theory (why token bucket and not leaky bucket, how windows are compared, distributed designs, rate limiting at the gateway) is in Rate Limiting: Token Bucket, Leaky Bucket, Windows, Distributed Limits; it is linked, not repeated. Neighbours: Middlewares owns the func(http.Handler) http.Handler pattern, HTTP Server & Client owns timeouts and transports, Context owns cancellation, Sync Primitives owns mutexes and atomics, Time, Random Numbers owns clocks and timers, and Testing & Benchmarking owns the test tools. All code is in docs/snippets/go/rate-limiting-in-go/go/ (module academy/rate-limiting-in-go, go 1.24), tested with go test -race.
Page map
| If you are looking for | Go to |
|---|---|
| Algorithms and Go calls in tables | Everything in one minute |
| Rate versus concurrency versus quota | Why it exists |
| Where token bucket, GCRA and the 429 status come from | Where it comes from |
rate.Limiter, burst, zero value, rate.Inf | Token bucket and rate.Limiter |
Allow vs Reserve vs Wait | Three calls, three policies |
Reservation.Delay, Cancel | Reservations |
SetLimit, SetBurst, plans that change | Changing limits at runtime |
uber-go/ratelimit | Leaky bucket as a smoother |
| Fixed window, atomics vs mutex | Fixed window |
| Sliding window log and counter | Sliding window |
| GCRA | GCRA |
| One limiter per IP, key or tenant | Per-key limiters and eviction |
| LRU, contention, sharding | LRU and sharded limiters |
semaphore.Weighted | Concurrency limits |
The time.Ticker limiter | Why the ticker limiter fails |
| Per-IP, trusted proxies, API keys | HTTP middleware |
429, Retry-After, RateLimit-* | The response vocabulary |
| Calling someone else's API politely | Client-side limiting |
| Many replicas, Redis Lua | Distributed limiter |
| gRPC interceptors | gRPC |
Fake clock, synctest | Testing without sleeping |
| Shed or queue? | Backpressure vs load shedding |
| Exact error texts, numbers, benchmarks | Mechanics |
| Which limiter for which job | Choosing |
| Monolith to many services | In architecture |
| Reproduce everything | Lab |
Laravel RateLimiter facade | For PHP/Laravel developers |
Everything in one minute
The algorithms. Each row is unpacked in the concept catalogue.
| Algorithm | In plain words | State per key | Burst behaviour | Go tool |
|---|---|---|---|---|
| Token bucket | A bucket refills steadily; each event takes a token | A float and a timestamp | Up to burst at once, then the refill rate | rate.Limiter |
| Leaky bucket (smoother) | Events leave at an even pace; callers wait | One timestamp | None by default, small slack after idling | go.uber.org/ratelimit |
| Fixed window | Count per aligned interval, reset at the boundary | A counter and a window id | Up to 2x the limit across a boundary | Own code (windows) |
| Sliding window log | Remember every timestamp of the last interval | O(limit) timestamps | Exact | Own code |
| Sliding window counter | Weight the previous window's count | Two counters | Approximate, no 2x burst | Own code |
| GCRA | A token bucket stored as one "theoretical arrival time" | One timestamp | Same as token bucket | Own code (gcra) |
| Concurrency limit | At most N calls in flight, whatever the speed | A counter | N at once | semaphore.Weighted |
The Go calls. Every rate.Limiter method has an N variant and an At variant that takes the time as an argument.
| Call | When no token is available | Blocks? | Use for |
|---|---|---|---|
Allow() / AllowN(t, n) | Returns false, nothing consumed | No | Servers: answer 429 |
Reserve() / ReserveN(t, n) | Returns a Reservation with a delay; tokens may go negative | No | Pacing with your own sleeping, or peeking |
Wait(ctx) / WaitN(ctx, n) | Sleeps until a token exists | Yes, until ctx ends | Clients and workers |
SetLimit(r) / SetBurst(b) | n/a | No | Changing plans at runtime |
Tokens() / TokensAt(t) | n/a | No | Remaining quota, metrics |
rate.Every(d) | n/a | No | "One event per d" as a Limit |
rate.Inf | Everything passes, burst ignored | No | Switching a limiter off |
The HTTP vocabulary.
| Name | Meaning | Who sends it |
|---|---|---|
429 Too Many Requests | "The user has sent too many requests in a given amount of time" (RFC 6585) | Server, when it refuses |
Retry-After | Seconds or an HTTP-date to wait (RFC 9110 section 10.2.3) | Server, on 429 and 503 |
RateLimit-Limit | The quota of the current window or bucket | Server, every response |
RateLimit-Remaining | What is left of that quota | Server, every response |
RateLimit-Reset | Seconds until the quota is restored | Server, every response |
RateLimit-Policy and RateLimit | The newer structured fields of the IETF draft (version 12) | Server |
X-Forwarded-For | The chain of client and proxy addresses; only trustworthy past a trusted proxy | Proxies |
Why it exists
A service has a finite budget of CPU, connections, database queries and downstream calls. One misbehaving client, one retry storm or one scraper can spend all of it. A rate limiter turns "everyone fights for the budget" into "each caller gets a share, and the excess is refused or delayed early, while it is still cheap to do so".
| Two ideas that look alike | What it bounds | Typical Go tool | What it protects |
|---|---|---|---|
| Rate limit | Events per unit time, per caller | rate.Limiter, GCRA | Fairness, cost, abuse |
| Concurrency limit | Calls in flight at once | semaphore.Weighted, worker pool | Memory, connections, latency |
| Quota | Total per day or month, stored | Database or Redis counter | Billing, plans |
| Load shedding | Refuse when the server is overloaded, whoever you are | In-flight counter, queue age | Survival (Load Shedding) |
An everyday picture. A nightclub with a bouncer. A rate limit is "one person per ten seconds may enter, and up to five may enter together if the queue was empty" (token bucket). A concurrency limit is "the room holds 200, nobody enters until someone leaves". Load shedding is "the fire marshal closed the door because the building is full, even for the regulars".
Three common misunderstandings, up front
- "A rate limit of 100 per second means at most 100 in any second." Not for a token bucket with burst 100 plus refill: over one second it can admit up to 200 (the full bucket plus a second of refill). Only the sliding log is exact. See Burst.
- "The limiter protects the database." It protects the database only if it counts what the database feels. Ten slow requests in flight hurt more than a hundred fast ones; that is what a concurrency limit is for.
- "
rate.Limiterhas no clock, so it cannot be tested without sleeping."AllowandWaitreadtime.Now, butAllowN,ReserveN,TokensAtandSetLimitAttake the time as an argument. See testing.
Where it comes from
- Token bucket and leaky bucket are network-traffic shapers from the telecom world. The Wikipedia article on the Generic Cell Rate Algorithm (a secondary source) says GCRA "is a leaky bucket-type scheduling algorithm for the network scheduler that is used in Asynchronous Transfer Mode (ATM) networks", described by the ATM Forum and by ITU-T I.371 in two equivalent ways: virtual scheduling and a continuous-state leaky bucket. The Go GCRA below is the virtual-scheduling form.
golang.org/x/time/rateis the Go team's limiter. Its source says "The zero value is a valid Limiter, but it will reject all events" and "Most callers should use Wait". It is a token bucket whose state istokens,lastandlastEventunder a mutex.go.uber.org/ratelimit: its README calls the package "a Golang implementation of the leaky-bucket rate limit algorithm" that "refills the bucket based on the time elapsed between requests instead of requiring an interval clock". ItsTakeblocks to space calls evenly.- 429 was added by RFC 6585 (2012).
Retry-Afteris defined in RFC 9110 (HTTP Semantics) section 10.2.3 asHTTP-date / delay-seconds. RateLimit-*headers are still an Internet-Draft. The version fetched for this page,draft-ietf-httpapi-ratelimit-headers-12(expires 24 May 2027), definesRateLimit-PolicyandRateLimitas structured-field lists. The older trioRateLimit-Limit,RateLimit-Remaining,RateLimit-Resetcomes from earlier revisions of the same draft; the draft's change log says revision 08 "refactored both fields to lists of Items", which is our inference for why the trio disappeared. The trio is still what many gateways and SDKs emit, so the middleware below sends it.testing/synctest(a fake clock for goroutines) was experimental in Go 1.24 and became stable in Go 1.25; see testing.
The concept catalogue
Token bucket and rate.Limiter Must-know
In plain words: Picture a bucket that holds at most b tokens and receives r new tokens per second. Every event must take a token; if the bucket is empty, the event is refused or has to wait. A bucket that sat idle is full, so a short burst of up to b events passes at once; after that you get one event per 1/r seconds.
Common misunderstanding: "burst is a queue length." No. Burst is the bucket capacity, and also the largest n a single AllowN/WaitN can ever ask for. Nothing is queued by Allow; Wait queues goroutines only in the sense that each sleeps until its own reserved moment.
Definition: rate.NewLimiter(r rate.Limit, b int) returns a *rate.Limiter. rate.Limit is a float64 of events per second. The bucket starts full. Over any interval of length T the limiter admits at most b + r*T events. The zero Limiter has limit 0 and burst 0 and rejects everything.
Limiter: r = 2 tokens/s (rate.Every(500ms)), b = 3, bucket starts full
t(ms) event tokens after result
1 0 Allow 2.00 true
2 0 Allow 1.00 true
3 0 Allow 0.00 true
4 0 Allow 0.00 false -- empty, nothing consumed
5 500 Allow 0.00 true -- one token refilled
6 4000 Allow 2.00 true -- refill capped at b = 3, then one takenReal scenario: an API allows 10 requests per second per key with bursts of 20 (rate.NewLimiter(10, 20)); a mailer sends at most one email per 200 ms (rate.Every(200*time.Millisecond), burst 1); a crawler wants 5 requests per second to one host.
| What | Value | Consequence |
|---|---|---|
rate.NewLimiter(10, 20) | 10 tokens/s, capacity 20 | 20 at once after idling, then 10/s |
rate.NewLimiter(rate.Every(time.Minute), 1) | One per minute | Strict spacing, no burst |
rate.NewLimiter(rate.Inf, 0) | Infinite | Every call passes; burst is ignored |
rate.NewLimiter(0, 5) | Refill 0 | Five events ever, then never (until SetLimit) |
rate.Limiter{} (zero value) | 0 and 0 | Everything refused |
Fix / how to use it: the wrapper stdlimit.Gate routes every decision through an injected clock, which is what makes the tests below deterministic.
// Package stdlimit wraps golang.org/x/time/rate so that every decision uses an
// injected clock. Limiter.Allow and Limiter.Wait read time.Now internally, but
// AllowN, ReserveN, TokensAt and SetLimitAt accept the time as an argument.
package stdlimit
import (
"context"
"errors"
"math"
"time"
"golang.org/x/time/rate"
"academy/rate-limiting-in-go/internal/fakeclock"
)
// ErrBurst is returned when a request is larger than the bucket can ever hold.
var ErrBurst = errors.New("stdlimit: request exceeds burst")
// Sleeper blocks for d or until ctx is done. Tests replace it.
type Sleeper func(ctx context.Context, d time.Duration) error
// RealSleep sleeps on a real timer.
func RealSleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Gate is a rate.Limiter plus a clock.
type Gate struct {
lim *rate.Limiter
clk fakeclock.Clock
}
// NewGate builds a token bucket of size burst refilled at r tokens per second.
func NewGate(r rate.Limit, burst int, clk fakeclock.Clock) *Gate {
return &Gate{lim: rate.NewLimiter(r, burst), clk: clk}
}
// Allow consumes one token if available (drop policy).
func (g *Gate) Allow() bool { return g.lim.AllowN(g.clk.Now(), 1) }
// RetryAfter reports how long until one token exists, without consuming it.
// It rounds up to a whole second because Retry-After carries delay-seconds.
func (g *Gate) RetryAfter() time.Duration {
now := g.clk.Now()
tokens := g.lim.TokensAt(now)
if tokens >= 1 {
return 0
}
lim := g.lim.Limit()
if lim <= 0 {
return rate.InfDuration
}
secs := (1 - tokens) / float64(lim)
return time.Duration(math.Ceil(secs)) * time.Second
}
// Wait is x/time/rate's Wait with an injectable clock and sleeper.
// If the sleep is interrupted the reservation is handed back with CancelAt.
func (g *Gate) Wait(ctx context.Context, sleep Sleeper) error {
now := g.clk.Now()
r := g.lim.ReserveN(now, 1)
if !r.OK() {
return ErrBurst
}
d := r.DelayFrom(now)
if d == 0 {
return nil
}
if err := sleep(ctx, d); err != nil {
r.CancelAt(g.clk.Now())
return err
}
return nil
}
// Limiter exposes the wrapped limiter for SetLimit/SetBurst experiments.
func (g *Gate) Limiter() *rate.Limiter { return g.lim }Three calls, three policies Must-know
In plain words: Allow says "yes or no, right now". Wait says "I will sleep until it is my turn". Reserve says "book me a slot and tell me how long to wait; I will do the sleeping".
Common misunderstanding: "Wait polls the limiter in a loop." It does not. It reserves a future token once (so later callers queue behind it), then sleeps on a single timer. That is why many goroutines calling Wait are served in a smooth order without a thundering herd.
Definition: all three consume tokens; they differ when the bucket is short. Allow returns false and consumes nothing. Reserve always books if n <= burst (the bucket may go negative, which is the "debt" later callers wait behind). Wait is Reserve plus a sleep that respects ctx.
Bucket r = 1/s, b = 1, already empty at t = 0. Three goroutines arrive at t = 0.
1 G1: Wait -> reserves slot at t = 1s, sleeps 1s
2 G2: Wait -> reserves slot at t = 2s, sleeps 2s (debt: tokens = -1)
3 G3: Wait -> reserves slot at t = 3s, sleeps 3s (debt: tokens = -2)
4 G4: Allow -> false (Allow never reserves)
5 ctx of G2 is cancelled at t = 0.5s -> r.Cancel() refunds its slot; G3 is not moved earlierReal scenario: an HTTP handler uses Allow (never sleep inside a request); a nightly job calling a partner API uses Wait(ctx) with the job's context; a client that logs "retry in 1.3s" uses Reserve and reads Delay().
| Need | Call | Why |
|---|---|---|
| Refuse excess work cheaply | Allow | No goroutine is parked |
| Smooth outbound calls, honour deadlines | Wait(ctx) | Returns an error before sleeping if the deadline cannot be met |
| Tell the caller how long to wait | Reserve then Delay, Cancel | You decide whether to sleep |
| Several tokens at once (bytes, batch size) | AllowN, WaitN, ReserveN | n must be at most burst |
Fix / how to use it: tests in the next snippet prove the burst, the refill, the debt and the refund.
package stdlimit
import (
"context"
"errors"
"testing"
"time"
"golang.org/x/time/rate"
"academy/rate-limiting-in-go/internal/fakeclock"
)
func TestBurstThenRefill(t *testing.T) {
clk := fakeclock.New()
g := NewGate(rate.Every(100*time.Millisecond), 3, clk) // 10/s, burst 3
for i := 0; i < 3; i++ {
if !g.Allow() {
t.Fatalf("call %d inside the burst was refused", i+1)
}
}
if g.Allow() {
t.Fatal("fourth call must be refused, bucket is empty")
}
clk.Advance(100 * time.Millisecond)
if !g.Allow() {
t.Fatal("one token should have refilled after 100ms")
}
if g.Allow() {
t.Fatal("only one token refilled")
}
clk.Advance(time.Hour)
for i := 0; i < 3; i++ {
if !g.Allow() {
t.Fatalf("after a long idle the bucket is full again, call %d refused", i+1)
}
}
if g.Allow() {
t.Fatal("tokens must never exceed burst")
}
}
func TestRetryAfterRoundsUp(t *testing.T) {
clk := fakeclock.New()
g := NewGate(2, 1, clk) // 2 tokens/s, burst 1
g.Allow()
if got := g.RetryAfter(); got != time.Second {
t.Fatalf("RetryAfter = %v, want 1s (500ms rounded up)", got)
}
clk.Advance(500 * time.Millisecond)
if got := g.RetryAfter(); got != 0 {
t.Fatalf("RetryAfter = %v, want 0", got)
}
}
func TestReservationDelayAndCancel(t *testing.T) {
clk := fakeclock.New()
lim := rate.NewLimiter(10, 1)
now := clk.Now()
r1 := lim.ReserveN(now, 1) // takes the only token
r2 := lim.ReserveN(now, 1) // goes into debt
if r1.DelayFrom(now) != 0 {
t.Fatalf("first reservation delay = %v, want 0", r1.DelayFrom(now))
}
if got := r2.DelayFrom(now); got != 100*time.Millisecond {
t.Fatalf("second reservation delay = %v, want 100ms", got)
}
r2.CancelAt(now) // not used: give the token back
r3 := lim.ReserveN(now, 1)
if got := r3.DelayFrom(now); got != 100*time.Millisecond {
t.Fatalf("after Cancel the next reservation delay = %v, want 100ms (the slot was refunded)", got)
}
}
func TestReserveBeyondBurstIsNotOK(t *testing.T) {
lim := rate.NewLimiter(10, 2)
r := lim.ReserveN(time.Now(), 3)
if r.OK() {
t.Fatal("n greater than burst must not be OK")
}
if r.Delay() != rate.InfDuration {
t.Fatalf("Delay = %v, want InfDuration", r.Delay())
}
}
func TestWaitInjectedSleeper(t *testing.T) {
clk := fakeclock.New()
g := NewGate(10, 1, clk)
var slept []time.Duration
sleep := func(_ context.Context, d time.Duration) error {
slept = append(slept, d)
clk.Advance(d)
return nil
}
for i := 0; i < 3; i++ {
if err := g.Wait(context.Background(), sleep); err != nil {
t.Fatal(err)
}
}
want := []time.Duration{100 * time.Millisecond, 100 * time.Millisecond}
if len(slept) != 2 || slept[0] != want[0] || slept[1] != want[1] {
t.Fatalf("slept = %v, want %v", slept, want)
}
}
func TestWaitCancelRefundsToken(t *testing.T) {
clk := fakeclock.New()
g := NewGate(1, 1, clk)
g.Allow() // empty the bucket
boom := errors.New("interrupted")
err := g.Wait(context.Background(), func(context.Context, time.Duration) error { return boom })
if !errors.Is(err, boom) {
t.Fatalf("err = %v", err)
}
// The cancelled reservation was refunded, so a new waiter is delayed 1s, not 2s.
var got time.Duration
_ = g.Wait(context.Background(), func(_ context.Context, d time.Duration) error { got = d; return nil })
if got != time.Second {
t.Fatalf("second waiter delay = %v, want 1s", got)
}
}
func TestSetLimitChangesRefillRate(t *testing.T) {
clk := fakeclock.New()
g := NewGate(1, 5, clk)
for i := 0; i < 5; i++ {
g.Allow()
}
g.Limiter().SetLimitAt(clk.Now(), 10)
clk.Advance(200 * time.Millisecond)
if !g.Allow() || !g.Allow() {
t.Fatal("at 10 tokens/s, 200ms should have produced two tokens")
}
if g.Allow() {
t.Fatal("no third token yet")
}
}
func TestInfAllowsEverythingEvenWithZeroBurst(t *testing.T) {
lim := rate.NewLimiter(rate.Inf, 0)
for i := 0; i < 1000; i++ {
if !lim.Allow() {
t.Fatal("rate.Inf must allow every event")
}
}
}
func TestZeroValueRejectsEverything(t *testing.T) {
var lim rate.Limiter
if lim.Allow() {
t.Fatal("the zero Limiter allows nothing")
}
}
// Real error texts from x/time/rate. These do not depend on timing.
func TestWaitErrorTexts(t *testing.T) {
lim := rate.NewLimiter(10, 2)
err := lim.WaitN(context.Background(), 3)
if err == nil || err.Error() != "rate: Wait(n=3) exceeds limiter's burst 2" {
t.Fatalf("err = %v", err)
}
slow := rate.NewLimiter(1, 1)
slow.Allow()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
err = slow.Wait(ctx)
if err == nil || err.Error() != "rate: Wait(n=1) would exceed context deadline" {
t.Fatalf("err = %v", err)
}
ctx2, cancel2 := context.WithCancel(context.Background())
cancel2()
if err := slow.Wait(ctx2); !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
}Reservations: Delay and Cancel Important
In plain words: A Reservation is a receipt for a future token. OK() says whether the limiter could book it; Delay() says how long to wait before acting; Cancel() hands the booking back if you decide not to act.
Common misunderstanding: "If I do not use the reservation, nothing happens." The token is gone for everyone else until you call Cancel. Forgetting it on an error path silently lowers throughput. Cancel restores tokens only "as much as possible, considering that other reservations may have already been made" (source comment); a reservation made before later ones cannot pull them forward.
Definition: ReserveN returns a *Reservation that is not OK when n > burst (or when a Wait would pass the context deadline). Delay() returns rate.InfDuration (the constant time.Duration(math.MaxInt64)) for a reservation that is not OK. DelayFrom(t) and CancelAt(t) take the time explicitly.
r = 10/s, b = 1, at fixed time t0
1 r1 := ReserveN(t0, 1) OK, Delay 0 (takes the only token)
2 r2 := ReserveN(t0, 1) OK, Delay 100ms (tokens = -1)
3 r2.CancelAt(t0) (refund: tokens back to 0)
4 r3 := ReserveN(t0, 1) OK, Delay 100ms (the slot r2 gave up)Real scenario: a download manager reserves a slot, sees Delay() is over its patience, calls Cancel and tells the user "busy"; a worker reserves, then ctx.Done() fires during its own sleep, and Cancel returns the slot.
| Situation | What to do |
|---|---|
!r.OK() | n exceeds burst; fix the configuration (it will never succeed) |
| You will not act after reserving | r.Cancel() |
| Your own sleep was interrupted | r.CancelAt(now) (what Gate.Wait does) |
| Need the delay without consuming | Use TokensAt(t) instead, as Gate.RetryAfter does |
Fix / how to use it: Gate.Wait above is the pattern: reserve, sleep, on error cancel.
Burst, rate.Every, rate.Inf and the zero value Must-know
In plain words: Three numbers describe a limiter: how fast it refills, how big the bucket is, and whether it is switched off.
Common misunderstanding: "Burst 0 means no bursts." Burst 0 with a finite limit means no event can ever be admitted, because every event needs a whole token and the bucket's capacity is zero. rate.Inf is the only value for which burst is ignored.
Definition: rate.Every(interval) converts a minimum gap to a Limit (1/interval.Seconds()); a non-positive interval gives rate.Inf. rate.Inf is Limit(math.MaxFloat64). With Inf, Allow is always true, even for a zero or one-token burst.
| Expression | Limit | Meaning |
|---|---|---|
rate.Every(100*time.Millisecond) | 10 | One per 100 ms |
rate.Every(0) | rate.Inf | No limit |
rate.Limit(0.5) | 0.5 | One per two seconds |
rate.Inf | MaxFloat64 | Pass-through |
Real scenario: a feature flag "rate limiting off in staging" is rate.NewLimiter(rate.Inf, 0); an hourly job is rate.Every(time.Hour) with burst 1.
Fix / how to use it: validate configuration at startup: reject burst < 1 when limit != rate.Inf.
Changing limits at runtime Good to know
In plain words: SetLimit and SetBurst change the refill rate and bucket size of a live limiter, for example when a customer upgrades their plan.
Common misunderstanding: "After SetLimit, every waiter is rescheduled." No. The doc comment says the new limit and burst "may be violated or underutilized by those which reserved (using Reserve or Wait) but did not yet act before SetLimitAt was called". Existing reservations keep their promised time.
Definition: SetLimitAt(t, r) first advances the bucket to t with the old rate, then switches rate. SetBurstAt does the same for capacity.
r = 1/s, b = 5, bucket drained at t0
1 SetLimitAt(t0, 10)
2 t0 + 200ms: Allow -> true, Allow -> true, Allow -> false (2 tokens at 10/s)| Plan | Limit | Burst |
|---|---|---|
| Free | 1 | 5 |
| Pro | 10 | 50 |
| Internal | rate.Inf | 0 |
Fix / how to use it: keep the plan table in the database (see the SQL below) and call SetLimit/SetBurst when the plan changes; the test TestSetLimitChangesRefillRate in the snippet above checks the arithmetic.
Leaky bucket as a smoother: go.uber.org/ratelimit Important
In plain words: Where a token bucket allows a burst and then a steady rate, a leaky bucket "as a meter in front of a queue" lets work out at a constant drip. ratelimit.Take() blocks the caller just long enough that calls leave at an even pace, for example exactly every 100 ms for 10 per second.
Common misunderstanding: "It rejects the excess." Take never refuses; it only delays. It has no Allow. It is a smoother for clients and workers, not an admission controller for servers.
Definition: ratelimit.New(rate, opts...) returns a Limiter with one method, Take() time.Time. Options: Per(d) (default window one second), WithSlack(n) (default 10) or WithoutSlack, and WithClock(c) where Clock has Now() and Sleep(d). The v0.3.1 implementation keeps one int64 (the next permission time in Unix nanoseconds) and updates it with CompareAndSwapInt64.
ratelimit.New(10): 100ms per call
1 Take -> returns now, no sleep (first call)
2 Take -> sleeps 100ms
3 ... 10 seconds of silence ...
4 Take x 11 -> all return at once (slack 10: idle time pays for a short burst)
5 Take -> sleeps 100ms againReal scenario: a batch exporter writing to a billing API at 50 requests per second; a load generator that must be steady; a scraper that must not look like a burst.
| Option | Effect | Use |
|---|---|---|
default (slack = 10) | After idling, up to 10 calls pass at once | Smooth, tolerant of GC pauses |
ratelimit.WithoutSlack | Strict spacing | Partner APIs that count bursts |
ratelimit.Per(time.Minute) | New(2, Per(time.Minute)) is two per minute | Slow quotas |
ratelimit.WithClock(c) | Inject a fake clock | Tests |
Fix / how to use it: the test uses a stepClock whose Sleep just advances time, so the pacing is asserted without waiting.
// Package smoother demonstrates go.uber.org/ratelimit, a leaky-bucket-style
// smoother: Take blocks so that calls leave at an even pace.
package smoother
import (
"testing"
"time"
"go.uber.org/ratelimit"
)
// stepClock is a ratelimit.Clock whose Sleep simply moves time forward, so a
// test needs no goroutine and no real waiting. It records every sleep.
type stepClock struct {
now time.Time
sleeps []time.Duration
}
func (c *stepClock) Now() time.Time { return c.now }
func (c *stepClock) Sleep(d time.Duration) {
c.sleeps = append(c.sleeps, d)
c.now = c.now.Add(d)
}
func newClock() *stepClock {
return &stepClock{now: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)}
}
func TestTakeSpacesCallsEvenly(t *testing.T) {
clk := newClock()
rl := ratelimit.New(10, ratelimit.WithClock(clk), ratelimit.WithoutSlack) // 10/s: 100ms apart
var stamps []time.Time
for i := 0; i < 5; i++ {
stamps = append(stamps, rl.Take())
}
for i := 1; i < len(stamps); i++ {
if gap := stamps[i].Sub(stamps[i-1]); gap != 100*time.Millisecond {
t.Fatalf("gap %d = %v, want 100ms", i, gap)
}
}
if len(clk.sleeps) != 4 {
t.Fatalf("sleeps = %v, want 4 sleeps of 100ms (the first Take never waits)", clk.sleeps)
}
}
// After a long idle gap the default slack (10) lets a short burst through before
// pacing resumes; WithoutSlack paces from the very next call.
func TestSlackAllowsABurstAfterIdle(t *testing.T) {
count := func(opts ...ratelimit.Option) (instant int) {
clk := newClock()
rl := ratelimit.New(10, append([]ratelimit.Option{ratelimit.WithClock(clk)}, opts...)...)
rl.Take()
clk.now = clk.now.Add(10 * time.Second) // nobody calls for ten seconds
clk.sleeps = nil
for i := 0; i < 20; i++ {
before := len(clk.sleeps)
rl.Take()
if len(clk.sleeps) == before {
instant++
}
}
return instant
}
if got := count(); got != 11 {
t.Fatalf("default slack: %d calls returned immediately, want 11", got)
}
if got := count(ratelimit.WithoutSlack); got != 1 {
t.Fatalf("WithoutSlack: %d calls returned immediately, want 1", got)
}
}Fixed window Must-know
In plain words: Divide time into aligned slices (each second, each minute). Count requests in the current slice; when the slice changes, the counter resets. Cheap, easy to explain, easy to put in Redis (INCR plus EXPIRE).
Common misunderstanding: "Fixed window enforces N per any interval of that length." It enforces N per aligned slice. A client can send N at 12:00:00.999 and N at 12:00:01.001, so 2N arrive within 2 ms.
Definition: window index = floor(now / window); the counter is valid only for its index. Go has two natural implementations: a mutex around two fields, or one atomic.Uint64 that packs the window index (high 32 bits) with the counter (low 32 bits) and moves with CompareAndSwap.
limit 100 per second
1 12:00:00.999 100 requests -> all admitted (window 0 is now full)
2 12:00:01.000 window index changes, counter resets
3 12:00:01.001 100 requests -> all admitted (200 requests in 2 ms)Real scenario: quota-style limits where the boundary burst is acceptable ("1000 emails per day", "5 login attempts per 15 minutes" with a lockout); anything stored in Redis or a database where one atomic increment is all you have.
| Variant | Cost | Under contention |
|---|---|---|
| Mutex | Lock, compare, increment | Measured ~150 ns/op on 12 cores (see Mechanics) |
| Atomic CAS | No lock; retry loop on conflict | Measured ~450 to 500 ns/op on 12 cores: retries made it slower here |
Fix / how to use it: do not assume atomics are faster; measure with go test -bench . -cpu 1,4,12. Both pass the same boundary and exact-count tests.
// Package windows holds fixed-window and sliding-window-counter limiters.
package windows
import (
"sync"
"sync/atomic"
"time"
"academy/rate-limiting-in-go/internal/fakeclock"
)
// FixedMutex counts requests in aligned windows [k*w, (k+1)*w). Simple and obviously correct.
type FixedMutex struct {
mu sync.Mutex
limit int
window time.Duration
clk fakeclock.Clock
idx int64
count int
}
// NewFixedMutex allows limit requests per window.
func NewFixedMutex(limit int, window time.Duration, clk fakeclock.Clock) *FixedMutex {
return &FixedMutex{limit: limit, window: window, clk: clk, idx: -1}
}
// Allow reports whether one more request fits in the current window.
func (f *FixedMutex) Allow() bool {
idx := f.clk.Now().UnixNano() / int64(f.window)
f.mu.Lock()
defer f.mu.Unlock()
if idx != f.idx {
f.idx, f.count = idx, 0
}
if f.count >= f.limit {
return false
}
f.count++
return true
}
// FixedAtomic is the same algorithm without a mutex: the window index (high 32
// bits) and the counter (low 32 bits) live in one uint64 and move with a CAS loop.
type FixedAtomic struct {
state atomic.Uint64
limit uint32
window time.Duration
clk fakeclock.Clock
}
// NewFixedAtomic allows limit requests per window.
func NewFixedAtomic(limit uint32, window time.Duration, clk fakeclock.Clock) *FixedAtomic {
return &FixedAtomic{limit: limit, window: window, clk: clk}
}
// Allow is lock-free; under contention a goroutine retries its CAS.
func (f *FixedAtomic) Allow() bool {
cur := uint32(f.clk.Now().UnixNano() / int64(f.window))
for {
old := f.state.Load()
var next uint64
if uint32(old>>32) != cur {
next = uint64(cur)<<32 | 1 // new window: this request is the first
} else {
if uint32(old) >= f.limit {
return false
}
next = old + 1
}
if f.state.CompareAndSwap(old, next) {
return true
}
}
}Sliding window: log and counter Important
In plain words: The log remembers the time of every recent request and counts those inside the last interval: exact, but it stores up to limit timestamps per key. The counter keeps only the current and previous fixed-window counts and weights the previous one by how much of it still overlaps: approximate, two integers per key.
Common misunderstanding: "The sliding counter is exact." It assumes the previous window's requests were evenly spread. If they were all in the last millisecond, it under-counts slightly late in the new window and over-counts early; it never allows the 2x boundary burst.
Definition: estimate = prev * (1 - elapsedFraction) + cur; admit when estimate + 1 <= limit.
limit 100 per second, 150 requests at 12:00:00.999, then 150 at 12:00:01.001
1 first burst: 100 admitted, 50 refused
2 at .001 into window 1: elapsed fraction 0.001 -> estimate = 100 * 0.999 + 0 = 99.9
3 second burst: at most 1 admittedReal scenario: public APIs where the boundary burst is a cost problem; login throttling; any place a log is too big (millions of keys) but fixed windows are too crude.
| Algorithm | Memory per key | Exactness | Boundary burst |
|---|---|---|---|
| Fixed window | 2 ints | Per aligned slice | Up to 2x |
| Sliding counter | 2 ints | Approximate | Prevented |
| Sliding log | limit timestamps | Exact | Prevented |
| Token bucket / GCRA | 1 float or 1 timestamp | Exact for its own definition | burst by design |
Fix / how to use it: the tests assert the 2x burst for fixed windows, the near-zero second burst for the counter and exactness of the log.
package windows
import (
"sync"
"time"
"academy/rate-limiting-in-go/internal/fakeclock"
)
// SlidingCounter is the "sliding window counter" approximation: it keeps the
// count of the current and the previous fixed window and weights the previous
// one by how much of it still overlaps the sliding window.
//
// estimate = prev * (1 - elapsedFractionOfCurrent) + cur
type SlidingCounter struct {
mu sync.Mutex
limit float64
window time.Duration
clk fakeclock.Clock
idx int64
prev float64
cur float64
}
// NewSlidingCounter allows about limit requests in any window-long interval.
func NewSlidingCounter(limit int, window time.Duration, clk fakeclock.Clock) *SlidingCounter {
return &SlidingCounter{limit: float64(limit), window: window, clk: clk}
}
// Allow admits a request when the weighted estimate stays below the limit.
func (s *SlidingCounter) Allow() bool {
now := s.clk.Now()
idx := now.UnixNano() / int64(s.window)
s.mu.Lock()
defer s.mu.Unlock()
switch {
case idx == s.idx:
case idx == s.idx+1:
s.prev, s.cur, s.idx = s.cur, 0, idx
default:
s.prev, s.cur, s.idx = 0, 0, idx
}
into := float64(now.UnixNano()%int64(s.window)) / float64(s.window)
if s.prev*(1-into)+s.cur+1 > s.limit {
return false
}
s.cur++
return true
}
// SlidingLog keeps every timestamp: exact, but O(limit) memory per key.
type SlidingLog struct {
mu sync.Mutex
limit int
window time.Duration
clk fakeclock.Clock
log []time.Time
}
// NewSlidingLog allows exactly limit requests in any window-long interval.
func NewSlidingLog(limit int, window time.Duration, clk fakeclock.Clock) *SlidingLog {
return &SlidingLog{limit: limit, window: window, clk: clk}
}
// Allow drops expired timestamps, then admits if there is room.
func (s *SlidingLog) Allow() bool {
now := s.clk.Now()
s.mu.Lock()
defer s.mu.Unlock()
cut := now.Add(-s.window)
i := 0
for i < len(s.log) && !s.log[i].After(cut) {
i++
}
s.log = s.log[i:]
if len(s.log) >= s.limit {
return false
}
s.log = append(s.log, now)
return true
}package windows
import (
"sync"
"sync/atomic"
"testing"
"time"
"academy/rate-limiting-in-go/internal/fakeclock"
)
type allower interface{ Allow() bool }
// burstAt fires n requests and returns how many were admitted.
func burstAt(a allower, n int) int {
ok := 0
for i := 0; i < n; i++ {
if a.Allow() {
ok++
}
}
return ok
}
// The classic flaw: 100 requests in the last millisecond of one window and 100
// in the first millisecond of the next are all admitted: 200 in 2ms.
func TestFixedWindowBoundaryBurst(t *testing.T) {
for name, mk := range map[string]func(*fakeclock.Fake) allower{
"mutex": func(c *fakeclock.Fake) allower { return NewFixedMutex(100, time.Second, c) },
"atomic": func(c *fakeclock.Fake) allower { return NewFixedAtomic(100, time.Second, c) },
} {
clk := fakeclock.New() // 12:00:00.000 is a window boundary
a := mk(clk)
clk.Advance(999 * time.Millisecond)
first := burstAt(a, 150)
clk.Advance(2 * time.Millisecond) // now 12:00:01.001
second := burstAt(a, 150)
if first != 100 || second != 100 {
t.Fatalf("%s: first=%d second=%d, want 100 and 100 (200 admitted in 2ms)", name, first, second)
}
}
}
func TestSlidingCounterSmoothsTheBoundary(t *testing.T) {
clk := fakeclock.New()
s := NewSlidingCounter(100, time.Second, clk)
clk.Advance(999 * time.Millisecond)
first := burstAt(s, 150)
clk.Advance(2 * time.Millisecond)
second := burstAt(s, 150)
if first != 100 {
t.Fatalf("first = %d, want 100", first)
}
if second > 1 {
t.Fatalf("second = %d, the previous window still weighs ~99.9%% so almost nothing fits", second)
}
}
func TestSlidingLogIsExact(t *testing.T) {
clk := fakeclock.New()
s := NewSlidingLog(3, time.Second, clk)
for i := 0; i < 3; i++ {
if !s.Allow() {
t.Fatal("first three must pass")
}
clk.Advance(300 * time.Millisecond)
}
// t = 900ms: log holds 0, 300, 600.
if s.Allow() {
t.Fatal("fourth request inside one second must be refused")
}
clk.Advance(101 * time.Millisecond) // t = 1001ms: the entry at 0 expired
if !s.Allow() {
t.Fatal("one slot should be free now")
}
if s.Allow() {
t.Fatal("only one slot was free")
}
}
// Run with -race. With a frozen clock exactly limit goroutines may win.
func TestConcurrentExactCount(t *testing.T) {
for name, a := range map[string]allower{
"mutex": NewFixedMutex(100, time.Second, fakeclock.New()),
"atomic": NewFixedAtomic(100, time.Second, fakeclock.New()),
} {
var admitted atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if a.Allow() {
admitted.Add(1)
}
}()
}
wg.Wait()
if admitted.Load() != 100 {
t.Fatalf("%s: admitted %d, want exactly 100", name, admitted.Load())
}
}
}
func BenchmarkFixedMutex(b *testing.B) {
a := NewFixedMutex(1<<30, time.Hour, fakeclock.System{})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
a.Allow()
}
})
}
func BenchmarkFixedAtomic(b *testing.B) {
a := NewFixedAtomic(1<<30, time.Hour, fakeclock.System{})
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
a.Allow()
}
})
}GCRA: the token bucket in one timestamp Important
In plain words: Instead of storing "how many tokens", store "the earliest time the next request would be on schedule" (the theoretical arrival time, TAT). A request is admitted if it is not too early; each admission pushes the TAT forward by one interval.
Common misunderstanding: "GCRA is a different limiter from the token bucket." For the same rate and burst it makes the same decisions; the state is just encoded as a time instead of a count. That is why it fits in one Redis key and why TestMatchesTokenBucket compares it to rate.Limiter on a trace.
Definition: with emission interval T and burst b (tolerance tau = T * b): tat = max(tat, now), newTAT = tat + T, allowAt = newTAT - tau; if now < allowAt refuse with retryAfter = allowAt - now, else store newTAT.
T = 100ms, b = 3, all at the same instant
1 req 1: tat = now, newTAT = now+100, allowAt = now-200 -> admit
2 req 2: tat = now+100, newTAT = now+200, allowAt = now-100 -> admit
3 req 3: tat = now+200, newTAT = now+300, allowAt = now -> admit
4 req 4: tat = now+300, newTAT = now+400, allowAt = now+100 -> refuse, retry after 100msReal scenario: shared limits in Redis (one GET, one SET, one script), embedded-device limiters, anywhere a single int64 of state matters, and any API that needs an exact Retry-After without floating-point tokens.
| Property | GCRA | Token bucket (rate.Limiter) |
|---|---|---|
| State | One timestamp | Float tokens and two timestamps |
| Retry-After | allowAt - now, exact | Computed from missing tokens |
| Cancel/refund | Not provided here | Reservation.Cancel |
| Waiting | Add a sleep yourself | Wait built in |
Fix / how to use it:
// Package gcra implements the Generic Cell Rate Algorithm: a token bucket
// stored as one timestamp, the "theoretical arrival time" (TAT).
package gcra
import (
"sync"
"time"
)
// Limiter admits one event every emission interval, with burst events of slack.
type Limiter struct {
mu sync.Mutex
interval time.Duration // T: time one event "costs"
tau time.Duration // burst tolerance: interval * burst
tat time.Time // theoretical arrival time of the next conforming event
}
// New builds a limiter for events spaced interval apart on average, with bursts up to burst.
func New(interval time.Duration, burst int) *Limiter {
return &Limiter{interval: interval, tau: interval * time.Duration(burst)}
}
// Allow decides at time now. When it refuses, retryAfter is how long until it would admit.
func (l *Limiter) Allow(now time.Time) (ok bool, retryAfter time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
tat := l.tat
if tat.Before(now) {
tat = now
}
newTAT := tat.Add(l.interval)
allowAt := newTAT.Add(-l.tau)
if now.Before(allowAt) {
return false, allowAt.Sub(now)
}
l.tat = newTAT
return true, 0
}
// Remaining reports how many more events would be admitted back to back at now.
func (l *Limiter) Remaining(now time.Time) int {
l.mu.Lock()
defer l.mu.Unlock()
tat := l.tat
if tat.Before(now) {
tat = now
}
left := l.tau - tat.Sub(now)
if left < 0 {
return 0
}
return int(left / l.interval)
}package gcra
import (
"testing"
"time"
"golang.org/x/time/rate"
)
func TestBurstThenSteadyRate(t *testing.T) {
l := New(100*time.Millisecond, 3)
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
for i := 0; i < 3; i++ {
if ok, _ := l.Allow(now); !ok {
t.Fatalf("burst event %d refused", i+1)
}
}
ok, retry := l.Allow(now)
if ok || retry != 100*time.Millisecond {
t.Fatalf("ok=%v retry=%v, want refused with 100ms", ok, retry)
}
if ok, _ := l.Allow(now.Add(100 * time.Millisecond)); !ok {
t.Fatal("event after one interval must pass")
}
if got := l.Remaining(now.Add(100 * time.Millisecond)); got != 0 {
t.Fatalf("Remaining = %d, want 0", got)
}
if got := l.Remaining(now.Add(time.Hour)); got != 3 {
t.Fatalf("Remaining after idling = %d, want 3", got)
}
}
// GCRA and the token bucket are the same machine: on the same trace they must agree.
func TestMatchesTokenBucket(t *testing.T) {
const interval = 100 * time.Millisecond
g := New(interval, 3)
b := rate.NewLimiter(rate.Every(interval), 3)
start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
offsets := []int{0, 10, 20, 30, 40, 150, 160, 170, 400, 410, 420, 430, 440, 1000, 1001, 1002, 1003}
for _, ms := range offsets {
at := start.Add(time.Duration(ms) * time.Millisecond)
gOK, _ := g.Allow(at)
bOK := b.AllowN(at, 1)
if gOK != bOK {
t.Fatalf("t=%dms: gcra=%v token bucket=%v", ms, gOK, bOK)
}
}
}Per-key limiters and eviction Must-know
In plain words: One global limiter treats the whole internet as one caller. In practice you want one bucket per IP, API key or user, so a noisy client cannot starve the rest. That means a map from key to limiter, and a plan for the map not to grow forever.
Common misunderstanding: "Delete idle keys whenever memory looks big." Evicting a limiter resets its bucket. If the key's bucket was nearly empty, the recreated one is full, and the client just earned a free burst. Eviction is invisible only when the key was idle at least burst / rate seconds (the bucket would be full anyway).
Definition: keyed.Map holds map[string]*entry{lim, seen} under one mutex; Decide(key) returns a Decision (allowed, limit, remaining, retry-after, reset); Sweep(ttl) deletes entries unseen for ttl.
r = 1/s, b = 3 (full refill 3s), key "idle" drained at t0
1 t0+3s Sweep(ttl 3s) -> nothing removed (seen exactly ttl ago, not older)
2 t0+4s Sweep(ttl 3s) -> "idle" removed; next request recreates it FULL = same as the old bucket
3 ttl 500ms instead of 3s -> bucket was only 1/3 full, recreated one is full: free burstReal scenario: per-IP limiting on a public endpoint (millions of IPs a day), per-API-key limits (thousands of keys, long-lived), per-user limits on a login form.
| Strategy | Memory bound | Eviction risk | Use |
|---|---|---|---|
Map + periodic Sweep(ttl >= burst/rate) | Active keys in the last ttl | None | Default |
LRU(capacity) | Hard capacity | A flood of fake keys flushes real ones | Many keys, hostile traffic plus a global limit |
| Redis keys with TTL | Redis memory | TTL set to the refill time | Many replicas |
| No eviction | Unbounded | Memory growth, DoS | Never for IPs |
Fix / how to use it: run Sweep from a ticker goroutine tied to the server's context; never hold the map's lock while calling the limiter (the snippet unlocks first).
// Package keyed holds one token bucket per key (IP, API key, tenant) and shows
// three ways to keep that map from growing forever.
package keyed
import (
"container/list"
"hash/maphash"
"math"
"sync"
"time"
"golang.org/x/time/rate"
"academy/rate-limiting-in-go/internal/fakeclock"
)
// Decision is everything an HTTP or gRPC layer needs to answer a client.
type Decision struct {
Allowed bool
Limit int // burst size, advertised as the quota
Remaining int // whole tokens left after this decision
RetryAfter time.Duration // zero when allowed
Reset time.Duration // time until the bucket is full again
}
func decide(lim *rate.Limiter, now time.Time) Decision {
ok := lim.AllowN(now, 1)
tokens := lim.TokensAt(now)
d := Decision{Allowed: ok, Limit: lim.Burst(), Remaining: int(math.Max(0, math.Floor(tokens)))}
r := float64(lim.Limit())
if r > 0 {
d.Reset = time.Duration((float64(lim.Burst()) - tokens) / r * float64(time.Second))
if !ok {
d.RetryAfter = time.Duration((1 - tokens) / r * float64(time.Second))
}
}
return d
}
type entry struct {
lim *rate.Limiter
seen time.Time
}
// Map is the simplest per-key limiter: a mutex-guarded map plus a Sweep method.
type Map struct {
mu sync.Mutex
m map[string]*entry
r rate.Limit
burst int
clk fakeclock.Clock
}
// NewMap gives every key its own bucket of size burst refilled at r per second.
func NewMap(r rate.Limit, burst int, clk fakeclock.Clock) *Map {
return &Map{m: make(map[string]*entry), r: r, burst: burst, clk: clk}
}
// Decide takes one token from key's bucket.
func (k *Map) Decide(key string) Decision {
now := k.clk.Now()
k.mu.Lock()
e, ok := k.m[key]
if !ok {
e = &entry{lim: rate.NewLimiter(k.r, k.burst)}
k.m[key] = e
}
e.seen = now
k.mu.Unlock()
return decide(e.lim, now)
}
// Len returns the number of tracked keys.
func (k *Map) Len() int {
k.mu.Lock()
defer k.mu.Unlock()
return len(k.m)
}
// Sweep deletes keys not seen for ttl and returns how many it removed.
// Safe only when ttl >= burst/rate: by then the bucket would be full anyway,
// so a recreated limiter starts in exactly the state the old one would have.
func (k *Map) Sweep(ttl time.Duration) int {
cut := k.clk.Now().Add(-ttl)
k.mu.Lock()
defer k.mu.Unlock()
n := 0
for key, e := range k.m {
if e.seen.Before(cut) {
delete(k.m, key)
n++
}
}
return n
}
// LRU bounds memory at capacity keys by evicting the least recently used one.
// An attacker who sends capacity+1 distinct keys flushes honest keys and resets
// their buckets, so pair it with a coarser global limit.
type LRU struct {
mu sync.Mutex
cap int
ll *list.List
items map[string]*list.Element
r rate.Limit
burst int
clk fakeclock.Clock
}
type lruItem struct {
key string
lim *rate.Limiter
}
// NewLRU returns a bounded per-key limiter.
func NewLRU(capacity int, r rate.Limit, burst int, clk fakeclock.Clock) *LRU {
return &LRU{cap: capacity, ll: list.New(), items: make(map[string]*list.Element), r: r, burst: burst, clk: clk}
}
// Decide takes one token from key's bucket, creating or evicting as needed.
func (l *LRU) Decide(key string) Decision {
now := l.clk.Now()
l.mu.Lock()
var lim *rate.Limiter
if el, ok := l.items[key]; ok {
l.ll.MoveToFront(el)
lim = el.Value.(*lruItem).lim
} else {
lim = rate.NewLimiter(l.r, l.burst)
l.items[key] = l.ll.PushFront(&lruItem{key: key, lim: lim})
if l.ll.Len() > l.cap {
last := l.ll.Back()
l.ll.Remove(last)
delete(l.items, last.Value.(*lruItem).key)
}
}
l.mu.Unlock()
return decide(lim, now)
}
// Len returns the number of tracked keys.
func (l *LRU) Len() int {
l.mu.Lock()
defer l.mu.Unlock()
return l.ll.Len()
}
// Sharded spreads keys over independent Maps so goroutines rarely share a mutex.
type Sharded struct {
seed maphash.Seed
shards []*Map
}
// NewSharded builds n shards (n should be a power of two or at least a few times GOMAXPROCS).
func NewSharded(n int, r rate.Limit, burst int, clk fakeclock.Clock) *Sharded {
s := &Sharded{seed: maphash.MakeSeed(), shards: make([]*Map, n)}
for i := range s.shards {
s.shards[i] = NewMap(r, burst, clk)
}
return s
}
// Decide hashes the key to a shard and decides there.
func (s *Sharded) Decide(key string) Decision {
h := maphash.String(s.seed, key)
return s.shards[h%uint64(len(s.shards))].Decide(key)
}
// Sweep sweeps every shard.
func (s *Sharded) Sweep(ttl time.Duration) int {
n := 0
for _, sh := range s.shards {
n += sh.Sweep(ttl)
}
return n
}LRU, tenants and sharded limiters Good to know
In plain words: Two refinements. An LRU cache of limiters caps memory by dropping the least recently used key. A sharded limiter splits the map into many independent maps so goroutines rarely wait on the same mutex.
Common misunderstanding: "An LRU of limiters is a safe bound." The bound is safe for memory, not for fairness: an attacker who rotates capacity + 1 keys evicts everyone, and each victim returns with a full bucket. Pair it with a global limit.
Definition: keyed.LRU is a container/list plus a map. keyed.Sharded hashes the key with hash/maphash (random seed per process) and picks one of n Maps.
LRU capacity 2: a, b, a, c
1 Decide(a) -> [a]
2 Decide(b) -> [b a]
3 Decide(a) -> [a b] (a moved to front)
4 Decide(c) -> [c a] (b evicted: next Decide(b) starts with a fresh bucket)Real scenario: a multi-tenant SaaS where each tenant has a plan (Multi-Tenancy Strategies): the limiter key is the tenant id, the limits come from the plan row. Sharding matters above roughly ten thousand decisions per second per process.
| Option | When | Measured on 12 cores (see Mechanics) |
|---|---|---|
Single Map | Under a few thousand req/s | 184 ns/op |
Sharded with 64 shards | Contended hot path | 34 ns/op |
Fix / how to use it: the tests cover LRU order and a concurrent run under -race; benchmarks are in the same file.
package keyed
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"academy/rate-limiting-in-go/internal/fakeclock"
)
type decider interface{ Decide(string) Decision }
func TestKeysAreIndependent(t *testing.T) {
clk := fakeclock.New()
k := NewMap(1, 2, clk)
for i := 0; i < 2; i++ {
if !k.Decide("a").Allowed {
t.Fatal("a inside burst refused")
}
}
d := k.Decide("a")
if d.Allowed || d.RetryAfter != time.Second || d.Remaining != 0 || d.Limit != 2 {
t.Fatalf("a: %+v", d)
}
if !k.Decide("b").Allowed {
t.Fatal("b must have its own bucket")
}
}
func TestDecisionFields(t *testing.T) {
clk := fakeclock.New()
k := NewMap(1, 4, clk)
d := k.Decide("x")
if !d.Allowed || d.Remaining != 3 || d.Reset != time.Second {
t.Fatalf("%+v", d)
}
}
func TestSweepIsInvisibleWhenTTLCoversRefill(t *testing.T) {
clk := fakeclock.New()
k := NewMap(1, 3, clk) // full refill takes 3s
for i := 0; i < 3; i++ {
k.Decide("idle")
}
clk.Advance(3 * time.Second)
k.Decide("fresh")
if n := k.Sweep(3 * time.Second); n != 0 {
t.Fatalf("swept %d keys that were seen exactly ttl ago", n)
}
clk.Advance(time.Second)
if n := k.Sweep(3 * time.Second); n != 1 || k.Len() != 1 {
t.Fatalf("swept %d, len %d, want 1 and 1", n, k.Len())
}
// The recreated bucket equals what the old one would hold: full.
for i := 0; i < 3; i++ {
if !k.Decide("idle").Allowed {
t.Fatal("recreated limiter must start full")
}
}
}
func TestSweepTooEarlyHandsOutFreeBursts(t *testing.T) {
clk := fakeclock.New()
k := NewMap(1, 3, clk)
for i := 0; i < 3; i++ {
k.Decide("abuser")
}
clk.Advance(time.Second)
k.Sweep(500 * time.Millisecond) // ttl shorter than burst/rate: the bucket is only 1/3 full
if !k.Decide("abuser").Allowed || !k.Decide("abuser").Allowed {
t.Fatal("after an early sweep the key gets a full burst again")
}
}
func TestLRUEvictsLeastRecentlyUsed(t *testing.T) {
clk := fakeclock.New()
l := NewLRU(2, 1, 1, clk)
l.Decide("a")
l.Decide("b")
l.Decide("a") // a is now most recent; b is the eviction candidate
l.Decide("c") // evicts b
if l.Len() != 2 {
t.Fatalf("len = %d", l.Len())
}
if !l.Decide("b").Allowed {
t.Fatal("b was evicted, so it starts with a fresh bucket")
}
if l.Decide("c").Allowed {
t.Fatal("c still has its old (empty) bucket")
}
}
func TestShardedSameAnswersAsMapUnderConcurrency(t *testing.T) {
clk := fakeclock.New()
s := NewSharded(16, 1, 5, clk)
var allowed atomic.Int64
var wg sync.WaitGroup
for g := 0; g < 50; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 20; i++ {
if s.Decide(fmt.Sprintf("key-%d", i%4)).Allowed {
allowed.Add(1)
}
}
}()
}
wg.Wait()
if allowed.Load() != 4*5 {
t.Fatalf("allowed %d, want 20 (4 keys x burst 5)", allowed.Load())
}
}
func benchDecider(b *testing.B, d decider) {
var n atomic.Uint64
b.RunParallel(func(pb *testing.PB) {
keys := make([]string, 1024)
for i := range keys {
keys[i] = fmt.Sprintf("10.0.%d.%d", i/256, i%256)
}
i := int(n.Add(1)) * 7
for pb.Next() {
d.Decide(keys[i&1023])
i++
}
})
}
func BenchmarkMapSingleMutex(b *testing.B) {
benchDecider(b, NewMap(1e9, 1<<30, fakeclock.System{}))
}
func BenchmarkSharded64(b *testing.B) {
benchDecider(b, NewSharded(64, 1e9, 1<<30, fakeclock.System{}))
}Concurrency limits with semaphore.Weighted Must-know
In plain words: A rate limit says "start at most 100 per second". A concurrency limit says "at most 20 running at once". When the downstream is slow, a rate limit keeps starting work and the pile grows; a concurrency limit stops starting new work until old work finishes.
Common misunderstanding: "If I rate limit, I am protected from overload." Little's law: concurrency = rate x latency. At 100 requests per second and 50 ms latency you hold 5 in flight; when latency becomes 2 s, the same rate holds 200. Only a concurrency limit notices.
Definition: golang.org/x/sync/semaphore.NewWeighted(n); Acquire(ctx, w) blocks until w units are free or ctx ends; TryAcquire(w) never blocks; Release(w). Asking for more than the total size blocks until ctx is done and then returns ctx.Err() (source: "Don't make other Acquire calls block on one that's doomed to fail").
Pool of 1, G1 running
1 G2: Do(ctx) -> Acquire waits (backpressure)
2 G3: TryDo -> ErrBusy at once (load shedding)
3 G2: ctx times out -> returns context deadline exceeded, slot never taken
4 G1: finishes -> Release(1)Real scenario: at most 10 concurrent image resizes; at most 5 connections to a legacy SOAP service; at most 100 in-flight requests to protect memory.
| Question | Rate limit | Concurrency limit |
|---|---|---|
| Bounds | Starts per second | Calls in flight |
| Slow downstream | Pile-up grows | Self-regulating |
| Typical Go tool | rate.Limiter | semaphore.Weighted, buffered channel, worker pool |
| Response when full | 429 with Retry-After | 503 or wait (Worker Pools & Pipelines) |
Fix / how to use it: Do queues (backpressure), TryDo refuses (shedding); the test checks peak concurrency never exceeds the limit.
// Package concurrency limits how many calls are IN FLIGHT, which is a different
// question from how many calls START per second.
package concurrency
import (
"context"
"errors"
"golang.org/x/sync/semaphore"
)
// ErrBusy means every slot is taken and the caller chose not to queue.
var ErrBusy = errors.New("concurrency: all slots busy")
// Pool allows at most n calls to run at once.
type Pool struct {
sem *semaphore.Weighted
}
// New returns a Pool with n slots.
func New(n int64) *Pool { return &Pool{sem: semaphore.NewWeighted(n)} }
// Do waits for a slot (or ctx) and runs fn. This is backpressure: callers queue.
func (p *Pool) Do(ctx context.Context, fn func(context.Context) error) error {
if err := p.sem.Acquire(ctx, 1); err != nil {
return err
}
defer p.sem.Release(1)
return fn(ctx)
}
// TryDo never waits. This is load shedding: the caller is refused at once.
func (p *Pool) TryDo(ctx context.Context, fn func(context.Context) error) error {
if !p.sem.TryAcquire(1) {
return ErrBusy
}
defer p.sem.Release(1)
return fn(ctx)
}package concurrency
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/sync/semaphore"
)
func TestNeverMoreThanNInFlight(t *testing.T) {
p := New(3)
var cur, peak atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 30; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_ = p.Do(context.Background(), func(context.Context) error {
n := cur.Add(1)
for {
old := peak.Load()
if n <= old || peak.CompareAndSwap(old, n) {
break
}
}
time.Sleep(2 * time.Millisecond)
cur.Add(-1)
return nil
})
}()
}
wg.Wait()
if peak.Load() > 3 || peak.Load() == 0 {
t.Fatalf("peak concurrency = %d, want 1..3", peak.Load())
}
}
func TestTryDoShedsWhenFull(t *testing.T) {
p := New(1)
started, release := make(chan struct{}), make(chan struct{})
done := make(chan error, 1)
go func() {
done <- p.Do(context.Background(), func(context.Context) error {
close(started)
<-release
return nil
})
}()
<-started
if err := p.TryDo(context.Background(), func(context.Context) error { return nil }); !errors.Is(err, ErrBusy) {
t.Fatalf("err = %v, want ErrBusy", err)
}
close(release)
if err := <-done; err != nil {
t.Fatal(err)
}
}
func TestDoGivesUpWhenContextExpires(t *testing.T) {
p := New(1)
hold := make(chan struct{})
started := make(chan struct{})
go p.Do(context.Background(), func(context.Context) error { close(started); <-hold; return nil })
<-started
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err := p.Do(ctx, func(context.Context) error { return nil })
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context deadline exceeded", err)
}
close(hold)
}
// Asking for more weight than the semaphore owns can never succeed: Acquire
// blocks until ctx is done, then returns ctx.Err().
func TestAcquireMoreThanSizeBlocksUntilContextDone(t *testing.T) {
s := semaphore.NewWeighted(2)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
if err := s.Acquire(ctx, 3); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
if s.TryAcquire(3) {
t.Fatal("TryAcquire(3) on size 2 must be false")
}
}Why the time.Ticker limiter fails Good to know
In plain words: The first limiter many people write is a time.Ticker and a loop that receives from its channel once per tick. It looks like "one per interval". It has no memory of idle time, no burst, no per-key state and no way to say "no".
Common misunderstanding: "A ticker accumulates ticks while I am busy, so I can catch up." It does the opposite. The time docs say "the ticker will adjust the time interval or drop ticks to make up for slow receivers". After eight idle intervals exactly one tick is waiting.
Definition: Wait receives from ticker.C (or ctx.Done()); Allow does a non-blocking receive. Since Go 1.23 timer channels are synchronous (capacity 0) and unstopped tickers are collected, but one pending tick can still be received.
interval 10ms, nobody calls for 80ms
1 Allow -> true (the one tick that is pending)
2 Allow -> false (the other seven were dropped, not saved)
3 Allow -> falseReal scenario: a script limited to one call per second works until the day a call takes 3 s; then it fires immediately afterwards instead of waiting, or after idling it cannot send two quick calls although the bucket "should" allow a small burst.
| Property | time.Ticker loop | rate.Limiter |
|---|---|---|
| Burst after idle | None (one tick) | Up to burst |
| Non-blocking check | Racy: consumes a possibly stale tick | Allow is exact |
| Per-key | One ticker (and goroutine-free but one rate) per key | Cheap map entries |
| Cancel | select on ctx.Done() | Wait(ctx) |
| Cleanup | Call Stop (before Go 1.23 required for GC) | None |
Fix / how to use it: use rate.Limiter; the naive package exists only so the tests can show the failure.
package naive
import (
"testing"
"time"
)
// A ticker channel holds one tick. Idle time does not accumulate, so there is
// no burst: after a long pause exactly one event is available, not five.
func TestNoBurstAfterIdle(t *testing.T) {
l := New(10 * time.Millisecond)
defer l.Stop()
time.Sleep(80 * time.Millisecond) // eight intervals pass with nobody calling
allowed := 0
for i := 0; i < 8; i++ {
if l.Allow() {
allowed++
}
}
if allowed != 1 {
t.Fatalf("allowed %d events after idling, want exactly 1 (ticks are dropped, not saved)", allowed)
}
}
// The tick that Allow consumes may be old: Allow answers "was there a tick
// since I last looked", not "is the rate respected right now".
func TestAllowConsumesStaleTick(t *testing.T) {
l := New(10 * time.Millisecond)
defer l.Stop()
time.Sleep(35 * time.Millisecond)
if !l.Allow() {
t.Fatal("expected a buffered tick")
}
if l.Allow() {
t.Fatal("second call must find the channel empty")
}
}HTTP middleware: per-IP, trusted proxies, API keys Must-know
In plain words: A middleware wraps the handler, derives a key from the request, asks the limiter, and either lets the request through with quota headers or answers 429 with Retry-After. The hard part is the key: behind a load balancer every request's RemoteAddr is the load balancer.
Common misunderstanding: "Read the first address in X-Forwarded-For." The first address is the one the client wrote; anyone can send X-Forwarded-For: 1.2.3.4 and rotate it to get a fresh bucket each time. The correct rule: trust the header only if the TCP peer is one of your own proxies, then walk the list from the right, skipping your own proxies, and use the first address that is not yours.
Definition: httpmw.ClientIP(r, trusted []netip.Prefix); httpmw.ByIP, httpmw.ByAPIKey(header, fallback); httpmw.Limit(decider, keyFunc) returns func(http.Handler) http.Handler.
trusted = 10.0.0.0/8
1 peer 203.0.113.7, header "198.51.100.1" -> key 203.0.113.7 (peer untrusted, header ignored)
2 peer 10.0.0.2, header "1.2.3.4, 198.51.100.9" -> key 198.51.100.9 (right-most untrusted hop)
3 peer 10.0.0.2, header "198.51.100.9, 10.0.0.3" -> key 198.51.100.9 (10.0.0.3 is our proxy)
4 peer 10.0.0.2, header "not-an-ip" -> key 10.0.0.2 (fall back to the proxy)Real scenario: a public JSON API behind nginx or a cloud load balancer; an internal API where clients present X-API-Key; a login endpoint that needs a stricter, separate limiter per account.
| Identity | Key | Risk |
|---|---|---|
| Direct connection | RemoteAddr host | NAT: many users share one IP; IPv6 users have a /64 or more, so key IPv6 by prefix if you need to |
| Behind trusted proxies | Right-most untrusted X-Forwarded-For hop | Misconfigured trusted list gives spoofing or one shared key |
| API key | key:<value> | Do not log the raw key; hash it for metrics |
| Authenticated user | User id after authentication | Run the limiter after auth, plus a coarse per-IP limiter before it |
Fix / how to use it:
// Package httpmw is a net/http middleware that rate limits per client IP or per API key
// and speaks the RateLimit-* and Retry-After header vocabulary.
package httpmw
import (
"math"
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"time"
"academy/rate-limiting-in-go/keyed"
)
// Decider is satisfied by keyed.Map, keyed.LRU and keyed.Sharded.
type Decider interface {
Decide(key string) keyed.Decision
}
// KeyFunc extracts the identity to limit. ok=false means "no usable identity".
type KeyFunc func(r *http.Request) (key string, ok bool)
// Limit returns middleware that applies d to every request.
func Limit(d Decider, key KeyFunc) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
k, ok := key(r)
if !ok {
http.Error(w, "missing client identity", http.StatusBadRequest)
return
}
dec := d.Decide(k)
SetHeaders(w.Header(), dec)
if !dec.Allowed {
w.Header().Set("Retry-After", strconv.Itoa(ceilSeconds(dec.RetryAfter)))
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}
// SetHeaders writes the three widely deployed RateLimit fields from the earlier
// IETF drafts: a quota, what is left, and seconds until the quota is whole again.
func SetHeaders(h http.Header, d keyed.Decision) {
h.Set("RateLimit-Limit", strconv.Itoa(d.Limit))
h.Set("RateLimit-Remaining", strconv.Itoa(d.Remaining))
h.Set("RateLimit-Reset", strconv.Itoa(ceilSeconds(d.Reset)))
}
func ceilSeconds(d time.Duration) int {
if d <= 0 {
return 0
}
return int(math.Ceil(d.Seconds()))
}
// ByIP keys on the client address after resolving X-Forwarded-For against trusted proxies.
func ByIP(trusted []netip.Prefix) KeyFunc {
return func(r *http.Request) (string, bool) {
ip, ok := ClientIP(r, trusted)
if !ok {
return "", false
}
return ip.String(), true
}
}
// ByAPIKey keys on a header value and falls back to another KeyFunc (usually ByIP).
func ByAPIKey(header string, fallback KeyFunc) KeyFunc {
return func(r *http.Request) (string, bool) {
if v := strings.TrimSpace(r.Header.Get(header)); v != "" {
return "key:" + v, true
}
return fallback(r)
}
}
// ClientIP returns the first address, reading X-Forwarded-For from the right,
// that is not one of our own trusted proxies. The header is only believed when
// the TCP peer itself is trusted; otherwise any client could write its own value.
func ClientIP(r *http.Request, trusted []netip.Prefix) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
peer, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
peer = peer.Unmap()
if !isTrusted(peer, trusted) {
return peer, true
}
hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",")
for i := len(hops) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
if err != nil {
return peer, true // garbage in the chain: fall back to the proxy itself
}
a = a.Unmap()
if !isTrusted(a, trusted) {
return a, true
}
}
return peer, true
}
func isTrusted(a netip.Addr, trusted []netip.Prefix) bool {
for _, p := range trusted {
if p.Contains(a) {
return true
}
}
return false
}package httpmw
import (
"net/http"
"net/http/httptest"
"net/netip"
"testing"
"time"
"academy/rate-limiting-in-go/internal/fakeclock"
"academy/rate-limiting-in-go/keyed"
)
var proxies = []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}
func req(remote, xff string) *http.Request {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = remote
if xff != "" {
r.Header.Set("X-Forwarded-For", xff)
}
return r
}
func TestClientIPTrustRules(t *testing.T) {
cases := []struct{ name, remote, xff, want string }{
{"direct client", "203.0.113.7:5555", "", "203.0.113.7"},
{"spoofed header from an untrusted peer is ignored", "203.0.113.7:5555", "198.51.100.1", "203.0.113.7"},
{"one trusted proxy", "10.0.0.2:4000", "198.51.100.9", "198.51.100.9"},
{"client-supplied prefix is skipped, real hop wins", "10.0.0.2:4000", "1.2.3.4, 198.51.100.9", "198.51.100.9"},
{"two trusted hops", "10.0.0.2:4000", "198.51.100.9, 10.0.0.3", "198.51.100.9"},
{"garbage falls back to the proxy", "10.0.0.2:4000", "not-an-ip", "10.0.0.2"},
{"ipv4-mapped ipv6", "[::ffff:203.0.113.7]:80", "", "203.0.113.7"},
}
for _, c := range cases {
got, ok := ClientIP(req(c.remote, c.xff), proxies)
if !ok || got.String() != c.want {
t.Errorf("%s: got %v ok=%v, want %s", c.name, got, ok, c.want)
}
}
}
func TestMiddlewareHeadersAnd429(t *testing.T) {
clk := fakeclock.New()
lim := keyed.NewMap(1, 2, clk) // 1 per second, burst 2
h := Limit(lim, ByIP(proxies))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
do := func(remote string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req(remote, ""))
return rec
}
r1 := do("203.0.113.7:1")
if r1.Code != 204 || r1.Header().Get("RateLimit-Limit") != "2" || r1.Header().Get("RateLimit-Remaining") != "1" {
t.Fatalf("first: %d %v", r1.Code, r1.Header())
}
do("203.0.113.7:2")
r3 := do("203.0.113.7:3")
if r3.Code != 429 || r3.Header().Get("Retry-After") != "1" || r3.Header().Get("RateLimit-Remaining") != "0" {
t.Fatalf("third: %d %v", r3.Code, r3.Header())
}
if other := do("203.0.113.8:1"); other.Code != 204 {
t.Fatalf("another IP must have its own bucket, got %d", other.Code)
}
clk.Advance(time.Second)
if again := do("203.0.113.7:4"); again.Code != 204 {
t.Fatalf("after a second the first IP may call again, got %d", again.Code)
}
}
func TestByAPIKeyFallsBackToIP(t *testing.T) {
kf := ByAPIKey("X-API-Key", ByIP(nil))
r := req("203.0.113.7:1", "")
if k, _ := kf(r); k != "203.0.113.7" {
t.Fatalf("key = %q", k)
}
r.Header.Set("X-API-Key", "k_live_123")
if k, _ := kf(r); k != "key:k_live_123" {
t.Fatalf("key = %q", k)
}
}The response vocabulary: 429, Retry-After, RateLimit-* Must-know
In plain words: A refused client should be told two things: "you were refused" (429) and "come back in N seconds" (Retry-After). Quota headers on every response let well-behaved clients slow down before they are refused.
Common misunderstanding: "Return 503 or 403 for rate limits." 503 means the server is overloaded or down (and also may carry Retry-After); 403 means forbidden. RFC 6585 added 429 for exactly this case: "the user has sent too many requests in a given amount of time". Clients, SDKs and CDNs treat the three differently.
Definition: Retry-After is HTTP-date / delay-seconds (RFC 9110); delay-seconds is a non-negative integer, so a fractional wait is rounded up. The RateLimit-* fields are an Internet-Draft; per the draft, "If a response contains both the RateLimit and Retry-After fields, the Retry-After field MUST take precedence".
HTTP/1.1 429 Too Many Requests
Retry-After: 1
RateLimit-Limit: 20
RateLimit-Remaining: 0
RateLimit-Reset: 1
Content-Type: text/plain; charset=utf-8Real scenario: a mobile SDK reads Retry-After and backs off; a dashboard shows RateLimit-Remaining; a CDN caches the 429 for the Retry-After period.
| Field | Format | Rounding rule |
|---|---|---|
Retry-After | Integer seconds (or HTTP-date) | Round up, never 0 on a refusal |
RateLimit-Limit | Integer | The bucket size (burst) here |
RateLimit-Remaining | Integer | Floor of tokens |
RateLimit-Reset | Integer seconds | Time until the bucket is full |
RateLimit-Policy: default;q=20;w=2 (draft-12) | Structured field list | Optional; send in addition if clients want it |
Fix / how to use it: SetHeaders and Limit in the snippet above; the test asserts a 429 carries Retry-After: 1 and RateLimit-Remaining: 0.
Client-side limiting for outbound calls Must-know
In plain words: When your service calls someone else's API, you are the one who must stay polite: a local limiter spaces your calls, and if the server still says 429, you obey its Retry-After.
Common misunderstanding: "Retry immediately on 429." That turns one refusal into a storm. The server told you how long to wait; sleeping less is how accounts get blocked. Also, never retry a request whose body you cannot replay.
Definition: client.Transport is an http.RoundTripper: Limiter.Wait(ctx) before every attempt; on 429 parse Retry-After (seconds or HTTP-date), refuse to sit out more than MaxWait, drain and close the old body, sleep, then retry up to MaxRetries with GetBody for replay.
1 RoundTrip: Wait(ctx) -> a token after 0 ms
2 server: 429 Retry-After: 7
3 Transport: 7s <= MaxWait -> drain body, Sleep(ctx, 7s)
4 RoundTrip: Wait(ctx) -> token
5 server: 200 -> returned to the caller
(Retry-After: 3600 > MaxWait -> the 429 is returned to the caller unchanged)Real scenario: a payments client with 50 requests per second per merchant; a GitHub-style API with a rolling quota; a webhook sender per customer endpoint.
| Concern | Rule |
|---|---|
| Deadline | Wait(ctx) returns rate: Wait(n=1) would exceed context deadline immediately instead of sleeping past the deadline |
| Many hosts | One limiter per host, per per-key rules |
| Body replay | Needs Request.GetBody (set by http.NewRequest for bytes.Reader, strings.Reader) |
| Jitter | Add jitter on top of Retry-After for many clients (Timeouts, Retries & Jitter) |
| Transport reuse | Share one http.Client; see HTTP Server & Client |
Fix / how to use it:
// Package client rate limits OUTBOUND HTTP calls: a local token bucket decides
// when a request may leave, and a 429 with Retry-After makes the transport pause.
package client
import (
"context"
"io"
"net/http"
"strconv"
"strings"
"time"
"golang.org/x/time/rate"
)
// Transport wraps another RoundTripper.
type Transport struct {
Base http.RoundTripper // nil means http.DefaultTransport
Limiter *rate.Limiter // our own politeness budget
MaxRetries int // extra attempts after a 429
MaxWait time.Duration // longest Retry-After we are willing to sit out
Sleep func(ctx context.Context, d time.Duration) error
Now func() time.Time
}
// RoundTrip waits for a token, sends, and honours Retry-After on 429.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
base := t.Base
if base == nil {
base = http.DefaultTransport
}
ctx := req.Context()
for attempt := 0; ; attempt++ {
if err := t.Limiter.Wait(ctx); err != nil {
return nil, err // burst misconfiguration, deadline or cancellation
}
resp, err := base.RoundTrip(req)
if err != nil || resp.StatusCode != http.StatusTooManyRequests || attempt >= t.MaxRetries {
return resp, err
}
wait, ok := RetryAfter(resp.Header.Get("Retry-After"), t.Now())
if !ok || wait > t.MaxWait {
return resp, nil // the caller sees the 429 and decides
}
retry, err := rewind(req)
if err != nil {
return resp, nil
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
resp.Body.Close()
if err := t.Sleep(ctx, wait); err != nil {
return nil, err
}
req = retry
}
}
// rewind returns a request that can be sent again, or an error if the body cannot be replayed.
func rewind(req *http.Request) (*http.Request, error) {
if req.Body == nil || req.Body == http.NoBody {
return req, nil
}
if req.GetBody == nil {
return nil, io.ErrUnexpectedEOF
}
body, err := req.GetBody()
if err != nil {
return nil, err
}
c := req.Clone(req.Context())
c.Body = body
return c, nil
}
// RetryAfter parses delay-seconds or an HTTP-date, the two forms RFC 9110 allows.
func RetryAfter(v string, now time.Time) (time.Duration, bool) {
v = strings.TrimSpace(v)
if v == "" {
return 0, false
}
if secs, err := strconv.ParseInt(v, 10, 64); err == nil {
if secs < 0 {
return 0, false
}
return time.Duration(secs) * time.Second, true
}
if at, err := http.ParseTime(v); err == nil {
if d := at.Sub(now); d > 0 {
return d, true
}
return 0, true
}
return 0, false
}package client
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"golang.org/x/time/rate"
)
func TestRetryAfterForms(t *testing.T) {
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
cases := []struct {
in string
want time.Duration
ok bool
}{
{"120", 120 * time.Second, true},
{"0", 0, true},
{"-5", 0, false},
{"Thu, 01 Jan 2026 12:00:30 GMT", 30 * time.Second, true},
{"Thu, 01 Jan 2026 11:00:00 GMT", 0, true},
{"soon", 0, false},
{"", 0, false},
}
for _, c := range cases {
got, ok := RetryAfter(c.in, now)
if got != c.want || ok != c.ok {
t.Errorf("%q: got %v,%v want %v,%v", c.in, got, ok, c.want, c.ok)
}
}
}
func newTransport(slept *[]time.Duration) *Transport {
return &Transport{
Limiter: rate.NewLimiter(rate.Inf, 0),
MaxRetries: 2,
MaxWait: time.Minute,
Now: time.Now,
Sleep: func(_ context.Context, d time.Duration) error {
*slept = append(*slept, d)
return nil
},
}
}
func TestSleepsRetryAfterThenSucceeds(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1) == 1 {
w.Header().Set("Retry-After", "7")
w.WriteHeader(http.StatusTooManyRequests)
return
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
var slept []time.Duration
c := &http.Client{Transport: newTransport(&slept)}
resp, err := c.Post(srv.URL, "text/plain", strings.NewReader("payload"))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 || hits.Load() != 2 {
t.Fatalf("status %d after %d hits", resp.StatusCode, hits.Load())
}
if len(slept) != 1 || slept[0] != 7*time.Second {
t.Fatalf("slept %v, want [7s]", slept)
}
}
func TestGivesUpWhenRetryAfterIsTooLong(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "3600")
w.WriteHeader(http.StatusTooManyRequests)
}))
defer srv.Close()
var slept []time.Duration
c := &http.Client{Transport: newTransport(&slept)}
resp, err := c.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 429 || len(slept) != 0 {
t.Fatalf("status %d slept %v: an hour is too long to sit out", resp.StatusCode, slept)
}
}
func TestLimiterErrorsSurface(t *testing.T) {
tr := &Transport{Limiter: rate.NewLimiter(1, 1), Now: time.Now}
tr.Limiter.Allow() // drain
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "http://192.0.2.1/", nil)
_, err := tr.RoundTrip(req)
if err == nil || err.Error() != "rate: Wait(n=1) would exceed context deadline" {
t.Fatalf("err = %v", err)
}
}Distributed limiter with Redis and Lua Important
In plain words: A per-process limiter lets each of N replicas admit the full rate, so the cluster admits N times the limit. A shared limiter keeps the state in one place, usually Redis, and makes the read-modify-write atomic with a Lua script.
Common misunderstanding: "GET then SET from Go is fine." Two replicas can both read the same value, both admit, and both write. The check and the update must be one atomic step; Redis runs a script atomically (EVAL/EVALSHA, see the Redis scripting docs). A related trap: client clocks drift, so read the time inside the script with redis.call('TIME').
Definition: redislimiter.Limiter runs a GCRA script through redis.NewScript(...) from go-redis v9 (Run tries EVALSHA first and falls back to EVAL). The script returns {allowed, remaining, retry_after_ms}. It is brief here because the design lives in Rate Limiting: Token Bucket, Leaky Bucket, Windows, Distributed Limits and the data structure in Redis.
replica 1 and 2, same key, bucket nearly empty
1 R1: EVALSHA gcra.lua rl:user:42 100 5 -> {1, 0, 0}
2 R2: EVALSHA gcra.lua rl:user:42 100 5 -> {0, 0, 98} (sees R1's write; script ran after it)
3 Redis down: R1 Allow -> error -> caller picks fail-open, fail-closed or local fallbackReal scenario: a 1000-requests-per-minute plan enforced across 12 pods; a login throttle shared by all instances; an API gateway tier that keeps buckets in a Redis cluster.
| Concern | Choice | Cost |
|---|---|---|
| Redis unreachable | Fail open (FailOpen) keeps the site up, unprotected; fail closed is safe but an outage | Decide per endpoint |
| Latency | One round trip per request; add a local pre-filter | +0.2 to 1 ms in-region (typical, not measured here) |
| Redis Cluster | All keys of a script must hash to one slot; use {tag} | Hot keys concentrate |
| Hot keys | One key per client is fine; one global key is a bottleneck | Shard the key |
| Scripts and replication | Effects replication is the default since Redis 5.0 and the only mode from 7.0, so reading TIME in a script is safe | Very old servers differ; check yours |
Fix / how to use it: the code compiles and its tests use a fake redis.Scripter; running it against a real Redis is "expected, not run".
// Package redislimiter shares one GCRA bucket per key across many processes.
// The decision runs inside Redis as a Lua script, so it is atomic and uses ONE
// clock (the Redis server's) instead of every app server's.
package redislimiter
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
// script returns {allowed, remaining, retry_after_ms}. KEYS[1] is the bucket key.
// ARGV[1] = emission interval in ms, ARGV[2] = burst.
const luaSource = `
local emission = tonumber(ARGV[1])
local burst = tonumber(ARGV[2])
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local tat = tonumber(redis.call('GET', KEYS[1]))
if tat == nil or tat < now then tat = now end
local new_tat = tat + emission
local allow_at = new_tat - emission * burst
if now < allow_at then
return {0, 0, math.ceil(allow_at - now)}
end
redis.call('SET', KEYS[1], new_tat, 'PX', math.ceil(new_tat - now))
local remaining = math.floor((now + emission * burst - new_tat) / emission)
return {1, remaining, 0}
`
var script = redis.NewScript(luaSource)
// Limiter talks to any redis.Scripter: *redis.Client, *redis.ClusterClient, or a test double.
type Limiter struct {
rdb redis.Scripter
interval time.Duration
burst int
}
// New builds a limiter admitting one event per interval with bursts up to burst.
func New(rdb redis.Scripter, interval time.Duration, burst int) *Limiter {
return &Limiter{rdb: rdb, interval: interval, burst: burst}
}
// Result is the script's answer.
type Result struct {
Allowed bool
Remaining int
RetryAfter time.Duration
}
// Allow runs the script for key. In Redis Cluster put a {hash tag} in the key if you add more keys.
func (l *Limiter) Allow(ctx context.Context, key string) (Result, error) {
vals, err := script.Run(ctx, l.rdb, []string{key}, l.interval.Milliseconds(), l.burst).Int64Slice()
if err != nil {
return Result{}, err // the caller chooses fail-open or fail-closed
}
if len(vals) != 3 {
return Result{}, fmt.Errorf("redislimiter: script returned %d values, want 3", len(vals))
}
return Result{
Allowed: vals[0] == 1,
Remaining: int(vals[1]),
RetryAfter: time.Duration(vals[2]) * time.Millisecond,
}, nil
}
// FailOpen turns a Redis outage into "allow", which keeps the site up but unprotected.
func FailOpen(r Result, err error) Result {
if err != nil {
return Result{Allowed: true, Remaining: -1}
}
return r
}package redislimiter
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/redis/go-redis/v9"
)
// fake satisfies redis.Scripter without a server. It records what the limiter sent.
type fake struct {
reply any
err error
keys []string
args []any
scripts []string
}
func (f *fake) run(script string, keys []string, args []any) *redis.Cmd {
f.keys, f.args = keys, args
f.scripts = append(f.scripts, script)
return redis.NewCmdResult(f.reply, f.err)
}
func (f *fake) Eval(_ context.Context, s string, k []string, a ...any) *redis.Cmd {
return f.run(s, k, a)
}
func (f *fake) EvalSha(_ context.Context, s string, k []string, a ...any) *redis.Cmd {
return f.run(s, k, a)
}
func (f *fake) EvalRO(_ context.Context, s string, k []string, a ...any) *redis.Cmd {
return f.run(s, k, a)
}
func (f *fake) EvalShaRO(_ context.Context, s string, k []string, a ...any) *redis.Cmd {
return f.run(s, k, a)
}
func (f *fake) ScriptExists(context.Context, ...string) *redis.BoolSliceCmd {
return redis.NewBoolSliceCmd(context.Background())
}
func (f *fake) ScriptLoad(context.Context, string) *redis.StringCmd {
return redis.NewStringCmd(context.Background())
}
func TestAllowedAndRefusedAreParsed(t *testing.T) {
f := &fake{reply: []any{int64(1), int64(4), int64(0)}}
l := New(f, 100*time.Millisecond, 5)
res, err := l.Allow(context.Background(), "rl:user:42")
if err != nil || !res.Allowed || res.Remaining != 4 {
t.Fatalf("res=%+v err=%v", res, err)
}
if len(f.keys) != 1 || f.keys[0] != "rl:user:42" || f.args[0] != int64(100) || f.args[1] != 5 {
t.Fatalf("keys=%v args=%v", f.keys, f.args)
}
f.reply = []any{int64(0), int64(0), int64(250)}
res, _ = l.Allow(context.Background(), "rl:user:42")
if res.Allowed || res.RetryAfter != 250*time.Millisecond {
t.Fatalf("res=%+v", res)
}
}
func TestRedisErrorsAreVisibleAndFailOpenIsExplicit(t *testing.T) {
f := &fake{err: errors.New("dial tcp 192.0.2.10:6379: i/o timeout")}
res, err := New(f, time.Second, 1).Allow(context.Background(), "k")
if err == nil {
t.Fatal("the error must reach the caller")
}
if got := FailOpen(res, err); !got.Allowed {
t.Fatal("FailOpen must allow on error")
}
}
func TestScriptUsesServerTimeNotClientTime(t *testing.T) {
f := &fake{reply: []any{int64(1), int64(0), int64(0)}}
_, _ = New(f, time.Second, 1).Allow(context.Background(), "k")
if !strings.Contains(luaSource, "redis.call('TIME')") {
t.Fatal("the script must read the clock inside Redis")
}
// go-redis optimistically sends EVALSHA with the script's digest first.
if len(f.scripts) != 1 || f.scripts[0] != script.Hash() {
t.Fatalf("sent %v, want the script digest %s", f.scripts, script.Hash())
}
}gRPC interceptors Important
In plain words: In gRPC the same idea lives in an interceptor. A unary server interceptor runs before the handler and can refuse with a status code instead of an HTTP 429.
Common misunderstanding: "Return Unavailable for limits." The convention is codes.ResourceExhausted for a quota or rate limit; Unavailable means the server cannot serve right now, which is a different signal for clients. The gRPC status text is rpc error: code = ResourceExhausted desc = rate limit exceeded.
Definition: grpclimit.Unary(allow, key) returns a grpc.UnaryServerInterceptor; grpclimit.Stream limits stream creation, not messages inside a stream. The key can come from the peer address (peer.FromContext) or metadata.
client -> Unary interceptor -> Allower(key)
1 allowed -> handler runs, response
2 refused -> status.Error(codes.ResourceExhausted, "rate limit exceeded"), handler never runsReal scenario: a gRPC gateway limiting per client certificate; a streaming API limiting how many streams a user may open per minute (gRPC & Protobuf in Go).
| Concern | Rule |
|---|---|
| Status | ResourceExhausted |
| Key | Peer IP, mTLS identity, or an authenticated metadata value |
| Streams | Limit stream open rate and concurrent streams (semaphore) separately |
| Hint to client | Put a retry delay in trailers or a RetryInfo detail (not done in the snippet) |
Fix / how to use it:
// Package grpclimit rejects gRPC calls with RESOURCE_EXHAUSTED when a limiter says no.
package grpclimit
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// Allower decides for one identity. keyed.Map.Decide(key).Allowed fits.
type Allower func(key string) bool
// KeyFunc picks the identity: peer address, a metadata value, the method name.
type KeyFunc func(ctx context.Context, fullMethod string) string
// PeerKey uses the transport peer address.
func PeerKey(ctx context.Context, _ string) string {
if p, ok := peer.FromContext(ctx); ok {
return p.Addr.String()
}
return "unknown"
}
// Unary returns a server interceptor for unary RPCs.
func Unary(allow Allower, key KeyFunc) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
if !allow(key(ctx, info.FullMethod)) {
return nil, status.Error(codes.ResourceExhausted, "rate limit exceeded")
}
return next(ctx, req)
}
}
// Stream returns a server interceptor that limits stream creation, not messages.
func Stream(allow Allower, key KeyFunc) grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, next grpc.StreamHandler) error {
if !allow(key(ss.Context(), info.FullMethod)) {
return status.Error(codes.ResourceExhausted, "rate limit exceeded")
}
return next(srv, ss)
}
}package grpclimit
import (
"context"
"net"
"testing"
"golang.org/x/time/rate"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
func TestUnaryRejectsWithResourceExhausted(t *testing.T) {
lim := rate.NewLimiter(rate.Every(1e9), 1) // one call, then (almost) never again
icpt := Unary(func(string) bool { return lim.Allow() }, PeerKey)
ctx := peer.NewContext(context.Background(), &peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("203.0.113.7"), Port: 5000}})
info := &grpc.UnaryServerInfo{FullMethod: "/demo.Greeter/SayHello"}
handler := func(context.Context, any) (any, error) { return "hello", nil }
if got, err := icpt(ctx, nil, info, handler); err != nil || got != "hello" {
t.Fatalf("first call: %v %v", got, err)
}
_, err := icpt(ctx, nil, info, handler)
if status.Code(err) != codes.ResourceExhausted {
t.Fatalf("code = %v, want ResourceExhausted", status.Code(err))
}
if err.Error() != "rpc error: code = ResourceExhausted desc = rate limit exceeded" {
t.Fatalf("err text = %q", err.Error())
}
}
func TestPeerKey(t *testing.T) {
if PeerKey(context.Background(), "/x") != "unknown" {
t.Fatal("no peer in ctx should yield unknown")
}
}Testing without sleeping: fake clock, clock injection, synctest Must-know
In plain words: A limiter test that sleeps is slow and flaky. Give the limiter a clock you control, advance it by hand, and assert exact decisions.
Common misunderstanding: "rate.Limiter cannot take a fake clock." It does not have a clock field, but every decision method has a time-taking twin: AllowN(t, n), ReserveN(t, n), TokensAt(t), SetLimitAt(t, r), Reservation.DelayFrom(t), CancelAt(t). Wrap them in a type that reads an injected clock (stdlimit.Gate). Only Wait/WaitN use real time and a real timer, so wrap them with an injected sleeper.
Definition: three levels. (1) Clock injection: fakeclock.Fake with Advance(d). (2) Library hooks: ratelimit.WithClock for uber. (3) Go 1.25 testing/synctest: inside synctest.Test the clock is fake and jumps forward when every goroutine in the bubble is blocked, so even the real Limiter.Wait runs instantly.
//go:build go1.25
func TestWaitInBubble(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
lim := rate.NewLimiter(rate.Every(time.Second), 1)
start := time.Now()
for i := 0; i < 3; i++ {
_ = lim.Wait(context.Background())
}
// time.Since(start) == 2*time.Second, and the test took microseconds
})
}Real scenario: a regression test for "burst then refill" runs in microseconds; a CI job runs 200 limiter cases without one time.Sleep; a flaky test that failed once a week disappears.
| Technique | Works for | Limit |
|---|---|---|
...At(t) methods with a fake clock | Allow, Reserve, Tokens, SetLimit | Wait still uses real time |
Injected sleeper (Gate.Wait) | Wait semantics | You re-implement the thin wrapper |
ratelimit.WithClock | uber-go | Mock must implement Now and Sleep |
testing/synctest (Go 1.25+) | Anything using time and goroutines | No real I/O inside the bubble; file has a go1.25 build tag |
Fix / how to use it: the module ships fakeclock (above), and the build-tagged bubble test; both run in go test -race ./....
// Package fakeclock is a manually advanced clock for deterministic limiter tests.
package fakeclock
import (
"sync"
"time"
)
// Clock is the one method every limiter in this module needs.
type Clock interface {
Now() time.Time
}
// System is the production clock.
type System struct{}
// Now returns the wall clock time (with its monotonic reading).
func (System) Now() time.Time { return time.Now() }
// Fake only moves when Advance is called.
type Fake struct {
mu sync.Mutex
t time.Time
}
// New returns a Fake starting at a fixed, documentation-friendly instant.
func New() *Fake {
return &Fake{t: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)}
}
// Now returns the current fake time.
func (f *Fake) Now() time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return f.t
}
// Advance moves the fake time forward by d.
func (f *Fake) Advance(d time.Duration) {
f.mu.Lock()
f.t = f.t.Add(d)
f.mu.Unlock()
}//go:build go1.25
// Package fakeclockbubble uses testing/synctest (stable since Go 1.25): inside
// the bubble time.Now, timers and rate.Limiter.Wait all run on a fake clock
// that jumps forward whenever every goroutine in the bubble is blocked.
package fakeclockbubble
import (
"context"
"testing"
"testing/synctest"
"time"
"golang.org/x/time/rate"
)
func TestWaitInBubble(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
lim := rate.NewLimiter(rate.Every(time.Second), 1)
start := time.Now()
for i := 0; i < 3; i++ {
if err := lim.Wait(context.Background()); err != nil {
t.Fatal(err)
}
}
if got := time.Since(start); got != 2*time.Second {
t.Fatalf("elapsed %v, want 2s of fake time", got)
}
})
}Backpressure versus load shedding Important
In plain words: When demand exceeds capacity you can make callers wait (backpressure) or tell some of them to go away (shedding). A rate limiter sheds per caller; a concurrency limit with Acquire applies backpressure; a concurrency limit with TryAcquire sheds.
Common misunderstanding: "Waiting is always kinder than refusing." An unbounded queue turns overload into latency for everyone and memory growth for you. Past some queue age the work is useless anyway (the client has timed out).
Definition: backpressure: the producer is slowed (blocking call, bounded channel, Wait). Shedding: the request is refused at once (Allow false, TryAcquire false, 429 or 503). See Load Shedding, Backpressure & Flow Control and Bulkhead & Graceful Degradation.
queue bound 100, arrival 150/s, service 100/s
1 t = 0..2s queue fills to 100 (backpressure: callers block, latency climbs)
2 t > 2s queue full -> TryAcquire false -> 503 (shedding)
3 rate limiter in front: one noisy client gets 429, the others keep their quotaReal scenario: an internal worker pool uses backpressure (blocking send on a bounded channel, Worker Pools & Pipelines); a public API sheds with 429 for abuse and 503 for overload.
| Situation | Choose | Status |
|---|---|---|
| One caller too fast | Rate limit, shed | 429 + Retry-After |
| Server saturated, any caller | Concurrency limit, shed | 503 + Retry-After |
| Batch producer, bounded buffer | Backpressure | None (blocks) |
| Outbound to a partner | Wait(ctx) | None |
Fix / how to use it: combine them: per-key rate limit, then global concurrency limit, then handler timeout (Timeouts, Retries & Jitter).
Mechanics
Exact error and status texts Must-know
| Source | Exact text | When |
|---|---|---|
Limiter.WaitN | rate: Wait(n=4) exceeds limiter's burst 3 | n greater than burst and limit not Inf |
Limiter.WaitN | rate: Wait(n=1) would exceed context deadline | The reservation delay is longer than the time left on ctx |
Limiter.WaitN | context canceled / context deadline exceeded | ctx ended before or during the sleep |
semaphore.Acquire | context deadline exceeded | Waited past the deadline; slot never taken |
| gRPC | rpc error: code = ResourceExhausted desc = rate limit exceeded | Interceptor refusal |
| HTTP | 429 Too Many Requests + Retry-After: 1 | Middleware refusal |
| Redis | NOSCRIPT No matching script. Please use EVAL. | go-redis recovers by retrying with EVAL |
| Client body | unexpected EOF from rewind | A 429 retry needed a body that cannot be replayed |
What reserveN does Good to know
Under one mutex: advance tokens by elapsed * limit capped at burst; subtract n; if negative, the wait is -tokens / limit; the call is OK when n <= burst and the wait is at most maxFutureReserve (zero for Allow, InfDuration for Reserve, the time to the deadline for Wait). Only an OK call updates tokens, last and lastEvent. That is why Allow that returns false changes nothing, and why Reserve can push the bucket arbitrarily far into debt.
| Field | Meaning |
|---|---|
tokens | Current count, may be negative (reserved future events) |
last | When tokens was last brought up to date |
lastEvent | Time of the latest granted event, past or future; used by Cancel |
limit, burst | Rate and capacity, changed by SetLimit, SetBurst |
Benchmarks of contention Good to know
One run on an Apple M4 Pro (12 logical CPUs), Go 1.27.4, go test -bench . -cpu 1,4,12. Numbers show a shape, not a promise; run them on your hardware.
| Benchmark | 1 CPU (ns/op) | 4 CPUs | 12 CPUs |
|---|---|---|---|
keyed.Map, one mutex, 1024 keys | 83 | 86 | 184 |
keyed.Sharded, 64 shards | 91 | 42 | 34 |
| Fixed window, mutex, one counter | 33 | 84 | 150 |
| Fixed window, atomic CAS, one counter | 32 | 94 | 499 |
Reading: sharding helps when keys are many; a single hot counter does not get faster by adding goroutines, and CAS retries can lose to a mutex.
Version notes Good to know
| Version | Change | Source |
|---|---|---|
| Go 1.23 | Timer and ticker channels are unbuffered (capacity 0); unreferenced tickers are collected | go.dev/doc/go1.23 |
| Go 1.24 | testing/synctest as GOEXPERIMENT=synctest | go.dev/doc/go1.24 |
| Go 1.25 | testing/synctest stable with synctest.Test | go.dev/doc/go1.25 |
x/time v0.12.0 | Has Tokens, TokensAt, SetLimitAt, SetBurstAt, Sometimes | go doc golang.org/x/time/rate |
go.uber.org/ratelimit v0.3.1 | New uses the int64 atomic limiter | limiter_atomic_int64.go |
rate.Sometimes is a related tool: it runs an action on the first N calls, every Nth call or at most once per interval, which is the right fit for rate limited logging.
Solving the classic problems
| Problem | Solution | How | Cost or limit |
|---|---|---|---|
| Public API abuse | Per-IP token bucket, 429 | httpmw.Limit with keyed.Sharded | NAT shares an IP |
| Paid plans | Per-API-key bucket, plan table | Load limits from the database (SQL) | Plan change needs SetLimit |
| Credential stuffing | Strict per-account and per-IP limits plus lockout | Two limiters, fixed window per account | UX friction |
| Slow downstream | Concurrency limit | semaphore.Weighted | Needs a timeout too |
| Calling a partner | Outbound Wait(ctx) plus Retry-After | client.Transport | Local limit is per process |
| Many replicas | Shared GCRA in Redis | redislimiter | Redis latency and failure mode |
| Memory growth | Sweep(ttl) or LRU | per-key | Eviction resets buckets if ttl is short |
| Flaky tests | Fake clock or synctest | testing | Wait needs the sleeper wrapper |
Wiring middleware, sweeper and graceful stop
trusted := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}
lim := keyed.NewSharded(64, rate.Limit(10), 20, fakeclock.System{})
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/orders", listOrders)
handler := httpmw.Limit(lim, httpmw.ByAPIKey("X-API-Key", httpmw.ByIP(trusted)))(mux)
// Evict only keys idle for at least burst/rate (2s) plus a margin.
go func() {
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-t.C:
lim.Sweep(10 * time.Minute)
case <-ctx.Done():
return
}
}
}()Plans in the database
-- One row per plan; the Go service loads it at start and on change,
-- then calls SetLimit/SetBurst (or builds limiters with these numbers).
CREATE TABLE rate_plans (
plan text PRIMARY KEY,
per_second numeric(10,3) NOT NULL CHECK (per_second > 0),
burst integer NOT NULL CHECK (burst >= 1)
);
INSERT INTO rate_plans VALUES ('free', 1, 5), ('pro', 10, 50);
-- API key -> plan
CREATE TABLE api_keys (
key_hash text PRIMARY KEY,
plan text NOT NULL REFERENCES rate_plans(plan)
);A strict login limiter
Use two independent limiters: per IP (loose, to stop a single source) and per account name (strict, to stop distributed guessing), for example rate.NewLimiter(rate.Every(30*time.Second), 5) per account. Always evaluate both before checking the password so response timing does not reveal valid accounts, and return the same message for both refusals. Authentication in Go covers the rest.
Choosing
| Situation | Limiter | Extra | Reason |
|---|---|---|---|
| Public HTTP API, one process | rate.Limiter per key in Sharded | Sweep, 429 + Retry-After | Built in, exact, cheap |
| Many replicas, one shared quota | GCRA in Redis (Lua) | Local pre-filter, fail-open policy | One clock, atomic |
| Calling a partner API | rate.Limiter.Wait(ctx) or uber Take | Honour Retry-After | Smooth, polite |
| Even pacing of a batch job | uber-go/ratelimit | WithoutSlack | One line |
| Daily or monthly quota | Fixed window counter in DB/Redis | Reset time in headers | Boundary burst is acceptable |
| Exact "N per rolling minute" | Sliding log (small N) or sliding counter | Cap N | Memory vs accuracy |
| Protect a slow dependency | semaphore.Weighted | Timeout, TryAcquire for shedding | Rate does not bound in-flight work |
| Hostile traffic with many keys | LRU plus a global limit | Alerts on eviction rate | Bounded memory |
| gRPC service | Interceptor with ResourceExhausted | mTLS identity as key | Idiomatic status |
| Tests | Fake clock, synctest | No time.Sleep | Deterministic |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One keyed.Sharded in memory is exactly right. Put the limiter in the middleware chain after panic recovery and request logging and before authentication for a coarse per-IP limit, then a second per-user limit after authentication. Example: a small invoicing app allows 20 requests per second per API key with a burst of 40, plus 5 login attempts per 30 seconds per IP. Nothing is shared, nothing can fail.
Modular monolith and multiple databases
Give each module its own limiter configuration (an exports module at 1 request per second per tenant, a search module at 20), built from the same keyed package, so one module's noisy tenant cannot consume another's budget. Plans live in one table owned by the billing module; other modules read limits through an interface. Concurrency limits belong next to the resource: the module that talks to the legacy database owns the semaphore.
Microservices
Each service enforces its own limits on what it can afford, and the edge (API gateway, see API Gateway, BFF & Service Mesh) enforces per-customer limits. Service-to-service calls use client-side limiting (client.Transport) and propagate deadlines (Context). Sequence: gateway admits 100/s per customer -> orders service accepts 500/s total with a concurrency limit of 50 -> payments client limits itself to 20/s toward the bank and sleeps for Retry-After. Failures cross the boundary as 429, 503 or gRPC ResourceExhausted, never as silent drops. Sagas and retries must be idempotent (API Idempotency) because a refused request is retried.
Distributed data: replicas, caches, Redis and multi-region
N replicas with local limiters admit N times the limit, so either accept that (limit the cluster by capacity, not by fairness), divide the quota (limit/N, which breaks when replicas scale), or share state. Shared state in Redis gives one clock and atomic decisions at the price of a round trip and a failure mode. Multi-region: a global limit needs cross-region coordination and is usually replaced by per-region limits plus asynchronous reconciliation. Caches in front (CDN) can serve 429 responses and cache them for the Retry-After period; make sure the cache key includes the identity, or one client's refusal is served to everyone (Caching).
Scaling path: 1x, 10x, 100x
| Load | Design | What breaks first |
|---|---|---|
| 1x (hundreds of req/s) | One Map, mutex | Nothing |
| 10x (thousands) | Sharded, Sweep goroutine, metrics on 429s | Map memory if keys are unbounded |
| 100x (tens of thousands per process, many pods) | Local pre-filter plus shared Redis limiter, gateway limits, concurrency limits | Redis hot keys, fail-open policy under outage |
See also Scaling Strategies and Cascading Failures.
Lab
Expected output is labelled "expected, not run" where it needs a running server; the first command is real and was run on the host (Go 1.27.4).
cd docs/snippets/go/rate-limiting-in-go/go
gofmt -l . && go vet ./... && go test -race ./...
go run ./cmd/demoReal output of go run ./cmd/demo:
t(ms) allow tokens
0 true 2.00
0 true 1.00
0 true 0.00
0 false 0.00
200 false 0.40
500 true 0.00
500 false 0.00
1000 true 0.00
1000 false 0.00
4000 true 2.00
reserve 3: true 0s
reserve 2: true 1s
after Cancel, reserve 1 delay: 500ms
reserve 4: false true
rate: Wait(n=4) exceeds limiter's burst 3
rate: Wait(n=1) would exceed context deadline- Read the table: the first four rows show the burst of three; the 200 ms row shows 0.40 tokens, not enough; the 4000 ms row shows the refill capped at the burst (3, minus the one taken, equals 2).
- Reserve 3 at once costs nothing; reserve 2 more waits 1 s (two tokens at 2 per second); cancelling it gives the slot back (500 ms for the next one).
- Run the contention benchmark:
go test -bench . -run xxx -cpu 1,4,12 ./keyed ./windows- Wire the middleware in your own
mainand hit it (expected, not run):
for i in $(seq 1 25); do curl -s -o /dev/null -w '%{http_code} ' -H 'X-API-Key: demo' http://localhost:8080/v1/orders; done; echo
# expected, not run: 200 repeated 20 times (burst), then 429 429 ... interleaved with an occasional 200
curl -si -H 'X-API-Key: demo' http://localhost:8080/v1/orders | head -8
# expected, not run:
# HTTP/1.1 429 Too Many Requests
# Retry-After: 1
# RateLimit-Limit: 20
# RateLimit-Remaining: 0
# RateLimit-Reset: 1- Spoof test (expected, not run): with the proxy list set to your own network,
curl -H 'X-Forwarded-For: 1.2.3.4' http://localhost:8080/from a laptop must be counted as the laptop's address, not1.2.3.4. - Redis variant (expected, not run): start any Redis you own, point
redis.NewClientat it, callAllow6 times withinterval=100ms, burst=5; the sixth returnsAllowed=falsewith aRetryAfternear 100 ms.
For PHP/Laravel developers
The RateLimiter facade (Illuminate\Support\Facades\RateLimiter, Laravel 13 docs, "Rate Limiting") is a cache-backed counter: RateLimiter::attempt($key, $perMinute, $callback, $decaySeconds), tooManyAttempts, increment, remaining, availableIn, clear. HTTP limits use named limiters and the throttle middleware.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
// Route::middleware(['throttle:api'])->group(...)| Question | Laravel | Go in this chapter |
|---|---|---|
| State lives | In the cache (database, Redis, ...), shared across PHP-FPM workers | In process memory; share via Redis yourself |
| Algorithm | Counter with a decay window (the docs call it the "decay rate"; reading it as fixed-window is our inference) | Token bucket, GCRA, windows: your choice |
| Key | ->by($id) | ByAPIKey, ByIP, any KeyFunc |
| Refusal | Automatic 429; custom via ->response() | http.StatusTooManyRequests in httpmw |
| Shared across workers | Yes, by design | Not unless you add Redis |
| Waiting | None | Wait(ctx), Take() |
| Concurrency | Not provided | semaphore.Weighted |
The biggest difference: PHP-FPM workers share nothing, so Laravel must keep counters in a shared store, which makes a Redis limiter the default; a Go server is one long-lived process, so an in-memory token bucket is the default and shared state is an optimisation you add when you scale out.
Common misconceptions
| Belief | Reality |
|---|---|
"rate.NewLimiter(100, 100) allows 100 in any second" | It can admit about 200 in a second: a full bucket plus a second of refill |
| "Burst is the queue length" | Burst is the bucket capacity and the largest n per call; nothing is queued by Allow |
"rate.Limiter cannot be tested without sleeping" | AllowN, ReserveN, TokensAt take the time; wrap them with a fake clock; or use synctest in Go 1.25 |
| "Atomics are faster than a mutex" | Under heavy contention on one word the CAS loop lost to a mutex (499 vs 150 ns/op measured) |
"First X-Forwarded-For entry is the client" | It is whatever the client wrote; trust the header only past your own proxies, read from the right |
| "A rate limit protects a slow database" | Only a concurrency limit bounds in-flight work |
| "Evicting idle limiters is free" | A recreated limiter starts full; evict only after burst/rate of idleness |
| "Return 503 for rate limits" | 429 is the status for too many requests; 503 means overload or outage |
| "Retry immediately after a 429" | Obey Retry-After, add jitter, cap the wait |
| "A time.Ticker is a rate limiter" | It drops ticks and has no burst, no per-key state and no refusal path |
"Reserve without use is harmless" | Unused reservations hold tokens until Cancel |
| "Per-process limits give a cluster limit" | N replicas admit N times the limit |
Cheat sheet
| Topic | What to remember |
|---|---|
| Create | rate.NewLimiter(r, b); rate.Every(d) for "one per d"; rate.Inf switches it off |
| Server | Allow(); refuse with 429 and Retry-After rounded up |
| Client | Wait(ctx); errors if n > burst or the deadline is too near |
| Plan change | SetLimit, SetBurst; existing reservations keep their time |
| Refund | Reservation.Cancel or CancelAt |
| Zero value | rate.Limiter{} rejects everything |
| Tests | AllowN(t, 1) with a fake clock; synctest in Go 1.25 |
| Per key | Map plus Sweep(ttl >= burst/rate), or LRU plus a global limit |
| Contention | Shard by maphash; measure before using atomics |
| Windows | Fixed: 2x boundary burst; sliding counter: approximate; log: exact but O(limit) |
| GCRA | One timestamp; same decisions as token bucket |
| Leaky bucket | ratelimit.Take() smooths and blocks; WithoutSlack for strict pacing |
| In-flight | semaphore.Weighted; Acquire queues, TryAcquire sheds |
| Proxies | Trust X-Forwarded-For only from trusted peers; read from the right |
| Redis | Lua script, redis.call('TIME'), decide fail-open or fail-closed |
| gRPC | codes.ResourceExhausted from a unary interceptor |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the maximum number of events rate.NewLimiter(10, 5) admits in the first second? Must-know
Answer
Answer: The bucket starts full with 5 tokens, and one second adds 10 more but the bucket holds at most 5 at any instant; counting the refill during the second, at most 5 + 10 = 15 events can be admitted (the formula is b + r*T).
2 — Why can Allow returning false be called repeatedly without changing the limiter? Important
Answer
Answer: AllowN calls reserveN with a zero maximum wait; an unsuccessful reservation does not update tokens, last or lastEvent.
3 — What error does WaitN(ctx, 4) return on a limiter with burst 3, and does it consume tokens? Important
Answer
Answer: rate: Wait(n=4) exceeds limiter's burst 3, checked before any reservation, so nothing is consumed (unless the limit is rate.Inf).
4 — How do you test Wait semantics without sleeping? Important
Answer
Answer: Reserve with ReserveN(fakeNow, 1), read DelayFrom(fakeNow), call an injected sleeper that advances the fake clock, and on interruption call CancelAt; or run the real Wait inside synctest.Test on Go 1.25.
5 — A request arrives with X-Forwarded-For: 1.2.3.4, 198.51.100.9 from the proxy 10.0.0.2, and 10.0.0.0/8 is trusted. Which address is the client? Important
Answer
Answer: 198.51.100.9: walking from the right, it is the first address not in the trusted ranges; 1.2.3.4 is a client-supplied prefix.
6 — Why can a fixed window admit twice the limit? Must-know
Answer
Answer: The counter resets at the aligned boundary, so N requests just before it and N just after are all admitted within a very short time.
7 — When is evicting an idle per-key limiter invisible to the client? Good to know
Answer
Answer: When the key has been idle at least burst/rate seconds, because its bucket would be full anyway and the recreated one starts full.
8 — What is the difference between Acquire and TryAcquire for overload? Must-know
Answer
Answer: Acquire(ctx, 1) waits for a slot (backpressure, bounded by the context); TryAcquire(1) returns false at once (load shedding).
9 — Which header wins if a response has both RateLimit and Retry-After? Important
Answer
Answer: Retry-After, according to the IETF draft ("the Retry-After field MUST take precedence").
10 — Why does the Redis limiter read redis.call('TIME') instead of passing the client's time.Now()? Important
Answer
Answer: Replicas have different clocks; reading the time inside the atomic script gives every replica the same clock and avoids skew between decisions.
11 — Which gRPC code signals a rate limit? Must-know
Answer
Answer: codes.ResourceExhausted; the interceptor above returns rpc error: code = ResourceExhausted desc = rate limit exceeded.
Glossary
| Term | Meaning |
|---|---|
| Rate limiting | Bounding how many events a caller may cause per unit of time |
| Token bucket | A bucket refilled at rate r holding at most b tokens; each event takes one |
rate.Limiter | The token bucket in golang.org/x/time/rate, safe for concurrent use |
x/time/rate | The Go team's module golang.org/x/time, package rate |
Allow, AllowN | Take tokens now or return false |
Reserve, ReserveN | Book tokens for a future time; returns a Reservation |
Reservation | A receipt with OK, Delay, Cancel |
Delay | How long a reservation holder must wait; InfDuration if not OK |
Cancel | Gives back a reservation's tokens as far as possible |
Wait, WaitN | Block until tokens are available or the context ends |
| Burst | Bucket capacity and the largest single request size |
rate.Every | Converts an interval to a Limit |
rate.Inf | The infinite limit; burst ignored |
SetLimit, SetBurst | Change rate or capacity of a live limiter |
| Leaky bucket | Events leave at a constant rate; as a smoother it delays callers |
uber-go/ratelimit | Library whose Take blocks to space calls evenly |
| Slack | Idle credit in uber's limiter; default 10 |
| Fixed window | Counter reset at aligned interval boundaries |
| Sliding window | Counting over the last interval, as a log or a weighted counter |
| GCRA | Generic Cell Rate Algorithm: a token bucket stored as a theoretical arrival time |
| Concurrency limit | Cap on calls in flight, e.g. semaphore.Weighted |
semaphore.Weighted | Counting semaphore from golang.org/x/sync/semaphore |
| Middleware | func(http.Handler) http.Handler wrapper |
| Per-IP limiting | One bucket per client address |
| Trusted proxy | A proxy whose X-Forwarded-For entries you believe |
| API key | A client credential used as a limiting identity |
429 Too Many Requests | HTTP status for rate-limited requests (RFC 6585) |
Retry-After | Header: seconds or date to wait before retrying (RFC 9110) |
RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset | Quota headers from earlier drafts, still widely sent |
RateLimit-Policy | Structured quota policy field in IETF draft version 12 |
| Client-side limiting | Limiting your own outbound calls |
| Redis Lua | A script run atomically inside Redis |
| Distributed limiter | A limiter whose state is shared by many replicas |
| Fake clock | A clock a test advances by hand |
| Clock injection | Passing the clock as a dependency |
testing/synctest | Go 1.25 package giving goroutines a fake clock |
| Sharded limiter | Many independent maps to reduce lock contention |
| LRU | Least-recently-used eviction |
| Tenant | A customer account in a multi-tenant system |
| Backpressure | Slowing the producer instead of dropping work |
| Load shedding | Refusing work to stay alive |
| gRPC interceptor | Middleware for gRPC calls |
ResourceExhausted | gRPC status code for quotas and limits |
time.Ticker | Periodic channel; drops ticks for slow receivers |
References
Versions read: golang.org/x/time v0.12.0 and master rate.go, go.uber.org/ratelimit v0.3.1 and main, Go 1.25 release notes, Laravel 13.x docs, IETF draft 12.
- golang.org/x/time/rate source (
rate.go):Limiter,Reservation,WaitN,reserveN. - go.uber.org/ratelimit README and
limiter_atomic_int64.go. - golang.org/x/sync semaphore source.
- Go 1.23 release notes, Go 1.24, Go 1.25 (timers,
synctest). - Testing time (and other asynchronicity) with synctest.
- Effective Go: channels as semaphores.
- RFC 6585, section 4: 429 Too Many Requests.
- RFC 9110, section 10.2.3: Retry-After.
- IETF draft: RateLimit header fields for HTTP.
- Generic cell rate algorithm (Wikipedia, secondary source).
- Brandur Leach: Rate Limiting, Cells, and GCRA.
- Redis EVAL and Scripting with Lua (atomic execution, effects replication).
- Laravel 13.x: Rate Limiting and Routing: rate limiting.
- Related pages: Rate Limiting: Token Bucket, Leaky Bucket, Windows, Distributed Limits, Load Shedding, Middlewares, Context.