module RateLimit::Htb

Htb is a ruby implementation of the hierarchical token bucket algorithm.

It allows you to do rate limiting in a hierarchical fashion in other words you can put a large rate at the root of and smaller rates as children. This way you can guarantee your children a minimum rate and a maximum rate up to the rate of the parents. The rate is represented by Tokens you take out of buckets.

The sum of the rates of the children on the same level may not be greater than the rate of their parent or they will exceed the the rate of their parent.

Example

root = RateLimit::Htb::Bucket.new 1000
child1 = RateLimit::Htb::Bucket.new 300, root
child2 = RateLimit::Htb::Bucket.new 600, root

threads = []

# prints stuff twice as fast as the other two
threads << Thread.new do
  100.times do
    child1.blocking_take 200
    puts "stuff"
  end
end

threads << Thread.new do
  100.times do
    child2.blocking_take 400
    puts "stuff2"
  end
end

# Is called rarely because the other thread needs all the tokens.
threads << Thread.new do
  100.times do
    child2.blocking_take 400
    puts "stuff3"
  end
end

threads.each { |t| t.join }

Constants

VERSION