Advanced Usage
Table of Contents
- Different Limits for Different Routes
- Custom Key Generators
- Dynamic Configuration
- IP Allowlist and Denylist
- Redis Distributed Storage
- Response Outcome Rollback
- Custom Response Handler
- Framework Integration Patterns
- Production Notes
- Related Documents
Different Limits for Different Routes
Route-level limits let one application use different quotas for login, normal API calls, admin operations, and internal endpoints.
Express Example
Egg.js Route-Level Pattern
Egg.js projects often keep route logic in middleware and use route path or route name as part of the key:
Custom Key Generators
Why Key Generation Matters
The key defines who shares a quota. A poor key can accidentally make unrelated users share the same limit, or let one user bypass expected limits.
Key Strategy Comparison
Examples
Dynamic Configuration
Dynamic max
Dynamic skip
Use skip carefully. It bypasses rate limiting. For IP allowlists, prefer an independent allowlist middleware before the limiter unless bypassing quota is the explicit requirement.
IP Allowlist and Denylist
Independent Allowlist Pattern
The allowlist authorizes access. The limiter still controls request volume. See Allowlist and Rate Limit Independence.
Denylist Pattern
Place denylist/allowlist middleware before rate limiting when you want rejected traffic to avoid consuming quota.
Redis Distributed Storage
Use Redis when multiple application instances need shared counters:
Use CacheHubStore when you want cache-hub atomic primitives:
Response Outcome Rollback
Roll Back Successful Requests
This is useful when you only want failed requests to count, such as login failures.
Roll Back Failed Requests
This is useful when successful requests should count but failed downstream responses should not consume user quota.
Important Implementation Detail
Rollback requires internal metadata. Direct public check() results hide this metadata by default. Middleware explicitly enables it when rollback options are configured.
Custom Response Handler
Use a handler when your API has a standard error format.
Framework Integration Patterns
Direct check()
Use direct check() when the framework is not Express-compatible:
Express-Compatible Middleware
Use middleware() when the framework supports (req, res, next):
Wrapper Middleware
When a framework uses a different signature, wrap check() and map the result to the framework's own response object.
Production Notes
- Call
close()for limiter-owned Redis clients or cache-hub cleanup timers. - Use RedisStore or CacheHubStore with Redis when counters must be shared.
- Keep allowlist authorization separate from rate limiting unless bypass is intentional.
- Use business keys for sensitive operations.
- Record benchmark environment before using benchmark results in capacity planning.
- Keep English and Chinese docs synchronized when examples, options, or behavior change.