ratelimit

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ratelimit implements a reserving token bucket.

A caller takes its tokens at once, letting the balance go negative, and then sleeps until the debt is repaid. Callers are therefore served in arrival order, and an expensive request cannot be starved by a stream of cheap ones.

Index

Constants

This section is empty.

Variables

View Source
var ErrStopped = errors.New("ratelimit: stopped")

ErrStopped is returned by Wait when its stop channel is closed.

Functions

This section is empty.

Types

type Bucket

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

Bucket is a reserving token bucket. It is safe for concurrent use.

func New

func New(max, rate float64) *Bucket

New returns a full bucket of max tokens refilled at rate tokens per second.

func (*Bucket) SetTokens

func (b *Bucket) SetTokens(n float64)

SetTokens sets the balance. It exists for tests that need a bucket in a given state.

func (*Bucket) Tokens

func (b *Bucket) Tokens() float64

Tokens returns the current balance, negative while tokens are reserved ahead of the refill.

func (*Bucket) Wait

func (b *Bucket) Wait(ctx context.Context, n float64, stop <-chan struct{}) error

Wait reserves n tokens and blocks until they are available. A cost above the bucket size is capped at it.

If the wait would end after ctx's deadline, Wait fails at once without reserving anything. If ctx ends or stop is closed while waiting, the reservation is returned and ctx's error (or ErrStopped) is reported. A nil stop channel never fires.

Jump to

Keyboard shortcuts

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