Rate Limiting
Introduction
Rate limiting lets you cap how often an action can occur within a given time window. For example, you might allow each user to post 60 messages per minute. Once a user exceeds that limit, Laravel rejects subsequent requests with a 429 Too Many Requests response.
Rate limits also help protect your application from brute-force login attempts, keep high-volume API clients from degrading performance for other users, and keep background jobs within third-party API quotas.
Cache configuration
Laravel tracks rate limit attempts in your default cache store. The memory, database, and Redis stores all support rate limiting. Because the memory store is local to a single process and resets on restart, use it only for local development and tests. In production, use the database or Redis store so rate limit counters persist across deploys and are shared across all application servers.
Throttling routes
To limit how often clients can access a route, attach the Throttle middleware in your route file. For example, this route allows up to 60 messages per minute from each client:
1use laravel::http::middleware::Throttle;23pub fn routes(route: &mut Router) {4 route5 .post("/messages", messages::store)6 .middleware(Throttle::per_minute(60));7}1use laravel::http::middleware::Throttle;23pub fn routes(route: &mut Router) {4 route5 .post("/messages", messages::store)6 .middleware(Throttle::per_minute(60));7}
Alongside per_minute, Throttle offers per_second, per_hour, per_day, and per with a custom span such as Throttle::per(100, 5.minutes()). You can also construct a Throttle from a Limit with Throttle::new(limit).
Limits do not reset all at once at the end of a window. Instead, Laravel uses a token bucket algorithm: a client can burst through its allowance immediately and then regains capacity steadily over time. With a limit of 60 requests per minute, a client that sends 60 requests in a few seconds can make its next request roughly one second later, and one more each second after that.
Because Throttle is standard middleware, you can apply it to route groups or middleware stacks. To rate limit every route in your API, append a throttle to the api middleware group in src/app.rs:
1.with_middleware(|middleware, _| {2 middleware.api(|api| {3 api.append(Throttle::per_minute(60));4 });5})1.with_middleware(|middleware, _| {2 middleware.api(|api| {3 api.append(Throttle::per_minute(60));4 });5})
Routes configured with the same limit share a counter per client. For example, a client that sends 60 requests to /messages above has also exhausted its quota on any other route throttled at per_minute(60). To isolate a route under its own counter, give the throttle a bucket name:
1route2 .post("/uploads", uploads::store)3 .middleware(Throttle::per_minute(60).bucket("uploads"));1route2 .post("/uploads", uploads::store)3 .middleware(Throttle::per_minute(60).bucket("uploads"));
If a route sits inside multiple groups that each define a throttle, every throttle evaluates the request. To exclude a route from an inherited throttle, such as a health check endpoint polled by your monitoring service, use without_middleware:
1route.get("/status", status::show).without_middleware::<Throttle>();1route.get("/status", status::show).without_middleware::<Throttle>();
How requests are counted
Throttles track a separate counter for each client. For authenticated users, Laravel keys the counter by user ID so all of their requests share one limit across devices and IP addresses. For guests, Laravel keys the counter by IP address as resolved by your trusted proxies.
Laravel resolves the authenticated user from the session or from a request guard such as an ApiTokens guard. Because request guards authenticate inside Authenticate::via, attach Throttle after it so the throttle can identify the user rather than falling back to their IP address:
1use laravel::auth::Authenticate;23route4 .get("/api/me", users::me)5 .middleware(Authenticate::via::<ApiTokens>())6 .middleware(Throttle::per_minute(60));1use laravel::auth::Authenticate;23route4 .get("/api/me", users::me)5 .middleware(Authenticate::via::<ApiTokens>())6 .middleware(Throttle::per_minute(60));
Several limits
Sometimes a single window isn't enough. For example, an export route might permit bursts of 10 exports per minute while capping total usage at 100 per day. Chain additional limits with and; a request is allowed only when it satisfies every limit:
1use laravel::http::middleware::Throttle;2use laravel::rate_limit::Limit;34route5 .prefix("/exports")6 .middleware(Throttle::per_minute(10).and(Limit::per_day(100)))7 .group(|route| {8 // ...9 });1use laravel::http::middleware::Throttle;2use laravel::rate_limit::Limit;34route5 .prefix("/exports")6 .middleware(Throttle::per_minute(10).and(Limit::per_day(100)))7 .group(|route| {8 // ...9 });
One limit for every client
Some limits protect your application globally rather than per user, such as capping total sign-ups per minute across all traffic. Call global to share one counter across every client, and assign a bucket name so it doesn't collide with other global throttles:
1route2 .post("/signups", signups::store)3 .middleware(Throttle::per_minute(1_000).bucket("signups").global());1route2 .post("/signups", signups::store)3 .middleware(Throttle::per_minute(1_000).bucket("signups").global());
Choosing a limit for each request
When the appropriate limit depends on the caller, such as offering higher API quotas on paid plans, write a #[middleware] function that constructs a Throttle dynamically and delegates to its handle method.
For example, suppose each User is a member of a Team whose plan sets api_requests_per_minute. This middleware calls by to share a per-team limit across all members of a signed-in user's team, and falls back to a lower per-IP limit for guests:
1use laravel::auth::Auth;2use laravel::http::middleware::Throttle;3use laravel::http::{Middleware, Next, middleware};4use laravel::prelude::*;56use crate::models::{Team, User};78#[middleware]9pub async fn throttle_api(10 auth: Auth<User>,11 request: Request,12 next: Next,13) -> laravel::Result<Response> {14 match auth.user().await? {15 Some(user) => {16 let team = Team::find_or_fail(user.team_id).await?;1718 Throttle::per_minute(team.api_requests_per_minute)19 .by(format!("team:{}", team.id))20 .handle(request, next)21 .await22 }23 None => {24 Throttle::per_minute(10)25 .handle(request, next)26 .await27 }28 }29}1use laravel::auth::Auth;2use laravel::http::middleware::Throttle;3use laravel::http::{Middleware, Next, middleware};4use laravel::prelude::*;56use crate::models::{Team, User};78#[middleware]9pub async fn throttle_api(10 auth: Auth<User>,11 request: Request,12 next: Next,13) -> laravel::Result<Response> {14 match auth.user().await? {15 Some(user) => {16 let team = Team::find_or_fail(user.team_id).await?;1718 Throttle::per_minute(team.api_requests_per_minute)19 .by(format!("team:{}", team.id))20 .handle(request, next)21 .await22 }23 None => {24 Throttle::per_minute(10)25 .handle(request, next)26 .await27 }28 }29}
Whereas bucket names the feature or group of routes being counted, by chooses who the counter tracks in place of the authenticated user or IP address, and global shares one counter across all clients. You may combine bucket and by to keep separate counters per feature for the same key, or to carry over a team's usage when their plan limit changes.
Then attach throttle_api to your routes or route groups:
1use laravel::routing::Router;23use crate::http::middleware::throttle_api;4use crate::http::handlers::projects;56pub fn routes(route: &mut Router) {7 route8 .prefix("/api")9 .middleware(throttle_api)10 .group(|route| {11 route.get("/projects", projects::index);12 route.post("/projects", projects::store);13 });14}1use laravel::routing::Router;23use crate::http::middleware::throttle_api;4use crate::http::handlers::projects;56pub fn routes(route: &mut Router) {7 route8 .prefix("/api")9 .middleware(throttle_api)10 .group(|route| {11 route.get("/projects", projects::index);12 route.post("/projects", projects::store);13 });14}
Responses
Laravel includes two headers on every response from a throttled route indicating the configured limit and remaining attempts:
1X-RateLimit-Limit: 602X-RateLimit-Remaining: 421X-RateLimit-Limit: 602X-RateLimit-Remaining: 42
Requests that exceed the limit never reach your handler. Instead, Laravel returns a 429 Too Many Requests response with a Retry-After header indicating how many seconds the client should wait before retrying.
Because the 429 response is produced from a TooManyAttempts error, Laravel renders JSON for API requests and an error page for browser requests. To render a custom response, such as an Inertia page showing the remaining wait time, register a renderer for TooManyAttempts in src/app.rs. Laravel still attaches the rate limit headers automatically:
1use laravel::inertia::props;2use laravel::rate_limit::TooManyAttempts;34.with_errors(|errors, _| {5 errors.render(|error: &TooManyAttempts, request, status| {6 let seconds = error.retry_after().as_secs().max(1);78 Some(9 request10 .inertia()?11 .render("Errors/TooManyAttempts", props! { seconds => seconds })12 .with_status(status),13 )14 });15})1use laravel::inertia::props;2use laravel::rate_limit::TooManyAttempts;34.with_errors(|errors, _| {5 errors.render(|error: &TooManyAttempts, request, status| {6 let seconds = error.retry_after().as_secs().max(1);78 Some(9 request10 .inertia()?11 .render("Errors/TooManyAttempts", props! { seconds => seconds })12 .with_status(status),13 )14 });15})
Limiting your own code
Not every rate limit belongs on an entire route. You might limit a user to sending 5 messages per minute inside a broader handler, or throttle calls to a third-party API from a background job. For these cases, call the functions in laravel::rate_limit directly. Each function accepts a key string identifying what you are limiting, such as messages: followed by the user's ID. Because each key tracks one counter, use distinct keys if you want to enforce multiple windows against the same action.
attempt records an attempt and checks whether it falls within the limit. It returns a nested result: the outer Result reports cache errors, while the inner Result returns Ok(Quota) when allowed or Err(TooManyAttempts) when throttled. In a handler, ?? unwraps both so a throttled call produces the same 429 response as Throttle:
1use laravel::prelude::*;2use laravel::rate_limit::{self, Limit};34pub async fn store(user: Authenticated<User>) -> laravel::Result<Redirect> {5 rate_limit::attempt(&format!("messages:{}", user.id), Limit::per_minute(5)).await??;67 // Send the message...89 Ok(Redirect::back())10}1use laravel::prelude::*;2use laravel::rate_limit::{self, Limit};34pub async fn store(user: Authenticated<User>) -> laravel::Result<Redirect> {5 rate_limit::attempt(&format!("messages:{}", user.id), Limit::per_minute(5)).await??;67 // Send the message...89 Ok(Redirect::back())10}
Counting only some attempts
Sometimes only failed attempts should count against a limit. On a login form, for example, you want to throttle repeated wrong passwords without counting successful logins. Call check to verify remaining capacity without incrementing the counter, call hit only when an attempt fails, and call clear to reset the counter on success.
This login handler allows 5 failed attempts per minute per email address and IP address, clearing the counter once the user signs in:
1use laravel::auth::Auth;2use laravel::hash::Password;3use laravel::prelude::*;4use laravel::rate_limit::{self, Limit};5use laravel::validation::ValidRequest;67#[laravel::input]8#[validate(anyone)]9pub struct Login {10 #[validate(required, email)]11 email: String,12 #[validate(required)]13 password: Password,14}1516pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> laravel::Result<Redirect> {17 let limit = Limit::per_minute(5);1819 let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());2021 rate_limit::check(&key, limit).await??;2223 if let Err(error) = auth.attempt(&login.email, &login.password).await {24 rate_limit::hit(&key, limit).await?;25 return Err(error);26 }2728 rate_limit::clear(&key).await?;2930 Ok(Redirect::intended(dashboard::show, ()))31}1use laravel::auth::Auth;2use laravel::hash::Password;3use laravel::prelude::*;4use laravel::rate_limit::{self, Limit};5use laravel::validation::ValidRequest;67#[laravel::input]8#[validate(anyone)]9pub struct Login {10 #[validate(required, email)]11 email: String,12 #[validate(required)]13 password: Password,14}1516pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> laravel::Result<Redirect> {17 let limit = Limit::per_minute(5);1819 let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());2021 rate_limit::check(&key, limit).await??;2223 if let Err(error) = auth.attempt(&login.email, &login.password).await {24 rate_limit::hit(&key, limit).await?;25 return Err(error);26 }2728 rate_limit::clear(&key).await?;2930 Ok(Redirect::intended(dashboard::show, ()))31}
The handler extracts ValidRequest instead of Valid so it has access to both the validated Login fields and the client's IP address on the underlying request.
Outside a request
Inside a queued job, propagating TooManyAttempts with ?? automatically releases the job back onto the queue until the rate limit allows it to run instead of failing the job. For example, this job stays within a mail provider's limit of 14 sends per second:
1use laravel::prelude::*;2use laravel::queue::{Queueable, job};3use laravel::rate_limit::{self, Limit};45#[derive(Queueable)]6pub struct SendNewsletter {7 pub user_id: i64,8}910#[job(retry_for = 1.hours())]11impl SendNewsletter {12 async fn handle(self) -> laravel::Result<()> {13 rate_limit::attempt("newsletter", Limit::per_second(14)).await??;1415 // Send the newsletter...1617 Ok(())18 }19}1use laravel::prelude::*;2use laravel::queue::{Queueable, job};3use laravel::rate_limit::{self, Limit};45#[derive(Queueable)]6pub struct SendNewsletter {7 pub user_id: i64,8}910#[job(retry_for = 1.hours())]11impl SendNewsletter {12 async fn handle(self) -> laravel::Result<()> {13 rate_limit::attempt("newsletter", Limit::per_second(14)).await??;1415 // Send the newsletter...1617 Ok(())18 }19}
Because a rate-limited job may be released many times before running, configure retry_for rather than a fixed tries count. If the next available slot falls past the job's retry_for window, Laravel fails the job immediately with TooManyAttempts rather than letting it wait. To also cap genuine failures while allowing releases, configure max_errors as described in limiting errors.
If you want custom behavior when a job hits a rate limit, such as deleting it, match on the inner result instead of using ??:
1use laravel::queue::Attempt;23async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {4 match rate_limit::attempt("newsletter", Limit::per_second(14)).await? {5 Ok(_) => {6 // Send the newsletter...7 }8 Err(_) => attempt.delete(),9 }1011 Ok(())12}1use laravel::queue::Attempt;23async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {4 match rate_limit::attempt("newsletter", Limit::per_second(14)).await? {5 Ok(_) => {6 // Send the newsletter...7 }8 Err(_) => attempt.delete(),9 }1011 Ok(())12}
Testing
Each test runs with an isolated application and in-memory cache, so rate limit counters never leak between tests. To verify that limits recover as time passes, travel forward in time instead of sleeping:
1use laravel::rate_limit::TooManyAttempts;2use laravel::testing::prelude::*;34#[laravel::test]5async fn messages_are_throttled(app: Application) {6 for _ in 0..60 {7 app.post("/messages").await.assert_ok();8 }910 app.post("/messages")11 .await12 .assert_status(429)13 .assert_header("x-ratelimit-remaining", "0")14 .assert_error::<TooManyAttempts>();1516 app.travel(2.minutes());1718 app.post("/messages").await.assert_ok();19}1use laravel::rate_limit::TooManyAttempts;2use laravel::testing::prelude::*;34#[laravel::test]5async fn messages_are_throttled(app: Application) {6 for _ in 0..60 {7 app.post("/messages").await.assert_ok();8 }910 app.post("/messages")11 .await12 .assert_status(429)13 .assert_header("x-ratelimit-remaining", "0")14 .assert_error::<TooManyAttempts>();1516 app.travel(2.minutes());1718 app.post("/messages").await.assert_ok();19}
Test requests originate from 127.0.0.1 by default. Use with_ip to simulate multiple guest clients, or acting_as to test per-user limits:
1app.post("/messages").with_ip([203, 0, 113, 7]).await.assert_ok();23app.post("/messages").acting_as(&user).await.assert_ok();1app.post("/messages").with_ip([203, 0, 113, 7]).await.assert_ok();23app.post("/messages").acting_as(&user).await.assert_ok();