Class TokenBucketRateLimiter
java.lang.Object
ai.redouble.nucleo.harness.admission.AbstractRateLimiter<Integer>
ai.redouble.nucleo.harness.admission.TokenBucketRateLimiter
- All Implemented Interfaces:
LimiterIdentity, RateLimiter<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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classConfiguration for a rate limiter.Nested classes/interfaces inherited from interface RateLimiter
RateLimiter.Replenishment -
Constructor Summary
ConstructorsConstructorDescriptionTokenBucketRateLimiter(String modelName, TokenBucketRateLimiter.Config config) Creates a new rate limiter with the given configuration. -
Method Summary
Modifier and TypeMethodDescriptionlongcapacity()Configured capacity of this account.longCurrent in-use count.earliestFit(List<Integer> mine, List<Integer> reservedAhead) TheSystem.nanoTime()instant at whichRateLimiter.fits(List, List)would become true for these lists from the clock alone;nullwhen only an external event can change the answer - always forRateLimiter.Replenishment.RELEASEaccounts, and for any account whenmineplusreservedAheadexceeds its capacity.booleanWouldminefit right now withreservedAheadset aside.Gets the current available capacity, computed at this instant from the clock.doubleGets current throttle coefficient.voidRefunds a debit whose request never went upstream: rollback and grant compensation.Category identifier.Stable display name for this account.voidonRateLimitError(UpstreamFailure failure) Logs the upstream's summary at warn, so the cause is on record, and records one increment throughrecord429().voidNotifies the rate limiter of a successful operation.voidRecords a 429 response of any kind.voidrecordBackpressure(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, letrecordSuccess()walk it back).voidRecords a successful request.Defaults toRateLimiter.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.voidsetConfig(TokenBucketRateLimiter.Config newConfig) Updates RPM/TPM caps in place.Short human-readable tag describing an abnormal operational state of this account:"blocked","probing","throttle:2.0x","pace:1500ms".booleanTakesmineifmineandreservedAheadfit together; the check and the debit are one atomic step under the account's own lock.Methods inherited from class AbstractRateLimiter
accountFor, capacityChanged, onCapacityChangeMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface RateLimiter
observeHeld, onRateLimitError, onSuccess, requiresHttpConnection
-
Constructor Details
-
TokenBucketRateLimiter
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
Description copied from interface:RateLimiterWouldminefit right now withreservedAheadset aside. -
tryTake
Description copied from interface:RateLimiterTakesmineifmineandreservedAheadfit 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
-
earliestFit
Description copied from interface:RateLimiterTheSystem.nanoTime()instant at whichRateLimiter.fits(List, List)would become true for these lists from the clock alone;nullwhen only an external event can change the answer - always forRateLimiter.Replenishment.RELEASEaccounts, and for any account whenmineplusreservedAheadexceeds its capacity. A past instant means now. -
setConfig
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 invariantavailable <= capacityholds 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 andrecordSuccess()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, letrecordSuccess()walk it back). The weight comes fromUpstreamRetryException.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:RateLimiterNotifies the rate limiter of a successful operation. Used by adaptive strategies to relax throttling. -
onRateLimitError
Logs the upstream's summary at warn, so the cause is on record, and records one increment throughrecord429().- Parameters:
failure- the upstream's status and response detail; never null
-
replenishment
Description copied from class:AbstractRateLimiterDefaults toRateLimiter.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:
replenishmentin interfaceRateLimiter<Integer>- Overrides:
replenishmentin classAbstractRateLimiter<Integer>
-
limiterName
Description copied from interface:LimiterIdentityStable display name for this account. Used as a metric tag, a log prefix and thewait_timeskey. -
limiterCategory
Description copied from interface:LimiterIdentityCategory identifier. One of: "memory", "token_bucket", "elastic_window", "semaphore". -
capacity
public long capacity()Description copied from interface:LimiterIdentityConfigured capacity of this account. -
currentInUse
-
statusIndicator
Description copied from interface:LimiterIdentityShort human-readable tag describing an abnormal operational state of this account:"blocked","probing","throttle:2.0x","pace:1500ms". Returnsnullwhen 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:
statusIndicatorin interfaceLimiterIdentity- Overrides:
statusIndicatorin classAbstractRateLimiter<Integer>
-
recordSuccess
public void recordSuccess()Records a successful request. Every third success takes0.2off the throttle; after five minutes without a backpressure signal every success takes0.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
Gets the current available capacity, computed at this instant from the clock.
-