Rate Limiting
Implement rate limiting using Upstash Redis to prevent abuse and ensure fair usage of resources.
This template uses Upstash Redis for rate limiting. For more information, visit the Upstash Redis documentation.
Setup
Prerequisites
Upstash Redis
Connection Details
Environment Setup
Environment Variables
Add the following variables to your .env.local
file:
Ensure your Upstash Redis credentials are kept secure and never committed to version control.
Implementation
Redis Client Setup
Configure the Upstash Redis client in lib/upstash.ts
:
Rate Limiter Configuration
Set up rate limiting with sliding window algorithm:
The sliding window algorithm provides a balance between fixed window and rolling window rate limiting approaches, offering better protection against traffic spikes.
Usage Examples
Server Action Rate Limiting
Implementing rate limiting in server actions:
API Route Rate Limiting
Protecting API routes with rate limiting:
Common Use Cases
Image Uploads
🖼️ Limit the number of image uploads per user per minute
Authentication
🔐 Prevent brute force attacks on authentication endpoints
API Endpoints
🔌 Control access rates to public and private API endpoints
Form Submissions
📝 Prevent spam by limiting form submission frequency
Advanced Configuration
Different Rate Limits
You can create multiple rate limiters with different configurations:
IP-Based Rate Limiting
For public endpoints, you can implement IP-based rate limiting:
When using IP-based rate limiting, be aware of potential issues with shared IPs (e.g., users behind NAT) and implement appropriate limits.
Best Practices
Implementation
- Use unique identifiers per action
- Include user ID in rate limit keys
- Set appropriate time windows
- Handle rate limit errors gracefully
Security
- Implement rate limiting early in request pipeline
- Use different limits for different actions
- Monitor rate limit usage
- Provide clear feedback to users
Error Handling
Create custom error types and response handlers for rate limiting:
Provide user-friendly responses when rate limits are exceeded:
Monitoring
Monitor rate limit usage to identify potential abuse patterns: