How do I run queues in a multi-tenant app without leaking tenant context?
Laravel multi-tenant queues stay safe when every job rebuilds its own tenant environment from the tenant ID it carries. A queue worker has no request, subdomain, or logged-in user to identify the tenant. It also handles jobs for many tenants, one after another, in the same long-lived process.
Quick answer
Store the tenant ID in the job, restore that tenant before any tenant-specific code runs, and reset it when the job ends. Laravel’s Context facade can carry the ID from dispatch to worker, but it does not switch databases, cache prefixes, or query scopes. Your own code, or a package such as stancl/tenancy or spatie/laravel-multitenancy, has to do that. Test by running Tenant A, Tenant B, and a central job back to back on one worker.
Why do queued jobs leak tenant context in Laravel?
Laravel’s queue documentation describes workers as long-lived processes that keep the booted application in memory. It also notes that static state your code creates or changes is not reset between jobs. A daemon worker does not reboot the framework before each job. One job’s tenant can become the next job’s tenant.
That produces two failure modes. In one, a job runs with no tenant and reads the central database. In the other, it inherits the previous job’s tenant and touches another customer’s data. The second case is the dangerous one because nothing throws an error.
How do you run Laravel multi-tenant queues without leaking tenant context?
Step 1: Carry the tenant ID with the job
Laravel’s Context facade captures data when you dispatch a job and hydrates it back into the context while the job executes. Add the tenant ID in the middleware that identifies the tenant.
use Illuminate\Support\Facades\Context;
Context::add('tenant_id', $tenant->getKey());
Context only moves data. It does not initialise a tenant database, a connection, a cache prefix, or a query scope. That work happens in step 2.
Visible context values are appended to log entries as metadata, which helps when you trace a tenant’s jobs. To keep the ID out of log metadata, use Context::addHidden() and read it with hasHidden() and getHidden(). Hidden values still travel to the job. Step 3 shows the alternative of passing the ID as a constructor property.
Step 2: Restore the tenant before the job runs
Laravel does not restore a tenant for you. The examples use a TenantManager class that you write yourself. Its currentId(), switchTo(), and reset() methods are application-defined, not Laravel built-ins. They stand in for whatever your app does to switch connections, cache prefixes, and scopes.
Register a hydrated callback in AppServiceProvider::boot(). It switches to the tenant when an ID exists and resets to the central context when none does. Use the repository passed into the callback, because the documentation advises against calling the Context facade inside it.
use Illuminate\Log\Context\Repository;
use Illuminate\Support\Facades\Context;
Context::hydrated(function (Repository $context): void {
$tenants = app(TenantManager::class);
if ($context->has('tenant_id')) {
$tenants->switchTo($context->get('tenant_id'));
} else {
$tenants->reset();
}
});
Make switchTo() throw when the tenant is unknown or unavailable. A failed lookup must never fall back to the central database or to another tenant. Your tests in step 6 should confirm that such a job fails.
Step 3: Use job middleware when you need per-job control and cleanup
Job middleware is the second way to restore a tenant. The job carries a tenant ID, and the middleware wraps its execution and restores the previous tenant afterward.
use Closure;
class RestoreTenant
{
public function __construct(private int|string $tenantId) {}
public function handle(object $job, Closure $next): mixed
{
$tenants = app(TenantManager::class);
$previous = $tenants->currentId();
try {
// Throws if the tenant no longer exists or is unavailable.
$tenants->switchTo($this->tenantId);
return $next($job);
} finally {
$previous === null
? $tenants->reset()
: $tenants->switchTo($previous);
}
}
}
Attach it from the job:
public function __construct(public int|string $tenantId) {}
public function middleware(): array
{
return [new RestoreTenant($this->tenantId)];
}
The example has no separate existence check. A check followed by a switch leaves a gap, because the tenant can be deleted or suspended between the two calls. Putting the lookup inside switchTo() closes it. If it throws, the job fails through Laravel’s normal retry rules and the finally block restores the previous context.
Cleanup matters because a worker reuses its process. It also matters for dispatchSync(), which Laravel runs inside the caller’s process. Without the restore, a synchronous job would wipe the dispatching code’s tenant.
A job’s failed() method runs on a new job instance, according to the Laravel documentation. Do not assume the tenant is active there. Restore it explicitly if the method touches tenant data.
Step 4: Load tenant-scoped models after the tenant is restored
Laravel serializes only an Eloquent model’s identifier when you pass a model to a job. It restores the model from the database when it unserializes the job. In Laravel’s queue handler, that happens before job middleware runs and before handle() is called. A tenant-scoped model in the constructor is therefore queried before your middleware can restore the tenant.
If the tenant connection or scope is not active at that point, the query can fail or hit the wrong database. Pass the model’s ID, and load the model inside handle() after the tenant is restored. That removes any dependency on restore ordering.
Step 5: Switch every other tenant-specific resource
The database connection is the obvious part. The leaks that survive code review are quieter:
- Cache: use tenant-prefixed keys or a tenant-scoped store, and never cache tenant data under a global key.
- Filesystem: resolve disks and paths per tenant at run time, inside the job.
- Static properties and singletons: anything a service stores in a static property or a container singleton survives until the worker exits.
- Runtime config: values such as mail or payment credentials stay set until you restore them.
Your TenantManager or tenancy package should switch and restore all of these together. Separate queues or worker pools can help with uneven tenant workloads, but they do not replace restoring context inside each job.
Step 6: Test consecutive jobs on one worker
Run a single queue:work process and dispatch jobs in this order. Each scenario should pass on its own and when run back to back.
- Tenant A’s job runs successfully.
- Tenant B’s job runs immediately afterwards on the same worker and sees only Tenant B’s data.
- A central job runs after a tenant job and does not inherit the tenant context.
- Tenant A’s job fails, and Tenant B’s job that follows still runs correctly.
- A job for a deleted or unavailable tenant fails and never runs against the central database or another tenant’s data.
- A failed job is retried from the failed jobs table and runs with the correct tenant context.
Inside each job, assert the active database connection, the cache prefix, and the storage path. Checking the current tenant ID alone is not enough, because the ID can be right while a connection or prefix is stale. Keep these tests in your automated suite so a new static property cannot reintroduce the leak unnoticed.
What do stancl/tenancy and spatie/laravel-multitenancy handle for you?
Both packages provide their own tenant-aware queue mechanisms. These are package features, not Laravel core, and each package documents its own setup.
stancl/tenancy
With its QueueTenancyBootstrapper enabled, jobs dispatched from a tenant context become tenant-aware. The jobs are stored centrally, and tenancy is initialised for the tenant before each job is processed.
- With the database queue driver and DatabaseTenancyBootstrapper, point the queue connection at your central database.
- With the redis queue driver and RedisTenancyBootstrapper, keep the queue’s connection out of
tenancy.redis.prefixed_connections. - Jobs dispatched from the central context stay central. The documentation recommends separate queue connections for central and tenant jobs, because leftover global state can make a central job think it is in the previous tenant’s context.
spatie/laravel-multitenancy
With its tenant-aware queue setting, the package tracks the current tenant when a job is dispatched and makes it current inside the job.
- Set
queues_are_tenant_aware_by_defaulttotrue, or set it tofalseand mark jobs with theTenantAwareorNotTenantAwareinterfaces. A job that is not tenant-aware runs without a current tenant. - If a tenant-aware job cannot retrieve its tenant, for example because the tenant was deleted, it fails with a
CurrentTenantCouldNotBeDeterminedInTenantAwareJobexception. - After a job finishes, including on failure, the dispatching code gets its previous tenant back. This covers
dispatchSync().
Where to start
Run the six scenarios from step 6 against your current setup before you change anything. They show whether your Laravel multi-tenant queues already restore the right tenant and which resources still leak. If you are designing tenant isolation, Stagebit’s Laravel development team can review your queue setup with you.
Related Answers
Still need help?
Questions about tenant context in your Laravel queues?
If you're checking whether your queue workers restore the right tenant for every job, we're happy to walk through what you're seeing and what your options are.
