| 1 |
# Go rate limiter [![GoDoc][doc-img]][doc] [![Coverage Status][cov-img]][cov] ![test][test-img] |
| 2 |
|
| 3 |
This package provides a Golang implementation of the leaky-bucket rate limit algorithm. |
| 4 |
This implementation refills the bucket based on the time elapsed between |
| 5 |
requests instead of requiring an interval clock to fill the bucket discretely. |
| 6 |
|
| 7 |
Create a rate limiter with a maximum number of operations to perform per second. |
| 8 |
Call Take() before each operation. Take will sleep until you can continue. |
| 9 |
|
| 10 |
```go |
| 11 |
import ( |
| 12 |
"fmt" |
| 13 |
"time" |
| 14 |
|
| 15 |
"go.uber.org/ratelimit" |
| 16 |
) |
| 17 |
|
| 18 |
func main() { |
| 19 |
rl := ratelimit.New(100) // per second |
| 20 |
|
| 21 |
prev := time.Now() |
| 22 |
for i := 0; i < 10; i++ { |
| 23 |
now := rl.Take() |
| 24 |
fmt.Println(i, now.Sub(prev)) |
| 25 |
prev = now |
| 26 |
} |
| 27 |
|
| 28 |
// Output: |
| 29 |
// 0 0 |
| 30 |
// 1 10ms |
| 31 |
// 2 10ms |
| 32 |
// 3 10ms |
| 33 |
// 4 10ms |
| 34 |
// 5 10ms |
| 35 |
// 6 10ms |
| 36 |
// 7 10ms |
| 37 |
// 8 10ms |
| 38 |
// 9 10ms |
| 39 |
} |
| 40 |
``` |
| 41 |
|
| 42 |
## FAQ: |
| 43 |
- What's the major diff v.s. https://pkg.go.dev/golang.org/x/time/rate? (based on #77) |
| 44 |
|
| 45 |
This ratelimiter was meant to have a (1) simple API and (2) minimal overhead. For more complex use-cases [x/time/rate] is a great choice. See [here][redit] for historical context, and [here][bench] for benchmarks (from 2016). |
| 46 |
|
| 47 |
- Why does example_test.go fail when I run it locally on Windows? (based on #80) |
| 48 |
|
| 49 |
Windows has some known issues with timers precision. See golang/go#44343. We don't expect to work around it. |
| 50 |
|
| 51 |
[cov-img]: https://codecov.io/gh/uber-go/ratelimit/branch/master/graph/badge.svg?token=zhLeUjjrm2 |
| 52 |
[cov]: https://codecov.io/gh/uber-go/ratelimit |
| 53 |
[doc-img]: https://pkg.go.dev/badge/go.uber.org/ratelimit |
| 54 |
[doc]: https://pkg.go.dev/go.uber.org/ratelimit |
| 55 |
[test-img]: https://github.com/uber-go/ratelimit/workflows/test/badge.svg |
| 56 |
[redit]: https://www.reddit.com/r/golang/comments/59k2bi/ubergoratelimit_a_golang_blocking_leakybucket/d99ob9q |
| 57 |
[x/time/rate]: https://pkg.go.dev/golang.org/x/time/rate |
| 58 |
[bench]: https://gist.github.com/prashantv/26016a7dbc6fc1ec52d8c2b6591f3582 |