1. Overview of Access frequency limits
Frequency limits are often used in APIs to limit the frequency of requests by independent requesters to specific APIs. For example, if the set frequency is limited to 1000 times per minute, if the limit is exceeded within a minute, then the server returns 429:too many attempts. Response.
Typically, a well-coded, frequency-constrained application will also 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 in a given time, x-ratelimit-remaining refers to the number of requests remaining within a specified period of time, retry-after refers to the amount of time to wait (s) from the next retry request.
Note: Each API chooses one of its own frequency limit time spans, GitHub chooses 1 hours, Twitter chooses 15 minutes, and Laravel middleware chooses 1 minutes.
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 use 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, throttle the default limit of 60 attempts per minute and access is forbidden after 60 visits 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, you will see the response header as follows:
The response means:
- Request succeeded (status code is 200)
- Access only 60 times per minute
- Access 57 times during this time period
If the number of visits exceeds 60, the response header is as follows:
At the same time, the response content text is: Too many attempts.
If you retry after 44s, the page resumes normal access.
3. Custom Throttle Middleware
Let's do a little customization, and now we want to limit access 5 times per minute:
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 reaching the specified limit, you can customize this:
Route::group ([' prefix ' = ' API ', ' middleware ' = ' throttle:5,10 '],function () { route::get (' users ', function () { return \app\user::all (); });});