Key Strategies
Determining how to identify and group clients for rate limiting.
Key strategies define how the unique identifier (key) for rate limiting is constructed. Halt provides flexible options to limit by IP, user, API key, or custom logic.
Built-in Strategies
1. Per-IP Address
Limits requests based on the client's IP address. Useful for public APIs.
# Automatically handles X-Forwarded-For headers
key = f"ip:{request.client.host}"2. Per-User
Limits requests based on the authenticated user ID.
key = f"user:{current_user.id}"3. Per-API Key
Limits based on the API key provided in headers.
key = f"apikey:{api_key}"Composite Keys
Combine multiple identifiers for more granular control.
// Limit per user per IP
const key = `user:${userId}:ip:${ipAddress}`;Custom extraction in Middleware
You can customize how the key is extracted in framework adapters.
FastAPI Example
async def custom_key_func(request: Request):
return request.headers.get("X-Custom-ID") or "anonymous"
app.add_middleware(
HaltMiddleware,
limiter=limiter,
key_func=custom_key_func
)