Exception Handling
Relevant source files
The following files were used as context for generating this wiki page:
Exception handling in FastLimit is designed to provide clear, actionable feedback when rate limits are exceeded or when the system encounters configuration and backend errors. It ensures that both the application logic and end-users receive the necessary metadata—such as retry timings and current usage stats—to handle throttling gracefully.
The system distinguishes between expected operational events (like hitting a rate limit) and exceptional failure states (such as Redis connection issues or invalid configuration strings). This separation allows developers to implement specific logic for user-facing 429 responses while logging or recovering from backend failures.
Core Exception Classes
FastLimit utilizes a hierarchy of exceptions to categorize different failure modes. The primary exception encountered by users is RateLimitExceeded, which is used for flow control.
| Exception Class | Description | Key Attributes |
|---|---|---|
RateLimitExceeded | Raised when a request exceeds the defined rate limit. | retry_after, limit, remaining |
RateLimitConfigError | Raised when invalid configuration is provided (e.g., malformed rate strings or unknown algorithms). | Error message |
BackendError | Raised when the storage backend (Redis) operations fail. | Error message |
Sources: fastlimit/exceptions.py, tests/test_edge_cases.py:27-56, CHANGELOG.md:16-17
RateLimitExceeded Logic
The RateLimitExceeded exception is unique because it carries state about the current window. This metadata is essential for generating HTTP headers like Retry-After.
The diagram shows the inheritance structure of the custom exceptions in the FastLimit library.
Sources: fastlimit/exceptions.py, README.md:255-267
Input Validation and Configuration Errors
FastLimit validates inputs before attempting backend operations. If the library detects invalid parameters, it raises a RateLimitConfigError.
- Invalid Algorithms: Providing an algorithm name that is not "fixed_window", "token_bucket", or "sliding_window" triggers an error. Sources: tests/test_edge_cases.py:27-34
- Malformed Rate Strings: Rate strings must follow the
number/periodformat (e.g., "10/minute"). Invalid formats like "10", "/minute", or "10/week" result in configuration or value errors. Sources: tests/test_edge_cases.py:36-51 - Cost Violations: If a request
costexceeds the total allowedlimitfor a window, the system immediately denies the request with aRateLimitExceededexception. Sources: tests/test_edge_cases.py:65-71
Global Error Handling in Web Frameworks
In FastAPI applications, FastLimit exceptions can be caught using global exception handlers to return standardized JSON responses.
@app.exception_handler(RateLimitExceeded)
async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
return JSONResponse(
status_code=429,
content={
"error": "Rate limit exceeded",
"retry_after": exc.retry_after,
},
headers={
"Retry-After": str(exc.retry_after),
"X-RateLimit-Limit": str(exc.limit),
"X-RateLimit-Remaining": str(exc.remaining)
}
)
Sources: examples/fastapi_app.py:53-69, README.md:255-267
Backend and Connection Resilience
FastLimit identifies and surfaces issues related to the Redis backend.
- Connection Failures: If the
redis_urlis invalid or the server is unreachable, theconnect()method raises an exception. Sources: tests/test_edge_cases.py:126-135 - Health Checks: The
health_check()method returns a boolean (True/False) rather than raising an exception, allowing for safe monitoring of the backend status. Sources: tests/test_edge_cases.py:144-156 - Automatic Reconnection: The
check()method is designed to attempt auto-connection if it detects the backend is not currently connected. Sources: tests/test_edge_cases.py:176-184
This flowchart illustrates the internal logic when a rate check is performed, including connection handling and exception triggers.
Sources: tests/test_edge_cases.py:126-184, README.md:120-131
Metadata and CheckInfo API
The modern check_with_info() API is an alternative to standard checks that helps avoid redundant Redis calls. While it returns a CheckResult object for successful requests, it still raises RateLimitExceeded for failed requests to maintain backward compatibility, ensuring the exception contains the most up-to-date usage data.
Sources: tests/test_edge_cases.py:187-215, CHANGELOG.md:28-29
Conclusion
Exception handling in FastLimit serves as the primary interface for managing traffic flow and system reliability. By utilizing specific exception types like RateLimitExceeded and RateLimitConfigError, the library provides developers with the precise context needed to build resilient, distributed applications that can inform users of throttling constraints via standard HTTP mechanisms.