ratelimit

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: AGPL-3.0 Imports: 3 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 provides a per-key token-bucket rate limiter. It is used to throttle login and public HTTP endpoints (FA-API-07).

The limiter keeps one bucket per key. Each bucket holds up to Burst tokens and refills at Rate tokens per second; a request consumes one token. The number of buckets is bounded by Limit to protect against memory exhaustion through many distinct keys (for example spoofed client addresses).

Index

Constants

View Source
const DefaultLimit = 100_000

DefaultLimit is the number of keys a Limiter created by New keeps before it starts evicting buckets. A zero Limit field also falls back to it.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter struct {
	// Rate is the number of tokens refilled per second. It should be > 0;
	// a non-positive Rate disables refilling.
	Rate float64
	// Burst is the bucket size, the maximum number of requests allowed at once.
	// Values below 1 are treated as 1.
	Burst int
	// Limit is the maximum number of keys kept. When the limit is reached and
	// a new key arrives, buckets that are full again are dropped first; if none
	// are full, the least recently used bucket is dropped.
	Limit int
	// Now returns the current time. Nil means time.Now. It is intended to be
	// replaced in tests.
	Now func() time.Time
	// contains filtered or unexported fields
}

Limiter allows Burst requests per key at once and refills Rate tokens per second.

A Limiter must not be copied after first use. The zero value is usable once Rate and Burst are set; Limit falls back to DefaultLimit when it is not positive. Limiter is safe for concurrent use.

func New

func New(rate float64, burst int) *Limiter

New returns a limiter with rate tokens per second, the given burst and a key limit of DefaultLimit.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) (ok bool, retryAfter time.Duration)

Allow takes one token for key. If none is available it returns false and how long until the next token is available. The returned duration is always > 0 when ok is false and is rounded up, so waiting for it is sufficient. When ok is true the duration is 0.

Jump to

Keyboard shortcuts

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