ratelimit

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2019 License: MIT Imports: 3 Imported by: 686

README

Go rate limiter

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
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Clock

type Clock interface {
	Now() time.Time
	Sleep(time.Duration)
}

Clock is the minimum necessary interface to instantiate a rate limiter with a clock or mock clock, compatible with clocks created using github.com/andres-erbsen/clock.

type Limiter

type Limiter interface {
	// Take should block to make sure that the RPS is met.
	Take() time.Time
}

Limiter is used to rate-limit some process, possibly across goroutines. The process is expected to call Take() before every iteration, which may block to throttle the goroutine.

func New

func New(rate int, opts ...Option) Limiter

New returns a Limiter that will limit to the given RPS.

func NewUnlimited

func NewUnlimited() Limiter

NewUnlimited returns a RateLimiter that is not limited.

type Option

type Option func(l *limiter)

Option configures a Limiter.

var WithoutSlack Option = withoutSlackOption

WithoutSlack is an option for ratelimit.New that initializes the limiter without any initial tolerance for bursts of traffic.

func WithClock

func WithClock(clock Clock) Option

WithClock returns an option for ratelimit.New that provides an alternate Clock implementation, typically a mock Clock for testing.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL