Class SlidingWindowStrategy

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

public final class SlidingWindowStrategy extends Object implements RateLimitStrategy
Sliding-window counter rate limit: approximates a true sliding window by interpolating between the previous fixed window's count and the current window's count.
   estimate = prevCount × (1 − elapsed / windowMs) + currentCount
 

This is the same approximation used by Redis. It eliminates the boundary burst problem of FixedWindowStrategy while staying O(1) memory and lock-free. The error is bounded: in the worst case the true rate at the boundary can exceed the limit by at most limit × (1 − elapsed/windowMs) — typically a few percent.

Slot layout

  • Bucket.slot0 — packed (reducedEpoch << 32 | currentCount)
  • Bucket.slot1 — count from the immediately preceding epoch (0 = none)

On a window transition the thread that wins the slot0 CAS also writes slot1. A concurrent thread that reads slot0 after the transition but before slot1 is written sees a slightly stale previous count — acceptable for an approximation algorithm.

  • Constructor Details

    • SlidingWindowStrategy

      public SlidingWindowStrategy()
  • 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