DefaultRateLimiter

class DefaultRateLimiter(config: RateLimiterConfig, onRateLimited: suspend (Duration) -> Unit = {}, timeSource: TimeSource = SystemTimeSource) : RateLimiter

A default, thread-safe implementation of the RateLimiter interface that uses a token-bucket algorithm.

Refill semantics: Tokens refill at the start of each RateLimiterConfig.period (fixed-window refill). When a full period has elapsed since the last refill, the bucket is refilled with RateLimiterConfig.maxCalls tokens (capped at maxCalls). So with maxCalls=10 and period=1s, you get at most 10 calls per second, with the "window" aligned to when the bucket was last refilled. This is a single global bucket per policy.

Each call to execute consumes one token. When no tokens are available:

  1. If RateLimiterConfig.timeoutWhenLimited is null, it immediately throws RateLimitExceededException.

  2. If a timeout is configured, it waits up to that duration for the next refill; if the wait would exceed the timeout, it throws RateLimitExceededException.

This implementation is thread-safe. Access to the token count is synchronized.

Parameters

config

The configuration for this rate limiter, specifying the maximum number of calls per period and the timeout behavior.

onRateLimited

A suspendable lambda that is invoked when a call is rate-limited and forced to wait. It receives the duration of the wait as a parameter. This is called before the wait begins.

timeSource

A source for the current time, used for calculating token refills. Defaults to the system clock.

Constructors

Link copied to clipboard
constructor(config: RateLimiterConfig, onRateLimited: suspend (Duration) -> Unit = {}, timeSource: TimeSource = SystemTimeSource)

Functions

Link copied to clipboard
open suspend override fun <T> execute(block: suspend () -> T): T

Executes block after obtaining a permit from the rate limiter; may suspend or throw if the limit is exceeded.

Link copied to clipboard

Returns a point-in-time snapshot of the rate limiter state.