Rate limiting is an important feature of the modern web application for prevention against abuse, optimal performance, and fair usage of servers. Laravel 11 simplifies rate limit implementation in routing and lets the developer manage traffic efficiently.
In this blog, we will explore how to apply rate limiting in Laravel 11 routes
What is Rate Limiting?
Rate limiting restricts the number of requests that a user or client can send to a server over a given period. Laravel provides a flexible rate limiting feature via middleware supported by the RateLimiter facade. This feature gives the developer power to:
- Limit abuse (e.g., brute force attacks)
- Ensure fair usage
- Optimize server resources
Benefits of Rate Limiting in Laravel:
- Improved application performance
- Enhanced user experience
- Reduction in the backend’s load
- Protection of APIs and better security
Steps to Apply Rate Limiting in Laravel 11 Routing:
Step 1: Define the rate limit
You need to define the rate limit in the RouteserviceProvider
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Http\Request;
class RouteServiceProvider extends ServiceProvider
{
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
// Define your routes here
});
}
protected function configureRateLimiting()
{
RateLimiter::for(‘api’, function (Request $request) {
return Limit::perSecond(5)->by($request->ip());
});
}
}
Explanation:
- RateLimiter::for(‘api’): Defines rate limits for the API middleware group.
- Limit::perSecond(5): Restrict user to 5 requests per second.
- by($request->ip()): Apply the limit based on the user’s IP address.
Step 2: Apply the rate limit to the routes
Open the Web.php File and apply rate limit
use Illuminate\Support\Facades\Route;
Route::middleware([‘throttle:api’])->group(function () {
Route::get(‘/data’, [DataController::class, ‘index’]);
});
Step 3: Handling rate limiting response
public function render($request, Throwable $exception)
{
if ($exception instanceof ThrottleRequestsException) {
return response()->json([
‘message’ => ‘Too many requests. Please try again later.’,
], 429);
}
return parent::render($request, $exception);
}
Step 4: Testing per second rate limit
Open Postman and hit this curl
curl -X GET http://your-app.test/api/data
Send multiple requests in a short span to ensure that the 429 response is triggered after exceeding the limit.
Conclusion
The rate-limiter features of Laravel 11 provide a powerful tool that can be used for traffic control in applications, ensuring application security, and maintaining smooth user experience.
Let’s get your Laravel application optimized with rate limiting. Share your use case or questions below!