<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Matt Mochalkin</title>
    <description>The latest articles on DEV Community by Matt Mochalkin (@mattleads).</description>
    <link>https://dev.to/mattleads</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3458770%2F5dd4157c-9e79-4084-ad2e-56c3953d8c26.png</url>
      <title>DEV Community: Matt Mochalkin</title>
      <link>https://dev.to/mattleads</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mattleads"/>
    <language>en</language>
    <item>
      <title>Messenger --concurrency in Symfony 8.2: What the First Message of Every Class Costs You</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Fri, 27 Nov 2026 11:29:47 +0000</pubDate>
      <link>https://dev.to/mattleads/messenger-concurrency-in-symfony-82-what-the-first-message-of-every-class-costs-you-3ne8</link>
      <guid>https://dev.to/mattleads/messenger-concurrency-in-symfony-82-what-the-first-message-of-every-class-costs-you-3ne8</guid>
      <description>&lt;p&gt;You upgraded to Symfony 8.2, replaced four &lt;code&gt;messenger:consume&lt;/code&gt; processes with one &lt;code&gt;--concurrency=4&lt;/code&gt;, and the dashboard looks better: one connection to the broker instead of four, one process to supervise. Then a deploy restarts the worker, and for a minute the short messages that used to take half a second sit in the queue while three of the four children do nothing.&lt;/p&gt;

&lt;p&gt;The cause is a design decision in the new parallel worker. It 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. On 8.2.0-BETA2 the probe paused consumption for the whole worker, and what the probe learned lived in the memory of the parent process, so every restart paid it again. A fix merged on 23 November 2026 and shipped in 8.2.0-RC1 scopes the pause to the probed class. The probe itself stays, and so does a cost worth understanding before you size a pool.&lt;/p&gt;

&lt;p&gt;This article walks through how &lt;code&gt;--concurrency&lt;/code&gt; schedules work, why the probe exists, what it cost on BETA2 and what it costs after the fix, with a reproduction you can run in ten minutes. Then it covers the decisions that follow: which messages get their own transport, how long a worker should live, and when &lt;code&gt;--concurrency&lt;/code&gt; is the wrong tool.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.4 (tested on 8.4.22)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;symfony/messenger&lt;/code&gt; 8.2.0-BETA2 for the worker-wide pause, 8.2.0-RC1 for the fixed behaviour&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;amphp/parallel&lt;/code&gt;, which &lt;code&gt;--concurrency&lt;/code&gt; requires, and &lt;code&gt;symfony/runtime&lt;/code&gt;, which the children use to boot&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;symfony/doctrine-messenger&lt;/code&gt; with a SQLite database as the async transport; any transport works, the parent is the only process that talks to it&lt;/li&gt;
&lt;li&gt;no &lt;code&gt;ext-parallel&lt;/code&gt;; with it the children are threads instead of processes and the scheduling is the same&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. One fetcher, N children, one strategy
&lt;/h2&gt;

&lt;p&gt;A worker without &lt;code&gt;--concurrency&lt;/code&gt; fetches a message and handles it in the same process. With &lt;code&gt;--concurrency=N&lt;/code&gt; the &lt;code&gt;Worker&lt;/code&gt; keeps the fetching and hands each envelope to a &lt;code&gt;ParallelExecutionStrategy&lt;/code&gt;, which owns a pool of up to N amphp workers. Each child is a separate PHP process that boots your application through &lt;code&gt;bin/console&lt;/code&gt; (&lt;code&gt;DispatchTask::bootstrap()&lt;/code&gt; requires the file and asks &lt;code&gt;symfony/runtime&lt;/code&gt; for the container), then loops: receive an envelope over a channel, dispatch it on the bus, send the handled envelope back. The parent acks or rejects on the transport when the answer arrives.&lt;/p&gt;

&lt;p&gt;Two things follow from this shape. The parent is the only connection to the transport, which is the point of the feature. And fetching plus unserializing is not parallel, which is why Nicolas Grekas, who wrote the feature in symfony/symfony PR #63650, notes that it is "unfavorable for very short tasks". His own measurement in that PR, 192 plain messages of 20 ms each on 24 cores with warm workers, gives 3.73x at &lt;code&gt;--concurrency=4&lt;/code&gt; and 7.52x at 8.&lt;/p&gt;

&lt;p&gt;The strategy decides which child gets a message with an affinity key:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Symfony\Component\Messenger\Execution\ParallelExecutionStrategy, 8.2&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;getAffinityKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Envelope&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BusNameStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getBusName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'message.bus'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'|'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ReceivedStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getTransportName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'|'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bus, transport and message class. For a key the strategy knows as non-batching, any idle child will do. For a key it knows as batching, the message goes to the child that already holds the batch, busy or not, because a batch handler accumulates state in the memory of one child and flushing it from another child is impossible. That is the pin, and it is the reason batch handlers do not parallelize within one message class: the PR's table shows a single batching class at 0.98x whatever the concurrency, two classes at 2.00x.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. The probe, and what it cost on BETA2
&lt;/h2&gt;

&lt;p&gt;The pin needs a fact the strategy does not have when it sees a class for the first time: does its handler batch? A batch handler leaves a &lt;code&gt;NoAutoAckStamp&lt;/code&gt; on the envelope and acks later, when its batch flushes, and the child reports that as a &lt;code&gt;DeferredEnvelopeMessage&lt;/code&gt; instead of a handled envelope. The strategy learns that a class batches at that moment and not before. Until then, spreading five messages of that class across four children could strand a batch on a child that never gets the sixth.&lt;/p&gt;

&lt;p&gt;So the first message of an unknown key runs as a probe. On BETA2 the whole worker waited for it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// 8.2.0-BETA2&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$pendingProbeRequestId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;shouldPauseConsumption&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;pendingProbeRequestId&lt;/span&gt;
        &lt;span class="o"&gt;||&lt;/span&gt; \&lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;busyChannels&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;concurrencyLimit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Worker::run()&lt;/code&gt; checks &lt;code&gt;shouldPauseConsumption()&lt;/code&gt; after every message it hands over. When it returns true, the envelopes already fetched stay in a buffer and the loop waits for a child to answer. With &lt;code&gt;--fetch-size&lt;/code&gt; defaulting to &lt;code&gt;--concurrency&lt;/code&gt;, a cold worker fetched four messages, gave the first one to a child as the probe, and buffered the other three until that one child came back. If the first message was a report that takes a minute, the other three children idled for a minute, and so did every message behind them on the transport, whatever its class.&lt;/p&gt;

&lt;p&gt;The second half of the cost is where the answer is stored. &lt;code&gt;$keyModes&lt;/code&gt; is an array on the strategy, which lives in the parent process. A worker that stops on &lt;code&gt;--time-limit&lt;/code&gt;, &lt;code&gt;--memory-limit&lt;/code&gt;, a deploy or a crash starts with an empty array. Every class probes again, and the worker is paused again for the duration of each class's first message, one class after another. Nothing in the documentation mentions the probe; it says that batch-handled messages go to the same child, which is the consequence, not the mechanism.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Reproducing it
&lt;/h2&gt;

&lt;p&gt;The reproduction is a skeleton application with three messages and no batch handler at all, so every probe ends the same way, with the key learned as non-batching, and the cost is pure waiting:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;#[AsMessageHandler]&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SlowMessageHandler&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SlowMessage&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;seconds&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;#[AsMessageHandler]&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;FastMessageHandler&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;FastMessage&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;usleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500_000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;#[AsMessageHandler]&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PingHandler&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Ping&lt;/span&gt; &lt;span class="nv"&gt;$ping&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$wait&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;microtime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nv"&gt;$ping&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;dispatchedAt&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nf"&gt;file_put_contents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__DIR__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/../../var/ping-waits.log'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"%.3f\n"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$wait&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;FILE_APPEND&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Ping&lt;/code&gt; carries its dispatch time, so its handler records how long the message waited in the queue. That number is what a user of a latency-sensitive message feels. All three are routed to one Doctrine transport on SQLite, and every scenario starts a fresh worker on an empty queue, so the probe runs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 1: four slow messages of one class
&lt;/h3&gt;

&lt;p&gt;Four &lt;code&gt;SlowMessage(10)&lt;/code&gt; and &lt;code&gt;messenger:consume async --concurrency=4 --limit=4&lt;/code&gt;.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Version&lt;/th&gt;
&lt;th&gt;Wall time&lt;/th&gt;
&lt;th&gt;Timeline&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-BETA2&lt;/td&gt;
&lt;td&gt;21.9 s&lt;/td&gt;
&lt;td&gt;probe from 1.0 s to 11.0 s, then three in parallel until 21.9 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-RC1&lt;/td&gt;
&lt;td&gt;21.8 s&lt;/td&gt;
&lt;td&gt;probe from 0.8 s to 10.8 s, held siblings dispatched at 11.2 s to 11.8 s, done at 21.8 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The fix changes nothing here, and that is by design: the three other messages share the probed key, so they are held until the probe completes. Four messages of one class on a cold worker take two rounds, before and after the fix. The first second is the child booting the kernel.&lt;/p&gt;

&lt;p&gt;One measurement trap on the way: with &lt;code&gt;--limit=4&lt;/code&gt; the fixed strategy finished in 11.8 s, because the limit stops the worker as soon as it has taken its four messages, and a stopping worker releases what it holds (&lt;code&gt;flush(true)&lt;/code&gt;), so all four ran in parallel. That is the shutdown path, not the scheduling. Use &lt;code&gt;--time-limit&lt;/code&gt; to measure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 2: one slow class ahead of two fast ones
&lt;/h3&gt;

&lt;p&gt;One &lt;code&gt;SlowMessage(10)&lt;/code&gt;, then three &lt;code&gt;FastMessage&lt;/code&gt;, then three &lt;code&gt;Ping&lt;/code&gt;, &lt;code&gt;--concurrency=4 --limit=7&lt;/code&gt;.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Version&lt;/th&gt;
&lt;th&gt;Messages done&lt;/th&gt;
&lt;th&gt;Ping waits&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-BETA2&lt;/td&gt;
&lt;td&gt;12.8 s&lt;/td&gt;
&lt;td&gt;13,174 ms, 13,175 ms, 13,175 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-RC1&lt;/td&gt;
&lt;td&gt;11.1 s&lt;/td&gt;
&lt;td&gt;3,949 ms, 3,950 ms, 3,952 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;This is the case the fix was written for. On BETA2 the three pings sat behind the ten-second probe of a class they have nothing to do with, then behind the probe of &lt;code&gt;FastMessage&lt;/code&gt;, then their own. On RC1 they waited for the &lt;code&gt;FastMessage&lt;/code&gt; probe and their own, about four seconds, while the slow message ran on another child. Four seconds is still not zero: every class pays its probe, one class after another, and a ping dispatched before the worker starts is behind all of them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 3: the mixed load from the bug report
&lt;/h3&gt;

&lt;p&gt;The issue that led to the fix, symfony/symfony#68311, describes a transport that mixes an LLM-backed job of several minutes with short messages and a latency-sensitive one every few seconds. Scaled down to a run of a few minutes: one &lt;code&gt;SlowMessage(60)&lt;/code&gt;, five &lt;code&gt;SlowMessage(3)&lt;/code&gt;, twenty &lt;code&gt;FastMessage&lt;/code&gt;, and a &lt;code&gt;Ping&lt;/code&gt; dispatched every five seconds for ninety seconds from a second process, all consumed by a worker started cold with &lt;code&gt;--concurrency=4&lt;/code&gt;. Then the same load again against the same worker, now warm.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Version&lt;/th&gt;
&lt;th&gt;Cold worker, average wait&lt;/th&gt;
&lt;th&gt;Cold, max&lt;/th&gt;
&lt;th&gt;Warm worker, average wait&lt;/th&gt;
&lt;th&gt;Warm, max&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-BETA2&lt;/td&gt;
&lt;td&gt;25,238 ms&lt;/td&gt;
&lt;td&gt;67,253 ms&lt;/td&gt;
&lt;td&gt;12,151 ms&lt;/td&gt;
&lt;td&gt;44,056 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8.2.0-RC1&lt;/td&gt;
&lt;td&gt;25,390 ms&lt;/td&gt;
&lt;td&gt;67,812 ms&lt;/td&gt;
&lt;td&gt;11,493 ms&lt;/td&gt;
&lt;td&gt;43,862 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Eighteen pings per phase. Cold, thirteen of them waited behind the sixty-second message, from 67 seconds for the first down to 2 seconds for the last, on both versions. The fix did not change the cold phase, and the worker log says why: the five &lt;code&gt;SlowMessage(3)&lt;/code&gt; share the affinity key of the &lt;code&gt;SlowMessage(60)&lt;/code&gt; probe, so they are held, and held messages count against the concurrency limit. One probe plus three held messages is four slots, &lt;code&gt;shouldPauseConsumption()&lt;/code&gt; is true, and the parent fetches nothing until the probe completes at 62 seconds. The RC1 log shows a &lt;code&gt;SlowMessage&lt;/code&gt; received at 2.0 s and the next line at 62.1 s.&lt;/p&gt;

&lt;p&gt;That is the sharpest cost left after the fix. A class whose first message is slow and whose next messages are already queued fills the pool with its own held messages, and the whole worker waits as before. The fix helps when the slow class arrives alone, as in scenario 2. It does not help when the slow class arrives in a burst of &lt;code&gt;--concurrency&lt;/code&gt; or more.&lt;/p&gt;

&lt;p&gt;The warm numbers are dominated by a second problem that has nothing to do with the probe, covered in section 7, and they are reported here because that is what we measured.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. What the fix changed
&lt;/h2&gt;

&lt;p&gt;symfony/symfony PR #68313, merged on 23 November 2026 and released in 8.2.0-RC1 two days later, keeps the probe and removes the worker-wide pause. The probe is now tracked per key, and the messages of a key whose probe is in flight are held by the strategy instead of blocking the fetch loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/messenger 8.2.0-RC1&lt;/span&gt;
&lt;span class="cm"&gt;/** @var array&amp;lt;string, int&amp;gt; The request id of the probe in flight, by affinity key */&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$pendingProbeRequests&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/** @var array&amp;lt;string, list&amp;lt;array{Envelope, string, callable}&amp;gt;&amp;gt; Messages held until the probe of their key completes */&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$heldRequests&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Envelope&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$transportName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;callable&lt;/span&gt; &lt;span class="nv"&gt;$onHandled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
    &lt;span class="nv"&gt;$affinityKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getAffinityKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$keyMode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;keyModes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$affinityKey&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;releasingHeldRequests&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$keyMode&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;isset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;pendingProbeRequests&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$affinityKey&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// a probe is learning whether this key batches: the message joins its siblings&lt;/span&gt;
        &lt;span class="c1"&gt;// and is dispatched when the probe completes&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;heldRequests&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$affinityKey&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$transportName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$onHandled&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;shouldPauseConsumption&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// held messages occupy the slot of the worker they wait for, like busy ones do&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; \&lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;busyChannels&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;countHeldRequests&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;concurrencyLimit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the probe answers, &lt;code&gt;releaseHeldRequests()&lt;/code&gt; re-executes the held messages in arrival order. If the probe deferred, the key is now batching and they go to the pinned child one after another. If it completed, they are spread over idle children like any other message. Held messages count against the concurrency limit, so the parent cannot buffer an unbounded queue behind a slow probe, and a worker that stops releases what it holds instead of leaving it unacked. The three new tests in &lt;code&gt;ParallelExecutionStrategyTest&lt;/code&gt; fail on BETA2 and describe the contract in their names: a probe does not pause consumption of other keys, messages of a probed key are held until its probe defers, held messages count towards the concurrency limit.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. What the first message still costs
&lt;/h2&gt;

&lt;p&gt;The fix changes who waits, not whether anyone does. Four costs remain, and they are worth knowing when you size a pool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The probed class waits for itself.&lt;/strong&gt; Messages of the probed key are held until the probe completes, whatever the children are doing. If &lt;code&gt;ReportMessage&lt;/code&gt; takes a minute and ten of them arrive on a cold worker, the second to the tenth start after the first finishes, then spread over the children. The probe can only end sooner if the handler defers earlier, which a plain handler never does.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The answer still dies with the process.&lt;/strong&gt; &lt;code&gt;$keyModes&lt;/code&gt; is still an array in the parent. Every restart, planned or not, probes every class again. The first message of each class after a restart is the slow one, and now only its own class pays. A worker with &lt;code&gt;--time-limit=3600&lt;/code&gt; probes each class once an hour; one with &lt;code&gt;--time-limit=60&lt;/code&gt; does it once a minute. With a class whose handler runs for longer than the time limit, the probe is the only message of that class the worker will ever run alone, and the next worker probes again. Set the time limit from the longest handler you route to that worker, not from habit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A burst of the probed class fills the pool.&lt;/strong&gt; Held messages occupy a slot each, so with &lt;code&gt;--concurrency=4&lt;/code&gt; a probe plus three queued messages of the same class pauses the fetch loop for the duration of the probe, as scenario 3 shows. The PR takes that trade-off deliberately, so the parent cannot buffer an unbounded queue behind a slow probe. The practical consequence is that the class most likely to have a slow first message, a report or an import that arrives in batches, is the class the fix helps least.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The children boot too.&lt;/strong&gt; Each child requires &lt;code&gt;bin/console&lt;/code&gt; and builds the container before its first message. That is the same cost as starting one more &lt;code&gt;messenger:consume&lt;/code&gt;, paid N times per restart, and it adds to the probe on a cold worker because the probe's child boots first. A warm pool does not pay it; a child replaced after reaching &lt;code&gt;--memory-limit&lt;/code&gt; pays it once, without a new probe.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Decisions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Give latency-sensitive messages their own worker, not only their own transport.&lt;/strong&gt; The affinity key includes the transport, so on RC1 a &lt;code&gt;Ping&lt;/code&gt; on &lt;code&gt;async_fast&lt;/code&gt; is never held by a probe on &lt;code&gt;async&lt;/code&gt;. It is still fetched by the same parent, and scenario 3 shows that parent pausing when a slow class arrives in a burst. On BETA2 the pause was per worker in every case. So the separation that holds on both versions is a second &lt;code&gt;messenger:consume&lt;/code&gt; for the fast transport. A message that must be handled within a second has no business sharing a worker with one that takes a minute, and that was true before &lt;code&gt;--concurrency&lt;/code&gt; existed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pick &lt;code&gt;--concurrency&lt;/code&gt; from the number of distinct keys in flight when handlers batch.&lt;/strong&gt; The PR's table is the whole argument: one batching class gains nothing from any concurrency, two classes cap at 2x. For a transport that carries one batching class, several workers remain the way to parallelize.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep the parent alive as long as you safely can.&lt;/strong&gt; A restart of the parent costs a probe per class and a boot per child. &lt;code&gt;--time-limit&lt;/code&gt; stops the parent. &lt;code&gt;--memory-limit&lt;/code&gt; is enforced in the parent and in every child: a child that crosses it after a message stops, and the strategy replaces it with a fresh one, which costs a boot but no probe, because the answers live in the parent. For leaky handlers that is the limit to rely on; the time limit should come from the slowest handler, as above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not use &lt;code&gt;--concurrency&lt;/code&gt; for very short messages.&lt;/strong&gt; Fetching and unserializing stays in the parent, and the handled envelope travels back over a channel. For a handler that takes two milliseconds, the round trip is the work. Several plain workers scale that case; &lt;code&gt;--concurrency&lt;/code&gt; scales the case where the handler, not the transport, is the bottleneck.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Upgrade past BETA2 before you turn it on.&lt;/strong&gt; The worker-wide pause is the kind of cost that only shows on a restart with a slow message at the head of the queue, which is to say in production on deploy day. The fix is in 8.2.0-RC1 and every later 8.2 release.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. A second cost that is not the probe: the parent blocks on a busy child
&lt;/h2&gt;

&lt;p&gt;In the warm phase of scenario 3, on both versions, the parent fetched nothing for about fifty seconds while one child was inside the sixty-second handler and the other three were idle. Every key was known by then, so the probe was not involved. The minimal form of it is one slow message alone on a warm worker, with a ping every five seconds:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ping waits (ms): 717, 390, 34, 44359, 38982, 33574, 28210, 22815, 17439, 12088, 6707, 1318, 984, 636
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The cause is in &lt;code&gt;flush()&lt;/code&gt;. The idle loop of &lt;code&gt;Worker::run()&lt;/code&gt; calls &lt;code&gt;flush(false)&lt;/code&gt; and &lt;code&gt;flush(30.0)&lt;/code&gt; on every pass, and &lt;code&gt;flush()&lt;/code&gt; sends a &lt;code&gt;FlushBatchHandlersMessage&lt;/code&gt; to every channel with a pending request, including the channel of a child that is inside a handler. That child does not read its channel until the handler returns. Each flush waits in the socket buffer, and once the buffer is full the next &lt;code&gt;$channel-&amp;gt;send()&lt;/code&gt; suspends the parent until the child reads. An amphp worker inside &lt;code&gt;sleep()&lt;/code&gt; accepts 29 sends of 100 bytes on macOS; the 30th blocks until the sleep ends. At two flushes per idle second that is about fifteen seconds into any handler. Instrumented, 42 sends to the busy channel took 0.000 s and the 43rd took 47.678 s.&lt;/p&gt;

&lt;p&gt;The fix is a condition in &lt;code&gt;flush()&lt;/code&gt;: a timed flush skips the busy channels, since a child inside a handler cannot act on a flush before the handler returns anyway, and a child holding a batch is never busy. A forced flush, which stops the worker, still reaches every child. With it, the same run gives:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ping waits (ms): 722, 385, 45, 708, 379, 1024, 690, 318, 995, 680, 345, 985, 988, 655
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This one is still in 8.2.0-RC1. The fix is open as &lt;a href="https://github.com/symfony/symfony/pull/68459" rel="noopener noreferrer"&gt;symfony/symfony#68459&lt;/a&gt; against 8.2, so until it is merged, a child inside a handler longer than about fifteen seconds stops the parent's fetch loop for the rest of that handler, whatever the other children are doing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;--concurrency&lt;/code&gt; moves the parallelism from N processes polling a broker to one process and N children, and it needs one piece of information it can only learn at runtime: whether a class batches. The probe is how it learns, and the probe is why the first message of every class after every restart runs alone. On 8.2.0-BETA2 it ran alone with the whole worker waiting; from the fix of 23 November it runs alone with its own class waiting. In the reproduction, a ping behind a slow probe of another class waited 13.2 s on BETA2 and 3.9 s on RC1; a ping behind a slow probe whose class had three more messages queued waited 67 s on both.&lt;/p&gt;

&lt;p&gt;If you adopt it: separate the slow classes from the fast ones by transport, set the time limit from the slowest handler, and measure a cold restart and a long handler next to short ones, because those are the two moments where the parent stops fetching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/messenger-concurrency-probe" rel="noopener noreferrer"&gt;https://github.com/mattleads/messenger-concurrency-probe&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>messenger</category>
      <category>performance</category>
    </item>
    <item>
      <title>Retry #1 Forever: What Symfony Messenger 8.1 Expects From Your Custom Serializer</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Mon, 23 Nov 2026 08:39:14 +0000</pubDate>
      <link>https://dev.to/mattleads/retry-1-forever-what-symfony-messenger-81-expects-from-your-custom-serializer-2d4j</link>
      <guid>https://dev.to/mattleads/retry-1-forever-what-symfony-messenger-81-expects-from-your-custom-serializer-2d4j</guid>
      <description>&lt;p&gt;Your worker is logging the same line over and over:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WARNING: Sending for retry #1 using 0 ms delay. Error: "Cannot decode message: unknown encryption key "k2"."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Retry #1, again and again. &lt;code&gt;max_retries&lt;/code&gt; is 3. The failure transport is empty. The message is still in the queue, nothing else in that queue moves, and nothing crashed, so no alert fired.&lt;/p&gt;

&lt;p&gt;That is what a custom Messenger serializer written before Symfony 8.1 does on 8.1.0 through 8.1.10 when it meets a payload it cannot read. I hit it while writing a serializer decorator for compression and encryption (&lt;a href="https://dev.to/mattleads/77x-smaller-and-encrypted-at-rest-compressing-symfony-messenger-payloads-without-touching-a-1ij4"&gt;that article&lt;/a&gt; mentions it in two sentences). This one is the full story: what 8.1 changed in the decode contract and why, where the retry counter goes, the fix that shipped in 8.1.11 and how to write &lt;code&gt;decode()&lt;/code&gt; today so a poisoned message ends up on the failure transport instead of in a loop. There is a second, unrelated trap in the Redis transport at the end, found the same week.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;symfony/messenger&lt;/code&gt; 8.1. The loop exists on 8.1.0 to 8.1.10; the fix is in 8.1.11 (released 4 November 2026) and in 8.2.&lt;/li&gt;
&lt;li&gt;Any transport with a receiver: the reproducer uses &lt;code&gt;symfony/doctrine-messenger&lt;/code&gt; 8.1 on SQLite in memory, no framework, one PHP file.&lt;/li&gt;
&lt;li&gt;A custom serializer, or a decorator around the built-in &lt;code&gt;Serializer&lt;/code&gt;. If every transport you have uses the stock &lt;code&gt;Serializer&lt;/code&gt; or &lt;code&gt;PhpSerializer&lt;/code&gt;, you are not affected by the loop, but the contract in section 4 still applies to any serializer you write next.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The reproducer is at &lt;a href="https://github.com/mattleads/messenger-decode-throw-repro" rel="noopener noreferrer"&gt;mattleads/messenger-decode-throw-repro&lt;/a&gt;: &lt;code&gt;php repro.php throw&lt;/code&gt; and &lt;code&gt;php repro.php return&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. What 8.0 did with a message it could not decode
&lt;/h2&gt;

&lt;p&gt;Before 8.1, a serializer reported a decoding failure by throwing &lt;code&gt;MessageDecodingFailedException&lt;/code&gt; from &lt;code&gt;decode()&lt;/code&gt;. The Doctrine receiver on 8.0 handled it like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/doctrine-messenger 8.0, DoctrineReceiver::createEnvelopeFromData()&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$envelope&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;serializer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s1"&gt;'body'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'headers'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'headers'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt; &lt;span class="nv"&gt;$exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connection&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nv"&gt;$exception&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reject, then rethrow. The reject deletes the row. The rethrow escapes &lt;code&gt;Worker::run()&lt;/code&gt;, which has no &lt;code&gt;catch&lt;/code&gt; around &lt;code&gt;$receiver-&amp;gt;get()&lt;/code&gt;, and &lt;code&gt;messenger:consume&lt;/code&gt; only wraps the run in a &lt;code&gt;finally&lt;/code&gt;. So the worker process exited with the exception and the message was gone. Under a process manager the worker restarted and ate the next poisoned message the same way. Nothing reached the failure transport, because the failure path starts at the bus and the message never got there.&lt;/p&gt;

&lt;p&gt;The usual way to meet this was a deploy that renamed a message class while the queue still held the old name. Symfony issue #44117, opened in 2021, asked that those messages stop being deleted.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What 8.1 changed, and the piece that makes retries work
&lt;/h2&gt;

&lt;p&gt;Symfony 8.1 (May 2026) routes decoding failures through the same pipeline as a failing handler. Nicolas Grekas' PR #62888 did three things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;MessageDecodingFailedException&lt;/code&gt; got a &lt;code&gt;wrap()&lt;/code&gt; factory and an &lt;code&gt;encodedEnvelope&lt;/code&gt; property. &lt;code&gt;wrap($encodedEnvelope, $message)&lt;/code&gt; returns an &lt;code&gt;Envelope&lt;/code&gt; whose message is the exception, and the exception carries the raw body and headers it could not read.&lt;/li&gt;
&lt;li&gt;Receivers no longer delete and throw. They yield the wrapped envelope with their own stamps, so &lt;code&gt;ack()&lt;/code&gt; and &lt;code&gt;reject()&lt;/code&gt; work on it like on any message.&lt;/li&gt;
&lt;li&gt;A new &lt;code&gt;DecodeFailedMessageMiddleware&lt;/code&gt; sits early in the bus. When the message is a &lt;code&gt;MessageDecodingFailedException&lt;/code&gt;, it looks up the serializer of the transport that received it and calls &lt;code&gt;decode()&lt;/code&gt; again. If decoding now works (the class was deployed, the key arrived), the real message continues down the stack with the stamps of the failed envelope merged in. If it still fails, the exception is thrown and the retry listener does its job.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The contract for serializers changed with it. From the 8.1.0 docblock of &lt;code&gt;SerializerInterface::decode()&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;On failure, implementations SHOULD return an Envelope wrapping a MessageDecodingFailedException instead of throwing, so that the worker can route the failure through the normal retry/DLQ path. Throwing a MessageDecodingFailedException is still supported for BC with custom serializers; transports will wrap the exception as a fallback.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How does Messenger know this is retry #2 and not retry #1? Through a stamp. &lt;code&gt;SendFailedMessageForRetryListener&lt;/code&gt; reads &lt;code&gt;RedeliveryStamp::getRetryCountFromEnvelope()&lt;/code&gt;, which is the count on the last &lt;code&gt;RedeliveryStamp&lt;/code&gt; of the envelope, or 0 if there is none. When a message is sent back for a retry, the listener adds a new &lt;code&gt;RedeliveryStamp&lt;/code&gt; with the incremented count, and the serializer writes it into the headers as &lt;code&gt;X-Message-Stamp-...RedeliveryStamp&lt;/code&gt;. On the next delivery the serializer decodes the headers, the stamp is back on the envelope, the count continues.&lt;/p&gt;

&lt;p&gt;So the retry counter lives in the headers of the message, and it comes back only if &lt;code&gt;decode()&lt;/code&gt; puts it back. That is the whole bug.&lt;/p&gt;

&lt;p&gt;The built-in &lt;code&gt;Serializer&lt;/code&gt; on 8.1 decodes the stamps first and keeps the ones that decode on every failure path:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/messenger 8.1.11, Serializer::decode()&lt;/span&gt;
&lt;span class="c1"&gt;// a failure keeps the stamps that decode, so that its retries are counted&lt;/span&gt;
&lt;span class="nv"&gt;$stamps&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decodeStamps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$stampFailure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;serializer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;deserialize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;format&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$context&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;\&lt;span class="nc"&gt;Throwable&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;wrap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'Could not decode message: '&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$stamps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It took three fixes on the 8.1 branch to get the stock serializer there. PR #65122 (August 2026) stopped &lt;code&gt;encode()&lt;/code&gt; from serializing the live exception as the new body, which had made the payload roughly double on every round, and re-sends the original body instead. PRs #66460 and #66452 (September 2026) kept the stamps when the body is empty or a stamp header is broken, and sent messages with a bad signature straight to the failure transport, since a retry cannot make a signature verify. Each of those was the same lost counter in a different place. Custom serializers had the fourth.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. The trap: throw, and the counter never comes back
&lt;/h2&gt;

&lt;p&gt;Every receiver on 8.1 kept the catch as the BC fallback the docblock promised. The 8.1.10 Doctrine receiver:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/doctrine-messenger 8.1.10 and 8.1.11, DoctrineReceiver::createEnvelopeFromData()&lt;/span&gt;
&lt;span class="nv"&gt;$stamps&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;DoctrineReceivedStamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TransportMessageIdStamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;serializer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s1"&gt;'body'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'headers'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'headers'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withoutAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TransportMessageIdStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$stamps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;wrap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$stamps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look at what &lt;code&gt;$stamps&lt;/code&gt; holds in the catch: the receiver's two stamps. Nothing from the headers. The receiver cannot decode them, because the only component that knows the header format just threw. The &lt;code&gt;RedeliveryStamp&lt;/code&gt; is in the row, in the &lt;code&gt;headers&lt;/code&gt; column, and it never reaches the envelope.&lt;/p&gt;

&lt;p&gt;From there the sequence is mechanical. The wrapped envelope reaches &lt;code&gt;DecodeFailedMessageMiddleware&lt;/code&gt;, which calls &lt;code&gt;decode()&lt;/code&gt; again. The serializer throws again. On 8.1.0 to 8.1.10 the middleware had no &lt;code&gt;try&lt;/code&gt; around that call, so the raw &lt;code&gt;MessageDecodingFailedException&lt;/code&gt; escapes to the worker. The retry listener sees an envelope with no &lt;code&gt;RedeliveryStamp&lt;/code&gt;, computes retry count 0, decides 0 &amp;lt; 3, and sends the message back with a &lt;code&gt;RedeliveryStamp(1)&lt;/code&gt;. The serializer's &lt;code&gt;encode()&lt;/code&gt; writes it into the headers. Next delivery, the serializer throws before reading headers, the stamp is lost, count is 0 again. Retry #1, forever.&lt;/p&gt;

&lt;p&gt;The reproducer has one serializer with two modes. It wraps the stock &lt;code&gt;Serializer&lt;/code&gt; and pretends it cannot read the body:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UnreadableSerializer&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;SerializerInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Envelope&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'Cannot decode message: unknown encryption key "k2".'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'throw'&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;mode&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// pre-8.1 contract, "still supported for BC" according to SerializerInterface::decode()&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// 8.1 contract: return the failure, and keep the stamps that still decode from the headers&lt;/span&gt;
        &lt;span class="nv"&gt;$stamps&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;array_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;wrap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$stamps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Doctrine transport, &lt;code&gt;max_retries: 3&lt;/code&gt;, a failure transport, one message, one worker with a time limit. &lt;code&gt;php repro.php throw&lt;/code&gt; on 8.1.10:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WARNING: ... Sending for retry #1 using 0 ms delay. Error: "Cannot decode message: unknown encryption key "k2"."
WARNING: ... Sending for retry #1 using 0 ms delay. ...
WARNING: ... Sending for retry #1 using 0 ms delay. ...
(repeats until the worker is stopped)

mode=throw  still queued on async: 1  on failure transport: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;php repro.php return&lt;/code&gt;, same serializer, same message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WARNING: ... Sending for retry #1 using 0 ms delay. ...
WARNING: ... Sending for retry #2 using 0 ms delay. ...
WARNING: ... Sending for retry #3 using 0 ms delay. ...
CRITICAL: ... Removing from transport after 3 retries. ...
INFO: Rejected message ... will be sent to the failure transport ...

mode=return  still queued on async: 0  on failure transport: 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only difference between the two runs is whether &lt;code&gt;decode()&lt;/code&gt; throws or returns.&lt;/p&gt;

&lt;p&gt;Two things make this worse than the 8.0 behavior in practice. On 8.0 the worker died, which is loud. On 8.1 the worker stays up and busy, the queue depth stays flat at one, and the failure transport, the place you look when something is wrong with a message, is empty. And the throwing path is the one every serializer written against 7.x or 8.0 uses, because it was the only path that existed.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. The fix in 8.1.11
&lt;/h2&gt;

&lt;p&gt;The receiver cannot restore the counter, so the fix had to live where the second &lt;code&gt;decode()&lt;/code&gt; happens. The issue I opened proposed two options: treat a thrown failure as unrecoverable in the middleware, or make the retry listener read the count back from the raw header when the envelope has no stamp. The second only works for serializers that use the stock header format. Ptraaah, a first-time contributor, took the first option in PR #67799 the same day:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/messenger 8.1.11, DecodeFailedMessageMiddleware::handle()&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$decodedEnvelope&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$serializer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// the stamps of a thrown failure are lost and its retries cannot be counted, so it should not be retried&lt;/span&gt;
    &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getPrevious&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;UnrecoverableExceptionInterface&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getPrevious&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;UnrecoverableMessageHandlingException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A thrown decoding failure becomes an &lt;code&gt;UnrecoverableMessageHandlingException&lt;/code&gt;, with the original exception as &lt;code&gt;previous&lt;/code&gt;. The retry listener sees an unrecoverable exception, skips the retries, and the message goes to the failure transport after 0 retries. From there &lt;code&gt;messenger:failed:retry&lt;/code&gt; replays it through &lt;code&gt;DecodeFailedMessageMiddleware&lt;/code&gt; once the serializer can read it. Serializers that return &lt;code&gt;wrap()&lt;/code&gt; keep their retries, since their stamps are intact.&lt;/p&gt;

&lt;p&gt;Nicolas Grekas added a worker-level test to &lt;code&gt;FailureIntegrationTest&lt;/code&gt; that runs a throwing serializer through a real &lt;code&gt;Worker&lt;/code&gt;, asserts one failure with count 0 and class &lt;code&gt;UnrecoverableMessageHandlingException&lt;/code&gt;, and then replays the message from the failure transport once the serializer works. He also changed &lt;code&gt;SigningSerializer&lt;/code&gt;: it used to catch everything its inner serializer threw and return it as a wrapped failure, which lost the inner serializer's stamps the same way. It now rethrows what the inner serializer throws (wrapped in &lt;code&gt;MessageDecodingFailedException&lt;/code&gt; if it was something else), so the fix covers signed messages too.&lt;/p&gt;

&lt;p&gt;The docblock no longer promises that throwing is equivalent:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Throwing a MessageDecodingFailedException is still supported for BC, but the stamps of the message are then lost. In this case, the message is sent to the failure transport without being retried.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What a serializer that cannot read a payload gets on each version:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;
&lt;code&gt;decode()&lt;/code&gt; does&lt;/th&gt;
&lt;th&gt;8.0&lt;/th&gt;
&lt;th&gt;8.1.0 to 8.1.10&lt;/th&gt;
&lt;th&gt;8.1.11 and later&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;throws &lt;code&gt;MessageDecodingFailedException&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;message deleted, worker exits&lt;/td&gt;
&lt;td&gt;retry #1 forever, failure transport empty&lt;/td&gt;
&lt;td&gt;failure transport after 0 retries, replay possible&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;returns &lt;code&gt;wrap()&lt;/code&gt; with the decoded stamps&lt;/td&gt;
&lt;td&gt;not available&lt;/td&gt;
&lt;td&gt;retried up to &lt;code&gt;max_retries&lt;/code&gt;, then failure transport&lt;/td&gt;
&lt;td&gt;same&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;returns &lt;code&gt;wrap()&lt;/code&gt; without stamps&lt;/td&gt;
&lt;td&gt;not available&lt;/td&gt;
&lt;td&gt;retry #1 forever&lt;/td&gt;
&lt;td&gt;retry #1 forever&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The last row is the one to remember. The fix handles throwing. It cannot handle a serializer that returns a wrapped failure and drops the stamps, because from the outside that envelope looks like a first delivery. If you return, you must return the stamps.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. The contract to write against today
&lt;/h2&gt;

&lt;p&gt;Three rules, taken from the 8.1.11 docblock and the docs' custom serializer example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Return the failure, do not throw it.&lt;/strong&gt; &lt;code&gt;MessageDecodingFailedException::wrap($encodedEnvelope, $message, $code, $previous)&lt;/code&gt; gives you the envelope. The raw body and headers go into the exception, so the message can be sent again as it was received.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep every stamp you can still decode.&lt;/strong&gt; For a decorator around the stock &lt;code&gt;Serializer&lt;/code&gt; that is one call: the inner serializer's &lt;code&gt;decode()&lt;/code&gt; on the unreadable payload returns its own failure envelope, and that envelope carries the stamps it read from the headers. Take them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Envelope&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// decrypt, decompress, whatever can fail&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;\&lt;span class="nc"&gt;Throwable&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// the inner serializer still reads the headers, and the RedeliveryStamp is in them&lt;/span&gt;
        &lt;span class="nv"&gt;$stamps&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;array_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;wrap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$stamps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$body&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;$encodedEnvelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This relies on the stamps living in the headers, which is how &lt;code&gt;Serializer&lt;/code&gt; stores them. &lt;code&gt;PhpSerializer&lt;/code&gt; puts the whole envelope in the body, so a decorator around it has nothing to recover when the body is unreadable, and a thrown failure on 8.1.11 is the honest answer there.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Re-send a failure as it was received.&lt;/strong&gt; When the failed message is retried or moved to the failure transport, your &lt;code&gt;encode()&lt;/code&gt; gets an envelope whose message is the &lt;code&gt;MessageDecodingFailedException&lt;/code&gt;. Do not transform that body again. The stock &lt;code&gt;Serializer&lt;/code&gt; already handles it: it re-emits &lt;code&gt;encodedEnvelope['body']&lt;/code&gt; as is, keeps the original &lt;code&gt;type&lt;/code&gt; header, and writes the current stamps, including the new &lt;code&gt;RedeliveryStamp&lt;/code&gt;, into the headers. A decorator only has to step aside:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Envelope&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$encoded&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// a decoding failure is sent again with its original body, which is transformed already&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;MessageDecodingFailedException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$encoded&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nv"&gt;$encoded&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;seal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encoded&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$encoded&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A serializer that does not delegate, like the token decoder in the docs, returns &lt;code&gt;$message-&amp;gt;encodedEnvelope&lt;/code&gt; directly from &lt;code&gt;encode()&lt;/code&gt; for a failure. That is the example the docs show since PR #23459, which replaced the old &lt;code&gt;return new Envelope($throwable)&lt;/code&gt; in the "Message Serializer For Custom Data Formats" section. The old example dispatched a plain throwable as a message, and its &lt;code&gt;encode()&lt;/code&gt; then threw when the worker tried to re-send it.&lt;/p&gt;

&lt;p&gt;One configuration rule goes with this. The failure transport must use the same serializer as the transport that fed it, because &lt;code&gt;DecodeFailedMessageMiddleware&lt;/code&gt; re-decodes with the serializer of the original transport and the failure transport has to be able to store the payload that serializer produced. The docs say so under "Handling Decode Failures". The reproducer gets away with a &lt;code&gt;PhpSerializer&lt;/code&gt; on the failure transport only because it never replays.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. The sibling trap: the Redis DSN overrides &lt;code&gt;consumer&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Found the same week, while testing the Redis transport. The docs list &lt;code&gt;consumer&lt;/code&gt; as an option you can set in the DSN or under &lt;code&gt;options&lt;/code&gt; in &lt;code&gt;messenger.yaml&lt;/code&gt;, with an example that sets it from an env var under &lt;code&gt;options&lt;/code&gt;. Right above that list sits the "Full DSN Example", and it ends in &lt;code&gt;/messages/symfony/consumer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;Connection::parseDsn()&lt;/code&gt; the query string is merged over the options array, and in &lt;code&gt;fromDsn()&lt;/code&gt; the path segments are read last:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// symfony/redis-messenger 8.1.11, Connection::fromDsn()&lt;/span&gt;
&lt;span class="nv"&gt;$pathParts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;explode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;rtrim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'path'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'stream'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$pathParts&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'stream'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'group'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$pathParts&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'group'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'consumer'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$pathParts&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'consumer'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So whoever copies the full example and then sets &lt;code&gt;consumer: '%env(MESSENGER_CONSUMER_NAME)%'&lt;/code&gt; gets every worker registered in Redis under the literal name &lt;code&gt;consumer&lt;/code&gt;, with no warning. Verified on &lt;code&gt;symfony/redis-messenger&lt;/code&gt; 8.1.10 against a live Redis, with &lt;code&gt;consumer: worker-42&lt;/code&gt; under &lt;code&gt;options&lt;/code&gt;:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;DSN&lt;/th&gt;
&lt;th&gt;Consumer registered in Redis&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;redis://localhost/messages&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;worker-42&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;redis://localhost/messages/symfony&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;worker-42&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;redis://localhost/messages/symfony/consumer&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;consumer&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;redis://localhost?consumer=dsnq&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;dsnq&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;redis://localhost/messages/symfony/dsnpath?consumer=dsnq&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;dsnpath&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The precedence is the same in 5.4, 6.4 and 7.4. Note the docs' general "Transport Configuration" section says options under &lt;code&gt;options&lt;/code&gt; take precedence over the DSN; for the Redis transport the code does the opposite, and the path wins over the query. The Redis section now says so (docs PR #23472, merged into 6.4 so it reaches every maintained branch): when the name comes from &lt;code&gt;options&lt;/code&gt;, stop the DSN path at &lt;code&gt;/stream/group&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The name is not cosmetic. Redis tracks the pending entries of a stream group per consumer name, so every worker that shares the name &lt;code&gt;consumer&lt;/code&gt; shares one pending list, and the per-worker accounting the option exists for is gone.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. How this went upstream
&lt;/h2&gt;

&lt;p&gt;For anyone who has not sent a bug to Symfony before, the sequence, with dates.&lt;/p&gt;

&lt;p&gt;On 1 November 2026 I opened symfony-docs PR #23459 to fix the custom serializer example, because the docs example was the first thing I had copied and it was wrong on 8.1. Javier Eguiluz merged it the next day.&lt;/p&gt;

&lt;p&gt;On 2 November I opened symfony/symfony issue #67791 with the one-file reproducer linked above and the two options from section 4. Ten hours later Ptraaah, a first-time contributor, picked option 1 and opened PR #67799 with tests. The next morning I ran the PR branch against the reproducer on 8.1.10 (throw mode now lands on the failure transport after 0 retries, return mode unchanged) and suggested a worker-level test in &lt;code&gt;FailureIntegrationTest&lt;/code&gt;, where the three earlier counter fixes had put theirs. Nicolas Grekas added that test and the &lt;code&gt;SigningSerializer&lt;/code&gt; change, and merged on 3 November. 8.1.11 shipped on 4 November with it.&lt;/p&gt;

&lt;p&gt;The Redis docs PR #23472 went in on 5 November and was merged the next day.&lt;/p&gt;

&lt;p&gt;Three things made it quick. The reproducer had no framework, so anyone could run it in a minute. The issue named the exact line in each receiver where the stamps were lost, which turned "retried forever" into a known shape the maintainers had already fixed three times. And the proposed fix was the smallest one that matched an existing pattern in the same file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;If you maintain a custom Messenger serializer, decide these three things now.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;On 8.1.0 to 8.1.10, update to 8.1.11.&lt;/strong&gt; Until then, a serializer that throws from &lt;code&gt;decode()&lt;/code&gt; loops at retry #1 on any poisoned message, and your failure transport will not tell you.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Return &lt;code&gt;wrap()&lt;/code&gt; with the stamps if you want retries.&lt;/strong&gt; A decorator around &lt;code&gt;Serializer&lt;/code&gt; gets them from the inner serializer's own failure envelope. If you cannot recover the stamps, throw, and accept that the message goes to the failure transport on first sight, which on 8.1.11 is what throwing means.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let the failure re-send itself.&lt;/strong&gt; In &lt;code&gt;encode()&lt;/code&gt;, pass a &lt;code&gt;MessageDecodingFailedException&lt;/code&gt; message through untransformed and give the failure transport the same serializer as its source.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And if your Redis DSN has three path segments, check what name your workers are registered under.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/messenger-decode-throw-repro" rel="noopener noreferrer"&gt;https://github.com/mattleads/messenger-decode-throw-repro&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>messenger</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>One Right Answer in Ten: The mcp/sdk 0.8 Session Race and the Case for a Stateless MCP Server in PHP</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Thu, 19 Nov 2026 11:28:40 +0000</pubDate>
      <link>https://dev.to/mattleads/one-right-answer-in-ten-the-mcpsdk-08-session-race-and-the-case-for-a-stateless-mcp-server-in-php-516i</link>
      <guid>https://dev.to/mattleads/one-right-answer-in-ten-the-mcpsdk-08-session-race-and-the-case-for-a-stateless-mcp-server-in-php-516i</guid>
      <description>&lt;p&gt;An MCP server I run in production behind FrankenPHP started answering tool calls with other tool calls' results. Not every time. An agent that fired six calls at once got most of them right, a few came back as an empty &lt;code&gt;202 Accepted&lt;/code&gt;, and a few carried the answer to a different request id. Thirty rounds of six parallel calls on one session gave 137 correct answers, 21 foreign ones and 22 empty under FrankenPHP worker mode, and 150, 17 and 13 under php-fpm. Nothing in the logs. The same calls one at a time never failed.&lt;/p&gt;

&lt;p&gt;The server ran &lt;code&gt;symfony/mcp-bundle&lt;/code&gt; 0.14.1 on &lt;code&gt;mcp/sdk&lt;/code&gt; 0.8.1, the official PHP SDK for the Model Context Protocol. The cause is a lost-update race on the session that the SDK kept for every Streamable HTTP client, and the fix upstream took three pull requests and two releases. This article walks through the race with the 0.8.1 code, reproduces it with ten parallel calls against &lt;code&gt;php -S&lt;/code&gt;, shows what 0.9.0 and 0.10.0 changed, and explains why the MCP server in &lt;code&gt;mattleads/agent-publishing-bundle&lt;/code&gt; keeps no session at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.4.22, with &lt;code&gt;PHP_CLI_SERVER_WORKERS=8 php -S&lt;/code&gt; as the multi-process server for the reproduction. The race needs several workers and a session store they share; php-fpm and FrankenPHP worker mode behave the same.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mcp/sdk&lt;/code&gt; 0.8.1 (released 29 August 2026), 0.9.0 (18 October 2026) and 0.10.0 (10 November 2026), each cloned at its tag with &lt;code&gt;composer install&lt;/code&gt; for the dev dependencies, which include &lt;code&gt;nyholm/psr7&lt;/code&gt; and &lt;code&gt;laminas/laminas-httphandlerrunner&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;symfony/mcp-bundle&lt;/code&gt; 0.14.1, which requires &lt;code&gt;mcp/sdk ^0.8.1&lt;/code&gt;, and 0.15.0, which requires &lt;code&gt;^0.9&lt;/code&gt; and adds a &lt;code&gt;session.lock&lt;/code&gt; option.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mattleads/agent-publishing-bundle&lt;/code&gt; 0.3.1 for the stateless server, with its demo app from &lt;a href="https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c"&gt;the previous article&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. What a Streamable HTTP session is
&lt;/h2&gt;

&lt;p&gt;The Streamable HTTP transport in the MCP specification (revision 2025-06-18) is one HTTP endpoint. Every client message is a POST. A notification or a response gets &lt;code&gt;202 Accepted&lt;/code&gt; with no body. A request gets either &lt;code&gt;Content-Type: application/json&lt;/code&gt; with one JSON-RPC object, or an SSE stream that eventually carries the response. The client may also open a GET for server-initiated messages.&lt;/p&gt;

&lt;p&gt;Sessions are optional on the server side. The spec says a server "MAY assign a session ID at initialization time" through an &lt;code&gt;Mcp-Session-Id&lt;/code&gt; response header. If it does, the client must send that header on every later request, the server may end the session whenever it likes and answer &lt;code&gt;404&lt;/code&gt;, and a client that sees &lt;code&gt;404&lt;/code&gt; starts over with a new &lt;code&gt;initialize&lt;/code&gt;. A server that never sends the header has no session, and the client has nothing to carry.&lt;/p&gt;

&lt;p&gt;What a session is for is the other direction of the conversation. If the server wants to ask the client something (an elicitation, a sampling request), push a &lt;code&gt;notifications/resources/updated&lt;/code&gt;, or let the client resume a stream after a disconnect, it needs somewhere to park those messages between HTTP requests. That somewhere is the session, keyed by the id in the header. A server that only answers &lt;code&gt;tools/call&lt;/code&gt; has nothing to park.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What mcp/sdk 0.8.1 kept in the session
&lt;/h2&gt;

&lt;p&gt;The 0.8.1 server parks everything there, including the answer to the request it is currently handling. The relevant pieces are in &lt;code&gt;Mcp\Server\Protocol&lt;/code&gt; and &lt;code&gt;Mcp\Server\Transport\StreamableHttpTransport&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A POST arrives, &lt;code&gt;Protocol::doProcessInput()&lt;/code&gt; loads the session named by the header, handles each message, and saves the session once at the end:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// mcp/sdk 0.8.1, src/Server/Protocol.php, doProcessInput()&lt;/span&gt;
&lt;span class="nv"&gt;$session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;resolveSession&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$transport&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$sessionId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$messages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$messages&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ... handleRequest() / handleResponse() / handleNotification()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a tool handler returns, &lt;code&gt;handleRequest()&lt;/code&gt; calls &lt;code&gt;sendResponse()&lt;/code&gt;. With a session present the response is not sent. It is queued inside the session under the key &lt;code&gt;_mcp.outgoing_queue&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Server/Protocol.php, 0.8.1&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;SESSION_OUTGOING_QUEUE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'_mcp.outgoing_queue'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;sendResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TransportInterface&lt;/span&gt; &lt;span class="nv"&gt;$transport&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="nc"&gt;Error&lt;/span&gt; &lt;span class="nv"&gt;$response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;SessionInterface&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// ... json_encode and $transport-&amp;gt;send($encoded, $context);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;queueOutgoing&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'type'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'response'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;queueOutgoing&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="nc"&gt;Notification&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="nc"&gt;Error&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;SessionInterface&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
    &lt;span class="nv"&gt;$queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SESSION_OUTGOING_QUEUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$queue&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'message'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$encoded&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'context'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$context&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SESSION_OUTGOING_QUEUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$queue&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The transport then builds the HTTP response by reading the queue back, through &lt;code&gt;Protocol::consumeOutgoingMessages()&lt;/code&gt;, which loads the session again, takes the whole queue, writes an empty queue and saves:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Server/Protocol.php, 0.8.1&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;consumeOutgoingMessages&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Uuid&lt;/span&gt; &lt;span class="nv"&gt;$sessionId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;sessionManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createWithId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$sessionId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SESSION_OUTGOING_QUEUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SESSION_OUTGOING_QUEUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$session&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$queue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Server/Transport/StreamableHttpTransport.php, 0.8.1, createJsonResponse()&lt;/span&gt;
&lt;span class="nv"&gt;$outgoingMessages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getOutgoingMessages&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;sessionId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$outgoingMessages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;responseFactory&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;202&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withHeader&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Content-Type'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'application/json'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nv"&gt;$messages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;array_column&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$outgoingMessages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'message'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$responseBody&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; \&lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$messages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$messages&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'['&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;implode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;','&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$messages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;']'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two more details complete the picture. &lt;code&gt;Session::readData()&lt;/code&gt; reads the store once and caches the array for the life of the object, so the session a request works on is a snapshot taken when it was first touched. And &lt;code&gt;Session::save()&lt;/code&gt; in 0.8.1 is &lt;code&gt;json_encode($this-&amp;gt;readData())&lt;/code&gt; written back whole, every key, not only the ones this request changed.&lt;/p&gt;

&lt;p&gt;With one worker and one request at a time this is fine. The queue is read, appended, saved, read, emptied, saved, and the POST that carried the request gets its response. The design assumes the requests of a session are sequential. Nothing in PHP's deployment model guarantees that.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. The race, step by step
&lt;/h2&gt;

&lt;p&gt;Take two workers, A and B, each handling one &lt;code&gt;tools/call&lt;/code&gt; of the same session, with a shared &lt;code&gt;FileSessionStore&lt;/code&gt;. Each step reads or writes the whole session blob.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A loads the session. Queue: empty.&lt;/li&gt;
&lt;li&gt;B loads the session. Queue: empty.&lt;/li&gt;
&lt;li&gt;A's handler returns. A appends response RA to its in-memory queue and saves. Store: &lt;code&gt;[RA]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;B's handler returns. B appends RB to its own snapshot, which never saw RA, and saves. Store: &lt;code&gt;[RB]&lt;/code&gt;. RA is gone. That is the lost update.&lt;/li&gt;
&lt;li&gt;A's transport calls &lt;code&gt;consumeOutgoingMessages()&lt;/code&gt;. It loads the store fresh, takes &lt;code&gt;[RB]&lt;/code&gt;, writes &lt;code&gt;[]&lt;/code&gt;. A's HTTP response carries B's answer. That is the foreign answer.&lt;/li&gt;
&lt;li&gt;B's transport does the same. The queue is empty, so B answers &lt;code&gt;202&lt;/code&gt; with no body. That is the empty response.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Shift the timing a little and step 4 happens after step 5: B saves &lt;code&gt;[RB]&lt;/code&gt; after A emptied the queue, then B's own consume takes it. Both correct, by luck. Shift it the other way and A's consume runs after both saves of a three-worker race: it takes &lt;code&gt;[RB, RC]&lt;/code&gt; and the &lt;code&gt;implode&lt;/code&gt; branch sends a JSON array, which a spec-compliant client rejects, because the spec requires "a single JSON-RPC" object in a JSON response. The TypeScript client reports the lost ones as &lt;code&gt;MCP error -32001: Request timed out&lt;/code&gt;, which is what the n8n and LangChain users in the upstream issues saw.&lt;/p&gt;

&lt;p&gt;There is a fourth outcome that is a race on the file rather than on the queue. &lt;code&gt;FileSessionStore::write()&lt;/code&gt; in 0.8.1 writes to one temporary file per session, &lt;code&gt;&amp;lt;id&amp;gt;.tmp&lt;/code&gt;, and renames it into place. Two workers saving the same session at once share that temporary file, and in the reproduction below some requests died with &lt;code&gt;JsonException: Syntax error&lt;/code&gt; thrown from &lt;code&gt;Session::readData()&lt;/code&gt;: the worker read a session document that did not parse. That outcome shows up in the server log as a fatal error. The other three do not show up anywhere.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Reproducing it
&lt;/h2&gt;

&lt;p&gt;The server is short. One tool, a file session store, the SDK's Streamable HTTP transport over &lt;code&gt;nyholm/psr7&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="n"&gt;php&lt;/span&gt;
&lt;span class="c1"&gt;// server.php, run with: PHP_CLI_SERVER_WORKERS=8 php -S 127.0.0.1:8768 server.php&lt;/span&gt;
&lt;span class="k"&gt;require&lt;/span&gt; &lt;span class="nf"&gt;getenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'SDK_DIR'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/vendor/autoload.php'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Http&lt;/span&gt;\&lt;span class="nc"&gt;Discovery&lt;/span&gt;\&lt;span class="nc"&gt;Psr17Factory&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Laminas&lt;/span&gt;\&lt;span class="nc"&gt;HttpHandlerRunner&lt;/span&gt;\&lt;span class="nc"&gt;Emitter&lt;/span&gt;\&lt;span class="nc"&gt;SapiEmitter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Mcp&lt;/span&gt;\&lt;span class="nc"&gt;Server&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Mcp&lt;/span&gt;\&lt;span class="nc"&gt;Server&lt;/span&gt;\&lt;span class="nc"&gt;Session&lt;/span&gt;\&lt;span class="nc"&gt;FileSessionStore&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Mcp&lt;/span&gt;\&lt;span class="nc"&gt;Server&lt;/span&gt;\&lt;span class="nc"&gt;Transport&lt;/span&gt;\&lt;span class="nc"&gt;StreamableHttpTransport&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Psr&lt;/span&gt;\&lt;span class="nc"&gt;Log&lt;/span&gt;\&lt;span class="nc"&gt;NullLogger&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Tools&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;listSections&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'sections'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'blog'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nv"&gt;$server&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Server&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setServerInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'race-test'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'1.0.0'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setLogger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;NullLogger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;addTool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Tools&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'listSections'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'list_sections'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setSession&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;FileSessionStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;getenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'SESSION_DIR'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;StreamableHttpTransport&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Psr17Factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createServerRequestFromGlobals&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;NullLogger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SapiEmitter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;emit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;setSession()&lt;/code&gt; matters. Without it the 0.8.1 builder falls back to &lt;code&gt;InMemorySessionStore&lt;/code&gt;, which each worker process keeps for itself, so the second request of a session lands on a worker that has never heard of it and gets &lt;code&gt;404&lt;/code&gt;. That is a different bug, and the reason every production deployment uses a file or cache store, which is exactly what makes the race possible.&lt;/p&gt;

&lt;p&gt;The client is a Python script. It sends &lt;code&gt;initialize&lt;/code&gt;, keeps the &lt;code&gt;Mcp-Session-Id&lt;/code&gt;, sends &lt;code&gt;notifications/initialized&lt;/code&gt;, then runs rounds of ten &lt;code&gt;tools/call&lt;/code&gt; requests in ten threads, each with its own request id, and sorts the answers into five bins: a single object with the right id, a single object with another id, a JSON array, an empty &lt;code&gt;202&lt;/code&gt;, and anything else.&lt;/p&gt;

&lt;p&gt;One round of ten against 0.8.1 looked like this. Request &lt;code&gt;c1&lt;/code&gt; got its own answer. &lt;code&gt;c0&lt;/code&gt; got &lt;code&gt;c7&lt;/code&gt;'s, &lt;code&gt;c3&lt;/code&gt; and &lt;code&gt;c7&lt;/code&gt; both got &lt;code&gt;c9&lt;/code&gt;'s, &lt;code&gt;c4&lt;/code&gt;, &lt;code&gt;c8&lt;/code&gt; and &lt;code&gt;c9&lt;/code&gt; got &lt;code&gt;202&lt;/code&gt; with no body, and &lt;code&gt;c2&lt;/code&gt;, &lt;code&gt;c5&lt;/code&gt; and &lt;code&gt;c6&lt;/code&gt; got an HTML fatal error page from the torn session file. One right answer in ten.&lt;/p&gt;

&lt;p&gt;Over more rounds the numbers move with timing, so here is one run of each configuration rather than an average:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Server, 8 workers, 10 parallel calls per round&lt;/th&gt;
&lt;th&gt;Rounds&lt;/th&gt;
&lt;th&gt;Own answer&lt;/th&gt;
&lt;th&gt;Foreign answer&lt;/th&gt;
&lt;th&gt;JSON array&lt;/th&gt;
&lt;th&gt;Empty 202&lt;/th&gt;
&lt;th&gt;Fatal&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.8.1, &lt;code&gt;FileSessionStore&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;30&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;280&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;11&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.8.1, &lt;code&gt;FileSessionStore&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;100&lt;/td&gt;
&lt;td&gt;46&lt;/td&gt;
&lt;td&gt;897&lt;/td&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;td&gt;43&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.9.0, &lt;code&gt;FileSessionStore&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;30&lt;/td&gt;
&lt;td&gt;300&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.9.0, &lt;code&gt;FileSessionStore&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;100&lt;/td&gt;
&lt;td&gt;1,000&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.9.0, &lt;code&gt;FileSessionStore&lt;/code&gt; + &lt;code&gt;FileSessionLock&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;30&lt;/td&gt;
&lt;td&gt;300&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mcp/sdk 0.9.0, &lt;code&gt;FileSessionStore&lt;/code&gt; + &lt;code&gt;FileSessionLock&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;100&lt;/td&gt;
&lt;td&gt;1,000&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The author of the upstream fix measured the same shape with a different tool, &lt;code&gt;chr-hertel/mcp-concurrency-test&lt;/code&gt;, on FrankenPHP worker mode: 100 rounds of 10 calls, 0 rounds fully correct, 328 foreign and 185 lost before the fix, 100 rounds correct after. His production figure on 0.8.1 through &lt;code&gt;symfony/mcp-bundle&lt;/code&gt; was "1 call in 10 got a &lt;code&gt;202&lt;/code&gt;".&lt;/p&gt;

&lt;p&gt;The lock rows are correct and slow. With &lt;code&gt;FileSessionLock&lt;/code&gt; the 100-round run took 8.9 seconds against 0.7 seconds without it, because the lock does what it says: the ten calls of a round run one after another. We come back to that trade-off in section 7.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. What 0.9.0 changed
&lt;/h2&gt;

&lt;p&gt;The fix landed in three pull requests between 6 and 14 October 2026, all in 0.9.0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PR #535 took responses out of the session.&lt;/strong&gt; &lt;code&gt;Protocol::sendResponse()&lt;/code&gt; now hands every response to &lt;code&gt;TransportInterface::send()&lt;/code&gt; with the session id in the context, and &lt;code&gt;createJsonResponse()&lt;/code&gt; answers the POST with the responses of the requests that POST carried. The outgoing queue still exists, but only for server-initiated requests and notifications. The release note calls it a BC break for custom transports: &lt;code&gt;send()&lt;/code&gt; now receives every response of a handler, and a batch gets several. A POST of only notifications or responses is answered &lt;code&gt;202&lt;/code&gt; and the queued messages stay where they are. The same PR fixed the JSON array branch for the messages that do still go through the queue: a request whose session has queued notifications is answered as SSE, queued messages first, instead of as an array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PR #572 made &lt;code&gt;Session::save()&lt;/code&gt; write only the keys the request changed&lt;/strong&gt;, applied onto a fresh read of the store, so two requests that touch different keys of one session no longer overwrite each other. The 0.9.0 &lt;code&gt;save()&lt;/code&gt; also refuses to resurrect a session that was deleted while the request ran. A read-modify-write of the same key by two requests, such as a counter kept in the session by a tool handler, is still a race. That is what the lock is for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PR #584 added the opt-in per-session lock.&lt;/strong&gt; &lt;code&gt;Builder::setSessionLock()&lt;/code&gt; takes a &lt;code&gt;SessionLockInterface&lt;/code&gt;. &lt;code&gt;FileSessionLock&lt;/code&gt; uses &lt;code&gt;flock()&lt;/code&gt; on one file per session next to &lt;code&gt;FileSessionStore&lt;/code&gt;, for the workers of one machine. &lt;code&gt;SymfonyLockSessionLock&lt;/code&gt; wraps a &lt;code&gt;symfony/lock&lt;/code&gt; store, for sessions shared across machines through Redis or a database. &lt;code&gt;Protocol&lt;/code&gt; takes the lock before the session is read and releases it after the save, releases it while a handler is suspended waiting for the client, and takes it briefly on each turn of the SSE loop. A request that cannot get the lock within the timeout, 30 seconds by default, is answered &lt;code&gt;503&lt;/code&gt; with a JSON-RPC error under its own id.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$server&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Server&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setSession&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;FileSessionStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__DIR__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/sessions'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setSessionLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;FileSessionLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__DIR__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/sessions'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;symfony/mcp-bundle&lt;/code&gt; 0.15.0 the same thing is configuration: &lt;code&gt;session.lock.enabled&lt;/code&gt;, &lt;code&gt;session.lock.factory&lt;/code&gt; for a &lt;code&gt;LockFactory&lt;/code&gt; service when the store is not &lt;code&gt;file&lt;/code&gt;, &lt;code&gt;session.lock.timeout&lt;/code&gt; (30 seconds) and &lt;code&gt;session.lock.ttl&lt;/code&gt; (300 seconds). The bundle refuses a lock without a factory on any store but &lt;code&gt;file&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For the production server the upgrade was &lt;code&gt;symfony/mcp-bundle&lt;/code&gt; 0.14.1 to 0.15.0 and &lt;code&gt;mcp/sdk&lt;/code&gt; 0.8.1 to 0.9.0, nothing else. The same 30 rounds of six parallel calls went from 175 correct, 2 foreign and 3 empty on the last 0.8.1 build to 180 correct. The existing connector session kept working across the deploy. Three BC breaks in 0.9.0 are worth checking before you do the same: &lt;code&gt;OAuthRequestMetaMiddleware&lt;/code&gt; is gone and the validated token comes from &lt;code&gt;RequestContext::getAccessToken()&lt;/code&gt;, ids of requests the server sends to the client are UUIDs instead of integers, and &lt;code&gt;TransportInterface::send()&lt;/code&gt; has the new semantics above if you wrote your own transport. The lock stayed off: with responses out of the session and nothing else written per call, there was nothing left for it to protect.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. What 0.10.0 changed, and what the spec changed
&lt;/h2&gt;

&lt;p&gt;0.10.0 went a step further and made the no-session case the default. From the release notes: handshake-era servers over Streamable HTTP "run without sessions unless &lt;code&gt;Builder::setSession()&lt;/code&gt; is called". &lt;code&gt;initialize&lt;/code&gt; is answered without &lt;code&gt;Mcp-Session-Id&lt;/code&gt;, later requests run on an ephemeral session that is never stored, and GET and DELETE get &lt;code&gt;405&lt;/code&gt;. The old fallback to &lt;code&gt;InMemorySessionStore&lt;/code&gt;, the one that produced &lt;code&gt;404&lt;/code&gt;s under any multi-process server, is gone. A server that wants sessions declares a store, and with it accepts the race surface and, if it needs to, the lock.&lt;/p&gt;

&lt;p&gt;Two other 0.10.0 changes bear on this article. JSON-RPC batches are refused with &lt;code&gt;-32600&lt;/code&gt; and HTTP &lt;code&gt;400&lt;/code&gt; on every protocol revision, including 2025-03-26, which required batch support. And PHP 8.2 is the minimum.&lt;/p&gt;

&lt;p&gt;The protocol moved the same way. MCP revision 2026-07-28 removed protocol-level sessions and the &lt;code&gt;Mcp-Session-Id&lt;/code&gt; header from the Streamable HTTP transport (SEP-2567), and removed the &lt;code&gt;initialize&lt;/code&gt; handshake (SEP-2575). Every request carries its protocol version and client capabilities in &lt;code&gt;_meta&lt;/code&gt;, and a server that needs state across calls hands the client an explicit handle as an ordinary tool argument. The SDK's release notes call the two designs the handshake era and the modern era, and 0.8.1 already served both on one endpoint. The design that caused the race is the one the protocol is retiring.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. When you still want a session
&lt;/h2&gt;

&lt;p&gt;Sessionless is not free. A session is the only place a server can keep things the protocol expects it to keep between HTTP requests on the handshake-era revisions that most clients still speak:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Requests from the server to the client.&lt;/strong&gt; Elicitation and sampling suspend the handler in a fiber, send a request over the stream, and resume when the client's answer arrives in a later POST. The pending request and the fiber's state live in the session.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server-initiated notifications.&lt;/strong&gt; &lt;code&gt;notifications/resources/updated&lt;/code&gt; for a subscription, or &lt;code&gt;notifications/tools/list_changed&lt;/code&gt;, need a queue the GET stream can drain.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resumable streams.&lt;/strong&gt; A client that lost its SSE connection can send &lt;code&gt;Last-Event-ID&lt;/code&gt; and expect the server to replay what it missed, which means the server stored it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your server does any of that, keep the session, and on 0.9.0 or later turn the lock on. The price is the one in the table: the calls of one session run one at a time, so a client that sends ten calls in parallel waits for the slowest chain of ten. For quick tools that is invisible. For tools that wait on an external API it adds up, and the modern-era design, state in an explicit handle rather than in a session, is the way out.&lt;/p&gt;

&lt;p&gt;If your server does none of that, the session is pure liability. It costs a store, it costs a lock or a race, and it buys nothing.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. A tools-only server with no session
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;mattleads/agent-publishing-bundle&lt;/code&gt; exposes its publishing tools over MCP so an agent can draft, lint and submit articles. The decision in &lt;a href="https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c"&gt;the article that introduced it&lt;/a&gt; was to implement the protocol directly rather than depend on &lt;code&gt;mcp/sdk&lt;/code&gt; while it was moving. The race is the other half of that decision. The server offers &lt;code&gt;initialize&lt;/code&gt;, &lt;code&gt;ping&lt;/code&gt;, &lt;code&gt;tools/list&lt;/code&gt; and &lt;code&gt;tools/call&lt;/code&gt;, acknowledges notifications, and that is the whole surface. No resources, no prompts, no server-initiated requests, so no session.&lt;/p&gt;

&lt;p&gt;The transport is one Symfony controller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// agent-publishing-bundle, src/Mcp/McpController.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;endpoint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
    &lt;span class="nv"&gt;$headers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'MCP-Protocol-Version'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;McpServer&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;negotiate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'MCP-Protocol-Version'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isMethod&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'DELETE'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;HTTP_NO_CONTENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isMethod&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'POST'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'error'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Send JSON-RPC messages with POST. This server does not open server-to-client streams.'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;HTTP_METHOD_NOT_ALLOWED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$headers&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'Allow'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'POST, DELETE'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// ... decode the body, resolve the API key from the Authorization header&lt;/span&gt;

    &lt;span class="nv"&gt;$batch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;array_is_list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$payload&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$messages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$batch&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$payload&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$payload&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$responses&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$messages&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// ...&lt;/span&gt;
        &lt;span class="nv"&gt;$response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;server&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nv"&gt;$response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$responses&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$response&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$responses&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;HTTP_ACCEPTED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$batch&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$responses&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$responses&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;HTTP_OK&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every response is computed from the request that carried it and returned in the same HTTP response. There is no queue, no store, no id to look up. &lt;code&gt;initialize&lt;/code&gt; answers without &lt;code&gt;Mcp-Session-Id&lt;/code&gt;, so the client has nothing to send back and nothing to lose. GET answers &lt;code&gt;405&lt;/code&gt;, which the spec allows for a server "that does not offer an SSE stream". DELETE answers &lt;code&gt;204&lt;/code&gt;, because ending a session that does not exist is a no-op. The identity that a session would otherwise carry, which client this is and what it may do, comes from the API key on every request, and &lt;code&gt;tools/list&lt;/code&gt; is filtered by that key's scopes. The server negotiates the three handshake-era revisions, 2025-06-18, 2025-03-26 and 2024-11-05, and accepts a JSON array from a 2025-03-26 client because that revision required it, which is one place it is more lenient than &lt;code&gt;mcp/sdk&lt;/code&gt; 0.10.0.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;McpServer::handle()&lt;/code&gt; returns &lt;code&gt;null&lt;/code&gt; for a message without an &lt;code&gt;id&lt;/code&gt;, which is how a notification becomes a &lt;code&gt;202&lt;/code&gt;. A batch answers only its requests. The bundle's functional test, &lt;code&gt;tests/Functional/McpTest.php&lt;/code&gt;, drives the handshake, the version echo, a &lt;code&gt;notifications/initialized&lt;/code&gt; with its empty &lt;code&gt;202&lt;/code&gt;, scope-filtered tool lists for an agent key and an editor key, the full agent loop from &lt;code&gt;list_sections&lt;/code&gt; to &lt;code&gt;submit_article&lt;/code&gt;, tool errors as results with &lt;code&gt;isError&lt;/code&gt;, protocol errors with JSON-RPC codes, a batch, the GET &lt;code&gt;405&lt;/code&gt; and the DELETE &lt;code&gt;204&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The same race script, pointed at the demo app on 8 workers with &lt;code&gt;initialize&lt;/code&gt; and 10 parallel &lt;code&gt;tools/call list_sections&lt;/code&gt; per round:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Server, 8 workers, 10 parallel calls per round&lt;/th&gt;
&lt;th&gt;Rounds&lt;/th&gt;
&lt;th&gt;Own answer&lt;/th&gt;
&lt;th&gt;Foreign&lt;/th&gt;
&lt;th&gt;Array&lt;/th&gt;
&lt;th&gt;Empty 202&lt;/th&gt;
&lt;th&gt;Fatal&lt;/th&gt;
&lt;th&gt;Time&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;agent-publishing-bundle 0.3.1 on Symfony 8.1, &lt;code&gt;php -S&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;30&lt;/td&gt;
&lt;td&gt;300&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0.8 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;agent-publishing-bundle 0.3.1 on Symfony 8.1, &lt;code&gt;php -S&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;100&lt;/td&gt;
&lt;td&gt;1,000&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;2.6 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Nothing is shared between the requests of a client, so there is nothing to race. The time is the Symfony kernel booting per request under &lt;code&gt;php -S&lt;/code&gt;, not serialization.&lt;/p&gt;

&lt;p&gt;The limitation is the one stated in the previous article: agents that need resources, prompts or server-to-client streams need a different server. For a publishing workflow, where the agent's job is to call tools and read their results, that has not come up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Each pattern here maps to a decision you make once per server.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Tools only, no server-initiated messages.&lt;/strong&gt; Do not keep a session. Answer each POST from its own request, authenticate every request on its own, and send no &lt;code&gt;Mcp-Session-Id&lt;/code&gt;. That is what &lt;code&gt;mcp/sdk&lt;/code&gt; 0.10.0 does by default, what MCP 2026-07-28 made the only option, and what &lt;code&gt;agent-publishing-bundle&lt;/code&gt; does on every revision it serves.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Elicitation, sampling, subscriptions or resumable streams.&lt;/strong&gt; Keep a session, use a store every worker can reach, and on &lt;code&gt;mcp/sdk&lt;/code&gt; 0.9.0 or later turn on the per-session lock. Accept that one session's calls run in series.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Still on &lt;code&gt;mcp/sdk&lt;/code&gt; 0.8.x behind php-fpm or FrankenPHP.&lt;/strong&gt; Upgrade before anything else. The race is in every multi-process deployment, and the first symptom you will see is an agent reporting a timeout on a call your logs say succeeded.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you are writing the server, test it the way agents use it: ten calls at once on one session, against several workers, counting whose answer came back.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/agent-publishing-bundle" rel="noopener noreferrer"&gt;https://github.com/mattleads/agent-publishing-bundle&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>php</category>
      <category>mcp</category>
      <category>symfony</category>
      <category>ai</category>
    </item>
    <item>
      <title>One Kernel for Every Tenant: FrankenPHP Worker Mode for Database-per-Tenant Symfony 8.1</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Mon, 16 Nov 2026 08:39:01 +0000</pubDate>
      <link>https://dev.to/mattleads/one-kernel-for-every-tenant-frankenphp-worker-mode-for-database-per-tenant-symfony-81-2o77</link>
      <guid>https://dev.to/mattleads/one-kernel-for-every-tenant-frankenphp-worker-mode-for-database-per-tenant-symfony-81-2o77</guid>
      <description>&lt;p&gt;In &lt;a href="https://dev.to/mattleads/stop-paying-for-idle-tenants-database-per-tenant-symfony-81-on-one-shared-deployment"&gt;part 1&lt;/a&gt; we put every free tenant of a database-per-tenant SaaS on one shared Symfony 8.1 deployment. Each request names its tenant in the path, a DBAL wrapper reconnects to the tenant's database, a cache decorator namespaces by tenant, and one Messenger worker reads every tenant's stream. The saving was memory: one set of processes per placement instead of one per tenant.&lt;/p&gt;

&lt;p&gt;The HTTP side of that deployment still ran under php-fpm, and php-fpm forgets everything between requests. Every request boots the kernel, loads the compiled container, asks Redis whether the tenant is placed here, and opens a connection to the tenant's database. Part 1 measured that last step at about six milliseconds per switch and shrugged, because a php-fpm request pays a connection anyway. This article is about that shrug.&lt;/p&gt;

&lt;p&gt;FrankenPHP's worker mode keeps the kernel alive across requests. For a single-tenant app that is a throughput story. For a shared multi-tenant deployment it changes what a tenant switch costs, and it changes which state leaks if you are careless. We'll move the demo from part 1 to FrankenPHP, keep one open connection per tenant database inside each worker, go through the state that must and must not survive a request, and measure four deployments under a load that changes tenant on every request.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The demo from part 1: &lt;a href="https://github.com/mattleads/tenant-shared-demo" rel="noopener noreferrer"&gt;mattleads/tenant-shared-demo&lt;/a&gt;, PHP 8.4, Symfony 8.1, Doctrine DBAL 4, PostgreSQL 16 and Redis 7 in Docker.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;symfony/runtime&lt;/code&gt; 7.4 or later. It ships &lt;code&gt;FrankenPhpWorkerRunner&lt;/code&gt; and detects worker mode on its own, so the separate &lt;code&gt;runtime/frankenphp-symfony&lt;/code&gt; package is not needed. That package is still capped at Symfony 7 at the time of writing and will not install on 8.1.&lt;/li&gt;
&lt;li&gt;FrankenPHP 1.13 from the &lt;code&gt;dunglas/frankenphp:1-php8.4&lt;/code&gt; image (PHP 8.4.27, Caddy 2.11), &lt;code&gt;php:8.4-fpm-alpine&lt;/code&gt; and &lt;code&gt;nginx:1.27-alpine-slim&lt;/code&gt; for the baseline, and &lt;code&gt;wrk&lt;/code&gt; for the load.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Everything below is in the same repository: &lt;code&gt;docker/&lt;/code&gt;, &lt;code&gt;compose.bench.yaml&lt;/code&gt;, &lt;code&gt;scripts/bench.sh&lt;/code&gt; and &lt;code&gt;bench/&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. What php-fpm throws away on every request
&lt;/h2&gt;

&lt;p&gt;Trace one &lt;code&gt;GET /tenant_&amp;lt;uuid&amp;gt;/notes&lt;/code&gt; on the shared deployment of part 1:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;PHP starts, opcache hands over the compiled files, the kernel boots and the container is instantiated.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;TenantRequestListener&lt;/code&gt; reads the prefix and asks &lt;code&gt;PlacementReader&lt;/code&gt; whether the tenant is served here. The reader has a 30 second in-memory cache, which under php-fpm is always empty, so this is one &lt;code&gt;HGET&lt;/code&gt; on Redis per request.&lt;/li&gt;
&lt;li&gt;The repository runs its query. &lt;code&gt;TenantConnection::connect()&lt;/code&gt; opens a connection to &lt;code&gt;tenant_&amp;lt;uuid&amp;gt;&lt;/code&gt; first: a TCP handshake, Postgres authentication, a backend process forked on the server.&lt;/li&gt;
&lt;li&gt;The response goes out and the process forgets all of it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Step 3 is the one we measured in part 1 with &lt;code&gt;app:bench:switch&lt;/code&gt;, the command that runs &lt;code&gt;SELECT 1&lt;/code&gt; three hundred times on one tenant and then three hundred times alternating tenants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;300 queries on one tenant:              0.172 ms per query
300 queries switching tenant each time: 5.976 ms per query (299 reconnects)
cost of a tenant switch: 5.80 ms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Under php-fpm nothing can be done about steps 1 to 3 except making each cheaper. Under a worker they can stop happening.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. FrankenPHP in one Dockerfile and three environment variables
&lt;/h2&gt;

&lt;p&gt;FrankenPHP is a PHP SAPI embedded in Caddy. It serves PHP two ways. In classic mode each request gets a fresh PHP execution, like php-fpm but without FastCGI and without a separate web server. In worker mode a script is started once per worker thread and handles requests in a loop. Both modes run from the same image; only the configuration differs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight docker"&gt;&lt;code&gt;&lt;span class="c"&gt;# docker/frankenphp/Dockerfile&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; dunglas/frankenphp:1-php8.4

&lt;span class="k"&gt;RUN&lt;/span&gt; install-php-extensions pdo_pgsql redis intl opcache zip
&lt;span class="k"&gt;COPY&lt;/span&gt; --from=composer:2 /usr/bin/composer /usr/bin/composer
&lt;span class="k"&gt;COPY&lt;/span&gt; docker/php/app.ini /usr/local/etc/php/conf.d/app.ini

&lt;span class="k"&gt;ENV&lt;/span&gt; &lt;span class="nv"&gt;APP_ENV&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;prod &lt;span class="nv"&gt;APP_DEBUG&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;0 &lt;span class="nv"&gt;SERVER_NAME&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;:80 &lt;span class="nv"&gt;SERVER_ROOT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;/app/public
&lt;span class="k"&gt;WORKDIR&lt;/span&gt; /app

&lt;span class="k"&gt;COPY&lt;/span&gt; composer.json composer.lock symfony.lock ./
&lt;span class="k"&gt;RUN&lt;/span&gt; composer install --no-dev --no-scripts --no-progress --prefer-dist --no-autoloader
&lt;span class="k"&gt;COPY&lt;/span&gt; . .
&lt;span class="k"&gt;RUN&lt;/span&gt; composer dump-autoload --no-dev --classmap-authoritative \
 &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; bin/console cache:warmup --no-interaction \
 &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; chown -R www-data:www-data var
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The image ships a Caddyfile that reads its site block from &lt;code&gt;SERVER_NAME&lt;/code&gt; and &lt;code&gt;SERVER_ROOT&lt;/code&gt;, and its FrankenPHP block from &lt;code&gt;FRANKENPHP_CONFIG&lt;/code&gt;. Classic mode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;FRANKENPHP_CONFIG&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;num_threads 8&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Worker mode, eight workers running &lt;code&gt;public/index.php&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;FRANKENPHP_CONFIG&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt;
  &lt;span class="s"&gt;num_threads 8&lt;/span&gt;
  &lt;span class="s"&gt;worker ./public/index.php 8&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nothing in &lt;code&gt;public/index.php&lt;/code&gt; changes. Since &lt;code&gt;symfony/runtime&lt;/code&gt; 7.4, &lt;code&gt;SymfonyRuntime::getRunner()&lt;/code&gt; checks the &lt;code&gt;FRANKENPHP_WORKER&lt;/code&gt; variable that FrankenPHP sets inside a worker and returns a &lt;code&gt;FrankenPhpWorkerRunner&lt;/code&gt;. That runner is short enough to read in full, and you should, because it decides what your application sees between requests:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It calls &lt;code&gt;frankenphp_handle_request()&lt;/code&gt; in a loop. For each request it builds a &lt;code&gt;Request&lt;/code&gt; from globals, calls &lt;code&gt;$kernel-&amp;gt;handle()&lt;/code&gt;, sends the response, then calls &lt;code&gt;$kernel-&amp;gt;terminate()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;After each request it drops its references to the request and response and runs &lt;code&gt;gc_collect_cycles()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It stops after &lt;code&gt;FRANKENPHP_LOOP_MAX&lt;/code&gt; requests, 500 by default, and FrankenPHP starts a fresh worker. A slow leak is bounded by that number.&lt;/li&gt;
&lt;li&gt;With &lt;code&gt;FRANKENPHP_RESET_KERNEL=1&lt;/code&gt; it clones the kernel after every request. That is the heavy option for applications with state you cannot track down. We will not need it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;$_SERVER['APP_RUNTIME_MODE']&lt;/code&gt; tells the application how it runs: &lt;code&gt;web=1&lt;/code&gt; under php-fpm or classic FrankenPHP, &lt;code&gt;web=1&amp;amp;worker=1&lt;/code&gt; inside a worker. The demo's &lt;code&gt;/whoami&lt;/code&gt; prints it.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. What survives a request, and what must not
&lt;/h2&gt;

&lt;p&gt;A worker keeps the kernel, the container and every service instance alive. For a multi-tenant application that is the whole question. Go through the state of part 1 one item at a time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The tenant itself.&lt;/strong&gt; &lt;code&gt;TenantContext&lt;/code&gt; is static. It is set by &lt;code&gt;TenantRequestListener&lt;/code&gt; on &lt;code&gt;kernel.request&lt;/code&gt; and cleared on &lt;code&gt;kernel.terminate&lt;/code&gt;. The worker runner calls &lt;code&gt;terminate()&lt;/code&gt; after every request, including one that ended in an exception caught by the kernel, so the next request starts without a tenant and a path without a prefix is still a 404. If your tenant context has no clear on terminate, add one before you turn worker mode on. A worker that keeps the previous tenant and serves a request without a prefix answers from the wrong database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open transactions.&lt;/strong&gt; A controller that throws between &lt;code&gt;beginTransaction()&lt;/code&gt; and &lt;code&gt;commit()&lt;/code&gt; leaves the connection inside that transaction. Under php-fpm the process ended the request and the server rolled it back. In a worker the connection survives, and Doctrine's &lt;code&gt;kernel.reset&lt;/code&gt; recreates the entity manager but keeps the connection, so the next request runs inside the leftover transaction, or, if it is for another tenant, hits the transaction guard of &lt;code&gt;TenantConnection&lt;/code&gt;. The demo rolls back on &lt;code&gt;kernel.terminate&lt;/code&gt;, next to the tenant clear, and logs a warning naming the request that left it open. &lt;code&gt;TwoTenantIsolationTest&lt;/code&gt; reproduces it with one kernel serving two requests, the way the worker does. A reader pointed this out after the first version of this article went out; the first version only cleared the tenant.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Services reset by the kernel.&lt;/strong&gt; Symfony resets tagged services before it handles the next request. &lt;code&gt;Kernel::boot()&lt;/code&gt; checks a &lt;code&gt;resetServices&lt;/code&gt; flag set by the previous &lt;code&gt;handle()&lt;/code&gt; and calls &lt;code&gt;services_resetter&lt;/code&gt;, which runs every &lt;code&gt;kernel.reset&lt;/code&gt; method: the entity manager clears its identity map, the Doctrine connection does nothing, loggers flush, and the part 1 cache decorator &lt;code&gt;TenantAwareCache::reset()&lt;/code&gt; drops its per-tenant sub-pools. That decorator inherited the &lt;code&gt;kernel.reset&lt;/code&gt; tag from &lt;code&gt;cache.app&lt;/code&gt; when it took over the service id, so there is nothing to add. This is the same mechanism Messenger workers have relied on since they exist, so a codebase whose workers are clean is most of the way there.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The placement cache.&lt;/strong&gt; &lt;code&gt;PlacementReader&lt;/code&gt; keeps the list of served tenants for 30 seconds. Under php-fpm that cache never outlived a request and the TTL was decorative. In a worker it is real: a tenant moved to another placement keeps being served here for up to 30 seconds by each worker that had read the list. Decide whether that is acceptable for your move procedure. The demo's &lt;code&gt;app:tenant:place&lt;/code&gt; invalidates its own reader, which does nothing for the workers; a move that must be immediate needs a shorter TTL or a Redis pub/sub signal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The database connection.&lt;/strong&gt; This is the one we want to survive. &lt;code&gt;TenantConnection&lt;/code&gt; from part 1 already keeps its connection as long as the tenant does not change, and under php-fpm that meant nothing. In a worker it means the second request of the same tenant on the same worker runs no handshake. Three tenants in turn, though, still reconnect on every request, because the wrapper closes the previous connection before opening the next one. Section 4 fixes that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Static counters, singletons, memoized lookups.&lt;/strong&gt; Part 1 counted 31 classes with tenant-specific state in constructors in the production codebase, and a scan test keeps them from coming back. That test is the entry ticket to worker mode. A memoized "current tenant's settings" in a private property, a &lt;code&gt;static $cache&lt;/code&gt; keyed by nothing, a connection pool keyed by nothing: each of them is correct under php-fpm and a cross-tenant leak under a worker. Run the scan, then run two tenants through one worker in a test, as in section 7.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Keep one connection per tenant database
&lt;/h2&gt;

&lt;p&gt;The wrapper from part 1 switched database by closing and reconnecting. In a worker the switch happens on most requests, so instead of closing the previous connection we park it, keyed by database name, and take it back the next time that tenant comes round. The number of connections a process keeps is a query parameter of &lt;code&gt;DATABASE_URL&lt;/code&gt;, so a php-fpm deployment and a worker deployment can run the same image with different settings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight conf"&gt;&lt;code&gt;&lt;span class="na"&gt;DATABASE_URL&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;postgresql&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="c1"&gt;//app:app@database:5432/app?serverVersion=16&amp;amp;charset=utf8&amp;amp;tenantConnections=16&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;DoctrineBundle merges every query parameter of the URL into the connection parameters, so the wrapper reads it from &lt;code&gt;getParams()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantConnection.php&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TenantConnection&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Connection&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$connectedTo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="cm"&gt;/** @var array&amp;lt;string, DriverConnection&amp;gt; Open connections of other tenants, least recently used first. */&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$parked&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="cm"&gt;/** How many times this connection opened a driver connection, for the benchmark and /whoami. */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$connects&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DriverConnection&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getParams&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;databaseFor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'dbname'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$target&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isTransactionActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; \&lt;span class="nc"&gt;LogicException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Tenant changed to %s inside a database transaction'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// take the target out before parking the current one, so it cannot be the one dropped over the limit&lt;/span&gt;
        &lt;span class="nv"&gt;$resumed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nb"&gt;unset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$resumed&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$connection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$resumed&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$connection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;driver&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'dbname'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Driver&lt;/span&gt;\&lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;convertException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$connects&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isAutoCommit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;beginTransaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/** Keep the current connection for its tenant's next turn, dropping the least recently used one over the limit. */&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$keep&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'tenantConnections'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$keep&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$keep&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nb"&gt;unset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;array_key_first&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;parked&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things to notice. The default is 1, which is the part 1 behavior: close on switch, right for php-fpm where a kept connection would die with the process anyway. The parked array is ordered by last use, so a worker that serves a hundred tenants with &lt;code&gt;tenantConnections=16&lt;/code&gt; keeps the sixteen it saw most recently, and dropping one is a plain &lt;code&gt;unset&lt;/code&gt;: PDO closes the connection in its destructor. The transaction guard is unchanged, a switch inside a transaction is still refused, kept connections or not.&lt;/p&gt;

&lt;p&gt;The first bug I wrote here is the comment in the middle. Parking the current connection before taking the target out of the parked list evicts the very connection you are about to reuse, as soon as the list is full. The test in section 7 caught it on the second case.&lt;/p&gt;

&lt;p&gt;The CLI benchmark from part 1 with the parameter set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;300 queries on one tenant:              0.154 ms per query
300 queries switching tenant each time: 0.160 ms per query (2 reconnects)
cost of a tenant switch: 0.01 ms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two reconnects for three tenants: the first was already connected. The switch went from 5.80 milliseconds to the cost of an array lookup.&lt;/p&gt;

&lt;p&gt;Postgres sees the difference as idle backends. A worker that keeps 16 connections holds 16 Postgres backends, each a process with a few megabytes of its own. Eight workers times sixteen is 128 backends from one container, so set &lt;code&gt;tenantConnections&lt;/code&gt; from &lt;code&gt;max_connections&lt;/code&gt; on the server, not from the number of tenants, and put PgBouncer in session mode in front if the sum across placements gets close.&lt;/p&gt;

&lt;p&gt;The same knob applies to the Messenger worker of part 1, which was already a long-lived process and reconnected on most messages. Set it in the worker's &lt;code&gt;DATABASE_URL&lt;/code&gt; too.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Watching a worker switch tenant
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;/whoami&lt;/code&gt; now reports how the process runs and what its connection has done. Twelve requests rotating three tenants against worker mode without kept connections, then a thirteenth:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;"tenant"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;"11111111-…"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"runtime"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;"web=1&amp;amp;worker=1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"connects"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"open"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"tenant_11111111_…"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same against worker mode with &lt;code&gt;tenantConnections=16&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;"tenant"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;"11111111-…"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"runtime"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s2"&gt;"web=1&amp;amp;worker=1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"connects"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nl"&gt;"open"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"tenant_22222222_…"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s2"&gt;"tenant_33333333_…"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s2"&gt;"tenant_11111111_…"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three connections for thirteen requests, three databases open, the current one last. One detail that bites when you read these numbers: FrankenPHP workers are threads of one process, so &lt;code&gt;pid&lt;/code&gt; is 1 in every answer, and PHP statics such as &lt;code&gt;$connects&lt;/code&gt; are per thread. Each worker thread counts its own connections.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. The benchmark: four deployments, a tenant switch on every request
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;compose.bench.yaml&lt;/code&gt; starts the same code four ways on the Postgres and Redis of part 1, every container limited to 4 CPUs and 8 PHP threads or processes:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;serves PHP with&lt;/th&gt;
&lt;th&gt;tenant connections kept&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;fpm-nginx&lt;/td&gt;
&lt;td&gt;php-fpm 8.4, &lt;code&gt;pm = static&lt;/code&gt;, 8 children, behind nginx&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp&lt;/td&gt;
&lt;td&gt;FrankenPHP classic mode, 8 threads&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp-worker&lt;/td&gt;
&lt;td&gt;FrankenPHP worker mode, 8 workers&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp-worker-keep&lt;/td&gt;
&lt;td&gt;FrankenPHP worker mode, 8 workers&lt;/td&gt;
&lt;td&gt;16&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;code&gt;scripts/bench.sh&lt;/code&gt; gives every tenant 20 notes, warms each deployment for 10 seconds and then runs &lt;code&gt;wrk&lt;/code&gt; for 20 seconds with 4 threads and 32 connections. The Lua script sends &lt;code&gt;GET /tenant_&amp;lt;uuid&amp;gt;/notes&lt;/code&gt; for the three tenants in turn, so each PHP thread or process sees a tenant switch on most requests. That endpoint runs the request listener, the Redis placement check, an ORM query and JSON serialization: a small but real page.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;deployment&lt;/th&gt;
&lt;th&gt;requests/s&lt;/th&gt;
&lt;th&gt;avg latency&lt;/th&gt;
&lt;th&gt;p50&lt;/th&gt;
&lt;th&gt;p99&lt;/th&gt;
&lt;th&gt;max&lt;/th&gt;
&lt;th&gt;DB connections opened&lt;/th&gt;
&lt;th&gt;container RSS&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;fpm-nginx&lt;/td&gt;
&lt;td&gt;690&lt;/td&gt;
&lt;td&gt;46.28 ms&lt;/td&gt;
&lt;td&gt;45.44 ms&lt;/td&gt;
&lt;td&gt;70.09 ms&lt;/td&gt;
&lt;td&gt;81.35 ms&lt;/td&gt;
&lt;td&gt;13,892&lt;/td&gt;
&lt;td&gt;41.6 MiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp (classic)&lt;/td&gt;
&lt;td&gt;366&lt;/td&gt;
&lt;td&gt;87.06 ms&lt;/td&gt;
&lt;td&gt;90.30 ms&lt;/td&gt;
&lt;td&gt;113.40 ms&lt;/td&gt;
&lt;td&gt;153.72 ms&lt;/td&gt;
&lt;td&gt;7,383&lt;/td&gt;
&lt;td&gt;78.0 MiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp-worker&lt;/td&gt;
&lt;td&gt;553&lt;/td&gt;
&lt;td&gt;57.70 ms&lt;/td&gt;
&lt;td&gt;64.33 ms&lt;/td&gt;
&lt;td&gt;88.14 ms&lt;/td&gt;
&lt;td&gt;280.13 ms&lt;/td&gt;
&lt;td&gt;7,771&lt;/td&gt;
&lt;td&gt;68.7 MiB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;frankenphp-worker-keep&lt;/td&gt;
&lt;td&gt;8,521&lt;/td&gt;
&lt;td&gt;3.86 ms&lt;/td&gt;
&lt;td&gt;3.38 ms&lt;/td&gt;
&lt;td&gt;10.65 ms&lt;/td&gt;
&lt;td&gt;41.41 ms&lt;/td&gt;
&lt;td&gt;1,026&lt;/td&gt;
&lt;td&gt;75.4 MiB&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;20 seconds each, no errors in any row. "DB connections opened" is what Postgres counted in &lt;code&gt;pg_stat_database.sessions&lt;/code&gt; for the three tenant databases during the measured run, not what PHP believes. The full output of each run is in &lt;code&gt;bench/&lt;/code&gt; and the table is &lt;code&gt;bench/results-2026-11-12-sslmode-prefer.md&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Read the table from the bottom. Worker mode with kept connections serves 8,521 requests per second with a p99 of 10.65 milliseconds, against 690 and 70 milliseconds for php-fpm: twelve times the throughput on the same 4 CPUs, with no change to a controller, a repository or a route. Its connection column is the other thing to read. Eight workers times three tenants is 24 connections for the whole run; Postgres counted 1,026. That is &lt;code&gt;FRANKENPHP_LOOP_MAX&lt;/code&gt;: a worker recycles after 500 requests, 170,000 requests is about 340 recycles, and every new worker opens its three connections again. Raise the loop max and that column drops to 24.&lt;/p&gt;

&lt;p&gt;The two middle rows are the ones a benchmark on a single-tenant app would not show you. Worker mode without kept connections is slower than php-fpm. It saves the kernel boot and the placement read, and it still opens a connection for 7,771 of its 11,100 requests, because the tenant changes on most of them. The connect it keeps paying costs more than the boot it saves. Classic FrankenPHP is slower still, at about half of php-fpm's throughput, and that one took me a while.&lt;/p&gt;

&lt;p&gt;The memory column is the part 1 saving unchanged: one set of processes per placement either way. The FrankenPHP container sits at 69 to 78 MiB with Caddy and eight PHP threads inside, the eight php-fpm children at 42 MiB, nginx not counted.&lt;/p&gt;

&lt;h3&gt;
  
  
  A trap I did not expect: concurrent connects inside one process
&lt;/h3&gt;

&lt;p&gt;The classic FrankenPHP row is slower than php-fpm on this page, which it is not on a page without a database: on &lt;code&gt;/health&lt;/code&gt; alone, classic mode serves about 1.5 times the requests of php-fpm and worker mode about 3.8 times. The difference is the connect. A single &lt;code&gt;new PDO(...)&lt;/code&gt; to a tenant database takes about 4 milliseconds from either image, measured in a loop. Eight CLI processes in the FrankenPHP container running that loop at the same time still get 4.5 milliseconds each. Eight FrankenPHP threads serving a script that only connects and disconnects get about 390 connects per second between them, against about 1,800 for the eight processes.&lt;/p&gt;

&lt;p&gt;Something between &lt;code&gt;pdo_pgsql&lt;/code&gt; and libpq 17 serializes connection setup across the threads of one process. It is not SSL negotiation, not GSS negotiation and not name resolution: &lt;code&gt;sslmode=disable&lt;/code&gt;, &lt;code&gt;gssencmode=disable&lt;/code&gt; and connecting by IP each left the number where it was. I stopped there, because the fix for a shared deployment is the same whatever the lock is: stop connecting. With &lt;code&gt;tenantConnections&lt;/code&gt; set, a worker opens its connections once and the lock is never contended. If you run FrankenPHP without kept connections on a connect-heavy page, expect php-fpm to win.&lt;/p&gt;

&lt;p&gt;Docker Desktop on a laptop, with the load generator, Postgres and Redis on the same machine: the absolute numbers say nothing about your servers. The ratios between the rows are the point, and they will move with your page. A page that spends 50 milliseconds in queries gains less from skipping a 6 millisecond connect than one that spends 5.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Testing it
&lt;/h2&gt;

&lt;p&gt;Two tests, both against the real Postgres of the demo. &lt;code&gt;TenantConnectionKeepTest&lt;/code&gt; builds a &lt;code&gt;TenantConnection&lt;/code&gt; straight from &lt;code&gt;DATABASE_URL&lt;/code&gt; with &lt;code&gt;tenantConnections&lt;/code&gt; set and walks it through tenants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// tests/TenantConnectionKeepTest.php (abridged)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;testKeptConnectionsAreReusedAndTheLeastRecentlyUsedIsDropped&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$connection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;connection&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$before&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TenantConnection&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$connects&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;B&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TenantConnection&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$connects&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nv"&gt;$before&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'A came back from the parked connection'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;B&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;C&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TenantConnection&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$connects&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nv"&gt;$before&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;C&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'B was the least recently used'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A third case begins a transaction on one tenant, switches, and expects the &lt;code&gt;LogicException&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The isolation test from part 1 stays as it is. It runs two tenants through one kernel in multi mode and reads the result back through HTTP, which is the closest a PHPUnit test gets to a worker: one kernel, many requests, the identity map reset in between. Run it after every change to a listener or a decorator, and before you deploy worker mode for the first time.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Deploying it
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One image, two modes.&lt;/strong&gt; &lt;code&gt;FRANKENPHP_CONFIG&lt;/code&gt; decides between classic and worker mode, &lt;code&gt;TENANT_MODE&lt;/code&gt; between dedicated and shared. The dedicated deployments of paying tenants can run the same image in worker mode with &lt;code&gt;tenantConnections=1&lt;/code&gt;; they never switch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Workers and connections.&lt;/strong&gt; Start with &lt;code&gt;num_threads&lt;/code&gt; equal to the CPUs you give the container and the same number of workers. &lt;code&gt;tenantConnections&lt;/code&gt; times workers is the number of Postgres backends one container can hold open; check &lt;code&gt;max_connections&lt;/code&gt; before raising it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Health and restarts.&lt;/strong&gt; &lt;code&gt;/health&lt;/code&gt; is open on both modes and answers from a worker, so a wedged worker fails the check. &lt;code&gt;FRANKENPHP_LOOP_MAX&lt;/code&gt; recycles a worker after 500 requests by default, and every recycle reopens the kept connections: that is where the 1,026 connections of the benchmark came from. Raise it once the scan test and the isolation test are green, keep it while you are not sure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Messenger workers&lt;/strong&gt; are unchanged. They were already long-lived, and they take the same &lt;code&gt;tenantConnections&lt;/code&gt; parameter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Do not do this&lt;/strong&gt; when the scan test from part 1 is red. Every class it flags is a cross-tenant leak waiting for the first worker. Fix those under php-fpm first, where they only cost performance, then switch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Worker mode turns the per-request cost of a shared deployment into a per-switch cost, and &lt;code&gt;tenantConnections&lt;/code&gt; turns the switch into an array lookup: twelve times the throughput of php-fpm on a page that changes tenant on every request, and a p99 of 10.65 milliseconds instead of 70.&lt;/li&gt;
&lt;li&gt;The state that must not survive a request is the same state Messenger workers have had to handle for years: the tenant context, cleared on terminate, and the services reset by the kernel. If your workers are clean, your web workers are too.&lt;/li&gt;
&lt;li&gt;The state that may survive is the one you choose: the placement list for 30 seconds, and up to N open tenant connections, sized by the database server, not by the tenant count.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Start with classic FrankenPHP mode, which already removes FastCGI and the second container and changes nothing in the application. Turn on worker mode when the two tests are green. Add &lt;code&gt;tenantConnections&lt;/code&gt; when &lt;code&gt;/whoami&lt;/code&gt; shows connects climbing with requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/tenant-shared-demo" rel="noopener noreferrer"&gt;https://github.com/mattleads/tenant-shared-demo&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>frankenphp</category>
      <category>multitenancy</category>
    </item>
    <item>
      <title>Stop Paying for Idle Tenants: Database-per-Tenant Symfony 8.1 on One Shared Deployment</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Thu, 12 Nov 2026 16:56:17 +0000</pubDate>
      <link>https://dev.to/mattleads/stop-paying-for-idle-tenants-database-per-tenant-symfony-81-on-one-shared-deployment-2k1c</link>
      <guid>https://dev.to/mattleads/stop-paying-for-idle-tenants-database-per-tenant-symfony-81-on-one-shared-deployment-2k1c</guid>
      <description>&lt;p&gt;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 &lt;code&gt;WHERE tenant_id = ?&lt;/code&gt; 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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;The standard fixes trade the isolation away. Merging everything into one database with a &lt;code&gt;tenant_id&lt;/code&gt; 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 &lt;code&gt;search_path&lt;/code&gt; per connection, which breaks behind a transaction pooler and still runs N migrations.&lt;/p&gt;

&lt;p&gt;This article takes the third road: &lt;strong&gt;keep a database per tenant, share the processes.&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.4, Symfony 8.1 (everything here works from 7.3, which introduced cache sub-namespaces), Doctrine ORM 3 with DBAL 4.&lt;/li&gt;
&lt;li&gt;PostgreSQL 16 and Redis 7 (Docker is enough), &lt;code&gt;symfony/redis-messenger&lt;/code&gt; for the tenant streams and &lt;code&gt;symfony/doctrine-messenger&lt;/code&gt; for the failure transport.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. The tenant and where the code reads it
&lt;/h2&gt;

&lt;p&gt;Everything that used to come from a dedicated deployment's environment is derived from one uuid:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/Tenant.php&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Tenant&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nc"&gt;UuidV4&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;isValid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; \&lt;span class="nc"&gt;InvalidArgumentException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'"%s" is not a tenant uuid'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;mb_substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;strtolower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;dbName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;         &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;str_replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'-'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'_'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;cacheNamespace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'t_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;stream&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$suffix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'tenant-'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$suffix&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;pathPrefix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;     &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The current tenant lives in a static holder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantContext.php&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;Tenant&lt;/span&gt; &lt;span class="nv"&gt;$default&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;Tenant&lt;/span&gt; &lt;span class="nv"&gt;$current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Tenant&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$current&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$default&lt;/span&gt;
            &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;NoTenantException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'No tenant is set for this request or message'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;isDefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Tenant&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$default&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$default&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Tenant&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;             &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;setDefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;Tenant&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nv"&gt;$default&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Which brings us to the one rule everything else depends on. &lt;strong&gt;Read the tenant at call time, never in a constructor and never into a property.&lt;/strong&gt; 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 &lt;code&gt;src/&lt;/code&gt; for constructors touching the tenant.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;$default&lt;/code&gt; slot is what makes the dedicated deployment work unchanged. &lt;code&gt;current()&lt;/code&gt; 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 &lt;code&gt;NoTenantException&lt;/code&gt; is cheaper than a quiet row in the wrong database.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Two modes, one codebase
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight conf"&gt;&lt;code&gt;&lt;span class="c1"&gt;# .env
&lt;/span&gt;&lt;span class="na"&gt;TENANT_MODE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;single&lt;/span&gt;      &lt;span class="c1"&gt;# dedicated: this deployment is one tenant&lt;/span&gt;
&lt;span class="na"&gt;TENANT_UUID&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;            &lt;span class="c1"&gt;# that tenant&lt;/span&gt;
&lt;span class="na"&gt;TENANT_PLACEMENT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;shared&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;   &lt;span class="c1"&gt;# shared: which placement this deployment serves&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The kernel sets the default at boot:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Kernel.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;boot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kc"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;boot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;SingleTenantResolver&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;boot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_SERVER&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'TENANT_MODE'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$_ENV&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'TENANT_MODE'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'single'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_SERVER&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'TENANT_UUID'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$_ENV&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'TENANT_UUID'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;SingleTenantResolver::boot()&lt;/code&gt; calls &lt;code&gt;TenantContext::setDefault(new Tenant($uuid))&lt;/code&gt; in single mode and &lt;code&gt;setDefault(null)&lt;/code&gt; in multi mode. It is the only class that reads &lt;code&gt;TENANT_UUID&lt;/code&gt;. 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.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. HTTP: the tenant is the path prefix
&lt;/h2&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantPathPrefix.php&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TenantPathPrefix&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="no"&gt;ATTRIBUTE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'_tenant_prefix'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="no"&gt;PATTERN&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'#^/tenant_([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?:/|$)#i'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;rebase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nf"&gt;preg_match&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;PATTERN&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;rawurldecode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getPathInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$match&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getBaseUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$uuid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;strtolower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$match&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$server&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;server&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'SCRIPT_NAME'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'PHP_SELF'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'/tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/index.php'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'SCRIPT_FILENAME'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'SCRIPT_FILENAME'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'SCRIPT_FILENAME'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'index.php'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nv"&gt;$rebased&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;duplicate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;server&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$server&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$rebased&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;attributes&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;ATTRIBUTE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$rebased&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Request::getBaseUrl()&lt;/code&gt; derives the base from &lt;code&gt;SCRIPT_NAME&lt;/code&gt;, so rewriting &lt;code&gt;SCRIPT_NAME&lt;/code&gt; to &lt;code&gt;/tenant_&amp;lt;uuid&amp;gt;/index.php&lt;/code&gt; is all it takes. The kernel applies it before anything else sees the request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Kernel.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$type&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;MAIN_REQUEST&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nv"&gt;$catch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$type&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;MAIN_REQUEST&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$request&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TenantPathPrefix&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;rebase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$catch&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A listener at priority 2048, ahead of the firewall, turns the prefix into the tenant:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantRequestListener.php&lt;/span&gt;
&lt;span class="c1"&gt;#[AsEventListener(event: KernelEvents::REQUEST, priority: 2048)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;onRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;RequestEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isMainRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nv"&gt;$request&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$prefix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;attributes&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantPathPrefix&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;ATTRIBUTE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;mode&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nc"&gt;TenantMode&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;Single&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;is_string&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$prefix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;has&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nv"&gt;$prefix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;NotFoundHttpException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'No such tenant here'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nf"&gt;is_string&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$prefix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;preg_match&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'#^/health(/|$)#'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getPathInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;NotFoundHttpException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'No tenant in the path'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;resolver&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$prefix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;#[AsEventListener(event: KernelEvents::TERMINATE)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;onTerminate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TerminateEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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 &lt;code&gt;MultiTenantResolver&lt;/code&gt; answers 404 for a tenant that is not placed here. The resolver has no fallback branch.&lt;/p&gt;

&lt;p&gt;Run the demo and ask the shared instance who it is for two tenants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ curl -s http://127.0.0.1:8770/tenant_11111111-…/whoami
&lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"tenant"&lt;/span&gt;:&lt;span class="s2"&gt;"11111111-…"&lt;/span&gt;,&lt;span class="s2"&gt;"database"&lt;/span&gt;:&lt;span class="s2"&gt;"tenant_11111111_1111_4111_8111_111111111111"&lt;/span&gt;,&lt;span class="s2"&gt;"basePath"&lt;/span&gt;:&lt;span class="s2"&gt;"/tenant_11111111-…"&lt;/span&gt;,&lt;span class="s2"&gt;"notesUrl"&lt;/span&gt;:&lt;span class="s2"&gt;"/tenant_11111111-…/notes"&lt;/span&gt;&lt;span class="o"&gt;}&lt;/span&gt;

$ curl -s http://127.0.0.1:8770/tenant_22222222-…/whoami
&lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"tenant"&lt;/span&gt;:&lt;span class="s2"&gt;"22222222-…"&lt;/span&gt;,&lt;span class="s2"&gt;"database"&lt;/span&gt;:&lt;span class="s2"&gt;"tenant_22222222_2222_4222_8222_222222222222"&lt;/span&gt;,&lt;span class="s2"&gt;"basePath"&lt;/span&gt;:&lt;span class="s2"&gt;"/tenant_22222222-…"&lt;/span&gt;,&lt;span class="s2"&gt;"notesUrl"&lt;/span&gt;:&lt;span class="s2"&gt;"/tenant_22222222-…/notes"&lt;/span&gt;&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;h2&gt;
  
  
  4. The database follows the tenant
&lt;/h2&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantConnection.php&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TenantConnection&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Connection&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$connectedTo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DriverConnection&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getParams&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;databaseFor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'dbname'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$target&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isTransactionActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; \&lt;span class="nc"&gt;LogicException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Tenant changed to %s inside a database transaction'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;close&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'dbname'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$connection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;_conn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;driver&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Driver&lt;/span&gt;\&lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;convertException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;connectedTo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isAutoCommit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;beginTransaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;databaseFor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$configured&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$tenant&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;isDefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$configured&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dbName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/doctrine.yaml
&lt;/span&gt;&lt;span class="na"&gt;doctrine&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;dbal&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;url&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'%env(resolve:DATABASE_URL)%'&lt;/span&gt;
        &lt;span class="na"&gt;wrapper_class&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;App\Tenant\TenantConnection&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things matter here.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The dedicated deployment is untouched.&lt;/strong&gt; Its own tenant is the default, so &lt;code&gt;databaseFor()&lt;/code&gt; returns the configured &lt;code&gt;dbname&lt;/code&gt; from &lt;code&gt;DATABASE_URL&lt;/code&gt;. Any other tenant gets &lt;code&gt;tenant_&amp;lt;uuid&amp;gt;&lt;/code&gt; on the same server.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A tenant change inside a transaction is a bug, so it throws.&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;There is one EntityManager.&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;Post a note to each tenant and read them back:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ curl -s -X POST -H &lt;span class="s1"&gt;'Content-Type: application/json'&lt;/span&gt; -d &lt;span class="s1"&gt;'{"body":"hello from A"}'&lt;/span&gt; http://127.0.0.1:8770/tenant_1111…/notes
$ curl -s -X POST -H &lt;span class="s1"&gt;'Content-Type: application/json'&lt;/span&gt; -d &lt;span class="s1"&gt;'{"body":"hello from B"}'&lt;/span&gt; http://127.0.0.1:8770/tenant_2222…/notes

$ curl -s http://127.0.0.1:8770/tenant_1111…/notes
&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;:2,&lt;span class="s2"&gt;"body"&lt;/span&gt;:&lt;span class="s2"&gt;"hello from A"&lt;/span&gt;,&lt;span class="s2"&gt;"processedAt"&lt;/span&gt;:&lt;span class="s2"&gt;"2026-11-09T20:36:49+00:00"&lt;/span&gt;,&lt;span class="s2"&gt;"processedBy"&lt;/span&gt;:&lt;span class="s2"&gt;"MacBookPro16.local:95790"&lt;/span&gt;&lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;
$ curl -s http://127.0.0.1:8770/tenant_2222…/notes
&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;:1,&lt;span class="s2"&gt;"body"&lt;/span&gt;:&lt;span class="s2"&gt;"hello from B"&lt;/span&gt;,&lt;span class="s2"&gt;"processedAt"&lt;/span&gt;:&lt;span class="s2"&gt;"2026-11-09T20:36:49+00:00"&lt;/span&gt;,&lt;span class="s2"&gt;"processedBy"&lt;/span&gt;:&lt;span class="s2"&gt;"MacBookPro16.local:95790"&lt;/span&gt;&lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The ids overlap because the rows live in different databases. &lt;code&gt;processedBy&lt;/code&gt; is the same worker pid for both and that worker is the subject of section 6.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. The cache follows the tenant
&lt;/h2&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/TenantAwareCache.php&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TenantAwareCache&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;AdapterInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CacheInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;NamespacedPoolInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ResettableInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/** @var array&amp;lt;string, AdapterInterface&amp;amp;CacheInterface&amp;amp;NamespacedPoolInterface&amp;gt; */&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$byTenant&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="nc"&gt;AdapterInterface&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nc"&gt;CacheInterface&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nc"&gt;NamespacedPoolInterface&lt;/span&gt; &lt;span class="nv"&gt;$inner&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;pool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;AdapterInterface&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$tenant&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;isDefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withSubNamespace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;cacheNamespace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;callable&lt;/span&gt; &lt;span class="nv"&gt;$callback&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="nv"&gt;$beta&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;$metadata&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;mixed&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;pool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$callback&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$beta&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$metadata&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// getItem(), save(), deleteItem(), … all delegate to $this-&amp;gt;pool()&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;array_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$pool&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$pool&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;ResettableInterface&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$pool&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/services.yaml
&lt;/span&gt;&lt;span class="na"&gt;services&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;App\Tenant\TenantAwareCache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;decorates&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;cache.app&lt;/span&gt;
        &lt;span class="na"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'@.inner'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again the dedicated deployment's keys do not change, so its caches stay warm through the deploy that introduces this.&lt;/p&gt;

&lt;p&gt;One trap with tag-aware pools. Symfony stores tags in the pool's &lt;strong&gt;root&lt;/strong&gt; namespace, shared by every sub-namespace. If tenant A invalidates the tag &lt;code&gt;product_list&lt;/code&gt;, it drops tenant B's &lt;code&gt;product_list&lt;/code&gt; 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.&lt;/p&gt;

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

&lt;h2&gt;
  
  
  6. Workers: one process, every tenant's stream
&lt;/h2&gt;

&lt;p&gt;This is where most multitenancy write-ups stop and where most of the cost sits. A dedicated deployment runs its own &lt;code&gt;messenger:consume&lt;/code&gt; 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 &lt;code&gt;tenant-&amp;lt;uuid&amp;gt;&lt;/code&gt; streams today and they should keep doing exactly that.&lt;/p&gt;

&lt;p&gt;The transport keeps its &lt;strong&gt;name&lt;/strong&gt;. Only its DSN changes with the mode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/messenger.yaml
&lt;/span&gt;&lt;span class="na"&gt;framework&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;messenger&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;failure_transport&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;failed&lt;/span&gt;
        &lt;span class="na"&gt;transports&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;async&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;dsn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'%env(MESSENGER_TRANSPORT_DSN)%'&lt;/span&gt;   &lt;span class="c1"&gt;# redis://…/tenant-&amp;lt;uuid&amp;gt; or tenant-multi://…?kind=main
&lt;/span&gt;                &lt;span class="na"&gt;options&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;consumer:&lt;/span&gt; &lt;span class="s1"&gt;'%env(MESSENGER_CONSUMER_NAME)%'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;redeliver_timeout:&lt;/span&gt; &lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;claim_interval:&lt;/span&gt; &lt;span class="mi"&gt;30000&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="na"&gt;retry_strategy&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;max_retries:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;delay:&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="na"&gt;failed&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'doctrine://default?queue_name=failed'&lt;/span&gt;
        &lt;span class="na"&gt;routing&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;'App\Message\NoteCreated'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;async&lt;/span&gt;
            &lt;span class="na"&gt;'App\Message\SlowJob'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;async&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/Messenger/MultiTenantTransport.php (abridged)&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MultiTenantTransport&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;TransportInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;KeepaliveReceiverInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;MessageCountAwareInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/** @var array&amp;lt;string, array{RedisReceiver, RedisSender}&amp;gt; */&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$byTenant&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;\&lt;span class="nc"&gt;Redis&lt;/span&gt; &lt;span class="nv"&gt;$redis&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$fetchSize&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;iterable&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$tenants&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;placement&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;tenants&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenants&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nv"&gt;$count&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$uuid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$tenants&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nv"&gt;$count&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;fairUse&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;fairUse&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;canTake&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nv"&gt;$count&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;fairUse&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;took&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withoutAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;with&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TenantStamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;ack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Envelope&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$uuid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;tenantOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;ack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;fairUse&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;done&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Envelope&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Envelope&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$uuid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenant&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;current&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;pair&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$envelope&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withoutAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;pair&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nb"&gt;isset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$dsn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;rtrim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;redisDsn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;streamFor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="nv"&gt;$connection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Connection&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;fromDsn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$dsn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;redis&lt;/span&gt; &lt;span class="o"&gt;??=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; \&lt;span class="nc"&gt;Redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RedisReceiver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;serializer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RedisSender&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$connection&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;serializer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;byTenant&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three decisions and why.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reuse Symfony's &lt;code&gt;RedisReceiver&lt;/code&gt; per tenant instead of writing a multi-stream &lt;code&gt;XREADGROUP&lt;/code&gt;.&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rotate the starting tenant.&lt;/strong&gt; &lt;code&gt;$this-&amp;gt;next&lt;/code&gt; 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.&lt;/p&gt;

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

&lt;p&gt;The worker side is a listener on three Messenger events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/Messenger/TenantWorkerListener.php&lt;/span&gt;
&lt;span class="c1"&gt;#[AsEventListener(priority: 1024)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;onReceived&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WorkerMessageReceivedEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$stamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEnvelope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$stamp&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                                   &lt;span class="c1"&gt;// dedicated deployment: nothing to do&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                       &lt;span class="c1"&gt;// no entity of the previous tenant survives&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenant&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Tenant&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenant&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;#[AsEventListener(priority: -1024)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;onHandled&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WorkerMessageHandledEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;leave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEnvelope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;#[AsEventListener(priority: -1024)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;onFailed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WorkerMessageFailedEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;leave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEnvelope&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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 &lt;strong&gt;that tenant's&lt;/strong&gt; stream and a failed message is written to &lt;strong&gt;that tenant's&lt;/strong&gt; &lt;code&gt;messenger_messages&lt;/code&gt; table, because &lt;code&gt;doctrine://default&lt;/code&gt; resolves through &lt;code&gt;TenantConnection&lt;/code&gt; while the tenant is still set. The demo proves it with a job that always throws:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ 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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;h2&gt;
  
  
  7. Fair use: a busy free tenant waits, the others do not
&lt;/h2&gt;

&lt;p&gt;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 &lt;code&gt;TENANT_INFLIGHT_CAP&lt;/code&gt; 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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/Messenger/FairUse.php (abridged)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;canTake&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;cap&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;took&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;incr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;expire&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;180&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;done&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;del&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$kind&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;get()&lt;/code&gt; skips a tenant at its cap, &lt;code&gt;ack()&lt;/code&gt; and &lt;code&gt;reject()&lt;/code&gt; release the slot, &lt;code&gt;keepalive()&lt;/code&gt; 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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;The trade-off is in that &lt;code&gt;expire(…, 180)&lt;/code&gt;. A worker that dies between &lt;code&gt;took()&lt;/code&gt; and &lt;code&gt;done()&lt;/code&gt; 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 &lt;code&gt;--keepalive&lt;/code&gt; so a long legitimate message keeps its slot alive.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Placement: which tenants live here
&lt;/h2&gt;

&lt;p&gt;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: &lt;code&gt;tenant:placement&lt;/code&gt; maps each uuid to a placement name, &lt;code&gt;shared-1&lt;/code&gt;, &lt;code&gt;shared-2&lt;/code&gt; or &lt;code&gt;dedicated&lt;/code&gt;. The service that creates tenants and handles plan changes writes it; the deployments only read it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Tenant/PlacementReader.php (abridged)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;tenants&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isFresh&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;                       &lt;span class="c1"&gt;// at most every 30 s&lt;/span&gt;
        &lt;span class="nv"&gt;$hash&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;hGetAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenants&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;array_keys&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;array_filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$hash&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$v&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;placement&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nf"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenants&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;readAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;time&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenants&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;serves&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$tenantUuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isFresh&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;in_array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;strtolower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenantUuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;tenants&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;hGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;strtolower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$tenantUuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;placement&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;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 &lt;code&gt;redeliver_timeout&lt;/code&gt;, the same way a rolling deploy already behaves. Its database and bucket do not move at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Migrations: every tenant, one process each
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;So each tenant gets its own process, running as a dedicated deployment of that tenant:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Command/TenantsMigrateCommand.php (abridged)&lt;/span&gt;
&lt;span class="nv"&gt;$running&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Process&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;fromShellCommandline&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s1"&gt;'bin/console doctrine:database:create --if-not-exists -n &amp;amp;&amp;amp; bin/console doctrine:migrations:migrate -n --allow-no-migration'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;projectDir&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'TENANT_MODE'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'single'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'TENANT_UUID'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'DATABASE_URL'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;tenantDatabaseUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The child sees &lt;code&gt;TENANT_MODE=single&lt;/code&gt; and a plain &lt;code&gt;DATABASE_URL&lt;/code&gt; pointing at &lt;code&gt;tenant_&amp;lt;uuid&amp;gt;&lt;/code&gt;, so Doctrine's own commands run untouched and &lt;code&gt;--concurrency&lt;/code&gt; bounds how many run at once:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ 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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A failed tenant is reported and the others continue. In production the command also writes a &lt;code&gt;migration-blocked:&amp;lt;uuid&amp;gt;&lt;/code&gt; flag that the request resolver turns into a 503 for that tenant alone, until a later run succeeds.&lt;/p&gt;

&lt;h2&gt;
  
  
  10. What it costs and when not to do this
&lt;/h2&gt;

&lt;p&gt;The tenant switch is a reconnect. &lt;code&gt;app:bench:switch&lt;/code&gt; runs &lt;code&gt;SELECT 1&lt;/code&gt; three hundred times on one tenant, then three hundred times alternating tenants, against Postgres in Docker on a laptop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Do not do this when:&lt;/p&gt;

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

&lt;h2&gt;
  
  
  11. Testing it
&lt;/h2&gt;

&lt;p&gt;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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// tests/TwoTenantIsolationTest.php (abridged)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;testEachTenantReadsItsOwnDatabase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nv"&gt;$body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'isolation '&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;bin2hex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;random_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;jsonRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'POST'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/notes'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'body'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$body&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertResponseStatusCodeSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;201&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'GET'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/notes'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertStringContainsString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'GET'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/tenant_'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;B&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="s1"&gt;'/notes'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;assertStringNotContainsString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use the real &lt;code&gt;messenger.yaml&lt;/code&gt;, 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 &lt;code&gt;messenger_messages&lt;/code&gt;. A test that checks a stamp on an envelope will pass while a worker writes into the wrong database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Each piece above is a decision you can take separately.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;static &lt;code&gt;TenantContext&lt;/code&gt;&lt;/strong&gt; 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.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;base URL&lt;/strong&gt; carries the tenant on HTTP, so routes and generated URLs do not change.&lt;/li&gt;
&lt;li&gt;A DBAL &lt;strong&gt;&lt;code&gt;wrapper_class&lt;/code&gt;&lt;/strong&gt; and a &lt;strong&gt;cache decorator&lt;/strong&gt; make the database and the cache follow the tenant with no change to repositories or services.&lt;/li&gt;
&lt;li&gt;A Messenger transport that wraps &lt;strong&gt;one &lt;code&gt;RedisReceiver&lt;/code&gt; per tenant&lt;/strong&gt; keeps every sender and every handler unchanged and the listener priorities keep retries and failures inside the tenant.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;per-tenant in-flight cap&lt;/strong&gt; is enough fair use for free tenants; dedicated deployments are the fair use for paying ones.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next in this series.&lt;/strong&gt; 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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub in Part 2.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>architecture</category>
      <category>multitenancy</category>
    </item>
    <item>
      <title>Draft by Agent, Approve by Human: A Publishing API and MCP Server for Symfony 8.1</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Mon, 09 Nov 2026 12:20:58 +0000</pubDate>
      <link>https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c</link>
      <guid>https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c</guid>
      <description>&lt;p&gt;If you want an AI agent to publish to a WordPress site, you point it at the REST API and you are done. If your site runs on Symfony, you have a choice between handing the agent an admin login, which nobody should do, or pasting its output into your CMS by hand, which defeats the purpose.&lt;/p&gt;

&lt;p&gt;The gap is on the server side. A Symfony site needs an endpoint an agent can draft into, a check the agent can run on its own work before a human sees it, a human-only approve step, and a way to find out afterwards whether the article reached anyone. None of that is CMS territory. It is a thin layer over whatever entities the site already has.&lt;/p&gt;

&lt;p&gt;This article walks through &lt;code&gt;mattleads/agent-publishing-bundle&lt;/code&gt;, which adds that layer. We install it on a Symfony 8.1 site, issue scoped keys, run an agent through draft, lint and submit, approve through the API, then look at the view counts the bundle collected, including how many came from ChatGPT and how many from GPTBot. The last section covers the MCP endpoint, which exposes the same operations as tools without adding a protocol dependency.&lt;/p&gt;

&lt;p&gt;I maintain the bundle. The demo repository has every file shown here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.2 or later. The demo uses 8.4.&lt;/li&gt;
&lt;li&gt;Symfony 6.4, 7.4 or 8.1. The demo is a fresh &lt;code&gt;symfony/skeleton&lt;/code&gt; 8.1 project.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mattleads/agent-publishing-bundle&lt;/code&gt; 0.2.0.&lt;/li&gt;
&lt;li&gt;Doctrine ORM for the bundled storage, or your own implementation of two small interfaces.&lt;/li&gt;
&lt;li&gt;Optional: &lt;code&gt;symfony/messenger&lt;/code&gt; to count views off the request, &lt;code&gt;twig/twig&lt;/code&gt; for the JSON-LD helper.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nothing in the bundle renders HTML. Your templates and routes stay yours.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Install and declare what exists
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require mattleads/agent-publishing-bundle doctrine/orm doctrine/doctrine-bundle symfony/security-bundle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bundle needs to know which sections and languages the site has, because an agent must never invent one. That lives in configuration, where a deploy review can see it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/mattleads_agent_publishing.yaml&lt;/span&gt;
&lt;span class="na"&gt;mattleads_agent_publishing&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;storage&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;doctrine&lt;/span&gt;
    &lt;span class="na"&gt;locales&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;en&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;de&lt;/span&gt;&lt;span class="pi"&gt;]&lt;/span&gt;
    &lt;span class="na"&gt;default_locale&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;en&lt;/span&gt;
    &lt;span class="na"&gt;sections&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;blog&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;/blog&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
        &lt;span class="na"&gt;docs&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;/docs&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;locales&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;en&lt;/span&gt;&lt;span class="pi"&gt;],&lt;/span&gt; &lt;span class="nv"&gt;lint&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;require_faq&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;true&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;min_words&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;200&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
    &lt;span class="na"&gt;seo&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;site_name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Agent Publishing Demo&lt;/span&gt;
        &lt;span class="na"&gt;publisher&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;Demo Publishing Ltd&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;url&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;https&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;&lt;span class="nv"&gt;//example.com&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The API is a stateless firewall with the bundle's authenticator. Keys arrive as bearer tokens, and a missing key gets a JSON 401 from the entry point rather than a login redirect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/security.yaml&lt;/span&gt;
&lt;span class="na"&gt;security&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;firewalls&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;agent_publishing&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;pattern&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;^/api/publisher&lt;/span&gt;
            &lt;span class="na"&gt;stateless&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
            &lt;span class="na"&gt;provider&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;none&lt;/span&gt;
            &lt;span class="na"&gt;entry_point&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;MattLeads\AgentPublishingBundle\Security\ApiKeyAuthenticator&lt;/span&gt;
            &lt;span class="na"&gt;custom_authenticators&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;MattLeads\AgentPublishingBundle\Security\ApiKeyAuthenticator&lt;/span&gt;
    &lt;span class="na"&gt;access_control&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;^/api/publisher/v1/openapi\.json$&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;roles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;PUBLIC_ACCESS&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;^/api/publisher&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;roles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;ROLE_AGENT_PUBLISHING&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Import the routes, run a migration, and the site has an OpenAPI 3.1 document at &lt;code&gt;/api/publisher/v1/openapi.json&lt;/code&gt; that a client generator or an agent can read.&lt;/p&gt;

&lt;p&gt;With &lt;code&gt;storage: doctrine&lt;/code&gt; you get four tables: articles, keys, and two daily rollups for analytics. With &lt;code&gt;storage: custom&lt;/code&gt; you implement &lt;code&gt;ArticleStorageInterface&lt;/code&gt; against your own entity. The bundle validates input, resolves slugs and checks workflow rules before it calls you, so the implementation only persists what it is given. &lt;code&gt;ArticleInterface&lt;/code&gt; has no setters. That is deliberate: the bundle never mutates your entities behind your back.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Keys that cannot grow
&lt;/h2&gt;

&lt;p&gt;Every caller holds a key with scopes and, optionally, a list of sections:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console agent-publishing:api-key:create seo-agent &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;articles:read &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;articles:draft &lt;span class="nt"&gt;--section&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;blog
php bin/console agent-publishing:api-key:create editor &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;articles:read &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;articles:approve &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;articles:publish &lt;span class="nt"&gt;--scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;stats:read
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The secret is printed once and stored as an HMAC keyed with the kernel secret. A new key gets read and draft by default. Nobody gets publish unless a human types it.&lt;/p&gt;

&lt;p&gt;The scopes map onto the workflow. &lt;code&gt;articles:draft&lt;/code&gt; creates, edits and submits. &lt;code&gt;articles:approve&lt;/code&gt; approves or rejects what is in review. &lt;code&gt;articles:publish&lt;/code&gt; publishes directly or on a schedule. &lt;code&gt;stats:read&lt;/code&gt; reads counts. &lt;code&gt;keys:manage&lt;/code&gt; issues keys over the API, with one rule that matters for platforms: a key can only mint keys with a subset of its own scopes and sections. A marketing platform holding draft rights in &lt;code&gt;blog&lt;/code&gt; can create keys for its customers' agents, and none of them can ever hold publish.&lt;/p&gt;

&lt;p&gt;Section restrictions are enforced as "does not exist" rather than "forbidden". A key limited to &lt;code&gt;blog&lt;/code&gt; gets a 404 for an article in &lt;code&gt;docs&lt;/code&gt;, and its listings and totals never include other sections. There is nothing to probe.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. The agent loop: lint, fix, create, submit
&lt;/h2&gt;

&lt;p&gt;The piece that makes agents useful rather than noisy is &lt;code&gt;POST /lint&lt;/code&gt;. It takes the same body as create, stores nothing, and returns one entry per rule with pass, warn or fail, a message, and a hint. Here is the demo's first attempt, a two-line body with a seven-character title:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WARN  title_length       Title is 7 characters, which is short for search and social previews.
                         -&amp;gt; Name the outcome and the subject: aim for 30-60 characters.
FAIL  summary            No summary. It is used as the meta description and in previews.
WARN  opening_paragraph  The body does not start with a paragraph.
                         -&amp;gt; Put a short answer to the title before the first heading, list or image.
WARN  word_count         5 words; this section expects at least 300.
FAIL  images_alt         1 of 1 image(s) have no alt text (first: /img/retry.png).
WARN  links              Link text "here" says nothing about the target.
status: fail (2 pass, 5 warn, 2 fail)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Eleven rules run. Title length, summary length, a quotable opening paragraph that uses the title's terms, heading structure, word count, Flesch reading ease for English, alt text, link text and internal links, tags, slug uniqueness, and a FAQ block for sections that ask for one. The opening-paragraph rule is the one aimed at answer engines: they quote the first paragraph, so it should be 40 to 120 words and answer the title. Per-section thresholds come from the &lt;code&gt;lint&lt;/code&gt; block in configuration, and a host adds rules by tagging a service.&lt;/p&gt;

&lt;p&gt;The agent reads the hints, rewrites, lints again, and gets &lt;code&gt;status: pass&lt;/code&gt;. Then it creates the draft and submits it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="err"&gt;POST /articles            -&amp;gt; 201, state draft, slug symfony-messenger-retries-throwing-serializer
POST /articles/{id}/publish with the agent key -&amp;gt; 403, This key lacks the "articles:publish" scope.
POST /articles/{id}/submit -&amp;gt; 200, state in_review
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The whole loop is about 150 lines of plain PHP in the demo's &lt;code&gt;scripts/agent.php&lt;/code&gt;. No SDK, only JSON over HTTP.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. The human side, also through the API
&lt;/h2&gt;

&lt;p&gt;The bundle ships no admin screen. Approval is an API call, which means your existing backend, a Slack bot or a one-line curl can do it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="err"&gt;POST /articles/{id}/reject  { "reason": "Add the version the fix landed in." }   -&amp;gt; draft, review_note set
POST /articles/{id}/submit                                                       -&amp;gt; in_review
POST /articles/{id}/approve                                                      -&amp;gt; published
POST /articles/{id}/publish { "publish_at": "2099-01-01T09:00:00+00:00" }        -&amp;gt; scheduled
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every transition dispatches an &lt;code&gt;ArticleTransitioned&lt;/code&gt; event with the actor, so a listener can notify reviewers on submit or purge a cache on publish. Scheduled articles flip to published when their time comes, through a console command for cron or a Symfony Scheduler task if you enable it. Published articles are frozen for editing; the agent gets a 409 if it tries.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Counting readers without cookies
&lt;/h2&gt;

&lt;p&gt;The bundle counts views per article and per referrer, by day, and stores nothing else. No cookies, no IP addresses, no user agents, no URLs. To make a page countable, the site's route declares which section it renders:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="na"&gt;#[Route('/blog/{slug}', name: 'blog_show', defaults: ['_agent_publishing_section' =&amp;gt; 'blog', '_locale' =&amp;gt; 'en'])]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A listener runs after the response is sent, looks up the published article by section, locale and slug, and records the view. With Messenger installed the view is a message you can route to an async transport. Each view is bucketed by user agent and referrer into one of eight kinds:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Kind&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;direct&lt;/td&gt;
&lt;td&gt;no referrer&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;internal&lt;/td&gt;
&lt;td&gt;a link from your own site&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;search&lt;/td&gt;
&lt;td&gt;Google, Bing, DuckDuckGo and others&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;social&lt;/td&gt;
&lt;td&gt;X, LinkedIn, Reddit, Hacker News, Telegram and friends&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ai_referral&lt;/td&gt;
&lt;td&gt;a human sent by ChatGPT, Perplexity, Claude or Gemini&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ai_crawler&lt;/td&gt;
&lt;td&gt;GPTBot, ClaudeBot, PerplexityBot, Google-Extended and other AI crawlers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;bot&lt;/td&gt;
&lt;td&gt;anything else that is not a browser&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;referral&lt;/td&gt;
&lt;td&gt;any other site&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Human kinds count as views. Crawler kinds are counted in a separate column, so you can see which articles AI systems read without inflating the human numbers. The demo sends seven requests at the published page, from Chrome with no referrer, from Google twice, from ChatGPT, from Hacker News, then as GPTBot and as ClaudeBot. The stats endpoint reports:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;views 5, crawler_views 2
by_kind {"ai_crawler":2,"ai_referral":1,"direct":1,"search":2,"social":1}
referrers: google.com search 2, chatgpt.com ai_referral 1, news.ycombinator.com social 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is the number a content team asks for and rarely gets: not "how many views" but "which assistants and which engines sent them, and did the crawlers come at all".&lt;/p&gt;

&lt;h2&gt;
  
  
  6. MCP without a dependency
&lt;/h2&gt;

&lt;p&gt;Agents increasingly speak the Model Context Protocol rather than REST. On 6 November 2026 the official PHP SDK, &lt;code&gt;mcp/sdk&lt;/code&gt;, is at 0.9.0 and &lt;code&gt;symfony/mcp-bundle&lt;/code&gt; is at 1.0.0-BETA1. Pinning either would make their breaking releases the bundle's breaking releases. For a tools-only server the protocol is small, so the bundle implements it directly: JSON-RPC 2.0 over one HTTP endpoint with &lt;code&gt;initialize&lt;/code&gt;, &lt;code&gt;ping&lt;/code&gt;, &lt;code&gt;tools/list&lt;/code&gt; and &lt;code&gt;tools/call&lt;/code&gt;, notifications acknowledged, batches accepted, and three protocol versions negotiated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;claude mcp add &lt;span class="nt"&gt;--transport&lt;/span&gt; http publisher https://example.com/api/publisher/v1/mcp &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--header&lt;/span&gt; &lt;span class="s2"&gt;"Authorization: Bearer apb_..."&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sixteen tools wrap the same services as the REST API, so the two cannot drift. &lt;code&gt;tools/list&lt;/code&gt; is filtered by the key's scopes. The demo's agent key sees nine tools and never learns that &lt;code&gt;approve_article&lt;/code&gt; exists. Tool failures such as a validation error or a forbidden transition come back as results with &lt;code&gt;isError&lt;/code&gt; and a readable message, which is what an agent acts on. Protocol mistakes get JSON-RPC error codes. Two tools exist only for agents: &lt;code&gt;get_style_guide&lt;/code&gt; returns the site's writing rules from configuration, and &lt;code&gt;list_sections&lt;/code&gt; includes each section's lint thresholds, so an agent can plan before it writes.&lt;/p&gt;

&lt;p&gt;When the official SDK stabilizes, a bridge can expose the same &lt;code&gt;McpToolInterface&lt;/code&gt; implementations through it. The tool code will not change.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. What search engines and language models see
&lt;/h2&gt;

&lt;p&gt;Three outputs come for free once articles are published. A Twig function, &lt;code&gt;agent_publishing_jsonld(article)&lt;/code&gt;, emits schema.org &lt;code&gt;Article&lt;/code&gt; markup with headline, description, dates, language, keywords, author and publisher. A sitemap at &lt;code&gt;/sitemap-publisher.xml&lt;/code&gt; lists published articles with &lt;code&gt;lastmod&lt;/code&gt; and hreflang alternates for articles that share a translation group. In the demo, an English article and its German translation produce two URLs and six hreflang links, including &lt;code&gt;x-default&lt;/code&gt;. And &lt;code&gt;/llms.txt&lt;/code&gt; follows the llmstxt.org format: the site name, a description, and a Markdown list per section of recent articles with their summaries.&lt;/p&gt;

&lt;p&gt;All three build URLs through &lt;code&gt;UrlResolverInterface&lt;/code&gt;. The default pattern is &lt;code&gt;{base}{locale_prefix}{section_path}/{slug}&lt;/code&gt;, where the locale prefix is empty for the default language. A site with different routing registers its own resolver. Set &lt;code&gt;seo.base_url&lt;/code&gt; in production so a forged &lt;code&gt;Host&lt;/code&gt; header cannot plant another domain in cached output.&lt;/p&gt;

&lt;h2&gt;
  
  
  Proof
&lt;/h2&gt;

&lt;p&gt;The bundle has 59 PHPUnit tests with 681 assertions, running the functional flows against both the in-memory and the Doctrine storage, plus PHPStan at level 8. CI covers PHP 8.2 to 8.4 against Symfony 6.4, 7.4 and 8. The demo repository runs the whole loop with one script and prints every response, so you can verify the numbers above in about a minute.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it does not fit
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;You want a CMS.&lt;/strong&gt; There is no admin UI, no editor, no media upload. Sulu or Bolt are the right tools then.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;You render HTML bodies as-is.&lt;/strong&gt; The bundle stores &lt;code&gt;format: html&lt;/code&gt; bodies unchanged. Sanitize before rendering, or an agent key with draft rights becomes a script injection path before any human approves.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;You need per-visitor analytics.&lt;/strong&gt; The rollups are counts by day, article, referrer host and kind. Funnels and sessions are a different product.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Your agents need resources or prompts over MCP.&lt;/strong&gt; The server is tools-only by design, and it does not open server-to-client streams.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The decisions in this design are the useful part, whichever bundle you end up with. Keep articles in the host's entities and mutate them only through a storage contract, so the integration survives your schema. Make the lint report the agent's feedback loop, so humans review finished work instead of first drafts. Default keys to draft rights and let keys mint only subsets of themselves, so a platform cannot escalate. Count referrer kinds rather than visitors, so you can tell which assistants send readers without a consent banner. And speak MCP directly while the SDKs settle, since five JSON-RPC methods are cheaper to own than a beta dependency.&lt;/p&gt;

&lt;p&gt;Start with the REST API and a draft-only key for one agent. Add the MCP endpoint when an agent asks for it. Grant publish rights to nobody until the lint reports have been green for a month.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/agent-publishing-bundle" rel="noopener noreferrer"&gt;https://github.com/mattleads/agent-publishing-bundle&lt;/a&gt;, with the runnable demo at &lt;a href="https://github.com/mattleads/agent-publishing-demo" rel="noopener noreferrer"&gt;https://github.com/mattleads/agent-publishing-demo&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>ai</category>
      <category>seo</category>
    </item>
    <item>
      <title>Passkeys in 17 Files: Hybrid Login, Recovery Codes and Revocation in Symfony 8.1</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Thu, 05 Nov 2026 15:07:53 +0000</pubDate>
      <link>https://dev.to/mattleads/passkeys-in-17-files-hybrid-login-recovery-codes-and-revocation-in-symfony-81-542k</link>
      <guid>https://dev.to/mattleads/passkeys-in-17-files-hybrid-login-recovery-codes-and-revocation-in-symfony-81-542k</guid>
      <description>&lt;p&gt;Most passkey tutorials end when the browser prompt appears. Production starts there. Your users already have passwords, so they need to add a passkey from their account page, sign in with it next time or pick it from the browser's autofill, see when each key was last used, revoke one, and get back in with a recovery code when every device is gone.&lt;/p&gt;

&lt;p&gt;This guide builds exactly that on Symfony 8.1. Two bundles do the heavy lifting: &lt;a href="https://github.com/web-auth/webauthn-symfony-bundle" rel="noopener noreferrer"&gt;&lt;code&gt;web-auth/webauthn-symfony-bundle&lt;/code&gt;&lt;/a&gt; runs the FIDO2 ceremonies, and &lt;a href="https://github.com/mattleads/passkeys-bundle" rel="noopener noreferrer"&gt;&lt;code&gt;mattleads/passkeys-bundle&lt;/code&gt;&lt;/a&gt; adds the product layer around them: the login flow, recovery codes, usage tracking, management pages and Stimulus controllers. I maintain the second one. You should be able to follow this guide without reading either bundle's source.&lt;/p&gt;

&lt;p&gt;The finished code is at &lt;a href="https://github.com/mattleads/passkeys-demo" rel="noopener noreferrer"&gt;github.com/mattleads/passkeys-demo&lt;/a&gt;. You write or edit 17 files. Everything else comes from Flex recipes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.2 or later. This guide uses 8.4.&lt;/li&gt;
&lt;li&gt;Composer.&lt;/li&gt;
&lt;li&gt;SQLite, which ships with PHP.&lt;/li&gt;
&lt;li&gt;A browser with a platform authenticator: Touch ID, Windows Hello, Android or a security key.&lt;/li&gt;
&lt;li&gt;No Node.js. AssetMapper serves everything.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Versions used below: &lt;code&gt;symfony/skeleton&lt;/code&gt; 8.1.*, &lt;code&gt;web-auth/webauthn-symfony-bundle&lt;/code&gt; 5.3.10, &lt;code&gt;mattleads/passkeys-bundle&lt;/code&gt; 0.1.1, &lt;code&gt;doctrine/orm&lt;/code&gt; 3.7 and &lt;code&gt;symfony/stimulus-bundle&lt;/code&gt; 3.6.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Skeleton and packages
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer create-project symfony/skeleton:&lt;span class="s2"&gt;"8.1.*"&lt;/span&gt; passkeys-demo
&lt;span class="nb"&gt;cd &lt;/span&gt;passkeys-demo
composer config extra.symfony.allow-contrib &lt;span class="nb"&gt;true&lt;/span&gt;   &lt;span class="c"&gt;# lets Flex apply the WebAuthn bundle's recipe&lt;/span&gt;

composer require mattleads/passkeys-bundle web-auth/webauthn-symfony-bundle &lt;span class="se"&gt;\&lt;/span&gt;
  symfony/security-bundle symfony/twig-bundle symfony/asset-mapper symfony/stimulus-bundle &lt;span class="se"&gt;\&lt;/span&gt;
  doctrine/orm doctrine/doctrine-bundle symfony/uid symfony/serializer symfony/property-access symfony/property-info &lt;span class="se"&gt;\&lt;/span&gt;
  symfony/rate-limiter symfony/lock symfony/password-hasher

php bin/console importmap:require @hotwired/stimulus @simplewebauthn/browser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;symfony/rate-limiter&lt;/code&gt; and &lt;code&gt;symfony/lock&lt;/code&gt; are for login throttling, which you want because recovery codes are short. &lt;code&gt;@simplewebauthn/browser&lt;/code&gt; is the small client library the Stimulus controllers use to talk to &lt;code&gt;navigator.credentials&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Flex registers the bundles and drops &lt;code&gt;config/packages/webauthn.yaml&lt;/code&gt; and &lt;code&gt;config/routes/webauthn_routes.yaml&lt;/code&gt; for you.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Environment
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# .env.local
APP_SECRET=change-me-to-something-long-and-random
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
RELYING_PARTY_ID=localhost
RELYING_PARTY_NAME="Passkeys Demo"
WEBAUTHN_ALLOWED_ORIGINS="http://localhost:8765,http://127.0.0.1:8765"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two values matter here. The relying-party id is &lt;code&gt;localhost&lt;/code&gt;. WebAuthn only works in a secure context. Browsers make an exception for &lt;code&gt;localhost&lt;/code&gt; over plain HTTP, but not for &lt;code&gt;127.0.0.1&lt;/code&gt;, so always open the app as &lt;code&gt;http://localhost:…&lt;/code&gt;. The port is part of the origin. If you serve on a different port, change it both here and in &lt;code&gt;webauthn.yaml&lt;/code&gt; below, or the ceremony fails with an origin mismatch.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Entities
&lt;/h2&gt;

&lt;p&gt;Two entities. The user carries an opaque &lt;em&gt;user handle&lt;/em&gt; for WebAuthn, never the email, so the email can change later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// src/Entity/User.php&lt;/span&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Entity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Repository\UserRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\ORM\Mapping&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="no"&gt;ORM&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;Symfony\Component\Security\Core\User\&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nc"&gt;PasswordAuthenticatedUserInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;UserInterface&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\Uid\Ulid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\PublicKeyCredentialUserEntity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="na"&gt;#[ORM\Entity(repositoryClass: UserRepository::class)]&lt;/span&gt;
&lt;span class="na"&gt;#[ORM\Table(name: 'app_user')]&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;UserInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;PasswordAuthenticatedUserInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Id, ORM\GeneratedValue, ORM\Column]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?int&lt;/span&gt; &lt;span class="nv"&gt;$id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(length: 180, unique: true)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(length: 26, unique: true)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$userHandle&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(length: 255, nullable: true)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="cd"&gt;/** @var list&amp;lt;string&amp;gt; */&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Column]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$roles&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;userHandle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Ulid&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getUserIdentifier&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getUserHandle&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;userHandle&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getPassword&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;setPassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;?string&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;password&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getRoles&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;array_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;array_unique&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;roles&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'ROLE_USER'&lt;/span&gt;&lt;span class="p"&gt;]));&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;eraseCredentials&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;toWebAuthnUserEntity&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;PublicKeyCredentialUserEntity&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PublicKeyCredentialUserEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;userHandle&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The credential extends the WebAuthn bundle's &lt;code&gt;CredentialRecord&lt;/code&gt;, whose fields come from a mapped superclass the bundle registers with Doctrine. We add an id and the usage timestamps, and implement the passkeys bundle's one-method interface so "last used" gets filled in automatically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// src/Entity/Credential.php&lt;/span&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Entity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Repository\CredentialRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\ORM\Mapping&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="no"&gt;ORM&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;MattLeads\PasskeysBundle\Contract\TracksCredentialUsageInterface&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\CredentialRecord&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="na"&gt;#[ORM\Entity(repositoryClass: CredentialRepository::class)]&lt;/span&gt;
&lt;span class="na"&gt;#[ORM\Table(name: 'webauthn_credentials')]&lt;/span&gt;
&lt;span class="na"&gt;#[ORM\HasLifecycleCallbacks]&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Credential&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;CredentialRecord&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;TracksCredentialUsageInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Id, ORM\GeneratedValue, ORM\Column]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?int&lt;/span&gt; &lt;span class="nv"&gt;$id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(nullable: true)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;\DateTimeImmutable&lt;/span&gt; &lt;span class="nv"&gt;$createdAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(nullable: true)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;\DateTimeImmutable&lt;/span&gt; &lt;span class="nv"&gt;$lastUsedAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\PrePersist]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;onPrePersist&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;createdAt&lt;/span&gt; &lt;span class="o"&gt;??=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;\DateTimeImmutable&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cd"&gt;/** The validators hand back a plain CredentialRecord; we turn it into this entity before saving. */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;fromRecord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;CredentialRecord&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;self&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;publicKeyCredentialId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;transports&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;attestationType&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;trustPath&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;aaguid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;credentialPublicKey&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;userHandle&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;counter&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;otherUI&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;backupEligible&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;backupStatus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uvInitialized&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cd"&gt;/** Fields that change after each successful login. */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;syncFrom&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;CredentialRecord&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;counter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;backupStatus&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;backupStatus&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uvInitialized&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;uvInitialized&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;otherUI&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$r&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;otherUI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getLastUsedAt&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;\DateTimeImmutable&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;lastUsedAt&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;markUsed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;\DateTimeImmutable&lt;/span&gt; &lt;span class="nv"&gt;$at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;lastUsedAt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$at&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep &lt;code&gt;fromRecord()&lt;/code&gt; and &lt;code&gt;syncFrom()&lt;/code&gt; in mind. Section 4 explains why they exist, and they prevent the first error you would otherwise hit.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Repositories
&lt;/h2&gt;

&lt;p&gt;The WebAuthn bundle looks users up by username, and that string must be exactly what &lt;code&gt;getUserIdentifier()&lt;/code&gt; returns. If the two disagree, the "add a passkey" page cannot find the current user and the login flow endpoint cannot find anyone.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// src/Repository/UserRepository.php&lt;/span&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Entity\User&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Persistence\ManagerRegistry&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;Symfony\Component\Security\Core\User\&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nc"&gt;PasswordAuthenticatedUserInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;PasswordUpgraderInterface&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\Bundle\Repository\PublicKeyCredentialUserEntityRepositoryInterface&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\PublicKeyCredentialUserEntity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;ServiceEntityRepository&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;PublicKeyCredentialUserEntityRepositoryInterface&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;PasswordUpgraderInterface&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;ManagerRegistry&lt;/span&gt; &lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;findOneByUsername&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;?PublicKeyCredentialUserEntity&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOneBy&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s1"&gt;'email'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$username&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toWebAuthnUserEntity&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;findOneByUserHandle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$userHandle&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;?PublicKeyCredentialUserEntity&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOneBy&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s1"&gt;'userHandle'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$userHandle&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toWebAuthnUserEntity&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;User&lt;/span&gt; &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;persist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;upgradePassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;PasswordAuthenticatedUserInterface&lt;/span&gt; &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$newHashedPassword&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setPassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$newHashedPassword&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For credentials, the WebAuthn bundle ships a Doctrine repository that already handles the base64 storage of binary ids. Extend it, add deletion so the passkeys bundle can offer &lt;strong&gt;Revoke&lt;/strong&gt;, and override &lt;code&gt;saveCredentialRecord()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// src/Repository/CredentialRepository.php&lt;/span&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Entity\Credential&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Persistence\ManagerRegistry&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;MattLeads\PasskeysBundle\Contract\CanDeleteCredentialRecord&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\Bundle\Repository\DoctrineCredentialSourceRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Webauthn\CredentialRecord&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CredentialRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;DoctrineCredentialSourceRepository&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;CanDeleteCredentialRecord&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;ManagerRegistry&lt;/span&gt; &lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Credential&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;saveCredentialRecord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;CredentialRecord&lt;/span&gt; &lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;Credential&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$existing&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOneByCredentialId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;publicKeyCredentialId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$existing&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;Credential&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$existing&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;syncFrom&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;   &lt;span class="c1"&gt;// after a login: counter, backup flags&lt;/span&gt;
                &lt;span class="nv"&gt;$credentialRecord&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$existing&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$credentialRecord&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Credential&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;fromRecord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;   &lt;span class="c1"&gt;// registration&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;saveCredentialRecord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;deleteCredentialRecord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;CredentialRecord&lt;/span&gt; &lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$credentialRecord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The conversion exists because the attestation and assertion validators construct a plain &lt;code&gt;Webauthn\CredentialRecord&lt;/code&gt;. Persist that directly and Doctrine throws &lt;em&gt;"The given entity of type 'Webauthn\CredentialRecord' has no identity/no id values set"&lt;/em&gt;, because only your subclass has an id mapping. Registration needs a new entity. A login needs the existing row updated, because the signature counter and the backup state changed.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Security configuration
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/security.yaml&lt;/span&gt;
&lt;span class="na"&gt;security&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;password_hashers&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;auto'&lt;/span&gt;
    &lt;span class="na"&gt;providers&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;app_users&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;entity&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;class&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;App\Entity\User&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;property&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;email&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
    &lt;span class="na"&gt;firewalls&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;dev&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;pattern&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;^/(_profiler(/|$)|(_wdt|assets|build)/)&lt;/span&gt;
            &lt;span class="na"&gt;security&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;
        &lt;span class="na"&gt;main&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;lazy&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
            &lt;span class="na"&gt;provider&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_users&lt;/span&gt;
            &lt;span class="na"&gt;entry_point&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;form_login&lt;/span&gt;
            &lt;span class="na"&gt;form_login&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;login_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_login&lt;/span&gt;
                &lt;span class="na"&gt;check_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_login&lt;/span&gt;
                &lt;span class="na"&gt;username_parameter&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;_username&lt;/span&gt;
                &lt;span class="na"&gt;password_parameter&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;_password&lt;/span&gt;
                &lt;span class="na"&gt;enable_csrf&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
                &lt;span class="na"&gt;default_target_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_account&lt;/span&gt;
            &lt;span class="na"&gt;webauthn&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;authentication&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                    &lt;span class="na"&gt;routes&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                        &lt;span class="na"&gt;options_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/login/passkey/options&lt;/span&gt;
                        &lt;span class="na"&gt;result_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/login/passkey/result&lt;/span&gt;
            &lt;span class="na"&gt;custom_authenticators&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;MattLeads\PasskeysBundle\Security\RecoveryCodeAuthenticator&lt;/span&gt;
            &lt;span class="na"&gt;login_throttling&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;max_attempts&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;5&lt;/span&gt;
            &lt;span class="na"&gt;logout&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_logout&lt;/span&gt;
                &lt;span class="na"&gt;target&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;app_login&lt;/span&gt;
    &lt;span class="na"&gt;access_control&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;^/account&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;roles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;ROLE_USER&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three authenticators live on this firewall: password form, WebAuthn assertion and recovery code. Symfony needs &lt;code&gt;entry_point&lt;/code&gt; to know where to send anonymous visitors. Forget it and the container refuses to compile with a long message about "multiple authenticators".&lt;/p&gt;

&lt;p&gt;There is no &lt;code&gt;registration:&lt;/code&gt; block under &lt;code&gt;webauthn:&lt;/code&gt;, and that is deliberate. That block is for passwordless &lt;em&gt;sign-up&lt;/em&gt; and always reads the username from the request body. To add a passkey to the account you are already logged into, use the WebAuthn bundle's standalone creation controllers instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/webauthn.yaml&lt;/span&gt;
&lt;span class="na"&gt;webauthn&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;credential_repository&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;App\Repository\CredentialRepository&lt;/span&gt;
    &lt;span class="na"&gt;user_repository&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;App\Repository\UserRepository&lt;/span&gt;
    &lt;span class="na"&gt;allowed_origins&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;http://localhost:8765'&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;http://127.0.0.1:8765'&lt;/span&gt;&lt;span class="pi"&gt;]&lt;/span&gt;
    &lt;span class="na"&gt;creation_profiles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;rp&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(RELYING_PARTY_NAME)%'&lt;/span&gt;
                &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(RELYING_PARTY_ID)%'&lt;/span&gt;
            &lt;span class="na"&gt;authenticator_selection_criteria&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;resident_key&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;required&lt;/span&gt;        &lt;span class="c1"&gt;# discoverable credential → shows up in browser autofill&lt;/span&gt;
                &lt;span class="na"&gt;user_verification&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;preferred&lt;/span&gt;
    &lt;span class="na"&gt;request_profiles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;rp_id&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(RELYING_PARTY_ID)%'&lt;/span&gt;
            &lt;span class="na"&gt;user_verification&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;preferred&lt;/span&gt;
    &lt;span class="na"&gt;controllers&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="na"&gt;creation&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;add_passkey&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;options_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/account/passkeys/add/options&lt;/span&gt;
                &lt;span class="na"&gt;result_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/account/passkeys/add/result&lt;/span&gt;
                &lt;span class="na"&gt;user_entity_guesser&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Webauthn\Bundle\Security\Guesser\CurrentUserEntityGuesser&lt;/span&gt;
                &lt;span class="na"&gt;profile&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;default&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;resident_key: required&lt;/code&gt; makes the passkey &lt;em&gt;discoverable&lt;/em&gt;, which lets the browser offer it from the username field's autofill (conditional UI). Without it you get a credential that only works when the server names it first.&lt;/p&gt;

&lt;p&gt;The creation controllers above are registered as routes named &lt;code&gt;webauthn.controller.creation.request.add_passkey&lt;/code&gt; and &lt;code&gt;…response.add_passkey&lt;/code&gt;. Tell the passkeys bundle about them so its management page can render the "Add a passkey" button, and import its routes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/mattleads_passkeys.yaml&lt;/span&gt;
&lt;span class="na"&gt;mattleads_passkeys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;recovery&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;default_target_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/account&lt;/span&gt;
    &lt;span class="na"&gt;management&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;add_passkey&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;options_route&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;webauthn.controller.creation.request.add_passkey&lt;/span&gt;
            &lt;span class="na"&gt;result_route&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;webauthn.controller.creation.response.add_passkey&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/routes/mattleads_passkeys.yaml&lt;/span&gt;
&lt;span class="na"&gt;mattleads_passkeys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;resource&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;@MattLeadsPasskeysBundle/config/routes.php'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That gives you &lt;code&gt;/login/flow&lt;/code&gt;, &lt;code&gt;/login/recovery&lt;/code&gt;, &lt;code&gt;/account/passkeys&lt;/code&gt;, &lt;code&gt;/account/passkeys/revoke&lt;/code&gt; and &lt;code&gt;/account/passkeys/recovery-codes&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Controllers
&lt;/h2&gt;

&lt;p&gt;Two of ours. A security controller for the login page, logout and the account page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// src/Controller/SecurityController.php&lt;/span&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Controller&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Bundle\FrameworkBundle\Controller\AbstractController&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\HttpFoundation\Response&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\Routing\Attribute\Route&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\Security\Http\Attribute\IsGranted&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\Security\Http\Authentication\AuthenticationUtils&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SecurityController&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;AbstractController&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;#[Route('/login', name: 'app_login')]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;login&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;AuthenticationUtils&lt;/span&gt; &lt;span class="nv"&gt;$utils&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;Response&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getUser&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redirectToRoute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'app_account'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;render&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'security/login.html.twig'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'error'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$utils&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getLastAuthenticationError&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
            &lt;span class="s1"&gt;'last_username'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$utils&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getLastUsername&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="na"&gt;#[Route('/logout', name: 'app_logout')]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;logout&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;never&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;\LogicException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Handled by the firewall.'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="na"&gt;#[Route('/', name: 'app_home')]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;home&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;Response&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;redirectToRoute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getUser&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="s1"&gt;'app_account'&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'app_login'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="na"&gt;#[Route('/account', name: 'app_account')]&lt;/span&gt;
    &lt;span class="na"&gt;#[IsGranted('ROLE_USER')]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;Response&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;render&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'account/index.html.twig'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And a deliberately plain registration controller: email and password, no Form component, so the tutorial stays about passkeys. The repository has the full version with validation and a CSRF check.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nv"&gt;$user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$email&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setPassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$hasher&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;hashPassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$password&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="nv"&gt;$users&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Users then add passkeys from their account page. This progressive adoption path is the one most real applications want. Passwordless sign-up is a separate topic.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Templates
&lt;/h2&gt;

&lt;p&gt;A base layout with the importmap, and a login page that includes the bundle's hybrid form. The include is the whole integration on the frontend:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight twig"&gt;&lt;code&gt;&lt;span class="c"&gt;{# templates/security/login.html.twig #}&lt;/span&gt;
&lt;span class="cp"&gt;{%&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="s1"&gt;'base.html.twig'&lt;/span&gt; &lt;span class="cp"&gt;%}&lt;/span&gt;
&lt;span class="cp"&gt;{%&lt;/span&gt; &lt;span class="k"&gt;block&lt;/span&gt; &lt;span class="nv"&gt;body&lt;/span&gt; &lt;span class="cp"&gt;%}&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;h1&amp;gt;&lt;/span&gt;Sign in&lt;span class="nt"&gt;&amp;lt;/h1&amp;gt;&lt;/span&gt;
    &lt;span class="cp"&gt;{{&lt;/span&gt; &lt;span class="nv"&gt;include&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'@MattLeadsPasskeys/login/hybrid.html.twig'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="err"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;login_check_path&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'app_login'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;options_url&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'webauthn.controller.security.main.request.options'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;result_url&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'webauthn.controller.security.main.request.result'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;flow_url&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'mattleads_passkeys_login_flow'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;recovery_url&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'mattleads_passkeys_recovery_login'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;csrf_token&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;csrf_token&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'authenticate'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="nv"&gt;last_identifier&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;last_username&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nv"&gt;error&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="err"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="cp"&gt;}}&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;p&amp;gt;&amp;lt;a&lt;/span&gt; &lt;span class="na"&gt;href=&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="cp"&gt;{{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'app_register'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="cp"&gt;}}&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;No account yet? Create one&lt;span class="nt"&gt;&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;{%&lt;/span&gt; &lt;span class="k"&gt;endblock&lt;/span&gt; &lt;span class="cp"&gt;%}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The two &lt;code&gt;webauthn.controller.security.main.request.*&lt;/code&gt; routes are created by the firewall's &lt;code&gt;authentication:&lt;/code&gt; block. &lt;code&gt;main&lt;/code&gt; is the firewall name.&lt;/p&gt;

&lt;p&gt;The bundle's own pages (passkey list, recovery codes, recovery login) extend &lt;code&gt;@MattLeadsPasskeys/layout.html.twig&lt;/code&gt;. Override that one file to pull them into your layout:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight twig"&gt;&lt;code&gt;&lt;span class="c"&gt;{# templates/bundles/MattLeadsPasskeysBundle/layout.html.twig #}&lt;/span&gt;
&lt;span class="cp"&gt;{%&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="s1"&gt;'base.html.twig'&lt;/span&gt; &lt;span class="cp"&gt;%}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;base.html.twig&lt;/code&gt; needs &lt;code&gt;{{ importmap('app') }}&lt;/code&gt; in the head and, for the demo, a nav with links to &lt;code&gt;app_account&lt;/code&gt;, &lt;code&gt;mattleads_passkeys_manage&lt;/code&gt; and &lt;code&gt;app_logout&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Frontend without Node
&lt;/h2&gt;

&lt;p&gt;Enable the bundle's Stimulus controllers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;assets/controllers.json&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"controllers"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"@mattleads/passkeys-bundle"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"hybrid-login"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"enabled"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"fetch"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"eager"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"passkey"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"enabled"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"fetch"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"lazy"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"confirm"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"enabled"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"fetch"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"lazy"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"entrypoints"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// assets/app.js&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./stimulus_bootstrap.js&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;StimulusBundle reads the bundle's &lt;code&gt;assets/package.json&lt;/code&gt;, AssetMapper serves the files from &lt;code&gt;vendor/&lt;/code&gt;, and the browser imports &lt;code&gt;@simplewebauthn/browser&lt;/code&gt; from the importmap you populated in step 1. Check with &lt;code&gt;php bin/console debug:asset-map | grep passkeys&lt;/code&gt;. You should see the three controllers and &lt;code&gt;webauthn_service.js&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Run it
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console doctrine:schema:create
php &lt;span class="nt"&gt;-S&lt;/span&gt; localhost:8765 &lt;span class="nt"&gt;-t&lt;/span&gt; public public/index.php
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open &lt;a href="http://localhost:8765" rel="noopener noreferrer"&gt;http://localhost:8765&lt;/a&gt; and walk through:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;Create account&lt;/em&gt;, then sign in with the password. The flow endpoint returned &lt;code&gt;password&lt;/code&gt;, so the form revealed a password field.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Passkeys&lt;/em&gt;, then &lt;em&gt;Add a passkey to this device&lt;/em&gt;, then approve with Touch ID or Windows Hello. The table shows the new credential, its transports (&lt;code&gt;hybrid, internal&lt;/code&gt; for a synced platform passkey), whether it is backed up, and &lt;em&gt;Last used: never&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Sign out. Type the email and press &lt;em&gt;Continue&lt;/em&gt;. This time the flow endpoint says &lt;code&gt;passkey&lt;/code&gt;, the browser prompts, and you land on &lt;code&gt;/account&lt;/code&gt; without ever seeing a password field. Back on the passkeys page, &lt;em&gt;Last used&lt;/em&gt; now has a timestamp.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Generate new recovery codes&lt;/em&gt;. Ten codes, shown once. Sign out, open &lt;em&gt;Lost access?&lt;/em&gt; and enter one. Each code works exactly once, and after five bad attempts the firewall's throttling kicks in.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Revoke&lt;/em&gt;, which takes two clicks because the button changes to &lt;em&gt;Confirm revoke&lt;/em&gt;. Sign out and in again, and you are back to the password field.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One thing to know about step 5: revoking deletes the credential on the server, but the passkey still exists in iCloud Keychain or Google Password Manager as an orphan. That is how passkeys work everywhere. The platform vendors are adding signal APIs so a site can ask the client to clean up, but you cannot rely on them yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  10. The three errors you will hit if you skip a step
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Error&lt;/th&gt;
&lt;th&gt;Cause&lt;/th&gt;
&lt;th&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;em&gt;"has no identity/no id values set"&lt;/em&gt; on registration&lt;/td&gt;
&lt;td&gt;persisting the validator's plain &lt;code&gt;CredentialRecord&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;convert to your entity in &lt;code&gt;saveCredentialRecord()&lt;/code&gt; (section 4)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;em&gt;"Unable to find the user entity"&lt;/em&gt; when adding a passkey&lt;/td&gt;
&lt;td&gt;using the firewall's &lt;code&gt;registration:&lt;/code&gt; block, which reads the username from the body&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;webauthn.controllers.creation&lt;/code&gt; with &lt;code&gt;CurrentUserEntityGuesser&lt;/code&gt; (section 5)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ceremony fails with an origin / RP id error&lt;/td&gt;
&lt;td&gt;opened via &lt;code&gt;127.0.0.1&lt;/code&gt;, or a port not in &lt;code&gt;allowed_origins&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;use &lt;code&gt;http://localhost:&amp;lt;port&amp;gt;&lt;/code&gt; and list that exact origin&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;A fourth problem raises no error at all. Without &lt;code&gt;resident_key: required&lt;/code&gt;, passkeys never appear in the browser's autofill, and users keep typing passwords.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where to go from here
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Passwordless sign-up&lt;/strong&gt;: the firewall's &lt;code&gt;registration:&lt;/code&gt; block with &lt;code&gt;RequestBodyUserEntityGuesser&lt;/code&gt; and a &lt;code&gt;CanRegisterUserEntity&lt;/code&gt; repository.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Production&lt;/strong&gt;: HTTPS, &lt;code&gt;RELYING_PARTY_ID&lt;/code&gt; set to your apex domain so passkeys work on all subdomains, &lt;code&gt;allowed_origins&lt;/code&gt; listing every origin that will call the endpoints, migrations instead of &lt;code&gt;schema:create&lt;/code&gt;, and a real session storage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Styling&lt;/strong&gt;: override any template under &lt;code&gt;templates/bundles/MattLeadsPasskeysBundle/&lt;/code&gt;. The Stimulus controllers dispatch &lt;code&gt;error&lt;/code&gt;, &lt;code&gt;authenticated&lt;/code&gt; and &lt;code&gt;armed&lt;/code&gt; events if you want your own UI instead of the built-in error line.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Which path to take depends on your users. If they already have passwords, ship this hybrid flow and let passkeys spread one account page at a time. If you are starting from zero and want no passwords at all, start from the firewall's &lt;code&gt;registration:&lt;/code&gt; block instead. Either way, ship recovery codes and login throttling together, because a short code without a rate limit is a brute-force target.&lt;/p&gt;

&lt;p&gt;Issues and pull requests on the demo or the bundle are welcome.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/passkeys-demo" rel="noopener noreferrer"&gt;https://github.com/mattleads/passkeys-demo&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>webauthn</category>
      <category>security</category>
    </item>
    <item>
      <title>7.7x Smaller and Encrypted at Rest: Compressing Symfony Messenger Payloads Without Touching a Handler</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Mon, 02 Nov 2026 17:14:07 +0000</pubDate>
      <link>https://dev.to/mattleads/77x-smaller-and-encrypted-at-rest-compressing-symfony-messenger-payloads-without-touching-a-1ij4</link>
      <guid>https://dev.to/mattleads/77x-smaller-and-encrypted-at-rest-compressing-symfony-messenger-payloads-without-touching-a-1ij4</guid>
      <description>&lt;p&gt;Symfony Messenger serializes a message, hands the bytes to a transport and forgets about them. Two things routinely go wrong with those bytes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;They are too big.&lt;/strong&gt; A bulk export, a sync job with a few thousand rows, a report with embedded data, and you're past SQS's 256 KB limit or your Redis memory is going somewhere it shouldn't.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;They are readable.&lt;/strong&gt; Names, emails, IBANs sit in plain text in &lt;code&gt;messenger_messages&lt;/code&gt;, in a Redis RDB dump, on a RabbitMQ disk and in the dead-letter queue nobody has looked at since March.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://github.com/mattleads/messenger-compress-bundle" rel="noopener noreferrer"&gt;&lt;code&gt;mattleads/messenger-compress-bundle&lt;/code&gt;&lt;/a&gt; fixes both at the transport-serializer layer. You opt in per message with a stamp or enforce a policy per transport, and your handlers receive the same plain PHP objects they always did. We'll walk through the whole thing on a small Doctrine (SQLite) transport, because then the queue is a table you can &lt;code&gt;SELECT&lt;/code&gt; from and see what changed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;PHP 8.2 or newer. &lt;code&gt;ext-zlib&lt;/code&gt; and &lt;code&gt;ext-sodium&lt;/code&gt; ship with PHP, so there is nothing to install.&lt;/li&gt;
&lt;li&gt;A Symfony 6.4, 7.x or 8.x application with &lt;code&gt;symfony/messenger&lt;/code&gt;. The outputs below come from Symfony 8.1.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mattleads/messenger-compress-bundle&lt;/code&gt; v0.1.1.&lt;/li&gt;
&lt;li&gt;To follow along exactly, clone &lt;a href="https://github.com/mattleads/messenger-compress-demo" rel="noopener noreferrer"&gt;the demo&lt;/a&gt;. It uses a Doctrine transport on SQLite.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. Install
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require mattleads/messenger-compress-bundle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Symfony Flex registers the bundle. Without Flex, add it yourself:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// config/bundles.php&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
    &lt;span class="nc"&gt;MattLeads\MessengerCompressBundle\MattLeadsMessengerCompressBundle&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'all'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nothing happens yet. The bundle registers a serializer service, &lt;code&gt;mattleads_messenger_compress.serializer&lt;/code&gt;, that wraps Messenger's default serializer. Until a transport uses it, your messages are untouched.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Wire it to a transport
&lt;/h2&gt;

&lt;p&gt;You have two options. Start with &lt;strong&gt;one transport&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/messenger.yaml&lt;/span&gt;
&lt;span class="na"&gt;framework&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;messenger&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;failure_transport&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;failed&lt;/span&gt;
        &lt;span class="na"&gt;transports&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;async&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;dsn&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_TRANSPORT_DSN)%'&lt;/span&gt;
                &lt;span class="na"&gt;serializer&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;mattleads_messenger_compress.serializer&lt;/span&gt;
            &lt;span class="na"&gt;failed&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;doctrine://default?queue_name=failed'&lt;/span&gt;
        &lt;span class="na"&gt;routing&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;App\Message\GenerateInvoiceBatch'&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="s"&gt;async&lt;/span&gt;
            &lt;span class="s"&gt;'App\Message\ExportCustomerData'&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="s"&gt;async&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or wrap the default serializer so &lt;strong&gt;every&lt;/strong&gt; transport gets it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/mattleads_messenger_compress.yaml&lt;/span&gt;
&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;decorate_default_serializer&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One tip for the walkthrough only: Messenger's default serializer is PHP &lt;code&gt;serialize()&lt;/code&gt;. If you switch the default to the JSON one, plain bodies become human-readable in the database, which makes the "before" picture much clearer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;framework&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;messenger&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;serializer&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;default_serializer&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;messenger.transport.symfony_serializer&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bundle doesn't care which one you wrap. It compresses and encrypts bytes.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. See the problem first
&lt;/h2&gt;

&lt;p&gt;Here is a message you would not want sitting in a queue table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ExportCustomerData&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$customerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$fullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$iban&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dispatch it as usual and look at the row. In the demo, &lt;code&gt;app:queue:inspect --grep &amp;lt;string&amp;gt;&lt;/code&gt; does this. By hand it's just SQL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;messenger_messages&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; id   message              X-Compression   X-Encryption   key   encoding   body bytes   body preview
 1    ExportCustomerData   -               -              -     -          119          {"customerId":"cust-4711","fullName":"Nino Beri…
 [ERROR] "GE29NB0000000101904917" is readable in 1 stored message(s).
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The IBAN is right there. Every backup of that database has it too.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Encrypt it
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Generate a key
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;bin/console messenger-compress:generate-key &lt;span class="nt"&gt;-v&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;k3Jm…(44 characters of base64)…=

Add to .env.local (never commit it):
  MESSENGER_ENCRYPTION_KEY_V1=k3Jm…
and to config/packages/mattleads_messenger_compress.yaml:
  encryption: { enabled: true, keys: { v1: '%env(MESSENGER_ENCRYPTION_KEY_V1)%' } }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's 32 random bytes, base64-encoded. Put it in &lt;code&gt;.env.local&lt;/code&gt; for development and in your secrets store for production. Symfony's own vault works fine:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;bin/console secrets:set MESSENGER_ENCRYPTION_KEY_V1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Configure
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/mattleads_messenger_compress.yaml&lt;/span&gt;
&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;encryption&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="na"&gt;keys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;v1&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_ENCRYPTION_KEY_V1)%'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Dispatch with a stamp
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;MattLeads\MessengerCompressBundle\Stamp\EncryptStamp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nv"&gt;$bus&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ExportCustomerData&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;EncryptStamp&lt;/span&gt;&lt;span class="p"&gt;()]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Same row, after:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; 2    ExportCustomerData   -               xchacha20poly1305   v1    base64     212          jUa0PNnAtVBUT5+uTPOOxsbUrOTsIg9cYKnD1WAKsnRQEyN…
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The body is XChaCha20-Poly1305 ciphertext (libsodium, fresh 192-bit nonce per message, authenticated). The headers are still readable: the message type, the scheme, the key id. That's deliberate: the consumer needs them to know what to do and Messenger needs the type to route the message. Which brings up the one rule worth memorizing, call it &lt;strong&gt;the header rule: stamps travel as headers and are not encrypted.&lt;/strong&gt; Put secrets in the message body, never in a stamp.&lt;/p&gt;

&lt;p&gt;Notice the size went &lt;em&gt;up&lt;/em&gt;: 119 bytes became 212. A 24-byte nonce, a 16-byte tag and base64's 33 % overhead cost more than a tiny body saves. That's fine. Encryption is a decision about sensitivity, not about size.&lt;/p&gt;

&lt;h3&gt;
  
  
  Or encrypt everything on this transport
&lt;/h3&gt;

&lt;p&gt;If a transport only ever carries sensitive work, stop thinking about stamps:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;encryption&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="na"&gt;always&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="na"&gt;keys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;v1&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_ENCRYPTION_KEY_V1)%'&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A single message can opt out with &lt;code&gt;PlainStamp&lt;/code&gt;. An explicit &lt;code&gt;EncryptStamp&lt;/code&gt; always wins over policy.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Compress the big ones
&lt;/h2&gt;

&lt;p&gt;Now the other problem. &lt;code&gt;GenerateInvoiceBatch&lt;/code&gt; with 5,000 order lines serializes to 759 KB of JSON. Three ways to shrink it:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explicitly, per message:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;MattLeads\MessengerCompressBundle\Stamp\CompressStamp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nv"&gt;$bus&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$batch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CompressStamp&lt;/span&gt;&lt;span class="p"&gt;()]);&lt;/span&gt;            &lt;span class="c1"&gt;// configured default: deflate&lt;/span&gt;
&lt;span class="nv"&gt;$bus&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$batch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CompressStamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'gzip'&lt;/span&gt;&lt;span class="p"&gt;)]);&lt;/span&gt;
&lt;span class="nv"&gt;$bus&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$batch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CompressStamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'zstd'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)]);&lt;/span&gt;   &lt;span class="c1"&gt;// algorithm + level; zstd needs ext-zstd&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Automatically above a size.&lt;/strong&gt; This is the default to pick, because nobody remembers to add a stamp to the one message that grows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;compression&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;default_algorithm&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;deflate&lt;/span&gt;     &lt;span class="c1"&gt;# deflate | gzip | zstd&lt;/span&gt;
        &lt;span class="na"&gt;level&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;                    &lt;span class="c1"&gt;# null = the algorithm's default&lt;/span&gt;
        &lt;span class="na"&gt;auto_threshold&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;4096&lt;/span&gt;           &lt;span class="c1"&gt;# any body &amp;gt;= 4 KiB is compressed, no stamp needed&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Always:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;compression&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;always&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two details of the automatic policies: they only &lt;em&gt;keep&lt;/em&gt; the compressed body when it is actually smaller than the original (random blobs and already-compressed data pass through untouched) and &lt;code&gt;PlainStamp&lt;/code&gt; opts a message out. An explicit &lt;code&gt;CompressStamp&lt;/code&gt; is always honored even if the result is larger.&lt;/p&gt;

&lt;p&gt;What it looks like with &lt;code&gt;auto_threshold: 4096&lt;/code&gt;:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Message&lt;/th&gt;
&lt;th&gt;Stamps&lt;/th&gt;
&lt;th&gt;Raw&lt;/th&gt;
&lt;th&gt;On the wire&lt;/th&gt;
&lt;th&gt;Ratio&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;50 invoice lines&lt;/td&gt;
&lt;td&gt;none (auto)&lt;/td&gt;
&lt;td&gt;7.6 KB&lt;/td&gt;
&lt;td&gt;1,416 B&lt;/td&gt;
&lt;td&gt;18.6 %&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5,000 invoice lines&lt;/td&gt;
&lt;td&gt;none (auto)&lt;/td&gt;
&lt;td&gt;758,571 B&lt;/td&gt;
&lt;td&gt;98,060 B&lt;/td&gt;
&lt;td&gt;12.9 %&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5,000 invoice lines&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;CompressStamp('gzip')&lt;/code&gt;, &lt;code&gt;EncryptStamp('v2')&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;758,571 B&lt;/td&gt;
&lt;td&gt;98,136 B&lt;/td&gt;
&lt;td&gt;12.9 %&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Customer export&lt;/td&gt;
&lt;td&gt;&lt;code&gt;EncryptStamp()&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;119 B&lt;/td&gt;
&lt;td&gt;212 B&lt;/td&gt;
&lt;td&gt;178 %&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The third row is the common production combination: compress &lt;em&gt;and&lt;/em&gt; encrypt. The bundle always compresses first and encrypts second regardless of the order of your stamps, because ciphertext does not compress. The 76 bytes between rows two and three are the gzip header plus the nonce and tag.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;One caveat from the CRIME/BREACH family: compressed-then-encrypted length can leak information about the plaintext. If a single message mixes attacker-controlled input with a secret and the length is observable to that attacker, do not compress it. For almost every queue job this isn't a concern, but it's worth knowing.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. What goes over the wire
&lt;/h2&gt;

&lt;p&gt;The bundle adds up to four headers to the encoded envelope. Everything else (the &lt;code&gt;type&lt;/code&gt; header, the stamp headers) is whatever the inner serializer produced.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Header&lt;/th&gt;
&lt;th&gt;Value&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;X-Compression&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;deflate&lt;/code&gt; \&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;gzip&lt;/code&gt; \&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;X-Encryption&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;xchacha20poly1305&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;body was encrypted with this scheme&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;X-Encryption-Key-Id&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;e.g. &lt;code&gt;v1&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;which key, so consumers can rotate&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;X-Payload-Encoding&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;base64&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;body is base64 text&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Base64 is the default because the Doctrine, Redis and SQS transports all want text bodies. On AMQP you can drop it and save the 33 %:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;encoding&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;raw&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because everything is in headers and the body is self-describing, a consumer with the bundle installed decodes any mix of plain, compressed, encrypted and compressed-and-encrypted messages from the same queue. You can roll the bundle out to consumers first and start stamping messages later.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Consume, and get metrics for free
&lt;/h2&gt;

&lt;p&gt;Nothing changes in the handler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="na"&gt;#[AsMessageHandler]&lt;/span&gt;
&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ExportCustomerDataHandler&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;ExportCustomerData&lt;/span&gt; &lt;span class="nv"&gt;$message&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// $message is the plain object. Decryption happened in the transport serializer.&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But the envelope your handler is wrapped in now carries a &lt;code&gt;TransformedStamp&lt;/code&gt; describing what the serializer undid: &lt;code&gt;compression&lt;/code&gt;, &lt;code&gt;encryption&lt;/code&gt;, &lt;code&gt;keyId&lt;/code&gt;, &lt;code&gt;wireSize&lt;/code&gt;, &lt;code&gt;rawSize&lt;/code&gt; and a &lt;code&gt;ratio()&lt;/code&gt; helper. It implements &lt;code&gt;NonSendableStampInterface&lt;/code&gt;, so it is never sent back out if the message is re-dispatched. A tiny listener turns it into logs or metrics:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;MattLeads\MessengerCompressBundle\Stamp\TransformedStamp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\EventDispatcher\Attribute\AsEventListener&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TransformedStampLogger&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;LoggerInterface&lt;/span&gt; &lt;span class="nv"&gt;$logger&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

    &lt;span class="na"&gt;#[AsEventListener]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;WorkerMessageReceivedEvent&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$stamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEnvelope&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;last&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TransformedStamp&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// message was neither compressed nor encrypted&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'compression={c} encryption={e} key={k} wire={w} raw={r} ratio={ratio}'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'c'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;compression&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'-'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'e'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;encryption&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'-'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'k'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;keyId&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'-'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'w'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;wireSize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'r'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;rawSize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'ratio'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'%.1f%%'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nv"&gt;$stamp&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;ratio&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ bin/console messenger:consume async --limit=5
Received ExportCustomerData: compression=- encryption=xchacha20poly1305 key=v1 wire=212 B raw=119 B ratio=178.2%
Handled export for cust-4711 (Nino Beridze, iban ends 4917)
Received GenerateInvoiceBatch: compression=deflate encryption=- key=- wire=98,060 B raw=758,571 B ratio=12.9%
Handled batch-5000: 5000 lines, total 15,537,656.65 EUR
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Push &lt;code&gt;ratio()&lt;/code&gt; and &lt;code&gt;wireSize&lt;/code&gt; into your metrics backend tagged by message class and you've got a dashboard of what each job actually costs your broker.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Rotate keys without draining the queue
&lt;/h2&gt;

&lt;p&gt;Keys leak, people leave, policies say "every 90 days". Rotation is the part most home-grown encryption layers get wrong, because there's always a message in flight encrypted with the old key.&lt;/p&gt;

&lt;p&gt;The bundle's answer is a key ring. Every encrypted message carries its key id in &lt;code&gt;X-Encryption-Key-Id&lt;/code&gt;; consumers decode with whichever key the message names and &lt;code&gt;active_key&lt;/code&gt; says which key &lt;em&gt;new&lt;/em&gt; messages use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;mattleads_messenger_compress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;encryption&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="na"&gt;active_key&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_ACTIVE_KEY)%'&lt;/span&gt;
        &lt;span class="na"&gt;keys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;v1&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_ENCRYPTION_KEY_V1)%'&lt;/span&gt;
            &lt;span class="na"&gt;v2&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(MESSENGER_ENCRYPTION_KEY_V2)%'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The procedure, in order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Generate &lt;code&gt;v2&lt;/code&gt; (&lt;code&gt;messenger-compress:generate-key --id v2 -v&lt;/code&gt;) and deploy it to &lt;strong&gt;every consumer&lt;/strong&gt; alongside &lt;code&gt;v1&lt;/code&gt;. Nothing changes yet; &lt;code&gt;active_key&lt;/code&gt; is still &lt;code&gt;v1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Flip &lt;code&gt;active_key&lt;/code&gt; to &lt;code&gt;v2&lt;/code&gt; on producers. New messages are &lt;code&gt;v2&lt;/code&gt;; consumers still decode the &lt;code&gt;v1&lt;/code&gt; backlog.&lt;/li&gt;
&lt;li&gt;Once the queues (including the failure transport) have cycled, remove &lt;code&gt;v1&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can watch it happen in the demo by running the producer with one key and the consumer with the other:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console app:dispatch &lt;span class="nt"&gt;--export&lt;/span&gt; &lt;span class="nt"&gt;--encrypt&lt;/span&gt;                              &lt;span class="c"&gt;# active_key=v1&lt;/span&gt;
&lt;span class="nv"&gt;MESSENGER_ACTIVE_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;v2 php bin/console app:dispatch &lt;span class="nt"&gt;--export&lt;/span&gt; &lt;span class="nt"&gt;--encrypt&lt;/span&gt;
&lt;span class="nv"&gt;MESSENGER_ACTIVE_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;v2 php bin/console messenger:consume async &lt;span class="nt"&gt;--limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Received ExportCustomerData: … encryption=xchacha20poly1305 key=v1 …
Received ExportCustomerData: … encryption=xchacha20poly1305 key=v2 …
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;active_key&lt;/code&gt; is omitted, the last key in the map is used.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. When it goes wrong: wrong key, tampered body
&lt;/h2&gt;

&lt;p&gt;This is the part to understand &lt;em&gt;before&lt;/em&gt; production. Decryption is authenticated, so a message encrypted with a key the consumer doesn't have, or modified in the broker, is refused rather than handed to your handler as garbage. Let's corrupt a stored body by hand:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console app:dispatch &lt;span class="nt"&gt;--export&lt;/span&gt; &lt;span class="nt"&gt;--encrypt&lt;/span&gt;
sqlite3 var/data.db &lt;span class="s2"&gt;"UPDATE messenger_messages SET body = substr(body,1,40) || 'X' || substr(body,42) WHERE delivered_at IS NULL;"&lt;/span&gt;
php bin/console messenger:consume async &lt;span class="nt"&gt;--limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;3
php bin/console messenger:failed:show
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Error thrown while handling message MessageDecodingFailedException. Sending for retry #1 using 93 ms delay. Error: "Decryption failed: authentication tag mismatch (wrong key or tampered payload)."
Error thrown while handling message MessageDecodingFailedException. Sending for retry #2 using 110 ms delay. …
Error thrown while handling message MessageDecodingFailedException. Removing from transport after 2 retries. …

There is 1 message pending in the failure transport.
  Id   Class                                                                   Failed at             Error
  4    Symfony\Component\Messenger\Exception\MessageDecodingFailedException   2026-11-01 15:12:53   Decryption failed: authentication tag mismatch (wrong key or tampered payload).
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So: the worker doesn't crash, the handler never runs, the retry strategy you configured applies and the message is parked on the failure transport with the original bytes intact. That last point matters for the "wrong key" case. Suppose a consumer was deployed without &lt;code&gt;v2&lt;/code&gt; and some &lt;code&gt;v2&lt;/code&gt; messages failed. Add the key and replay:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console messenger:failed:retry &lt;span class="nt"&gt;--force&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Handled export for cust-4711 (Nino Beridze, iban ends 4917)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The failed message is re-sent through the serializer untouched (it isn't compressed or encrypted a second time), decoded with the now-present key and handled normally.&lt;/p&gt;

&lt;p&gt;A note on Symfony 8.1. Messenger 8.1 changed how a transport serializer must report a message it cannot decode: it has to &lt;em&gt;return&lt;/em&gt; an envelope wrapping &lt;code&gt;MessageDecodingFailedException&lt;/code&gt; instead of throwing, so the stamps that count retries survive. Bundle v0.1.0 threw and on 8.1 that meant "retry #1" forever with an empty failure transport. The scenario above is how I found it; v0.1.1 returns the wrapped failure. The official custom-serializer example in the Symfony docs now shows the same pattern (&lt;a href="https://github.com/symfony/symfony-docs/pull/23459" rel="noopener noreferrer"&gt;symfony-docs#23459&lt;/a&gt;) and the throwing path itself is tracked in &lt;a href="https://github.com/symfony/symfony/issues/67791" rel="noopener noreferrer"&gt;symfony/symfony#67791&lt;/a&gt;, with a &lt;a href="https://github.com/mattleads/messenger-decode-throw-repro" rel="noopener noreferrer"&gt;one-file reproducer&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The errors you can see and what they mean:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Message&lt;/th&gt;
&lt;th&gt;Cause&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Decryption failed: authentication tag mismatch (wrong key or tampered payload).&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The key with that id exists on the consumer but is different from the producer's or the body was modified.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;No encryption key with id "v2" is configured. Known ids: v1.&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The consumer has not received the new key yet. Rotation step 1 was skipped.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Received an encrypted message but encryption is not configured on this consumer.&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;encryption.enabled&lt;/code&gt; is false on the consumer or it has no keys.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Message requested encryption but mattleads_messenger_compress.encryption is not enabled / has no keys.&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Producer side: you dispatched with &lt;code&gt;EncryptStamp&lt;/code&gt; before configuring a key.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;Unknown compression algorithm "zstd". Available: deflate, gzip.&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;ext-zstd&lt;/code&gt; is not loaded on this host.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  10. Testing
&lt;/h2&gt;

&lt;p&gt;Your handler tests do not change; they never saw the serializer. For an integration test that exercises the real round trip, the in-memory transport can run the serializer like a broker would:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/test/messenger.yaml&lt;/span&gt;
&lt;span class="na"&gt;framework&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;messenger&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;transports&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;async&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;dsn&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;in-memory://?serialize=true'&lt;/span&gt;
                &lt;span class="na"&gt;serializer&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;mattleads_messenger_compress.serializer&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dispatch with stamps, consume, assert on the &lt;code&gt;TransformedStamp&lt;/code&gt; of the received envelope. This is how the bundle's own functional tests work.&lt;/p&gt;

&lt;h2&gt;
  
  
  11. Production checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Keys come from a secrets store&lt;/strong&gt;, never from the repository. &lt;code&gt;secrets:set&lt;/code&gt;, Vault, SSM, whatever you already use.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consumers before producers.&lt;/strong&gt; Install the bundle on consumers first; add keys to consumers first; only then stamp or switch &lt;code&gt;active_key&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prefer a threshold over stamps.&lt;/strong&gt; &lt;code&gt;auto_threshold: 4096&lt;/code&gt; catches the message that grows six months from now. Reserve explicit stamps for &lt;code&gt;zstd&lt;/code&gt;/level tuning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Encrypt by transport if you can.&lt;/strong&gt; A dedicated &lt;code&gt;sensitive&lt;/code&gt; transport with &lt;code&gt;encryption.always: true&lt;/code&gt; is easier to audit than stamps scattered through services.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Headers are plain text.&lt;/strong&gt; Message class, stamp contents, key id are all visible. Keep secrets in the body.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep the failure transport in mind during rotation.&lt;/strong&gt; Messages parked there may still be on the old key; do not remove it until the failure transport is empty or replayed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Watch &lt;code&gt;ratio()&lt;/code&gt;.&lt;/strong&gt; If a message class is consistently above 100 %, it's small and doesn't need compression; if it is consistently at 100 %, the data is already compressed (images, archives) and &lt;code&gt;PlainStamp&lt;/code&gt; saves CPU.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Where to go from here
&lt;/h2&gt;

&lt;p&gt;The bundle is on &lt;a href="https://packagist.org/packages/mattleads/messenger-compress-bundle" rel="noopener noreferrer"&gt;Packagist&lt;/a&gt; and &lt;a href="https://github.com/mattleads/messenger-compress-bundle" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; (MIT, Symfony 6.4–8.x, PHP 8.2+). The runnable walkthrough with the inspect command, the listener and the tamper scenario is at &lt;a href="https://github.com/mattleads/messenger-compress-demo" rel="noopener noreferrer"&gt;github.com/mattleads/messenger-compress-demo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Custom compressors (Brotli, LZ4) plug in by implementing &lt;code&gt;CompressorInterface&lt;/code&gt; and are picked up by the &lt;code&gt;mattleads_messenger_compress.compressor&lt;/code&gt; tag. Custom encryptors implement &lt;code&gt;EncryptorInterface&lt;/code&gt;. If you run this against SQS, Redis or AMQP at volume, open an issue with the ratios you see and anything that surprised you. That's what the issue tracker is for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project's progress on GitHub: &lt;a href="https://github.com/mattleads/messenger-compress-bundle" rel="noopener noreferrer"&gt;https://github.com/mattleads/messenger-compress-bundle&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: &lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;X (Twitter): &lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Telegram: &lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>security</category>
      <category>programming</category>
    </item>
    <item>
      <title>Mastering Symfony Security, Passports and Custom Authenticators</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Fri, 19 Jun 2026 16:20:42 +0000</pubDate>
      <link>https://dev.to/mattleads/mastering-symfony-security-passports-and-custom-authenticators-36j5</link>
      <guid>https://dev.to/mattleads/mastering-symfony-security-passports-and-custom-authenticators-36j5</guid>
      <description>&lt;p&gt;Security is the cornerstone of any modern web application, but historically, implementing robust authentication and authorization mechanisms has been plagued by accidental complexity, rigid abstractions and boilerplate code. In the PHP ecosystem, Symfony has long been the reference framework for high-performance, enterprise-grade applications. However, prior to Symfony 5.3 and continuing into the refined releases of Symfony 7.4 and 8.1, the framework’s security component was notoriously complex.&lt;/p&gt;

&lt;p&gt;Developers had to contend with legacy abstractions such as Guard, multiple disparate interfaces (GuardAuthenticatorInterface, SimplePreAuthenticatorInterface) and a multi-layered, opaque token-rendering lifecycle that made custom authentications a daunting task. The system was powerful but brittle, heavily relying on concrete classes, complex inheritance and a lack of granular lifecycle hooks.&lt;/p&gt;

&lt;p&gt;With the introduction of the Modern Security System — which became the default and was subsequently polished in Symfony 7 and 8 — Symfony completed a paradigm shift. The framework deprecated the legacy Guard component entirely and replaced it with a highly cohesive, unified, event-driven security architecture built around two foundational primitives: &lt;strong&gt;Authenticators and Passports&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This modern system breaks authentication down into distinct, logical phases:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Request Interception:&lt;/strong&gt; Deciding whether an authenticator should handle a request.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Passport Creation:&lt;/strong&gt; Extracting user identity credentials and packaging them into an object representation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Passport Validation:&lt;/strong&gt; Processing security checks (e.g., matching password hashes, validating CSRF states, checking user account status) via modular, reusable "Badges".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Outcome Resolution:&lt;/strong&gt; Directing the next steps of the HTTP pipeline based on success or failure.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By decoupling the validation checks from the user loading process, Symfony's modern security component operates much like a Lego system: developers can mix and match badges, authenticators and providers to support any imaginable authentication flow — from simple session-based forms to stateless API keys, cryptographic JWTs and federated OAuth2 portals — without writing a single line of redundant code.&lt;/p&gt;

&lt;p&gt;This article provides an exhaustive, production-ready guide to mastering this modern paradigm. We will dissect the inner workings of the security pipeline, explore the lifecycle of Passports and Badges, write a custom, stateless API Key authenticator and detail advanced validation, testing and security strategies.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Modern Security Pipeline
&lt;/h2&gt;

&lt;p&gt;To write secure, idiomatic Symfony code, we must first map out the precise sequence of events that occurs from the moment an HTTP request hits the PHP process to the moment the controller receives control. Symfony organizes this execution flow into a highly structured, chronological pipeline.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming Request
       │
       ▼
┌─────────────────────────────────────────┐
│           Firewall Matching             │ (security.yaml rules)
└────────────────────┬────────────────────┘
                     │ Match
                     ▼
┌─────────────────────────────────────────┐
│         Authenticator Selection         │ (supports() loop)
└────────────────────┬────────────────────┘
                     │ Handled
                     ▼
┌─────────────────────────────────────────┐
│           Passport Creation             │ (authenticate())
└────────────────────┬────────────────────┘
                     │ Passport Created
                     ▼
┌─────────────────────────────────────────┐
│     Authentication Event Dispatch       │ (CheckPassportEvent)
└────────────────────┬────────────────────┘
                     │ Badges Resolved
                     ▼
┌─────────────────────────────────────────┐
│           User Resolution               │ (UserProvider / Badges)
└────────────────────┬────────────────────┘
                     │ Validated
                     ▼
┌─────────────────────────────────────────┐
│      Success or Failure Resolution      │ (onAuthenticationSuccess / 
└─────────────────────────────────────────┘  Failure)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Firewall Matching
&lt;/h3&gt;

&lt;p&gt;The entry point of the pipeline is governed by the &lt;strong&gt;security.yaml&lt;/strong&gt; configuration. When a request enters the application, the &lt;strong&gt;FirewallMap&lt;/strong&gt; iterates through all configured firewalls in chronological order. A firewall is matched using a regular expression defined by the &lt;strong&gt;pattern&lt;/strong&gt; key (e.g. &lt;code&gt;^/api/&lt;/code&gt;).&lt;br&gt;
If a match is found, the security system activates the firewall's corresponding request listener. If the firewall is marked with &lt;strong&gt;security: false&lt;/strong&gt; (such as for assets or profiler paths), the security interceptor is bypassed completely.&lt;/p&gt;
&lt;h3&gt;
  
  
  Authenticator Selection (The &lt;strong&gt;supports()&lt;/strong&gt; Loop)
&lt;/h3&gt;

&lt;p&gt;Once a firewall is selected, it gathers all registered authenticators associated with it. The firewall loops through these authenticators and executes their &lt;strong&gt;supports(Request $request)&lt;/strong&gt; method. &lt;br&gt;
This method acts as a high-speed HTTP guard rail. It must return &lt;strong&gt;true&lt;/strong&gt; if the authenticator knows how to extract credentials from the given request and &lt;strong&gt;false&lt;/strong&gt; (or &lt;strong&gt;null&lt;/strong&gt;) otherwise. Because this loop runs on every single request matched by the firewall, the &lt;strong&gt;supports&lt;/strong&gt; method must remain incredibly lightweight and performant. It should only inspect request attributes, headers, query parameters or cookies—never execute database queries or performance-intensive operations.&lt;/p&gt;
&lt;h3&gt;
  
  
  Passport Creation (The &lt;strong&gt;authenticate()&lt;/strong&gt; Phase)
&lt;/h3&gt;

&lt;p&gt;If an authenticator's &lt;strong&gt;supports()&lt;/strong&gt; method returns &lt;strong&gt;true&lt;/strong&gt;, the security system halts the selection loop and delegates responsibility to that authenticator's &lt;strong&gt;authenticate(Request $request)&lt;/strong&gt; method. &lt;br&gt;
The sole responsibility of &lt;strong&gt;authenticate&lt;/strong&gt; is to extract authentication tokens or credentials from the request and package them into a &lt;strong&gt;Passport&lt;/strong&gt; object. If the request is missing essential criteria (e.g. an empty token header), the authenticator should throw an &lt;strong&gt;AuthenticationException&lt;/strong&gt;. This terminates the process and routes execution to the failure handler.&lt;/p&gt;
&lt;h3&gt;
  
  
  Passport Validation &amp;amp; Events
&lt;/h3&gt;

&lt;p&gt;Once a Passport is returned Symfony's security manager takes over. It fires a &lt;strong&gt;CheckPassportEvent&lt;/strong&gt; in the event dispatcher. A series of system listeners hook into this event to validate the badges attached to the Passport:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The user account status is checked (e.g. verifying if the user is enabled, locked or expired).&lt;/li&gt;
&lt;li&gt;Credentials are validated (e.g. checking password hashes).&lt;/li&gt;
&lt;li&gt;Custom security assertions are processed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If any listener throws an &lt;strong&gt;AuthenticationException&lt;/strong&gt; during this event-driven phase, validation is aborted and the authentication fails.&lt;/p&gt;
&lt;h3&gt;
  
  
  Success or Failure Resolution
&lt;/h3&gt;

&lt;p&gt;After validation concludes the pipeline branches depending on the outcome:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;On Failure&lt;/strong&gt;: The authenticator's &lt;strong&gt;onAuthenticationFailure(Request $request, AuthenticationException $exception)&lt;/strong&gt; method is triggered. It is responsible for returning a &lt;strong&gt;Response&lt;/strong&gt; (such as a 401 JSON object or a redirected login form with error flash messages).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;On Success&lt;/strong&gt;: The authenticator's &lt;strong&gt;onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName)&lt;/strong&gt; method is called. In a stateful web application, it typically returns a &lt;strong&gt;RedirectResponse&lt;/strong&gt; to a dashboard. In a stateless API, it returns &lt;strong&gt;null&lt;/strong&gt;, telling Symfony to bypass further security handling and allow the request to proceed seamlessly to the matched controller.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Deep Dive into Passports and Badges
&lt;/h2&gt;

&lt;p&gt;The genius of Symfony's modern security architecture lies in its separation of concerns via &lt;strong&gt;Passports&lt;/strong&gt; and &lt;strong&gt;Badges&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;Passport&lt;/strong&gt; is a concrete representation of an authentication attempt. It is a data transfer object (DTO) that holds the user's identity and any security credentials submitted with the request.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;Badge&lt;/strong&gt; is a modular, self-contained metadata container attached to a Passport. Badges declare "assertions" or "requirements" that must be validated during the authentication process. Instead of write-blocking authentication methods an authenticator simply attaches various Badges to the Passport, leaving it to specialized services to resolve them.&lt;/p&gt;

&lt;p&gt;Symfony ships with several core Passports and Badges:&lt;/p&gt;
&lt;h3&gt;
  
  
  Core Passports
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Passport&lt;/strong&gt;: The generic implementation. It requires a &lt;code&gt;UserBadge&lt;/code&gt; (to locate the user) and a &lt;strong&gt;CredentialsBadge&lt;/strong&gt; (to verify the identity proof, such as a password).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SelfValidatingPassport&lt;/strong&gt;: A highly useful specialized subclass. It only requires a &lt;strong&gt;UserBadge&lt;/strong&gt;. It is used in scenarios where the credentials are self-validating, meaning that the validation of the token itself is sufficient proof of identity (e.g. API Keys, JWTs, OAuth2 access tokens).&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Core Badges
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;UserBadge&lt;/strong&gt;: The absolute minimum requirement for any Passport. It accepts a &lt;strong&gt;userIdentifier&lt;/strong&gt; (such as an email, username or API token) and an optional loader callback. The loader callback is a callable that queries the database or external user provider to return the matching &lt;strong&gt;UserInterface&lt;/strong&gt; object. If no callback is specified, Symfony falls back on the default configured &lt;strong&gt;UserProvider&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;PasswordCredentials&lt;/strong&gt;: Bundles a plaintext password. Symfony automatically grabs this badge and passes it to the password hasher service to verify it against the hashed password stored on the user entity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CsrfTokenBadge&lt;/strong&gt;: Holds a CSRF token. Symfony's security listener automatically validates the token against the CSRF token manager before allowing authentication to succeed, keeping your forms safe from CSRF attacks.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;RememberMeBadge&lt;/strong&gt;: Tells Symfony to generate a remember-me cookie on successful authentication, enabling automated persistent logins across sessions.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  The Extensibility of Badges
&lt;/h3&gt;

&lt;p&gt;Because Badges are simply objects attached to the Passport, you can create custom Badges to represent any business constraint. For example, if your enterprise SaaS application requires Multi-Factor Authentication (MFA), you can attach a custom &lt;strong&gt;MfaPassedBadge&lt;/strong&gt; to your Passport. A security event listener can then listen to &lt;strong&gt;CheckPassportEvent&lt;/strong&gt;, inspect if the &lt;strong&gt;MfaPassedBadge&lt;/strong&gt; is present and valid and reject the authentication if the badge is missing. This extensibility ensures your core authenticator logic remains simple and reusable.&lt;/p&gt;
&lt;h3&gt;
  
  
  Deep Code Walkthrough
&lt;/h3&gt;

&lt;p&gt;Let us carefully analyze each method of our &lt;strong&gt;ApiKeyAuthenticator&lt;/strong&gt; to understand the underlying mechanics:&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;supports()&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The framework executes this method first. By using &lt;strong&gt;$request-&amp;gt;headers-&amp;gt;has('X-API-KEY')&lt;/strong&gt;, we cleanly scope the authenticator. If an external client requests &lt;strong&gt;/api/test&lt;/strong&gt; but uses a standard browser session or JWT, this authenticator quietly steps aside (&lt;strong&gt;returns false&lt;/strong&gt;), allowing other authenticators (like the JWT Authenticator) to evaluate the request instead.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;authenticate()&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;If selected, we extract the header. We validate that the token is not empty. If it is empty, throwing &lt;strong&gt;CustomUserMessageAuthenticationException&lt;/strong&gt; immediately halts execution. &lt;br&gt;
If it is present, we instantiate &lt;strong&gt;SelfValidatingPassport&lt;/strong&gt; and wrap our logic in a &lt;strong&gt;UserBadge&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;The closure passed to the &lt;strong&gt;UserBadge&lt;/strong&gt; is &lt;strong&gt;lazy-evaluated&lt;/strong&gt;. Symfony does not execute this database query until the validation phase of the pipeline. If a previous event listener rejects the Passport before user validation (e.g. due to a failed IP blacklist check), the database lookup is never executed, saving precious database CPU cycles.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;onAuthenticationSuccess()&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;In typical session login forms, on success, you redirect users to &lt;strong&gt;/dashboard&lt;/strong&gt;. However, for APIs, redirection is a massive anti-pattern. By returning &lt;strong&gt;null&lt;/strong&gt;, we instruct Symfony's Firewall listener to let the request continue down the pipeline to the matched Controller.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;onAuthenticationFailure()&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;If any step of the &lt;strong&gt;authenticate()&lt;/strong&gt; or Badge verification phase throws an exception, this handler captures it. Rather than outputting standard HTML stack traces (which leaks database or path details to potential attackers), we capture the exception's message key, translate it safely using &lt;strong&gt;strtr&lt;/strong&gt; and output a clean, unified JSON structure with a HTTP 401 status.&lt;/p&gt;
&lt;h2&gt;
  
  
  Testing &amp;amp; Debugging Custom Authenticators
&lt;/h2&gt;

&lt;p&gt;Writing code is only half the battle; verifying that your authentication layer works reliably under extreme edge cases is mandatory for ensuring long-term technical integrity.&lt;/p&gt;
&lt;h3&gt;
  
  
  Debugging Routes and Security via CLI
&lt;/h3&gt;

&lt;p&gt;Symfony includes a suite of command-line utilities that allow developers to inspect how security rules match against URLs without running a web server.&lt;/p&gt;

&lt;p&gt;To check which firewall and authenticator will match a specific route, run the &lt;strong&gt;router:match&lt;/strong&gt; debug utility:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console router:match /api/test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This output tells you exactly which controller and route matches your path.&lt;/p&gt;

&lt;p&gt;To inspect your entire security configuration, including registered providers, hashers and firewalls, run the &lt;strong&gt;debug:security&lt;/strong&gt; command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php bin/console debug:security
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is extremely valuable for verifying that your custom authenticator has been correctly registered under the &lt;strong&gt;custom_authenticators&lt;/strong&gt; key of your target firewall.&lt;/p&gt;

&lt;h3&gt;
  
  
  Writing Automated Integration Tests
&lt;/h3&gt;

&lt;p&gt;To ensure our custom authenticator operates correctly under both successful and failing states, we can write automated integration tests using Symfony's &lt;strong&gt;WebTestCase&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;
&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Tests\Security&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Entity\User&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\ORM\EntityManagerInterface&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Bundle\FrameworkBundle\Test\WebTestCase&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApiKeyAuthenticatorTest&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;WebTestCase&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;EntityManagerInterface&lt;/span&gt; &lt;span class="nv"&gt;$entityManager&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;setUp&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;setUp&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="c1"&gt;// Boot the kernel and retrieve the entity manager&lt;/span&gt;
        &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;bootKernel&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;getContainer&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EntityManagerInterface&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testRequestWithoutHeaderFails&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'GET'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/api/test'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertResponseStatusCodeSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;401&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertJson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

        &lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;json_decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertArrayHasKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'message'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'JWT Token not found'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'message'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testRequestWithInvalidTokenFails&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'GET'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/api/test'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'HTTP_X-API-KEY'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'invalid_token_123'&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertResponseStatusCodeSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;401&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertJson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

        &lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;json_decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Invalid API Token'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'message'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testRequestWithValidTokenSucceeds&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="nv"&gt;$user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setEmail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'api_test_user@example.com'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setPassword&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'any_hashed_password'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setApiToken&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'valid_test_token_xyz'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;persist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'GET'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/api/test'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'HTTP_X-API-KEY'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'valid_test_token_xyz'&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertResponseStatusCodeSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertJson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

        &lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;json_decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$client&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getContent&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'success'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'status'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertSame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'api_test_user@example.com'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'user'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;

        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why Automated Verification is Mandatory
&lt;/h3&gt;

&lt;p&gt;Manual browser testing is slow, error-prone and cannot easily be automated in CI/CD pipelines. By writing these integration tests, we prove that:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The routing matches correctly.&lt;/li&gt;
&lt;li&gt;The firewall is correctly enforcing security.&lt;/li&gt;
&lt;li&gt;The database matches correctly under SQLite.&lt;/li&gt;
&lt;li&gt;Edge cases (invalid keys, missing keys and valid keys) behave exactly as specified.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Best Practices for API Security
&lt;/h2&gt;

&lt;p&gt;When designing custom security components for production applications, several strict security rules must be enforced to protect your users and infrastructure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use &lt;strong&gt;stateless: true&lt;/strong&gt; Aggressively
&lt;/h3&gt;

&lt;p&gt;For any pure API firewall (e.g. JWT endpoints, API keys, OAuth endpoints), always specify &lt;strong&gt;stateless: true&lt;/strong&gt; in your &lt;strong&gt;security.yaml&lt;/strong&gt;. &lt;br&gt;
By default, Symfony starts a PHP session and sends a &lt;strong&gt;PHPSESSID&lt;/strong&gt; cookie to the client on successful authentication. While useful for HTML browsers, sessions are a major architectural bottleneck for REST APIs. They disable scaling (since sessions require shared Redis stores or sticky load balancing) and expose your clients to &lt;strong&gt;CSRF (Cross-Site Request Forgery)&lt;/strong&gt; attacks.&lt;br&gt;
Setting &lt;strong&gt;stateless: true&lt;/strong&gt; forces Symfony to completely bypass session generation, cookie storage and session garbage collection, guaranteeing your API is 100% immune to CSRF and can scale horizontally infinitely.&lt;/p&gt;

&lt;h3&gt;
  
  
  Protect Exception Traces
&lt;/h3&gt;

&lt;p&gt;During development, Symfony's error handler intercepts exceptions and displays beautiful, detailed HTML traces. However, in production, showing database connection strings or class namespace failures inside your JSON responses is a massive security risk.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Always&lt;/strong&gt; throw &lt;strong&gt;CustomUserMessageAuthenticationException&lt;/strong&gt; inside your authenticators. It is designed to safely carry user-friendly error messages (e.g. "Invalid API Token") directly to the HTTP response without exposing internal implementation details.&lt;/li&gt;
&lt;li&gt;Ensure &lt;strong&gt;APP_ENV=prod&lt;/strong&gt; is set in production to instantly disable debug logs and stack trace rendering in HTTP outputs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Enforce SSL/TLS
&lt;/h3&gt;

&lt;p&gt;API keys and JWT tokens are sent in plaintext HTTP headers (&lt;strong&gt;X-API-KEY&lt;/strong&gt;, &lt;strong&gt;Authorization: Bearer&lt;/strong&gt;). If a client requests your API over an unencrypted &lt;strong&gt;http://&lt;/strong&gt; connection, anyone on the network can sniff the packets and steal the token, completely compromising the account.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Configure your web server (Nginx, Apache) to force redirect all traffic to &lt;strong&gt;https://&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;In &lt;strong&gt;security.yaml&lt;/strong&gt;, enforce HTTPS matching using the &lt;strong&gt;requires_channel&lt;/strong&gt; parameter:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;  &lt;span class="na"&gt;access_control&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
      &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;^/api&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;roles&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;ROLE_USER&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;requires_channel&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;https&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Token Salting &amp;amp; Hashing
&lt;/h3&gt;

&lt;p&gt;Storing raw API keys in plaintext inside your database is a severe security vulnerability. If an attacker breaches your database via a SQL injection or a leaked backup, they instantly gain access to every single client account.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Actionable Advice&lt;/strong&gt;: Treat API tokens exactly like passwords. When creating an API key, generate a cryptographically secure random string, output it to the user &lt;em&gt;once&lt;/em&gt; but store only the &lt;strong&gt;SHA-256 hash&lt;/strong&gt; of that key in your database.&lt;/li&gt;
&lt;li&gt;In your custom authenticator, when extracting the key from the header, hash it before running your query:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;  &lt;span class="nv"&gt;$hashedToken&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'sha256'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$apiToken&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nv"&gt;$user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;userRepository&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOneBy&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="s1"&gt;'apiToken'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$hashedToken&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This guarantees that even if your database is entirely breached, no API keys are compromised.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Symfony 8.1 and 7.4 have transformed the way we think about web and API security. By transitioning from inheritance-heavy legacy controllers and Guard classes to a highly cohesive, event-driven architecture based on &lt;strong&gt;Passports&lt;/strong&gt; and &lt;strong&gt;Badges&lt;/strong&gt;, the framework empowers developers to write code that is clean, secure, testable and highly maintainable.&lt;/p&gt;

&lt;p&gt;By understanding the request lifecycle, decoupling identity provisioning from credential checks and following strict security best practices like token hashing and stateless firewalls, you can confidently build enterprise-ready authentication layers capable of safeguarding your application against modern threats. &lt;/p&gt;

&lt;h3&gt;
  
  
  Next Up - Scaling to Enterprise Security
&lt;/h3&gt;

&lt;p&gt;While custom headers and stateless API keys are perfect for machine-to-machine integration, a complete production ecosystem demands scalable session persistence and frictionless onboarding. &lt;/p&gt;

&lt;p&gt;In our next article, &lt;strong&gt;"Mastering Enterprise Authentication: JWT Customization and OAuth2 Pipelines in Symfony"&lt;/strong&gt;, we will take this application to the next level:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We will implement cryptographically signed &lt;strong&gt;JSON Web Tokens (JWT)&lt;/strong&gt; with custom payload data.&lt;/li&gt;
&lt;li&gt;We will integrate &lt;strong&gt;JWT Refresh Tokens&lt;/strong&gt; to build seamless session persistence with robust &lt;strong&gt;Refresh Token Rotation (RTR)&lt;/strong&gt; to prevent replay attacks.&lt;/li&gt;
&lt;li&gt;We will wire up a full &lt;strong&gt;Google OAuth2 Social Login&lt;/strong&gt; pipeline, demonstrating how to keep our authentication DRY by decoupling registration logic into a specialized reusable &lt;strong&gt;User Provisioning Service&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Source Code: Please DM me if you need access to the project's GitHub repository.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: [&lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;X (Twitter): [&lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;Telegram: [&lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;GitHub: [&lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;]&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>php</category>
      <category>security</category>
      <category>oauth</category>
    </item>
    <item>
      <title>The SOC 2 Blueprint: Beyond RBAC with AppLevel Infrastructure Isolation &amp; Key Sharding. Part #2</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Thu, 04 Jun 2026 14:53:52 +0000</pubDate>
      <link>https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-infrastructure-isolation-key-sharding-part-2-38c4</link>
      <guid>https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-infrastructure-isolation-key-sharding-part-2-38c4</guid>
      <description>&lt;p&gt;In &lt;a href="https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-3fch"&gt;Part 1&lt;/a&gt;, we implemented Application-Level Envelope Encryption. Our documents are now protected by per-record AES keys, wrapped in user-specific RSA envelopes. But a secure application is more than just secure data — it must have a secure infrastructure.&lt;/p&gt;

&lt;p&gt;Under SOC 2, two critical principles often challenge developers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Log Integrity (Audit Trail):&lt;/strong&gt; You must prove that security logs are immutable and cannot be tampered with, even if the primary database is compromised.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Key Lifecycle Management:&lt;/strong&gt; You must prove that your encryption keys are rotated and that the compromise of a single key does not result in the compromise of the entire system.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this deep dive, we will implement &lt;strong&gt;Audit Trail Isolation&lt;/strong&gt; using the &lt;strong&gt;Outbox Pattern&lt;/strong&gt; and a &lt;strong&gt;Distributed Key Management Service (KMS)&lt;/strong&gt; with &lt;strong&gt;Master Key Sharding&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Physical Isolation - The Three-Database Architecture
&lt;/h2&gt;

&lt;p&gt;To fulfill SOC 2 requirements, we move away from a monolithic data store. We will configure three physically and logically separate SQLite databases:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Primary DB (data.db):&lt;/strong&gt; Stores users, encrypted documents and envelopes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Audit DB (audit.db):&lt;/strong&gt; Stores immutable log entries. It should ideally be on a separate mount point with &lt;strong&gt;“Append-Only”&lt;/strong&gt; permissions in production.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keys DB (keys.db):&lt;/strong&gt; Stores the encrypted pool of Master Keys.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Configuring Multiple Entity Managers
&lt;/h3&gt;

&lt;p&gt;In Symfony’s &lt;strong&gt;doctrine.yaml&lt;/strong&gt;, we define three connections and three entity managers. This allows us to inject a specific manager (e.g., @doctrine.orm.audit_entity_manager) into our services, ensuring they can only “see” their designated database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# config/packages/doctrine.yaml&lt;/span&gt;
&lt;span class="na"&gt;doctrine&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;dbal&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;connections&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;url&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(resolve:DATABASE_URL)%'&lt;/span&gt;
            &lt;span class="na"&gt;audit&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;url&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(resolve:AUDIT_DATABASE_URL)%'&lt;/span&gt;
            &lt;span class="na"&gt;keys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;url&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%env(resolve:KEYS_DATABASE_URL)%'&lt;/span&gt;

    &lt;span class="na"&gt;orm&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;entity_managers&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;connection&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;default&lt;/span&gt;
                &lt;span class="na"&gt;mappings&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                    &lt;span class="na"&gt;App&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;type&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;attribute&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;dir&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%kernel.project_dir%/src/Entity'&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;prefix&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;App\Entity'&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
            &lt;span class="na"&gt;audit&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;connection&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;audit&lt;/span&gt;
                &lt;span class="na"&gt;mappings&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                    &lt;span class="na"&gt;gedmo_loggable&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;type&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;attribute&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;dir&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Loggable/Entity'&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;prefix&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Gedmo\Loggable\Entity'&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
            &lt;span class="na"&gt;keys&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                &lt;span class="na"&gt;connection&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;keys&lt;/span&gt;
                &lt;span class="na"&gt;mappings&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
                    &lt;span class="na"&gt;KeyStore&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;type&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;attribute&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;dir&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;%kernel.project_dir%/src/Entity/KeyStore'&lt;/span&gt;&lt;span class="pi"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;prefix&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'&lt;/span&gt;&lt;span class="s"&gt;App\Entity\KeyStore'&lt;/span&gt; &lt;span class="pi"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The Immutable Audit Trail - Outbox Pattern
&lt;/h2&gt;

&lt;p&gt;A common mistake is to write logs to a separate database synchronously. This creates two problems:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Performance:&lt;/strong&gt; Every document save now waits for two database writes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Atomicity:&lt;/strong&gt; If the primary DB saves but the Audit DB fails, you have an unlogged action — a major SOC 2 violation.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Symfony Messenger + Outbox Pattern
&lt;/h3&gt;

&lt;p&gt;The Outbox Pattern ensures that business data and the intent to log are saved in the same atomic SQL transaction.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Capture:&lt;/strong&gt; During the primary Entity Manager’s onFlush event, we identify new LogEntry entities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queue:&lt;/strong&gt; We dispatch an AuditLogMessage to the Symfony Messenger bus.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Outbox:&lt;/strong&gt; We use the doctrine://default transport (or any other). This saves the message into a messenger_messages table in the Primary DB.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Process:&lt;/strong&gt; A background worker consumes the message and uses the Audit Entity Manager to move the data to audit.db.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This architecture provides Asynchronous Persistence with Synchronous Reliability.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/EventListener/AuditLogMoverListener.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;onFlush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;OnFlushEventArgs&lt;/span&gt; &lt;span class="nv"&gt;$args&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$uow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$args&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getObjectManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getUnitOfWork&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$uow&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getScheduledEntityInsertions&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$entity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$entity&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;LogEntry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Track logs to be moved to the audit database&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;logsToMove&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;attach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$entity&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;postFlush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;PostFlushEventArgs&lt;/span&gt; &lt;span class="nv"&gt;$args&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;logsToMove&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$log&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Dispatch to Messenger for asynchronous processing&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;messageBus&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AuditLogMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="nv"&gt;$log&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getData&lt;/span&gt;&lt;span class="p"&gt;()));&lt;/span&gt;

        &lt;span class="c1"&gt;// Remove from primary DB to keep it clean&lt;/span&gt;
        &lt;span class="nv"&gt;$args&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getObjectManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$log&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nv"&gt;$args&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getObjectManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Distributed Key Management (KMS)
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;“Server Master Key”&lt;/strong&gt; used in &lt;a href="https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-3fch"&gt;Part 1&lt;/a&gt; is a liability. If it’s stored in a .env file and that file is leaked, your entire backup recovery system is compromised.&lt;/p&gt;

&lt;p&gt;The “Dual Lock” Root Key Strategy&lt;br&gt;
We store our &lt;strong&gt;Master Keys&lt;/strong&gt; in the &lt;strong&gt;keys.db&lt;/strong&gt;. However, we never store them in plain text. Every Master Key is encrypted using a &lt;strong&gt;ROOT_KEY&lt;/strong&gt; stored in the server’s environment.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To access a document’s DEK, you need the Keys DB AND the Environment ROOT_KEY.&lt;/li&gt;
&lt;li&gt;This fulfills the SOC 2 requirement for &lt;strong&gt;“Separation of Duties”&lt;/strong&gt; and &lt;strong&gt;“Layered Defense”&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Master Key Sharding - Reducing the Blast Radius
&lt;/h3&gt;

&lt;p&gt;If you have 1,000,000 documents encrypted with one Master Key, the value of that key to an attacker is immense. Master Key Sharding distributes this risk.&lt;/p&gt;

&lt;p&gt;We maintain a pool of 10 active Master Keys. When creating a document, we pick one deterministically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Security/MasterKeyStore.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getActiveKeyData&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$activeKeys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getActiveKeyEntities&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="c1"&gt;// Selection Algorithm: Pick one deterministically based on current millisecond&lt;/span&gt;
    &lt;span class="nv"&gt;$index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;microtime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$activeKeys&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nv"&gt;$selectedKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$activeKeys&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$index&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s1"&gt;'id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$selectedKey&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getId&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
        &lt;span class="s1"&gt;'key'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decryptWithRootKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$selectedKey&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEncryptedKey&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By using millisecond-precision timestamps, we ensure a near-perfect distribution.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Blast Radius Math
&lt;/h3&gt;

&lt;p&gt;In a standard system, a compromised Master Key = &lt;strong&gt;100% data loss&lt;/strong&gt;.&lt;br&gt;
In our sharded system, a compromised Master Key = &lt;strong&gt;~10% data loss&lt;/strong&gt;.&lt;br&gt;
This 90% reduction in risk is exactly what SOC 2 auditors look for in high-maturity organizations.&lt;/p&gt;
&lt;h2&gt;
  
  
  Key Lifecycle &amp;amp; Rotation
&lt;/h2&gt;

&lt;p&gt;Master Keys are not eternal. They have a lifecycle defined by &lt;strong&gt;activatedAt&lt;/strong&gt; and &lt;strong&gt;deactivatedAt&lt;/strong&gt; timestamps.&lt;/p&gt;
&lt;h3&gt;
  
  
  Automatic Selection for Encryption
&lt;/h3&gt;

&lt;p&gt;When encryptDekForServer is called, the MasterKeyStore always provides a key from the currently active pool.&lt;/p&gt;
&lt;h3&gt;
  
  
  Versioned Decryption
&lt;/h3&gt;

&lt;p&gt;Every encrypted payload in our system is prefixed with its &lt;strong&gt;Key ID: keyId:initializationVector:authenticationTag:cipherText&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When an administrator or a backup process needs to decrypt a document from three years ago, the system sees Key ID: 14. It fetches Key #14 from the historical archive in keys.db, unwraps it with the ROOT_KEY and restores the document. This makes rotation completely transparent to the application logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Security/EnvelopeCryptoService.php&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;decryptDekFromServer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$serverEncryptedDek&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$keyId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$encryptedPayload&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;explode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;':'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$serverEncryptedDek&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// Fetch the specific key used for THIS record&lt;/span&gt;
    &lt;span class="nv"&gt;$masterKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;masterKeyStore&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getKeyById&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$keyId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;decryptContent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$encryptedPayload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$masterKey&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Security Performance -The Stateful Listener
&lt;/h2&gt;

&lt;p&gt;Moving logs and managing sharded keys can be computationally expensive. In our &lt;strong&gt;AuditLogMoverListener&lt;/strong&gt;, we use an optimized Stateful Tracking pattern:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We use SplObjectStorage to track entities within a single request.&lt;/li&gt;
&lt;li&gt;We only process the exact logs created in that request.&lt;/li&gt;
&lt;li&gt;We avoid findAll() or heavy database scans, ensuring our security layer adds only negligible millisecond overhead to the user experience.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Final Architecture Summary
&lt;/h2&gt;

&lt;p&gt;We have built a “Fortress” application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Record-Level Privacy:&lt;/strong&gt; Every document has a unique AES-256 key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Zero Trust Logs:&lt;/strong&gt; Audit trails are physically isolated and moved asynchronously via the Outbox pattern.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sharded Authority:&lt;/strong&gt; Master Keys are pooled and distributed, reducing the impact of any single failure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dual-Lock Protection:&lt;/strong&gt; The KMS database is itself encrypted by an environment-level Root Key.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Closing Thoughts
&lt;/h2&gt;

&lt;p&gt;SOC 2 compliance is often viewed as a “check-the-box” exercise in documentation. But we have the power to make it a &lt;strong&gt;technical reality&lt;/strong&gt;. By using the patterns described in these two articles — Envelope Encryption, &lt;strong&gt;Outbox Isolation&lt;/strong&gt; and &lt;strong&gt;Key Sharding&lt;/strong&gt; — you aren’t just passing an audit. You are building a system that is fundamentally resilient to the most common failure modes in modern software.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project’s progress on GitHub: [&lt;a href="https://github.com/mattleads/SOC2Database" rel="noopener noreferrer"&gt;https://github.com/mattleads/SOC2Database&lt;/a&gt;]&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: [&lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;X (Twitter): [&lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;Telegram: [&lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;GitHub: [&lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;]&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>security</category>
      <category>php</category>
      <category>architecture</category>
    </item>
    <item>
      <title>The SOC 2 Blueprint: Beyond RBAC with AppLevel Encryption and Audit Isolation. Part #1</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Wed, 27 May 2026 11:56:07 +0000</pubDate>
      <link>https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-3fch</link>
      <guid>https://dev.to/mattleads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-3fch</guid>
      <description>&lt;p&gt;In the modern landscape of SaaS and enterprise software, SOC 2 (System and Organization Controls 2) is no longer a “nice to have” — it is a foundational requirement for doing business. At its core, SOC 2 asks a simple but difficult question: &lt;strong&gt;How can you prove that only authorized users accessed specific data and how do you protect that data if your perimeter fails?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most developers believe that standard &lt;strong&gt;Role-Based Access Control (RBAC)&lt;/strong&gt; and database-level encryption-at-rest (like AWS RDS encryption) are enough. They aren’t. Standard RDS encryption protects your data if someone physically steals a hard drive from a data center but it does nothing if an attacker gains access to your running application or your primary database credentials.&lt;/p&gt;

&lt;p&gt;In this exhaustive guide we will move beyond standard security and implement Application-Level Envelope Encryption. By the end of this article you will understand how to build a Symfony application where &lt;strong&gt;data is cryptographically isolated&lt;/strong&gt; at the record level.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Architectural Strategy - Hybrid Cryptography
&lt;/h2&gt;

&lt;p&gt;Before writing a single line of code we must define our cryptographic strategy. We face a classic dilemma:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Symmetric Encryption (AES):&lt;/strong&gt; Fast, efficient for large files but requires sharing the secret key. If you use one key for everyone, a single leak compromises the entire system.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Asymmetric Encryption (RSA):&lt;/strong&gt; Great for sharing secrets securely using Public/Private key pairs, but incredibly slow for large data and has strict limits on payload size.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Hybrid Solution - The Envelope Pattern
&lt;/h3&gt;

&lt;p&gt;Envelope Encryption combines the best of both worlds.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Step A:&lt;/strong&gt; We generate a unique, random, one-time-use Data Encryption Key (DEK) for every single document. We use AES-256-GCM to encrypt the document content with this DEK.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Step B:&lt;/strong&gt; We take that small DEK and “wrap” (encrypt) it using the recipient’s RSA Public Key (The KEK — Key Encrypting Key).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Step C:&lt;/strong&gt; We store the encrypted content and the “wrapped” DEK (the Envelope) in the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To decrypt, the user uses their RSA Private Key to unwrap the DEK, then uses the DEK to decrypt the document. The document itself is never encrypted with a shared password.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deep Dive into the Primitives
&lt;/h2&gt;

&lt;p&gt;Standard AES modes like &lt;strong&gt;CBC (Cipher Block Chaining)&lt;/strong&gt; are vulnerable to “Bit-Flipping” attacks. An attacker might not be able to read your data, but they can modify the cipher text in a way that changes the decrypted values (e.g., changing a price from 100 to 900).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GCM (Galois/Counter Mode)&lt;/strong&gt; is an Authenticated Encryption mode. It generates an Authentication Tag alongside the cipher text. If even a single bit of the encrypted data is modified, the decryption will fail. This provides Integrity and Authenticity, which are critical for SOC 2.&lt;/p&gt;

&lt;p&gt;When wrapping keys, we use &lt;strong&gt;OAEP (Optimal Asymmetric Encryption Padding)&lt;/strong&gt;. Older padding schemes like PKCS#1 v1.5 are vulnerable to “padding oracle” attacks. OAEP adds a layer of randomness that ensures the same DEK encrypted twice with the same Public Key will result in different cipher texts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data Modeling for Cryptographic Isolation
&lt;/h2&gt;

&lt;p&gt;We need a database schema that supports this hybrid model. We will use Symfony’s Doctrine ORM with Attribute-based mapping.&lt;/p&gt;

&lt;h3&gt;
  
  
  The User Entity - The Key Custodian
&lt;/h3&gt;

&lt;p&gt;Each user must have an asymmetric identity. While the Private Key should be managed by a secure session vault or HSM, the Public Key is stored in our database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity]
#[ORM\Table(name: 'users')]
class User implements UserInterface
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 180, unique: true)]
    private ?string $email = null;

    // The KEK (Key Encrypting Key) Public Component
    #[ORM\Column(type: 'text')]
    private ?string $publicKey = null;

    // ... standard getters and setters ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Document Entity - The Encrypted Payload
&lt;/h3&gt;

&lt;p&gt;The document doesn’t care who owns it, it only cares about its encrypted bits. We also store a Server-Side Envelope. This is a copy of the DEK encrypted with a Master Key. Why? Because SOC 2 requires “Availability.” If a user loses their private key, you need a way for authorized administrators to recover data or for automated backup processes to verify integrity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[ORM\Entity]
#[ORM\Table(name: 'documents')]
class Document
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\ManyToOne(targetEntity: User::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?User $owner = null;

    // The AES-256-GCM Encrypted Content
    #[ORM\Column(type: 'text')]
    private ?string $encryptedContent = null;

    // The DEK encrypted with the Server's Master Key (Backup/Audit)
    #[ORM\Column(type: 'string', length: 255)]
    private ?string $serverEncryptedDek = null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The DocumentShare Entity - The Envelope Store
&lt;/h3&gt;

&lt;p&gt;This is a many-to-many relationship table on steroids. It maps a document to a user and stores the DEK wrapped specifically for that user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[ORM\Entity]
#[ORM\Table(name: 'document_shares')]
class DocumentShare
{
    #[ORM\ManyToOne(targetEntity: Document::class, inversedBy: 'shares')]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private ?Document $document = null;

    #[ORM\ManyToOne(targetEntity: User::class)]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private ?User $sharedWith = null;

    // The DEK encrypted specifically for $sharedWith's RSA Public Key
    #[ORM\Column(type: 'text')]
    private ?string $userEncryptedDek = null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementing the Cryptographic Engine
&lt;/h2&gt;

&lt;p&gt;In Symfony, we follow the Dependency Inversion Principle. We don’t want our business logic to depend on the openssl_* functions directly. Instead, we define an interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Interface - EnvelopeCryptoServiceInterface
&lt;/h3&gt;

&lt;p&gt;This interface defines the contract for all cryptographic operations. If you later decide to move to AWS KMS or HashiCorp Vault, you simply implement this interface and swap the service in services.yaml.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface EnvelopeCryptoServiceInterface {
    public function generateDek(): string;
    public function encryptContent(string $plainText, string $dek): string;
    public function decryptContent(string $payload, string $dek): ?string;
    public function encryptDekForUser(string $dek, string $publicKey): string;
    public function decryptDekWithUserKey(string $wrappedDek, string $privateKey): string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Implementation - EnvelopeCryptoService
&lt;/h3&gt;

&lt;p&gt;Using PHP’s native OpenSSL extension, we implement the logic. Note the handling of the IV (Initialization Vector) and Tag. We concatenate them with the cipher text and base64-encode the entire package for easy storage in text fields.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function encryptContent(string $plainText, string $dek): string {
    $ivLength = openssl_cipher_iv_length('aes-256-gcm');
    $iv = random_bytes($ivLength);

    // GCM handles the $tag automatically
    $cipherText = openssl_encrypt($plainText, 'aes-256-gcm', $dek, OPENSSL_RAW_DATA, $iv, $tag);

    // Package: [IV][TAG][CIPHERTEXT]
    return base64_encode($iv . $tag . $cipherText);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The Orchestrator - DocumentManager
&lt;/h2&gt;

&lt;p&gt;The DocumentManager is the most important part of our business logic. It ensures that whenever a document is created, the cryptographic chain is completed correctly and atomically.&lt;/p&gt;

&lt;p&gt;It has three main responsibilities:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Creation:&lt;/strong&gt; Orchestrates DEK generation, content encryption and the creation of the primary owner’s envelope.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sharing:&lt;/strong&gt; Retrieves the DEK (using the server’s backup envelope) and re-wraps it for a new recipient.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reading:&lt;/strong&gt; Locates the user’s specific envelope and performs the multi-stage decryption.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Notice that the DocumentManager does not call flush(). It only prepares the entities. The caller (Controller or Command) is responsible for the transaction. This follows the Unit of Work pattern and ensures that we don’t end up with “half-created” records if a network error occurs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Logical Security - Symfony Voters
&lt;/h2&gt;

&lt;p&gt;Even with perfect encryption, we still need application-level logic. If Alice tries to view Bob’s document, we shouldn’t even attempt to perform the expensive RSA decryption. We use a &lt;strong&gt;Symfony Voter&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;DocumentVoter&lt;/strong&gt; checks two conditions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Does the user own the document?&lt;/li&gt;
&lt;li&gt;Is there a &lt;strong&gt;DocumentShare&lt;/strong&gt; record mapping the document to the user?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By placing this check in a Voter, we can use the &lt;strong&gt;#[IsGranted]&lt;/strong&gt; attribute in our controllers, keeping them incredibly clean.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#[Route('/documents/{id}', name: 'document_view')]
#[IsGranted('DOCUMENT_VIEW', subject: 'document')]
public function view(Document $document, DocumentManagerInterface $manager): Response {
    // If the code execution gets here, we KNOW the user has logical access.
    // Now we just need to verify they have the cryptographic key.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We have successfully moved from a “Trust the Database” model to a “Trust the Math” model. Even if an intruder dumps your documents table, they see nothing but base64 gibberish. They cannot decrypt the documents without the users’ RSA Private Keys, which aren’t in the database.&lt;/p&gt;

&lt;p&gt;However, we still have two problems:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Log Leakage:&lt;/strong&gt; If we log every change, do the logs themselves contain sensitive data?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Key Centralization:&lt;/strong&gt; If the server’s Master Key is stolen, all document DEKs can be recovered.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In Part 2, we will solve these issues by implementing &lt;strong&gt;Asynchronous Audit Isolation&lt;/strong&gt; and a &lt;strong&gt;Sharded Key Management Service (KMS)&lt;/strong&gt; and share full implementation GitHub repo.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LinkedIn: [&lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;X (Twitter): [&lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;Telegram: [&lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;GitHub: [&lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;]&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>symfony</category>
      <category>security</category>
      <category>php</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Stop N+1 Queries Forever: Advanced Doctrine ORM Strategies in Symfony 8.1</title>
      <dc:creator>Matt Mochalkin</dc:creator>
      <pubDate>Fri, 22 May 2026 13:26:48 +0000</pubDate>
      <link>https://dev.to/mattleads/stop-n1-queries-forever-advanced-doctrine-orm-strategies-in-symfony-81-b8b</link>
      <guid>https://dev.to/mattleads/stop-n1-queries-forever-advanced-doctrine-orm-strategies-in-symfony-81-b8b</guid>
      <description>&lt;p&gt;The N+1 query problem is the silent killer of application performance. You build a beautiful new Symfony endpoint, test it locally with a handful of database records and the response time is a lightning-fast 30ms. You deploy to production and suddenly, that same endpoint takes 3 seconds to load, choking the database connection pool and bringing your application to its knees.&lt;/p&gt;

&lt;p&gt;If you check the Symfony Web Profiler, you’ll see a wall of identical SELECT statements varying only by an ID. You’ve been hit by the N+1 query problem.&lt;/p&gt;

&lt;p&gt;In this guide, we are moving past the beginner advice of “just use joins.” We need to leverage the full power of Doctrine ORM 3.x in Symfony 8.1. We will explore custom Doctrine Query Language (DQL), precise Fetch Modes, Partial Objects and Data Transfer Object (DTO) hydration to guarantee high-performance, scalable endpoints.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Core Concept - What is N+1?
&lt;/h2&gt;

&lt;p&gt;An N+1 problem occurs when an Object-Relational Mapper (ORM) executes one query to retrieve a list of “N” entities (the “1” query) and then executes an additional query for each entity to retrieve its related data (the “N” queries). If you fetch 100 Author entities and iterate over them to get their Book entities, Doctrine defaults to lazy loading, resulting in 101 queries instead of 1.&lt;/p&gt;

&lt;h3&gt;
  
  
  Prerequisites and Setup
&lt;/h3&gt;

&lt;p&gt;To follow along with these advanced strategies, ensure your environment meets the following specifications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PHP: 8.2 or 8.3&lt;/li&gt;
&lt;li&gt;Symfony: 8.1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Packages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;doctrine/orm (v3.1+)&lt;/li&gt;
&lt;li&gt;doctrine/doctrine-bundle (v2.12+)&lt;/li&gt;
&lt;li&gt;symfony/profiler-pack (v3.3+) — Crucial for verification.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Strategy 1: The Golden Standard — DQL and JOIN FETCH
&lt;/h2&gt;

&lt;p&gt;The most reliable way to eliminate N+1 queries is explicitly telling Doctrine to fetch the primary entity and its relations in a single database round-trip. This is done using JOIN FETCH in DQL or the QueryBuilder.&lt;/p&gt;

&lt;p&gt;Standard JOIN in DQL filters the results but does not hydrate the related entities into the primary entity. JOIN FETCH does both.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Code: Implementing JOIN FETCH
&lt;/h3&gt;

&lt;p&gt;Let’s assume we have an Author entity and a Book entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Entity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Repository\AuthorRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Common\Collections\ArrayCollection&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Common\Collections\Collection&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\ORM\Mapping&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="no"&gt;ORM&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="na"&gt;#[ORM\Entity(repositoryClass: AuthorRepository::class)]&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Author&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Id]&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\GeneratedValue]&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Column]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?int&lt;/span&gt; &lt;span class="nv"&gt;$id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(length: 255)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt; &lt;span class="nv"&gt;$name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * @var Collection&amp;lt;int, Book&amp;gt;
     */&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\OneToMany(targetEntity: Book::class, mappedBy: 'author', cascade: ['persist', 'remove'])]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;Collection&lt;/span&gt; &lt;span class="nv"&gt;$books&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayCollection&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getId&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;?int&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getName&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;setName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$name&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;static&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * @return Collection&amp;lt;int, Book&amp;gt;
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getBooks&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;Collection&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;addBook&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Book&lt;/span&gt; &lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;static&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setAuthor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;removeBook&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Book&lt;/span&gt; &lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;static&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;removeElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// set the owning side to null (unless already changed)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getAuthor&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;setAuthor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we want to load all authors and their books, we write a custom repository method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\DTO\AuthorBookSummary&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Entity\Author&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\Persistence\ManagerRegistry&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cd"&gt;/**
 * @extends ServiceEntityRepository&amp;lt;Author&amp;gt;
 */&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuthorRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;ServiceEntityRepository&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;ManagerRegistry&lt;/span&gt; &lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$registry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Author&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * Strategy 1: JOIN FETCH
     * Fetches all authors and eagerly loads their associated books.
     * @return Author[]
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;findAllWithBooks&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createQueryBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// We MUST select both 'a' and 'b' to hydrate the relation&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;leftJoin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a.books'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQuery&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResult&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="mf"&gt;...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By passing both ‘a’, ‘b’ to select() and joining a.books as b Doctrine generates a single SQL query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;a0_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;id_0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a0_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;name_1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b1_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;id_2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b1_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;title&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;title_3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b1_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;author_id&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;author_id_4&lt;/span&gt; 
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;author&lt;/span&gt; &lt;span class="n"&gt;a0_&lt;/span&gt; 
&lt;span class="k"&gt;LEFT&lt;/span&gt; &lt;span class="k"&gt;JOIN&lt;/span&gt; &lt;span class="n"&gt;book&lt;/span&gt; &lt;span class="n"&gt;b1_&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;a0_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;b1_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;author_id&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When Doctrine hydrates the Author objects, it sees the Book data in the result set and pre-populates the $books collection. No lazy loading will be triggered.&lt;/p&gt;

&lt;h2&gt;
  
  
  Strategy 2: Fetch Modes via Attributes
&lt;/h2&gt;

&lt;p&gt;Sometimes you know that a specific relation will always be accessed when the parent entity is loaded. In these cases, you can alter the default fetch mode at the entity level using PHP 8 Attributes.&lt;/p&gt;

&lt;p&gt;Doctrine provides three fetch modes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LAZY (Default):&lt;/strong&gt; Fetches related data only when accessed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;EAGER:&lt;/strong&gt; Always fetches the related data alongside the parent entity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;EXTRA_LAZY:&lt;/strong&gt; Optimized for collections (e.g., count($author-&amp;gt;getBooks()) issues a COUNT() query instead of loading the whole collection).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Forcing Eager Loading
&lt;/h3&gt;

&lt;p&gt;If every time we load a Book, we need to know its Author, we can set the ManyToOne relation to EAGER.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Entity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\Repository\BookRepository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Doctrine\ORM\Mapping&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="no"&gt;ORM&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="na"&gt;#[ORM\Entity(repositoryClass: BookRepository::class)]&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Id]&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\GeneratedValue]&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\Column]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?int&lt;/span&gt; &lt;span class="nv"&gt;$id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="na"&gt;#[ORM\Column(length: 255)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?string&lt;/span&gt; &lt;span class="nv"&gt;$title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// Setting fetch mode to EAGER&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\ManyToOne(targetEntity: Author::class, inversedBy: 'books', fetch: 'EAGER')]&lt;/span&gt;
    &lt;span class="na"&gt;#[ORM\JoinColumn(nullable: false)]&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;?Author&lt;/span&gt; &lt;span class="nv"&gt;$author&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// ... getters and setters&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Do not overuse &lt;strong&gt;EAGER&lt;/strong&gt; fetching. If you set too many relations to EAGER, Doctrine will generate massive, complex queries (or multiple background queries depending on the relation type) every time you fetch a single entity, resulting in memory exhaustion. Reserve EAGER strictly for relations that are universally required by the application business logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Strategy 3: Precision Optimization with Partial Objects
&lt;/h2&gt;

&lt;p&gt;One major source of overhead in ORMs is hydration — converting database rows into PHP objects. If an Author entity has 30 columns (bio, birthdate, profile picture URL, etc.) but your endpoint only needs to display a list of Author names and Book titles, hydrating the full object wastes CPU and memory.&lt;/p&gt;

&lt;p&gt;Doctrine allows you to load Partial Objects. This bypasses full entity hydration and only populates the specific fields you request.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using the partial Keyword
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/Repository/AuthorRepository.php&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * @return Author[]
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;findPartialAuthorsWithPartialBooks&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createQueryBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;// Using the 'partial' keyword to only select ID and Name&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'partial a.{id, name}'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;addSelect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'partial b.{id, title}'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;leftJoin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a.books'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQuery&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResult&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Danger of Partial Objects
&lt;/h3&gt;

&lt;p&gt;Doctrine issues a strict warning regarding partial objects - they should be considered read-only.&lt;br&gt;
If you load a partial Author object, modify its name and call EntityManager::flush() Doctrine’s Unit of Work might behave unpredictably regarding the omitted fields, potentially nullifying them in the database.&lt;/p&gt;

&lt;p&gt;Only use partial objects for heavily-trafficked read-only APIs or reports.&lt;/p&gt;
&lt;h2&gt;
  
  
  Strategy 4: The Ultimate Read-Only Fix — DTO Hydration
&lt;/h2&gt;

&lt;p&gt;If you are building a high-traffic API endpoint, hydrating ORM entities — even partial ones — is often unnecessary overhead. You don’t need the Doctrine Unit of Work tracking changes on objects you only intend to serialize to JSON.&lt;/p&gt;

&lt;p&gt;Instead, construct custom Data Transfer Objects (DTOs) directly in your DQL using the NEW operator.&lt;/p&gt;
&lt;h3&gt;
  
  
  Direct DTO Hydration
&lt;/h3&gt;

&lt;p&gt;First, create a simple, immutable DTO using PHP 8.2+ readonly classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\DTO&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuthorBookSummary&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$authorId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$authorName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$bookId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$bookTitle&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, use the NEW syntax in your Repository to instantiate these DTOs straight from the query result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;App\DTO\AuthorBookSummary&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// ...&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * @return AuthorBookSummary[]
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getAuthorBookSummaries&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createQueryBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s1"&gt;'NEW %s(a.id, a.name, b.id, b.title)'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="nc"&gt;AuthorBookSummary&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;
            &lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a.books'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQuery&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getResult&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Zero N+1 Queries:&lt;/strong&gt; The data is pulled in a single join.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Zero Unit of Work Overhead:&lt;/strong&gt; Doctrine does not track these DTOs for changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Low Memory Footprint:&lt;/strong&gt; You avoid instantiating Doctrine Proxy classes, ArrayCollection instances and full entities.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Strategy 5: The Hidden N+1 in Iterators (Iterator N+1)
&lt;/h2&gt;

&lt;p&gt;When dealing with massive datasets — like exporting thousands of records or processing batch updates via a Symfony Console Command — loading all entities into memory at once with getResult() will cause a fatal out-of-memory error.&lt;/p&gt;

&lt;p&gt;To solve this, developers correctly turn to Doctrine’s &lt;strong&gt;toIterable()&lt;/strong&gt; method (the modern replacement for the old iterate() method in Doctrine 3.x). This yields results one by one, keeping the memory footprint low. However, this introduces a highly dangerous, hidden N+1 trap.&lt;/p&gt;

&lt;h3&gt;
  
  
  Iterating over Lazy Relations
&lt;/h3&gt;

&lt;p&gt;Imagine a background command that exports authors and their books. If you iterate over the Author entities but fail to eagerly load the Book relation, Doctrine will fire a new query for the books on every single iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;InputInterface&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;OutputInterface&lt;/span&gt; &lt;span class="nv"&gt;$output&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// 🚨 THE TRAP: We select 'a' but do not JOIN FETCH 'a.books'&lt;/span&gt;
        &lt;span class="nv"&gt;$query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;authorRepository&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createQueryBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQuery&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="nv"&gt;$batchSize&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="c1"&gt;// toIterable() loads one Author at a time into memory&lt;/span&gt;
        &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$query&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toIterable&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$author&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// 💥 N+1 TRIGGERED: Accessing $author-&amp;gt;getBooks() fires a new query!&lt;/span&gt;
            &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$author&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getBooks&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$book&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Do something with the book...&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Detach entities to prevent memory leaks in the Unit of Work&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nv"&gt;$batchSize&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Command&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SUCCESS&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have 50,000 authors, this loop will execute 50,001 queries, completely nullifying the performance benefits of the iterator and grinding your background worker to a halt. You could fix this with a JOIN FETCH but if you are just exporting data, there is a much better, memory-safe way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Strategy 6: High-Performance Iterators with DTOs (Iterator DTO)
&lt;/h2&gt;

&lt;p&gt;To achieve the ultimate combination of low memory usage and zero N+1 queries during batch processing, we can combine the &lt;strong&gt;toIterable()&lt;/strong&gt; method with the &lt;strong&gt;direct DTO hydration (NEW)&lt;/strong&gt; strategy we discussed in Strategy 4.&lt;/p&gt;

&lt;p&gt;By yielding Data Transfer Objects instead of Doctrine Entities, you bypass the Unit of Work entirely. You don’t need to worry about calling &lt;strong&gt;$entityManager-&amp;gt;clear()&lt;/strong&gt; in batches because Doctrine isn’t tracking the DTOs and the data is fetched in a single optimized query stream.&lt;/p&gt;

&lt;h3&gt;
  
  
  Yielding DTOs from an Iterator
&lt;/h3&gt;

&lt;p&gt;Let’s refactor our AuthorRepository and our background command to use this approach. We will reuse the AuthorBookSummary DTO from earlier.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getAuthorBookSummariesIterable&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;iterable&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getEntityManager&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;createQueryBuilder&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sprintf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s1"&gt;'NEW %s(a.id, a.name, b.id, b.title)'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="nc"&gt;AuthorBookSummary&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;
            &lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'App\Entity\Book'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'b.author'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQuery&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toIterable&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Constant Memory Footprint:&lt;/strong&gt; PHP streams the results from the database. You will use roughly the same amount of RAM processing 10 rows as you would processing 1,000,000 rows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Absolute Zero N+1 Queries:&lt;/strong&gt; The JOIN in the DQL ensures the database does the heavy lifting, delivering flat, predictable rows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CPU Efficiency:&lt;/strong&gt; Because Doctrine doesn’t have to create Proxy classes or maintain state tracking for the Unit of Work, your script execution time will drop dramatically.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Proving You Fixed the Problem
&lt;/h2&gt;

&lt;p&gt;Writing the code is only half the battle, we must prove our optimizations work. Symfony provides the ultimate tool for this: The Profiler.&lt;/p&gt;

&lt;h3&gt;
  
  
  Install the Profiler
&lt;/h3&gt;

&lt;p&gt;If you haven’t already, install the profiler pack in your dev environment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require &lt;span class="nt"&gt;--dev&lt;/span&gt; symfony/profiler-pack
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Analyze the Database Tab
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Load your endpoint in the browser.&lt;/li&gt;
&lt;li&gt;Click on the Doctrine icon in the Symfony Web Debug Toolbar (bottom of the screen).&lt;/li&gt;
&lt;li&gt;Look at the Query Metrics.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Before Optimization:&lt;/strong&gt; You will see a high number of queries (e.g., “102 queries”) and warnings in yellow about “Similar Queries” or “Identical Queries.”&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;After Optimization:&lt;/strong&gt; You should see exactly 1 query executed for the endpoint, with a substantially lower execution time.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Automated Testing for N+1
&lt;/h3&gt;

&lt;p&gt;You can integrate query counting into your functional tests to prevent regressions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="kn"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;App\Tests\Functional&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Symfony\Bundle\FrameworkBundle\Test\WebTestCase&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuthorApiTest&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;WebTestCase&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testAuthorsNPlusOneProblem&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$queryCount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getQueryCountForEndpoint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'/api/authors/n-plus-one'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// With 10 authors, we expect 1 query for authors + 10 queries for books = 11 queries&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertGreaterThan&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$queryCount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'N+1 query problem should be present in the non-optimized endpoint'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertEquals&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$queryCount&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Benchmarking the Strategies
&lt;/h2&gt;

&lt;p&gt;In software engineering, we don’t just guess — we measure. To prove the massive impact of these optimizations, let’s look at a performance benchmark comparing all the strategies discussed above.&lt;/p&gt;

&lt;p&gt;This test simulates fetching a collection of primary entities and their relations, measuring CPU time, allocated memory (RAM) and average execution time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+--------------------+-----------+-------------+------------+------------------------------------------------------------+
| Strategy Name      | CPU (avg) | RAM (alloc) | Time (avg) | Summary                                                    |
+--------------------+-----------+-------------+------------+------------------------------------------------------------+
| 1. N+1 Problem     | 1.90 ms   | 0.1607 MB   | 2.14 ms    | Baseline: 1 query for Author, N queries for Books.         |
| 2. JOIN FETCH      | 1.37 ms   | 0.0741 MB   | 1.43 ms    | Eager loads collections in 1 query via DQL.                |
| 3. Eager Fetch     | 1.03 ms   | 0.0714 MB   | 1.03 ms    | Eager loading relations dynamically using query builder.   |
| 4. Partial Objects | 1.14 ms   | 0.0741 MB   | 1.14 ms    | Hydrates only specific fields, reducing memory.            |
| 5. DTO Hydration   | 0.36 ms   | 0.0084 MB   | 0.37 ms    | Bypasses ORM entities entirely. Fastest array fetch.       |
| 6. Iterator (N+1)  | 1.56 ms   | 0.1615 MB   | 1.57 ms    | Streams entities, but lazy-loading relations triggers N+1. |
| 7. Iterator (DTO)  | 0.37 ms   | 0.0081 MB   | 0.37 ms    | Streams DTOs. Lowest RAM usage for massive exports.        |
+--------------------+-----------+-------------+------------+------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The numbers speak for themselves, revealing some critical insights for your application’s architecture:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The Baseline is Expensive:&lt;/strong&gt; The standard N+1 scenario is the slowest (2.14 ms) and uses the most memory (0.1607 MB) because Doctrine has to instantiate objects, manage the Unit of Work and execute multiple round-trips to the database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JOIN FETCH is the Easy Win:&lt;/strong&gt; Simply adding a JOIN FETCH (Strategy 1) cuts memory usage by more than half and speeds up the response time by ~33%. It’s the most effective fix for standard entity workflows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The DTO Dominance:&lt;/strong&gt; Look at Strategies 4 and 6. Bypassing entity hydration entirely and yielding Data Transfer Objects drops memory usage to an incredibly lean 0.008 MB and execution time to a blazingly fast ~0.37 ms. This is an 80%+ reduction in response time and a 95% reduction in memory usage compared to the baseline.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Iterator Trap:&lt;/strong&gt; Strategy 5 proves that simply using an iterator doesn’t save you if you still have an N+1 problem hiding inside the loop. It consumed nearly as much memory as the baseline and was heavily bottlenecked by CPU overhead.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you are building an API endpoint or a heavy background export command, DTOs are the undisputed champions of Doctrine performance. Combine them with iterators (Strategy 6) and your Symfony 8.1 application will scale effortlessly, regardless of how large your database grows.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The N+1 query problem is a rite of passage for every PHP developer but it doesn’t have to dictate your application’s performance. As the benchmarks clearly show, the difference between a sluggish, memory-hungry endpoint and a lightning-fast API often comes down to just a few carefully crafted lines of Doctrine Query Language.&lt;/p&gt;

&lt;p&gt;You now have a complete, advanced toolkit for Symfony 8.1 to completely eradicate N+1 queries from your projects:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;For Standard Workflows:&lt;/strong&gt; Default to JOIN FETCH (Strategy 1) to explicitly eager-load related data in a single round-trip when your business logic requires full entities.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;For Universal Relations:&lt;/strong&gt; Use EAGER fetch modes via PHP 8 Attributes (Strategy 2) sparingly, reserving them strictly for data that is universally required across your entire application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;For Read-Only Views:&lt;/strong&gt; Leverage Partial Objects (Strategy 3) to cut down on hydration overhead when you only need a handful of entity properties.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;For High-Traffic APIs:&lt;/strong&gt; Switch to direct DTO Hydration using the NEW keyword (Strategy 4) to bypass the Doctrine Unit of Work entirely, resulting in massive speed improvements.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;For Massive Datasets:&lt;/strong&gt; Combine the toIterable() method with DTOs (Strategy 6) to process thousands of records with a near-zero memory footprint and absolute zero N+1 queries.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Always remember to lean heavily on the Symfony Web Profiler. Never guess at your database performance — measure your query counts, implement these optimizations and verify the results. By applying these advanced Doctrine ORM 3.x strategies, you are doing more than just fixing bugs; you are engineering robust, highly scalable Symfony applications that will thrive under heavy traffic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Source Code:&lt;/strong&gt; You can find the full implementation and follow the project’s progress on GitHub: [&lt;a href="https://github.com/mattleads/DQLStrategies" rel="noopener noreferrer"&gt;https://github.com/mattleads/DQLStrategies&lt;/a&gt;]&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s Connect!
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;p&gt;LinkedIn: [&lt;a href="https://www.linkedin.com/in/matthew-mochalkin/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/matthew-mochalkin/&lt;/a&gt;]&lt;br&gt;
X (Twitter): [&lt;a href="https://x.com/MattLeads" rel="noopener noreferrer"&gt;https://x.com/MattLeads&lt;/a&gt;]&lt;br&gt;
Telegram: [&lt;a href="https://t.me/MattLeads" rel="noopener noreferrer"&gt;https://t.me/MattLeads&lt;/a&gt;]&lt;br&gt;
GitHub: [&lt;a href="https://github.com/mattleads" rel="noopener noreferrer"&gt;https://github.com/mattleads&lt;/a&gt;]&lt;/p&gt;

</description>
      <category>symfony</category>
      <category>sql</category>
      <category>php</category>
      <category>performance</category>
    </item>
  </channel>
</rss>
