StmRateWindow

STM-based rate tracking window for sliding window rate limiting.

Tracks request timestamps in a sliding window and provides atomic acquire operations for rate limiting.

Basic usage:

val window = StmRateWindow.create(windowMs = 1000L)
val now = Clock.System.now().toEpochMilliseconds()
val allowed = atomically {
with(window) { tryAcquire(maxRequests = 10, nowMs = now) }
} // true if under rate limit

Checking current request count:

val window = StmRateWindow.create(windowMs = 5000L)
val now = Clock.System.now().toEpochMilliseconds()
atomically {
with(window) {
tryAcquire(maxRequests = 100, nowMs = now)
val count = currentCount(nowMs = now)
println("Requests in window: $count")
}
}

Types

Link copied to clipboard
object Companion

Factory for StmRateWindow.

Functions

Link copied to clipboard
fun STM.currentCount(nowMs: Long): Int

Returns the current number of active requests in the window within an STM transaction. Also cleans up expired entries.

Link copied to clipboard
fun STM.reset()

Resets the rate window, clearing all tracked requests within an STM transaction.

Link copied to clipboard
fun STM.tryAcquire(maxRequests: Int, nowMs: Long): Boolean

Attempts to acquire a request slot within an STM transaction. Cleans up expired entries and checks against maxRequests.