A simple example of rate limiting API requests with Redis and Laravel

Hiram
Hiram
Aug 24, 2018 · 3 min read
php artisan make:command ResetQuotaForFreeUsers
class ResetQuotaForFreeUsers extends Command
{
/**
* The name and signature of the console command.
*
*
@var string
*/
protected $signature = 'reset:quotas';

/**
* The console command description.
*
*
@var string
*/
protected $description = 'This command resets the quota to free users.';

/**
* Create a new command instance.
*
*
@return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
*
@return mixed
*/
public function handle()
{
for ($i = 1; $i <= 500; $i++) {
Redis::command("hset", ["RateLimits", "User:{$i}:limit", 100]);
}
}
}
php artisan reset:quotas
php artisan make:middleware CheckRateLimit
protected $routeMiddleware = [
...
'rate.limit' => \App\Http\Middleware\CheckRateLimit::class,
];
class CheckRateLimit
{
/**
* Handle an incoming request.
*
*
@param \Illuminate\Http\Request $request
*
@param \Closure $next
*
@return mixed
*/
public function handle($request, Closure $next)
{
$id = 50;

if (Redis::command('hincrby', ['RateLimits', "User:{$id}:limit", -1]) >= 0) {
return $next($request);
} else {
return response()->json(['status' => 0, 'message' => 'You already reached your requests limit.']);
}
}
}
Route::get('/users', function () {
$users = factory('App\User', 5)->make();
return response()->json(['status' => 1, 'users' => $users], 200);
})->middleware('rate.limit');
{
"status": 1,
"users": [
{
"name": "Brett Torphy",
"email": "xander.konopelski@example.net"
},
{
"name": "Catherine Mraz",
"email": "rprice@example.com"
},
{
"name": "Madalyn Williamson",
"email": "ydubuque@example.net"
},
{
"name": "Dr. Hillard Barton",
"email": "schmeler.norma@example.com"
},
{
"name": "Zola Turner",
"email": "kristopher.jacobson@example.net"
}
]
}
{
“status”: 0,
“message”: “You already reached your requests limit.”
}
Hiram

Written by

Hiram

Is a passionate developer eager for learning and sharing.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade