API Rate-Limiting with Lumen 5.6 and Illuminate Routing/ThrottleRequests Class

API Rate-Limiting with Lumen 5.6 and Illuminate Routing/ThrottleRequests Class
Rate This Post

Off the back of this article, there could be some potential improvements to make the setup a bit more robust. Instead of copying classes manually into the Lumen’s middleware, it may be best to pull packages from composer and sub-class Laravel’s ThrottleRequests class – part of Laravel’s Illuminate Routing library – to avoid missing any potential changes/features in the future.

This process can be done in the following steps:

Add the Illuminate Routing library via Composer

Add Laravel’s Illuminate Routing library to your project by running the following command within your root Lumen directory:

  1. composer require illuminate/routing


Create a sub-classed ThrottleRequests middleware class

Instead of modifying core libraries or copying it into your project, simply create your own middleware class (in this example it was arbitrarily named RateLimits) to sub-class the existing ThrottleRequests class from the Illumincate Routing library and implement the fingerprinting function within your class.

Within your `app/Http/Middleware` folder create a new middleware class that extends \Illuminate\Routing\Middleware\ThrottleRequests.  The key is to implement the resolveRequestSignature function to define how we want to fingerprint each request.

  1. <?php
  3. namespace App\Http\Middleware;
  5. use Closure;
  7. class RateLimits extends \Illuminate\Routing\Middleware\ThrottleRequests
  8. {
  9. protected function resolveRequestSignature($request)
  10. {
  11. return sha1(implode('|', [
  12. $request->method(),
  13. $request->root(),
  14. $request->path(),
  15. $request->ip(),
  16. $request->query('access_token')
  17. ]
  18. ));
  20. return $request->fingerprint();
  21. }
  23. }


Add the middleware class to the bootstrap

Once your middleware class is created. Activate the middleware via your `bootstrap/app.php` file by adding:

  1. $app->routeMiddleware([
  2. 'throttle' => App\Http\Middleware\RateLimits::class
  3. ]);


Implement middleware into the routes

Use your middleware class in your routes. In the following example we are allowing 2 requests every minute for the “myroute” endpoint.

  1. $router->get('/myroute', ['middleware' => ['throttle:2,1'], function () use ($router) {
  2. //do things
  3. }]);

All steps should now be completed for the Throttling middleware to be activated. If the route is refreshed 3 times very quickly (i.e. within a minute) a 429 HTTP Error response should be returned. In development mode you should see: