Skip to content

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.)

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), or create(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 (default fw:rl:), in artifact framework-ratelimit-redis. The connection comes from the Redis module. Building it loads the script, so build it in boot or a provider, when Redis is connected.
  • The policy: limit requests per period, with up to burst at once. The shorthand of(limit, period) sets the burst to the limit. Ranges: limit and burst 1 to 1 000 000; period 1 ms to 1 day; period / limit at least 1 µs; burst * period / limit at most about 73 years. Out of range is IllegalArgumentException in Java and an error wrapping ratelimit.ErrInvalidPolicy in Go (MustPolicy is 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 maxKeys callers 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.

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) {}
@Override
public 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.

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(...).

  • Over the limit: 429 with {"error":"RATE_LIMITED","message":"too many requests"} and Retry-After in 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, and RateLimit-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 in fw_http_rate_limit_store_failures_total. DENY answers 503 instead; 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.

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.

  • 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) or ratelimit.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 no RateLimit-* 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: with ALLOW the request is decided with the limiter’s default policy, so it is still limited; with DENY it gets 503. 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.
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.

  • Go returns errors where Java throws (Middleware returns 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) with net/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.

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.