ratelimit

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 7 Imported by: 1 module, 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 local rate-limiting primitives: a token bucket, a leaky bucket, and a concurrency limiter. They are transport-agnostic and can be composed into middleware or applied directly.

Index

Constants

View Source
const (
	// Unknown indicates the outcome could not be determined (store error).
	Unknown = iota
	// Allowed means the request is within quota and quota is not yet full.
	Allowed
	// HitQuota means the request is within quota and just filled it.
	HitQuota
	// OverQuota means the request exceeds the quota.
	OverQuota
)

PeriodLimit result codes. Unlike a boolean limiter, these let callers distinguish "allowed", "allowed but just hit the quota", and "rejected".

Variables

This section is empty.

Functions

This section is empty.

Types

type ConcurrencyLimiter

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

ConcurrencyLimiter limits the number of concurrently active operations. Unlike TokenBucket/LeakyBucket it is not time-based: the caller must explicitly release an acquired slot.

func NewConcurrencyLimiter

func NewConcurrencyLimiter(n int) *ConcurrencyLimiter

NewConcurrencyLimiter returns a ConcurrencyLimiter allowing n concurrent operations.

func (*ConcurrencyLimiter) Acquire

func (l *ConcurrencyLimiter) Acquire() bool

Acquire attempts to take a slot without blocking. It returns false when the concurrency limit is reached.

func (*ConcurrencyLimiter) Release

func (l *ConcurrencyLimiter) Release()

Release returns a previously acquired slot.

type LeakyBucket

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

LeakyBucket is a leaky-bucket rate limiter: requests fill a bucket of fixed capacity that leaks one request per interval.

func NewLeakyBucket

func NewLeakyBucket(capacity int, interval time.Duration) *LeakyBucket

NewLeakyBucket returns a LeakyBucket that holds up to capacity requests and leaks one request per interval.

func (*LeakyBucket) Allow

func (b *LeakyBucket) Allow() bool

Allow implements Limiter.

type Limiter

type Limiter interface {
	// Allow reports whether a single request may proceed.
	Allow() bool
}

Limiter decides whether a request may proceed.

type PeriodLimit

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

PeriodLimit limits how many requests are allowed within a rolling (or aligned) time window, backed by a shared Store for cross-instance coordination.

func NewPeriodLimit

func NewPeriodLimit(period time.Duration, quota int, store Store, keyPrefix string,
	opts ...PeriodOption) *PeriodLimit

NewPeriodLimit returns a PeriodLimit allowing quota requests per period, keyed under keyPrefix.

func (*PeriodLimit) Take

func (l *PeriodLimit) Take(key string) (int, error)

Take records one request for key and reports its result code.

func (*PeriodLimit) TakeCtx

func (l *PeriodLimit) TakeCtx(ctx context.Context, key string) (int, error)

TakeCtx is Take with a context.

func (*PeriodLimit) TakeCtxQuota added in v0.0.6

func (l *PeriodLimit) TakeCtxQuota(ctx context.Context, key string, quota int) (int, error)

TakeCtxQuota is TakeCtx with the allowance supplied by the caller instead of the one the limiter was built with.

What is per-call and what is not

Only the **comparison** moves. The counter is still `keyPrefix + key` and its TTL is still the period the limiter was constructed with, both unchanged by this argument — so calling this with a different quota against the same key reads and increments the *same* counter. That is the whole point: raising an allowance for one caller must not hand them a fresh window, which is what would happen if the quota were folded into the key.

It exists for a limiter whose allowance is per-caller (a per-user override resolved before each request) and which therefore cannot fix the number at construction. A caller with a fixed allowance should keep using TakeCtx.

type PeriodOption

type PeriodOption func(*PeriodLimit)

PeriodOption customizes a PeriodLimit.

func Align

func Align() PeriodOption

Align aligns the window to natural boundaries (e.g. a 1-day period resets at midnight rather than one day after first use).

type RateLimiter

type RateLimiter interface {
	// Acquire reports whether a request may proceed, consuming a token if so.
	Acquire(ctx context.Context) bool
	// Status reports the current (max, cur, interval) limiter state.
	Status(ctx context.Context) (max, cur int, interval time.Duration)
}

RateLimiter is a lightweight, local (non-distributed) rate limiter for non-critical paths where a Redis round-trip would be too heavy.

func NewQPSLimiter

func NewQPSLimiter(interval time.Duration, limit int) RateLimiter

NewQPSLimiter returns a local QPS limiter that refills to limit tokens every interval. The returned RateLimiter owns a background goroutine released when the limiter is garbage collected via the finalizer-free Stop-free design: callers using it for the process lifetime need no explicit shutdown.

func NewQPSLimiterWithStop

func NewQPSLimiterWithStop(interval time.Duration, limit int) (RateLimiter, func())

NewQPSLimiterWithStop returns a QPS limiter together with a stop function that releases its background goroutine.

type Store

type Store interface {
	// TakeTokens atomically consumes n tokens from the bucket identified by key,
	// which refills at rate tokens per second up to burst capacity. It reports
	// whether the tokens were granted.
	TakeTokens(ctx context.Context, key string, rate, burst, n int) (bool, error)
	// IncrWindow atomically increments the counter identified by key and returns
	// the new value. The first increment starts an expiry of window.
	IncrWindow(ctx context.Context, key string, window time.Duration) (int64, error)
	// Ping checks the health of the backing store.
	Ping(ctx context.Context) error
	// Close releases resources held by the store.
	Close() error
}

Store is the storage abstraction for distributed rate limiting. Implementations provide atomic operations across instances; a memory implementation is used for single-instance or testing, and a Redis implementation for multi-instance coordination. It is defined consumer-side (interface segregation) so callers do not depend on any specific backend.

type TokenBucket

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

TokenBucket is a token-bucket rate limiter: it refills tokens at a steady rate and allows bursts up to the configured capacity.

func NewTokenBucket

func NewTokenBucket(rate float64, burst int) *TokenBucket

NewTokenBucket returns a TokenBucket refilling rate tokens per second and allowing bursts of up to burst tokens.

func (*TokenBucket) Allow

func (b *TokenBucket) Allow() bool

Allow implements Limiter.

type TokenLimiter

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

TokenLimiter is a distributed token-bucket limiter with a local fallback: it normally consumes tokens from a shared Store, but when the store becomes unavailable it transparently degrades to an in-process limiter and resumes the store once it recovers. This prevents a remote-store outage from taking rate limiting down with it (cascading-failure protection).

func NewTokenLimiter

func NewTokenLimiter(rate, burst int, store Store, key string) *TokenLimiter

NewTokenLimiter returns a TokenLimiter consuming from store under key, refilling at rate tokens per second with bursts up to burst.

func (*TokenLimiter) Allow

func (l *TokenLimiter) Allow() bool

Allow reports whether a single request may proceed.

func (*TokenLimiter) AllowContext

func (l *TokenLimiter) AllowContext(ctx context.Context, n int) bool

AllowContext reports whether n requests may proceed, honoring ctx for the remote store call so a canceled request does not block on the store.

func (*TokenLimiter) AllowN

func (l *TokenLimiter) AllowN(n int) bool

AllowN reports whether n requests may proceed.

func (*TokenLimiter) Close

func (l *TokenLimiter) Close() error

Close stops the recovery monitor goroutine, if any. It is idempotent and safe to call when the limiter is no longer needed.

type WindowGiver added in v0.0.6

type WindowGiver interface {
	// GiveBackWindow returns one to the counter identified by key.
	//
	// It never lets the counter fall below zero: a give-back may arrive after the
	// window expired (the key is gone) or after another process reset it, and a
	// negative count would make the next window start with free requests. Both
	// cases are a no-op rather than an error.
	GiveBackWindow(ctx context.Context, key string) error
}

WindowGiver is an optional Store capability: returning one count to a window the caller had charged for a request that produced no result.

Why a counter needs to move backwards

A window aligned to the platform day is a *quota* — "twenty posts today", not "twenty requests a minute". A request the handler refused (a validation error, a permission refusal, an outage) produced nothing to count, and leaving it in the day's total is how an account loses a quota it never spent: retrying a publish that fails for a fixable reason spends the whole day's allowance, and nothing the account does afterwards can get it back before midnight.

The short windows and token buckets are deliberately *not* given the same treatment by their callers: those measure request load, and a failed request still consumed the service's work. The distinction lives in the caller, not here — this interface only provides the primitive.

It is separate from Store for the same reason WindowReader is

A Store that cannot give a count back is still a complete Store, and a caller type-asserts this capability and falls back to "every request counts" when it is absent. Both shipped implementations provide it.

type WindowReader added in v0.0.6

type WindowReader interface {
	// PeekWindow returns a window counter's current value. The second return is
	// false when the key does not exist, which means no requests have been
	// counted in this window — not an error.
	PeekWindow(ctx context.Context, key string) (int64, bool, error)
}

WindowReader is an optional Store capability: reading a window counter without changing it.

Why it is separate from Store

A Store that cannot answer this is still a complete Store — the limiter only ever increments — so requiring it would force every implementation to grow a method it has no use for. The two implementations also differ in how naturally they answer it: Redis has GET, the in-process map already holds the entry.

A caller uses a type assertion and treats its absence as "this deployment cannot report usage", which is the honest answer rather than a zero: a screen showing "0 of 10 used" for a ceiling nobody can measure is reporting a fact it does not have.

It is read-only on purpose. An operator's view of a ceiling must not be able to move it, and a method that could also reset a counter would be one call away from doing so.

Directories

Path Synopsis
store
memory
Package memory provides an in-process ratelimit.Store.
Package memory provides an in-process ratelimit.Store.
redis
Package redis provides a Redis-backed ratelimit.Store using atomic Lua scripts, for distributed rate limiting across multiple instances.
Package redis provides a Redis-backed ratelimit.Store using atomic Lua scripts, for distributed rate limiting across multiple instances.

Jump to

Keyboard shortcuts

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