1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで 429 Too Many Requests が出たときの備忘録 🗒 + Kernel.php 深掘り

Last updated at Posted at 2025-07-14

0. はじめに

  • 想定読者

    • AWS/ECS 上の Laravel 本番で突然 429 が出て焦った人
    • Kernel.php が何をしているのかイマイチ掴めていない人
  • この記事でわかること

    1. ルートに届く前にリクエストが辿る “Laravel Kernel → ミドルウェア → ルーティング” の全体像
    2. ThrottleRequests ミドルウェアが 429 を返す条件
    3. AWS・外部 API 側の 429 との切り分けポイント

参考にした公開記事: 「Laravel api Throttle機能調べてみた」([Qiita][1])


1. リクエストのライフサイクルをざっくり図解

ポイント

  • Kernel が全 HTTP リクエストの司令塔
  • Kernel::$middlewareGroups['api']throttle:xxx があれば 必ず Rate Limiter が走る
  • 429 は Controller 以前 に止めるのでアプリのログに何も残らないことが多い

2. Kernel.php ― 何をしている?

2.1 ファイルの場所

app/Http/Kernel.php

2.2 3つの責務

セクション 役割 よく触るポイント
$middleware グローバル。全リクエストに適用 例)TrimStrings
$middlewareGroups ルートグループ毎 ( web, api 等) api に throttle を付ける
$routeMiddleware 名前付きミドルウェアの辞書 例)'throttle' => ThrottleRequests::class
// 抜粋
protected $middlewareGroups = [
    'api' => [
        'throttle:120,1',   // ← 1分120回まで
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

3. ThrottleRequests が 429 を返す仕組み

3.1 ざっくりフロー

3.2 設定方法(3パターン)

指定例 (Kernel か Route) 意味
throttle:60,1 60 回 / 1分(IP or ユーザID毎)
throttle:api RouteServiceProvider::configureRateLimiting() で定義した 命名リミッタ を使う
throttle:uploads,6,1 カスタムリミッタuploads に 6 回/分上限を設定しておく)

3.3 返ってくるヘッダ

ヘッダ名 意味
X-RateLimit-Limit 120 許可回数
X-RateLimit-Remaining 0 残り回数
Retry-After 23 次に試せるまでの秒数

4. 外部で 429 が返るケースとの切り分け

発生箇所 原因 どこを見る?
Laravel ThrottleRequests の上限超過 自分の API ログ, ヘッダ
nginx / ALB / WAF limit_req / WAF rate-based rule nginx.conf or AWS WAF 設定
外部 API (Firebase / LINE etc.) サービス提供側 Rate Limit レスポンスボディ or ドキュメント

まずは レスポンスヘッダ を確認して Server: nginxServer: cloudfront か、
そしてボディに "error_description": "xxx" があるかで切り分けると早い。
ThrottleRequestsの上限はルートグループ毎のリクエスト数
※ただ、ほとんどの場合はlravelのThrottleRequests の上限超過。


5. 429 が出た時のチェックリスト

  1. どのサーバーが返した 429?

    • AWS ALB ログ / nginx アクセスログの status=429 を grep
  2. ヘッダの Retry-After を見る

  3. Kernel の api グループに throttle が何個付いているか 確認

  4. RateLimiter::for()` の設定値 を確認

  5. 外部 API コールなら SDK のリトライ設定 or バックオフ を入れる


6. まとめ

  • Kernel.php = リクエストの交通整理係
  • ThrottleRequests がミドルウェアに入っていれば Controller に届く前 に 429 を返す。
  • 429 が出たら 「どのレイヤで弾かれたか」 を最初に切り分ける(基本はlaravel)。

参考リンク

  • Laravel 公式: Rate Limiting
  • Qiita 先行記事: Laravel api Throttle機能調べてみた([Qiita][1])
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?