Skip to content

alexrios/lbucket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

lbucket

Go Reference

lbucket is an idiomatic Go leaky bucket implementation.

The library make use of plain old Go stdlib; in other words, there are no third-party dependencies.

How to use

Package lbucket provides support for using leaky buckets on your app.

Creating a new Leaky bucket informing 3 as the bucket capacity and the frequency how the bucket leaks.

NewTickLeakyBucket(3, 1 * time.Second)

Calling Refill() you're add more volume in the bucket.

bucket := NewTickLeakyBucket(3, 1 * time.Second)
err := bucket.Refill()

Note: When the bucket capacity is reached a ErrBucketReachedCap will be returned until the bucket leaks once again. A simple errors.Is could be used in this scenario:

errors.Is(err, ErrBucketReachedCap)

To stop the bucket leaking you can call the Fix() method.

bucket.Fix()

Use Size() to get to current volume in the bucket.

bucket.Size()

Common use case(s)

API's rate limiter.

In this use you can read:

  • NewTickLeakyBucket() as How many requests per second it's gonna handle?
  • Refill() as Can I respond this request?
    • ErrBucketReachedCap as Reched the server limit
  • Fix() as From now on I'm no longer accepting requests
  • Size() as How many requests are in flight?

eg: NewTickLeakyBucket(3, 1 * time.Second) -> 3 requests / second.