Skip to content

Instantly share code, notes, and snippets.

@bgentry
Created October 11, 2012 23:48
Show Gist options
  • Save bgentry/3876453 to your computer and use it in GitHub Desktop.
Save bgentry/3876453 to your computer and use it in GitHub Desktop.
Go token bucket rate limiter #golang
package main
import (
"fmt"
"time"
)
func main() {
ticker := rateLimit(4, 10)
go work("A", ticker, 2e9)
go work("B", ticker, 3e9)
work("C", ticker, 4e9)
}
func work(name string, ratelimiter chan int, backoff time.Duration) {
for {
select {
case _ = <- ratelimiter:
fmt.Printf(name)
default:
time.Sleep(backoff)
}
}
}
func rateLimit(rps int, burst int) chan int {
c := make(chan int, burst)
for i := 0; i < burst; i++ {
c <- 0
}
ticker := time.Tick(time.Second/time.Duration(rps))
go func() {
for {
_ = <- ticker
c <- 0
}
}()
return c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment