DistributedRateLimiter

class DistributedRateLimiter(store: SharedStateStore, key: String, maxRequests: Int, window: Duration, clock: Clock = Clock.System)(source)

Cross-instance fixed-window rate limiter whose counter lives in a SharedStateStore (e.g. a Redis-backed one), so every process sharing the store shares one budget of maxRequests per window.

val limiter = DistributedRateLimiter(redisStore, "api", maxRequests = 100, window = 1.minutes)
limiter.execute { callApi() } // throws RateLimitExceededException when over budget

Constructors

Link copied to clipboard
constructor(store: SharedStateStore, key: String, maxRequests: Int, window: Duration, clock: Clock = Clock.System)

Functions

Link copied to clipboard

Adapts this limiter into a Policy.

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

Runs block if a permit is available.

Link copied to clipboard
suspend fun tryAcquire(): Boolean

Tries to take one permit. Returns true if granted.

Link copied to clipboard
suspend fun <T> tryExecute(block: suspend () -> T): T?

Like execute but returns null when over budget.