Understanding Rate Limiting
When we build an e-commerce API, we’re essentially creating a digital storefront that needs to handle various types of traffic. Without proper controls, we might face scenarios like:- Bots aggressively scraping our product catalog
- Brute force attempts on our authentication endpoints
- Legitimate users experiencing slowdowns due to excessive requests from others
Implementing Rate Limiting
We’ll implement rate limiting using the @perseidesjs/medusa-plugin-rate-limit plugin, which uses Redis under the hood to track and limit requests. Redis acts as our request tracking system, maintaining a real-time count of requests from each client and their timestamps to enforce our rate limiting rules. First, let’s install our rate limiting plugin:medusa-config.js
The plugin defaults are 10 requests per 60 seconds.
src/api/middlewares/rate-limit.ts
src/api/middlewares.ts
For development, Medusa provides a fake Redis instance out of the box. For production, make sure to configure a real Redis instance by setting the
redis_url
in your project config.Fine-tuning Your Rate Limits
Different endpoints might need different limits. For instance:- Authentication endpoints might need stricter limits to prevent brute force attacks
- Product listing endpoints could be more lenient
- Checkout endpoints might need moderate limits to prevent abuse
Use the default middleware
The plugin provides a default middleware that you can use to protect your routes. This middleware is configured with the default rate limits specified in the plugin options.src/api/middlewares.ts