Rate limiting
Rate limiting is a middleware that answers 429 Too Many Requests with Retry-After when a caller goes over its
budget. Limiters are built in code and passed to the middleware: there is no configuration section, no registry
and no module for rate limits. There are two limiters, one per process (memory) and one shared by every replica
(Redis). A limiter has a default policy, and the middleware can decide each request with a policy of its own, for
limits that differ per caller and change while the application runs. The normative text, with its abuse cases, is
the rate-limiting specification.
The algorithm is GCRA: a token bucket of size burst, refilled at limit / period, stored as one number per
caller. The algorithm, numbers, headers and Redis keys and script are identical in Java and Go, so a Java replica
and a Go replica sharing one Redis server share one budget. (The Go script is a byte-for-byte copy of the Java one,
and a test compares them.)
Building limiters
Section titled “Building limiters”RateLimiter api = MemoryRateLimiter.create("api", new RateLimitPolicy(100, Duration.ofMinutes(1), 20));RateLimiter login = RedisRateLimiter.create("login", app.get(RedisConnections.class).defaultInstance(), RateLimitPolicy.of(5, Duration.ofMinutes(1)));MemoryRateLimiter.create(name, policy), orcreate(name, policy, maxKeys)(default 100 000), or with a clock for tests.RedisRateLimiter.create(name, connection, policy), or with a key prefix as a fourth argument (defaultfw:rl:), in artifactframework-ratelimit-redis. The connection comes from the Redis module. Building it loads the script, so build it inbootor a provider, when Redis is connected.
api, err := ratelimit.NewMemory("api", ratelimit.MustPolicy(100, time.Minute, 20))login, err := redisrl.FromClient(ctx, "login", redis, ratelimit.MustPolicy(5, time.Minute, 5))NewMemorytakes optionsMaxKeys(default 100 000, 1 to 10 000 000),MemoryClockandMemoryLogger.redisrl.Newandredisrl.FromClientload the Lua script, so the server must be reachable (otherwise an error wrappingratelimit.ErrStore). Build the limiter in the build function after the Redis connections.redisrl.Prefixchanges the key prefix (defaultfw:rl:).Limiter.Acquire(ctx, key, cost)returns anAllowed(remaining, time to full) orLimited(retry after, time to full). A store that cannot answer is an error wrappingErrStore.PolicyLimiter.AcquireWith(ctx, key, cost, policy)decides under another policy against the same stored state; both limiters implement it.
- The policy:
limitrequests perperiod, with up toburstat once. The shorthandof(limit, period)sets the burst to the limit. Ranges:limitandburst1 to 1 000 000;period1 ms to 1 day;period / limitat least 1 µs;burst * period / limitat most about 73 years. Out of range isIllegalArgumentExceptionin Java and an error wrappingratelimit.ErrInvalidPolicyin Go (MustPolicyis for literals). The zero policy is invalid and refused everywhere. - The name (
[a-z][a-z0-9_-]*, at most 63 characters) labels the metrics and, for Redis, namespaces the keys. Give each limiter its own, and use the same name and prefix in every replica. - The memory limiter counts per process: with three replicas a caller gets three budgets. It is bounded. When
maxKeyscallers are tracked, those whose bucket is full again are dropped, and if it is still full, new callers share one overflow bucket (a warning says so). A flood of distinct keys can neither use up memory nor reset other callers’ limits. - The Redis limiter keeps one budget for all replicas, decides atomically in a Lua script on the Redis server’s clock, and lets idle keys expire by themselves.
Numbers from your own settings
Section titled “Numbers from your own settings”To tune numbers per environment, declare your own settings and pass the values in.
static final Setting<Integer> LIMIT = Setting.integer("ingest.rate-limit").withDefault(100);static final Setting<Duration> PERIOD = Setting.duration("ingest.rate-period").withDefault(Duration.ofMinutes(1));
record Limiters(RateLimiter api) {}
@Overridepublic void register(AppBuilder app) { app.declare(LIMIT); app.declare(PERIOD); app.provide( Limiters.class, lookup -> { Config config = lookup.get(Config.class); return new Limiters( MemoryRateLimiter.create("api", RateLimitPolicy.of(config.get(LIMIT), config.get(PERIOD)))); });}ingest.rate-limit: 20 in application.yaml (or INGEST_RATE_LIMIT=20) then gives 20 per minute.
Read your own settings in the build function (see config) and pass the values to
ratelimit.PolicyOf or ratelimit.NewPolicy.
Using the middleware
Section titled “Using the middleware”MemoryRateLimiter l = limiter(10, Duration.ofSeconds(10), 2);Routes routes = new Routes();routes.get("/x", handler, RouteOptions.none().with(RateLimit.by(l, KeyResolvers.clientAddress()).metrics(metrics).build()));In an application the limiter is the one you built and the metrics come from app.get(Metrics.class). Options:
.headers(false), .cost(n), .onStoreFailure(OnStoreFailure.DENY), .metrics(...), .policy(...).
limit, err := ratelimit.Middleware(api, ratelimit.ClientAddress(), ratelimit.WithMetrics(b.Metrics()), ratelimit.WithLogger(b.Logger("api")))routes.Handle("POST /login", handler, httpfw.With(limit))Middleware returns an httpfw.Middleware. Options: WithHeaders(false), WithCost(n) (1 to the burst),
WithOnStoreFailure(ratelimit.Deny), WithMetrics, WithLogger, WithPolicy.
- Over the limit:
429with{"error":"RATE_LIMITED","message":"too many requests"}andRetry-Afterin whole seconds, rounded up (at least 1). The handler is not called. - Headers on every answer, allowed or limited (turn off with the headers option):
RateLimit-Limit(the burst of the policy the request was decided with),RateLimit-Remaining, andRateLimit-Reset(seconds until the bucket is full). - Cost. One request can count as
n, at most the default policy’s burst. - When the store fails (Redis down): by default the request goes through (
ALLOW), logged and counted infw_http_rate_limit_store_failures_total.DENYanswers503instead; use it for login and password reset. Logging happens at most once a minute. - Metrics:
fw_http_rate_limited_total{limiter},fw_http_rate_limit_store_failures_total{limiter}and, with a policy function,fw_http_rate_limit_policy_failures_total{limiter}.
Where to put it. As route middleware it runs after the context is resolved, so the client and principal keys work. As global middleware it runs before routing and context resolution, so only address and header keys make sense there. See HTTP. For a typed operation, add it with the operation’s route options; see typed operations.
A policy per request
Section titled “A policy per request”When the limit depends on the caller and changes at run time (each ingestion has its own limit, set in a control plane), give the middleware a policy resolver.
PolicyResolver fromPlane() { return r -> { String ingestion = r.header("X-Ingestion"); return ingestion == null ? null : plane.get(ingestion); };}
RateLimit.by(limiter(1, Duration.ofMinutes(1), 1), KeyResolvers.header("X-Ingestion")) .policy(fromPlane()) .metrics(metrics) .build();.policy(...) needs a limiter whose supportsPerRequestPolicy() is true (both shipped ones are). A hand-written
limiter that does not override it is refused when the middleware is built.
WithPolicy(func(r) (Policy, ok, error)) decides each request with a policy of its own. ok=false means the
limiter’s default policy. Returning ratelimit.Unlimited means no limit (below).
- A change applies from the key’s next request. The limiter stores one time per key, not the policy, so there is nothing to migrate or reset on either driver. Usage carries over in proportion to time.
- A lowered policy never makes a caller wait out the old one. If the caller’s usage is beyond what the new
policy’s bucket can hold, it counts as an empty bucket, and the next request is allowed after one interval
(
period / limit) of the new policy. - Null means the default policy. It is never “no limit”.
- No limit is said out loud. Return
RateLimitPolicy.UNLIMITED(Java) orratelimit.Unlimited(Go) for a caller that has none. The request goes straight to the handler. The bucket is not read or written (so a later real policy for that key starts full) and the answer carries noRateLimit-*headers. Only that constant counts: a policy with the same numbers is an ordinary policy, and a resolver that throws is still a policy failure. - A resolver that fails (throws, returns the zero policy, or returns a burst below the cost) is a policy
failure. It is counted in
fw_http_rate_limit_policy_failures_total{limiter}, logged at most once a minute, then handled like a store failure: withALLOWthe request is decided with the limiter’s default policy, so it is still limited; withDENYit gets503. Choose the default policy with that in mind: it is the limit while your lookup fails. - Keep it cheap. The resolver runs on every request. Read from memory (a map a background loop refreshes, or a cache), and never call the control plane per request. The middleware does not cache what it returns.
- Never take the limit from the caller. A policy read from a header or the body lets the caller choose its own limit. Look it up by something the caller cannot forge, or by the key.
- One key, one policy. Requests with the same key share one bucket whatever policy each brings, and a request with a smaller policy shrinks the shared usage to fit it. If two routes need different limits for the same caller, give them separate limiters.
Choosing the key
Section titled “Choosing the key”| Resolver (Java / Go) | Key |
|---|---|
KeyResolvers.clientAddress() / ClientAddress() |
The connection’s peer address, never a header. IPv6 addresses are grouped by /64 |
KeyResolvers.forwardedFor(n) / ForwardedFor(n) |
Behind n proxies that each append to X-Forwarded-For: the entry n from the right, the address your outermost proxy saw. Entries further left are written by the caller and ignored. With fewer entries, or an entry that is not an IP literal, the peer address |
KeyResolvers.header(name) / Header(name) |
The header’s value, hashed (SHA-256), so an API key is never stored, logged or used as a label |
KeyResolvers.client(), principal() / Client(), Principal() |
From the route’s context |
A request for which the resolver has no key (a missing header, no context) uses one shared bucket, never no limit, so a caller cannot escape the limit by leaving the key out. Keys longer than 200 characters are hashed.
Use forwardedFor(n) only when you know n: trusting one proxy too many lets a caller choose its own key. Behind no
proxy, use the client address.
Differences between Java and Go
Section titled “Differences between Java and Go”- Go returns errors where Java throws (
Middlewarereturns an error for a cost above the burst or a policy function on a limiter that cannot take one). - Go parses the peer address from
RemoteAddr(which carries a port) withnet/netip. It refuses leading zeros (010.001.001.001), short forms (1.2.3) and a bare integer, and answers the shared bucket for them: the stricter result. Any IPv6 zone is dropped.
Testing
Section titled “Testing”In Java, TestClient calls come from 127.0.0.1 (.remoteAddress("10.0.0.2") sets another).
MemoryRateLimiter.create(name, policy, maxKeys, clock) takes a monotonic clock, so a test can move time instead of
sleeping, including across a policy change. The Redis limiter is tested against a real Redis.