Class TokenBucketRateLimiter

java.lang.Object
ai.redouble.nucleo.harness.admission.AbstractRateLimiter<Integer>
ai.redouble.nucleo.harness.admission.TokenBucketRateLimiter
All Implemented Interfaces:
LimiterIdentity, RateLimiter<Integer>

public class TokenBucketRateLimiter extends AbstractRateLimiter<Integer>
Dual-bucket token rate limiter (requests per minute + tokens per minute) with adaptive throttling, as an admission account: it never blocks, Admission does. Any upstream slow-down signal stretches the effective refill window via recordBackpressure(int), weighted by how hard the signal asks the fleet to yield (a 429 one increment via record429(), a 529 several - see UpstreamRetryException.backpressureIncrements); sustained successes relax it back. The loop deliberately seeks the boundary - occasional 429s are acceptable feedback signals that we are maximizing throughput.

The bucket is clocked, not ticked: availability at any instant is the stored level plus what the rate has refilled since it was last read, capped at the configured budget. There is no refill thread. earliestFit(List, List) tells the admission evaluator the exact instant a shortfall closes, and the evaluator parks until then.

The controller does not distinguish 429 subtypes (acceleration / capacity / per-second burst / vendor-specific). Any "slow down" signal feeds the same loop, which converges on whatever rate the provider is actually willing to serve without needing vendor-specific header parsing.

Since:
0.1 (2025-08-12)
Author:
Andrey Santrosyan
  • Constructor Details

    • TokenBucketRateLimiter

      public TokenBucketRateLimiter(String modelName, TokenBucketRateLimiter.Config config)
      Creates a new rate limiter with the given configuration.
      Parameters:
      modelName - the model identifier used as the limiter name for observability events (dashboards, logs, traces)
      config - rate-limit configuration
  • Method Details

    • fits

      public boolean fits(List<Integer> mine, List<Integer> reservedAhead)
      Description copied from interface: RateLimiter
      Would mine fit right now with reservedAhead set aside.
    • tryTake

      public boolean tryTake(List<Integer> mine, List<Integer> reservedAhead)
      Description copied from interface: RateLimiter
      Takes mine if mine and reservedAhead fit together; the check and the debit are one atomic step under the account's own lock.
      Returns:
      true when taken, false when the amounts do not fit at this instant
    • give

      public void give(List<Integer> amounts)
      Refunds a debit whose request never went upstream: rollback and grant compensation. Bounded by the configured caps.
    • earliestFit

      public Long earliestFit(List<Integer> mine, List<Integer> reservedAhead)
      Description copied from interface: RateLimiter
      The System.nanoTime() instant at which RateLimiter.fits(List, List) would become true for these lists from the clock alone; null when only an external event can change the answer - always for RateLimiter.Replenishment.RELEASE accounts, and for any account when mine plus reservedAhead exceeds its capacity. A past instant means now.
    • setConfig

      public void setConfig(TokenBucketRateLimiter.Config newConfig)
      Updates RPM/TPM caps in place. Preserves adaptive state (throttle coefficient, success counter, last-backpressure timestamp). When caps shrink, current allowances are clamped down so the invariant available <= capacity holds immediately; when caps grow, the admission evaluator is woken so a parked shortfall can be re-evaluated. No-op if the new config matches the current rpm/tpm pair.

      Called by RateLimiterFactory.updateLimits(ModelSpec, int, int) whenever the upstream provider reports its actual ceilings in response headers.

    • record429

      public void record429()
      Records a 429 response of any kind. Stretches the refill window by incrementing the throttle coefficient; the bucket then refills slower until successes accumulate and recordSuccess() brings the coefficient back down. The caller does not distinguish 429 subtypes (acceleration / capacity / per-second burst / vendor-specific): any upstream "slow down" signal feeds this single loop, which converges on whatever rate the provider is actually willing to serve.
    • recordBackpressure

      public void recordBackpressure(int increments)
      Feeds an upstream slow-down signal into the adaptive throttle, weighted by how hard the signal asks the fleet to yield: a 429 records one increment (this caller nudged past its own budget - a small correction converges), a 529 records several (the provider's whole fleet is saturated and every concurrent job is hearing the same thing - yield hard now, let recordSuccess() walk it back). The weight comes from UpstreamRetryException.backpressureIncrements(). A slower rate wakes nobody: a deadline computed under the old rate merely re-evaluates early.
    • onSuccess

      public void onSuccess()
      Description copied from interface: RateLimiter
      Notifies the rate limiter of a successful operation. Used by adaptive strategies to relax throttling.
    • onRateLimitError

      public void onRateLimitError(UpstreamFailure failure)
      Logs the upstream's summary at warn, so the cause is on record, and records one increment through record429().
      Parameters:
      failure - the upstream's status and response detail; never null
    • replenishment

      public RateLimiter.Replenishment replenishment()
      Description copied from class: AbstractRateLimiter
      Defaults to RateLimiter.Replenishment.RELEASE, which is what a permit means for the capacity gates built directly on this class - a semaphore slot, a pooled connection, heap headroom. All of those are genuinely free again when the work ends.
      Specified by:
      replenishment in interface RateLimiter<Integer>
      Overrides:
      replenishment in class AbstractRateLimiter<Integer>
    • limiterName

      public String limiterName()
      Description copied from interface: LimiterIdentity
      Stable display name for this account. Used as a metric tag, a log prefix and the wait_times key.
    • limiterCategory

      public String limiterCategory()
      Description copied from interface: LimiterIdentity
      Category identifier. One of: "memory", "token_bucket", "elastic_window", "semaphore".
    • capacity

      public long capacity()
      Description copied from interface: LimiterIdentity
      Configured capacity of this account.
    • currentInUse

      public long currentInUse()
      Description copied from interface: LimiterIdentity
      Current in-use count.
    • statusIndicator

      public String statusIndicator()
      Description copied from interface: LimiterIdentity
      Short human-readable tag describing an abnormal operational state of this account: "blocked", "probing", "throttle:2.0x", "pace:1500ms". Returns null when the account is in its nominal state. Consumers surface it alongside capacity and in-use so an out-of-sorts account is visible even when its numeric columns look calm.
      Specified by:
      statusIndicator in interface LimiterIdentity
      Overrides:
      statusIndicator in class AbstractRateLimiter<Integer>
    • recordSuccess

      public void recordSuccess()
      Records a successful request. Every third success takes 0.2 off the throttle; after five minutes without a backpressure signal every success takes 0.5, so a spike is recovered from quickly; a success at throttle zero does nothing. A relaxation wakes the admission evaluator: a faster refill moves every parked deadline earlier. Occasional 429s are acceptable feedback signals for optimal throughput.
    • getThrottleCoefficient

      public double getThrottleCoefficient()
      Gets current throttle coefficient.
    • getStatus

      public TokenBucketStatus getStatus()
      Gets the current available capacity, computed at this instant from the clock.