alphavel/rate-limit

High-performance rate limiting for Alphavel using Swoole Table

Maintainers

Package info

github.com/alphavel/rate-limit

pkg:composer/alphavel/rate-limit

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2025-11-26 15:47 UTC

This package is auto-updated.

Last update: 2026-03-27 01:19:55 UTC


README

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

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

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

Installation

composer require alphavel/rate-limit

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

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)

$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

  • 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

Show Statistics

php alpha rate-limit:stats

List Active Limits

php alpha rate-limit:list

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

Reset Rate Limit

php alpha rate-limit:reset ip:192.168.1.1

Block IP/User

# 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

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)

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

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

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!)

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

composer test

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

  • PHP >= 8.1
  • Swoole Extension >= 5.0
  • Alphavel Framework >= 1.0

License

MIT License - see LICENSE file for details.