Database-per-tenant is the safe way to build a B2B SaaS on Symfony. Every workspace gets its own PostgreSQL database, its own queue and its own bucket, so a missing WHERE tenant_id = ? cannot leak anything and a big customer can be moved to a bigger server by changing a DSN. The usual price is a deployment per tenant: a php-fpm pool, a couple of Messenger workers and a scheduler, always on, whether the tenant is used or not.

That price is fine while every tenant pays. It stops being fine the day you add a free plan. In our case two out of three workspaces had no paid plan, most of them had not been opened in weeks and their always-on processes were the main reason the nodes ran out of memory. Cost grew with the number of tenants, not with their usage and at a few hundred free tenants it would have eaten half the revenue of the paying ones.

The standard fixes trade the isolation away. Merging everything into one database with a tenant_id column means a data migration for every table and a leak waiting for every forgotten filter. A schema per tenant keeps the data apart but needs a search_path per connection, which breaks behind a transaction pooler and still runs N migrations.

This article takes the third road: keep a database per tenant, share the processes. One Symfony 8.1 deployment serves every free tenant placed on it. Each HTTP request and each queued message names its tenant and three small adapters follow that name: a DBAL connection that reconnects to the tenant's database, a cache decorator that namespaces by tenant and a Messenger transport that reads every tenant's stream. The same image still runs a dedicated deployment for paying tenants, with one environment variable flipped. Controllers, handlers and repositories do not change.

We'll build it step by step on a small demo, measure what a tenant switch costs and talk about when you should not do this.

Prerequisites

  • PHP 8.4, Symfony 8.1 (everything here works from 7.3, which introduced cache sub-namespaces), Doctrine ORM 3 with DBAL 4.
  • PostgreSQL 16 and Redis 7 (Docker is enough), symfony/redis-messenger for the tenant streams and symfony/doctrine-messenger for the failure transport.
  • The demo: mattleads/tenant-shared-demo. scripts/demo.sh runs the whole scenario below in about a minute. Every output in this article comes from that script.

1. The tenant and where the code reads it

Everything that used to come from a dedicated deployment's environment is derived from one uuid:

// src/Tenant/Tenant.php final readonly class Tenant { public string $uuid;   public function __construct(string $uuid) { if (!UuidV4::isValid($uuid)) { throw new \InvalidArgumentException(sprintf('"%s" is not a tenant uuid', mb_substr($uuid, 0, 60))); } $this->uuid = strtolower($uuid); }   public function dbName(): string { return 'tenant_'.str_replace('-', '_', $this->uuid); } public function cacheNamespace(): string { return 't_'.$this->uuid; } public function stream(string $suffix = ''): string { return 'tenant-'.$this->uuid.$suffix; } public function pathPrefix(): string { return 'tenant_'.$this->uuid; } } 

The current tenant lives in a static holder:

// src/Tenant/TenantContext.php final class TenantContext { private static ?Tenant $default = null; private static ?Tenant $current = null;   public static function current(): Tenant { return self::$current ?? self::$default ?? throw new NoTenantException('No tenant is set for this request or message'); }   public static function isDefault(Tenant $tenant): bool { return self::$default !== null && self::$default->uuid === $tenant->uuid; }   public static function set(Tenant $tenant): void { self::$current = $tenant; } public static function clear(): void { self::$current = null; } public static function setDefault(?Tenant $tenant): void { self::$default = $tenant; } } 

A static holder is unfashionable and here it is the right tool. The database connection and the cache decorator need the tenant below the level where services are injected and the value is per request or per message, not per service. Injecting a "current tenant" service into a hundred constructors would give you a hundred places that captured the wrong tenant the moment a worker handles two tenants in a row.

Which brings us to the one rule everything else depends on. Read the tenant at call time, never in a constructor and never into a property. A worker keeps its services alive across messages and in shared mode consecutive messages belong to different tenants. In the production codebase this rule is a unit test that scans src/ for constructors touching the tenant.

The $default slot is what makes the dedicated deployment work unchanged. current() never falls back to "some" tenant: on a shared deployment with nothing set, it throws. A request that reaches tenant data without a tenant is a bug and a loud NoTenantException is cheaper than a quiet row in the wrong database.

2. Two modes, one codebase

# .env TENANT_MODE=single # dedicated: this deployment is one tenant TENANT_UUID= # that tenant TENANT_PLACEMENT=shared-1 # shared: which placement this deployment serves 

The kernel sets the default at boot:

// src/Kernel.php public function boot(): void { parent::boot();   SingleTenantResolver::boot( (string) ($_SERVER['TENANT_MODE'] ?? $_ENV['TENANT_MODE'] ?? 'single'), (string) ($_SERVER['TENANT_UUID'] ?? $_ENV['TENANT_UUID'] ?? ''), ); } 

SingleTenantResolver::boot() calls TenantContext::setDefault(new Tenant($uuid)) in single mode and setDefault(null) in multi mode. It is the only class that reads TENANT_UUID. A dedicated deployment therefore runs every request, command and message for its own tenant, exactly as it did before this work. A shared deployment has no default and must be told the tenant each time.

3. HTTP: the tenant is the path prefix

A shared deployment addresses a tenant as /tenant_<uuid>/…. The obvious implementation is a route prefix and it is the wrong one: every path() call in Twig and every generateUrl() would need the tenant parameter. Symfony already has a mechanism for "this app lives under a sub-directory": the request's base URL. Make the prefix the base URL and routing sees the path without it while every generated URL keeps it.

// src/Tenant/TenantPathPrefix.php final class TenantPathPrefix { public const string ATTRIBUTE = '_tenant_prefix'; private const string PATTERN = '#^/tenant_([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?:/|$)#i';   public static function rebase(Request $request): ?Request { if (!preg_match(self::PATTERN, rawurldecode($request->getPathInfo()), $match) || $request->getBaseUrl() !== '') { return null; } $uuid = strtolower($match[1]); $server = $request->server->all(); $server['SCRIPT_NAME'] = $server['PHP_SELF'] = '/tenant_'.$uuid.'/index.php'; $server['SCRIPT_FILENAME'] = ($server['SCRIPT_FILENAME'] ?? '') !== '' ? $server['SCRIPT_FILENAME'] : 'index.php';   $rebased = $request->duplicate(server: $server); $rebased->attributes->set(self::ATTRIBUTE, $uuid);   return $rebased; } } 

Request::getBaseUrl() derives the base from SCRIPT_NAME, so rewriting SCRIPT_NAME to /tenant_<uuid>/index.php is all it takes. The kernel applies it before anything else sees the request:

// src/Kernel.php public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response { if ($type === self::MAIN_REQUEST) { $request = TenantPathPrefix::rebase($request) ?? $request; }   return parent::handle($request, $type, $catch); } 

A listener at priority 2048, ahead of the firewall, turns the prefix into the tenant:

// src/Tenant/TenantRequestListener.php #[AsEventListener(event: KernelEvents::REQUEST, priority: 2048)] public function onRequest(RequestEvent $event): void { if (!$event->isMainRequest()) { return; } $request = $event->getRequest(); $prefix = $request->attributes->get(TenantPathPrefix::ATTRIBUTE);   if ($this->mode === TenantMode::Single) { if (is_string($prefix) && (!TenantContext::has() || TenantContext::current()->uuid !== $prefix)) { throw new NotFoundHttpException('No such tenant here'); }   return; }   TenantContext::clear(); if (!is_string($prefix)) { if (preg_match('#^/health(/|$)#', $request->getPathInfo())) { return; } throw new NotFoundHttpException('No tenant in the path'); } TenantContext::set($this->resolver->resolve($prefix)); }   #[AsEventListener(event: KernelEvents::TERMINATE)] public function onTerminate(TerminateEvent $event): void { TenantContext::clear(); } 

The rules are deliberately strict. On a dedicated deployment a prefix naming another tenant is a 404; a request without a prefix is fine, because its ingress strips it. On a shared deployment a request without a prefix is a 404 unless it is the health check and MultiTenantResolver answers 404 for a tenant that is not placed here. The resolver has no fallback branch.

Run the demo and ask the shared instance who it is for two tenants:

$ curl -s http://127.0.0.1:8770/tenant_11111111-…/whoami {"tenant":"11111111-…","database":"tenant_11111111_1111_4111_8111_111111111111","basePath":"/tenant_11111111-…","notesUrl":"/tenant_11111111-…/notes"}   $ curl -s http://127.0.0.1:8770/tenant_22222222-…/whoami {"tenant":"22222222-…","database":"tenant_22222222_2222_4222_8222_222222222222","basePath":"/tenant_22222222-…","notesUrl":"/tenant_22222222-…/notes"} 

Same process, same controller, no route parameter. notesUrl comes from generateUrl('notes_list') and carries the prefix because it is the base path. The database field is the next section.

4. The database follows the tenant

Doctrine's DBAL has a wrapper_class option: your own subclass of Doctrine\DBAL\Connection, used for the connection service. DBAL calls connect() before every query, which gives us one place to pick the database:

// src/Tenant/TenantConnection.php class TenantConnection extends Connection { private ?string $connectedTo = null;   protected function connect(): DriverConnection { $params = $this->getParams(); $target = $this->databaseFor($params['dbname'] ?? null);   if ($this->_conn !== null) { if ($target === $this->connectedTo) { return $this->_conn; } if ($this->isTransactionActive()) { throw new \LogicException(sprintf('Tenant changed to %s inside a database transaction', TenantContext::current()->uuid)); } $this->close(); }   $params['dbname'] = $target; try { $connection = $this->_conn = $this->driver->connect($params); } catch (Driver\Exception $e) { throw $this->convertException($e); } $this->connectedTo = $target;   if (!$this->isAutoCommit()) { $this->beginTransaction(); }   return $connection; }   private function databaseFor(?string $configured): ?string { $tenant = TenantContext::current();   return TenantContext::isDefault($tenant) ? $configured : $tenant->dbName(); } } 
# config/packages/doctrine.yaml doctrine: dbal: url: '%env(resolve:DATABASE_URL)%' wrapper_class: App\Tenant\TenantConnection 

Three things matter here.

The dedicated deployment is untouched. Its own tenant is the default, so databaseFor() returns the configured dbname from DATABASE_URL. Any other tenant gets tenant_<uuid> on the same server.

A tenant change inside a transaction is a bug, so it throws. Reconnecting would silently commit nothing and lose the first half of the work. If you hit this, the code that opened the transaction is holding a tenant across a boundary it should not cross.

There is one EntityManager. When the tenant changes, the worker clears it (next section), so no entity of tenant A survives into tenant B's message. Metadata and query caches stay global, because the schema is identical in every tenant database. The result cache, if you use one, goes into the tenant namespace like any other application cache.

Post a note to each tenant and read them back:

$ curl -s -X POST -H 'Content-Type: application/json' -d '{"body":"hello from A"}' http://127.0.0.1:8770/tenant_1111…/notes $ curl -s -X POST -H 'Content-Type: application/json' -d '{"body":"hello from B"}' http://127.0.0.1:8770/tenant_2222…/notes   $ curl -s http://127.0.0.1:8770/tenant_1111…/notes [{"id":2,"body":"hello from A","processedAt":"2026-11-09T20:36:49+00:00","processedBy":"MacBookPro16.local:95790"}] $ curl -s http://127.0.0.1:8770/tenant_2222…/notes [{"id":1,"body":"hello from B","processedAt":"2026-11-09T20:36:49+00:00","processedBy":"MacBookPro16.local:95790"}] 

The ids overlap because the rows live in different databases. processedBy is the same worker pid for both and that worker is the subject of section 6.

5. The cache follows the tenant

Application caches hold tenant data: computed stats, rendered fragments, the scheduler's last-run state. Since Symfony 7.3 every cache adapter implements NamespacedPoolInterface, so a decorator can hand each tenant a sub-namespace of the same pool:

// src/Tenant/TenantAwareCache.php final class TenantAwareCache implements AdapterInterface, CacheInterface, NamespacedPoolInterface, ResettableInterface { /** @var array<string, AdapterInterface&CacheInterface&NamespacedPoolInterface> */ private array $byTenant = [];   public function __construct(private readonly AdapterInterface&CacheInterface&NamespacedPoolInterface $inner) { }   private function pool(): AdapterInterface { $tenant = TenantContext::current(); if (TenantContext::isDefault($tenant)) { return $this->inner; }   return $this->byTenant[$tenant->uuid] ??= $this->inner->withSubNamespace($tenant->cacheNamespace()); }   public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed { return $this->pool()->get($key, $callback, $beta, $metadata); }   // getItem(), save(), deleteItem(), … all delegate to $this->pool()   public function reset(): void { foreach ([$this->inner, ...array_values($this->byTenant)] as $pool) { if ($pool instanceof ResettableInterface) { $pool->reset(); } } $this->byTenant = []; } } 
# config/services.yaml services: App\Tenant\TenantAwareCache: decorates: cache.app arguments: ['@.inner'] 

Again the dedicated deployment's keys do not change, so its caches stay warm through the deploy that introduces this.

One trap with tag-aware pools. Symfony stores tags in the pool's root namespace, shared by every sub-namespace. If tenant A invalidates the tag product_list, it drops tenant B's product_list entries too. Prefix the tags with the tenant namespace as well as the keys. The demo's pool has no tags; the production one does and this is where its decorator differs from the one above.

Caches that are platform-wide by design, such as a revoked-tokens list that other services write, must not be decorated. Decide per pool and write the decision down next to the pool.

6. Workers: one process, every tenant's stream

This is where most multitenancy write-ups stop and where most of the cost sits. A dedicated deployment runs its own messenger:consume processes against its own Redis stream. We want a shared worker to read every placed tenant's stream, without changing the senders: other services push into tenant-<uuid> streams today and they should keep doing exactly that.

The transport keeps its name. Only its DSN changes with the mode:

# config/packages/messenger.yaml framework: messenger: failure_transport: failed transports: async: dsn: '%env(MESSENGER_TRANSPORT_DSN)%' # redis://…/tenant-<uuid> or tenant-multi://…?kind=main options: { consumer: '%env(MESSENGER_CONSUMER_NAME)%', redeliver_timeout: 300, claim_interval: 30000 } retry_strategy: { max_retries: 2, delay: 1000 } failed: 'doctrine://default?queue_name=failed' routing: 'App\Message\NoteCreated': async 'App\Message\SlowJob': async 

Routing, #[AsMessageHandler(fromTransport: 'async')] and the messenger:consume async command line are identical in both modes. A custom transport factory claims the tenant-multi:// scheme and builds this:

// src/Tenant/Messenger/MultiTenantTransport.php (abridged) final class MultiTenantTransport implements TransportInterface, KeepaliveReceiverInterface, MessageCountAwareInterface { /** @var array<string, array{RedisReceiver, RedisSender}> */ private array $byTenant = []; private ?\Redis $redis = null; private int $next = 0;   public function get(int $fetchSize = 1): iterable { $tenants = $this->placement->tenants(); $count = count($tenants); for ($i = 0; $i < $count; ++$i) { $uuid = $tenants[($this->next + $i) % $count]; if ($this->fairUse !== null && !$this->fairUse->canTake($uuid, $this->kind)) { continue; } foreach ($this->receiver($uuid)->get() as $envelope) { $this->next = ($this->next + $i + 1) % $count; $this->fairUse?->took($uuid, $this->kind);   return [$envelope->withoutAll(TenantStamp::class)->with(new TenantStamp($uuid))]; } }   return []; }   public function ack(Envelope $envelope): void { $uuid = $this->tenantOf($envelope); try { $this->receiver($uuid)->ack($envelope); } finally { $this->fairUse?->done($uuid, $this->kind); } }   public function send(Envelope $envelope): Envelope { $uuid = $envelope->last(TenantStamp::class)?->tenant ?? TenantContext::current()->uuid;   return $this->pair($uuid)[1]->send($envelope->withoutAll(TenantStamp::class)); }   private function pair(string $uuid): array { if (!isset($this->byTenant[$uuid])) { $dsn = rtrim($this->redisDsn, '/').'/'.$this->streamFor($uuid); $connection = Connection::fromDsn($dsn, $this->options, $this->redis ??= new \Redis()); $this->byTenant[$uuid] = [new RedisReceiver($connection, $this->serializer), new RedisSender($connection, $this->serializer)]; }   return $this->byTenant[$uuid]; } } 

Three decisions and why.

Reuse Symfony's RedisReceiver per tenant instead of writing a multi-stream XREADGROUP. Consumer-group creation, claiming of entries a dead worker left pending, ack, reject and keepalive then behave exactly as on a dedicated deployment and they are tested by Symfony, not by us. All the receivers share one phpredis client, so the connection count does not grow with tenants.

Rotate the starting tenant. $this->next moves past the tenant that just delivered, so a tenant with a deep backlog cannot starve the others out of a worker that polls in order.

Stamp the tenant from the stream name, nowhere else. The stream a message came from is the one trustworthy tenant id, because the sender chose it from the tenant's uuid. TenantStamp is added on receive and stripped on send; it never crosses the wire.

The worker side is a listener on three Messenger events:

// src/Tenant/Messenger/TenantWorkerListener.php #[AsEventListener(priority: 1024)] public function onReceived(WorkerMessageReceivedEvent $event): void { $stamp = $event->getEnvelope()->last(TenantStamp::class); if ($stamp === null) { return; // dedicated deployment: nothing to do } if ($this->last !== null && $this->last !== $stamp->tenant) { $this->em->clear(); // no entity of the previous tenant survives } $this->last = $stamp->tenant; TenantContext::set(new Tenant($stamp->tenant)); }   #[AsEventListener(priority: -1024)] public function onHandled(WorkerMessageHandledEvent $event): void { $this->leave($event->getEnvelope()); }   #[AsEventListener(priority: -1024)] public function onFailed(WorkerMessageFailedEvent $event): void { $this->leave($event->getEnvelope()); } 

The priorities are the point. Messenger's own retry and failure listeners run at 100 and -100. Setting the tenant at 1024 and clearing it at -1024 means a retry is sent back to that tenant's stream and a failed message is written to that tenant's messenger_messages table, because doctrine://default resolves through TenantConnection while the tenant is still set. The demo proves it with a job that always throws:

$ curl -s -X POST -H 'Content-Type: application/json' -d '{"seconds":1,"label":"fail"}' http://127.0.0.1:8770/tenant_2222…/jobs [warning] Error thrown while handling message App\Message\SlowJob. Sending for retry #1 using 900 ms delay. [warning] Error thrown while handling message App\Message\SlowJob. Sending for retry #2 using 1906 ms delay. [critical] Error thrown while handling message App\Message\SlowJob. Removing from transport after 2 retries.   $ bin/console app:tenant:failed 22222222-… show There are 2 messages pending in the failure transport. Id Class Failed at Error 1 App\Message\SlowJob 2026-11-09 20:40:40 This job always fails, to show where failures land 

Tenant A's database has no messenger_messages table at all, because nothing of A ever failed. app:tenant:failed is twelve lines: set the tenant, run Symfony's messenger:failed:show|retry|remove, clear the tenant.

7. Fair use: a busy free tenant waits, the others do not

Sharing workers means sharing a budget. Without a limit, one tenant's automation that queues ten thousand messages holds every worker for an hour and the other ninety-nine tenants on the deployment notice. The rule we settled on is a cap per tenant and stream kind: at most TENANT_INFLIGHT_CAP messages of a tenant being handled at once across all shared workers. The rest wait on that tenant's own stream. Nothing is dropped, nothing fails and the paying tenants are on dedicated deployments anyway.

// src/Tenant/Messenger/FairUse.php (abridged) public function canTake(string $tenant, string $kind): bool { return (int) $this->redis()->get($this->key($tenant, $kind)) < $this->cap; }   public function took(string $tenant, string $kind): void { $key = $this->key($tenant, $kind); $this->redis()->incr($key); $this->redis()->expire($key, 180); }   public function done(string $tenant, string $kind): void { if ($this->redis()->decr($this->key($tenant, $kind)) <= 0) { $this->redis()->del($this->key($tenant, $kind)); } } 

get() skips a tenant at its cap, ack() and reject() release the slot, keepalive() refreshes the key's TTL while a long handler runs. The demo queues four 4-second jobs for tenant A and posts a note for tenant B half a second later, with two shared workers and a cap of 1:

B note created 20:37:28, processed 20:37:28 by MacBookPro16.local:95981 in flight for A right now: 1 [20:37:32] slow job A-1 for tenant 11111111 done by pid 95790 [20:37:36] slow job A-2 for tenant 11111111 done by pid 95790 [20:37:40] slow job A-3 for tenant 11111111 done by pid 95790 [20:37:44] slow job A-4 for tenant 11111111 done by pid 95790 

B's note was handled in the same second by the second worker. A's jobs ran one at a time on the first, 16 seconds for the burst, while a worker stayed free for everyone else.

The trade-off is in that expire(…, 180). A worker that dies between took() and done() leaves the slot taken until the key expires, so that tenant's queue pauses for up to three minutes. The alternative, a lease per message with a heartbeat, costs more Redis traffic per poll than the cap saves. We took the three minutes and run workers with --keepalive so a long legitimate message keeps its slot alive.

8. Placement: which tenants live here

A shared deployment needs to know its tenants and a tenant needs to be movable between placements without redeploying anything. A Redis hash does both: tenant:placement maps each uuid to a placement name, shared-1, shared-2 or dedicated. The service that creates tenants and handles plan changes writes it; the deployments only read it.

// src/Tenant/PlacementReader.php (abridged) public function tenants(): array { if (!$this->isFresh()) { // at most every 30 s $hash = $this->redis()->hGetAll(self::KEY) ?: []; $this->tenants = array_keys(array_filter($hash, fn ($v) => $v === $this->placement)); sort($this->tenants); $this->readAt = time(); }   return $this->tenants; }   public function serves(string $tenantUuid): bool { if ($this->isFresh()) { return in_array(strtolower($tenantUuid), $this->tenants, true); }   return $this->redis()->hGet(self::KEY, strtolower($tenantUuid)) === $this->placement; } 

Workers call tenants() and amortise one HGETALL over 30 seconds of polling. A php-fpm request starts with an empty process and asks about one tenant with one HGET, because reading the whole registry per request would cost a call per placed tenant.

Moving a tenant is a change of one hash field. Its streams keep their names, so senders notice nothing; the workers of the new placement start reading them within 30 seconds and the entries the old workers left pending are claimed after redeliver_timeout, the same way a rolling deploy already behaves. Its database and bucket do not move at all.

9. Migrations: every tenant, one process each

A release must migrate every placed tenant's database before the new pods start. The obvious loop, "for each tenant, set the context, run the migrator", shares one process across tenants and a migration that fails half-way for tenant 17 leaves the process in a state you do not want tenant 18 to inherit.

So each tenant gets its own process, running as a dedicated deployment of that tenant:

// src/Command/TenantsMigrateCommand.php (abridged) $running[$uuid] = Process::fromShellCommandline( 'bin/console doctrine:database:create --if-not-exists -n && bin/console doctrine:migrations:migrate -n --allow-no-migration', $this->projectDir, ['TENANT_MODE' => 'single', 'TENANT_UUID' => $uuid, 'DATABASE_URL' => $this->tenantDatabaseUrl($uuid)], ); 

The child sees TENANT_MODE=single and a plain DATABASE_URL pointing at tenant_<uuid>, so Doctrine's own commands run untouched and --concurrency bounds how many run at once:

$ bin/console app:tenants:migrate --concurrency=3 11111111-… started 22222222-… started 33333333-… started 11111111-… migrated 22222222-… migrated 33333333-… migrated 3 tenant(s), 0 failed, 1.1 s 

A failed tenant is reported and the others continue. In production the command also writes a migration-blocked:<uuid> flag that the request resolver turns into a 503 for that tenant alone, until a later run succeeds.

10. What it costs and when not to do this

The tenant switch is a reconnect. app:bench:switch runs SELECT 1 three hundred times on one tenant, then three hundred times alternating tenants, against Postgres in Docker on a laptop:

300 queries on one tenant: 0.199 ms per query 300 queries switching tenant each time: 6.474 ms per query (299 reconnects) cost of a tenant switch: 6.27 ms 

Six milliseconds per switch. A web request switches at most once, at its first query, so it pays a connection it would have paid anyway under php-fpm. A worker pays it on every message whose tenant differs from the previous one, which with the rotation in section 6 is most messages. For free tenants doing a few hundred background jobs an hour that is noise. If your shared tenants process thousands of messages a minute, add a small per-worker pool of open connections keyed by database before reaching for PgBouncer, whose transaction mode you would have to check against advisory locks and session settings first.

Memory is where the saving is. In dev mode on PHP 8.4 a Messenger worker of this demo sits at 49 to 65 MB RSS and a web process at 42 to 55 MB. A dedicated deployment needs its own set of those per tenant, idle or not. A shared deployment needs one set per placement. With a hundred idle free tenants the difference is a hundred sets of always-on processes against one.

Do not do this when:

  • Tenants need cross-tenant transactions. TenantConnection refuses a switch inside a transaction on purpose. If your domain needs to write to two tenants atomically, you have one tenant.
  • A tenant's traffic justifies its own deployment. That is what the dedicated placement is for. Paying tenants stayed dedicated in our rollout and a burst on the free deployment cannot touch them.
  • Your services already hold tenant-specific state in constructors. Count them first. In the production codebase it was 31 classes and five constructor queries and the scan test keeps them from coming back.

11. Testing it

The multi-mode bugs that reached our production did so because tests used in-memory transports and asserted what was dispatched, not where it landed. The demo's test boots the real kernel in multi mode against two real tenant databases and reads the result back through HTTP:

// tests/TwoTenantIsolationTest.php (abridged) public function testEachTenantReadsItsOwnDatabase(): void { $client = static::createClient(); $body = 'isolation '.bin2hex(random_bytes(4));   $client->jsonRequest('POST', '/tenant_'.self::A.'/notes', ['body' => $body]); self::assertResponseStatusCodeSame(201);   $client->request('GET', '/tenant_'.self::A.'/notes'); self::assertStringContainsString($body, (string) $client->getResponse()->getContent());   $client->request('GET', '/tenant_'.self::B.'/notes'); self::assertStringNotContainsString($body, (string) $client->getResponse()->getContent()); } 

Use the real messenger.yaml, the real bus and routing and assert the destination: the row in the tenant's table, the entry in the tenant's stream, the failed message in the tenant's messenger_messages. A test that checks a stamp on an envelope will pass while a worker writes into the wrong database.

Conclusion

Each piece above is a decision you can take separately.

  • A static TenantContext with a default for dedicated deployments and no fallback for shared ones lets one codebase run both ways and turns "wrong tenant" into an exception instead of a row.
  • The base URL carries the tenant on HTTP, so routes and generated URLs do not change.
  • A DBAL wrapper_class and a cache decorator make the database and the cache follow the tenant with no change to repositories or services.
  • A Messenger transport that wraps one RedisReceiver per tenant keeps every sender and every handler unchanged and the listener priorities keep retries and failures inside the tenant.
  • A per-tenant in-flight cap is enough fair use for free tenants; dedicated deployments are the fair use for paying ones.

If you run database-per-tenant Symfony and most of your tenants are idle, start with the connection wrapper and the request listener, put two test tenants behind one php-fpm pool and measure. The workers are the second step and the bigger saving.

Next in this series. The shared deployment above still boots a kernel and opens the tenant's database connection on every request, because php-fpm forgets everything between requests. Part 2 moves the same demo to FrankenPHP worker mode, keeps one open connection per tenant database inside each worker and measures both against php-fpm under a load that changes tenant on every request. It will be published later, with the code in the same repository.

Source Code: You can find the full implementation and follow the project's progress on GitHub in Part 2.

Let's Connect!

If you found this helpful or have questions about the implementation, I'd love to hear from you. Let's stay in touch and keep the conversation going across these platforms:

  • LinkedIn: https://www.linkedin.com/in/matthew-mochalkin/
  • X (Twitter): https://x.com/MattLeads
  • Telegram: https://t.me/MattLeads
  • GitHub: https://github.com/mattleads