Go by Example

Rate Limiting

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

Rate limiting controls how often an operation proceeds. A ticker can pace a simple loop, while a token bucket also supports bursts and 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 can pace a single process, but it is not a durable token bucket and does not coordinate limits across service instances. Use golang.org/x/time/rate when burst capacity or per-process token-bucket behavior is needed. Enforce a shared quota at a shared service when all instances must obey one limit.

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