Ruby token bucket rate limiter
Ruby
class TokenBucket
def initialize(rate:, burst:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
@rate = Float(rate)
@burst = Float(burst)
@clock = clock
@tokens = @burst
@stamp = @clock.call
end
def allow?(cost = 1.0)
now = @clock.call
@tokens = [@burst, @tokens + (now - @stamp) * @rate].min
@stamp = now
return false if @tokens < cost
@tokens -= cost
true
end
end