DEV Community

Hiram
Hiram

Posted on

How to rate limit requests in Laravel with ThrottleRequests middleware

I decided to share this because I think it is the easiest way to protect your endpoints whether you are working with web or api endpoints with Laravel.

Given my API receives a lot of requests I am always looking for more and advanced ways to squeeze my stack and get the best performance without investing too much money on it.

Now, besides applying front and backend cache it was time to rate limit my api. After looking for some methods, I faced again with the 'laravel throttle' way to do it. The only thing you have to do is throttling your endpoints with the throttle middleware, here you have some examples:

Route::middleware(['auth:api'])->group(function () {
    Route::get('/recents', 'Api\WebappController@recents')->middleware('throttle:5,1,recents');
    Route::post('/directory', 'Api\WebappController@directory')->middleware('throttle:10,1,directory');
});
Enter fullscreen mode Exit fullscreen mode

As you can see in the applied middleware, I am specifying with the first value the number of allowed requests, and with the second the time window the counter is going to be valid. The third parameter (recents|directory) is the way you specify the scope or segment of the rate limit, it is optional.

If you are wondering how throttle manage the storage of the rate limit counter, the answer is that it takes the session driver value from the env file, in my case is the following:

SESSION_DRIVER=redis
Enter fullscreen mode Exit fullscreen mode

I strongly recommend you to use redis or memcached for caching and session storaging.

You can also apply a dynamic rate limiting or guest and auth rate limit to your endpoints. Here you have the Laravel official docs: Rate Limiting

I hope you find this information useful, in the next chapter I'll post how to use the less known RateLimiter class which encapsulates the same behaviour but with a different implementation.

Top comments (0)