Skip to content

Instantly share code, notes, and snippets.

@bbrala
Created October 17, 2025 06:59
Show Gist options
  • Select an option

  • Save bbrala/2509d96ff01d40aad229766720fdea22 to your computer and use it in GitHub Desktop.

Select an option

Save bbrala/2509d96ff01d40aad229766720fdea22 to your computer and use it in GitHub Desktop.
Build the Laravel Horizon queue settings dynamicly based on the queuesize of tenants
<?php
namespace App\Providers;
use App\Models\Tenant;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
class DynamicTenantQueueProvider extends ServiceProvider
{
public const QUEUE_WATCH_LIMIT = 20;
/**
* Bootstrap services.
*/
public function boot(): void
{
$queueWatchLimit = config('horizon.queue_watch_limit', self::QUEUE_WATCH_LIMIT);
try {
if (DB::getSchemaBuilder()->hasTable('tenants') === false) {
return;
}
/** @var Collection<Tenant> $tenants */
$tenants = Tenant::all(['id'])->shuffle();
$queue = config('horizon.defaults.supervisor-1.queue');
$queueGroups = [
'high' => [],
'low' => [],
'delayed' => [],
];
foreach ($tenants as $tenant) {
if (!isset($tenant->id)) {
continue;
}
$queueId = 'tenant-'.$tenant->id;
if (Queue::pendingSize($queueId) > 100) {
$queueGroups['high'][] = $queueId;
} elseif (Queue::pendingSize($queueId) > 0) {
$queueGroups['low'][] = $queueId;
} elseif (Queue::delayedSize($queueId) > 0) {
$queueGroups['delayed'][] = $queueId;
}
}
// Randomize the low priority queues.
shuffle($queueGroups['low']);
foreach (['high', 'low', 'delayed'] as $priority) {
foreach ($queueGroups[$priority] as $queueId) {
$queue[] = $queueId;
if (count($queue) >= $queueWatchLimit) {
break 2;
}
}
}
Config::set('horizon.defaults.supervisor-1.queue', $queue);
} catch (Exception $e) {
// Failed fetching tenants, do nothing.
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment