PHPackages                             kartubi/php-redis-rate - 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. [Caching](/categories/caching)
4. /
5. kartubi/php-redis-rate

ActiveLibrary[Caching](/categories/caching)

kartubi/php-redis-rate
======================

Redis-based rate limiting for PHP/Laravel using GCRA algorithm

v3.0.1(7mo ago)03MITPHPPHP ^8.1

Since Sep 23Pushed 7mo agoCompare

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

READMEChangelogDependencies (6)Versions (5)Used By (0)

PHP Redis Rate Limiter
======================

[](#php-redis-rate-limiter)

A modern Laravel package for Redis-based rate limiting using the GCRA (Generic Cell Rate Algorithm) algorithm. Built for Laravel 10+ with PHP 8.1+ features. Inspired by and compatible with the [go-redis/redis\_rate](https://github.com/go-redis/redis_rate) library.

> **Looking for legacy Laravel support?** Check out the [v1.x branch](https://github.com/kartubi/php-redis-rate/tree/v1.x) for Laravel 5.5-9.x compatibility.

Features
--------

[](#features)

- **GCRA Algorithm**: Uses the Generic Cell Rate Algorithm (aka leaky bucket) for precise rate limiting
- **Laravel Integration**: Built specifically for Laravel with service providers, facades, and middleware
- **Redis Lua Scripts**: Atomic operations using Redis Lua scripts for consistency
- **Flexible Limits**: Support for per-second, per-minute, per-hour, and custom rate limits
- **Burst Support**: Configure burst capacity independently from rate limits
- **Modern PHP Features**: Uses PHP 8.1+ features like readonly properties, named parameters, and match expressions
- **Middleware Support**: Ready-to-use middleware for HTTP rate limiting
- **Artisan Commands**: Built-in testing commands for debugging rate limits

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

[](#installation)

Install the package via Composer:

```
composer require kartubi/php-redis-rate
```

> **For legacy Laravel projects (5.5-9.x):** Use `composer require kartubi/php-redis-rate:^1.0` instead.

The package will automatically register itself via Laravel's package discovery.

Publish the configuration file (optional):

```
php artisan vendor:publish --tag=redis-rate-config
```

### Clean Redis Keys Setup (Recommended)

[](#clean-redis-keys-setup-recommended)

By default, Laravel adds an app-name prefix to Redis keys (e.g., `laravel-app-database-rate:user123`). For cleaner rate limiting keys, run the setup command:

```
php artisan redis-rate:setup
```

This command will:

- ✅ Publish the `config/redis-rate.php` configuration file
- ✅ Create a self-contained Redis connection (no changes to `config/database.php`)
- ✅ Use a separate Redis database (default: database 2)
- ✅ Remove Laravel's app-name prefix completely
- ✅ Result in clean keys like: `rate:user123`

You can also specify a custom database number:

```
php artisan redis-rate:setup --database=3
```

### Environment Configuration

[](#environment-configuration)

After running setup, you can optionally configure these environment variables:

```
# Redis Rate Limiter Configuration (all optional)
REDIS_RATE_HOST=127.0.0.1      # Redis host
REDIS_RATE_PORT=6379           # Redis port
REDIS_RATE_PASSWORD=null       # Redis password
REDIS_RATE_DB=2                # Redis database for rate limiting
REDIS_RATE_PREFIX=rate:        # Key prefix
REDIS_RATE_TIMEOUT=5.0         # Connection timeout
```

### Docker Configuration

[](#docker-configuration)

For Docker environments, add these environment variables to your `docker-compose.yml`:

```
services:
  your-laravel-app:
    environment:
      # Standard Redis connection
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - REDIS_PASSWORD=null
      - REDIS_DB=0

      # Redis Rate Limiter (clean keys)
      - REDIS_RATE_HOST=redis
      - REDIS_RATE_PORT=6379
      - REDIS_RATE_DB=2
      - REDIS_RATE_PREFIX=rate
```

The setup command will run automatically in your Dockerfile:

```
RUN php artisan redis-rate:setup --force --database=2 || true
```

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x
- Redis 3.2 or newer (requires `replicate_commands` feature)
- Either the Redis PHP extension or Predis 2.0+

Basic Usage
-----------

[](#basic-usage)

### Using the Facade

[](#using-the-facade)

```
use Kartubi\RedisRate\Facades\RedisRate;
use Kartubi\RedisRate\Limit;

// Allow 10 requests per second
$result = RedisRate::allow('user:123', Limit::perSecond(10));

if ($result->isAllowed()) {
    // Request is allowed
    echo "Request allowed. Remaining: " . $result->remaining;
} else {
    // Rate limit exceeded
    echo "Rate limit exceeded. Retry after: " . $result->getRetryAfterSeconds() . " seconds";
}
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use Kartubi\RedisRate\RedisRateLimiter;
use Kartubi\RedisRate\Limit;

class ApiController extends Controller
{
    public function __construct(
        private RedisRateLimiter $rateLimiter
    ) {}

    public function handle(Request $request)
    {
        $result = $this->rateLimiter->allow(
            'api:' . $request->ip(),
            Limit::perMinute(60)
        );

        if ($result->isExceeded()) {
            abort(429, 'Too Many Requests');
        }

        // Handle the request...
    }
}
```

Rate Limit Types
----------------

[](#rate-limit-types)

### Pre-defined Limits

[](#pre-defined-limits)

```
// 10 requests per second (burst: 10)
$limit = Limit::perSecond(10);

// 60 requests per minute (burst: 60)
$limit = Limit::perMinute(60);

// 1000 requests per hour (burst: 1000)
$limit = Limit::perHour(1000);
```

### Custom Limits

[](#custom-limits)

```
// 100 requests per minute with burst capacity of 150
$limit = Limit::custom(
    rate: 100,           // requests per period
    burst: 150,          // burst capacity
    periodInSeconds: 60  // period in seconds
);
```

Advanced Usage
--------------

[](#advanced-usage)

### Multiple Requests

[](#multiple-requests)

```
// Allow up to N requests at once
$result = RedisRate::allowN('bulk:user:123', Limit::perSecond(10), 5);

// Allow at most N requests (partial consumption)
$result = RedisRate::allowAtMost('batch:user:123', Limit::perSecond(10), 8);
```

### Reset Rate Limits

[](#reset-rate-limits)

```
// Reset all limits for a specific key
RedisRate::reset('user:123');
```

Middleware Usage
----------------

[](#middleware-usage)

Add the middleware to your HTTP kernel or use it directly in routes:

```
// In routes/api.php
Route::middleware('redis-rate:api')->group(function () {
    Route::get('/users', [UserController::class, 'index']);
});

// With custom limits
Route::middleware('redis-rate:60,api')->get('/search', [SearchController::class, 'search']);

// With custom key
Route::middleware('redis-rate:login,auth:login')->post('/login', [AuthController::class, 'login']);
```

### Register Middleware

[](#register-middleware)

In your `app/Http/Kernel.php`:

```
protected $routeMiddleware = [
    // ...
    'redis-rate' => \Kartubi\RedisRate\Middleware\RateLimitMiddleware::class,
];
```

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

[](#configuration)

The configuration file allows you to customize default settings:

```
return [
    // Default Redis connection (null uses default)
    'connection' => env('REDIS_RATE_CONNECTION'),

    // Key prefix for Redis keys
    'key_prefix' => env('REDIS_RATE_PREFIX', 'rate:'),

    // Pre-defined rate limits
    'limits' => [
        'api' => [
            'rate' => 60,
            'period' => 60,
            'burst' => 10,
        ],
        'login' => [
            'rate' => 5,
            'period' => 300, // 5 minutes
            'burst' => 5,
        ],
        'upload' => [
            'rate' => 10,
            'period' => 3600, // 1 hour
            'burst' => 20,
        ],
    ],
];
```

Testing Commands
----------------

[](#testing-commands)

Test your rate limiting configuration:

```
# Test with default settings
php artisan redis-rate:test "user:123"

# Test with custom parameters
php artisan redis-rate:test "api:test" --rate=10 --period=60 --burst=15 --requests=12
```

Understanding Results
---------------------

[](#understanding-results)

The `Result` object contains important information about the rate limiting decision:

```
$result = RedisRate::allow('key', $limit);

// Check if request is allowed
$result->isAllowed();    // true if allowed
$result->isExceeded();   // true if rate limit exceeded

// Get remaining capacity
$result->remaining;      // Number of requests remaining

// Get timing information
$result->getRetryAfterSeconds();  // Seconds until next request allowed
$result->getResetAfterSeconds();  // Seconds until rate limit resets

// Get the limit that was applied
$result->limit;          // The Limit object used
```

Algorithm Details
-----------------

[](#algorithm-details)

This package implements the GCRA (Generic Cell Rate Algorithm), also known as the leaky bucket algorithm. GCRA provides several advantages:

- **Smooth rate limiting**: Distributes requests evenly over time
- **Burst handling**: Allows controlled bursts while maintaining average rate
- **Memory efficient**: Uses minimal Redis memory per key
- **Atomic operations**: All operations are atomic using Redis Lua scripts

Version Compatibility
---------------------

[](#version-compatibility)

Package VersionLaravel VersionPHP VersionBranch**3.x** (Current)10.x, 11.x, 12.x8.1+`main`1.x (Legacy)5.5, 6.x, 7.x, 8.x, 9.x7.2+[`v1.x`](https://github.com/kartubi/php-redis-rate/tree/v1.x)> **Note:** This is the modern v3.x version. For legacy Laravel support, see the [v1.x branch documentation](https://github.com/kartubi/php-redis-rate/tree/v1.x).

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Credits
-------

[](#credits)

This package is inspired by the excellent [go-redis/redis\_rate](https://github.com/go-redis/redis_rate) library and implements the same GCRA algorithm for PHP/Laravel applications.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance62

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Every ~0 days

Total

4

Last Release

236d ago

Major Versions

v1.0.0 → v3.0.02025-09-23

v1.x-dev → v3.0.12025-09-24

PHP version history (2 changes)v1.0.0PHP &gt;=7.2.0

v3.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/b804d84c923eca41be800ec49c199423a4e9f1639428c13ebbb2c2daedc122a3?d=identicon)[kartubi](/maintainers/kartubi)

---

Top Contributors

[![kartubi](https://avatars.githubusercontent.com/u/13296410?v=4)](https://github.com/kartubi "kartubi (11 commits)")

---

Tags

laravelredisrate limitingleaky bucketGCRA

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kartubi-php-redis-rate/health.svg)

```
[![Health](https://phpackages.com/badges/kartubi-php-redis-rate/health.svg)](https://phpackages.com/packages/kartubi-php-redis-rate)
```

###  Alternatives

[monospice/laravel-redis-sentinel-drivers

Redis Sentinel integration for Laravel and Lumen.

103830.5k](/packages/monospice-laravel-redis-sentinel-drivers)[namoshek/laravel-redis-sentinel

An extension of Laravels Redis driver which supports connecting to a Redis master through Redis Sentinel.

38679.0k](/packages/namoshek-laravel-redis-sentinel)[encore/redis-manager

Redis manager for laravel

25243.1k](/packages/encore-redis-manager)[yangusik/laravel-balanced-queue

Laravel queue management with load balancing between partitions (user groups)

786.4k](/packages/yangusik-laravel-balanced-queue)[vetruvet/laravel-phpredis

Use phpredis as the redis connection in Laravel

43123.7k](/packages/vetruvet-laravel-phpredis)[ginnerpeace/laravel-redis-lock

Simple redis distributed locks for Laravel.

15114.4k](/packages/ginnerpeace-laravel-redis-lock)

PHPackages © 2026

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