An open API service indexing awesome lists of open source software.

https://github.com/alexrios/lbucket

An idiomatic Go implementation of Leaky bucket.
https://github.com/alexrios/lbucket

golang idiomatic leaky-bucket

Last synced: about 1 year ago
JSON representation

An idiomatic Go implementation of Leaky bucket.

Awesome Lists containing this project

README

          

# lbucket
[![Go Reference](https://pkg.go.dev/badge/github.com/alexrios/lbucket.svg)](https://pkg.go.dev/github.com/alexrios/lbucket?tab=doc)

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.
```go
NewTickLeakyBucket(3, 1 * time.Second)
```

Calling `Refill()` you're add more volume in the bucket.
```go
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:
```go
errors.Is(err, ErrBucketReachedCap)
```

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

Use Size() to get to current volume in the bucket.
```go
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.