Courses

How to Build Laravel 11 API From Scratch

Throttling Maximum Requests per Minute

Summary of this lesson:
- Implementing API rate limiting/throttling
- Configuring request limits per minute
- Custom rate limiting based on user roles

Let's talk about a feature called Rate Limiting, or in other words, called Throttling. What happens if the API is called too many times per minute or hour? Then the user receives an error with the message Too Many Attempts. and 429 Too Many Requests HTTP status.


First, we must enable the API throttling for the Middleware.

bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
->withProviders()
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix: 'api/v1',
)
->withMiddleware(function (Middleware $middleware) {
$middleware
->statefulApi()
->withThrottledApi();
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

Next, we can configure the rate limiter in the AppServiceProvider boot method. For example, we can limit the whole API to six requests per minute.

app/Providers/AppServiceProvider.php:

use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
 
class AppServiceProvider extends ServiceProvider
{
// ...
 
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(6)->by($request->user()?->id ?: $request->ip());
});
}
}

If you need to set different rate limiters on some routes, this can be done using...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord