RateLimiter

class RateLimiter(val permits: Int, val per: Duration, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

A sliding-window rate limiter that grants at most permits acquisitions within any window of length per.

Algorithm: the limiter remembers the time mark of each recent acquisition and grants a permit whenever fewer than permits marks are younger than per.

acquire and tryAcquire are coroutine-safe: shared state is guarded by a Mutex, and a coroutine suspended in acquire holds the mutex while it waits, so permits are granted to waiters in arrival order.

Constructors

Link copied to clipboard
constructor(permits: Int, per: Duration, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

Properties

Link copied to clipboard

A best-effort snapshot of how many permits are free right now.

Link copied to clipboard

The length of the sliding window.

Link copied to clipboard

The maximum number of acquisitions granted within one window.

Functions

Link copied to clipboard
suspend fun acquire()

Suspends until a permit is free, then consumes it.

Link copied to clipboard

Consumes a permit when one is free right now and reports whether it did.

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

Acquires a permit via acquire, then runs block and returns its result.