跳至正文

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 their next 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 slowing your application down for other users, and keep background jobs within the quotas of the third-party APIs they call.

Cache configuration ​

Laravel tracks rate limit attempts in your application's 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 when the process restarts, use it only for local development and tests. In production, use the database or redis store, so rate limit counts survive deploys and every application server shares them. The discard store keeps no counts at all, so with the discard store, Laravel throttles nothing.

Throttling routes ​

To limit how often clients can call a route, attach a throttle middleware from the middleware package in your route file. For example, this route allows each client to post up to 60 messages per minute:

go
package routes

import (
	"go.laravel.com/config"
	"go.laravel.com/middleware"
	"go.laravel.com/routing"

	"app/handlers/messages"
)

func API(route *routing.Router, cfg *config.Config) {
	route.Post("/messages", messages.Store).
		Middleware(middleware.ThrottlePerMinute(60))
}

Alongside middleware.ThrottlePerMinute, you may use middleware.ThrottlePerSecond, middleware.ThrottlePerHour, middleware.ThrottlePerDay, or middleware.ThrottlePer with a span of your own, such as middleware.ThrottlePer(100, 5*time.Minute). Each returns a middleware.Throttle value you may refine with chaining methods.

Limits don't reset all at once at the end of a window. Instead, Laravel uses a token bucket algorithm: a client may use its whole allowance in a burst, and then gets attempts back steadily over time. With a limit of 60 requests per minute, a client that sends 60 requests in a few seconds may make its next request about one second later, and one more each second after that.

Because Throttle is ordinary middleware, you may also attach it to route groups and middleware groups. To rate limit every route in your API, append a throttle to the api middleware group in bootstrap/app.go:

go
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.API.Append(middleware.ThrottlePerMinute(60))
},

Routes with the same limit share each client's count. For example, a client that sends 60 requests to /messages above has also used up its requests on every other route throttled at 60 per minute. To give a route a count of its own, chain WithBucket with a bucket name:

go
route.Post("/uploads", uploads.Store).
	Middleware(middleware.ThrottlePerMinute(60).WithBucket("uploads"))

If a route sits inside several groups that each have a throttle, every throttle counts the request. To keep a group's throttle off one route, such as a health check that your monitoring service polls, call Without on the route:

go
route.Get("/status", status.Show).Without(middleware.Throttle{})

How requests are counted ​

A throttle keeps a separate count for each client. For a logged-in user, Laravel counts by the user's ID, so all of the user's requests share one limit across devices and IP addresses. For a guest, Laravel counts by IP address, as your trusted proxies report it.

Laravel finds the logged-in user from the session, or from a request guard such as an apitokens.User guard that reads API tokens. Because a request guard logs the user in inside auth.Via, put the throttle after auth.Via, so the throttle can identify the user rather than falling back to their IP address:

go
import "go.laravel.com/auth"

route.Middleware(auth.Via(apitokens.User), middleware.ThrottlePerMinute(60)).
	Get("/me", users.Me)

Several limits ​

Sometimes a single window isn't enough. For example, an export route might allow bursts of 10 exports per minute while capping total use at 100 per day. Chain WithLimits with the extra rate.Limit values. A request reaches the handler only when it's within every limit:

go
route.Prefix("/exports").
	Middleware(middleware.ThrottlePerMinute(10).WithLimits(rate.PerDay(100))).
	Group(func(route *routing.Router) {
		// ...
	})

One limit for every client ​

Some limits protect your whole application rather than each user, such as a cap on total sign-ups per minute across all of your traffic. Chain Globally to share one count across every client, and give the throttle a bucket name with WithBucket so its count doesn't collide with other global throttles:

go
route.Post("/signups", signups.Store).
	Middleware(middleware.ThrottlePerMinute(1000).WithBucket("signups").Globally())

Choosing a limit for each request ​

When the right limit depends on the caller, such as higher API quotas on paid plans, write a middleware that builds a Throttle for each request and calls its Handle method.

For example, suppose each models.User belongs to a models.Team whose plan sets APIRequestsPerMinute. This middleware chains WithKey to share one count across every member of a logged-in user's team, and gives guests a lower limit, counted by IP address:

go
package teams

import (
	"fmt"

	"go.laravel.com/auth"
	"go.laravel.com/middleware"
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

// ThrottleAPI limits each team's API requests to its plan's limit.
type ThrottleAPI struct{}

func (ThrottleAPI) Handle(r *web.Request, next web.Next) *web.Response {
	if !auth.Check(r) {
		return middleware.ThrottlePerMinute(10).Handle(r, next)
	}

	user := r.User[models.User]()

	team, err := model.Find[models.Team](r, user.TeamID)
	if err != nil {
		return web.Fail(err)
	}

	return middleware.ThrottlePerMinute(team.APIRequestsPerMinute).
		WithKey(fmt.Sprintf("team:%d", team.ID)).
		Handle(r, next)
}

Whereas WithBucket names the feature or group of routes being counted, WithKey chooses whose requests the count tracks, in place of the logged-in user or IP address, and Globally shares one count across all clients. You may combine WithBucket and WithKey to keep separate counts for each feature with the same key. A bucket also carries a team's usage over when their plan's limit changes, because a throttle with a bucket names its count without its limits.

Then attach teams.ThrottleAPI to your routes or route groups in routes/web.go:

go
package routes

import (
	"go.laravel.com/config"
	"go.laravel.com/routing"

	"app/handlers/projects"
	"app/teams"
)

func Web(route *routing.Router, cfg *config.Config) {
	route.Prefix("/api").
		Middleware(teams.ThrottleAPI{}).
		Group(func(route *routing.Router) {
			route.Get("/projects", projects.Index)
			route.Post("/projects", projects.Store)
		})
}

Responses ​

Laravel adds two headers to every response from a throttled route, giving the route's limit and the attempts the client has left:

text
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 42

Requests that exceed the limit never reach your handler. Instead, Laravel responds with 429 Too Many Requests and a Retry-After header, which gives the number of seconds the client should wait before trying again.

Because the 429 response comes from a *rate.TooManyAttemptsError error, Laravel renders JSON for requests that expect JSON and an error page otherwise. To render a response of your own, such as an Inertia page that shows the remaining wait, check for the error in the Render function of the Errors option in bootstrap/app.go. Laravel still adds the rate limit headers to your response:

go
import (
	"errors"
	"math"

	"go.laravel.com/inertia"
	"go.laravel.com/rate"
	"go.laravel.com/web"
)

Errors: web.Errors{
	Render: func(r *web.Request, err error) *web.Response {
		tooMany, ok := errors.AsType[*rate.TooManyAttemptsError](err)
		if !ok || r.ExpectsJSON() {
			return nil
		}

		seconds := max(int(math.Ceil(tooMany.RetryAfter.Seconds())), 1)

		return inertia.Render("Errors/TooManyAttempts", inertia.Props{"seconds": seconds}).
			WithStatus(429)
	},
},

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 the rate package directly. Each function takes a context first, which in a handler is the request, then a key string that names what you're limiting, such as messages: followed by the user's ID.

rate.Attempt records an attempt and checks whether it's within the limit. It returns the rate.Quota that's left when the attempt is allowed, or a *rate.TooManyAttemptsError when it's throttled. In a handler, pass the error to web.Fail, and a throttled call gets the same 429 response that Throttle sends. This handler, on a route that requires a logged-in user, lets each user send 5 messages per minute:

go
package messages

import (
	"fmt"

	"go.laravel.com/rate"
	"go.laravel.com/web"

	"app/models"
)

func Store(r *web.Request) *web.Response {
	user := r.User[models.User]()

	if _, err := rate.Attempt(r, fmt.Sprintf("messages:%d", user.ID), rate.PerMinute(5)); err != nil {
		return web.Fail(err)
	}

	// Send the message...

	return web.Back()
}

To enforce several windows against the same action (like WithLimits on route middleware), pass the extra limits after the first. The attempt is allowed only when it's within every limit. Give each limit a different span, because a key keeps one count for each span:

go
_, err := rate.Attempt(r, fmt.Sprintf("messages:%d", user.ID), rate.PerMinute(5), rate.PerDay(100))

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 rate.Check to verify the remaining capacity without counting an attempt, call rate.Hit only when an attempt fails, and call rate.Clear to reset the count on success.

This login handler allows 5 failed attempts per minute for each email address and IP address, and clears the count once the user logs in:

go
package sessions

import (
	"errors"
	"strings"

	"go.laravel.com/auth"
	"go.laravel.com/rate"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"
)

type Login struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

func (f *Login) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Email, rule.Required, rule.Email),
		rule.Field(&f.Password, rule.Required),
	)
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[Login]()
	if err != nil {
		return web.Fail(err)
	}

	limit := rate.PerMinute(5)

	key := "login:" + strings.ToLower(form.Email) + "|" + r.IP()

	if _, err := rate.Check(r, key, limit); err != nil {
		if tooMany, ok := errors.AsType[*rate.TooManyAttemptsError](err); ok {
			return web.Fail(tooMany.On(
				"email",
				"Too many login attempts. Please try again in :seconds seconds.",
			))
		}

		return web.Fail(err)
	}

	if err := auth.Attempt(r, form.Email, form.Password, false); err != nil {
		if _, failed := errors.AsType[*web.InputError](err); failed {
			if hitErr := rate.Hit(r, key, limit); hitErr != nil {
				return web.Fail(hitErr)
			}
		}

		return web.Fail(err)
	}

	if err := rate.Clear(r, key); err != nil {
		return web.Fail(err)
	}

	return auth.RedirectIntended("/dashboard")
}

On a form, a 429 page would replace the login page, and the user would lose what they typed. So the handler calls the error's On method, which turns it into a validation error on the email field. Laravel sends the user back to the form with their input and shows the message, with :seconds replaced by the wait, rounded up to whole seconds.

Outside a request ​

Inside a queued job, returning a *rate.TooManyAttemptsError from Handle puts the job back on 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, however many workers run it:

go
package jobs

import (
	"context"
	"time"

	"go.laravel.com/queue"
	"go.laravel.com/rate"
)

type SendNewsletter struct {
	UserID int64
}

func (SendNewsletter) JobOptions() queue.Options {
	return queue.Options{RetryFor: time.Hour}
}

func (j SendNewsletter) Handle(ctx context.Context) error {
	if _, err := rate.Attempt(ctx, "newsletter", rate.PerSecond(14)); err != nil {
		return err
	}

	// Send the newsletter...

	return nil
}

Because a rate-limited job may be released many times before it runs, give the job a RetryFor rather than a fixed number of tries. If the next available attempt falls past the job's RetryFor, the worker fails the job right away with the *rate.TooManyAttemptsError rather than letting it wait. To also cap genuine failures while allowing releases, set MaxErrors as described in limiting errors.

If you want custom behavior when a job hits a rate limit, such as dropping the newsletter, check for the error with errors.AsType instead of returning it. Returning nil finishes the job without sending anything:

go
_, err := rate.Attempt(ctx, "newsletter", rate.PerSecond(14))
if _, ok := errors.AsType[*rate.TooManyAttemptsError](err); ok {
	return nil
}
if err != nil {
	return err
}

// Send the newsletter...

Testing ​

Each test builds its own application with an empty memory cache, so rate limit counts never leak between tests. To verify that limits recover as time passes, travel forward in time instead of sleeping:

go
package feature_test

import (
	"testing"
	"time"

	"app/tests"
)

func TestMessagesAreThrottled(t *testing.T) {
	client := tests.New(t)

	for range 60 {
		client.PostJSON("/api/messages", map[string]any{"body": "Hello"}).AssertOK()
	}

	client.PostJSON("/api/messages", map[string]any{"body": "Hello"}).
		AssertTooManyRequests().
		AssertHeader("X-RateLimit-Remaining", "0")

	client.Travel(2 * time.Minute)

	client.PostJSON("/api/messages", map[string]any{"body": "Hello"}).AssertOK()
}

Test requests come from 192.0.2.1 by default. Use WithIP to simulate several guest clients, or ActingAs to test per-user limits:

go
client.WithIP("203.0.113.7").PostJSON("/api/messages", map[string]any{"body": "Hello"}).AssertOK()

client.ActingAs(&user).PostJSON("/api/messages", map[string]any{"body": "Hello"}).AssertOK()