Go by Example

Rate Limiting

Control the rate of operations using tickers and the golang.org/x/time/rate token bucket.

Rate limiting sets how often an operation may happen. A ticker sends time values at regular intervals and can space out operations in one loop. A token bucket tracks credits that refill over time; each allowed operation uses one, and a small burst can use several. It is available in the golang.org/x/time/rate package.

Wait for one tick before each operation. When the work is fast, this spaces operations about 200 milliseconds apart.

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    limiter := time.NewTicker(200 * time.Millisecond)
    defer limiter.Stop()
    for request := 1; request <= 3; request++ {
        <-limiter.C
        fmt.Println("request", request)
    }
}

In production

A ticker limits work only inside one running program. If several copies of a server are running, each copy has its own ticker and limit. Put a shared limit in a service all copies can check when they must follow one quota.

Enjoyed this? Get more software craft delivered to your inbox.