PHPackages                             alphavel/rate-limit - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. alphavel/rate-limit

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

alphavel/rate-limit
===================

High-performance rate limiting for Alphavel using Swoole Table

v1.0.0(5mo ago)00MITPHPPHP ^8.4

Since Nov 26Pushed 5mo agoCompare

[ Source](https://github.com/alphavel/rate-limit)[ Packagist](https://packagist.org/packages/alphavel/rate-limit)[ RSS](/packages/alphavel-rate-limit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

Alphavel Rate Limit
===================

[](#alphavel-rate-limit)

High-performance rate limiting package for Alphavel Framework using Swoole Table.

Features
--------

[](#features)

- ⚡ **0.001ms latency** (1000x faster than Redis)
- 🚀 **Zero dependencies** (Swoole built-in)
- 🔒 **Thread-safe** (atomic operations)
- 💾 **Shared memory** between workers
- 🎯 **Multiple levels** (IP, User, Endpoint, Global)
- 🛡️ **DDoS protection** (global rate limiting)
- 📊 **CLI tools** (stats, list, reset, block)

Performance
-----------

[](#performance)

```
Baseline (no rate limit):  5,042 req/s
With rate limit:            5,038 req/s
Overhead:                   0.08% (negligible)

```

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

[](#installation)

```
composer require alphavel/rate-limit
```

Configuration
-------------

[](#configuration)

Publish configuration:

```
php alpha vendor:publish --tag=rate-limit-config
```

Configure `.env`:

```
RATE_LIMIT_DRIVER=swoole
RATE_LIMIT_MAX_ENTRIES=100000
RATE_LIMIT_DEFAULT=1000
RATE_LIMIT_WINDOW=60
RATE_LIMIT_ENABLE_GLOBAL=false
RATE_LIMIT_GLOBAL=10000
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
// routes/api.php

// 100 requests per minute per IP
$router->middleware('rate_limit:100,60,ip')->group(function ($router) {
    $router->post('/auth/login', [AuthController::class, 'login']);
});

// 1000 requests per minute per authenticated user
$router->middleware(['auth', 'rate_limit:1000,60,user'])->group(function ($router) {
    $router->get('/users', [UserController::class, 'index']);
});

// 10 requests per minute per IP on this specific endpoint
$router->middleware('rate_limit:10,60,endpoint')->post('/heavy-operation', [Controller::class, 'heavy']);
```

### Multiple Levels (Defense in Depth)

[](#multiple-levels-defense-in-depth)

```
$router->middleware([
    'rate_limit:1000,60,ip',      // 1000/min per IP
    'rate_limit:100,60,user',      // 100/min per user
    'rate_limit:10,60,endpoint'    // 10/min on this endpoint
])->post('/ai/generate', [AIController::class, 'generate']);
```

### Available Levels

[](#available-levels)

- `ip` - Rate limit by IP address
- `user` - Rate limit by authenticated user ID
- `api_key` - Rate limit by API key (X-API-Key header)
- `endpoint` - Rate limit by IP + endpoint path
- `session` - Rate limit by session ID
- `global` - Global rate limit (DDoS protection)

CLI Commands
------------

[](#cli-commands)

### Show Statistics

[](#show-statistics)

```
php alpha rate-limit:stats
```

### List Active Limits

[](#list-active-limits)

```
php alpha rate-limit:list

# Show only blocked entries
php alpha rate-limit:list --blocked
```

### Reset Rate Limit

[](#reset-rate-limit)

```
php alpha rate-limit:reset ip:192.168.1.1
```

### Block IP/User

[](#block-ipuser)

```
# Block for 1 hour (default)
php alpha rate-limit:block ip:192.168.1.1

# Block for specific duration
php alpha rate-limit:block ip:192.168.1.1 --duration=3600
```

Whitelist
---------

[](#whitelist)

Add trusted IPs to whitelist (never rate limited):

```
// config/rate_limit.php

'whitelist' => [
    '127.0.0.1',
    '::1',
    '10.0.0.0/8',        // Private network
    '192.168.1.100',     // Load balancer
],
```

Global Rate Limit (DDoS Protection)
-----------------------------------

[](#global-rate-limit-ddos-protection)

Enable global rate limiting to protect against DDoS:

```
RATE_LIMIT_ENABLE_GLOBAL=true
RATE_LIMIT_GLOBAL=10000  # 10k requests/second globally
```

This is applied **before** individual rate limits.

Response Headers
----------------

[](#response-headers)

Rate limit information is included in response headers:

```
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1700000000

```

When rate limit is exceeded:

```
HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1700000042

{
  "error": "rate_limit_exceeded",
  "message": "Rate limit of 100 requests per minute exceeded for your IP.",
  "retry_after": 42,
  "reset_at": 1700000042
}

```

Memory Usage
------------

[](#memory-usage)

Swoole Table memory calculation:

- **16 bytes per entry**
- 100k entries = 1.6 MB
- 1M entries = 16 MB

Configure based on your needs:

```
// config/rate_limit.php

'swoole' => [
    'max_entries' => 100000, // Adjust based on unique IPs/users expected
],
```

Bootstrap (Important!)
----------------------

[](#bootstrap-important)

Initialize Swoole Table **before** `$server->start()`:

```
// bootstrap/server.php

use Alphavel\RateLimit\Drivers\SwooleTableDriver;

// Initialize BEFORE server start
SwooleTableDriver::init(config('rate_limit.swoole.max_entries', 100000));

$server->start();
```

Testing
-------

[](#testing)

```
composer test
```

Benchmarking
------------

[](#benchmarking)

```
# Without rate limiting
wrk -t4 -c100 -d20s http://localhost:8087/api/test

# With rate limiting
wrk -t4 -c100 -d20s http://localhost:8087/api/test-limited
```

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

[](#requirements)

- PHP &gt;= 8.1
- Swoole Extension &gt;= 5.0
- Alphavel Framework &gt;= 1.0

License
-------

[](#license)

MIT License - see LICENSE file for details.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance70

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 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

172d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/51c953df141d0cfd39946d3e417b2eb3106d96170c62c4c908a6cc0b75352883?d=identicon)[arthur4weber](/maintainers/arthur4weber)

---

Top Contributors

[![arthur2weber](https://avatars.githubusercontent.com/u/9046093?v=4)](https://github.com/arthur2weber "arthur2weber (3 commits)")

---

Tags

swoolerate limitrate limitingalphavelddos-protection

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alphavel-rate-limit/health.svg)

```
[![Health](https://phpackages.com/badges/alphavel-rate-limit/health.svg)](https://phpackages.com/packages/alphavel-rate-limit)
```

###  Alternatives

[davedevelopment/stiphle

Simple rate limiting/throttling for php

2567.7M9](/packages/davedevelopment-stiphle)[bandwidth-throttle/token-bucket

Implementation of the Token Bucket algorithm.

5121.9M10](/packages/bandwidth-throttle-token-bucket)[hyperf/di

A DI for Hyperf.

182.8M594](/packages/hyperf-di)[hyperf/crontab

A crontab component for Hyperf.

131.6M62](/packages/hyperf-crontab)

PHPackages © 2026

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