Overview
TheRateLimiter class implements a Sliding Window Log algorithm to enforce configurable request limits per time window. It ensures safe interaction with the Steam Web API by preventing rate limit violations.
Class Definition
Constructor
Maximum requests allowed per window
Time window in seconds
Attributes
Async lock for thread-safe timestamp management
List of request timestamps within the current window
Maximum requests allowed per window
Time window in seconds
Methods
acquire_token()
Acquire a token to make a request, waiting if necessary to respect rate limits.max_requests occur within any sliding window of window_seconds. If the limit is reached, it calculates the exact wait time until a slot becomes available and sleeps until then.
Behavior:
- Removes expired timestamps (outside the current window)
- Checks if rate limit has been reached
- If limit reached: calculates wait time until oldest timestamp exits the window
- If capacity available: grants token immediately
- Waits outside the critical section to avoid blocking other operations
- None (blocks until token is available)
Algorithm: Sliding Window Log
The rate limiter uses a Sliding Window Log algorithm:- Timestamp Tracking: Every granted request is logged with its timestamp
- Window Calculation: On each
acquire_token()call, timestamps older thanwindow_secondsare removed - Capacity Check: If remaining timestamps <
max_requests, grant token immediately - Wait Calculation: If at capacity, calculate exact time until oldest timestamp expires
- Sleep & Retry: Sleep for calculated duration, then retry from step 2
- Exact rate limiting: Never exceeds
max_requestsperwindow_seconds - Fair queuing: FIFO token distribution
- Minimal wait times: Calculates precise sleep duration
- Thread safety: Uses async locks for concurrent access
Usage Example
Basic Usage
Shared Rate Limiter
Thread Safety
TheRateLimiter is fully thread-safe and async-safe:
- Uses
asyncio.Lockto protect critical sections - Multiple coroutines can safely call
acquire_token()concurrently - Token grants are atomic and FIFO-ordered
- Safe to share across multiple schedulers, clients, and tasks
Performance Characteristics
Where n = number of timestamps in current window (≤ max_requests)
Stores at most
max_requests timestampsCalculates exact wait time based on oldest timestamp
Best Practices
- Share Rate Limiter Instances: Use a single shared instance across all API clients to enforce global rate limits
-
Configure Conservatively: Set
max_requestsslightly below Steam’s actual limit to account for request processing time -
Match Steam’s Window: Steam typically uses 60-second windows, so use
window_seconds=60.0 -
Always Acquire Before Requests: Call
await rate_limiter.acquire_token()immediately before making API calls -
Don’t Catch Blocking: Let
acquire_token()block naturally - it’s designed to wait safely