https://github.com/linkdata/rate
Efficient rate limiter for Go
https://github.com/linkdata/rate
go golang nodependencies rate-limit rate-limiter rate-limiting
Last synced: 7 months ago
JSON representation
Efficient rate limiter for Go
- Host: GitHub
- URL: https://github.com/linkdata/rate
- Owner: linkdata
- License: mit
- Created: 2024-01-31T11:26:20.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2025-08-21T08:26:37.000Z (7 months ago)
- Last Synced: 2025-08-21T10:35:09.314Z (7 months ago)
- Topics: go, golang, nodependencies, rate-limit, rate-limiter, rate-limiting
- Language: Go
- Homepage:
- Size: 35.2 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/linkdata/rate/actions/workflows/go.yml)
[](https://htmlpreview.github.io/?https://github.com/linkdata/rate/blob/coverage/main/report.html)
[](https://goreportcard.com/report/github.com/linkdata/rate)
[](https://godoc.org/github.com/linkdata/rate)
## An efficient rate limiter for Go
Because too much of the CPU consumed was `golang.org/x/time/rate.Limiter.Wait()` calling `time.Now()`.
### Differences from `golang.org/x/time/rate` and `time.Ticker`
This package uses ticks-per-second rather than `time.Duration`, and is suitable for high-tickrate applications.
It allows you to change the rate by simply atomically changing an `int32`. It has no practical limitation on the upper rate.
If you need a slower rate than once per second, you're better off using `time.Ticker`.
### Sample usage
One of the more common non-trivial usages of rate limiting is restricting some underlying operation(s)
being utilized by more complex worker goroutines. This package supports those with `Ticker.Worker()`.
Assume we have a channel `taskCh` where we read tasks to process, and then
want spawn worker goroutines that handle them. We want to spawn enough of them
to stay as close to the max rate as possible without starting *too* many of them.
```go
for task := range taskCh {
// make sure to not alias variables you use in the lambda
// in case you use Go versions prior to 1.22.
task := task
if !ticker.Worker(func() { workerFn(ticker, task) }) {
// if ticker.Worker() fails to start the worker, it means the Ticker is closed.
break
}
}
```