Class: TokenBucketRateLimiter
Package:
@litert/concurrentImport path:@litert/concurrentSource: packages/partials/concurrent/src/Classes/TokenBucketRateLimiter.tsImplements:ISyncRateLimiter
A synchronous rate limiter using the token bucket algorithm. The bucket holds up to capacity tokens. One token is consumed per call; one token is restored every refillIntervalMs milliseconds (up to capacity). If no tokens are available, the call is rejected immediately.
Constructor
new TokenBucketRateLimiter(opts: ITokenBucketRateLimiterOptions)See ITokenBucketRateLimiterOptions.
Throws:
TypeError— ifcapacityorrefillIntervalMsis not a positive safe integer.TypeError— ifinitialTokensis outside[0, capacity].
Methods
challenge()
challenge(): voidConsumes one token. Throws if no tokens remain.
Throws: E_RATE_LIMITED (or custom error).
isBlocking()
isBlocking(): booleanReturns true when the bucket currently has zero tokens (after a lazy refill).
isIdle()
isIdle(): booleanReturns true when the bucket is full (no tokens have been consumed since the last full refill).
call(fn)
call<TFn extends IFunction>(fn: TFn): ReturnType<TFn>Calls fn after a successful challenge().
reset()
reset(): voidRefills the bucket to capacity immediately.
wrap(fn)
wrap<T extends IFunction>(fn: T): TReturns a wrapper function that challenges the bucket before every call.
Example
import { TokenBucketRateLimiter } from '@litert/concurrent';
const limiter = new TokenBucketRateLimiter({
capacity: 10,
refillIntervalMs: 100, // one token every 100ms
});
try {
limiter.challenge();
processRequest();
} catch {
console.log('Too many requests');
}