Rate Limiting
Wit’s server includes a flexible rate limiting middleware to protect API endpoints from abuse. The rate limiter supports multiple storage backends and provides fine-grained control over request limits.
Overview
Rate limiting features:
- Configurable limits - Set requests per time window
- Multiple stores - Memory, Redis, or sliding window
- Preset configurations - Ready-to-use limits for common endpoints
- User-aware limits - Different limits for authenticated users
- Trusted bypass - Skip limits for trusted sources
Basic Usage
Configuration Options
Presets
Wit includes presets for common use cases:
Standard
100 requests per minute for general API endpoints:
Strict
5 requests per minute for sensitive endpoints:
Auth
3 requests per 15 minutes for authentication:
Search
20 requests per minute for expensive operations:
Upload
30 requests per minute for file uploads:
Webhook
60 requests per minute for webhook endpoints:
Relaxed
300 requests per minute for read-only endpoints:
Preset Details
When headers: true (default), rate limit info is included in responses:
When rate limited:
Custom Key Generation
By default, rate limiting is based on IP address. Customize this:
User-Aware Rate Limiting
Different limits for authenticated vs anonymous users:
Trusted Source Bypass
Skip rate limiting for trusted sources:
Storage Backends
Memory Store (Default)
Suitable for single-instance deployments:
Redis Store
For distributed/multi-instance deployments:
Sliding Window Store
More accurate limiting using Redis sorted sets:
Endpoint-Specific Limits
Use the factory function for type-safe endpoint limits:
Custom Error Handler
Accessing Rate Limit Info
Access rate limit info in route handlers:
Best Practices
Use Redis storage for production deployments with multiple instances.
Set stricter limits on authentication endpoints to prevent brute force attacks.
Use the sliding window algorithm for more accurate rate limiting at the cost of slightly higher Redis load.
Memory store data is lost on restart. Use Redis for persistence.
Rate limits based on IP can be bypassed with proxies. Consider user-based limits for authenticated endpoints.
Example: Complete Setup