Parts one and two of this series put many tenant databases behind one Symfony deployment: each request and each queued message names its tenant, a DBAL connection wrapper follows it, and a shared worker handles messages of every tenant placed on the deployment. Then Symfony 8.2 shipped messenger:consume --concurrency, and the two shared workers of the demo became one worker with four children.

The first run retried every message. The handlers saw no tenant, because the listener that sets it runs in the parent process, and the handlers now run in children. That was the easy one. The harder ones came with the numbers: on a cold worker, tenant A's twenty-second job held tenant B's one-second job for 21 seconds while three children idled, and a batch handler marked rows in tenant B's database with the ids of tenant A's notes.

This article walks through what --concurrency moved where, what that does to tenant context, connections, probes and batches, with a reproduction on the demo repository, and ends with the decisions a shared deployment has to make before it turns the option on.

Prerequisites

  • PHP 8.4 (tested on 8.4.22)
  • symfony/messenger 8.2.0 and amphp/parallel, which --concurrency requires
  • The demo from parts one and two: mattleads/tenant-shared-demo, Doctrine DBAL 4, PostgreSQL 16 and Redis 7 in Docker, three tenants placed on one shared deployment
  • scripts/concurrency.sh runs the four scenarios below in about three minutes and writes results/concurrency.txt

1. What moved where

Without --concurrency, Worker::run() fetches a message, dispatches it on the bus, and acks it, all in one process. With --concurrency=4, the parent keeps the fetching, the acks and the retries, and hands each envelope to a ParallelExecutionStrategy, which owns a pool of four amphp workers. Each child is a PHP process that boots the application through bin/console, receives envelopes over a channel, dispatches them on the bus, and sends the handled envelope back.

The split runs through the middle of the worker's event flow. Worker::handleMessage() dispatches WorkerMessageReceivedEvent in the parent, before the strategy sees the envelope. WorkerMessageHandledEvent and WorkerMessageFailedEvent fire in the parent too, when the child's answer arrives and the parent acks or retries. The bus middleware and the handlers run in the child. Anything an application carries from a worker event to a handler, through a static, a request stack or a service property, does not cross that line.

The demo carried exactly that. MultiTenantTransport reads every tenant's Redis stream in rotation and adds a TenantStamp to each envelope it returns. TenantWorkerListener reads the stamp on WorkerMessageReceivedEvent and sets the tenant in TenantContext, which TenantConnection reads before every query to pick the database. On a parallel worker the stamp travels to the child with the envelope; the listener does not.

2. The tenant must travel with the envelope

The log of the first run, two notes posted for tenants A and B to a --concurrency=2 worker:

[info] Received message App\Message\NoteCreated [warning] Error thrown while handling message App\Message\NoteCreated. Sending for retry #1 using 1015 ms delay. Error: "Handling "App\Message\NoteCreated" failed: No tenant is set for this request or message" [info] Received message App\Message\NoteCreated [warning] Error thrown while handling message App\Message\NoteCreated. Sending for retry #1 using 930 ms delay. Error: "Handling "App\Message\NoteCreated" failed: No tenant is set for this request or message" 

TenantContext::current() throws on a shared deployment when nothing set a tenant, on purpose: falling back to some tenant would be worse. The parent had set it, in its own memory. The fix is a middleware that reads the stamp in the process that runs the handlers:

// src/Tenant/Messenger/TenantMiddleware.php final class TenantMiddleware implements MiddlewareInterface { private ?string $last = null;   public function __construct(private readonly EntityManagerInterface $em) { }   public function handle(Envelope $envelope, StackInterface $stack): Envelope { $stamp = $envelope->last(TenantStamp::class); if ($stamp === null) { return $stack->next()->handle($envelope, $stack); } if ($this->last !== null && $this->last !== $stamp->tenant) { $this->em->clear(); } $this->last = $stamp->tenant; TenantContext::set(new Tenant($stamp->tenant)); try { return $stack->next()->handle($envelope, $stack); } finally { TenantContext::clear(); } } } 
# config/packages/messenger.yaml framework: messenger: buses: messenger.bus.default: middleware: - App\Tenant\Messenger\TenantMiddleware 

The stamp is only present on a received envelope, so the middleware does nothing on dispatch. It clears the entity manager when the tenant changes, as the listener did, because an identity map full of tenant A's entities must not serve tenant B's queries.

The listener stays. The retry listener and the failure listener run in the parent, on WorkerMessageFailedEvent, and the demo's failure transport is doctrine://default, which lands in the tenant's own messenger_messages table only while that tenant is set. So the parent needs the tenant for its sends, and the child needs it for the handlers. One stamp, read twice, in two processes. Without --concurrency both run in the same process and set the same value.

With the middleware, each note lands in its own tenant's database, handled by two different children:

07:38:18 pid=87417 tenant=11111111 note 48 connects=1 open=1 07:38:19 pid=87419 tenant=22222222 note 46 connects=1 open=1 

The lines come from a one-line log the demo's handlers write: UTC time, the pid of the process that handled the message, the tenant, what was done, how many driver connections that process has opened so far, and how many databases it keeps open.

3. What the per-message reset keeps

A child resets the container's services after every message, as a plain worker does, through services_resetter. Part two made TenantConnection keep up to sixteen open connections, one per tenant database, so that a switch back to a tenant it has seen is free instead of a reconnect that part one measured at about 6 ms. The question was whether the reset closes them.

It does not. Doctrine's reset clears the entity manager and keeps the DBAL connection. Six notes over three tenants, handled by one child with tenantConnections=16:

07:38:25 pid=87513 tenant=11111111 note 49 connects=1 open=1 07:38:25 pid=87513 tenant=22222222 note 47 connects=2 open=2 07:38:25 pid=87513 tenant=33333333 note 39 connects=3 open=3 07:38:25 pid=87513 tenant=11111111 note 50 connects=3 open=3 07:38:25 pid=87513 tenant=22222222 note 48 connects=3 open=3 07:38:25 pid=87513 tenant=11111111 note 51 connects=3 open=3 

Three connections for six messages, and the same run without the option opens six. The kept connections are per child, so a pool of four children keeps up to four times sixteen. Size the Postgres side for that, or lower the number: the limit that matters is connections per database server, and a pool multiplies it.

4. One probe for every tenant

The parallel worker cannot know whether a handler batches until it has run one message of that class, so the first message of every bus, transport and class combination runs alone, as a probe, and the strategy holds the next messages of that key until the probe returns. The held messages count towards --concurrency. The affinity key is bus, transport and class. It knows nothing about tenants.

On a shared deployment every tenant's messages of one class share that key. Scenario three posts, on a cold --concurrency=4 worker, a twenty-second job for tenant A, then one-second jobs for tenants B and C and a note for tenant B, then the same load again when the worker is warm:

Message Posted Started, cold Started, warm SlowJob(20) tenant A 0 s 0 s 0 s SlowJob(1) tenant B 0 s 21 s 0 s SlowJob(1) tenant C 0 s 21 s 0 s NoteCreated tenant B 0 s 23 s 2 s 

Cold, B's and C's jobs are held for the whole of A's probe, with three children idle. That is the per-class hold of the parallel worker, measured in the previous article on one tenant; here one tenant pays for all of them, and the tenant with the slow first message decides who waits.

The note is the shared deployment's own contribution. NoteCreated is another class, with its own key, and nothing held it. What held it was the fair-use cap of part one: TENANT_INFLIGHT_CAP=1 lets each tenant have one message in flight, the transport counts a message as in flight from the moment the parent reads it, and B's held job was in flight for 21 seconds without a child touching it. B's note waited on B's job, which waited on A's job. Warm, the same note waits 2 seconds, which is B's job running.

Two decisions follow. A slow class belongs on its own transport and its own messenger:consume, as the previous article argued for one tenant; the demo's second stream kind, reports, exists for this. And a cap that counts held messages is a cap on waiting, not on handling. The transport cannot tell a held message from a running one, because holding happens in the strategy after the read. The cap is still right for what it was built for, one tenant flooding every worker; it is wrong for the probe, and the only answer to the probe is the first decision.

5. A batch that crosses tenants

Part three adds IndexNote, dispatched with every note and handled in batches of ten, one UPDATE note SET indexed_at = NOW() WHERE id IN (...) per flush. The first version was the textbook one:

#[AsMessageHandler] final class IndexNotesHandler implements BatchHandlerInterface { use BatchHandlerTrait;   public function __invoke(IndexNote $message, ?Acknowledger $ack = null): mixed { return $this->handle($message, $ack); }   private function process(array $jobs): void { $ids = array_map(static fn (array $job) => $job[0]->noteId, $jobs); $this->connection->executeStatement('UPDATE note SET indexed_at = NOW() WHERE id IN (?)', [$ids], [ArrayParameterType::INTEGER]); foreach ($jobs as [, $ack]) { $ack->ack(); } } } 

A batching class is pinned to one child, busy or not, because the batch lives in that child's memory. On a shared deployment that child's batch holds messages of every tenant. The flush ran when the worker stopped, and the log says under which tenant:

07:28:47 pid=61977 tenant=11111111 note 32 connects=1 open=1 07:28:47 pid=61977 tenant=33333333 note 28 connects=2 open=2 07:28:47 pid=61993 tenant=22222222 note 33 connects=1 open=1 07:28:58 pid=61977 tenant=22222222 indexed 32,28,33 connects=3 open=3 

One UPDATE, in tenant B's database, with A's note 32, C's note 28 and B's note 33. Every tenant database has a note 32 and a note 28, because every tenant numbers its own rows from one. Tenant B's database afterwards:

tenant 22222222: 28 park INDEXED | 32 during warm probe INDEXED | 33 index me INDEXED | 34 index me 

Two of B's unrelated notes marked as indexed, A's and C's notes not marked at all, no error anywhere. That is the failure mode a database-per-tenant design exists to make impossible, and a batch handler plus a shared worker produced it in one flush.

The mechanism is in the child's DispatchTask. A flush is not a call on the handler; it is a dispatch on the bus of one of the batched envelopes, with a FlushBatchHandlersStamp, so that the middleware stack runs and HandleMessageMiddleware calls flush() on the batch handlers that envelope names. The envelope carries one tenant's stamp, TenantMiddleware sets that tenant, and BatchHandlerTrait::flush() processes the whole batch under it. The same happens on a plain worker when a flush is triggered by a full batch inside __invoke(): the current tenant is the tenth message's. With a worker event setting the context and nothing clearing it in the child, the tenant would be whichever message ran last. Either way, the batch runs under one tenant and holds several.

The fix is to remember, for each message, the tenant it arrived for, and to replay it per group when the batch flushes:

#[AsMessageHandler] final class IndexNotesHandler implements BatchHandlerInterface { private const int BATCH_SIZE = 10;   /** @var list<array{IndexNote, Acknowledger, string}> The message, its ack and the tenant it arrived for */ private array $jobs = [];   public function __invoke(IndexNote $message, ?Acknowledger $ack = null): mixed { $tenant = TenantContext::current()->uuid; if ($ack === null) { $this->index($tenant, [$message->noteId]);   return null; } $this->jobs[] = [$message, $ack, $tenant]; if (\count($this->jobs) >= self::BATCH_SIZE && !$ack->deferFlush()) { $this->flush(true); }   return \count($this->jobs); }   public function flush(bool $force): void { if (!$force && \count($this->jobs) < self::BATCH_SIZE) { return; } $byTenant = []; foreach ($this->jobs as [$message, $ack, $tenant]) { $byTenant[$tenant][] = [$message, $ack]; } $this->jobs = [];   $previous = TenantContext::has() ? TenantContext::current() : null; try { foreach ($byTenant as $tenant => $group) { TenantContext::set(new Tenant($tenant)); try { $this->index($tenant, array_map(static fn (array $job) => $job[0]->noteId, $group)); foreach ($group as [, $ack]) { $ack->ack(); } } catch (\Throwable $e) { foreach ($group as [, $ack]) { $ack->nack($e); } } } } finally { $previous !== null ? TenantContext::set($previous) : TenantContext::clear(); } } } 

The handler drops the trait because the trait stores a message and its ack and nothing else. Ten notes over three tenants on a --concurrency=2 worker, posted within a second:

07:39:37 pid=88629 tenant=11111111 indexed 55,56,57,58 for 11111111 connects=3 open=3 07:39:37 pid=88629 tenant=33333333 indexed 41,42,43 for 33333333 connects=3 open=3 07:39:37 pid=88629 tenant=22222222 indexed 53,54,55 for 22222222 connects=3 open=3 

Three UPDATEs, each in its own database, each with its own ids, two seconds after the first note was posted. The flush switches tenant twice, which with kept connections costs nothing, and a group that fails nacks only its own messages.

There is a second trap in the same batch, and it is the cap again. A batched message is acked when its batch flushes, so the transport counts it as in flight until then. With TENANT_INFLIGHT_CAP=1, each tenant's first IndexNote sat in the batch and the parent skipped that tenant's stream, notes and jobs included, until the batch flushed. The batch flushes at ten messages, or when the parent's idle flush reaches it, which happens 30 seconds after the message was queued. Three tenants at one message each never reach ten. The first version of scenario four handled three of ten notes in ten seconds. The demo now exempts batched classes from the cap, TENANT_INFLIGHT_EXEMPT=App\Message\IndexNote: the cap bounds handling time, and a batched message spends its life waiting.

6. The decisions

Carry per-message context in a stamp and read it in a middleware. A worker event runs in the parent; a handler runs wherever the strategy puts it. The listener keeps its job for the parent's own sends, retries and failures, and the middleware takes over the handlers. This holds for anything a shared worker sets per message: the tenant, a locale, an impersonated user.

Keep the connections, and count the pool. The per-message reset keeps DBAL connections, so tenantConnections pays in a child as it did in a FrankenPHP worker. A pool of N children keeps N times as many. Watch open connections per database server rather than per process.

Give slow classes their own transport and their own worker. The probe holds a class, and on a shared deployment a class is every tenant. The tenant whose first message is slow decides how long the others wait, and no cap in the transport can see it, because the hold happens after the read.

A batch holds as many tenants as it has messages. Record the tenant when the message enters the batch, replay it per group at flush time, ack and nack per group. Any batch handler that writes to a tenant database on a shared worker needs this, with or without --concurrency; the parallel worker makes the wrong-tenant flush the common case instead of the rare one, because every batch is a cross-tenant batch.

Do not count a batched message against an in-flight cap. It is acked at flush, and the parent's idle flush waits 30 seconds. A cap that counts it stalls the tenant's stream for as long as the batch waits.

If you run one shared deployment for many tenants and want one worker for all of them: upgrade to 8.2.0, move the tenant into a middleware before you add --concurrency, run a cold restart with a slow message at the head of one tenant's queue, and read the batch handlers twice.

Source Code: You can find the full implementation and follow the project's progress on GitHub: https://github.com/mattleads/tenant-shared-demo

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