Hotstreak is lightweight library for creating a certain type of rate limiting solution.
It provides the tools needed for rate limiting, but does not try to solve everything.
Hotstreak uses 2 terms Active
and Hot
.
While it's active, you can call Hit
to increase the inner counter.
After you call Hit
for a configurable amount of times, the streak will become Hot
.
Hot
means that only deactivation can stop the service from being Active
for a configurable amount of time. (It also helps with handling hits as fast as possible)
After a configurable time, if no Hit
were made at all, it deactivates.
Limit
- int - Describes how many times we have to hit before a streak becomes hotHotWait
- time.Duration - Describes the amount of time we are waiting before declaring a cool downActiveWait
- time.Duration - Describes the amount of time we are waiting to check on a streak being activeAlwaysActive
- boolean - Describes if the streak can deactivate or should stay active forever
Most commands are chainable to allow easier handling.
streak := hotstreak.New(hotstreak.Config{
Limit: 20, // Hit 20 times before getting hot
HotWait: time.Minute * 5, // Wait 5 minutes before cooling down
ActiveWait: time.Minute * 10, // Wait 10 minutes before deactivation
})
streak.Activate().Hit()
// do things
if streak.Hit().IsHot() {
// Hit and do other things if the streak became hot
}
See docs for more info.
Make certain number of requests in given time period
streak := hotstreak.New(hotstreak.Config{
Limit: 20,
HotWait: time.Minute * 5,
ActiveWait: time.Minute * 10,
})
streak.Activate()
for _, request := range requests {
streak.Hit()
// If we are hitting it too hard, try slowing down
if streak.IsHot() {
<-time.After(time.Second * 5)
}
// .. logic
}