Class RateLimit
- All Implemented Interfaces:
Middleware
// 100 requests per minute and client address, global
app.use(RateLimit.builder(100, Duration.ofMinutes(1)).key(RateLimitKey.clientAddress(proxies)).build());
// a tighter budget for one group, keyed by user once authenticated
var login = RateLimit.builder(5, Duration.ofMinutes(1)).name("login").build();
app.group("/login", group -> group.post("/", handler, login));
Algorithms. RateLimit.Algorithm.TOKEN_BUCKET (the default) lets a key burst up to the
bucket capacity (RateLimit.Builder.burst, by default the whole limit) and refills continuously at
requests / window. RateLimit.Algorithm.SLIDING_WINDOW counts requests in the current and
the previous window and weights the previous one by how much of it still overlaps the last window
length, which smooths the doubled burst a fixed window allows at its boundary. Both keep constant
state per key.
Rejection. A request over its budget is answered with the problem response of a TooManyRequestsException: 429 application/problem+json, code rate_limited, and
Retry-After in whole seconds (rounded up, so waiting that long is enough). The request
does not reach the rest of the chain. The response is returned, not thrown, so it passes back
through the outer middleware like any response (security headers, CORS) and carries the
RateLimit-* headers too; it is not seen by error handlers. Allowed and rejected responses carry
the RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (seconds) and
RateLimit-Policy headers of the IETF rate limit headers draft when RateLimit.Builder.headers(boolean) is enabled; nested limiters keep the headers of the most constraining
one.
Bounded memory. At most RateLimit.Builder.maxKeys keys are tracked (10,000 by default).
When a new key arrives at capacity, the least recently used key of its shard is forgotten, so a
flood of random keys cannot grow memory. The trade-off is inherent: an evicted key starts with a
full budget, so size maxKeys well above the number of keys that are legitimately active
within one window. A key function that an attacker can vary freely defeats any limiter; see
RateLimitKey.
Time. All arithmetic uses the injected Clock. A clock that jumps backwards
never leaves a key blocked for longer than one window (stale future state is discarded), and one
that jumps forwards simply refills the budget.
Metrics. With RateLimit.Builder.metrics: counter
axiom.security.ratelimit.requests (tags limiter, outcome = allowed or
limited), counter axiom.security.ratelimit.evictions and gauge
axiom.security.ratelimit.keys (tag limiter). The limiter name is configured by the
application; keys are never tags.
Composition. Register the instance globally, on a group or on a route; each instance has its own state and budget, and several may guard one route (all must allow).
Thread-safe; owned by the application it is registered with, and holds no resources to close.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumThe counting algorithm.static final classBuildsRateLimits; not thread-safe, used during configuration.static final recordThe outcome of counting one request.Nested classes/interfaces inherited from interface com.jsgalactic.axiom.context.Middleware
Middleware.Next -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intLongest key tracked; longer keys are counted underRateLimitKey.ANONYMOUS. -
Method Summary
Modifier and TypeMethodDescriptionCounts one request under a key.static RateLimit.BuilderStarts a limiter allowing a number of requests per window for each key.handle(Context context, Middleware.Next next) Handles one request, usually by callingnext.run().toString()intReturns how many keys are tracked now, at mostRateLimit.Builder.maxKeys.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface com.jsgalactic.axiom.context.Middleware
afterError
-
Field Details
-
MAX_KEY_LENGTH
public static final int MAX_KEY_LENGTHLongest key tracked; longer keys are counted underRateLimitKey.ANONYMOUS.- See Also:
-
-
Method Details
-
builder
Starts a limiter allowing a number of requests per window for each key.- Parameters:
requests- requests per window, 1 to 1,000,000,000window- the window length, 1 millisecond to 1 hour- Returns:
- a builder with a token bucket, the transport peer address as key and 10,000 keys
- Throws:
IllegalArgumentException- if a value is out of range
-
trackedKeys
public int trackedKeys()Returns how many keys are tracked now, at mostRateLimit.Builder.maxKeys.- Returns:
- tracked keys
-
acquire
Counts one request under a key. Public so that non-HTTP code and tests can use the same budgets; keys longer than 512 characters share the anonymous key.- Parameters:
key- the key- Returns:
- the decision
-
handle
Description copied from interface:MiddlewareHandles one request, usually by callingnext.run().- Specified by:
handlein interfaceMiddleware- Parameters:
context- the request-scoped context shared with the handler; status settings made here apply to the handler's result mappingnext- the rest of the chain- Returns:
- the response to use; never null
- Throws:
Exception- to fail the request as a handler exception would
-
toString
-