LaravelRate Limit APIMiddleware

Membangun API Rate Limiting di Laravel dengan Redis dan Middleware

Oleh Aditya Nursyahbani20 menit baca39
Bagikan:
Membangun API Rate Limiting di Laravel dengan Redis dan Middleware

Modern web applications often expose APIs to mobile apps, frontend frameworks, third-party integrations, and public services. Without proper rate limiting, your API can become vulnerable to abuse, spam requests, brute-force attacks, or unexpected traffic spikes that degrade server performance.

Laravel provides a flexible rate limiting system out of the box, but many developers only use the default throttle middleware without understanding how to customize it for production-scale applications.

In this tutorial, you will learn how to implement advanced API rate limiting in Laravel using Redis, custom middleware, and user-based throttling strategies. We will also cover how to apply different limits for authenticated users, guests, and sensitive endpoints.

By the end of this guide, you will understand how to:

  • Configure Laravel rate limiting
  • Use Redis for high-performance throttling
  • Create custom throttle middleware
  • Apply dynamic request limits
  • Protect authentication and chatbot endpoints
  • Improve API stability in production

Why Rate Limiting Matters

Without rate limiting, attackers can:

  • Spam your API endpoints
  • Exhaust server resources
  • Trigger expensive database queries
  • Abuse login systems
  • Overload AI or chatbot APIs

Proper throttling helps maintain performance and security.


Step 1: Configure Redis

Install Redis support in Laravel.

bash
composer require predis/predis

Update your .env file:

bash
CACHE_DRIVER=redis QUEUE_CONNECTION=redis SESSION_DRIVER=redis REDIS_CLIENT=predis Step 2: Create API Rate Limiter

Open app/Providers/RouteServiceProvider.php.

php
<?php use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Http\Request; public function boot(): void { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by( $request->user()?->id ?: $request->ip() ); }); }

This configuration allows:

  • 60 requests per minute
  • Separate limits per authenticated user or IP

Step 3: Apply Middleware to Routes

php
<?php Route::middleware('throttle:api')->group(function () { Route::post('/chat/send', [ChatbotController::class, 'sendMessage']); });

Step 4: Custom Rate Limiting for Login

Login endpoints require stricter protection.

php
<?php RateLimiter::for('login', function (Request $request) { return Limit::perMinute(5)->by($request->ip()); });

Apply to route:

php
<?php Route::middleware('throttle:login')->post('/login', function () { // });

Step 5: Dynamic User Limits

Premium users may require higher request limits.

php
<?php RateLimiter::for('chatbot', function (Request $request) { if ($request->user()?->is_premium) { return Limit::perMinute(300); } return Limit::perMinute(50); });

Step 6: Custom Middleware Example

Create middleware:

bash
php artisan make:middleware ApiThrottle

Middleware implementation:

php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\RateLimiter; class ApiThrottle { public function handle($request, Closure $next) { $key = 'api-'.$request->ip(); if (RateLimiter::tooManyAttempts($key, 100)) { return response()->json([ 'message' => 'Too many requests' ], 429); } RateLimiter::hit($key, 60); return $next($request); } }

Step 7: Monitor API Abuse

You can log suspicious activity.

php
<?php Log::warning('Rate limit exceeded', [ 'ip' => $request->ip(), 'endpoint' => $request->path() ]);

This helps identify abusive traffic patterns.

Production Tips

  • Use Redis instead of file cache
  • Add Cloudflare or reverse proxy protection
  • Apply stricter limits to authentication endpoints
  • Monitor traffic spikes
  • Cache expensive responses

Conclusion

Laravel makes it easy to implement scalable API rate limiting using middleware and Redis. Proper throttling protects your infrastructure, improves stability, and ensures fair resource usage across applications.