PHPackages                             grazulex/laravel-api-throttle-smart - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. grazulex/laravel-api-throttle-smart

ActiveLibrary[API Development](/categories/api)

grazulex/laravel-api-throttle-smart
===================================

Intelligent, plan-aware rate limiting for Laravel APIs - Built for SaaS, multi-tenant, and enterprise applications

v0.1.0(3mo ago)311MITPHPPHP ^8.3CI passing

Since Feb 4Pushed 3mo agoCompare

[ Source](https://github.com/Grazulex/laravel-api-throttle-smart)[ Packagist](https://packagist.org/packages/grazulex/laravel-api-throttle-smart)[ Docs](https://github.com/grazulex/laravel-api-throttle-smart)[ GitHub Sponsors](https://github.com/Grazulex)[ RSS](/packages/grazulex-laravel-api-throttle-smart/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (13)Versions (2)Used By (0)

Laravel API Throttle Smart
==========================

[](#laravel-api-throttle-smart)

> Intelligent, plan-aware rate limiting for Laravel APIs - Multi-algorithm, multi-tenant, quota management

[![Latest Version on Packagist](https://camo.githubusercontent.com/1ac1cb0b05360874523b019fe6e5bda3879cd8600e74ff09430370e880ed6bf2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6772617a756c65782f6c61726176656c2d6170692d7468726f74746c652d736d6172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/grazulex/laravel-api-throttle-smart)[![Tests](https://camo.githubusercontent.com/d429507f19592cb724369ef0833092a253a700268297984f7c3005ffb9848097/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6772617a756c65782f6c61726176656c2d6170692d7468726f74746c652d736d6172742f74657374732e796d6c3f6c6162656c3d7465737473)](https://github.com/grazulex/laravel-api-throttle-smart/actions)[![Total Downloads](https://camo.githubusercontent.com/a3bfcf113b00fa510ed89b5c55ad60ec46c74ba3a1a30f58102cf0aed7120c61/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6772617a756c65782f6c61726176656c2d6170692d7468726f74746c652d736d6172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/grazulex/laravel-api-throttle-smart)[![License](https://camo.githubusercontent.com/10dd55bb6eb02b6d44033c9fc99be8cbd7c9b2ee4cdf41fd4c270c7d08e24e22/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6772617a756c65782f6c61726176656c2d6170692d7468726f74746c652d736d6172742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/grazulex/laravel-api-throttle-smart)

---

Features
--------

[](#features)

- **Plan-Based Limits** - Define different rate limits per subscription plan (Free, Pro, Enterprise)
- **Multiple Algorithms** - Fixed Window, Sliding Window, or Token Bucket
- **Multi-Window Limits** - Per-second, minute, hour, day, and month limits
- **Quota Management** - Daily/monthly API quota with alerts and top-ups
- **Multi-Tenant Scoping** - Scope by user, team, tenant, or IP
- **Multiple Storage Drivers** - Cache, Redis, or Database
- **RFC 7231 Compliant** - Standard rate limit headers
- **Burst Handling** - Token bucket algorithm for controlled bursts
- **Artisan Commands** - Status, analytics, cleanup, and management tools
- **Testing Helpers** - Fluent testing API with `ThrottleSmartFake`

---

Requirements
------------

[](#requirements)

- PHP 8.3+
- Laravel 11.x or 12.x

---

Installation
------------

[](#installation)

```
composer require grazulex/laravel-api-throttle-smart
```

Publish the configuration:

```
php artisan vendor:publish --tag="throttle-smart-config"
```

For database driver, publish migrations:

```
php artisan vendor:publish --tag="throttle-smart-migrations"
php artisan migrate
```

---

Quick Start
-----------

[](#quick-start)

Apply the middleware to routes:

```
// routes/api.php
Route::middleware(['auth:sanctum', 'throttle.smart'])->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/orders', [OrderController::class, 'store']);
});
```

The middleware automatically:

- Resolves the user's plan from the `plan` attribute
- Applies plan-specific rate limits
- Adds standard rate limit headers
- Returns 429 when limits exceeded

### Response Headers

[](#response-headers)

```
HTTP/1.1 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
X-RateLimit-Reset: 1706835600
X-RateLimit-Policy: 60;w=60
X-RateLimit-Plan: pro
X-Quota-Limit: 1000000
X-Quota-Remaining: 999542
X-Quota-Reset: 1709251200
```

When rate limited:

```
HTTP/1.1 429 Too Many Requests
Retry-After: 45
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1706835600
```

---

Plan Configuration
------------------

[](#plan-configuration)

```
// config/throttle-smart.php
'plans' => [
    'free' => [
        'label' => 'Free Plan',
        'requests_per_minute' => 60,
        'requests_per_hour' => 500,
        'requests_per_day' => 5000,
        'requests_per_month' => 100000,
        'burst_size' => 10,
        'burst_refill_rate' => 1,
    ],

    'pro' => [
        'label' => 'Pro Plan',
        'requests_per_minute' => 300,
        'requests_per_hour' => 5000,
        'requests_per_day' => 50000,
        'requests_per_month' => 1000000,
        'burst_size' => 50,
        'burst_refill_rate' => 5,
    ],

    'enterprise' => [
        'label' => 'Enterprise Plan',
        'requests_per_minute' => 1000,
        'requests_per_hour' => 20000,
        'requests_per_day' => 200000,
        'requests_per_month' => null, // Unlimited
        'burst_size' => 200,
        'burst_refill_rate' => 20,
    ],
],
```

---

PHP Attributes
--------------

[](#php-attributes)

```
use Grazulex\ThrottleSmart\Attributes\RateLimit;
use Grazulex\ThrottleSmart\Attributes\QuotaCost;

class ApiController extends Controller
{
    #[RateLimit(perMinute: 10, perHour: 100)]
    public function sensitiveEndpoint(Request $request)
    {
        // Custom limits for this endpoint
    }

    #[QuotaCost(5)]
    public function expensiveOperation(Request $request)
    {
        // Costs 5 quota units instead of 1
    }
}
```

---

Programmatic Usage
------------------

[](#programmatic-usage)

```
use Grazulex\ThrottleSmart\Facades\ThrottleSmart;

// Get rate limits for a user
$limits = ThrottleSmart::getLimits($user);
$limits->minute['remaining']; // 58
$limits->isLimited; // false

// Get quota information
$quota = ThrottleSmart::getQuota($user);
$quota->monthly['remaining']; // 999542
$quota->percentageUsed; // 0.05

// Check without consuming
if (ThrottleSmart::wouldLimit($request)) {
    return response()->json(['message' => 'Please slow down'], 429);
}

// Manually consume quota
ThrottleSmart::consume(5); // Consume 5 units

// Reset limits for a user
ThrottleSmart::reset("user:{$user->id}");

// Grant bonus quota
ThrottleSmart::addQuota($user, 10000, 'Customer support bonus');
```

---

Rate Limiting Algorithms
------------------------

[](#rate-limiting-algorithms)

### Fixed Window (Default)

[](#fixed-window-default)

Simple counter-based limiting with discrete time windows.

### Sliding Window

[](#sliding-window)

Weighted average across windows for smoother rate limiting.

```
'sliding_window' => [
    'enabled' => true,
    'precision' => 1,
],
```

### Token Bucket

[](#token-bucket)

Allows controlled bursts while maintaining average rate.

```
'token_bucket' => [
    'enabled' => true,
    'initial_tokens' => null, // Start with full bucket
],
```

---

Artisan Commands
----------------

[](#artisan-commands)

```
# View rate limit status
php artisan throttle:status

# Check specific user
php artisan throttle:user --user=123

# View analytics
php artisan throttle:analytics --period=day

# Reset user limits
php artisan throttle:reset --user=123

# Reset user quota
php artisan throttle:reset-quota --user=123

# Grant bonus quota
php artisan throttle:grant-quota --user=123 --amount=10000 --reason="Support"

# Cleanup old data
php artisan throttle:cleanup --days=90
```

---

Events
------

[](#events)

```
use Grazulex\ThrottleSmart\Events\RateLimitExceeded;
use Grazulex\ThrottleSmart\Events\RateLimitApproaching;
use Grazulex\ThrottleSmart\Events\QuotaExceeded;
use Grazulex\ThrottleSmart\Events\QuotaThresholdReached;

// In EventServiceProvider
protected $listen = [
    RateLimitExceeded::class => [
        SendRateLimitNotification::class,
    ],
    QuotaThresholdReached::class => [
        SendQuotaWarningEmail::class,
    ],
];
```

---

Testing
-------

[](#testing)

```
use Grazulex\ThrottleSmart\Facades\ThrottleSmart;

public function test_rate_limiting(): void
{
    ThrottleSmart::fake();

    // Make requests...

    ThrottleSmart::assertLimitExceeded('user:123');
    ThrottleSmart::assertNotLimited('user:456');
    ThrottleSmart::assertQuotaConsumed(150);
}
```

Integration testing:

```
public function test_api_is_rate_limited(): void
{
    $user = User::factory()->create(['plan' => 'free']);

    // Make 61 requests (free plan allows 60/min)
    for ($i = 0; $i < 61; $i++) {
        $response = $this->actingAs($user)
            ->getJson('/api/users');
    }

    $response->assertStatus(429)
        ->assertHeader('X-RateLimit-Remaining', '0')
        ->assertJsonPath('error.code', 'RATE_LIMIT_EXCEEDED');
}
```

---

Quality Tools
-------------

[](#quality-tools)

```
# Run tests
composer test

# Code style (Laravel Pint)
composer pint

# Static analysis (PHPStan Level 5)
composer analyse
```

---

Error Responses
---------------

[](#error-responses)

CodeStatusDescription`RATE_LIMIT_EXCEEDED`429Rate limit exceeded for time window`QUOTA_EXCEEDED`429Monthly/daily quota exceeded---

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Jean-Marc Strauven](https://github.com/Grazulex)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

---

See Also
--------

[](#see-also)

- [laravel-api-idempotency](https://github.com/Grazulex/laravel-api-idempotency) - API idempotency support
- [laravel-apiroute](https://github.com/Grazulex/laravel-apiroute) - API versioning lifecycle management

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

96d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/888105bd54b6b7f7905523a16a1d08eebc2e5d39b19a4c174b5961bb4d52929b?d=identicon)[Grazulex](/maintainers/Grazulex)

---

Top Contributors

[![Grazulex](https://avatars.githubusercontent.com/u/4521546?v=4)](https://github.com/Grazulex "Grazulex (10 commits)")

---

Tags

middlewareapilaravelsaasmulti-tenantthrottlerate limitingquota

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/grazulex-laravel-api-throttle-smart/health.svg)

```
[![Health](https://phpackages.com/badges/grazulex-laravel-api-throttle-smart/health.svg)](https://phpackages.com/packages/grazulex-laravel-api-throttle-smart)
```

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[imliam/laravel-throttle-simultaneous-requests

Throttle the current user's requests based on how many requests are currently being executed.

4623.0k](/packages/imliam-laravel-throttle-simultaneous-requests)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
