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. Configuration from aquilia.middleware_ext 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