PHP code example of largerio / laravel-concurrent-limiter

1. Go to this page and download the library: Download largerio/laravel-concurrent-limiter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

largerio / laravel-concurrent-limiter example snippets


// routes/api.php
Route::middleware('concurrent.limit:5,30')->group(function () {
    Route::get('/heavy-endpoint', HeavyController::class);
});

use Illuminate\Support\Facades\Route;

// Parameters: maxParallel, maxWaitTime, prefix
Route::middleware('concurrent.limit:10,30,api')->group(function () {
    Route::get('/data', [DataController::class, 'index']);
});

use Largerio\LaravelConcurrentLimiter\LaravelConcurrentLimiter;

Route::middleware(LaravelConcurrentLimiter::with(10, 30, 'api'))->group(function () {
    // ...
});

use Largerio\LaravelConcurrentLimiter\JobConcurrentLimiter;

class ProcessPayment implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function middleware(): array
    {
        return [
            new JobConcurrentLimiter(
                maxParallel: 5,        // Max 5 concurrent jobs
                key: 'stripe-api',     // Shared key for all Stripe jobs
                releaseAfter: 30,      // Retry after 30 seconds if limited
                shouldRelease: true    // Auto-release job back to queue
            ),
        ];
    }

    public function handle(): void
    {
        // Process payment with Stripe...
    }
}

// config/concurrent-limiter.php
'adaptive' => [
    'enabled' => true,
    'algorithm' => 'vegas',         // 'vegas' or 'gradient2'
    'min_limit' => 1,               // Never go below this
    'max_limit' => 100,             // Never exceed this
    'ewma_alpha' => 0.3,            // EWMA smoothing (Vegas)
    'sample_window' => 60,          // Metrics TTL in seconds
    'min_rtt_reset_samples' => 1000, // Reset minRTT after N samples (Vegas)
    'rtt_tolerance' => 2.0,         // Acceptable latency multiplier (Gradient2)
],

// Route configuration
Route::middleware('concurrent.limit:10,30,api')->group(...);
//                              ↑
//                              maxParallel = 10 (hard cap)

// Adaptive can only REDUCE the limit, never exceed maxParallel
// Effective limit = min(maxParallel, adaptiveLimit)

use Largerio\LaravelConcurrentLimiter\Contracts\AdaptiveResolver;

$resolver = app(AdaptiveResolver::class);
$metrics = $resolver->getMetrics('concurrent-limiter:api:user123');

// Vegas metrics:
// ['avg_latency_ms' => 245.5, 'min_latency_ms' => 100.0, 'current_limit' => 12, ...]

// Gradient2 metrics:
// ['short_ewma_ms' => 200.0, 'long_ewma_ms' => 150.0, 'current_limit' => 12, ...]

use Largerio\LaravelConcurrentLimiter\Events\ConcurrentLimitExceeded;

class LogConcurrentLimitExceeded
{
    public function handle(ConcurrentLimitExceeded $event): void
    {
        Log::warning('Concurrent limit exceeded', [
            'key' => $event->key,
            'waited_seconds' => $event->waitedSeconds,
            'url' => $event->request->fullUrl(),
        ]);
    }
}

namespace App\Limiters;

use Illuminate\Http\Request;
use Largerio\LaravelConcurrentLimiter\Contracts\KeyResolver;

class TenantKeyResolver implements KeyResolver
{
    public function resolve(Request $request): string
    {
        $tenantId = $request->header('X-Tenant-ID') ?? 'default';
        $userId = $request->user()?->id ?? $request->ip();

        return sha1($tenantId . ':' . $userId);
    }
}

// config/concurrent-limiter.php
'key_resolver' => App\Limiters\TenantKeyResolver::class,

namespace App\Limiters;

use Illuminate\Http\Request;
use Largerio\LaravelConcurrentLimiter\Contracts\ResponseHandler;
use Symfony\Component\HttpFoundation\Response;

class HtmlResponseHandler implements ResponseHandler
{
    public function handle(Request $request, float $waitedSeconds, int $maxWaitTime): Response
    {
        return response()->view('errors.503-concurrent', [
            'waited' => $waitedSeconds,
            'maxWait' => $maxWaitTime,
        ], 503)->header('Retry-After', (string) $maxWaitTime);
    }
}

// config/concurrent-limiter.php
'response_handler' => App\Limiters\HtmlResponseHandler::class,

// config/concurrent-limiter.php
'metrics' => [
    'enabled' => true,
    'route' => '/concurrent-limiter/metrics',
    'middleware' => ['auth:api'],
],

'cache_store' => 'redis', // or null to use default

// config/concurrent-limiter.php
'on_cache_failure' => 'reject', // Return 503 if cache is unavailable

'logging' => [
    'enabled' => true,
    'channel' => null,
    'level' => 'warning',
],
bash
php artisan vendor:publish --provider="Largerio\LaravelConcurrentLimiter\LaravelConcurrentLimiterServiceProvider" --tag="config"
bash
php artisan concurrent-limiter:clear {key} [--force]

# With confirmation
php artisan concurrent-limiter:clear abc123

# Skip confirmation
php artisan concurrent-limiter:clear abc123 --force