Skip to content

uber-go/ratelimit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

3e5300c · Apr 30, 2024

History

71 Commits
Apr 30, 2024
Apr 30, 2024
Jun 5, 2022
Mar 4, 2024
Oct 25, 2016
Jun 5, 2022
Jun 21, 2022
Jul 7, 2022
Jul 9, 2023
Jun 6, 2022
Jun 5, 2022
Mar 4, 2024
Jul 9, 2023
Oct 31, 2022
Jul 2, 2022
Mar 4, 2024

Repository files navigation

Go rate limiter GoDoc Coverage Status test

This package provides a Golang implementation of the leaky-bucket rate limit algorithm. This implementation refills the bucket based on the time elapsed between requests instead of requiring an interval clock to fill the bucket discretely.

Create a rate limiter with a maximum number of operations to perform per second. Call Take() before each operation. Take will sleep until you can continue.

import (
	"fmt"
	"time"

	"go.uber.org/ratelimit"
)

func main() {
    rl := ratelimit.New(100) // per second

    prev := time.Now()
    for i := 0; i < 10; i++ {
        now := rl.Take()
        fmt.Println(i, now.Sub(prev))
        prev = now
    }

    // Output:
    // 0 0
    // 1 10ms
    // 2 10ms
    // 3 10ms
    // 4 10ms
    // 5 10ms
    // 6 10ms
    // 7 10ms
    // 8 10ms
    // 9 10ms
}

FAQ:

  • What's the major diff v.s. https://pkg.go.dev/golang.org/x/time/rate? (based on #77)

    This ratelimiter was meant to have a (1) simple API and (2) minimal overhead. For more complex use-cases x/time/rate is a great choice. See here for historical context, and here for benchmarks (from 2016).

  • Why does example_test.go fail when I run it locally on Windows? (based on #80)

    Windows has some known issues with timers precision. See golang/go#44343. We don't expect to work around it.

About

A Go blocking leaky-bucket rate limit implementation

Resources

License

Stars

Watchers

Forks

Packages

No packages published