Scala token bucket rate limiter with bursts
Scala
final class TokenBucket(ratePerSecond: Double, capacity: Int):
require(ratePerSecond > 0, "rate must be positive")
require(capacity > 0, "capacity must be positive")
private var tokens = capacity.toDouble
private var lastRefill = System.nanoTime()
def tryAcquire(amount: Int = 1): Boolean = synchronized {
require(amount > 0 && amount <= capacity, "invalid amount")
val now = System.nanoTime()
val elapsed = (now - lastRefill).toDouble / 1e9
tokens = math.min(capacity.toDouble, tokens + elapsed * ratePerSecond)
lastRefill = now
if tokens >= amount then { tokens -= amount; true } else false
}