ratelimit

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ratelimit provides a small, dependency-free per-key token-bucket rate limiter suitable for guarding authentication and agent endpoints.

Buckets are keyed by an arbitrary string (typically a client IP). Each bucket refills lazily based on elapsed wall-clock time, so there is no background goroutine on the hot path. Idle buckets are evicted opportunistically to keep memory bounded under a churning set of source addresses.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Rate is the sustained number of allowed events per second.
	Rate float64
	// Burst is the maximum number of events allowed in an instantaneous spike.
	Burst float64
	// TTL evicts buckets that have not been touched for this long. Defaults to
	// 10 minutes when zero.
	TTL time.Duration
	// MaxKeys caps the number of tracked buckets to bound memory. Defaults to
	// 100000 when zero. When exceeded, the limiter sheds the oldest buckets.
	MaxKeys int
	// Now is an injectable clock for tests. Defaults to time.Now.
	Now func() time.Time
}

Config controls a Limiter. Rate and Burst must both be positive.

type Limiter

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

Limiter is a concurrency-safe collection of per-key token buckets.

func New

func New(cfg Config) *Limiter

New builds a Limiter from cfg, applying defaults for zero-valued fields.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) bool

Allow reports whether an event for key may proceed, consuming one token when it returns true.

func (*Limiter) AllowN

func (l *Limiter) AllowN(key string, n float64) bool

AllowN reports whether n events for key may proceed, consuming n tokens when it returns true. A request larger than the burst can never succeed.

func (*Limiter) Len

func (l *Limiter) Len() int

Len returns the number of currently tracked buckets. Primarily for tests.

Jump to

Keyboard shortcuts

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