Rate Limiting & Throttling in Laravel APIs – Preventing Abuse

Laravel rate limiting protects APIs by restricting request frequency. Define limits per user/IP using RateLimiter, like 60/min for users or 10/min for guests. Customize 429 responses when exceeded. Stack multiple limits (e.g., 500/min global + 3/min per email). Apply via throttle middleware. Use throttleWithRedis for better performance. Prevents abuse, DDoS, and ensures API stability.

Rate Limiting & Throttling in Laravel APIs – Preventing Abuse Image

When building APIs in Laravel, it's crucial to protect your application from abuse, such as brute-force attacks, DDoS attempts, or excessive requests from a single user. Laravel provides a powerful rate limiting (throttling) system to control how often clients can access your routes.

In this post, we’ll explore:
✔ What is Rate Limiting?
✔ Defining Rate Limiters in Laravel
✔ Dynamic Rate Limiting Based on Users or IPs
✔ Applying Multiple Rate Limits
✔ Attaching Rate Limiters to Routes
✔ Using Redis for Better Performance

What is Rate Limiting?

Rate limiting restricts the number of requests a client (user or IP) can make to your API within a given time frame. If a client exceeds the limit, Laravel automatically returns a 429 Too Many Requests response.

Common use cases:

  • Preventing brute-force login attempts
  • Protecting API endpoints from abuse
  • Ensuring fair usage of resources
  • Reducing server load

Defining Rate Limiters in Laravel

Rate limiters are configured in the AppServiceProvider using the RateLimiter facade.

Basic Example: Global Rate Limiting

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000); // 1000 requests per minute
});

Custom Rate Limit Response

You can override the default 429 response:

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000)->response(function (Request $request, array $headers) {
        return response('Too many requests! Try again later.', 429, $headers);
    });
});

Dynamic Rate Limiting Based on Users or IPs

You can apply different limits based on user status (e.g., VIP vs regular users).

Example: Different Limits for Authenticated vs Guest Users

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()  
        ? Limit::perMinute(100)->by($request->user()->id) // 100/min per user
        : Limit::perMinute(10)->by($request->ip()); // 10/min per IP for guests
});

VIP Users with No Rate Limits

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->isVip()
        ? Limit::none() // No rate limit for VIPs
        : Limit::perMinute(100); // 100/min for others
});

Multiple Rate Limits

You can apply multiple limits to a single route. Laravel checks them in order.

Example: Login Throttling

RateLimiter::for('login', function (Request $request) {
    return [
        Limit::perMinute(500), // Global limit (500/min)
        Limit::perMinute(3)->by($request->input('email')), // 3 attempts per email
    ];
});

Different Time-Based Limits

RateLimiter::for('api', function (Request $request) {
    return [
        Limit::perMinute(60)->by('min:' . $request->user()->id), // 60/min
        Limit::perHour(1000)->by('hour:' . $request->user()->id), // 1000/hour
    ];
});

Attaching Rate Limiters to Routes

Apply throttling using the throttle middleware:

Single Route

Route::post('/upload', [UploadController::class, 'store'])
    ->middleware('throttle:uploads');

Route Group

Route::middleware(['throttle:api'])->group(function () {
    Route::get('/posts', [PostController::class, 'index']);
    Route::post('/posts', [PostController::class, 'store']);
});

Using Redis for Better Performance

If your app uses Redis, Laravel can optimize rate limiting by replacing the default throttling system with ThrottleRequestsWithRedis.

Enable it in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->throttleWithRedis(); // Use Redis for throttling
});

Benefits:
✔ Faster rate limit checks
✔ Better scalability for high-traffic APIs
✔ More efficient than file/database-based throttling

Conclusion

Laravel’s rate limiting system is a powerful tool to:
✅ Prevent API abuse
✅ Control traffic fairly
✅ Protect against brute-force attacks
✅ Optimize performance with Redis

By defining custom rate limiters and applying them strategically, you can ensure your API remains stable, secure, and efficient.

🚀 Need more control? Check out Laravel’s official docs for advanced configurations!

Happy Coding! 😊

Do you Like?