philiprehberger/laravel-rate-limiter
Composer 安装命令:
composer require philiprehberger/laravel-rate-limiter
包简介
Advanced rate limiting with sliding window, token bucket, and per-entity controls for Laravel
README 文档
README
Advanced rate limiting with sliding window, token bucket, and per-entity controls for Laravel.
Requirements
- PHP 8.2+
- Laravel 11 or 12
Installation
composer require philiprehberger/laravel-rate-limiter
The service provider is auto-discovered. Optionally publish the config:
php artisan vendor:publish --tag=rate-limiter-config
Usage
Quick Start
use PhilipRehberger\RateLimiter\Facades\RateLimit; // Rate limit by arbitrary key $result = RateLimit::for('global-api') ->allow(1000) ->perHour() ->attempt(); if ($result->denied()) { return response()->json(['message' => 'Slow down'], 429, $result->headers()); }
Handling Rate-Limited Responses
$result = RateLimit::for('api') ->allow(100) ->perMinute() ->attempt(); if ($result->denied()) { $seconds = $result->retryAfter(); // e.g. 23 return response()->json([ 'message' => "Too many requests. Retry in {$seconds} seconds.", 'retry_after' => $seconds, 'remaining' => $result->remainingTokens(), ], 429, $result->headers()); }
Entry Points
// Arbitrary key RateLimit::for('some-key'); // Scoped to an authenticated user RateLimit::forUser($request->user()); // Scoped to an IP address RateLimit::forIp($request->ip());
Configuring the Limit
RateLimit::for('key') ->allow(100) // max attempts per window (must be >= 1) ->perMinute() // window = 60 seconds (per() requires >= 1) ->algorithm('sliding') ->cost(1) // tokens to consume per attempt ->on('export'); // composite key: "key:export"
Algorithms
| Algorithm | String | Best For |
|---|---|---|
| Fixed Window | 'fixed' |
Internal tooling, scenarios where boundary bursts are acceptable |
| Sliding Window | 'sliding' (default) |
Public APIs, auth endpoints, strict burst prevention |
| Token Bucket | 'token_bucket' |
Upload/download throttling, expensive compute endpoints |
Middleware
Apply to routes via the rate-limit alias:
// 100 requests per 60 seconds, sliding window Route::middleware('rate-limit:100,60,sliding')->group(function () { Route::get('/api/posts', [PostController::class, 'index']); });
Configuration
config/rate-limiter.php:
return [ 'default_algorithm' => env('RATE_LIMITER_ALGORITHM', 'sliding'), 'cache_store' => env('RATE_LIMITER_CACHE_STORE', null), 'prefix' => env('RATE_LIMITER_PREFIX', 'rate_limit'), ];
API
RateLimit Facade / Entry Points
| Method | Description |
|---|---|
RateLimit::for(string $key) |
Create a pending limit for an arbitrary key |
RateLimit::forUser(Authenticatable $user) |
Create a pending limit scoped to a user |
RateLimit::forIp(string $ip) |
Create a pending limit scoped to an IP address |
PendingRateLimit (Fluent Builder)
| Method | Description |
|---|---|
->allow(int $limit) |
Set the maximum attempts per window |
->perSecond() |
Set window to 1 second |
->perMinute() |
Set window to 60 seconds |
->perHour() |
Set window to 3,600 seconds |
->perDay() |
Set window to 86,400 seconds |
->per(int $seconds) |
Set a custom window in seconds |
->algorithm(string $algo) |
Set algorithm: 'fixed', 'sliding', or 'token_bucket' |
->cost(int $cost) |
Set token cost per attempt (default: 1) |
->on(string $action) |
Append an action suffix to the key |
->attempt() |
Consume tokens and return a RateLimitResult |
->check() |
Inspect state without consuming tokens |
RateLimitResult
| Property / Method | Type | Description |
|---|---|---|
->allowed() |
bool |
Whether the attempt was allowed |
->denied() |
bool |
Whether the attempt was denied |
->retryAfter() |
?int |
Seconds until next token is available; null if not rate-limited |
->remainingTokens() |
int |
Remaining tokens in the current window (clamped to 0) |
->remaining |
int |
Remaining tokens in current window |
->limit |
int |
Configured limit |
->retryAfter |
int|null |
Seconds until allowed; null if allowed |
->resetAt |
int |
Unix timestamp of next window reset |
->headers() |
array |
Standard HTTP rate limit headers |
Middleware Parameters
| Position | Parameter | Default |
|---|---|---|
| 1 | maxAttempts |
60 |
| 2 | windowSeconds |
60 |
| 3 | algorithm |
config default |
Development
composer install vendor/bin/phpunit vendor/bin/pint --test vendor/bin/phpstan analyse
Support
If you find this project useful:
License
philiprehberger/laravel-rate-limiter 适用场景与选型建议
philiprehberger/laravel-rate-limiter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 52 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「throttle」 「middleware」 「laravel」 「rate-limiting」 「token-bucket」 「sliding-window」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 philiprehberger/laravel-rate-limiter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 philiprehberger/laravel-rate-limiter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 philiprehberger/laravel-rate-limiter 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
A Laravel Pulse card to track users & URL's that are being throttled by your Rate Limiters
hyperf cache counter rate limiter
Slim Framework 3 CSRF protection middleware utilities
Cloudflare Middleware For Guzzle
PSR-15 middleware to handle CSRF-token verification
统计信息
- 总下载量: 52
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 40
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-09