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.
- Host: GitHub
- URL: https://github.com/alexrios/lbucket
- Owner: alexrios
- License: mit
- Created: 2021-05-30T18:56:17.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2021-05-31T20:43:27.000Z (about 5 years ago)
- Last Synced: 2025-04-02T06:12:04.815Z (about 1 year ago)
- Topics: golang, idiomatic, leaky-bucket
- Language: Go
- Homepage: https://pkg.go.dev/github.com/alexrios/lbucket?tab=doc
- Size: 5.86 KB
- Stars: 11
- Watchers: 2
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# lbucket
[](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.