Class FixedWindowStrategy

java.lang.Object
dev.relism.flash.ext.limiter.strategy.FixedWindowStrategy
All Implemented Interfaces:
RateLimitStrategy

public final class FixedWindowStrategy extends Object implements RateLimitStrategy
Fixed-window rate limit: allows up to LimitConfig.limit() requests per window of LimitConfig.windowMs() milliseconds. The window is aligned to clock time (e.g. 10:00:00 – 10:00:59 for a 60-second window), not sliding.

Implementation

The entire state fits in a single AtomicLong (Bucket.slot0), packed as:
   high 32 bits = reduced epoch  (currentTimeMs / windowMs) invalid input: '&' 0xFFFFFFFFL
   low  32 bits = request count in the current window
 
Each request performs a single CAS loop — no locks, no allocations. At a window boundary the CAS atomically resets the counter to 1.

The reduced epoch wraps every 2^32 × windowMs milliseconds (~13,000 years for a 100 ms window) — collision-free in practice.

  • Constructor Details

    • FixedWindowStrategy

      public FixedWindowStrategy()
  • Method Details

    • check

      public boolean check(Bucket bucket, LimitConfig cfg, long[] out)
      Description copied from interface: RateLimitStrategy
      Checks whether this request is within the limit and updates the bucket atomically.

      On return, out contains:

      • out[0] — remaining allowed requests in the current window (≥ 0).
      • out[1] — Unix epoch seconds at which the quota resets (for X-RateLimit-Reset and Retry-After headers).
      Specified by:
      check in interface RateLimitStrategy
      Parameters:
      bucket - per-key state carrier (pre-allocated, never null)
      cfg - immutable rule configuration
      out - caller-supplied two-element array; values are overwritten on every call
      Returns:
      true if the request is within the limit and should proceed