Skip to content

Hotstreak is a tiny library that provides all tools needed for rate limiting and nothing more

License

Notifications You must be signed in to change notification settings

Roverr/hotstreak

Repository files navigation

Codeship Status for Roverr/hotstreak Go Report Card codecov

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.

How

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.

Config

  • Limit - int - Describes how many times we have to hit before a streak becomes hot
  • HotWait - time.Duration - Describes the amount of time we are waiting before declaring a cool down
  • ActiveWait - time.Duration - Describes the amount of time we are waiting to check on a streak being active
  • AlwaysActive - boolean - Describes if the streak can deactivate or should stay active forever

Chainability

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.

Example

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
    }

About

Hotstreak is a tiny library that provides all tools needed for rate limiting and nothing more

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published