Class RateLimit

java.lang.Object
com.jsgalactic.axiom.security.RateLimit
All Implemented Interfaces:
Middleware

public final class RateLimit extends Object implements Middleware
Rate limiting middleware: at most a number of requests per window for each key, with memory that stays bounded however many distinct keys arrive.

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

  • Field Details

  • Method Details

    • builder

      public static RateLimit.Builder builder(long requests, Duration window)
      Starts a limiter allowing a number of requests per window for each key.
      Parameters:
      requests - requests per window, 1 to 1,000,000,000
      window - 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 most RateLimit.Builder.maxKeys.
      Returns:
      tracked keys
    • acquire

      public RateLimit.Decision acquire(String key)
      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

      public Response handle(Context context, Middleware.Next next) throws Exception
      Description copied from interface: Middleware
      Handles one request, usually by calling next.run().
      Specified by:
      handle in interface Middleware
      Parameters:
      context - the request-scoped context shared with the handler; status settings made here apply to the handler's result mapping
      next - the rest of the chain
      Returns:
      the response to use; never null
      Throws:
      Exception - to fail the request as a handler exception would
    • toString

      public String toString()
      Overrides:
      toString in class Object