Overview
The rate limiter provides IP-based request throttling using token bucket algorithm. It automatically manages visitor lifecycles and cleans up inactive entries.Types
IPRateLimiter
Manages rate limits for individual IP addresses with thread-safe operations.main.go:29-35
Map of IP addresses to their visitor rate limiters
Mutex for thread-safe access to the IP map
Rate limit (requests per second)
Burst size (maximum requests allowed in a burst)
visitor
Internal type tracking individual IP rate limiters.main.go:37-40
Functions
NewIPRateLimiter()
Creates and initializes a new IPRateLimiter with specified rate limit and burst size.main.go:56-64
Rate limit (requests per second). Use
rate.Limit(n) to convert from int.Burst size (maximum number of requests allowed in a burst)
Initialized rate limiter with background cleanup goroutine running
Usage Example
GetLimiter()
Returns a rate limiter for the specified IP address, creating a new one if it doesn’t exist, and updates its last seen time.main.go:68-81
IP address to get or create a limiter for
Rate limiter instance for the specified IP
Usage Example
cleanupVisitors()
Removes inactive visitors from the IP map based on a 3-minute inactivity duration. Runs continuously in a background goroutine.main.go:84-95
This function is automatically started as a goroutine by
NewIPRateLimiter(). It checks every minute and removes visitors inactive for more than 3 minutes.Environment Variables
See Environment Variables for rate limiter configuration:PROXY_RATE_LIMIT- Requests per second (default: 5)PROXY_RATE_BURST- Burst size (default: 10)
Implementation Details
Cleanup Interval
The cleanup goroutine runs every 1 minute and removes visitors that haven’t been seen for more than 3 minutes.Thread Safety
All operations usesync.Mutex to ensure thread-safe access to the internal IP map.
Token Bucket Algorithm
Uses Go’sgolang.org/x/time/rate package which implements the token bucket algorithm for smooth rate limiting.