Rate limiting is a crucial security and performance feature that helps prevent abuse, brute-force attacks, and overuse of your application resources. Laravel provides a powerful and flexible way to handle rate limiting via built-in middleware and custom configurations.
🚧 Why Use Rate Limiting?
- Protect endpoints from spamming or brute-force login attempts
- Ensure fair use of server resources
- Improve overall API and application performance
⚙️ Using Laravel's Built-in Throttle Middleware
Laravel includes a throttle
middleware you can apply to routes or route groups.
Route::middleware('throttle:60,1')->group(function () {
Route::get('/api/data', 'ApiController@getData');
});
This allows a maximum of 60 requests per minute per IP address.
🛠️ Creating Custom Rate Limiters
Since Laravel 8, you can define named rate limiters using the RateLimiter
facade inside your RouteServiceProvider
.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
public function boot()
{
RateLimiter::for('custom-api', function ($request) {
return Limit::perMinute(10)->by($request->ip());
});
}
Then use it in your routes like this:
Route::middleware('throttle:custom-api')->get('/api/custom', 'ApiController@custom');
👤 Rate Limiting by User ID
You can scope rate limits to the user instead of the IP address:
RateLimiter::for('login', function ($request) {
return Limit::perMinute(5)->by(optional($request->user())->id ?: $request->ip());
});
This helps protect login forms or endpoints based on authenticated user identity.
📉 Handling Exceeded Rate Limits
When a rate limit is exceeded, Laravel automatically returns a 429 Too Many Requests
response. You can customize the response by overriding the ThrottleRequests
middleware or handling it in your exception handler.
💡 Best Practices
- Apply lower limits on sensitive endpoints like login or registration
- Use different limiters for public vs. authenticated routes
- Log or monitor when limits are frequently hit to adjust thresholds
- Throttle APIs especially if exposed to third-party apps
✅ Conclusion
Rate limiting in Laravel is powerful, flexible, and easy to configure. Whether you're building a public API or securing internal routes, Laravel gives you full control to protect your app efficiently.
📘 Want to learn more? Check out the official docs: Laravel Rate Limiting
Comments
Post a Comment