More and more of my work in Laravel lately has been creating APIs. I have a manual rate limiter class I've been using, but I've had a sense that there's a cleaner way to do it. Unsurprisingly, when Taylor set out to write a rate limiter middleware for Laravel, he did it cleaner and better than I had.

Brief introduction to rate limiting

If you're not familiar with it, rate limiting is a tool—most often used in APIs—that limits the rate at which any individual requester can make requests.

That means, for example, if some bot is hitting a particularly expensive API route a thousand times a minute, your application won't crash, because after the nth try, they will instead get a 429: Too Many Attempts. response back from the server.

Usually a well-written application that implements rate limiting will also pass back three headers that might not be on another application: X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After (you'll only get Retry-After if you've hit the limit). X-RateLimit-Limit tells you the max number of requests you're allowed to make within this application's time period, X-RateLimit-Remaining tells you how many requests you have left within this current time period, and Retry-After tells you how many seconds to wait until you try again. (Retry-After could also be a date instead of a number of seconds).

Note: Each API chooses the time span it's rate limiting for. GitHub is per hour, Twitter is per 15-minute segment. This Laravel middleware is per minute.

How to use Laravel's rate-limiting middleware

So, on to the new feature in Laravel 5.2. There's a new throttle middleware that you can use. Let's take a look at our API group:

Route::group(['prefix' => 'api'], function () {
    Route::get('people', function () {