# Rate Limiting

- [Introduction](#introduction)
    - [Cache configuration](#cache-configuration)
- [Throttling routes](#throttling-routes)
    - [How requests are counted](#how-requests-are-counted)
    - [Several limits](#several-limits)
    - [One limit for every client](#one-limit-for-every-client)
    - [Choosing a limit for each request](#choosing-a-limit-for-each-request)
    - [Responses](#responses)
- [Limiting your own code](#limiting-your-own-code)
    - [Counting only some attempts](#counting-only-some-attempts)
    - [Outside a request](#outside-a-request)
- [Testing](#testing)

<a name="introduction"></a>

## Introduction


속도 제한은 일정 시간 안에 동작을 수행할 수 있는 횟수를 제한합니다. 예를 들어 사용자마다 분당 메시지 60개를 게시하게 할 수 있습니다. 한도를 초과하면 Laravel은 이후 요청에 `429 Too Many Requests`를 반환합니다.


속도 제한은 무차별 로그인 시도로부터 애플리케이션을 보호하고, 대량 요청을 보내는 API 클라이언트가 다른 사용자의 응답 속도를 떨어뜨리지 않게 하며, 백그라운드 잡이 호출하는 외부 API의 할당량을 지키는 데도 도움이 됩니다.

<a name="cache-configuration"></a>

### Cache configuration


Laravel은 기본 [cache store](/go/docs/cache)에 속도 제한 시도를 기록합니다. `memory`, `database`, `redis` 모두 지원합니다. `memory`는 프로세스 하나에 한정되고 재시작 시 초기화되므로 로컬 개발과 테스트에만 사용하세요. 운영에서는 배포 후에도 횟수가 유지되고 모든 서버가 공유하도록 `database`나 `redis`를 사용합니다. `discard`는 횟수를 전혀 저장하지 않으므로 `discard` 저장소를 사용하면 아무것도 제한하지 않습니다.

<a name="throttling-routes"></a>

## Throttling routes


라우트 호출 빈도를 제한하려면 라우트 파일에서 `middleware` 패키지의 제한 미들웨어를 추가하세요. 다음 라우트는 각 클라이언트가 분당 최대 메시지 60개를 게시하게 합니다.

```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))
}
```


`middleware.ThrottlePerMinute` 외에 `middleware.ThrottlePerSecond`, `middleware.ThrottlePerHour`, `middleware.ThrottlePerDay`를 사용할 수 있습니다. `middleware.ThrottlePer(100, 5*time.Minute)`처럼 `middleware.ThrottlePer`에 원하는 기간을 지정해도 됩니다. 각 함수는 메서드 체인으로 조정할 수 있는 `middleware.Throttle`을 반환합니다.


한도는 기간이 끝날 때 한꺼번에 초기화되지 않습니다. Laravel은 [token bucket](https://en.wikipedia.org/wiki/Token_bucket) 알고리즘을 사용하므로, 클라이언트는 허용량을 한 번에 소진한 뒤 시간이 흐르면서 일정하게 시도 가능 횟수를 회복합니다. 분당 60회 제한에서 몇 초 안에 60회를 요청하면 약 1초 후 다음 요청을 할 수 있고, 이후에도 매초 한 번씩 할 수 있습니다.


`Throttle`은 일반 [middleware](/go/docs/middleware)이므로 라우트 그룹과 미들웨어 그룹에도 추가할 수 있습니다. 모든 API 라우트에 적용하려면 `bootstrap/app.go`의 `api` 미들웨어 그룹에 추가하세요.

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


같은 한도를 가진 라우트는 클라이언트별 횟수를 공유합니다. 위의 `/messages`에 60번 요청했다면 분당 60회로 제한된 다른 모든 라우트의 요청 가능 횟수도 소진됩니다. 라우트별로 횟수를 관리하려면 버킷 이름과 함께 `WithBucket`을 연결하세요.

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


라우트가 제한이 있는 여러 그룹에 속하면 각각 요청을 셉니다. 모니터링 서비스가 조회하는 상태 검사처럼 특정 라우트에 그룹 제한을 적용하지 않으려면 라우트에서 [`Without`](/go/docs/middleware#excluding-middleware)을 호출하세요.

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

<a name="how-requests-are-counted"></a>

### How requests are counted


제한은 클라이언트마다 별도 횟수를 관리합니다. 로그인한 사용자는 ID로 집계하므로 기기나 IP가 달라도 한도를 공유합니다. 게스트는 [trusted proxies](/go/docs/middleware#trusting-proxies)가 보고한 IP 주소로 집계합니다.


Laravel은 세션이나 API 토큰을 읽는 `apitokens.User` 같은 [request guard](/go/docs/authentication#stateless-authentication)에서 로그인 사용자를 찾습니다. 요청 가드는 `auth.Via` 안에서 로그인시키므로, IP로 대체하지 않고 사용자를 식별할 수 있도록 제한 미들웨어를 `auth.Via` 뒤에 두세요.

```go
import "go.laravel.com/auth"

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

<a name="several-limits"></a>

### Several limits


기간 하나만으로 부족할 때도 있습니다. 예를 들어 내보내기는 분당 10번의 집중 호출을 허용하면서 하루 100번으로 제한할 수 있습니다. 추가 `rate.Limit` 값을 `WithLimits`로 연결하세요. 모든 한도 안에 있을 때만 핸들러에 도달합니다.

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

<a name="one-limit-for-every-client"></a>

### One limit for every client


전체 트래픽의 분당 가입 수처럼 사용자별이 아닌 애플리케이션 전체를 보호하는 한도도 있습니다. `Globally`를 연결해 모든 클라이언트가 한 횟수를 공유하게 하고, 다른 전역 제한과 충돌하지 않도록 `WithBucket`으로 버킷 이름을 지정하세요.

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

<a name="choosing-a-limit-for-each-request"></a>

### Choosing a limit for each request


유료 요금제의 더 높은 API 할당량처럼 호출자에 따라 한도가 달라지면, 요청마다 `Throttle`을 만들고 `Handle`을 호출하는 [middleware](/go/docs/middleware#defining-middleware)를 작성하세요.


각 `models.User`가 요금제로 `APIRequestsPerMinute`를 정하는 `models.Team`에 속한다고 가정해 보겠습니다. 다음 미들웨어는 `WithKey`로 로그인한 사용자의 팀원 모두가 횟수를 공유하게 하고, 게스트에는 IP별로 더 낮은 한도를 적용합니다.

```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)
}
```


`WithBucket`은 집계할 기능이나 라우트 그룹의 이름을 정하고, `WithKey`는 로그인 사용자나 IP 대신 누구의 요청을 집계할지 정하며, `Globally`는 모든 클라이언트가 횟수를 공유하게 합니다. `WithBucket`과 `WithKey`를 함께 사용하면 같은 키에 대해 기능별로 따로 셀 수 있습니다. 버킷이 있는 제한은 한도 값을 제외하고 횟수의 이름을 정하므로, 팀의 요금제 한도가 바뀌어도 사용량이 이어집니다.


그다음 `routes/web.go`의 라우트나 그룹에 `teams.ThrottleAPI`를 추가하세요.

```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)
		})
}
```

<a name="responses"></a>

### Responses


Laravel은 제한된 라우트의 모든 응답에 헤더 두 개를 추가해 한도와 남은 시도 횟수를 알려 줍니다.

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


한도를 초과한 요청은 핸들러에 도달하지 않습니다. Laravel은 `429 Too Many Requests`와 함께 다시 시도하기까지 기다릴 초를 나타내는 `Retry-After` 헤더를 반환합니다.


`429` 응답은 `*rate.TooManyAttemptsError` [error](/go/docs/errors)에서 발생하므로, Laravel은 JSON을 기대하는 요청에는 JSON을, 나머지는 오류 페이지를 렌더링합니다. 남은 대기 시간을 보여 주는 Inertia 페이지 등 사용자 지정 응답은 `bootstrap/app.go`의 `Errors` 옵션에 있는 `Render` 함수에서 오류를 확인해 처리하세요. 이 응답에도 속도 제한 헤더가 추가됩니다.

```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)
	},
},
```

<a name="limiting-your-own-code"></a>

## Limiting your own code


모든 제한이 라우트 전체에 적용되는 것은 아닙니다. 더 큰 핸들러 안에서 메시지 전송을 사용자당 분당 5개로 제한하거나, 백그라운드 잡의 외부 API 호출을 제한할 수 있습니다. 이런 경우 `rate` 패키지 함수를 직접 호출하세요. 각 함수는 첫 인수로 컨텍스트(핸들러에서는 요청), 다음으로 `messages:` 뒤에 사용자 ID를 붙인 것처럼 제한 대상을 나타내는 키 문자열을 받습니다.


`rate.Attempt`는 시도를 기록하고 한도 안인지 확인합니다. 허용되면 남은 `rate.Quota`, 제한되면 `*rate.TooManyAttemptsError`를 반환합니다. 핸들러에서 오류를 `web.Fail`에 전달하면 `Throttle`과 같은 `429` 응답이 됩니다. 로그인 필수 라우트의 다음 핸들러는 사용자마다 분당 메시지 5개를 허용합니다.

```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()
}
```


라우트 미들웨어의 `WithLimits`처럼 한 동작에 여러 기간을 적용하려면 첫 한도 뒤에 나머지를 전달하세요. 모든 한도 안일 때만 허용됩니다. 키는 기간별로 횟수를 보관하므로 각 한도에 서로 다른 기간을 지정하세요.

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

<a name="counting-only-some-attempts"></a>

### Counting only some attempts


실패한 시도만 집계해야 할 때도 있습니다. 로그인 폼에서는 성공을 세지 않고 잘못된 비밀번호의 반복 시도를 제한하고 싶을 수 있습니다. `rate.Check`로 집계 없이 남은 용량을 확인하고, 실패할 때만 `rate.Hit`을 호출하며, 성공 시 `rate.Clear`로 초기화하세요.


다음 로그인 핸들러는 이메일 주소와 IP 주소별로 분당 실패 5회를 허용하고, 로그인에 성공하면 횟수를 초기화합니다.

```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")
}
```


폼에서 `429` 페이지를 표시하면 로그인 페이지가 대체되어 입력값을 잃습니다. 따라서 핸들러는 오류의 `On` 메서드를 호출해 `email` 필드의 유효성 검증 오류로 바꿉니다. Laravel은 입력값과 함께 폼으로 돌려보내고, `:seconds`를 초 단위로 올림한 대기 시간으로 바꾼 메시지를 표시합니다.

<a name="outside-a-request"></a>

### Outside a request


[queued job](/go/docs/queues)의 `Handle`에서 `*rate.TooManyAttemptsError`를 반환하면 실패 처리 대신 한도가 허용할 때까지 잡을 큐로 돌려보냅니다. 다음 잡은 워커 수에 관계없이 메일 프로바이더의 초당 14회 전송 한도를 지킵니다.

```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
}
```


속도 제한된 잡은 실행 전 여러 번 큐로 돌아갈 수 있으므로, 고정 시도 횟수 대신 `RetryFor`를 지정하세요. 다음 허용 시점이 잡의 `RetryFor`를 넘으면 워커는 기다리게 하지 않고 즉시 `*rate.TooManyAttemptsError`로 실패 처리합니다. 큐 복귀는 허용하면서 실제 오류 수를 제한하려면 [limiting errors](/go/docs/queues#limiting-errors)처럼 `MaxErrors`를 설정하세요.


한도에 걸렸을 때 뉴스레터를 버리는 등의 처리가 필요하면 오류를 반환하지 말고 `errors.AsType`으로 확인하세요. `nil`을 반환하면 아무것도 보내지 않고 잡을 완료합니다.

```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...
```

<a name="testing"></a>

## Testing


각 테스트는 빈 `memory` 캐시로 자체 애플리케이션을 구성하므로 속도 제한 횟수가 테스트 사이에 섞이지 않습니다. 시간 경과에 따른 회복을 검증하려면 실제로 기다리지 말고 [travel forward in time](/go/docs/testing#time-travel)으로 시간을 이동하세요.

```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()
}
```


테스트 요청은 기본적으로 `192.0.2.1`에서 옵니다. 여러 게스트는 `WithIP`, 사용자별 제한은 `ActingAs`로 테스트하세요.

```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()
```