"Add rate limiting" sounds like one task. In practice it is a choice between several algorithms, and they do not behave the same way. One lets a client send twice the limit around a window edge. One is exact but keeps a timestamp for every request. One is cheap and slightly approximate. And once your service runs on more than one instance, the counter has to live somewhere shared, and two instances must never both believe there is "one request left".
ratelimit is my learning project on this topic. It implements five rate-limiting algorithms behind one Go interface, each available in memory and on Redis, plus net/http middleware. Writing all five side by side, with the same tests, is the clearest way I found to see what each one trades away.
What it does
Everything goes through one interface:
type Limiter interface {
AllowN(ctx context.Context, key string, n int) (Result, error)
}
type Result struct {
Allowed bool
Limit int
Remaining int
RetryAfter time.Duration
}
All five algorithms answer the same question, "may this key do n more things now?", with different trade-offs:
| algorithm | state per key | allows bursts? | exact? | notes |
|---|---|---|---|---|
TokenBucket(rate, burst) |
2 numbers | yes, up to burst
|
yes | the usual choice for APIs |
LeakyBucket(rate, capacity) |
2 numbers | up to capacity
|
yes | the token bucket upside down; a small capacity smooths traffic |
FixedWindow(limit, window) |
1 counter | 2x limit at window edges | no | cheapest; the test shows its edge burst |
SlidingLog(limit, window) |
limit timestamps |
no | yes | exact, but memory grows with the limit |
SlidingCounter(limit, window) |
2 counters | slightly | approx. | weights the previous window by how much of it is still in range |
Every limiter returns a RetryAfter, and the tests check that waiting exactly that long always lets the request through.
On top of the limiters there is HTTP middleware. A rejected request gets a 429 with Retry-After, and responses carry RateLimit-Limit and RateLimit-Remaining headers.
What I built from scratch, and what it teaches
The algorithms themselves. The token bucket refills at a steady rate and allows a burst up to its size, which is why it is the usual choice for APIs. The leaky bucket is the same idea upside down. The fixed window is one counter per window, which is cheap, but a client can use the full limit at the end of one window and again at the start of the next: twice the limit in a short moment. The sliding log fixes that exactly by remembering a timestamp per request, at the cost of memory. The sliding counter is the compromise: two counters, with the previous window weighted by how much of it is still in range.
In-memory state. The per-key state lives in a map guarded by one mutex. A limiter that never forgets keys leaks memory, so every 1024 operations, keys that have been idle long enough to reset are removed. Time comes from a Clock interface, and ratelimit.FakeClock makes every test deterministic.
Atomicity on Redis. Each AllowN on Redis is one EVALSHA. The Lua script reads the state, decides, and writes back with a TTL, all atomically. That is what stops two concurrent instances from both seeing "one left". Keys look like prefix:kind:{key}. Every key a script touches is passed in KEYS, and the hash tag keeps the sliding counter's two keys in one Cluster slot. The token and leaky buckets store floats as strings in a hash, and the sliding log uses a sorted set scored by timestamp.
Time in a distributed limiter. The caller's clock is passed to the script instead of calling Redis TIME. This keeps the scripts deterministic and testable. The price is that app servers need synced clocks (NTP).
How to use it
Add the library to your module. The Redis backends are in the redislimit package:
go get github.com/AbdeldjalilChougui/ratelimit@latest
Then pick a limiter and, if you serve HTTP, wrap your handler:
import (
"github.com/AbdeldjalilChougui/ratelimit"
"github.com/AbdeldjalilChougui/ratelimit/redislimit"
)
// In memory, one process:
l := ratelimit.NewTokenBucket(10, 20, nil) // 10 req/s, bursts of 20
// Shared across instances through Redis:
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
l = redislimit.NewSlidingCounter(rdb, "myapp", 100, time.Minute, nil)
// HTTP: 429 + Retry-After + RateLimit-Limit/RateLimit-Remaining headers.
mux := http.NewServeMux()
handler := ratelimit.Middleware(l, ratelimit.KeyByIP, ratelimit.MiddlewareOptions{})(mux)
Two options matter in production-like setups. MiddlewareOptions{FailClosed: true} returns 503 when the limiter itself errors, for example when Redis is down; the default fails open and lets the request through. And KeyByHeader("X-API-Key") keys by a header instead of the IP. Only use KeyByHeader("X-Forwarded-For") behind a proxy you trust, because any client can send that header.
The tests run without any service:
go test -race ./... # in-memory + miniredis, no services needed
docker compose up -d # optional: real Redis on :6399
REDIS_ADDR=localhost:6399 go test -tags integration ./redislimit/
docker compose down
They cover each algorithm's arithmetic on a fake clock, the fixed-window edge burst, idle-key sweeping, exact counts under concurrency (in memory and through Redis), and decision-by-decision agreement between the Redis and in-memory versions, on miniredis and, with the tag, on real Redis 7. They also cover the middleware headers and the fail-open and fail-closed behaviour.
Things to know
The README lists these limits:
- The in-memory limiters use one mutex per limiter. That is fine for thousands of requests per second. Shard it if you need more.
- The Redis limiters rely on client clocks. Large skew between instances makes limits looser or tighter by about the skew.
- The Redis sliding log stores one sorted-set member per accepted request, so memory grows with
limittimes the number of active keys. - There is no
Waitor reservation API likeReserveingolang.org/x/time/rate. It only answers allow or deny. -
Remainingis best-effort for the approximate algorithms.
What I learned
The table at the top of this article is the real result of the project. Before writing the five algorithms, "token bucket versus sliding window" was a list of names to me. After writing a test that shows the fixed window letting through twice its limit at an edge, the difference became concrete.
The second lesson is that the hard part of a distributed limiter is not the arithmetic. It is making "read, decide, write" a single step. Doing it in the application with two Redis calls is a race. A Lua script moves the whole decision into Redis, where it runs atomically. Checking that the Redis version and the in-memory version agree decision by decision is a test I would reuse elsewhere: write the simple version first, then use it as the reference for the distributed one.
The third is about time. Passing the clock in from the caller made the scripts testable, and it also made the dependency on synced clocks explicit instead of hidden. It is a trade-off, and the README says so.
Get the code
The source, the Lua scripts and the tests are on GitHub: https://github.com/AbdeldjalilChougui/ratelimit. It is MIT licensed. If you are choosing an algorithm for an API, reading the five implementations in algorithms.go takes less time than most articles comparing them.
Originally published at abdeldjalilchougui.biz.
Top comments (0)