Class SlidingWindowStrategy
java.lang.Object
dev.relism.flash.ext.limiter.strategy.SlidingWindowStrategy
- All Implemented Interfaces:
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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbooleancheck(Bucket bucket, LimitConfig cfg, long[] out) Checks whether this request is within the limit and updates the bucket atomically.
-
Constructor Details
-
SlidingWindowStrategy
public SlidingWindowStrategy()
-
-
Method Details
-
check
Description copied from interface:RateLimitStrategyChecks whether this request is within the limit and updates the bucket atomically.On return,
outcontains:out[0]— remaining allowed requests in the current window (≥ 0).out[1]— Unix epoch seconds at which the quota resets (forX-RateLimit-ResetandRetry-Afterheaders).
- Specified by:
checkin interfaceRateLimitStrategy- Parameters:
bucket- per-key state carrier (pre-allocated, never null)cfg- immutable rule configurationout- caller-supplied two-element array; values are overwritten on every call- Returns:
trueif the request is within the limit and should proceed
-