Rate limiting down to the second

Important for high-traffic applications

Joel Clermont
Joel Clermont
2024-04-17

Rate limiting is something you might not think about until you have a lot of traffic, or you have someone abusing your application.

Thankfully, Laravel allows us to set up rate limits with minimal effort. So we can establish some reasonable limits early on, even before we have a problem.

As traffic grows, you'll often find that you need to get more precise with your rate limit definitions. For example, let's say you want to allow a user to make 120 requests per minute. That seems like a reasonable usage for a normal user.

But how would you feel if they made all 120 requests within a single second? That might start to cause performance issues, or it might be a sign of abuse or account compromise.

Prior to Laravel 11, there was no official way to do rate-limiting with any precision lower than a minute.

There were some creative ways you could achieve it with custom middleware, or you could pull in a third-party package, but I never really liked either of those solutions.

Now though, Laravel 11 gives us a perSecond() method:

RateLimiter::for('api', fn () => [
    Limit::perMinute(120)->by($request->user()->id),
    Limit::perSecond(10)->by($request->user()->id),
]);

Combining these two rate limits, we have our original limit of 120 per second, but now we can also prevent any bursts of more than 10 requests within a single second.

Hope this helps,

Joel

P.S. Would you like help building out your Laravel API? We not only build a functional, efficient API, but we always write a formal API spec and have solid test coverage to make sure there's no drift. Get in touch!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.