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 ¶
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:
- Calculate current window timestamp: now.Unix() / window.Seconds()
- Get current count for this key in this window
- Increment count
- If count exceeds limit, reject with retryAfter duration
- 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:
- X-Forwarded-For header (first IP if multiple)
- r.RemoteAddr (direct connection)