Go

rate.Limiter — Token-Bucket Rate Limiting

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`golang.org/x/time/rate` provides a battle-tested token-bucket limiter. Use to enforce "N requests per second with bursts up to B" — for per-IP throttling, external API rate limits, etc.
Go
Raw
// go get golang.org/x/time/rate
package main

import (
    "context"
    "fmt"
    "time"

    "golang.org/x/time/rate"
)

func main() {
    // 5 events per second, burst up to 10
    limiter := rate.NewLimiter(5, 10)

    ctx := context.Background()
    for i := 0; i < 30; i++ {
        // Block until a token is available (or context cancels)
        if err := limiter.Wait(ctx); err != nil {
            fmt.Println("wait failed:", err); return
        }
        fmt.Printf("%2d: %s\n", i, time.Now().Format("15:04:05.000"))
    }

    // Non-blocking — Allow() returns false if a token isn't available
    if limiter.Allow() {
        // process
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.