Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GimmeMylanta's avatar

Strange behaviour with throttle hits

I am seeing some strange behaviour with my login throttling. The hit counting is not adding up and i cant figure out why. I want the user to have 3 attempts at logging in, after the second attempt i want to return a message to the user saying they have had 2 attempts. But at the moment, i enter the wrong creds twice, it shows the message, but then it allows another 2 attempts ... The code is set to 3 .... I just cant figure it out. any help would be great.

public function login(Request $request)
{
    $key = optional($request->user())->id ?: $request->ip();
    $maxAttempts = 3;

    if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
        return view('login')->with([
            'error' => 'Account locked.',
        ]);
    }

    $credentials = request(['email', 'password']);

    if (! Auth::attempt($credentials)) {
        RateLimiter::hit($key);

        $remaining = RateLimiter::retriesLeft($key, $maxAttempts);

        if ($remaining === 1) {
            return view('login')->with([
                'error' => 'You have had two failed login attempts.',
            ]);
        }

        return view('login')->with([
            'error' => 'Incorrect username/email or password',
        ]);
    } else {

        RateLimiter::clear($key);

        return redirect('/dashboard');
    }
}
0 likes
13 replies
MohamedTammam's avatar

@GimmeMylanta Try to increase the time and check again, if it works with more than one minute, it means you're not checking under one minute.

MohamedTammam's avatar

@GimmeMylanta I believe it works as it should be

  • You set the rate limit to 3
  • The user tries 2 times
  • Message will be displayed with allowed one time left
  • The user tries the third time (reaches the maximum)
  • The user tries the fourth and gets blocked

right?

1 like
GimmeMylanta's avatar

@MohamedTammam ... But if the limiter is set to 3 ... Then it should ban on the 3rd attempt, not the 4th otherwise i would set the limiter to 4

Sinnbeck's avatar

Interesting. Can you add a log to see remaining each time?

Log::info($key. ' - '. $remaining);
GimmeMylanta's avatar

@Sinnbeck I get the following;

[2022-09-29 14:46:19] testing.INFO: 127.0.0.1 - 2  
[2022-09-29 14:46:19] testing.INFO: 127.0.0.1 - 1  
[2022-09-29 14:46:19] testing.INFO: 127.0.0.1 - 0  
GimmeMylanta's avatar

Oh, i see whats going on ... Its counting down to 0 .. I have changed $maxAttempts = 2; and also instead of counting the remaining, i have changed that to $attempts = RateLimiter::attempts($key);

Well that was fun

Please or to participate in this conversation.