KeyedRateLimiter

class KeyedRateLimiter<Key>(val config: RateLimiterConfig = defaultRateLimiterConfig(), val semaphoreStateFactory: () -> SemaphoreState = { InMemorySemaphoreState() }) : AutoCloseable(source)

Manages multiple RateLimiter instances based on a Key, allowing rate limiting based on different keys. This is useful when you want to rate limit different resources or operations separately.

                +--------------------------------+
| +------+ +------+ |
| |-> | K1 | ---> | RL | |
| | +------+ +------+ |
| | | K2 | |
Request | | +------+ +------+ |
----------> + --|-> | K3 | ---> | RL | |
| | +------+ +------+ |
| |-> | K4 | ---> | RL | |
| | +------+ +------+ |
| |-> | K5 | |
| +------+ |
+--------------------------------+

Since each rate limiter can be used in distributed architectures, the semaphore state can be stored in a shared data store, such as a database, by implementing the SemaphoreState interface.

Parameters

Key

The type of key used to identify different rate limiters.

config

The configuration defining the behavior of each rate limiter.

semaphoreStateFactory

A factory function to create semaphore states for rate limiters. Defaults to creating an in-memory semaphore state for each rate limiter.

See also

Constructors

Link copied to clipboard
constructor(config: RateLimiterConfig = defaultRateLimiterConfig(), semaphoreStateFactory: () -> SemaphoreState = { InMemorySemaphoreState() })

Properties

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
private val lock: Mutex
Link copied to clipboard
Link copied to clipboard
internal val wasDisposed: AtomicBoolean

Functions

Link copied to clipboard
inline suspend fun <R> call(key: Key, permits: Int = 1, timeout: Duration = config.baseTimeoutDuration, block: Supplier<R>): R

Decorates a Supplier with a rate limiter based on the provided key.

Link copied to clipboard
open override fun close()
Link copied to clipboard
suspend fun getRateLimiter(key: Key): RateLimiter

Gets the rate limiter based on the provided key, creating a new one if it doesn't exist.

Link copied to clipboard
suspend fun removeRateLimiter(key: Key)

Removes the rate limiter based on the provided key. Before removing the rate limiter, it is closed to release any resources it may hold.