Laravel 12 Rate Limiting: A Reason Why Your Application Needs This Feature

logo icon

Admin Teguh

-

2025 August 26

iamge article

In developing modern web applications, maintaining system security and performance is a top priority. One of the outstanding features in Laravel that supports this is the Rate Limiting feature. This feature allows us developers to control the number of requests that can be made to the application within a certain period of time.

What is Rate Limiting?

Rate Limiting, also known as Rate Limiter, is a mechanism for limiting the number of HTTP Requests that can be made by users or IP addresses to an endpoint within a certain period of time. The goal is to prevent resource abuse, protect applications from cyber attacks such as brute force, and maintain optimal server performance.

In Laravel 12, the Rate Limiting feature has been improved with more flexible capabilities, including support for limiting requests per second, not just per minute as in previous versions.

How Does Rate Limiting Work?

Laravel 12 provides a built-in middleware called throttle that makes it easy to implement Rate Limiting. This middleware allows us to set limits on the number of requests and the duration of time with a simple approach. Here's how rate limiting works in Laravel:

  1. Rate Limiting can be applied based on IP address, user ID, or other combinations.
  2. Developers specify the maximum number of requests allowed within a certain time period, for example, 60 requests per minute.
  3. Laravel uses a cache system to track the number of requests and expiration times.
  4. If the request limit is exceeded, Laravel will automatically return an HTTP 429 (Too Many Requests) response.

Implementing Rate Limiting in Laravel 12

Here are the steps to implement Rate Limiting in Laravel 12:

  • Throttle Middleware

The simplest way is to use the throttle middleware on the route.

Route::post(/login-process’, [LoginController::class, ‘process’])->middleware(‘throttle:10,1’);

// group route
Route::middleware(‘throttle:10,1’)->group(function () {
    // Routes
});

The code above will limit HTTP Requests for login to 10 requests per minute.

  • Custom Rate Limiter

If you need to customize the Rate Limiter, you can do so through the /bootstrap/app.php or AppServiceProvider.php files in the boot method.

  • bootstrap/app.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        apiPrefix: '/api', // set prefix api routes
        then: function () {
            RateLimiter::for('api', function (Request $request) {
                return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
            });
        }
    )
    ->create();
  • AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
}

After that, define it to middleware on the route.

use Illuminate\Support\Facades\Route;

Route::middleware('throttle:api')->group(function () {
   // Routes
});

All routes with prefix /api will be limited to 60 requests per minute based on user ID or IP address.

  • Custom Error Message

If the user exceeds the request limit, they will receive a 429 Too Many Requests response. We can customize this error message in the /bootstrap/app.php file.

use Illuminate\RateLimiting\TooManyRequestsException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__./../routes/web.php’,
        api: __DIR__./../routes/api.php’,
        apiPrefix: /api’, // set prefix api routes
        then: function () {
            RateLimiter::for(‘api’, function (Request $request) {
                return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
            });
        }
    )
      ->withMiddleware()
      ->withExceptions(function (Exceptions $exceptions) {
		  $exceptions->render(function (TooManyRequestsException $e) {
                    return response()->json([
                            ‘message’ => ‘Rate limit reached. Please wait a moment before trying again.
                    ], 429);
            });
        })
    ->create();

Best Practices for Using Rate Limiting

For effective Rate Limiting implementation, here are some tips to follow:

  • Set request limits appropriate for the type of endpoint. For example, a login endpoint may require stricter limits (e.g., 10 requests per minute) than a public endpoint.
  • Use Redis for Scalability: Redis is an ideal choice for storing rate limiting data due to its speed and efficiency.
  • Ensure that the error messages displayed are easy for users to understand, so they know when they can try again.
  • Use tools such as Laravel Telescope or a log server to monitor request patterns and adjust the rate limiting configuration if necessary.

Read Related Articles Laravel Telescope

Conclusion

Rate Limiting in Laravel 12 is a very powerful feature for maintaining security and performance in the applications we develop. With the throttle middleware and the RateLimiter API, we can easily set request limits as needed, from simple limits to complex custom configurations. This feature is not only easy to implement, but also has a significant impact in protecting applications from cyber attacks and ensuring an optimal user experience.

Thank you.

Teguh Budi Laksono

Teguh Budi Laksono

"not a perfect person, just someone who keeps learning and trying, because he believes that big dreams are born from a long and consistent process."

Tags :

larvel 12

rate limiting laravel 12

rate limiter

understanding rate limiting in laravel 12

how rate limiter work in laravel 12

security

learn coding with nganggurdev

web development

Like the articles on NganggurDev? Let's give support to the writer. Thank you very much!

Want to read more? Click me!