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?

More than 1 year has passed since last update.

Laravel でリクエスト制限(レートリミット)

1
Posted at

SlackのAPIで情報を取得していた。
その時、リクエストの数が多かったのか制限がかかっていたりした。

リファレンスを見ると「1 分間に何回まで?」という制限があったわけだ。

Laravel で実装できるか調べてみた。

基本仕組み

ミドルウェア(@ throttle):

routes/api.php

Route::middleware(['throttle:60,1'])->get('/api/user', function () {
    // 呼ばれたら処理
});
  • throttle:60,1 → 1 分間で最大 60 回まで
  • 超過すると自動で 429 Too Many Requests を返す
  • 全ユーザー一律に制限

RateLimiter ファサード:条件で柔軟に

app/Providers/RouteServiceProvider.php

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

public function boot()
{
    RateLimiter::for('custom', function (Request $request) {
        return $request->user()
            ? Limit::perMinute(100)->by($request->user()->id)
            : Limit::perMinute(20)->by($request->ip());
    });
}

  • Limit::perMinute(100) → 認証ユーザは 100 回/分、それ以外は 20 回/分
  • ユーザーID/IP単位で制限を分けられます 

使う時は:


Route::middleware('throttle:custom')->post('/api/data', [DataController::class, 'store']);

どちらでも利用できるらしい。

  • とにかく制限だけ入れたい → throttle:60,1
  • 認証ユーザーと未認証で制限を分けたい/カスタム応答が欲しい → RateLimiter ファサード使用

まずはミドルウェア方式で試すのが良さそう。

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?