Start the worker
php artisan torque:start
Options:
php artisan torque:start --workers=8 --concurrency=100 --queues=emails,notifications
Dispatch jobs
Standard Laravel dispatching works unchanged:
ProcessDocument::dispatch($document);ProcessDocument::dispatch($document)->onQueue('high');ProcessDocument::dispatch($document)->delay(now()->addMinutes(5)); // Batches work out of the boxBus::batch([ new ProcessDocument($doc1), new ProcessDocument($doc2), new ProcessDocument($doc3),])->dispatch();
Async jobs with TorqueJob
Regular Laravel jobs run synchronously inside their coroutine slot. For async I/O, extend TorqueJob and type-hint the pools you need. HttpPool resolves on its own (15 concurrent requests). MysqlPool and RedisPool need connection strings, so bind them in your app first:
use Webpatser\Torque\Pool\MysqlPool; // In a service provider's register() method$this->app->singleton(MysqlPool::class, fn () => new MysqlPool('host=127.0.0.1 user=app password=secret db=app', 20));
Then the handler:
use Webpatser\Torque\Job\TorqueJob;use Webpatser\Torque\Pool\MysqlPool;use Webpatser\Torque\Pool\HttpPool; class IndexDocument extends TorqueJob{ public function __construct( private int $documentId, ) {} public function handle(MysqlPool $db, HttpPool $http): void { $result = $db->execute('SELECT * FROM documents WHERE id = ?', [$this->documentId]); $row = $result->fetchRow(); $response = $http->post('http://elasticsearch:9200/docs/_doc/' . $this->documentId, json_encode($row)); }}
The torque connection comes from a #[Connection] attribute on TorqueJob, so a subclass declares its own constructor like any Laravel job, with no parent::__construct() call. An explicit onConnection() still wins.
Avoid blocking calls
Warning: Eloquent uses PDO, which is sync-blocking. One
User::find($id)in a handler stalls the whole worker, and every other Fiber on it, until the round trip completes. On a 25-slot worker that is effectively concurrency 1 for the duration of the call.
Either keep Eloquent out of the handler by passing plain data at dispatch time, or use MysqlPool:
// Bad: blocks the OS thread, every Fiber on this worker waitspublic function handle(): void{ $user = User::find($this->userId); foreach ($user->subscriptions as $sub) { Http::post($sub->webhook_url, $payload); }} // Good (option 1): pre-fetch in dispatch, pass plain data into the handlerProcessWebhooks::dispatch( userId: $user->id, webhooks: $user->subscriptions->pluck('webhook_url')->all(),); // Good (option 2): extend TorqueJob, use MysqlPool for async queriesclass ProcessWebhooks extends TorqueJob{ public function handle(MysqlPool $db, HttpPool $http): void { $rows = $db->query('SELECT webhook_url FROM subscriptions WHERE user_id = ?', [$this->userId]); foreach ($rows as $row) { $response = $http->post($row['webhook_url'], $this->payload); } }}
Sync Eloquent is fine when the handler runs one or two fast queries (under 5 ms) and the worker is not fan-out heavy. The same rule applies to curl_exec, Guzzle without a non-blocking handler, usleep and blocking file I/O. Replace them with HttpPool, Fledge\Async\delay() or work done outside the handler.
Per-Fiber state
Use CoroutineContext for state isolated to one job:
use Webpatser\Torque\Job\CoroutineContext; // Inside a job handlerCoroutineContext::set('tenant_id', $this->tenantId);$tenantId = CoroutineContext::get('tenant_id');
State is cleaned up when the Fiber completes (backed by WeakMap).
Concurrency contract
One worker runs up to slots_per_worker jobs at once in a single PHP process. At slots_per_worker = 1 nothing is shared and stock worker semantics apply.
Isolated per attempt:
Context, including child fibers started throughasync(). A job starts with an emptyContextplus its payload's.Logcontext (Log::withContext()andLog::channel('x')->withContext()) on every channel.Authguards, includingasync()children.Cache::memo()stores that exist at boot.defer()callbacks.
Shared by every job on the worker:
- The locale,
config()->set()and the default DB connection. - Transactions on a shared connection. A
DB::beginTransaction()in one job is visible to every job using that connection. Use a pool per job (MysqlPool) or keep transactions out of async handlers. - User scoped bindings. With more than one slot the worker logs a boot WARN naming them. Resolve per-job state inside the job, or list safe stateless bindings in
shared_scoped_bindings. Auth::shouldUse(), services that captured the log or auth manager during boot, andCache::memo()for a store added after boot.
One gap: Auth::setUser() from a raw Fiber, an EventLoop::delay() callback, or a Looping or JobPopping listener writes to the ambient guard, which later attempts clone, for the worker's lifetime.
If your jobs rely on any shared item, lower slots_per_worker for those streams or run them on a dedicated worker.
Note: Laravel Cloud's queue listeners hold the current job in process-wide state. At more than one slot, exception attribution on Cloud is unreliable.
Shared transactions
A transaction belongs to a connection, and every job on the worker uses the same one. If job A hangs inside a transaction while job B is in flight, B nests in A's transaction. B's commit never reaches the database, B acks as a success, and when the worker exits the transaction rolls back, silently taking B's writes with it. Only separate connections per job (a pool) or slots_per_worker = 1 avoid the risk.
Timeouts
Timeouts are on by default (timeouts.enabled, TORQUE_TIMEOUTS). They limit only jobs that declare a $timeout, or streams with a timeout; no stream timeout is set by default.
- The limit is
$job->timeout() ?? the stream's timeout, in seconds.0or neither set means no limit. Keep it belowretry_after; the worker logs a WARN at boot otherwise. - At expiry the job is told through
interrupted(), then fails if$failOnTimeoutis set or its attempts are up, and is otherwise released with a delay of at leasttimeouts.release_delay_seconds.JobTimedOutandJobExceptionOccurredare dispatched. - A timeout stops the whole worker (exit 1) and the master starts a replacement. The other slots get
drain_grace_secondsto finish; what is still running after that is redelivered, so duplicates can happen. - Only a job suspended on the event loop (a Redis, HTTP or async DB call) can time out. Code that blocks the process never lets the timer run; the watchdog below covers that.
- The timer spans
handle()only.
Strict attempts
With strict_attempts (TORQUE_STRICT_ATTEMPTS, on by default) a job is checked against its tries and retryUntil before it runs, and a delivery after the first counts against $tries or the stream's max_retries. A job that keeps killing its worker then reaches the dead-letter stream with reason=redelivery_limit instead of looping.
Counted as a redelivery: a steal from another consumer, a pending re-read, a failed release, survivors abandoned by a drain, a rotation or another job's timeout, entries still prefetched when the worker is SIGKILLed, and a > reply lost to a failed connection.
Not counted: a worker re-reading its own entry, and entries returned at drain that never started.
Leave $tries headroom. With max_retries at 1, any worker death dead-letters a job that does not declare its own $tries; the worker logs a boot WARN for such streams. Set 'warn_strict_attempts' => false on a stream whose jobs all declare $tries to silence it.
Blocked event loop watchdog
A job that blocks the process (sleep(), a blocking PDO query, a blocking extension) freezes every slot and timer of its worker, so timeouts cannot fire. The watchdog is on by default: loop_stall_kill_seconds (TORQUE_LOOP_STALL_KILL) derives max(300, longest stream retry_after), 300 at package defaults. An integer overrides it and 0 is off.
Workers touch a heartbeat file in storage/framework/torque-heartbeats about once a second. The master sends SIGKILL to a worker whose file is older than the limit and starts a replacement.
storagemust be on a local disk, because the file's mtime is compared to the host's clock.- A kill takes every slot of that worker.
- Set the limit above the longest blocking call you accept.
- A worker that has not written a heartbeat yet is never killed, so a hang during boot is not covered.
Queue::popUsing()
Register the callback for the torque connection name:
Queue::popUsing('torque', fn ($queue) => /* ... */);
Registering under default has no effect. The callback receives the comma-joined list of queues this poll may read, not the full configured string.
Live job progress
Every job records a lifecycle timeline (queued, started, exception, completed, plus custom events) to a per-job Redis Stream. Tail it from the CLI:
php artisan torque:tail --job=088066c1-b045-4fb6-bc32-ca15cfdf7d08
queued 11:08:34 App\Jobs\ScrapeKvK -> scrprstarted 11:10:28 worker=web-01-4879 attempt=1exception 11:10:52 attempt=1 No alive nodes. All the 1 nodes seem to be down.started 11:11:34 worker=web-01-4882 attempt=2completed 11:11:34 memory=58.5MB
Add the Streamable trait to emit custom progress events. emit() needs the job instance, which the framework only sets on classes using InteractsWithQueue, so include it (or extend TorqueJob):
use Illuminate\Bus\Queueable;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Webpatser\Torque\Stream\Streamable; class ImportCsv implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, Streamable; public function handle(): void { foreach ($this->rows as $i => $row) { // process... $this->emit("Imported row {$i}", progress: $i / count($this->rows)); } }}
Read streams programmatically:
use Webpatser\Torque\Stream\JobStream; $stream = app(JobStream::class); // All events so far$events = $stream->events($uuid); // Tail (blocks, yields events as they arrive)foreach ($stream->tail($uuid) as $event) { echo $event['type'] . ': ' . ($event['data']['message'] ?? '');} // Check completion$stream->isFinished($uuid); // true after completed/failed
Streams auto-expire 5 minutes (job_events.ttl) after a terminal event.
Redis Cluster
Set TORQUE_CLUSTER=true on every Redis Cluster install. All Redis keys of a queue are then wrapped in hash tags ({queue-name}) so they land on one cluster slot. Job events use a multi-key script that a cluster rejects with CROSSSLOT without the flag; Torque falls back and logs one warning, but the flag avoids the failed call. Queue names that already contain hash tags are not double-wrapped.
Dashboard
Enable it with TORQUE_DASHBOARD=true and define the gate:
Gate::define('viewTorque', fn (User $user) => $user->isAdmin());
Without a gate Torque falls back to app()->environment('local'), so the dashboard stays locked in production until you define one. The dashboard is served at /torque with the middleware ['web', 'auth']; both are configurable under dashboard.
'dashboard' => [ 'enabled' => true, 'path' => 'torque', 'middleware' => ['web', 'auth', 'can:admin'],],
It is built with Livewire 4 and Blade, with a precompiled dist/torque.css inlined into the layout, so there is no npm step in your application. It offers real-time metrics with a smoothed throughput gauge, 1h / 24h / 7d / 90d history, a workers view, a per-job-class page, a queues view, a failed-jobs list with retry and delete, a per-job inspector, a live feed with tag filter, and a read-only batches page (needs php artisan make:queue-batches-table).
The gate is checked on every dashboard route and again on every Livewire mount and update. Retries from the failed-jobs page only accept targets that exist in config('torque.streams').
Content-Security-Policy
The dashboard works under a strict CSP with a nonce and needs no 'unsafe-eval'. Torque stamps its inline <style> and <script> tags with the nonce from Vite::useCspNonce() or one you set explicitly:
\Webpatser\Torque\Torque::cspNonce($nonce);
If your policy omits 'unsafe-eval', also set 'csp_safe' => true in config/livewire.php so Livewire loads its CSP-safe bundle. The dashboard shows a warning banner and logs one line per hour when the two disagree.
Failed jobs
Jobs that exhaust all retries move to the dead-letter Redis Stream. View them in the dashboard, retry or delete them there or programmatically, or listen for JobPermanentlyFailed:
use Webpatser\Torque\Events\JobPermanentlyFailed; Event::listen(JobPermanentlyFailed::class, function ($event) { // $event->jobName, $event->queue, $event->exceptionMessage, etc. Notification::route('slack', '#alerts')->notify(new YourNotification($event));});
A retry resets attempts, refreshes retryUntil, clears the maxExceptions counter, refuses when the job class no longer exists, and deletes the failed_jobs row (database-uuids failer only).
The stream is bounded by dead_letter.ttl and dead_letter.max_entries. The cap is enforced by the write itself (XADD ... MAXLEN ~), so the real length settles slightly above it. At about 6 KB per entry the default 100000 is roughly 600 MB worst case. The master trims and sweeps stale consumers every dead_letter.prune_interval seconds; run the same pass by hand with torque:prune.
Long-wait alerts
Set a threshold in seconds per queue in config/torque.php; queues you do not list are not checked:
'waits' => ['emails' => 60],
The master checks every 30 seconds. When the oldest waiting job on a queue is older than its threshold, Torque dispatches Webpatser\Torque\Events\LongWaitDetected and sends the notifications once per episode. It repeats after 15 minutes while the queue is still over, or after 5 minutes if the alert failed. Route notifications from a service provider:
Torque::routeSlackNotificationsTo($webhookUrl);
- The event and notifications run in a short-lived child process that boots the app fresh, so register listeners and routes in a service provider.
- One alert can take up to
long_wait_alert_seconds(60), shared across its steps. - Each host's master alerts separately, and a master restart may re-fire once for an ongoing episode.
Tags and silenced jobs
Tags are computed at dispatch on the real job object and stored in the payload. A tags() method wins. Without one, public properties holding an Eloquent model or a collection of models become Model:key tags (App\Models\User:42). Protected properties, arrays and nested objects are not inspected. A job gets at most 50 tags of 191 characters, and ShouldBeEncrypted jobs have none.
Silence jobs whose successes are noise: implement Webpatser\Torque\Contracts\Silenced, list the class under silenced, or list a tag under silenced_tags. A silenced job's success is omitted from the dashboard. Failures are always recorded; metrics and JobProcessed are unaffected.
Circuit breaker
When a stream's dependency dies, every job on it fails permanently and the backlog burns into the dead-letter stream. Once the permanent-failure ratio of a stream's recent outcomes crosses threshold, the stream is no longer polled for cooldown seconds. Other streams keep running. Only permanent failures count as failures; completions count as successes and a retry is neutral. After the cooldown the breaker goes half-open: up to half_open_max jobs are let through, all failing re-opens it, and the first success closes it.
Override per stream, or opt a stream out:
'streams' => [ 'scrpr' => ['circuit_breaker' => ['threshold' => 0.8, 'cooldown' => 600]], 'mail' => ['circuit_breaker' => false],],
State is shared across the fleet through Redis, and an open breaker is expressed as a paused queue, like php artisan queue:pause <name>. Listen for QueueCircuitOpened and QueueCircuitClosed to alert on it, and force one closed with php artisan torque:pause continue or php artisan queue:resume torque:<queue>.
Autoscaling
'autoscale' => [ 'enabled' => true, 'min_workers' => 2, 'max_workers' => 8, 'scale_up_threshold' => 0.85, // Scale up when 85% of slots are busy 'scale_down_threshold' => 0.20, // Scale down when 20% of slots are busy 'cooldown' => 30, // Seconds between scaling decisions],
A fleet below min_workers is grown back to it, one worker per decision, and never past max_workers. No worker is added while the fleet is paused with torque:pause; scale-down continues. torque:status shows a Respawns owed line while failed forks are owed.
Connection pools
Note: At 2.4.0 only
pools.redis.sizetakes effect (the worker's internal Redis pool). The MySQL and HTTP sizes and allidle_timeoutvalues are not read.
'pools' => [ 'redis' => ['size' => 30, 'idle_timeout' => 60], 'mysql' => ['size' => 20, 'idle_timeout' => 60], 'http' => ['size' => 15, 'idle_timeout' => 30],],