Class RateLimitRegistry

java.lang.Object
org.mockserver.ratelimit.RateLimitRegistry

public class RateLimitRegistry extends Object
Process-wide, stateful, protocol-neutral rate-limit registry backing the declarative RateLimit expectation clause. Supports two algorithms:
  • Fixed window — the fixed-window core extracted from HttpQuotaRegistry: the first request in a window starts it, the window expires windowMillis after it started, and a request is allowed when the in-window count (including itself) is at or below limit.
  • Token bucket — a leaky/token bucket of capacity burst refilling at refillPerSecond tokens/second; a request is allowed when at least one whole token is available (and consumes it).

Counters are keyed by name, so several expectations sharing a name share one counter (model an upstream account limit), while distinct names are independent. State is held in ConcurrentHashMaps and each acquire is an atomic per-key update, safe under concurrent requests. Misconfigured limits fail open (never rate-limit).

To bound memory, the total number of distinct named counters is capped at ConfigurationProperties.rateLimitMaxNamedQuotas(); once the cap is reached a request for a new key fails open (is allowed).

The time source is injectable so window/bucket behaviour is unit-testable without sleeping; production uses System.currentTimeMillis(). State is cleared on server reset (see HttpState.reset()).

  • Constructor Details

    • RateLimitRegistry

      public RateLimitRegistry(LongSupplier clock)
  • Method Details

    • getInstance

      public static RateLimitRegistry getInstance()
    • tryAcquire

      public RateLimitRegistry.Decision tryAcquire(RateLimit rl, String fallbackKey)
      Record one request against the named rate limit and report the decision.
      Parameters:
      rl - the declarative rate limit (may be null/misconfigured -> fail open)
      fallbackKey - counter key when rl.getName() is null (the expectation id)
      Returns:
      the decision; RateLimitRegistry.Decision.allowed is true when within the limit (or the limit is misconfigured/fails open)
    • reset

      public void reset()
      Clear all rate-limit state. Called on server reset and for test isolation.