ratelimit

package
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RateLimiter

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

RateLimiter implements fixed-window rate limiting using NATS KV storage. The fixed window algorithm tracks request counts within time windows identified by the current timestamp divided by the window duration.

Key format: "{urlEncodedIdentifier}-{windowTimestamp}" Example: "192.168.1.1-1769032800" or "2001%3Adb8%3A%3A1-1769032800" for IPv6

Note: Fixed window allows potential 2x burst at window boundaries (acceptable tradeoff for simplicity).

func NewRateLimiter

func NewRateLimiter(js jetstream.JetStream, bucket string, limit int, window time.Duration) (*RateLimiter, error)

NewRateLimiter creates a new rate limiter backed by NATS KV storage. It creates a KV bucket with TTL set to 2x the window duration to ensure old keys expire.

Parameters:

  • js: JetStream context for KV operations
  • bucket: KV bucket name (e.g., "ratelimit")
  • limit: Maximum requests per window (e.g., 5 for 5 req/min)
  • window: Time window duration (e.g., 1 minute)

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ctx context.Context, key string) (bool, time.Duration, error)

Allow checks if the request from the given key (e.g., IP address) is allowed based on the rate limit. It returns:

  • allowed: true if the request is allowed, false if rate limited
  • retryAfter: duration until the next window (only meaningful if allowed=false)
  • error: any error encountered during the check

The fixed window algorithm works as follows:

  1. Calculate current window timestamp: now.Unix() / window.Seconds()
  2. Get current count for this key in this window
  3. Increment count
  4. If count exceeds limit, reject with retryAfter duration
  5. Otherwise, allow the request

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware(next http.Handler) http.Handler

Middleware creates a Chi-compatible middleware that enforces rate limiting on authentication endpoints. It extracts the client IP address from the request and checks against the configured rate limit.

Rate limit responses include:

  • Status: 429 Too Many Requests
  • Header: Retry-After (seconds until next window)
  • Body: {"error": "rate_limited", "retry_after": <seconds>}

IP extraction priority:

  1. X-Forwarded-For header (first IP if multiple)
  2. r.RemoteAddr (direct connection)

Jump to

Keyboard shortcuts

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