ratelimit

package
v1.0.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: AGPL-3.0 Imports: 3 Imported by: 0

Documentation

Overview

Package ratelimit provides rate limiting domain types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatKey

func FormatKey(keyType KeyType, value string) string

FormatKey returns a structured rate limit key. Format: "ratelimit:{type}:{value}" Examples:

  • FormatKey(KeyTypeIP, "192.168.1.1") -> "ratelimit:ip:192.168.1.1"
  • FormatKey(KeyTypeUser, "user-123") -> "ratelimit:user:user-123"

Types

type KeyType

type KeyType string

KeyType identifies the type of rate limit key.

const (
	// KeyTypeIP is for IP-based rate limiting.
	KeyTypeIP KeyType = "ip"

	// KeyTypeUser is for user/API key-based rate limiting.
	KeyTypeUser KeyType = "user"
)

type RateLimitConfig

type RateLimitConfig struct {
	// Rate is the number of allowed events in the period.
	Rate int

	// Burst is the maximum number of events that can occur at once.
	// Burst should be >= Rate for meaningful operation.
	Burst int

	// Period is the time window for the rate limit.
	Period time.Duration
}

RateLimitConfig defines the rate limiting parameters.

type RateLimitResult

type RateLimitResult struct {
	// Allowed indicates whether the request is allowed.
	Allowed bool

	// Remaining is the number of remaining requests in the current window.
	Remaining int

	// RetryAfter is the duration until the next request will be allowed.
	// Only meaningful when Allowed is false.
	RetryAfter time.Duration

	// ResetAfter is the duration until the rate limit resets.
	ResetAfter time.Duration
}

RateLimitResult contains the result of a rate limit check.

type RateLimiter

type RateLimiter interface {
	// Allow checks if a request identified by key is allowed under the given config.
	// It returns the result of the check and any error that occurred.
	//
	// The key should be a structured identifier created by FormatKey.
	// The config specifies the rate limit parameters (rate, burst, period).
	//
	// Allow atomically decrements the rate limit counter and returns the result.
	// If the request is not allowed, RetryAfter in the result indicates when
	// the next request will be allowed.
	Allow(ctx context.Context, key string, config RateLimitConfig) (RateLimitResult, error)
}

RateLimiter is the interface for rate limiting operations.

Implementations should use the GCRA (Generic Cell Rate Algorithm) for smooth rate limiting without burst issues at window boundaries. GCRA provides more consistent behavior than fixed-window or sliding-window algorithms by spreading requests evenly over time.

The interface is designed to be storage-agnostic, allowing implementations backed by Redis, in-memory stores, or other backends.

Jump to

Keyboard shortcuts

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