PHP Classes

How to Use a PHP Rate Limiter That Uses Different Strategies to Protect Web Sites and APIs From Server Abuse Using the Package AI Rate Limiter: Limit the access rate using multiple strategies

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-07-29 (2 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
ai-rate-limiter 1.0.0Custom (specified...8Networking, Security, Artificial inte..., P...
Description 

Author

This package can limit the access rate using multiple strategies.

It provides a class that can take an identifier of the current user and checks if the user can access a resource of a given URL.

The class implements different access retry strategies based on access patterns to limit the access of the current user.

Currently, it supports the strategies:

- Exponential: only allows repeated accesses after a period of time that increases exponentially (back off 60s, 120s, 240s...)

- Linear: only allows repeated accesses after a period of time that increases linearly (60s, 120s, 180s...)

- Fixed: only allows repeated accesses after a period of time that is fixed (always 60s)

- Jitter: only allows repeated accesses after a period of time that increases exponentially adding random jitter (back off 60s, 120s, 240s...)

- Adaptive: only allows repeated accesses after a period of time is adapted according to patterns

The package uses Redis the data about the user accesses.

It is multi-tenant, so it supports limiting the rates of multiple users of multiple applications

It is able to detect access bursts.

The package can real-time analytics.

Innovation Award
PHP Programming Innovation award nominee
July 2025
Nominee
Vote
Many Websites and APIs are hosted in servers that are receiving an excessive number of robots.

These robots often cause server overload and may halt the Websites or APIs.

This package provides a solution to limit the rate of accesses of users of the Websites and API.

It implements different rate limiting strategies to allow the developers that use the package to adopt a strategy that is more suited to the type of Website or API that was developed.

Manuel Lemos
Picture of Ali Khaleghi
  Performance   Level  
Name: Ali Khaleghi <contact>
Classes: 1 package by
Country: Norway Norway
Age: 31
All time rank: Not yet ranked
Week rank: Not yet ranked
Innovation award
Innovation award
Nominee: 1x

Instructions

Clone the repo, install dependencies, and run examples — only Redis and the PHP Redis extension are required.

git clone https://github.com/ahur-system/ai-rate-limiter.git cd
ai-rate-limiter composer install

or

composer require ahur-system/ai-rate-limiter

Usage:

php examples/basic_usage.php

- No setup - No config - Just Redis + PHP 8.1+ + Redis extension.

Example

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use
AhurSystem\AIRateLimiter\AIRateLimiter;

// Initialize Redis connection
if (!class_exists('Redis')) {
    echo
"? Redis extension not available\n";
    echo
"Please install the Redis PHP extension: sudo pacman -S php-redis\n";
    exit(
1);
}

try {
   
$redis = new Redis();
   
$redis->connect('127.0.0.1', 6379);
} catch (
Exception $e) {
    echo
"? Redis connection failed: " . $e->getMessage() . "\n";
    echo
"Please ensure Redis is running on localhost:6379\n";
    exit(
1);
}

// Create AI Rate Limiter instance
$limiter = new AIRateLimiter($redis, [
   
'default_limit' => 100,
   
'default_window' => 3600, // 1 hour
   
'learning_enabled' => true,
   
'adaptive_throttling' => true,
   
'retry_strategy' => 'adaptive'
]);

// Example 1: Basic rate limiting
echo "=== Basic Rate Limiting Example ===\n";

$userId = 'user_123';
$endpoint = 'api/v1/users';

$result = $limiter->check($userId, $endpoint, [
   
'user_agent' => 'MyApp/1.0',
   
'ip' => '192.168.1.100'
]);

echo
"Request allowed: " . ($result->isAllowed() ? 'Yes' : 'No') . "\n";
echo
"Remaining requests: " . $result->getRemainingRequests() . "\n";
echo
"Retry delay: " . $result->getRetryDelay() . " seconds\n";
echo
"Reset time: " . $result->getResetDateTime()->format('Y-m-d H:i:s') . "\n";
echo
"Usage trend: " . round($result->getUsageTrend() * 100, 2) . "%\n";
echo
"Burst factor: " . round($result->getBurstFactor(), 2) . "\n\n";

// Example 2: Simulate burst requests
echo "=== Burst Detection Example ===\n";

for (
$i = 0; $i < 5; $i++) {
   
$result = $limiter->check($userId, $endpoint, [
       
'user_agent' => 'MyApp/1.0',
       
'ip' => '192.168.1.100',
       
'request_type' => 'burst'
   
]);
   
    echo
"Request " . ($i + 1) . ": " . ($result->isAllowed() ? 'Allowed' : 'Blocked') .
        
" (Burst factor: " . round($result->getBurstFactor(), 2) . ")\n";
}

// Example 3: Different endpoints
echo "\n=== Multi-Endpoint Example ===\n";

$endpoints = ['api/v1/users', 'api/v1/posts', 'api/v1/comments'];

foreach (
$endpoints as $endpoint) {
   
$result = $limiter->check($userId, $endpoint, [
       
'user_agent' => 'MyApp/1.0',
       
'ip' => '192.168.1.100'
   
]);
   
    echo
"Endpoint: $endpoint\n";
    echo
" Allowed: " . ($result->isAllowed() ? 'Yes' : 'No') . "\n";
    echo
" Remaining: " . $result->getRemainingRequests() . "\n";
    echo
" Pattern count: " . $result->getPatternCount() . "\n\n";
}

// Example 4: API response headers
echo "=== HTTP Headers Example ===\n";

$result = $limiter->check($userId, 'api/v1/data');
$headers = $result->getHeaders();

echo
"HTTP Headers:\n";
foreach (
$headers as $name => $value) {
    echo
" $name: $value\n";
}

// Example 5: JSON response
echo "\n=== JSON Response Example ===\n";

$jsonResponse = $result->toJson();
echo
$jsonResponse . "\n";

// Example 6: Reset rate limits
echo "\n=== Reset Example ===\n";

echo
"Before reset - Remaining: " . $result->getRemainingRequests() . "\n";
$limiter->reset($userId, 'api/v1/users');
$result = $limiter->check($userId, 'api/v1/users');
echo
"After reset - Remaining: " . $result->getRemainingRequests() . "\n";


Details

AI-Powered Rate Limiter for PHP

PHP Version License Redis

An innovative PHP rate limiting library that uses artificial intelligence to provide adaptive throttling based on usage patterns. This library goes beyond traditional rate limiting by learning from user behavior and optimizing limits in real-time.

?? Important Information

? AI Implementation

This library uses AI concepts (pattern learning, adaptive algorithms, intelligent decision making) but does NOT require: - ? No machine learning libraries - ? No neural networks or deep learning - ? No external AI services - ? No complex ML algorithms

The "AI" is implemented through: - Pattern Learning: Analyzes historical usage data - Adaptive Algorithms: Dynamically adjusts limits based on behavior - Intelligent Decision Making: Context-aware rate limiting - Statistical Analysis: Trend calculation and burst detection

? Licensing

  • MIT License: Completely free to use
  • No License Key Required: No proprietary licensing system
  • Open Source: Full source code available
  • No Usage Limits: Use in any number of projects
  • Commercial Use: Allowed for commercial applications

? Ready to Use

Simply install via Composer and start using immediately - no additional setup, licensing, or AI services required!

? Features

? AI-Powered Intelligence

  • Adaptive Rate Limiting: Automatically adjusts limits based on usage patterns
  • Burst Detection: Intelligently detects and handles traffic bursts
  • Pattern Learning: Learns from historical usage data to optimize performance
  • Predictive Throttling: Anticipates usage patterns to prevent rate limit violations

? Smart Features

  • Multi-Tenant Support: Isolated rate limiting for different users/APIs
  • Endpoint-Specific Limits: Different limits for different API endpoints
  • Intelligent Retry Strategies: Multiple strategies (exponential, linear, fixed, jitter, adaptive)
  • Real-time Analytics: Detailed usage statistics and trends
  • HTTP Header Integration: Standard rate limiting headers for APIs

? Technical Excellence

  • High Performance: Redis-based storage for lightning-fast operations
  • Memory Efficient: Automatic cleanup of old patterns
  • Thread Safe: Designed for concurrent access
  • Extensible: Easy to customize and extend

? Installation

Requirements

  • PHP 8.1 or higher
  • Redis server
  • PHP Redis extension

Composer Installation

composer require ahur-system/ai-rate-limiter

Manual Installation

git clone https://github.com/ahur-system/ai-rate-limiter.git
cd ai-rate-limiter
composer install

? Quick Start

<?php

require_once 'vendor/autoload.php';

use AhurSystem\AIRateLimiter\AIRateLimiter;

// Initialize Redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Create rate limiter
$limiter = new AIRateLimiter($redis, [
    'default_limit' => 100,
    'default_window' => 3600, // 1 hour
    'learning_enabled' => true,
    'adaptive_throttling' => true
]);

// Check rate limit
$result = $limiter->check('user_123', 'api/v1/users', [
    'user_agent' => 'MyApp/1.0',
    'ip' => '192.168.1.100'
]);

if ($result->isAllowed()) {
    echo "Request allowed! Remaining: " . $result->getRemainingRequests();
} else {
    echo "Rate limited! Retry after: " . $result->getRetryDelay() . " seconds";
}

? Usage Examples

Basic Rate Limiting

$result = $limiter->check('user_123', 'api/v1/users');

echo "Allowed: " . ($result->isAllowed() ? 'Yes' : 'No') . "\n";
echo "Remaining: " . $result->getRemainingRequests() . "\n";
echo "Reset time: " . $result->getResetDateTime()->format('Y-m-d H:i:s') . "\n";

API Integration with Headers

$result = $limiter->check('api_key_456', 'api/v1/data');

// Set HTTP headers
foreach ($result->getHeaders() as $name => $value) {
    header("$name: $value");
}

// Check if rate limited
if (!$result->isAllowed()) {
    http_response_code(429);
    echo json_encode([
        'error' => 'Rate limit exceeded',
        'retry_after' => $result->getRetryDelay()
    ]);
    exit;
}

Usage Statistics

$result = $limiter->check('user_123', 'api/v1/users');
$stats = $result->getStats();

echo "Current usage: " . $stats['current_usage'] . "\n";
echo "Pattern count: " . $stats['pattern_count'] . "\n";
echo "Usage trend: " . round($stats['trend'] * 100, 2) . "%\n";
echo "Burst factor: " . round($stats['burst_factor'], 2) . "\n";

Retry Strategies

The library supports multiple retry strategies for handling rate-limited requests:

// Available strategies
$strategies = $limiter->getStrategyDescriptions();
foreach ($strategies as $name => $description) {
    echo "$name: $description\n";
}

// Use different strategies
$limiter = new AIRateLimiter($redis, [
    'retry_strategy' => 'exponential' // Default: exponential backoff
]);

$limiter = new AIRateLimiter($redis, [
    'retry_strategy' => 'linear' // Linear increase
]);

$limiter = new AIRateLimiter($redis, [
    'retry_strategy' => 'jitter' // Exponential with random jitter
]);

$limiter = new AIRateLimiter($redis, [
    'retry_strategy' => 'fixed' // Fixed delay
]);

$limiter = new AIRateLimiter($redis, [
    'retry_strategy' => 'adaptive' // Pattern-based adaptive delay
]);

Strategy Details: - exponential: 60s, 120s, 240s, 480s... (recommended for APIs) - linear: 60s, 120s, 180s, 240s... (predictable increases) - fixed: Always 60s (simple and consistent) - jitter: Exponential with ±10% randomness (prevents thundering herd) - adaptive: Based on usage patterns and historical data

Reset Rate Limits

// Reset limits for a specific user and endpoint
$limiter->reset('user_123', 'api/v1/users');

?? Architecture

Core Components

  1. AIRateLimiter: Main class handling rate limiting logic
  2. RateLimitResult: Encapsulates rate limiting results
  3. Pattern Analysis: AI algorithms for usage pattern detection
  4. Redis Storage: High-performance data storage

Data Flow

Request ? Pattern Analysis ? AI Decision ? Rate Limit Check ? Result
    ?           ?              ?              ?              ?
  Context   Historical    Adaptive      Redis Store    Response
            Patterns      Limits

? Testing

Run the test suite:

composer test

Run examples:

php examples/basic_usage.php

? Performance

Benchmarks

  • Check Operation: ~0.1ms average response time
  • Pattern Analysis: ~0.5ms for complex patterns
  • Memory Usage: ~1KB per user pattern
  • Redis Operations: 2-3 operations per check

Scalability

  • Supports millions of concurrent users
  • Horizontal scaling with Redis cluster
  • Automatic cleanup of old patterns
  • Efficient memory usage

? Security Features

  • Isolation: Multi-tenant support with key isolation
  • Validation: Input validation and sanitization
  • Rate Limiting: Prevents abuse and DoS attacks
  • Audit Trail: Detailed logging of rate limit decisions

? Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/ahur-system/ai-rate-limiter.git
cd ai-rate-limiter
composer install
composer test

? License

This project is licensed under the MIT License - see the LICENSE file for details.

? Acknowledgments

  • Inspired by modern AI/ML approaches to rate limiting
  • Built for the PHP community
  • Designed for high-performance applications

? Support

Made with ?? for the PHP community

This innovative rate limiting solution combines the power of artificial intelligence with the simplicity of PHP to provide intelligent, adaptive API protection.


  Files folder image Files (39)  
File Role Description
Files folder imageexamples (2 files, 2 directories)
Files folder imagesrc (2 files, 1 directory)
Files folder imagetests (1 file)
Plain text file .npmignore Data Auxiliary data
Plain text file CHANGELOG.md Data Auxiliary data
Plain text file composer.json Data Auxiliary data
Plain text file DOCUMENTATION.md Example Example script
Plain text file LICENSE Lic. License text
Plain text file package.json Data Auxiliary data
Plain text file phpunit.xml Data Auxiliary data
Plain text file README.md Doc. Read me

  Files folder image Files (39)  /  examples  
File Role Description
Files folder imagedemos (2 files)
Files folder imageframeworks (1 file, 3 directories)
  Plain text file basic_usage.php Example Example script
  Plain text file strategy_usage.php Example Example script

  Files folder image Files (39)  /  examples  /  demos  
File Role Description
  Plain text file demo.php Example Example script
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  examples  /  frameworks  
File Role Description
Files folder imageCodeIgniter (2 files, 1 directory)
Files folder imageLaravel (2 files, 3 directories)
Files folder imageWordPress (2 directories)
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  
File Role Description
Files folder imageapp (3 directories)
  Plain text file composer.json Data Auxiliary data
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  /  app  
File Role Description
Files folder imageConfig (2 files)
Files folder imageControllers (1 directory)
Files folder imageFilters (1 file)

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  /  app  /  Config  
File Role Description
  Plain text file Filters.php Class Class source
  Plain text file Routes.php Example Example script

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  /  app  /  Controllers  
File Role Description
Files folder imageAPI (1 file)

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  /  app  /  Controllers  /  API  
File Role Description
  Plain text file UserController.php Class Class source

  Files folder image Files (39)  /  examples  /  frameworks  /  CodeIgniter  /  app  /  Filters  
File Role Description
  Plain text file AIRateLimitFilter.php Class Class source

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  
File Role Description
Files folder imageapp (2 directories)
Files folder imageconfig (1 file)
Files folder imageroutes (1 file)
  Plain text file composer.json Data Auxiliary data
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  app  
File Role Description
Files folder imageHttp (1 directory)
Files folder imageProviders (1 file)

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  app  /  Http  
File Role Description
Files folder imageMiddleware (1 file)

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  app  /  Http  /  Middleware  
File Role Description
  Plain text file AIRateLimitMiddleware.php Class Class source

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  app  /  Providers  
File Role Description
  Plain text file AppServiceProvider.php Class Class source

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  config  
File Role Description
  Plain text file ai-rate-limiter.php Aux. Configuration script

  Files folder image Files (39)  /  examples  /  frameworks  /  Laravel  /  routes  
File Role Description
  Plain text file api.php Class Class source

  Files folder image Files (39)  /  examples  /  frameworks  /  WordPress  
File Role Description
Files folder imagePlugin (1 file)
Files folder imageTheme (3 files)

  Files folder image Files (39)  /  examples  /  frameworks  /  WordPress  /  Plugin  
File Role Description
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  examples  /  frameworks  /  WordPress  /  Theme  
File Role Description
  Plain text file composer.json Data Auxiliary data
  Plain text file functions.php Example Example script
  Plain text file README.md Doc. Documentation

  Files folder image Files (39)  /  src  
File Role Description
Files folder imageStrategies (7 files)
  Plain text file AIRateLimiter.php Class Class source
  Plain text file RateLimitResult.php Class Class source

  Files folder image Files (39)  /  src  /  Strategies  
File Role Description
  Plain text file AdaptiveStrategy.php Class Class source
  Plain text file ExponentialStrategy.php Class Class source
  Plain text file FixedStrategy.php Class Class source
  Plain text file JitterStrategy.php Class Class source
  Plain text file LinearStrategy.php Class Class source
  Plain text file RetryStrategyFactory.php Class Class source
  Plain text file RetryStrategyInterface.php Class Class source

  Files folder image Files (39)  /  tests  
File Role Description
  Plain text file AIRateLimiterTest.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0