Class TokenBucketStrategy

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

public final class TokenBucketStrategy extends Object implements RateLimitStrategy
Token-bucket rate limit: tokens refill continuously at a rate of limit / windowMs tokens per millisecond, up to a maximum of limit tokens. Each request consumes one token. Burst traffic is absorbed until the bucket empties.

Implementation

  • Bucket.slot0 — current token count scaled by 1000L (allows sub-token precision without floating-point). Starts at 0; treated as maxScaled when Bucket.slot1 is 0 (first call → bucket starts full).
  • Bucket.slot1 — last-refill timestamp in ms. 0 = not yet initialised.

Each request CAS-loops on slot0; slot1 is advanced monotonically via CAS after a successful token consumption — never regresses to an older timestamp under concurrent load.

  • Constructor Details

    • TokenBucketStrategy

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