Class: Jaeger::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/jaeger/rate_limiter.rb

Overview

RateLimiter is based on leaky bucket algorithm, formulated in terms of a credits balance that is replenished every time check_credit() method is called (tick) by the amount proportional to the time elapsed since the last tick, up to the max_balance. A call to check_credit() takes a cost of an item we want to pay with the balance. If the balance exceeds the cost of the item, the item is “purchased” and the balance reduced, indicated by returned value of true. Otherwise the balance is unchanged and return false.

This can be used to limit a rate of messages emitted by a service by instantiating the Rate Limiter with the max number of messages a service is allowed to emit per second, and calling check_credit(1.0) for each message to determine if the message is within the rate limit.

It can also be used to limit the rate of traffic in bytes, by setting credits_per_second to desired throughput as bytes/second, and calling check_credit() with the actual message size.

Instance Method Summary collapse

Constructor Details

#initialize(credits_per_second:, max_balance:) ⇒ RateLimiter

Returns a new instance of RateLimiter.



22
23
24
25
26
27
# File 'lib/jaeger/rate_limiter.rb', line 22

def initialize(credits_per_second:, max_balance:)
  @credits_per_second = credits_per_second
  @max_balance = max_balance
  @balance = max_balance
  @last_tick = Time.now
end

Instance Method Details

#check_credit(item_cost) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/jaeger/rate_limiter.rb', line 29

def check_credit(item_cost)
  update_balance

  return false if @balance < item_cost

  @balance -= item_cost
  true
end

#update(credits_per_second:, max_balance:) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/jaeger/rate_limiter.rb', line 38

def update(credits_per_second:, max_balance:)
  update_balance

  @credits_per_second = credits_per_second

  # The new balance should be proportional to the old balance
  @balance = max_balance * @balance / @max_balance
  @max_balance = max_balance
end