tfarzin's avatar

Rate limiter is not working (at least in test)

I've defined a rate limiter to throttle the number of requests a user can send each time and now I'm trying to test it but it's not working:

my routes/api.php:

Route::middleware(['throttle:limiter'])->group(function () {
    Route::post('/audio', function () {
        return response()->json(['Done'], 200);
    });
}); 

my rate limiter (defined in configureRateLimiting function in RouteServiceProvider):

RateLimiter::for('limiter', function (Request $request) {
    return Limit::perMinute(5)->by(optional($request->user())->id ?: $request->ip())
        ->response(function () {
            return response()->json(['error'], 401);
        });
});

my test:

/**
* A basic unit test example.
* @dataProvider counterProver
* @return void
*/
public function testExample($counter)
{
    $response = $this->postJson('api/audio');
    $response->assertStatus(['Done'])->assertJson(200);
}

public function counterProver()
{
    return [
        '1' => [1],
        '2' => [2],
        '3' => [3],
        '4' => [4],
        '5' => [5],
        '6' => [6],
        '7' => [7],
        '8' => [8],
        '9' => [9],
    ];
}
0 likes
1 reply
cfsalina's avatar

@tfarzin, just a simple suggestion: have you ever tried to change the limiter word for api inside your RateLimiter?

I think the final solution also depends on the framework that you have installed. In my case, I'm using Laravel 9 with jetstream, and just for coincidence, it came already with a RateLimiter for api in the RouteServiceProvider:

    RateLimiter::for('api', function (Request $request) {
      return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

Please or to participate in this conversation.