limiter

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2024 License: Apache-2.0 Imports: 2 Imported by: 1

Documentation

Overview

Package limiter provides simple rate limiting primitives, and an implementation of a token bucket rate limiter.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter interface {
	Allow() bool
}

Limiter is used to abstract the rate limiter implementation to only expose the needed function for rate limiting. This is for example useful for testing, allowing us to use a modified rate limiter tuned for testing through the same interface.

type TokenTicker

type TokenTicker struct {
	// contains filtered or unexported fields
}

TokenTicker is a thread-safe and lock-free rate limiter based on a token bucket. The idea is to have a goroutine that will update the bucket with fresh tokens at regular intervals using a time.Ticker. The advantage of using a goroutine here is that the implementation becomes easily thread-safe using a few atomic operations with little overhead overall. TokenTicker.Start() *should* be called before the first call to TokenTicker.Allow() and TokenTicker.Stop() *must* be called once done using. Note that calling TokenTicker.Allow() before TokenTicker.Start() is valid, but it means the bucket won't be refilling until the call to TokenTicker.Start() is made

func NewTokenTicker

func NewTokenTicker(tokens, maxTokens int64) *TokenTicker

NewTokenTicker is a utility function that allocates a token ticker, initializes necessary fields and returns it

func (*TokenTicker) Allow

func (t *TokenTicker) Allow() bool

Allow checks and returns whether a token can be retrieved from the bucket and consumed. Thread-safe.

func (*TokenTicker) Start

func (t *TokenTicker) Start()

Start starts the ticker and launches the goroutine responsible for updating the token bucket. The ticker is set to tick at a fixed rate of 500us.

func (*TokenTicker) Stop

func (t *TokenTicker) Stop()

Stop shuts down the rate limiter, taking care stopping the ticker and closing all channels

Jump to

Keyboard shortcuts

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