Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

rate-limiter

Fixed-window rate limiting for Go HTTP services, with counters kept in a shared store so every instance of a service enforces the same limit.

github.com/philippe-berto/rate-limiter             Policy, Limiter, Middleware, ClientIP
github.com/philippe-berto/rate-limiter/redisstore  Store backed by Redis

Concepts

Type What it is
Policy A named limit: at most Limit requests per Window for one key. The name separates counters, so two policies never share a count even for the same key.
Limiter Checks a key against a policy using a Store. Built with ratelimiter.New(store).
Store Anything that can atomically increment a counter and give it an expiry. redisstore.Store is the implementation shipped here.
Decision The result of one check: Allowed, Limit, Remaining, and RetryAfter when rejected.
KeyFunc func(*http.Request) (string, bool) — what a request is counted against. Returning false means the request has no key.
ClientIP A KeyFunc source that derives the client address safely.

Algorithm

Each (policy, key) pair is one counter that starts on its first request and expires Window later. A request is allowed while the counter is at or below Limit. Because the window is fixed, a client can send up to 2 × Limit requests around a window boundary; size limits with that in mind.

Keys are hashed

The limiter never hands the store the raw key. StoreKey(policy, key) is policy + ":" + hex(SHA-256(key)), so IP addresses and account identifiers do not appear in Redis, and a client cannot make a key arbitrarily long. StoreKey is exported for tooling that needs to inspect or clear one counter.

Using the limiter directly

For limits that are not a whole route — attempts against one account inside a service method, for example — call Allow:

limiter := ratelimiter.New(redisstore.New(redisClient, redisstore.DefaultPrefix))

decision, err := limiter.Allow(ctx, ratelimiter.Policy{Name: "pairing", Limit: 5, Window: 2 * time.Minute}, pairingID)
if err != nil {
	return err
}
if !decision.Allowed {
	return ErrTooManyAttempts
}

Allow returns ErrInvalidPolicy for an empty name, a limit below 1 or a window below 1ms; ErrNoKey for an empty key; and the store's error, wrapped, when the store fails.

Middleware

signInLimit, err := limiter.Middleware(ratelimiter.MiddlewareConfig{
	Policy: ratelimiter.Policy{Name: "sign-in", Limit: 10, Window: time.Minute},
	Key:    ratelimiter.ClientIP{TrustedProxies: 1}.Key,
})
if err != nil {
	return err
}

router.With(signInLimit).Post("/sign-in", handler.SignIn)

Middleware validates the configuration once and returns an error rather than a handler that fails on every request.

Field Meaning
Policy Required.
Key Required. ErrNoKeyFunc when missing.
FailOpen What to do when the store fails or Key returns false. false (default) rejects the request; true lets it through.
Rejected Writes the response when the limit is exceeded. Default: 429 Too Many Requests, plain text.
Unavailable Writes the response when failing closed. Default: 503 Service Unavailable, plain text.
OnError Called with every failure, in both modes, before the response is decided. The package does not log; this is where logging and metrics go.

The middleware sets Retry-After (whole seconds, rounded up, never below 1) before calling Rejected, so a custom Rejected only has to write the status and body. It checks the limit with r.Context(), so cancellation, deadlines and tracing follow the request.

Choosing a failure mode

Fail closed where letting traffic through unmetered is the bigger risk — authentication, anything that guards a guessable secret. Fail open where a limiter outage should not become an outage of the routes behind it. A Key that returns false is treated as a failure, so a middleware mounted in the wrong place (an account key before authentication) is reported through OnError rather than silently counting nothing; with FailOpen it will still let those requests through.

Keying by account

Mount the middleware after authentication and key on the identity authentication established — never on a header the client sends:

uploadLimit, err := limiter.Middleware(ratelimiter.MiddlewareConfig{
	Policy:   ratelimiter.Policy{Name: "file-create", Limit: 60, Window: time.Hour},
	Key:      func(r *http.Request) (string, bool) { return accountFromContext(r.Context()) },
	FailOpen: true,
})

Client IP

ClientIP.Key returns the client address as the key: IPv4 as the address, IPv6 as its prefix (/64 by default, IPv6PrefixBits to change it; values outside 1–128 fall back to 64), because one IPv6 client normally controls a whole /64 and could otherwise rotate addresses freely. IPv4-mapped IPv6 addresses count as IPv4, and zones are dropped.

TrustedProxies Address used
0 (default) r.RemoteAddr. X-Forwarded-For is ignored entirely.
n ≥ 1 The n-th X-Forwarded-For entry counting from the right, across all header lines. If there are fewer than n entries, r.RemoteAddr.

Only set TrustedProxies when the service cannot be reached except through those proxies. Each proxy appends the address it received the connection from, so the rightmost entries are written by infrastructure and everything to their left is whatever the client sent. Behind one load balancer (an AWS ALB, for instance) use 1; behind a CDN in front of a load balancer, 2. If the service is also reachable directly, a client can send its own X-Forwarded-For and choose its key.

On platforms without a TCP peer (serverless adapters), the adapter must put the platform's source IP in r.RemoteAddr; otherwise write a KeyFunc that reads it from wherever the platform provides it.

An entry that the trusted position points at but cannot be parsed makes Key return false rather than falling back, because falling back would put every client behind that proxy into one counter.

Redis store

store := redisstore.New(redisClient, redisstore.DefaultPrefix)
  • Takes an existing client. Any redis.Scripter from github.com/redis/go-redis/v9 works — *redis.Client, *redis.ClusterClient, redis.UniversalClient — so the store shares the application's pool and configuration.
  • One atomic script. INCR, then PTTL; if the key has no expiry, PEXPIRE it to the window. The script is defined once and run with EVALSHA. Every counter has exactly one key, so it is safe on Redis Cluster.
  • Repairs keys without an expiry. A counter that somehow lost its TTL gets one on its next increment instead of blocking its key forever.
  • Millisecond windows. Windows are passed as milliseconds; anything finer is truncated.
  • Prefix. Prepended verbatim to every key. DefaultPrefix is ratelimit:.
  • Eviction. Under an allkeys-* memory policy Redis may evict counters, which resets those limits early. Counters are small and always expire, but if the same Redis holds data that must never be evicted, run it with noeviction.

A different backend only has to implement Store.Increment(ctx, key, window) (count, expiresIn, err) atomically, returning the counter after incrementing and the time left in its window.

Tests

go test ./...
go test -tags=integration ./...

Integration tests talk to Redis at REDIS_ADDR (default localhost:6379), write only under a unique ratelimiter-test:<nanos>: prefix and delete those keys when they finish.

Changes from v0.1

This version is not source-compatible with v0.1.

  • The API_KEY header path is gone. It accepted any value without verifying it, so sending a new value per request bypassed the limit. Key on an authenticated identity instead.
  • The client address no longer comes from the first X-Forwarded-For entry, which the client controls, and IPv6 remote addresses are parsed correctly instead of being cut at the first :.
  • Nothing is printed to stdout; use OnError.
  • Configuration is per middleware (MiddlewareConfig) instead of process-wide environment variables, so several policies can coexist without sharing counters.
  • database/redis is replaced by redisstore, which takes the application's Redis client instead of building its own.
  • Store failures default to 503 instead of 500, and can be configured to fail open.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages