Data Models and Configurations
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
FastLimit relies on a structured set of data models and configuration parameters to ensure production-ready rate limiting. The system is designed around Pydantic for robust configuration validation and standard Python dataclasses for high-performance result reporting. These models define how the library connects to Redis, which algorithms are utilized by default, and how the results of rate limit checks are communicated back to the application.
The core of the configuration system is the RateLimitConfig model, which governs the behavior of the RateLimiter. Check results are encapsulated in the CheckResult model, providing a consistent interface for developers to handle allowed or denied requests. Sources: fastlimit/models.py:1-71
Core Data Models
RateLimitConfig
The RateLimitConfig class is a Pydantic BaseModel used to configure the global behavior of the rate limiter. It includes settings for backend connectivity, default algorithmic choices, and performance tuning for the Redis connection pool.
| Field | Type | Default | Description |
|---|---|---|---|
redis_url | str | "redis://localhost:6379" | Connection URL (redis://, rediss://, or unix://). |
key_prefix | str | "ratelimit" | Prefix for all keys stored in Redis. |
default_algorithm | Literal | "fixed_window" | Choice of "fixed_window", "token_bucket", or "sliding_window". |
enable_metrics | bool | False | Enables Prometheus metrics collection. |
connection_timeout | int | 5 | Redis connection timeout in seconds. |
socket_timeout | int | 5 | Redis socket timeout in seconds. |
max_connections | int | 50 | Maximum connections in the Redis pool. |
Sources: fastlimit/models.py:40-69, README.md:144-156
CheckResult
The CheckResult is a dataclass returned by the check_with_info() method. It provides a comprehensive snapshot of the rate limit state for a specific key and window. This model is particularly useful for populating HTTP headers without making secondary backend calls.
The diagram above illustrates the structure of the result object returned after every rate limit evaluation. Sources: fastlimit/models.py:14-37
Rate Limit Definitions and Parsing
FastLimit uses a string-based format for defining rate limits (e.g., "100/minute"). These strings are processed by internal utility functions into numeric values used by the algorithms.
Supported Time Units
The parse_rate function handles the conversion of strings into a tuple of (requests, window_seconds).
| Unit | Seconds | Examples |
|---|---|---|
second / seconds | 1 | "10/second" |
minute / minutes | 60 | "100/minute" |
hour / hours | 3,600 | "1000/hour" |
day / days | 86,400 | "10000/day" |
Sources: tests/test_utils.py:27-50, README.md:158-163
Key Generation and Security
Data models for keys are constructed dynamically based on the identifier, the algorithm, and the tenant type. This ensures isolation across different users or tiers.
As shown in the flow above, keys are URL-encoded to prevent delimiter collisions (e.g., distinguishing between user:123 and user_123) and hashed if they exceed 200 characters to maintain Redis performance. Sources: fastlimit/utils.py:133-176, tests/test_security.py:20-40
Security Configurations
- Password Redaction: The configuration system ensures that if a
redis_urlcontains credentials, they are redacted in logs using the_redact_redis_urlutility. Sources: tests/test_security.py:108-125 - Proxy Headers: The
@limiter.limitdecorator andRateLimitMiddlewareinclude atrust_proxy_headersboolean (defaulting toFalse). WhenTrue, the system extracts client IPs fromX-Forwarded-FororX-Real-IP. Sources: fastlimit/decorators.py:202-235
Integration Configurations
Decorator Parameters
The limit decorator accepts several functional configurations to dynamically determine rate limiting behavior per request.
| Parameter | Type | Description |
|---|---|---|
rate | str | The limit string (e.g., "5/second"). |
key_func | Callable | Extracts the key from the Request object. |
tenant_func | Callable | Identifies the tenant tier (e.g., "premium"). |
cost_func | Callable | Calculates request weight (e.g., 5 for heavy operations). |
Sources: fastlimit/decorators.py:30-65, examples/fastapi_app.py:157-175
Middleware State
When using RateLimitHeadersMiddleware, the system injects rate limit metadata into the request.state. This allows the middleware to append X-RateLimit-* headers to the outgoing response automatically. Sources: fastlimit/decorators.py:168-185, fastlimit/middleware.py
Conclusion
The data models and configurations in FastLimit provide a robust foundation for distributed rate limiting. By combining Pydantic-validated configurations with standardized check results and secure key generation logic, the library ensures that rate limits are enforced accurately across various deployment environments. Sources: fastlimit/models.py:3-12, README.md:50-70