Laravel5.2 new feature series-use of the access frequency limit middleware throttle
1. access frequency limit overview
Frequency limit is often used in APIs to limit the frequency of requests from independent requesters to specific APIs. For example, if the frequency limit is set to 1000 times per minute, if the limit is exceeded within one minute, the server will return the 429: Too Many Attempts. response.
Generally, an application with good encoding and frequency restrictions will return three response headers: X-RateLimit-Limit, x-RateLimit-Remaining and Retry-After (if the limit is reached, only the Retry-After header can be obtained ). X-RateLimit-Limit tells us the maximum number of requests allowed within the specified time period. X-RateLimit-Remaining refers to the number of requests Remaining in the specified time period, retry-After refers to the waiting time (s) from the next Retry request ).
Note: Each API will select its own frequency limit time span. GitHub selects 1 hour, Twitter selects 15 minutes, and Laravel middleware selects 1 minute.
2. how to use Laravel's access frequency limit middleware
In the new features of Laravel5.2, you can use a new middleware throttle. let's take a look at the usage of this middleware. First, we define a routing rule as follows:
Route::group(['prefix'=>'api'],function(){ Route::get('users',function(){ return \App\User::all(); });});
Then we add the middleware throttle to it. the throttle is limited to 60 attempts per minute by default, and access is prohibited after the number of visits reaches 60 in one minute:
Route::group(['prefix'=>'api','middleware'=>'throttle'],function(){ Route::get('users',function(){ return \App\User::all(); });});
If you access the api/users route, the response header is shown as follows:
This response means:
- Request successful (status code 200)
- Only 60 accesses per minute
- You can access 57 more times in this period.
If the number of visits exceeds 60, the response header is as follows:
At the same time, the response text is: Too Many Attempts.
If you try again after 44s, the page will resume normal access.
3. Custom throttle middleware
Let's make some customization. now we want to limit the number of visits per minute to 5:
Route::group(['prefix'=>'api','middleware'=>'throttle:5'],function(){ Route::get('users',function(){ return \App\User::all(); });});
If we want to change the wait time after the specified number of times, we can customize it as follows:
Route::group(['prefix'=>'api','middleware'=>'throttle:5,10'],function(){ Route::get('users',function(){ return \App\User::all(); });});