Rate Limiting — Aquilia Documentation
Comprehensive guide and documentation for Rate Limiting in the Aquilia framework. View API reference, examples, and implementation patterns.
MIDDLEWARE / RATE LIMITING Rate Limiting Middleware The RateLimitMiddleware provides token bucket and sliding window rate limiting to protect services against denial-of-service and brute-force traffic. Supported Algorithms Sliding Window (Default) Maintains high accuracy by inspecting the current and previous fixed-time windows. It computes a weighted request count based on overlap, eliminating spikes at window boundaries while using minimal O(1) space. Token Bucket Implements lazy refills on request arrival. Tolerates short-term burst traffic up to a configured capacity, enforcing smooth limits over time. v1.4.0b2 Updates 500 to 429 Bug Fix Fixed a bug where rate limiting would crash with a NameError (returning 500) because the Response class was imported under TYPE_CHECKING only. It now correctly returns a 429 Too Many Requests response. Identity-Based Rate Limiting Identity-based rate limiting rules now run at priority 16 (after AUTH at 15), while anonymous IP-based rules still run at priority 12. This ensures user keys are extracted correctly. requires_identity field RateLimitRule gained a new requires_identity boolean field. This is automatically detected and set to true when using user_key_extractor. Socket Disconnect Cleanup BucketStore gained a discard() method to allow proper cleanup of sliding window and token bucket states on socket disconnects. Zero Refill Rate Guard TokenBucket.consume is now guarded against a zero refill rate (limit=0 no longer raises ZeroDivisionError). Configuration from aquilia.middleware.builtin import ( RateLimitMiddleware, RateLimitRule, ip_key_extractor, api_key_extractor, user_key_extractor, ) limiter = RateLimitMiddleware( rules=[ # 1. Global IP Limit: 100 requests per minute RateLimitRule( limit=100, window=60.0, key_func=ip_key_extractor, ), # 2. Scoped API Key Limit: 1000 requests per hour on /api paths RateLimitRule( limit=1000, window=3600.0, key_func=api_key_extractor, scope="/api", ), # 3. Burst Tolerant Token Bucket for logins (POST only) RateLimitRule( limit=5, window=300.0, algorithm="token_bucket", burst=10, key_func=ip_key_extractor, scope="/auth/login", methods=["POST"], ), ], response_format="json", ) server.middleware(limiter) Key Extractors The rate limiter groups requests by a unique string key. Aquilia ships with three built-in extractors: ip_key_extractor(request) Extracts the client IP address. Respects reverse proxies if ProxyFixMiddleware is active. api_key_extractor(request) Extracts from the X-API-Key header or the Bearer token in the Authorization header. user_key_extractor(request) Extracts the authenticated user ID from request state or identity objects set by Auth middleware. RateLimitRule Options Option Type Default Description limit int 100 Max requests allowed within the window. window float 60.0 Duration of the rate limit window in seconds. algorithm str "sliding_window" Limit algorithm ("sliding_window" or "token_bucket"). key_func Callable ip_key_extractor Function mapping Request to a string rate limit key. burst int | None None Extra burst capacity (token_bucket only). scope str "*" Path prefix this rule applies to. methods list[str] [] HTTP methods restricted by this rule (empty = all). CORS Security Headers )
Go to Homepage