RateLimiter

Token bucket rate limiter for controlling request throughput.

The Rate Limiter pattern controls the rate of operations to prevent overwhelming a system or service. It uses a token bucket algorithm where tokens are added at a fixed rate, and operations consume tokens.

Use Cases:

  • API rate limiting

  • Prevent service overload

  • Comply with third-party API rate limits

  • Control resource consumption

Token Bucket Algorithm:

  • Tokens are added to a bucket at a fixed rate

  • Each operation consumes one or more tokens

  • If no tokens are available, the operation is throttled

  • Allows bursts up to bucket capacity

Basic usage:

val limiter = RateLimiter.create(config = RateLimiterConfig(
permitsPerSecond = 10.0,
burstCapacity = 20
))

val result = limiter.tryExecute {
callApi()
} // returns null if rate exceeded

Blocking execution:

val result = limiter.execute {
callApi()
} // waits for available token

Sliding window variant:

val limiter = SlidingWindowRateLimiter.create(config = SlidingWindowConfig(
maxRequests = 100,
windowDuration = 1.minutes
))

Parameters

config

Configuration for rate limiter behavior

Types

Link copied to clipboard
object Companion

Factory for RateLimiter.

Functions

Link copied to clipboard

Adds a listener for rate limiter events.

Link copied to clipboard
suspend fun availableTokens(): Double

Gets the current number of available tokens.

Link copied to clipboard
suspend fun <T> execute(permits: Int = 1, block: suspend () -> T): T

Executes an operation with rate limiting.

Link copied to clipboard
suspend fun <T> executeOrFallback(permits: Int = 1, fallback: suspend () -> T, block: suspend () -> T): T

Executes an operation with a fallback if rate limited.

Link copied to clipboard
suspend fun reset()

Resets the rate limiter to initial state.

Link copied to clipboard
suspend fun resetStatistics()

Resets all statistics counters.

Link copied to clipboard

Gets the current statistics.

Link copied to clipboard
suspend fun tryAcquire(permits: Int = 1): Boolean

Tries to acquire the specified number of permits.

Link copied to clipboard
suspend fun <T> tryExecute(permits: Int = 1, block: suspend () -> T): T?

Tries to execute an operation, returning null if rate limited.

Inherited functions

Link copied to clipboard

Adapts this RateLimiter into a Policy.