<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matt Mochalkin on Medium]]></title>
        <description><![CDATA[Stories by Matt Mochalkin on Medium]]></description>
        <link>https://medium.com/@MattLeads?source=rss-a50875c323fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tuP6U30XS79vVLKn-h0aOQ.png</url>
            <title>Stories by Matt Mochalkin on Medium</title>
            <link>https://medium.com/@MattLeads?source=rss-a50875c323fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 26 Nov 2026 10:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MattLeads/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Retry #1 Forever: What Symfony Messenger 8.1 Expects From Your Custom Serializer]]></title>
            <link>https://medium.com/@MattLeads/retry-1-forever-what-symfony-messenger-8-1-expects-from-your-custom-serializer-8e4d08409823?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e4d08409823</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 08:42:49 GMT</pubDate>
            <atom:updated>2026-11-23T08:42:49.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Symfony 8.1 changed how a serializer reports a message it cannot decode. Why a throwing decode() looped at retry #1 on 8.1.0 to 8.1.10, the fix in 8.1.11, and the contract to write against today.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IczDjoFXMcKgoV5aichUKA.jpeg" /></figure><p>Your worker is logging the same line over and over:</p><pre>WARNING: Sending for retry #1 using 0 ms delay. Error: &quot;Cannot decode message: unknown encryption key &quot;k2&quot;.&quot;</pre><p>Retry #1, again and again. max_retries 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.</p><p>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 (<a href="https://dev.to/mattleads/77x-smaller-and-encrypted-at-rest-compressing-symfony-messenger-payloads-without-touching-a-1ij4">that article</a> 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 decode() 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.</p><h3>Prerequisites</h3><ul><li>symfony/messenger 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.</li><li>Any transport with a receiver: the reproducer uses symfony/doctrine-messenger 8.1 on SQLite in memory, no framework, one PHP file.</li><li>A custom serializer, or a decorator around the built-in Serializer. If every transport you have uses the stock Serializer or PhpSerializer, you are not affected by the loop, but the contract in section 4 still applies to any serializer you write next.</li></ul><p>The reproducer is at <a href="https://github.com/mattleads/messenger-decode-throw-repro">mattleads/messenger-decode-throw-repro</a>: php repro.php throw and php repro.php return.</p><h3>1. What 8.0 did with a message it could not decode</h3><p>Before 8.1, a serializer reported a decoding failure by throwing MessageDecodingFailedException from decode(). The Doctrine receiver on 8.0 handled it like this:</p><pre>// symfony/doctrine-messenger 8.0, DoctrineReceiver::createEnvelopeFromData()<br>try {<br>    $envelope = $this-&gt;serializer-&gt;decode([<br>        &#39;body&#39; =&gt; $data[&#39;body&#39;],<br>        &#39;headers&#39; =&gt; $data[&#39;headers&#39;],<br>    ]);<br>} catch (MessageDecodingFailedException $exception) {<br>    $this-&gt;connection-&gt;reject($data[&#39;id&#39;]);<br> <br>    throw $exception;<br>}</pre><p>Reject, then rethrow. The reject deletes the row. The rethrow escapes Worker::run(), which has no catch around $receiver-&gt;get(), and messenger:consume only wraps the run in a finally. 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.</p><p>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.</p><h3>2. What 8.1 changed, and the piece that makes retries work</h3><p>Symfony 8.1 (May 2026) routes decoding failures through the same pipeline as a failing handler. Nicolas Grekas’ PR #62888 did three things:</p><ol><li>MessageDecodingFailedException got a wrap() factory and an encodedEnvelope property. wrap($encodedEnvelope, $message) returns an Envelope whose message is the exception, and the exception carries the raw body and headers it could not read.</li><li>Receivers no longer delete and throw. They yield the wrapped envelope with their own stamps, so ack() and reject() work on it like on any message.</li><li>A new DecodeFailedMessageMiddleware sits early in the bus. When the message is a MessageDecodingFailedException, it looks up the serializer of the transport that received it and calls decode() 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.</li></ol><p>The contract for serializers changed with it. From the 8.1.0 docblock of SerializerInterface::decode():</p><blockquote><em>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.</em></blockquote><p>How does Messenger know this is retry #2 and not retry #1? Through a stamp. SendFailedMessageForRetryListener reads RedeliveryStamp::getRetryCountFromEnvelope(), which is the count on the last RedeliveryStamp of the envelope, or 0 if there is none. When a message is sent back for a retry, the listener adds a new RedeliveryStamp with the incremented count, and the serializer writes it into the headers as X-Message-Stamp-...RedeliveryStamp. On the next delivery the serializer decodes the headers, the stamp is back on the envelope, the count continues.</p><p>So the retry counter lives in the headers of the message, and it comes back only if decode() puts it back. That is the whole bug.</p><p>The built-in Serializer on 8.1 decodes the stamps first and keeps the ones that decode on every failure path:</p><pre>// symfony/messenger 8.1.11, Serializer::decode()<br>// a failure keeps the stamps that decode, so that its retries are counted<br>$stamps = $this-&gt;decodeStamps($encodedEnvelope, $stampFailure);<br>// ...<br>try {<br>    $message = $this-&gt;serializer-&gt;deserialize($encodedEnvelope[&#39;body&#39;], $type, $this-&gt;format, $context);<br>} catch (\Throwable $e) {<br>    return MessageDecodingFailedException::wrap($encodedEnvelope, &#39;Could not decode message: &#39;.$e-&gt;getMessage(), (int) $e-&gt;getCode(), $e)-&gt;with(...$stamps);<br>}</pre><p>It took three fixes on the 8.1 branch to get the stock serializer there. PR #65122 (August 2026) stopped encode() 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.</p><h3>3. The trap: throw, and the counter never comes back</h3><p>Every receiver on 8.1 kept the catch as the BC fallback the docblock promised. The 8.1.10 Doctrine receiver:</p><pre>// symfony/doctrine-messenger 8.1.10 and 8.1.11, DoctrineReceiver::createEnvelopeFromData()<br>$stamps = [<br>    new DoctrineReceivedStamp($data[&#39;id&#39;]),<br>    new TransportMessageIdStamp($data[&#39;id&#39;]),<br>];<br> <br>try {<br>    return $this-&gt;serializer-&gt;decode($data = [<br>        &#39;body&#39; =&gt; $data[&#39;body&#39;],<br>        &#39;headers&#39; =&gt; $data[&#39;headers&#39;],<br>    ])-&gt;withoutAll(TransportMessageIdStamp::class)-&gt;with(...$stamps);<br>} catch (MessageDecodingFailedException $e) {<br>    return MessageDecodingFailedException::wrap($data, $e-&gt;getMessage(), $e-&gt;getCode(), $e)-&gt;with(...$stamps);<br>}</pre><p>Look at what $stamps holds in the catch: the receiver&#39;s two stamps. Nothing from the headers. The receiver cannot decode them, because the only component that knows the header format just threw. The RedeliveryStamp is in the row, in the headers column, and it never reaches the envelope.</p><p>From there the sequence is mechanical. The wrapped envelope reaches DecodeFailedMessageMiddleware, which calls decode() again. The serializer throws again. On 8.1.0 to 8.1.10 the middleware had no try around that call, so the raw MessageDecodingFailedException escapes to the worker. The retry listener sees an envelope with no RedeliveryStamp, computes retry count 0, decides 0 &lt; 3, and sends the message back with a RedeliveryStamp(1). The serializer&#39;s encode() writes it into the headers. Next delivery, the serializer throws before reading headers, the stamp is lost, count is 0 again. Retry #1, forever.</p><p>The reproducer has one serializer with two modes. It wraps the stock Serializer and pretends it cannot read the body:</p><pre>final class UnreadableSerializer implements SerializerInterface<br>{<br>    public function decode(array $encodedEnvelope): Envelope<br>    {<br>        $error = &#39;Cannot decode message: unknown encryption key &quot;k2&quot;.&#39;;<br> <br>        if (&#39;throw&#39; === $this-&gt;mode) {<br>            // pre-8.1 contract, &quot;still supported for BC&quot; according to SerializerInterface::decode()<br>            throw new MessageDecodingFailedException($error);<br>        }<br> <br>        // 8.1 contract: return the failure, and keep the stamps that still decode from the headers<br>        $stamps = array_merge(...array_values($this-&gt;inner-&gt;decode($encodedEnvelope)-&gt;all()));<br> <br>        return MessageDecodingFailedException::wrap($encodedEnvelope, $error)-&gt;with(...$stamps);<br>    }<br>}</pre><p>Doctrine transport, max_retries: 3, a failure transport, one message, one worker with a time limit. php repro.php throw on 8.1.10:</p><pre>WARNING: ... Sending for retry #1 using 0 ms delay. Error: &quot;Cannot decode message: unknown encryption key &quot;k2&quot;.&quot;<br>WARNING: ... Sending for retry #1 using 0 ms delay. ...<br>WARNING: ... Sending for retry #1 using 0 ms delay. ...<br>(repeats until the worker is stopped)<br> <br>mode=throw  still queued on async: 1  on failure transport: 0</pre><p>php repro.php return, same serializer, same message:</p><pre>WARNING: ... Sending for retry #1 using 0 ms delay. ...<br>WARNING: ... Sending for retry #2 using 0 ms delay. ...<br>WARNING: ... Sending for retry #3 using 0 ms delay. ...<br>CRITICAL: ... Removing from transport after 3 retries. ...<br>INFO: Rejected message ... will be sent to the failure transport ...<br> <br>mode=return  still queued on async: 0  on failure transport: 1</pre><p>The only difference between the two runs is whether decode() throws or returns.</p><p>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.</p><h3>4. The fix in 8.1.11</h3><p>The receiver cannot restore the counter, so the fix had to live where the second decode() 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:</p><pre>// symfony/messenger 8.1.11, DecodeFailedMessageMiddleware::handle()<br>try {<br>    $decodedEnvelope = $serializer-&gt;decode($message-&gt;encodedEnvelope);<br>} catch (MessageDecodingFailedException $e) {<br>    // the stamps of a thrown failure are lost and its retries cannot be counted, so it should not be retried<br>    throw $e-&gt;getPrevious() instanceof UnrecoverableExceptionInterface ? $e-&gt;getPrevious() : new UnrecoverableMessageHandlingException($e-&gt;getMessage(), $e-&gt;getCode(), $e);<br>}</pre><p>A thrown decoding failure becomes an UnrecoverableMessageHandlingException, with the original exception as previous. The retry listener sees an unrecoverable exception, skips the retries, and the message goes to the failure transport after 0 retries. From there messenger:failed:retry replays it through DecodeFailedMessageMiddleware once the serializer can read it. Serializers that return wrap() keep their retries, since their stamps are intact.</p><p>Nicolas Grekas added a worker-level test to FailureIntegrationTest that runs a throwing serializer through a real Worker, asserts one failure with count 0 and class UnrecoverableMessageHandlingException, and then replays the message from the failure transport once the serializer works. He also changed SigningSerializer: it used to catch everything its inner serializer threw and return it as a wrapped failure, which lost the inner serializer&#39;s stamps the same way. It now rethrows what the inner serializer throws (wrapped in MessageDecodingFailedException if it was something else), so the fix covers signed messages too.</p><p>The docblock no longer promises that throwing is equivalent:</p><blockquote><em>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.</em></blockquote><p>What a serializer that cannot read a payload gets on each version:</p><pre>What decode() does, and what happens on each version<br> <br>decode() throws MessageDecodingFailedException<br>  8.0                message deleted, worker exits<br>  8.1.0 to 8.1.10    retry #1 forever, failure transport empty<br>  8.1.11 and later   failure transport after 0 retries, replay possible<br> <br>decode() returns wrap() with the decoded stamps<br>  8.0                not available<br>  8.1.0 to 8.1.10    retried up to max_retries, then failure transport<br>  8.1.11 and later   same<br> <br>decode() returns wrap() without stamps<br>  8.0                not available<br>  8.1.0 to 8.1.10    retry #1 forever<br>  8.1.11 and later   retry #1 forever</pre><p>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.</p><h3>5. The contract to write against today</h3><p>Three rules, taken from the 8.1.11 docblock and the docs’ custom serializer example.</p><p><strong>Return the failure, do not throw it.</strong> MessageDecodingFailedException::wrap($encodedEnvelope, $message, $code, $previous) gives you the envelope. The raw body and headers go into the exception, so the message can be sent again as it was received.</p><p><strong>Keep every stamp you can still decode.</strong> For a decorator around the stock Serializer that is one call: the inner serializer&#39;s decode() on the unreadable payload returns its own failure envelope, and that envelope carries the stamps it read from the headers. Take them:</p><pre>public function decode(array $encodedEnvelope): Envelope<br>{<br>    try {<br>        $body = $this-&gt;open($encodedEnvelope); // decrypt, decompress, whatever can fail<br>    } catch (\Throwable $e) {<br>        // the inner serializer still reads the headers, and the RedeliveryStamp is in them<br>        $stamps = array_merge(...array_values($this-&gt;inner-&gt;decode($encodedEnvelope)-&gt;all()));<br> <br>        return MessageDecodingFailedException::wrap($encodedEnvelope, $e-&gt;getMessage(), (int) $e-&gt;getCode(), $e)-&gt;with(...$stamps);<br>    }<br> <br>    return $this-&gt;inner-&gt;decode([&#39;body&#39; =&gt; $body] + $encodedEnvelope);<br>}</pre><p>This relies on the stamps living in the headers, which is how Serializer stores them. PhpSerializer 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.</p><p><strong>Re-send a failure as it was received.</strong> When the failed message is retried or moved to the failure transport, your encode() gets an envelope whose message is the MessageDecodingFailedException. Do not transform that body again. The stock Serializer already handles it: it re-emits encodedEnvelope[&#39;body&#39;] as is, keeps the original type header, and writes the current stamps, including the new RedeliveryStamp, into the headers. A decorator only has to step aside:</p><pre>public function encode(Envelope $envelope): array<br>{<br>    $encoded = $this-&gt;inner-&gt;encode($envelope);<br> <br>    // a decoding failure is sent again with its original body, which is transformed already<br>    if ($envelope-&gt;getMessage() instanceof MessageDecodingFailedException) {<br>        return $encoded;<br>    }<br> <br>    $encoded[&#39;body&#39;] = $this-&gt;seal($encoded[&#39;body&#39;]);<br> <br>    return $encoded;<br>}</pre><p>A serializer that does not delegate, like the token decoder in the docs, returns $message-&gt;encodedEnvelope directly from encode() for a failure. That is the example the docs show since PR #23459, which replaced the old return new Envelope($throwable) in the &quot;Message Serializer For Custom Data Formats&quot; section. The old example dispatched a plain throwable as a message, and its encode() then threw when the worker tried to re-send it.</p><p>One configuration rule goes with this. The failure transport must use the same serializer as the transport that fed it, because DecodeFailedMessageMiddleware 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 &quot;Handling Decode Failures&quot;. The reproducer gets away with a PhpSerializer on the failure transport only because it never replays.</p><h3>6. The sibling trap: the Redis DSN overrides consumer</h3><p>Found the same week, while testing the Redis transport. The docs list consumer as an option you can set in the DSN or under options in messenger.yaml, with an example that sets it from an env var under options. Right above that list sits the &quot;Full DSN Example&quot;, and it ends in /messages/symfony/consumer.</p><p>In Connection::parseDsn() the query string is merged over the options array, and in fromDsn() the path segments are read last:</p><pre>// symfony/redis-messenger 8.1.11, Connection::fromDsn()<br>$pathParts = explode(&#39;/&#39;, rtrim($params[&#39;path&#39;] ?? &#39;&#39;, &#39;/&#39;));<br>$options[&#39;stream&#39;] = $pathParts[1] ?? $options[&#39;stream&#39;];<br>$options[&#39;group&#39;] = $pathParts[2] ?? $options[&#39;group&#39;];<br>$options[&#39;consumer&#39;] = $pathParts[3] ?? $options[&#39;consumer&#39;];</pre><p>So whoever copies the full example and then sets consumer: &#39;%env(MESSENGER_CONSUMER_NAME)%&#39; gets every worker registered in Redis under the literal name consumer, with no warning. Verified on symfony/redis-messenger 8.1.10 against a live Redis, with consumer: worker-42 under options:</p><pre>DSN                                                       Consumer registered in Redis<br>--------------------------------------------------------  ----------------------------<br>redis://localhost/messages                                worker-42<br>redis://localhost/messages/symfony                        worker-42<br>redis://localhost/messages/symfony/consumer               consumer<br>redis://localhost?consumer=dsnq                           dsnq<br>redis://localhost/messages/symfony/dsnpath?consumer=dsnq  dsnpath</pre><p>The precedence is the same in 5.4, 6.4 and 7.4. Note the docs’ general “Transport Configuration” section says options under options 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 options, stop the DSN path at /stream/group.</p><p>The name is not cosmetic. Redis tracks the pending entries of a stream group per consumer name, so every worker that shares the name consumer shares one pending list, and the per-worker accounting the option exists for is gone.</p><h3>7. How this went upstream</h3><p>For anyone who has not sent a bug to Symfony before, the sequence, with dates.</p><p>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.</p><p>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 FailureIntegrationTest, where the three earlier counter fixes had put theirs. Nicolas Grekas added that test and the SigningSerializer change, and merged on 3 November. 8.1.11 shipped on 4 November with it.</p><p>The Redis docs PR #23472 went in on 5 November and was merged the next day.</p><p>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.</p><h3>Conclusion</h3><p>If you maintain a custom Messenger serializer, decide these three things now.</p><ul><li><strong>On 8.1.0 to 8.1.10, update to 8.1.11.</strong> Until then, a serializer that throws from decode() loops at retry #1 on any poisoned message, and your failure transport will not tell you.</li><li><strong>Return </strong><strong>wrap() with the stamps if you want retries.</strong> A decorator around Serializer gets them from the inner serializer&#39;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.</li><li><strong>Let the failure re-send itself.</strong> In encode(), pass a MessageDecodingFailedException message through untransformed and give the failure transport the same serializer as its source.</li></ul><p>And if your Redis DSN has three path segments, check what name your workers are registered under.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/messenger-decode-throw-repro">https://github.com/mattleads/messenger-decode-throw-repro</a></p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e4d08409823" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Right Answer in Ten: The mcp/sdk 0.8]]></title>
            <link>https://medium.com/@MattLeads/one-right-answer-in-ten-the-mcp-sdk-0-8-890a07ecc8ae?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/890a07ecc8ae</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 11:30:05 GMT</pubDate>
            <atom:updated>2026-11-19T11:30:05.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>One Right Answer in Ten: The mcp/sdk 0.8 Session Race and the Case for a Stateless MCP Server in PHP</h3><h3>Parallel tool calls on the official PHP MCP SDK 0.8 came back empty or with another call’s answer. The session race step by step, what 0.9 and 0.10 changed, and a tools-only server that keeps no session.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTS6ZZCBi_8OQA-3ldXsOQ.jpeg" /></figure><p>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 202 Accepted, 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.</p><p>The server ran symfony/mcp-bundle 0.14.1 on mcp/sdk 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 php -S, shows what 0.9.0 and 0.10.0 changed, and explains why the MCP server in mattleads/agent-publishing-bundle keeps no session at all.</p><h3>Prerequisites</h3><ul><li>PHP 8.4.22, with PHP_CLI_SERVER_WORKERS=8 php -S 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.</li><li>mcp/sdk 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 composer install for the dev dependencies, which include nyholm/psr7 and laminas/laminas-httphandlerrunner.</li><li>symfony/mcp-bundle 0.14.1, which requires mcp/sdk ^0.8.1, and 0.15.0, which requires ^0.9 and adds a session.lock option.</li><li>mattleads/agent-publishing-bundle 0.3.1 for the stateless server, with its demo app from <a href="https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c">the previous article</a>.</li></ul><h3>1. What a Streamable HTTP session is</h3><p>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 202 Accepted with no body. A request gets either Content-Type: application/json 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.</p><p>Sessions are optional on the server side. The spec says a server “MAY assign a session ID at initialization time” through an Mcp-Session-Id 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 404, and a client that sees 404 starts over with a new initialize. A server that never sends the header has no session, and the client has nothing to carry.</p><p>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 notifications/resources/updated, 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 tools/call has nothing to park.</p><h3>2. What mcp/sdk 0.8.1 kept in the session</h3><p>The 0.8.1 server parks everything there, including the answer to the request it is currently handling. The relevant pieces are in Mcp\Server\Protocol and Mcp\Server\Transport\StreamableHttpTransport.</p><p>A POST arrives, Protocol::doProcessInput() loads the session named by the header, handles each message, and saves the session once at the end:</p><pre>// mcp/sdk 0.8.1, src/Server/Protocol.php, doProcessInput()<br>$session = $this-&gt;resolveSession($transport, $sessionId, $messages);<br>// ...<br>foreach ($messages as $message) {<br>    // ... handleRequest() / handleResponse() / handleNotification()<br>}<br> <br>$session-&gt;save();</pre><p>When a tool handler returns, handleRequest() calls sendResponse(). With a session present the response is not sent. It is queued inside the session under the key _mcp.outgoing_queue:</p><pre>// src/Server/Protocol.php, 0.8.1<br>private const SESSION_OUTGOING_QUEUE = &#39;_mcp.outgoing_queue&#39;;<br> <br>private function sendResponse(TransportInterface $transport, Response|Error $response, ?SessionInterface $session, array $context = []): void<br>{<br>    if (null === $session) {<br>        // ... json_encode and $transport-&gt;send($encoded, $context);<br>    } else {<br>        $this-&gt;queueOutgoing($response, [&#39;type&#39; =&gt; &#39;response&#39;], $session);<br>    }<br>}<br> <br>private function queueOutgoing(Request|Notification|Response|Error $message, array $context, SessionInterface $session): void<br>{<br>    // ...<br>    $queue = $session-&gt;get(self::SESSION_OUTGOING_QUEUE, []);<br>    $queue[] = [&#39;message&#39; =&gt; $encoded, &#39;context&#39; =&gt; $context];<br>    $session-&gt;set(self::SESSION_OUTGOING_QUEUE, $queue);<br>}</pre><p>The transport then builds the HTTP response by reading the queue back, through Protocol::consumeOutgoingMessages(), which loads the session again, takes the whole queue, writes an empty queue and saves:</p><pre>// src/Server/Protocol.php, 0.8.1<br>public function consumeOutgoingMessages(Uuid $sessionId): array<br>{<br>    $session = $this-&gt;sessionManager-&gt;createWithId($sessionId);<br>    $queue = $session-&gt;get(self::SESSION_OUTGOING_QUEUE, []);<br>    $session-&gt;set(self::SESSION_OUTGOING_QUEUE, []);<br>    $session-&gt;save();<br> <br>    return $queue;<br>}</pre><pre>// src/Server/Transport/StreamableHttpTransport.php, 0.8.1, createJsonResponse()<br>$outgoingMessages = $this-&gt;getOutgoingMessages($this-&gt;sessionId);<br> <br>if (empty($outgoingMessages)) {<br>    return $this-&gt;responseFactory-&gt;createResponse(202)<br>        -&gt;withHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>}<br> <br>$messages = array_column($outgoingMessages, &#39;message&#39;);<br>$responseBody = 1 === \count($messages) ? $messages[0] : &#39;[&#39;.implode(&#39;,&#39;, $messages).&#39;]&#39;;</pre><p>Two more details complete the picture. Session::readData() 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 Session::save() in 0.8.1 is json_encode($this-&gt;readData()) written back whole, every key, not only the ones this request changed.</p><p>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.</p><h3>3. The race, step by step</h3><p>Take two workers, A and B, each handling one tools/call of the same session, with a shared FileSessionStore. Each step reads or writes the whole session blob.</p><ol><li>A loads the session. Queue: empty.</li><li>B loads the session. Queue: empty.</li><li>A’s handler returns. A appends response RA to its in-memory queue and saves. Store: [RA].</li><li>B’s handler returns. B appends RB to its own snapshot, which never saw RA, and saves. Store: [RB]. RA is gone. That is the lost update.</li><li>A’s transport calls consumeOutgoingMessages(). It loads the store fresh, takes [RB], writes []. A&#39;s HTTP response carries B&#39;s answer. That is the foreign answer.</li><li>B’s transport does the same. The queue is empty, so B answers 202 with no body. That is the empty response.</li></ol><p>Shift the timing a little and step 4 happens after step 5: B saves [RB] after A emptied the queue, then B&#39;s own consume takes it. Both correct, by luck. Shift it the other way and A&#39;s consume runs after both saves of a three-worker race: it takes [RB, RC] and the implode branch sends a JSON array, which a spec-compliant client rejects, because the spec requires &quot;a single JSON-RPC&quot; object in a JSON response. The TypeScript client reports the lost ones as MCP error -32001: Request timed out, which is what the n8n and LangChain users in the upstream issues saw.</p><p>There is a fourth outcome that is a race on the file rather than on the queue. FileSessionStore::write() in 0.8.1 writes to one temporary file per session, &lt;id&gt;.tmp, 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 JsonException: Syntax error thrown from Session::readData(): 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.</p><h3>4. Reproducing it</h3><p>The server is short. One tool, a file session store, the SDK’s Streamable HTTP transport over nyholm/psr7:</p><pre>&lt;?php<br>// server.php, run with: PHP_CLI_SERVER_WORKERS=8 php -S 127.0.0.1:8768 server.php<br>require getenv(&#39;SDK_DIR&#39;).&#39;/vendor/autoload.php&#39;;<br> <br>use Http\Discovery\Psr17Factory;<br>use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;<br>use Mcp\Server;<br>use Mcp\Server\Session\FileSessionStore;<br>use Mcp\Server\Transport\StreamableHttpTransport;<br>use Psr\Log\NullLogger;<br> <br>final class Tools<br>{<br>    public static function listSections(): array<br>    {<br>        return [&#39;sections&#39; =&gt; [[&#39;name&#39; =&gt; &#39;blog&#39;]]];<br>    }<br>}<br> <br>$server = Server::builder()<br>    -&gt;setServerInfo(&#39;race-test&#39;, &#39;1.0.0&#39;)<br>    -&gt;setLogger(new NullLogger())<br>    -&gt;addTool([Tools::class, &#39;listSections&#39;], &#39;list_sections&#39;)<br>    -&gt;setSession(new FileSessionStore(getenv(&#39;SESSION_DIR&#39;)))<br>    -&gt;build();<br> <br>$result = $server-&gt;run(new StreamableHttpTransport(<br>    (new Psr17Factory())-&gt;createServerRequestFromGlobals(),<br>    logger: new NullLogger(),<br>));<br>(new SapiEmitter())-&gt;emit($result);</pre><p>setSession() matters. Without it the 0.8.1 builder falls back to InMemorySessionStore, 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 404. 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.</p><p>The client is a Python script. It sends initialize, keeps the Mcp-Session-Id, sends notifications/initialized, then runs rounds of ten tools/call 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 202, and anything else.</p><p>One round of ten against 0.8.1 looked like this. Request c1 got its own answer. c0 got c7&#39;s, c3 and c7 both got c9&#39;s, c4, c8 and c9 got 202 with no body, and c2, c5 and c6 got an HTML fatal error page from the torn session file. One right answer in ten.</p><p>Over more rounds the numbers move with timing, so here is one run of each configuration rather than an average:</p><pre>8 workers, 10 parallel calls per round, FileSessionStore<br> <br>mcp/sdk  session lock     rounds  own    foreign  array  empty 202  fatal<br>-------  ---------------  ------  -----  -------  -----  ---------  -----<br>0.8.1    none                 30      3      280      2          4     11<br>0.8.1    none                100     46      897      9         43      5<br>0.9.0    none                 30    300        0      0          0      0<br>0.9.0    none                100  1,000        0      0          0      0<br>0.9.0    FileSessionLock      30    300        0      0          0      0<br>0.9.0    FileSessionLock     100  1,000        0      0          0      0</pre><p>The author of the upstream fix measured the same shape with a different tool, chr-hertel/mcp-concurrency-test, 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 symfony/mcp-bundle was &quot;1 call in 10 got a 202&quot;.</p><p>The lock rows are correct and slow. With FileSessionLock 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.</p><h3>5. What 0.9.0 changed</h3><p>The fix landed in three pull requests between 6 and 14 October 2026, all in 0.9.0.</p><p><strong>PR #535 took responses out of the session.</strong> Protocol::sendResponse() now hands every response to TransportInterface::send() with the session id in the context, and createJsonResponse() 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: send() now receives every response of a handler, and a batch gets several. A POST of only notifications or responses is answered 202 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.</p><p><strong>PR #572 made </strong><strong>Session::save() write only the keys the request changed</strong>, 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 save() 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.</p><p><strong>PR #584 added the opt-in per-session lock.</strong> Builder::setSessionLock() takes a SessionLockInterface. FileSessionLock uses flock() on one file per session next to FileSessionStore, for the workers of one machine. SymfonyLockSessionLock wraps a symfony/lock store, for sessions shared across machines through Redis or a database. Protocol 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 503 with a JSON-RPC error under its own id.</p><pre>$server = Server::builder()<br>    -&gt;setSession(new FileSessionStore(__DIR__.&#39;/sessions&#39;))<br>    -&gt;setSessionLock(new FileSessionLock(__DIR__.&#39;/sessions&#39;))<br>    -&gt;build();</pre><p>In symfony/mcp-bundle 0.15.0 the same thing is configuration: session.lock.enabled, session.lock.factory for a LockFactory service when the store is not file, session.lock.timeout (30 seconds) and session.lock.ttl (300 seconds). The bundle refuses a lock without a factory on any store but file.</p><p>For the production server the upgrade was symfony/mcp-bundle 0.14.1 to 0.15.0 and mcp/sdk 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: OAuthRequestMetaMiddleware is gone and the validated token comes from RequestContext::getAccessToken(), ids of requests the server sends to the client are UUIDs instead of integers, and TransportInterface::send() 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.</p><h3>6. What 0.10.0 changed, and what the spec changed</h3><p>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 Builder::setSession() is called&quot;. initialize is answered without Mcp-Session-Id, later requests run on an ephemeral session that is never stored, and GET and DELETE get 405. The old fallback to InMemorySessionStore, the one that produced 404s 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.</p><p>Two other 0.10.0 changes bear on this article. JSON-RPC batches are refused with -32600 and HTTP 400 on every protocol revision, including 2025-03-26, which required batch support. And PHP 8.2 is the minimum.</p><p>The protocol moved the same way. MCP revision 2026–07–28 removed protocol-level sessions and the Mcp-Session-Id header from the Streamable HTTP transport (SEP-2567), and removed the initialize handshake (SEP-2575). Every request carries its protocol version and client capabilities in _meta, and a server that needs state across calls hands the client an explicit handle as an ordinary tool argument. The SDK&#39;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.</p><h3>7. When you still want a session</h3><p>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:</p><ul><li><strong>Requests from the server to the client.</strong> 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.</li><li><strong>Server-initiated notifications.</strong> notifications/resources/updated for a subscription, or notifications/tools/list_changed, need a queue the GET stream can drain.</li><li><strong>Resumable streams.</strong> A client that lost its SSE connection can send Last-Event-ID and expect the server to replay what it missed, which means the server stored it.</li></ul><p>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.</p><p>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.</p><h3>8. A tools-only server with no session</h3><p>mattleads/agent-publishing-bundle exposes its publishing tools over MCP so an agent can draft, lint and submit articles. The decision in <a href="https://dev.to/mattleads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-81-260c">the article that introduced it</a> was to implement the protocol directly rather than depend on mcp/sdk while it was moving. The race is the other half of that decision. The server offers initialize, ping, tools/list and tools/call, acknowledges notifications, and that is the whole surface. No resources, no prompts, no server-initiated requests, so no session.</p><p>The transport is one Symfony controller:</p><pre>// agent-publishing-bundle, src/Mcp/McpController.php<br>public function endpoint(Request $request): Response<br>{<br>    // ...<br>    $headers = [&#39;MCP-Protocol-Version&#39; =&gt; McpServer::negotiate($request-&gt;headers-&gt;get(&#39;MCP-Protocol-Version&#39;))];<br> <br>    if ($request-&gt;isMethod(&#39;DELETE&#39;)) {<br>        return new Response(&#39;&#39;, Response::HTTP_NO_CONTENT, $headers);<br>    }<br>    if (!$request-&gt;isMethod(&#39;POST&#39;)) {<br>        return new JsonResponse([&#39;error&#39; =&gt; &#39;Send JSON-RPC messages with POST. This server does not open server-to-client streams.&#39;], Response::HTTP_METHOD_NOT_ALLOWED, $headers + [&#39;Allow&#39; =&gt; &#39;POST, DELETE&#39;]);<br>    }<br> <br>    // ... decode the body, resolve the API key from the Authorization header<br> <br>    $batch = array_is_list($payload);<br>    $messages = $batch ? $payload : [$payload];<br>    $responses = [];<br>    foreach ($messages as $message) {<br>        // ...<br>        $response = $this-&gt;server-&gt;handle($message, $key);<br>        if (null !== $response) {<br>            $responses[] = $response;<br>        }<br>    }<br> <br>    if ([] === $responses) {<br>        return new Response(&#39;&#39;, Response::HTTP_ACCEPTED, $headers);<br>    }<br> <br>    return new JsonResponse($batch ? $responses : $responses[0], Response::HTTP_OK, $headers);<br>}</pre><p>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. initialize answers without Mcp-Session-Id, so the client has nothing to send back and nothing to lose. GET answers 405, which the spec allows for a server &quot;that does not offer an SSE stream&quot;. DELETE answers 204, 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 tools/list is filtered by that key&#39;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 mcp/sdk 0.10.0.</p><p>McpServer::handle() returns null for a message without an id, which is how a notification becomes a 202. A batch answers only its requests. The bundle&#39;s functional test, tests/Functional/McpTest.php, drives the handshake, the version echo, a notifications/initialized with its empty 202, scope-filtered tool lists for an agent key and an editor key, the full agent loop from list_sections to submit_article, tool errors as results with isError, protocol errors with JSON-RPC codes, a batch, the GET 405 and the DELETE 204.</p><p>The same race script, pointed at the demo app on 8 workers with initialize and 10 parallel tools/call list_sections per round:</p><pre>agent-publishing-bundle 0.3.1 on Symfony 8.1, php -S,<br>8 workers, 10 parallel calls per round<br> <br>rounds  own    foreign  array  empty 202  fatal  time<br>------  -----  -------  -----  ---------  -----  -----<br>    30    300        0      0          0      0  0.8 s<br>   100  1,000        0      0          0      0  2.6 s</pre><p>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 php -S, not serialization.</p><p>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.</p><h3>Conclusion</h3><p>Each pattern here maps to a decision you make once per server.</p><ul><li><strong>Tools only, no server-initiated messages.</strong> Do not keep a session. Answer each POST from its own request, authenticate every request on its own, and send no Mcp-Session-Id. That is what mcp/sdk 0.10.0 does by default, what MCP 2026-07-28 made the only option, and what agent-publishing-bundle does on every revision it serves.</li><li><strong>Elicitation, sampling, subscriptions or resumable streams.</strong> Keep a session, use a store every worker can reach, and on mcp/sdk 0.9.0 or later turn on the per-session lock. Accept that one session&#39;s calls run in series.</li><li><strong>Still on </strong><strong>mcp/sdk 0.8.x behind php-fpm or FrankenPHP.</strong> 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.</li></ul><p>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.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/agent-publishing-bundle">https://github.com/mattleads/agent-publishing-bundle</a></p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890a07ecc8ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Kernel for Every Tenant: FrankenPHP Worker Mode for Database-per-Tenant Symfony 8.1]]></title>
            <link>https://medium.com/@MattLeads/one-kernel-for-every-tenant-frankenphp-worker-mode-for-database-per-tenant-symfony-8-1-42534e46c671?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/42534e46c671</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[frankenphp]]></category>
            <category><![CDATA[multitenancy]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:46:15 GMT</pubDate>
            <atom:updated>2026-11-17T08:54:14.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2 of the shared-deployment series: the database-per-tenant demo on FrankenPHP worker mode, with one open connection per tenant database in each worker and twelve times the throughput of php-fpm.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCjomqZ9Kd99vbrddmUm3w.png" /></figure><p>In <a href="https://dev.to/mattleads/stop-paying-for-idle-tenants-database-per-tenant-symfony-81-on-one-shared-deployment">part 1</a> 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.</p><p>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.</p><p>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.</p><h3>Prerequisites</h3><ul><li>The demo from part 1: <a href="https://github.com/mattleads/tenant-shared-demo">mattleads/tenant-shared-demo</a>, PHP 8.4, Symfony 8.1, Doctrine DBAL 4, PostgreSQL 16 and Redis 7 in Docker.</li><li>symfony/runtime 7.4 or later. It ships FrankenPhpWorkerRunner and detects worker mode on its own, so the separate runtime/frankenphp-symfony package is not needed. That package is still capped at Symfony 7 at the time of writing and will not install on 8.1.</li><li>FrankenPHP 1.13 from the dunglas/frankenphp:1-php8.4 image (PHP 8.4.27, Caddy 2.11), php:8.4-fpm-alpine and nginx:1.27-alpine-slim for the baseline, and wrk for the load.</li></ul><p>Everything below is in the same repository: docker/, compose.bench.yaml, scripts/bench.sh and bench/.</p><h3>1. What php-fpm throws away on every request</h3><p>Trace one GET /tenant_&lt;uuid&gt;/notes on the shared deployment of part 1:</p><ol><li>PHP starts, opcache hands over the compiled files, the kernel boots and the container is instantiated.</li><li>TenantRequestListener reads the prefix and asks PlacementReader 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 HGET on Redis per request.</li><li>The repository runs its query. TenantConnection::connect() opens a connection to tenant_&lt;uuid&gt; first: a TCP handshake, Postgres authentication, a backend process forked on the server.</li><li>The response goes out and the process forgets all of it.</li></ol><p>Step 3 is the one we measured in part 1 with app:bench:switch, the command that runs SELECT 1 three hundred times on one tenant and then three hundred times alternating tenants:</p><pre>300 queries on one tenant:              0.172 ms per query<br>300 queries switching tenant each time: 5.976 ms per query (299 reconnects)<br>cost of a tenant switch: 5.80 ms</pre><p>Under php-fpm nothing can be done about steps 1 to 3 except making each cheaper. Under a worker they can stop happening.</p><h3>2. FrankenPHP in one Dockerfile and three environment variables</h3><p>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.</p><pre># docker/frankenphp/Dockerfile<br>FROM dunglas/frankenphp:1-php8.4<br> <br>RUN install-php-extensions pdo_pgsql redis intl opcache zip<br>COPY --from=composer:2 /usr/bin/composer /usr/bin/composer<br>COPY docker/php/app.ini /usr/local/etc/php/conf.d/app.ini<br> <br>ENV APP_ENV=prod APP_DEBUG=0 SERVER_NAME=:80 SERVER_ROOT=/app/public<br>WORKDIR /app<br> <br>COPY composer.json composer.lock symfony.lock ./<br>RUN composer install --no-dev --no-scripts --no-progress --prefer-dist --no-autoloader<br>COPY . .<br>RUN composer dump-autoload --no-dev --classmap-authoritative \<br> &amp;&amp; bin/console cache:warmup --no-interaction \<br> &amp;&amp; chown -R www-data:www-data var</pre><p>The image ships a Caddyfile that reads its site block from SERVER_NAME and SERVER_ROOT, and its FrankenPHP block from FRANKENPHP_CONFIG. Classic mode:</p><pre>FRANKENPHP_CONFIG: num_threads 8</pre><p>Worker mode, eight workers running public/index.php:</p><pre>FRANKENPHP_CONFIG: |<br>  num_threads 8<br>  worker ./public/index.php 8</pre><p>Nothing in public/index.php changes. Since symfony/runtime 7.4, SymfonyRuntime::getRunner() checks the FRANKENPHP_WORKER variable that FrankenPHP sets inside a worker and returns a FrankenPhpWorkerRunner. That runner is short enough to read in full, and you should, because it decides what your application sees between requests:</p><ul><li>It calls frankenphp_handle_request() in a loop. For each request it builds a Request from globals, calls $kernel-&gt;handle(), sends the response, then calls $kernel-&gt;terminate().</li><li>After each request it drops its references to the request and response and runs gc_collect_cycles().</li><li>It stops after FRANKENPHP_LOOP_MAX requests, 500 by default, and FrankenPHP starts a fresh worker. A slow leak is bounded by that number.</li><li>With FRANKENPHP_RESET_KERNEL=1 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.</li></ul><p>$_SERVER[&#39;APP_RUNTIME_MODE&#39;] tells the application how it runs: web=1 under php-fpm or classic FrankenPHP, web=1&amp;worker=1 inside a worker. The demo&#39;s /whoami prints it.</p><h3>3. What survives a request, and what must not</h3><p>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.</p><p><strong>The tenant itself.</strong> TenantContext is static. It is set by TenantRequestListener on kernel.request and cleared on kernel.terminate. The worker runner calls terminate() 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.</p><p><strong>Open transactions.</strong> A controller that throws between `beginTransaction()` and `commit()` 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 `kernel.reset` 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 `TenantConnection`. The demo rolls back on `kernel.terminate`, next to the tenant clear, and logs a warning naming the request that left it open. `TwoTenantIsolationTest` 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.</p><p><strong>Services reset by the kernel.</strong> Symfony resets tagged services before it handles the next request. Kernel::boot() checks a resetServices flag set by the previous handle() and calls services_resetter, which runs every kernel.reset method: the entity manager clears its identity map, the Doctrine connection does nothing, loggers flush, and the part 1 cache decorator TenantAwareCache::reset() drops its per-tenant sub-pools. That decorator inherited the kernel.reset tag from cache.app 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.</p><p><strong>The placement cache.</strong> PlacementReader 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&#39;s app:tenant:place 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.</p><p><strong>The database connection.</strong> This is the one we want to survive. TenantConnection 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.</p><p><strong>Static counters, singletons, memoized lookups.</strong> 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 static $cache 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.</p><h3>4. Keep one connection per tenant database</h3><p>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 DATABASE_URL, so a php-fpm deployment and a worker deployment can run the same image with different settings:</p><pre>DATABASE_URL=postgresql://app:app@database:5432/app?serverVersion=16&amp;charset=utf8&amp;tenantConnections=16</pre><p>DoctrineBundle merges every query parameter of the URL into the connection parameters, so the wrapper reads it from getParams():</p><pre>// src/Tenant/TenantConnection.php<br>class TenantConnection extends Connection<br>{<br>    private ?string $connectedTo = null;<br> <br>    /** @var array&lt;string, DriverConnection&gt; Open connections of other tenants, least recently used first. */<br>    private array $parked = [];<br> <br>    /** How many times this connection opened a driver connection, for the benchmark and /whoami. */<br>    public static int $connects = 0;<br> <br>    protected function connect(): DriverConnection<br>    {<br>        $params = $this-&gt;getParams();<br>        $target = $this-&gt;databaseFor($params[&#39;dbname&#39;] ?? null);<br> <br>        if ($this-&gt;_conn !== null) {<br>            if ($target === $this-&gt;connectedTo) {<br>                return $this-&gt;_conn;<br>            }<br>            if ($this-&gt;isTransactionActive()) {<br>                throw new \LogicException(sprintf(&#39;Tenant changed to %s inside a database transaction&#39;, TenantContext::current()-&gt;uuid));<br>            }<br>        }<br> <br>        // take the target out before parking the current one, so it cannot be the one dropped over the limit<br>        $resumed = $this-&gt;parked[$target] ?? null;<br>        unset($this-&gt;parked[$target]);<br>        if ($this-&gt;_conn !== null) {<br>            $this-&gt;park($params);<br>        }<br> <br>        if ($resumed !== null) {<br>            $connection = $this-&gt;_conn = $resumed;<br>        } else {<br>            try {<br>                $connection = $this-&gt;_conn = $this-&gt;driver-&gt;connect([&#39;dbname&#39; =&gt; $target] + $params);<br>            } catch (Driver\Exception $e) {<br>                throw $this-&gt;convertException($e);<br>            }<br>            ++self::$connects;<br>        }<br>        $this-&gt;connectedTo = $target;<br> <br>        if (!$this-&gt;isAutoCommit()) {<br>            $this-&gt;beginTransaction();<br>        }<br> <br>        return $connection;<br>    }<br> <br>    /** Keep the current connection for its tenant&#39;s next turn, dropping the least recently used one over the limit. */<br>    private function park(array $params): void<br>    {<br>        $keep = max(1, (int) ($params[&#39;tenantConnections&#39;] ?? 1)) - 1;<br>        if ($keep &gt; 0 &amp;&amp; $this-&gt;connectedTo !== null) {<br>            $this-&gt;parked[$this-&gt;connectedTo] = $this-&gt;_conn;<br>            while (count($this-&gt;parked) &gt; $keep) {<br>                unset($this-&gt;parked[array_key_first($this-&gt;parked)]);<br>            }<br>        }<br>        $this-&gt;_conn = null;<br>        $this-&gt;connectedTo = null;<br>    }</pre><p>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 tenantConnections=16 keeps the sixteen it saw most recently, and dropping one is a plain unset: PDO closes the connection in its destructor. The transaction guard is unchanged, a switch inside a transaction is still refused, kept connections or not.</p><p>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.</p><p>The CLI benchmark from part 1 with the parameter set:</p><pre>300 queries on one tenant:              0.154 ms per query<br>300 queries switching tenant each time: 0.160 ms per query (2 reconnects)<br>cost of a tenant switch: 0.01 ms</pre><p>Two reconnects for three tenants: the first was already connected. The switch went from 5.80 milliseconds to the cost of an array lookup.</p><p>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 tenantConnections from max_connections on the server, not from the number of tenants, and put PgBouncer in session mode in front if the sum across placements gets close.</p><p>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 DATABASE_URL too.</p><h3>5. Watching a worker switch tenant</h3><p>/whoami 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:</p><pre>{&quot;tenant&quot;:&quot;11111111-…&quot;,&quot;runtime&quot;:&quot;web=1&amp;worker=1&quot;,&quot;connects&quot;:13,&quot;open&quot;:[&quot;tenant_11111111_…&quot;]}</pre><p>The same against worker mode with tenantConnections=16:</p><pre>{&quot;tenant&quot;:&quot;11111111-…&quot;,&quot;runtime&quot;:&quot;web=1&amp;worker=1&quot;,&quot;connects&quot;:3,&quot;open&quot;:[&quot;tenant_22222222_…&quot;,&quot;tenant_33333333_…&quot;,&quot;tenant_11111111_…&quot;]}</pre><p>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 pid is 1 in every answer, and PHP statics such as $connects are per thread. Each worker thread counts its own connections.</p><h3>6. The benchmark: four deployments, a tenant switch on every request</h3><p>compose.bench.yaml 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:</p><pre>name                    serves PHP with                                     tenant connections kept<br>----------------------  --------------------------------------------------  -----------------------<br>fpm-nginx               php-fpm 8.4, pm = static, 8 children, behind nginx  1<br>frankenphp              FrankenPHP classic mode, 8 threads                  1<br>frankenphp-worker       FrankenPHP worker mode, 8 workers                   1<br>frankenphp-worker-keep  FrankenPHP worker mode, 8 workers                   16</pre><p>scripts/bench.sh gives every tenant 20 notes, warms each deployment for 10 seconds and then runs wrk for 20 seconds with 4 threads and 32 connections. The Lua script sends GET /tenant_&lt;uuid&gt;/notes 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.</p><pre>deployment              requests/s  avg latency  p50       p99        max<br>----------------------  ----------  -----------  --------  ---------  ---------<br>fpm-nginx               690         46.28 ms     45.44 ms  70.09 ms   81.35 ms<br>frankenphp (classic)    366         87.06 ms     90.30 ms  113.40 ms  153.72 ms<br>frankenphp-worker       553         57.70 ms     64.33 ms  88.14 ms   280.13 ms<br>frankenphp-worker-keep  8,521       3.86 ms      3.38 ms   10.65 ms   41.41 ms</pre><pre>deployment              DB connections opened  container RSS<br>----------------------  ---------------------  -------------<br>fpm-nginx               13,892                 41.6 MiB<br>frankenphp (classic)    7,383                  78.0 MiB<br>frankenphp-worker       7,771                  68.7 MiB<br>frankenphp-worker-keep  1,026                  75.4 MiB</pre><p>20 seconds each, no errors in any row. “DB connections opened” is what Postgres counted in pg_stat_database.sessions for the three tenant databases during the measured run, not what PHP believes. The full output of each run is in bench/ and the table is bench/results-2026-11-12-sslmode-prefer.md.</p><p>Read the tables 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 FRANKENPHP_LOOP_MAX: 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.</p><p>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.</p><p>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.</p><h3>A trap I did not expect: concurrent connects inside one process</h3><p>The classic FrankenPHP row is slower than php-fpm on this page, which it is not on a page without a database: on /health 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 new PDO(...) 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.</p><p>Something between pdo_pgsql and libpq 17 serializes connection setup across the threads of one process. It is not SSL negotiation, not GSS negotiation and not name resolution: sslmode=disable, gssencmode=disable 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 tenantConnections 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.</p><p>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.</p><h3>7. Testing it</h3><p>Two tests, both against the real Postgres of the demo. TenantConnectionKeepTest builds a TenantConnection straight from DATABASE_URL with tenantConnections set and walks it through tenants:</p><pre>// tests/TenantConnectionKeepTest.php (abridged)<br>public function testKeptConnectionsAreReusedAndTheLeastRecentlyUsedIsDropped(): void<br>{<br>    $connection = $this-&gt;connection(2);<br>    $before = TenantConnection::$connects;<br> <br>    $this-&gt;query($connection, self::A);<br>    $this-&gt;query($connection, self::B);<br>    $this-&gt;query($connection, self::A);<br>    self::assertSame(2, TenantConnection::$connects - $before, &#39;A came back from the parked connection&#39;);<br>    self::assertSame([$this-&gt;db(self::B), $this-&gt;db(self::A)], $connection-&gt;open());<br> <br>    $this-&gt;query($connection, self::C);<br>    self::assertSame(3, TenantConnection::$connects - $before);<br>    self::assertSame([$this-&gt;db(self::A), $this-&gt;db(self::C)], $connection-&gt;open(), &#39;B was the least recently used&#39;);<br>}</pre><p>A third case begins a transaction on one tenant, switches, and expects the LogicException.</p><p>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.</p><h3>8. Deploying it</h3><ul><li><strong>One image, two modes.</strong> FRANKENPHP_CONFIG decides between classic and worker mode, TENANT_MODE between dedicated and shared. The dedicated deployments of paying tenants can run the same image in worker mode with tenantConnections=1; they never switch.</li><li><strong>Workers and connections.</strong> Start with num_threads equal to the CPUs you give the container and the same number of workers. tenantConnections times workers is the number of Postgres backends one container can hold open; check max_connections before raising it.</li><li><strong>Health and restarts.</strong> /health is open on both modes and answers from a worker, so a wedged worker fails the check. FRANKENPHP_LOOP_MAX 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.</li><li><strong>Messenger workers</strong> are unchanged. They were already long-lived, and they take the same tenantConnections parameter.</li><li><strong>Do not do this</strong> 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.</li></ul><h3>Conclusion</h3><ul><li>Worker mode turns the per-request cost of a shared deployment into a per-switch cost, and tenantConnections 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.</li><li>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.</li><li>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.</li></ul><p>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 tenantConnections when /whoami shows connects climbing with requests.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/tenant-shared-demo">https://github.com/mattleads/tenant-shared-demo</a></p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42534e46c671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Paying for Idle Tenants: Database-per-Tenant Symfony 8.1 on One Shared Deployment]]></title>
            <link>https://medium.com/@MattLeads/stop-paying-for-idle-tenants-database-per-tenant-symfony-8-1-on-one-shared-deployment-4892d9a672c7?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4892d9a672c7</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 16:39:59 GMT</pubDate>
            <atom:updated>2026-11-12T16:39:59.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keep a database per tenant and drop the deployment per tenant. The connection, cache and Messenger workers follow the tenant, with no change to controllers or handlers.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGFscmHIoS0swe7ttH92BA.png" /></figure><p>Database-per-tenant is the safe way to build a B2B SaaS on Symfony. Every workspace gets its own PostgreSQL database, its own queue and its own bucket, so a missing WHERE tenant_id = ? cannot leak anything and a big customer can be moved to a bigger server by changing a DSN. The usual price is a deployment per tenant: a php-fpm pool, a couple of Messenger workers and a scheduler, always on, whether the tenant is used or not.</p><p>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.</p><p>The standard fixes trade the isolation away. Merging everything into one database with a tenant_id column means a data migration for every table and a leak waiting for every forgotten filter. A schema per tenant keeps the data apart but needs a search_path per connection, which breaks behind a transaction pooler and still runs N migrations.</p><p>This article takes the third road: <strong>keep a database per tenant, share the processes.</strong> 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.</p><p>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.</p><h3>Prerequisites</h3><ul><li>PHP 8.4, Symfony 8.1 (everything here works from 7.3, which introduced cache sub-namespaces), Doctrine ORM 3 with DBAL 4.</li><li>PostgreSQL 16 and Redis 7 (Docker is enough), symfony/redis-messenger for the tenant streams and symfony/doctrine-messenger for the failure transport.</li></ul><h3>1. The tenant and where the code reads it</h3><p>Everything that used to come from a dedicated deployment’s environment is derived from one uuid:</p><pre>// src/Tenant/Tenant.php<br>final readonly class Tenant<br>{<br>    public string $uuid;<br> <br>    public function __construct(string $uuid)<br>    {<br>        if (!UuidV4::isValid($uuid)) {<br>            throw new \InvalidArgumentException(sprintf(&#39;&quot;%s&quot; is not a tenant uuid&#39;, mb_substr($uuid, 0, 60)));<br>        }<br>        $this-&gt;uuid = strtolower($uuid);<br>    }<br> <br>    public function dbName(): string         { return &#39;tenant_&#39;.str_replace(&#39;-&#39;, &#39;_&#39;, $this-&gt;uuid); }<br>    public function cacheNamespace(): string { return &#39;t_&#39;.$this-&gt;uuid; }<br>    public function stream(string $suffix = &#39;&#39;): string { return &#39;tenant-&#39;.$this-&gt;uuid.$suffix; }<br>    public function pathPrefix(): string     { return &#39;tenant_&#39;.$this-&gt;uuid; }<br>}</pre><p>The current tenant lives in a static holder:</p><pre>// src/Tenant/TenantContext.php<br>final class TenantContext<br>{<br>    private static ?Tenant $default = null;<br>    private static ?Tenant $current = null;<br> <br>    public static function current(): Tenant<br>    {<br>        return self::$current ?? self::$default<br>            ?? throw new NoTenantException(&#39;No tenant is set for this request or message&#39;);<br>    }<br> <br>    public static function isDefault(Tenant $tenant): bool<br>    {<br>        return self::$default !== null &amp;&amp; self::$default-&gt;uuid === $tenant-&gt;uuid;<br>    }<br> <br>    public static function set(Tenant $tenant): void { self::$current = $tenant; }<br>    public static function clear(): void             { self::$current = null; }<br>    public static function setDefault(?Tenant $tenant): void { self::$default = $tenant; }<br>}</pre><p>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.</p><p>Which brings us to the one rule everything else depends on. <strong>Read the tenant at call time, never in a constructor and never into a property.</strong> A worker keeps its services alive across messages and in shared mode consecutive messages belong to different tenants. In the production codebase this rule is a unit test that scans src/ for constructors touching the tenant.</p><p>The $default slot is what makes the dedicated deployment work unchanged. current() never falls back to &quot;some&quot; tenant: on a shared deployment with nothing set, it throws. A request that reaches tenant data without a tenant is a bug and a loud NoTenantException is cheaper than a quiet row in the wrong database.</p><h3>2. Two modes, one codebase</h3><pre># .env<br>TENANT_MODE=single      # dedicated: this deployment is one tenant<br>TENANT_UUID=            # that tenant<br>TENANT_PLACEMENT=shared-1   # shared: which placement this deployment serves</pre><p>The kernel sets the default at boot:</p><pre>// src/Kernel.php<br>public function boot(): void<br>{<br>    parent::boot();<br> <br>    SingleTenantResolver::boot(<br>        (string) ($_SERVER[&#39;TENANT_MODE&#39;] ?? $_ENV[&#39;TENANT_MODE&#39;] ?? &#39;single&#39;),<br>        (string) ($_SERVER[&#39;TENANT_UUID&#39;] ?? $_ENV[&#39;TENANT_UUID&#39;] ?? &#39;&#39;),<br>    );<br>}</pre><p>SingleTenantResolver::boot() calls TenantContext::setDefault(new Tenant($uuid)) in single mode and setDefault(null) in multi mode. It is the only class that reads TENANT_UUID. A dedicated deployment therefore runs every request, command and message for its own tenant, exactly as it did before this work. A shared deployment has no default and must be told the tenant each time.</p><h3>3. HTTP: the tenant is the path prefix</h3><p>A shared deployment addresses a tenant as /tenant_&lt;uuid&gt;/…. The obvious implementation is a route prefix and it is the wrong one: every path() call in Twig and every generateUrl() would need the tenant parameter. Symfony already has a mechanism for &quot;this app lives under a sub-directory&quot;: the request&#39;s <strong>base URL</strong>. Make the prefix the base URL and routing sees the path without it while every generated URL keeps it.</p><pre>// src/Tenant/TenantPathPrefix.php<br>final class TenantPathPrefix<br>{<br>    public const string ATTRIBUTE = &#39;_tenant_prefix&#39;;<br>    private const string PATTERN = &#39;#^/tenant_([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?:/|$)#i&#39;;<br> <br>    public static function rebase(Request $request): ?Request<br>    {<br>        if (!preg_match(self::PATTERN, rawurldecode($request-&gt;getPathInfo()), $match) || $request-&gt;getBaseUrl() !== &#39;&#39;) {<br>            return null;<br>        }<br>        $uuid = strtolower($match[1]);<br>        $server = $request-&gt;server-&gt;all();<br>        $server[&#39;SCRIPT_NAME&#39;] = $server[&#39;PHP_SELF&#39;] = &#39;/tenant_&#39;.$uuid.&#39;/index.php&#39;;<br>        $server[&#39;SCRIPT_FILENAME&#39;] = ($server[&#39;SCRIPT_FILENAME&#39;] ?? &#39;&#39;) !== &#39;&#39; ? $server[&#39;SCRIPT_FILENAME&#39;] : &#39;index.php&#39;;<br> <br>        $rebased = $request-&gt;duplicate(server: $server);<br>        $rebased-&gt;attributes-&gt;set(self::ATTRIBUTE, $uuid);<br> <br>        return $rebased;<br>    }<br>}</pre><p>Request::getBaseUrl() derives the base from SCRIPT_NAME, so rewriting SCRIPT_NAME to /tenant_&lt;uuid&gt;/index.php is all it takes. The kernel applies it before anything else sees the request:</p><pre>// src/Kernel.php<br>public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response<br>{<br>    if ($type === self::MAIN_REQUEST) {<br>        $request = TenantPathPrefix::rebase($request) ?? $request;<br>    }<br> <br>    return parent::handle($request, $type, $catch);<br>}</pre><p>A listener at priority 2048, ahead of the firewall, turns the prefix into the tenant:</p><pre>// src/Tenant/TenantRequestListener.php<br>#[AsEventListener(event: KernelEvents::REQUEST, priority: 2048)]<br>public function onRequest(RequestEvent $event): void<br>{<br>    if (!$event-&gt;isMainRequest()) {<br>        return;<br>    }<br>    $request = $event-&gt;getRequest();<br>    $prefix = $request-&gt;attributes-&gt;get(TenantPathPrefix::ATTRIBUTE);<br> <br>    if ($this-&gt;mode === TenantMode::Single) {<br>        if (is_string($prefix) &amp;&amp; (!TenantContext::has() || TenantContext::current()-&gt;uuid !== $prefix)) {<br>            throw new NotFoundHttpException(&#39;No such tenant here&#39;);<br>        }<br> <br>        return;<br>    }<br> <br>    TenantContext::clear();<br>    if (!is_string($prefix)) {<br>        if (preg_match(&#39;#^/health(/|$)#&#39;, $request-&gt;getPathInfo())) {<br>            return;<br>        }<br>        throw new NotFoundHttpException(&#39;No tenant in the path&#39;);<br>    }<br>    TenantContext::set($this-&gt;resolver-&gt;resolve($prefix));<br>}<br> <br>#[AsEventListener(event: KernelEvents::TERMINATE)]<br>public function onTerminate(TerminateEvent $event): void<br>{<br>    TenantContext::clear();<br>}</pre><p>The rules are deliberately strict. On a dedicated deployment a prefix naming another tenant is a 404; a request without a prefix is fine, because its ingress strips it. On a shared deployment a request without a prefix is a 404 unless it is the health check and MultiTenantResolver answers 404 for a tenant that is not placed here. The resolver has no fallback branch.</p><p>Run the demo and ask the shared instance who it is for two tenants:</p><pre>$ curl -s http://127.0.0.1:8770/tenant_11111111-…/whoami<br>{&quot;tenant&quot;:&quot;11111111-…&quot;,&quot;database&quot;:&quot;tenant_11111111_1111_4111_8111_111111111111&quot;,&quot;basePath&quot;:&quot;/tenant_11111111-…&quot;,&quot;notesUrl&quot;:&quot;/tenant_11111111-…/notes&quot;}<br> <br>$ curl -s http://127.0.0.1:8770/tenant_22222222-…/whoami<br>{&quot;tenant&quot;:&quot;22222222-…&quot;,&quot;database&quot;:&quot;tenant_22222222_2222_4222_8222_222222222222&quot;,&quot;basePath&quot;:&quot;/tenant_22222222-…&quot;,&quot;notesUrl&quot;:&quot;/tenant_22222222-…/notes&quot;}</pre><p>Same process, same controller, no route parameter. notesUrl comes from generateUrl(&#39;notes_list&#39;) and carries the prefix because it is the base path. The database field is the next section.</p><h3>4. The database follows the tenant</h3><p>Doctrine’s DBAL has a wrapper_class option: your own subclass of Doctrine\DBAL\Connection, used for the connection service. DBAL calls connect() before every query, which gives us one place to pick the database:</p><pre>// src/Tenant/TenantConnection.php<br>class TenantConnection extends Connection<br>{<br>    private ?string $connectedTo = null;<br> <br>    protected function connect(): DriverConnection<br>    {<br>        $params = $this-&gt;getParams();<br>        $target = $this-&gt;databaseFor($params[&#39;dbname&#39;] ?? null);<br> <br>        if ($this-&gt;_conn !== null) {<br>            if ($target === $this-&gt;connectedTo) {<br>                return $this-&gt;_conn;<br>            }<br>            if ($this-&gt;isTransactionActive()) {<br>                throw new \LogicException(sprintf(&#39;Tenant changed to %s inside a database transaction&#39;, TenantContext::current()-&gt;uuid));<br>            }<br>            $this-&gt;close();<br>        }<br> <br>        $params[&#39;dbname&#39;] = $target;<br>        try {<br>            $connection = $this-&gt;_conn = $this-&gt;driver-&gt;connect($params);<br>        } catch (Driver\Exception $e) {<br>            throw $this-&gt;convertException($e);<br>        }<br>        $this-&gt;connectedTo = $target;<br> <br>        if (!$this-&gt;isAutoCommit()) {<br>            $this-&gt;beginTransaction();<br>        }<br> <br>        return $connection;<br>    }<br> <br>    private function databaseFor(?string $configured): ?string<br>    {<br>        $tenant = TenantContext::current();<br> <br>        return TenantContext::isDefault($tenant) ? $configured : $tenant-&gt;dbName();<br>    }<br>}</pre><pre># config/packages/doctrine.yaml<br>doctrine:<br>    dbal:<br>        url: &#39;%env(resolve:DATABASE_URL)%&#39;<br>        wrapper_class: App\Tenant\TenantConnection</pre><p>Three things matter here.</p><p><strong>The dedicated deployment is untouched.</strong> Its own tenant is the default, so databaseFor() returns the configured dbname from DATABASE_URL. Any other tenant gets tenant_&lt;uuid&gt; on the same server.</p><p><strong>A tenant change inside a transaction is a bug, so it throws.</strong> 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.</p><p><strong>There is one EntityManager.</strong> 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.</p><p>Post a note to each tenant and read them back:</p><pre>$ curl -s -X POST -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;body&quot;:&quot;hello from A&quot;}&#39; http://127.0.0.1:8770/tenant_1111…/notes<br>$ curl -s -X POST -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;body&quot;:&quot;hello from B&quot;}&#39; http://127.0.0.1:8770/tenant_2222…/notes<br> <br>$ curl -s http://127.0.0.1:8770/tenant_1111…/notes<br>[{&quot;id&quot;:2,&quot;body&quot;:&quot;hello from A&quot;,&quot;processedAt&quot;:&quot;2026-11-09T20:36:49+00:00&quot;,&quot;processedBy&quot;:&quot;MacBookPro16.local:95790&quot;}]<br>$ curl -s http://127.0.0.1:8770/tenant_2222…/notes<br>[{&quot;id&quot;:1,&quot;body&quot;:&quot;hello from B&quot;,&quot;processedAt&quot;:&quot;2026-11-09T20:36:49+00:00&quot;,&quot;processedBy&quot;:&quot;MacBookPro16.local:95790&quot;}]</pre><p>The ids overlap because the rows live in different databases. processedBy is the same worker pid for both and that worker is the subject of section 6.</p><h3>5. The cache follows the tenant</h3><p>Application caches hold tenant data: computed stats, rendered fragments, the scheduler’s last-run state. Since Symfony 7.3 every cache adapter implements NamespacedPoolInterface, so a decorator can hand each tenant a sub-namespace of the same pool:</p><pre>// src/Tenant/TenantAwareCache.php<br>final class TenantAwareCache implements AdapterInterface, CacheInterface, NamespacedPoolInterface, ResettableInterface<br>{<br>    /** @var array&lt;string, AdapterInterface&amp;CacheInterface&amp;NamespacedPoolInterface&gt; */<br>    private array $byTenant = [];<br> <br>    public function __construct(private readonly AdapterInterface&amp;CacheInterface&amp;NamespacedPoolInterface $inner)<br>    {<br>    }<br> <br>    private function pool(): AdapterInterface<br>    {<br>        $tenant = TenantContext::current();<br>        if (TenantContext::isDefault($tenant)) {<br>            return $this-&gt;inner;<br>        }<br> <br>        return $this-&gt;byTenant[$tenant-&gt;uuid] ??= $this-&gt;inner-&gt;withSubNamespace($tenant-&gt;cacheNamespace());<br>    }<br> <br>    public function get(string $key, callable $callback, ?float $beta = null, ?array &amp;$metadata = null): mixed<br>    {<br>        return $this-&gt;pool()-&gt;get($key, $callback, $beta, $metadata);<br>    }<br> <br>    // getItem(), save(), deleteItem(), … all delegate to $this-&gt;pool()<br> <br>    public function reset(): void<br>    {<br>        foreach ([$this-&gt;inner, ...array_values($this-&gt;byTenant)] as $pool) {<br>            if ($pool instanceof ResettableInterface) {<br>                $pool-&gt;reset();<br>            }<br>        }<br>        $this-&gt;byTenant = [];<br>    }<br>}</pre><pre># config/services.yaml<br>services:<br>    App\Tenant\TenantAwareCache:<br>        decorates: cache.app<br>        arguments: [&#39;@.inner&#39;]</pre><p>Again the dedicated deployment’s keys do not change, so its caches stay warm through the deploy that introduces this.</p><p>One trap with tag-aware pools. Symfony stores tags in the pool’s <strong>root</strong> namespace, shared by every sub-namespace. If tenant A invalidates the tag product_list, it drops tenant B&#39;s product_list entries too. Prefix the tags with the tenant namespace as well as the keys. The demo&#39;s pool has no tags; the production one does and this is where its decorator differs from the one above.</p><p>Caches that are platform-wide by design, such as a revoked-tokens list that other services write, must <strong>not</strong> be decorated. Decide per pool and write the decision down next to the pool.</p><h3>6. Workers: one process, every tenant’s stream</h3><p>This is where most multitenancy write-ups stop and where most of the cost sits. A dedicated deployment runs its own messenger:consume processes against its own Redis stream. We want a shared worker to read every placed tenant&#39;s stream, without changing the senders: other services push into tenant-&lt;uuid&gt; streams today and they should keep doing exactly that.</p><p>The transport keeps its <strong>name</strong>. Only its DSN changes with the mode:</p><pre># config/packages/messenger.yaml<br>framework:<br>    messenger:<br>        failure_transport: failed<br>        transports:<br>            async:<br>                dsn: &#39;%env(MESSENGER_TRANSPORT_DSN)%&#39;   # redis://…/tenant-&lt;uuid&gt; or tenant-multi://…?kind=main<br>                options: { consumer: &#39;%env(MESSENGER_CONSUMER_NAME)%&#39;, redeliver_timeout: 300, claim_interval: 30000 }<br>                retry_strategy: { max_retries: 2, delay: 1000 }<br>            failed: &#39;doctrine://default?queue_name=failed&#39;<br>        routing:<br>            &#39;App\Message\NoteCreated&#39;: async<br>            &#39;App\Message\SlowJob&#39;: async</pre><p>Routing, #[AsMessageHandler(fromTransport: &#39;async&#39;)] and the messenger:consume async command line are identical in both modes. A custom transport factory claims the tenant-multi:// scheme and builds this:</p><pre>// src/Tenant/Messenger/MultiTenantTransport.php (abridged)<br>final class MultiTenantTransport implements TransportInterface, KeepaliveReceiverInterface, MessageCountAwareInterface<br>{<br>    /** @var array&lt;string, array{RedisReceiver, RedisSender}&gt; */<br>    private array $byTenant = [];<br>    private ?\Redis $redis = null;<br>    private int $next = 0;<br> <br>    public function get(int $fetchSize = 1): iterable<br>    {<br>        $tenants = $this-&gt;placement-&gt;tenants();<br>        $count = count($tenants);<br>        for ($i = 0; $i &lt; $count; ++$i) {<br>            $uuid = $tenants[($this-&gt;next + $i) % $count];<br>            if ($this-&gt;fairUse !== null &amp;&amp; !$this-&gt;fairUse-&gt;canTake($uuid, $this-&gt;kind)) {<br>                continue;<br>            }<br>            foreach ($this-&gt;receiver($uuid)-&gt;get() as $envelope) {<br>                $this-&gt;next = ($this-&gt;next + $i + 1) % $count;<br>                $this-&gt;fairUse?-&gt;took($uuid, $this-&gt;kind);<br> <br>                return [$envelope-&gt;withoutAll(TenantStamp::class)-&gt;with(new TenantStamp($uuid))];<br>            }<br>        }<br> <br>        return [];<br>    }<br> <br>    public function ack(Envelope $envelope): void<br>    {<br>        $uuid = $this-&gt;tenantOf($envelope);<br>        try {<br>            $this-&gt;receiver($uuid)-&gt;ack($envelope);<br>        } finally {<br>            $this-&gt;fairUse?-&gt;done($uuid, $this-&gt;kind);<br>        }<br>    }<br> <br>    public function send(Envelope $envelope): Envelope<br>    {<br>        $uuid = $envelope-&gt;last(TenantStamp::class)?-&gt;tenant ?? TenantContext::current()-&gt;uuid;<br> <br>        return $this-&gt;pair($uuid)[1]-&gt;send($envelope-&gt;withoutAll(TenantStamp::class));<br>    }<br> <br>    private function pair(string $uuid): array<br>    {<br>        if (!isset($this-&gt;byTenant[$uuid])) {<br>            $dsn = rtrim($this-&gt;redisDsn, &#39;/&#39;).&#39;/&#39;.$this-&gt;streamFor($uuid);<br>            $connection = Connection::fromDsn($dsn, $this-&gt;options, $this-&gt;redis ??= new \Redis());<br>            $this-&gt;byTenant[$uuid] = [new RedisReceiver($connection, $this-&gt;serializer), new RedisSender($connection, $this-&gt;serializer)];<br>        }<br> <br>        return $this-&gt;byTenant[$uuid];<br>    }<br>}</pre><p>Three decisions and why.</p><p><strong>Reuse Symfony’s </strong><strong>RedisReceiver per tenant instead of writing a multi-stream </strong><strong>XREADGROUP.</strong> 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.</p><p><strong>Rotate the starting tenant.</strong> $this-&gt;next moves past the tenant that just delivered, so a tenant with a deep backlog cannot starve the others out of a worker that polls in order.</p><p><strong>Stamp the tenant from the stream name, nowhere else.</strong> The stream a message came from is the one trustworthy tenant id, because the sender chose it from the tenant’s uuid. TenantStamp is added on receive and stripped on send; it never crosses the wire.</p><p>The worker side is a listener on three Messenger events:</p><pre>// src/Tenant/Messenger/TenantWorkerListener.php<br>#[AsEventListener(priority: 1024)]<br>public function onReceived(WorkerMessageReceivedEvent $event): void<br>{<br>    $stamp = $event-&gt;getEnvelope()-&gt;last(TenantStamp::class);<br>    if ($stamp === null) {<br>        return;                                   // dedicated deployment: nothing to do<br>    }<br>    if ($this-&gt;last !== null &amp;&amp; $this-&gt;last !== $stamp-&gt;tenant) {<br>        $this-&gt;em-&gt;clear();                       // no entity of the previous tenant survives<br>    }<br>    $this-&gt;last = $stamp-&gt;tenant;<br>    TenantContext::set(new Tenant($stamp-&gt;tenant));<br>}<br> <br>#[AsEventListener(priority: -1024)]<br>public function onHandled(WorkerMessageHandledEvent $event): void { $this-&gt;leave($event-&gt;getEnvelope()); }<br> <br>#[AsEventListener(priority: -1024)]<br>public function onFailed(WorkerMessageFailedEvent $event): void { $this-&gt;leave($event-&gt;getEnvelope()); }</pre><p>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 <strong>that tenant’s</strong> stream and a failed message is written to <strong>that tenant’s</strong> messenger_messages table, because doctrine://default resolves through TenantConnection while the tenant is still set. The demo proves it with a job that always throws:</p><pre>$ curl -s -X POST -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;seconds&quot;:1,&quot;label&quot;:&quot;fail&quot;}&#39; http://127.0.0.1:8770/tenant_2222…/jobs<br>[warning] Error thrown while handling message App\Message\SlowJob. Sending for retry #1 using 900 ms delay.<br>[warning] Error thrown while handling message App\Message\SlowJob. Sending for retry #2 using 1906 ms delay.<br>[critical] Error thrown while handling message App\Message\SlowJob. Removing from transport after 2 retries.<br> <br>$ bin/console app:tenant:failed 22222222-… show<br>There are 2 messages pending in the failure transport.<br>  Id   Class                 Failed at             Error<br>  1    App\Message\SlowJob   2026-11-09 20:40:40   This job always fails, to show where failures land</pre><p>Tenant A’s database has no messenger_messages table at all, because nothing of A ever failed. app:tenant:failed is twelve lines: set the tenant, run Symfony&#39;s messenger:failed:show|retry|remove, clear the tenant.</p><h3>7. Fair use: a busy free tenant waits, the others do not</h3><p>Sharing workers means sharing a budget. Without a limit, one tenant’s automation that queues ten thousand messages holds every worker for an hour and the other ninety-nine tenants on the deployment notice. The rule we settled on is a cap per tenant and stream kind: at most TENANT_INFLIGHT_CAP messages of a tenant being handled at once across all shared workers. The rest wait on that tenant&#39;s own stream. Nothing is dropped, nothing fails and the paying tenants are on dedicated deployments anyway.</p><pre>// src/Tenant/Messenger/FairUse.php (abridged)<br>public function canTake(string $tenant, string $kind): bool<br>{<br>    return (int) $this-&gt;redis()-&gt;get($this-&gt;key($tenant, $kind)) &lt; $this-&gt;cap;<br>}<br> <br>public function took(string $tenant, string $kind): void<br>{<br>    $key = $this-&gt;key($tenant, $kind);<br>    $this-&gt;redis()-&gt;incr($key);<br>    $this-&gt;redis()-&gt;expire($key, 180);<br>}<br> <br>public function done(string $tenant, string $kind): void<br>{<br>    if ($this-&gt;redis()-&gt;decr($this-&gt;key($tenant, $kind)) &lt;= 0) {<br>        $this-&gt;redis()-&gt;del($this-&gt;key($tenant, $kind));<br>    }<br>}</pre><p>get() skips a tenant at its cap, ack() and reject() release the slot, keepalive() refreshes the key&#39;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:</p><pre>B note created 20:37:28, processed 20:37:28 by MacBookPro16.local:95981<br>in flight for A right now: 1<br>[20:37:32] slow job A-1 for tenant 11111111 done by pid 95790<br>[20:37:36] slow job A-2 for tenant 11111111 done by pid 95790<br>[20:37:40] slow job A-3 for tenant 11111111 done by pid 95790<br>[20:37:44] slow job A-4 for tenant 11111111 done by pid 95790</pre><p>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.</p><p>The trade-off is in that expire(…, 180). A worker that dies between took() and done() leaves the slot taken until the key expires, so that tenant&#39;s queue pauses for up to three minutes. The alternative, a lease per message with a heartbeat, costs more Redis traffic per poll than the cap saves. We took the three minutes and run workers with --keepalive so a long legitimate message keeps its slot alive.</p><h3>8. Placement: which tenants live here</h3><p>A shared deployment needs to know its tenants and a tenant needs to be movable between placements without redeploying anything. A Redis hash does both: tenant:placement maps each uuid to a placement name, shared-1, shared-2 or dedicated. The service that creates tenants and handles plan changes writes it; the deployments only read it.</p><pre>// src/Tenant/PlacementReader.php (abridged)<br>public function tenants(): array<br>{<br>    if (!$this-&gt;isFresh()) {                       // at most every 30 s<br>        $hash = $this-&gt;redis()-&gt;hGetAll(self::KEY) ?: [];<br>        $this-&gt;tenants = array_keys(array_filter($hash, fn ($v) =&gt; $v === $this-&gt;placement));<br>        sort($this-&gt;tenants);<br>        $this-&gt;readAt = time();<br>    }<br> <br>    return $this-&gt;tenants;<br>}<br> <br>public function serves(string $tenantUuid): bool<br>{<br>    if ($this-&gt;isFresh()) {<br>        return in_array(strtolower($tenantUuid), $this-&gt;tenants, true);<br>    }<br> <br>    return $this-&gt;redis()-&gt;hGet(self::KEY, strtolower($tenantUuid)) === $this-&gt;placement;<br>}</pre><p>Workers call tenants() and amortise one HGETALL over 30 seconds of polling. A php-fpm request starts with an empty process and asks about one tenant with one HGET, because reading the whole registry per request would cost a call per placed tenant.</p><p>Moving a tenant is a change of one hash field. Its streams keep their names, so senders notice nothing; the workers of the new placement start reading them within 30 seconds and the entries the old workers left pending are claimed after redeliver_timeout, the same way a rolling deploy already behaves. Its database and bucket do not move at all.</p><h3>9. Migrations: every tenant, one process each</h3><p>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.</p><p>So each tenant gets its own process, running as a dedicated deployment of that tenant:</p><pre>// src/Command/TenantsMigrateCommand.php (abridged)<br>$running[$uuid] = Process::fromShellCommandline(<br>    &#39;bin/console doctrine:database:create --if-not-exists -n &amp;&amp; bin/console doctrine:migrations:migrate -n --allow-no-migration&#39;,<br>    $this-&gt;projectDir,<br>    [&#39;TENANT_MODE&#39; =&gt; &#39;single&#39;, &#39;TENANT_UUID&#39; =&gt; $uuid, &#39;DATABASE_URL&#39; =&gt; $this-&gt;tenantDatabaseUrl($uuid)],<br>);</pre><p>The child sees TENANT_MODE=single and a plain DATABASE_URL pointing at tenant_&lt;uuid&gt;, so Doctrine&#39;s own commands run untouched and --concurrency bounds how many run at once:</p><pre>$ bin/console app:tenants:migrate --concurrency=3<br>11111111-… started<br>22222222-… started<br>33333333-… started<br>11111111-… migrated<br>22222222-… migrated<br>33333333-… migrated<br>3 tenant(s), 0 failed, 1.1 s</pre><p>A failed tenant is reported and the others continue. In production the command also writes a migration-blocked:&lt;uuid&gt; flag that the request resolver turns into a 503 for that tenant alone, until a later run succeeds.</p><h3>10. What it costs and when not to do this</h3><p>The tenant switch is a reconnect. app:bench:switch runs SELECT 1 three hundred times on one tenant, then three hundred times alternating tenants, against Postgres in Docker on a laptop:</p><pre>300 queries on one tenant:              0.199 ms per query<br>300 queries switching tenant each time: 6.474 ms per query (299 reconnects)<br>cost of a tenant switch: 6.27 ms</pre><p>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.</p><p>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.</p><p>Do not do this when:</p><ul><li><strong>Tenants need cross-tenant transactions.</strong> TenantConnection refuses a switch inside a transaction on purpose. If your domain needs to write to two tenants atomically, you have one tenant.</li><li><strong>A tenant’s traffic justifies its own deployment.</strong> That is what the dedicated placement is for. Paying tenants stayed dedicated in our rollout and a burst on the free deployment cannot touch them.</li><li><strong>Your services already hold tenant-specific state in constructors.</strong> Count them first. In the production codebase it was 31 classes and five constructor queries and the scan test keeps them from coming back.</li></ul><h3>11. Testing it</h3><p>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:</p><pre>// tests/TwoTenantIsolationTest.php (abridged)<br>public function testEachTenantReadsItsOwnDatabase(): void<br>{<br>    $client = static::createClient();<br>    $body = &#39;isolation &#39;.bin2hex(random_bytes(4));<br> <br>    $client-&gt;jsonRequest(&#39;POST&#39;, &#39;/tenant_&#39;.self::A.&#39;/notes&#39;, [&#39;body&#39; =&gt; $body]);<br>    self::assertResponseStatusCodeSame(201);<br> <br>    $client-&gt;request(&#39;GET&#39;, &#39;/tenant_&#39;.self::A.&#39;/notes&#39;);<br>    self::assertStringContainsString($body, (string) $client-&gt;getResponse()-&gt;getContent());<br> <br>    $client-&gt;request(&#39;GET&#39;, &#39;/tenant_&#39;.self::B.&#39;/notes&#39;);<br>    self::assertStringNotContainsString($body, (string) $client-&gt;getResponse()-&gt;getContent());<br>}</pre><p>Use the real messenger.yaml, the real bus and routing and assert the destination: the row in the tenant&#39;s table, the entry in the tenant&#39;s stream, the failed message in the tenant&#39;s messenger_messages. A test that checks a stamp on an envelope will pass while a worker writes into the wrong database.</p><h3>Conclusion</h3><p>Each piece above is a decision you can take separately.</p><ul><li>A <strong>static </strong><strong>TenantContext</strong> with a default for dedicated deployments and no fallback for shared ones lets one codebase run both ways and turns &quot;wrong tenant&quot; into an exception instead of a row.</li><li>The <strong>base URL</strong> carries the tenant on HTTP, so routes and generated URLs do not change.</li><li>A DBAL <strong>wrapper_class</strong> and a <strong>cache decorator</strong> make the database and the cache follow the tenant with no change to repositories or services.</li><li>A Messenger transport that wraps <strong>one </strong><strong>RedisReceiver per tenant</strong> keeps every sender and every handler unchanged and the listener priorities keep retries and failures inside the tenant.</li><li>A <strong>per-tenant in-flight cap</strong> is enough fair use for free tenants; dedicated deployments are the fair use for paying ones.</li></ul><p>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.</p><p><strong>Next in this series.</strong> 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.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub in Part 2.</p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4892d9a672c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Draft by Agent, Approve by Human: A Publishing API and MCP Server for Symfony 8.1]]></title>
            <link>https://medium.com/@MattLeads/draft-by-agent-approve-by-human-a-publishing-api-and-mcp-server-for-symfony-8-1-22bfe2be74c1?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/22bfe2be74c1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 12:22:35 GMT</pubDate>
            <atom:updated>2026-11-09T12:22:35.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let AI agents draft, lint and submit articles on a Symfony site through scoped API keys and an MCP endpoint, while a human keeps the approve button.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBBjLsWKo9gH66aQzvPOmw.png" /></figure><p>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.</p><p>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.</p><p>This article walks through mattleads/agent-publishing-bundle, 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.</p><p>I maintain the bundle. The demo repository has every file shown here.</p><h3>Prerequisites</h3><ul><li>PHP 8.2 or later. The demo uses 8.4.</li><li>Symfony 6.4, 7.4 or 8.1. The demo is a fresh symfony/skeleton 8.1 project.</li><li>mattleads/agent-publishing-bundle 0.2.0.</li><li>Doctrine ORM for the bundled storage, or your own implementation of two small interfaces.</li><li>Optional: symfony/messenger to count views off the request, twig/twig for the JSON-LD helper.</li></ul><p>Nothing in the bundle renders HTML. Your templates and routes stay yours.</p><h3>1. Install and declare what exists</h3><pre>composer require mattleads/agent-publishing-bundle doctrine/orm doctrine/doctrine-bundle symfony/security-bundle</pre><p>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:</p><pre># config/packages/mattleads_agent_publishing.yaml<br>mattleads_agent_publishing:<br>    storage: doctrine<br>    locales: [en, de]<br>    default_locale: en<br>    sections:<br>        blog: { path: /blog }<br>        docs: { path: /docs, locales: [en], lint: { require_faq: true, min_words: 200 } }<br>    seo:<br>        site_name: Agent Publishing Demo<br>        publisher: { name: Demo Publishing Ltd, url: https://example.com }</pre><p>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:</p><pre># config/packages/security.yaml<br>security:<br>    firewalls:<br>        agent_publishing:<br>            pattern: ^/api/publisher<br>            stateless: true<br>            provider: none<br>            entry_point: MattLeads\AgentPublishingBundle\Security\ApiKeyAuthenticator<br>            custom_authenticators:<br>                - MattLeads\AgentPublishingBundle\Security\ApiKeyAuthenticator<br>    access_control:<br>        - { path: ^/api/publisher/v1/openapi\.json$, roles: PUBLIC_ACCESS }<br>        - { path: ^/api/publisher, roles: ROLE_AGENT_PUBLISHING }</pre><p>Import the routes, run a migration, and the site has an OpenAPI 3.1 document at /api/publisher/v1/openapi.json that a client generator or an agent can read.</p><p>With storage: doctrine you get four tables: articles, keys, and two daily rollups for analytics. With storage: custom you implement ArticleStorageInterface 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. ArticleInterface has no setters. That is deliberate: the bundle never mutates your entities behind your back.</p><h3>2. Keys that cannot grow</h3><p>Every caller holds a key with scopes and, optionally, a list of sections:</p><pre>php bin/console agent-publishing:api-key:create seo-agent --scope=articles:read --scope=articles:draft --section=blog<br>php bin/console agent-publishing:api-key:create editor --scope=articles:read --scope=articles:approve --scope=articles:publish --scope=stats:read</pre><p>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.</p><p>The scopes map onto the workflow. articles:draft creates, edits and submits. articles:approve approves or rejects what is in review. articles:publish publishes directly or on a schedule. stats:read reads counts. keys:manage 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 blog can create keys for its customers&#39; agents, and none of them can ever hold publish.</p><p>Section restrictions are enforced as “does not exist” rather than “forbidden”. A key limited to blog gets a 404 for an article in docs, and its listings and totals never include other sections. There is nothing to probe.</p><h3>3. The agent loop: lint, fix, create, submit</h3><p>The piece that makes agents useful rather than noisy is POST /lint. 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&#39;s first attempt, a two-line body with a seven-character title:</p><pre>WARN  title_length       Title is 7 characters, which is short for search and social previews.<br>                         -&gt; Name the outcome and the subject: aim for 30-60 characters.<br>FAIL  summary            No summary. It is used as the meta description and in previews.<br>WARN  opening_paragraph  The body does not start with a paragraph.<br>                         -&gt; Put a short answer to the title before the first heading, list or image.<br>WARN  word_count         5 words; this section expects at least 300.<br>FAIL  images_alt         1 of 1 image(s) have no alt text (first: /img/retry.png).<br>WARN  links              Link text &quot;here&quot; says nothing about the target.<br>status: fail (2 pass, 5 warn, 2 fail)</pre><p>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 lint block in configuration, and a host adds rules by tagging a service.</p><p>The agent reads the hints, rewrites, lints again, and gets status: pass. Then it creates the draft and submits it:</p><pre>POST /articles            -&gt; 201, state draft, slug symfony-messenger-retries-throwing-serializer<br>POST /articles/{id}/publish with the agent key -&gt; 403, This key lacks the &quot;articles:publish&quot; scope.<br>POST /articles/{id}/submit -&gt; 200, state in_review</pre><p>The whole loop is about 150 lines of plain PHP in the demo’s scripts/agent.php. No SDK, only JSON over HTTP.</p><h3>4. The human side, also through the API</h3><p>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:</p><pre>POST /articles/{id}/reject  { &quot;reason&quot;: &quot;Add the version the fix landed in.&quot; }   -&gt; draft, review_note set<br>POST /articles/{id}/submit                                                       -&gt; in_review<br>POST /articles/{id}/approve                                                      -&gt; published<br>POST /articles/{id}/publish { &quot;publish_at&quot;: &quot;2099-01-01T09:00:00+00:00&quot; }        -&gt; scheduled</pre><p>Every transition dispatches an ArticleTransitioned 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.</p><h3>5. Counting readers without cookies</h3><p>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:</p><pre>#[Route(&#39;/blog/{slug}&#39;, name: &#39;blog_show&#39;, defaults: [&#39;_agent_publishing_section&#39; =&gt; &#39;blog&#39;, &#39;_locale&#39; =&gt; &#39;en&#39;])]</pre><p>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:</p><p><strong>direct:</strong> No referrer.</p><p><strong>internal:</strong> A link from your own site.</p><p><strong>search:</strong> Google, Bing, DuckDuckGo and others.</p><p><strong>social:</strong> X, LinkedIn, Reddit, Hacker News, Telegram and friends.</p><p><strong>ai_referral:</strong> A human sent by ChatGPT, Perplexity, Claude or Gemini.</p><p><strong>ai_crawler:</strong> GPTBot, ClaudeBot, PerplexityBot, Google-Extended and other AI crawlers.</p><p><strong>bot:</strong> Anything else that is not a browser.</p><p><strong>referral:</strong> Any other site.</p><p>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:</p><pre>views 5, crawler_views 2<br>by_kind {&quot;ai_crawler&quot;:2,&quot;ai_referral&quot;:1,&quot;direct&quot;:1,&quot;search&quot;:2,&quot;social&quot;:1}<br>referrers: google.com search 2, chatgpt.com ai_referral 1, news.ycombinator.com social 1</pre><p>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”.</p><h3>6. MCP without a dependency</h3><p>Agents increasingly speak the Model Context Protocol rather than REST. On 6 November 2026 the official PHP SDK, mcp/sdk, is at 0.9.0 and symfony/mcp-bundle is at 1.0.0-BETA1. Pinning either would make their breaking releases the bundle&#39;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 initialize, ping, tools/list and tools/call, notifications acknowledged, batches accepted, and three protocol versions negotiated.</p><pre>claude mcp add --transport http publisher https://example.com/api/publisher/v1/mcp \<br>  --header &quot;Authorization: Bearer apb_...&quot;</pre><p>Sixteen tools wrap the same services as the REST API, so the two cannot drift. tools/list is filtered by the key&#39;s scopes. The demo&#39;s agent key sees nine tools and never learns that approve_article exists. Tool failures such as a validation error or a forbidden transition come back as results with isError and a readable message, which is what an agent acts on. Protocol mistakes get JSON-RPC error codes. Two tools exist only for agents: get_style_guide returns the site&#39;s writing rules from configuration, and list_sections includes each section&#39;s lint thresholds, so an agent can plan before it writes.</p><p>When the official SDK stabilizes, a bridge can expose the same McpToolInterface implementations through it. The tool code will not change.</p><h3>7. What search engines and language models see</h3><p>Three outputs come for free once articles are published. A Twig function, agent_publishing_jsonld(article), emits schema.org Article markup with headline, description, dates, language, keywords, author and publisher. A sitemap at /sitemap-publisher.xml lists published articles with lastmod 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 x-default. And /llms.txt follows the llmstxt.org format: the site name, a description, and a Markdown list per section of recent articles with their summaries.</p><p>All three build URLs through UrlResolverInterface. The default pattern is {base}{locale_prefix}{section_path}/{slug}, where the locale prefix is empty for the default language. A site with different routing registers its own resolver. Set seo.base_url in production so a forged Host header cannot plant another domain in cached output.</p><h3>Proof</h3><p>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.</p><h3>Where it does not fit</h3><ul><li><strong>You want a CMS.</strong> There is no admin UI, no editor, no media upload. Sulu or Bolt are the right tools then.</li><li><strong>You render HTML bodies as-is.</strong> The bundle stores format: html bodies unchanged. Sanitize before rendering, or an agent key with draft rights becomes a script injection path before any human approves.</li><li><strong>You need per-visitor analytics.</strong> The rollups are counts by day, article, referrer host and kind. Funnels and sessions are a different product.</li><li><strong>Your agents need resources or prompts over MCP.</strong> The server is tools-only by design, and it does not open server-to-client streams.</li></ul><h3>Conclusion</h3><p>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.</p><p>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.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/agent-publishing-bundle,">https://github.com/mattleads/agent-publishing-bundle,</a> with the runnable demo at <a href="https://github.com/mattleads/agent-publishing-demo">https://github.com/mattleads/agent-publishing-demo</a></p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22bfe2be74c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passkeys in 17 Files: Hybrid Login, Recovery Codes and Revocation in Symfony 8.1]]></title>
            <link>https://medium.com/@MattLeads/passkeys-in-17-files-hybrid-login-recovery-codes-and-revocation-in-symfony-8-1-6ac82f456701?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac82f456701</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 15:09:36 GMT</pubDate>
            <atom:updated>2026-11-05T15:09:36.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>A build-along guide from Symfony skeleton to a working passkey login, with a hybrid password form, revocation and recovery codes.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep5R06aU0tT33f9AKnYXOw.png" /></figure><p>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.</p><p>This guide builds exactly that on Symfony 8.1. Two bundles do the heavy lifting: <a href="https://github.com/web-auth/webauthn-symfony-bundle">web-auth/webauthn-symfony-bundle</a> runs the FIDO2 ceremonies, and <a href="https://github.com/mattleads/passkeys-bundle">mattleads/passkeys-bundle</a> 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&#39;s source.</p><p>The finished code is at <a href="https://github.com/mattleads/passkeys-demo">github.com/mattleads/passkeys-demo</a>. You write or edit 17 files. Everything else comes from Flex recipes.</p><h3>Prerequisites</h3><ul><li>PHP 8.2 or later. This guide uses 8.4.</li><li>Composer.</li><li>SQLite, which ships with PHP.</li><li>A browser with a platform authenticator: Touch ID, Windows Hello, Android or a security key.</li><li>No Node.js. AssetMapper serves everything.</li></ul><p>Versions used below: symfony/skeleton 8.1.*, web-auth/webauthn-symfony-bundle 5.3.10, mattleads/passkeys-bundle 0.1.1, doctrine/orm 3.7 and symfony/stimulus-bundle 3.6.</p><h3>1. Skeleton and packages</h3><pre>composer create-project symfony/skeleton:&quot;8.1.*&quot; passkeys-demo<br>cd passkeys-demo<br>composer config extra.symfony.allow-contrib true   # lets Flex apply the WebAuthn bundle&#39;s recipe<br> <br>composer require mattleads/passkeys-bundle web-auth/webauthn-symfony-bundle \<br>  symfony/security-bundle symfony/twig-bundle symfony/asset-mapper symfony/stimulus-bundle \<br>  doctrine/orm doctrine/doctrine-bundle symfony/uid symfony/serializer symfony/property-access symfony/property-info \<br>  symfony/rate-limiter symfony/lock symfony/password-hasher<br> <br>php bin/console importmap:require @hotwired/stimulus @simplewebauthn/browser</pre><p>symfony/rate-limiter and symfony/lock are for login throttling, which you want because recovery codes are short. @simplewebauthn/browser is the small client library the Stimulus controllers use to talk to navigator.credentials.</p><p>Flex registers the bundles and drops config/packages/webauthn.yaml and config/routes/webauthn_routes.yaml for you.</p><h3>2. Environment</h3><pre># .env.local<br>APP_SECRET=change-me-to-something-long-and-random<br>DATABASE_URL=&quot;sqlite:///%kernel.project_dir%/var/data.db&quot;<br>RELYING_PARTY_ID=localhost<br>RELYING_PARTY_NAME=&quot;Passkeys Demo&quot;<br>WEBAUTHN_ALLOWED_ORIGINS=&quot;http://localhost:8765,http://127.0.0.1:8765&quot;</pre><p>Two values matter here. The relying-party id is localhost. WebAuthn only works in a secure context. Browsers make an exception for localhost over plain HTTP, but not for 127.0.0.1, so always open the app as http://localhost:…. The port is part of the origin. If you serve on a different port, change it both here and in webauthn.yaml below, or the ceremony fails with an origin mismatch.</p><h3>3. Entities</h3><p>Two entities. The user carries an opaque <em>user handle</em> for WebAuthn, never the email, so the email can change later.</p><pre>&lt;?php<br>// src/Entity/User.php<br>namespace App\Entity;<br> <br>use App\Repository\UserRepository;<br>use Doctrine\ORM\Mapping as ORM;<br>use Symfony\Component\Security\Core\User\{PasswordAuthenticatedUserInterface, UserInterface};<br>use Symfony\Component\Uid\Ulid;<br>use Webauthn\PublicKeyCredentialUserEntity;<br> <br>#[ORM\Entity(repositoryClass: UserRepository::class)]<br>#[ORM\Table(name: &#39;app_user&#39;)]<br>class User implements UserInterface, PasswordAuthenticatedUserInterface<br>{<br>    #[ORM\Id, ORM\GeneratedValue, ORM\Column]<br>    private ?int $id = null;<br> <br>    #[ORM\Column(length: 180, unique: true)]<br>    private string $email;<br> <br>    #[ORM\Column(length: 26, unique: true)]<br>    private string $userHandle;<br> <br>    #[ORM\Column(length: 255, nullable: true)]<br>    private ?string $password = null;<br> <br>    /** @var list&lt;string&gt; */<br>    #[ORM\Column]<br>    private array $roles = [];<br> <br>    public function __construct(string $email)<br>    {<br>        $this-&gt;email = $email;<br>        $this-&gt;userHandle = (string) new Ulid();<br>    }<br> <br>    public function getUserIdentifier(): string { return $this-&gt;email; }<br>    public function getUserHandle(): string { return $this-&gt;userHandle; }<br>    public function getPassword(): ?string { return $this-&gt;password; }<br>    public function setPassword(?string $password): void { $this-&gt;password = $password; }<br>    public function getRoles(): array { return array_values(array_unique([...$this-&gt;roles, &#39;ROLE_USER&#39;])); }<br>    public function eraseCredentials(): void {}<br> <br>    public function toWebAuthnUserEntity(): PublicKeyCredentialUserEntity<br>    {<br>        return new PublicKeyCredentialUserEntity($this-&gt;email, $this-&gt;userHandle, $this-&gt;email);<br>    }<br>}</pre><p>The credential extends the WebAuthn bundle’s CredentialRecord, 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&#39;s one-method interface so &quot;last used&quot; gets filled in automatically.</p><pre>&lt;?php<br>// src/Entity/Credential.php<br>namespace App\Entity;<br> <br>use App\Repository\CredentialRepository;<br>use Doctrine\ORM\Mapping as ORM;<br>use MattLeads\PasskeysBundle\Contract\TracksCredentialUsageInterface;<br>use Webauthn\CredentialRecord;<br> <br>#[ORM\Entity(repositoryClass: CredentialRepository::class)]<br>#[ORM\Table(name: &#39;webauthn_credentials&#39;)]<br>#[ORM\HasLifecycleCallbacks]<br>class Credential extends CredentialRecord implements TracksCredentialUsageInterface<br>{<br>    #[ORM\Id, ORM\GeneratedValue, ORM\Column]<br>    private ?int $id = null;<br> <br>    #[ORM\Column(nullable: true)]<br>    private ?\DateTimeImmutable $createdAt = null;<br> <br>    #[ORM\Column(nullable: true)]<br>    private ?\DateTimeImmutable $lastUsedAt = null;<br> <br>    #[ORM\PrePersist]<br>    public function onPrePersist(): void { $this-&gt;createdAt ??= new \DateTimeImmutable(); }<br> <br>    /** The validators hand back a plain CredentialRecord; we turn it into this entity before saving. */<br>    public static function fromRecord(CredentialRecord $r): self<br>    {<br>        return new self($r-&gt;publicKeyCredentialId, $r-&gt;type, $r-&gt;transports, $r-&gt;attestationType, $r-&gt;trustPath,<br>            $r-&gt;aaguid, $r-&gt;credentialPublicKey, $r-&gt;userHandle, $r-&gt;counter, $r-&gt;otherUI,<br>            $r-&gt;backupEligible, $r-&gt;backupStatus, $r-&gt;uvInitialized);<br>    }<br> <br>    /** Fields that change after each successful login. */<br>    public function syncFrom(CredentialRecord $r): void<br>    {<br>        $this-&gt;counter = $r-&gt;counter;<br>        $this-&gt;backupStatus = $r-&gt;backupStatus;<br>        $this-&gt;uvInitialized = $r-&gt;uvInitialized;<br>        $this-&gt;otherUI = $r-&gt;otherUI;<br>    }<br> <br>    public function getLastUsedAt(): ?\DateTimeImmutable { return $this-&gt;lastUsedAt; }<br>    public function markUsed(\DateTimeImmutable $at): void { $this-&gt;lastUsedAt = $at; }<br>}</pre><p>Keep fromRecord() and syncFrom() in mind. Section 4 explains why they exist, and they prevent the first error you would otherwise hit.</p><h3>4. Repositories</h3><p>The WebAuthn bundle looks users up by username, and that string must be exactly what getUserIdentifier() returns. If the two disagree, the &quot;add a passkey&quot; page cannot find the current user and the login flow endpoint cannot find anyone.</p><pre>&lt;?php<br>// src/Repository/UserRepository.php<br>namespace App\Repository;<br> <br>use App\Entity\User;<br>use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;<br>use Doctrine\Persistence\ManagerRegistry;<br>use Symfony\Component\Security\Core\User\{PasswordAuthenticatedUserInterface, PasswordUpgraderInterface};<br>use Webauthn\Bundle\Repository\PublicKeyCredentialUserEntityRepositoryInterface;<br>use Webauthn\PublicKeyCredentialUserEntity;<br> <br>final class UserRepository extends ServiceEntityRepository implements PublicKeyCredentialUserEntityRepositoryInterface, PasswordUpgraderInterface<br>{<br>    public function __construct(ManagerRegistry $registry) { parent::__construct($registry, User::class); }<br> <br>    public function findOneByUsername(string $username): ?PublicKeyCredentialUserEntity<br>    {<br>        return $this-&gt;findOneBy([&#39;email&#39; =&gt; $username])?-&gt;toWebAuthnUserEntity();<br>    }<br> <br>    public function findOneByUserHandle(string $userHandle): ?PublicKeyCredentialUserEntity<br>    {<br>        return $this-&gt;findOneBy([&#39;userHandle&#39; =&gt; $userHandle])?-&gt;toWebAuthnUserEntity();<br>    }<br> <br>    public function save(User $user): void<br>    {<br>        $this-&gt;getEntityManager()-&gt;persist($user);<br>        $this-&gt;getEntityManager()-&gt;flush();<br>    }<br> <br>    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void<br>    {<br>        if ($user instanceof User) { $user-&gt;setPassword($newHashedPassword); $this-&gt;getEntityManager()-&gt;flush(); }<br>    }<br>}</pre><p>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 <strong>Revoke</strong>, and override saveCredentialRecord():</p><pre>&lt;?php<br>// src/Repository/CredentialRepository.php<br>namespace App\Repository;<br> <br>use App\Entity\Credential;<br>use Doctrine\Persistence\ManagerRegistry;<br>use MattLeads\PasskeysBundle\Contract\CanDeleteCredentialRecord;<br>use Webauthn\Bundle\Repository\DoctrineCredentialSourceRepository;<br>use Webauthn\CredentialRecord;<br> <br>final class CredentialRepository extends DoctrineCredentialSourceRepository implements CanDeleteCredentialRecord<br>{<br>    public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Credential::class); }<br> <br>    public function saveCredentialRecord(CredentialRecord $credentialRecord): void<br>    {<br>        if (!$credentialRecord instanceof Credential) {<br>            $existing = $this-&gt;findOneByCredentialId($credentialRecord-&gt;publicKeyCredentialId);<br>            if ($existing instanceof Credential) {<br>                $existing-&gt;syncFrom($credentialRecord);   // after a login: counter, backup flags<br>                $credentialRecord = $existing;<br>            } else {<br>                $credentialRecord = Credential::fromRecord($credentialRecord);   // registration<br>            }<br>        }<br>        parent::saveCredentialRecord($credentialRecord);<br>    }<br> <br>    public function deleteCredentialRecord(CredentialRecord $credentialRecord): void<br>    {<br>        $this-&gt;getEntityManager()-&gt;remove($credentialRecord);<br>        $this-&gt;getEntityManager()-&gt;flush();<br>    }<br>}</pre><p>The conversion exists because the attestation and assertion validators construct a plain Webauthn\CredentialRecord. Persist that directly and Doctrine throws <em>&quot;The given entity of type &#39;Webauthn\CredentialRecord&#39; has no identity/no id values set&quot;</em>, 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.</p><h3>5. Security configuration</h3><pre># config/packages/security.yaml<br>security:<br>    password_hashers:<br>        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: &#39;auto&#39;<br>    providers:<br>        app_users:<br>            entity: { class: App\Entity\User, property: email }<br>    firewalls:<br>        dev:<br>            pattern: ^/(_profiler(/|$)|(_wdt|assets|build)/)<br>            security: false<br>        main:<br>            lazy: true<br>            provider: app_users<br>            entry_point: form_login<br>            form_login:<br>                login_path: app_login<br>                check_path: app_login<br>                username_parameter: _username<br>                password_parameter: _password<br>                enable_csrf: true<br>                default_target_path: app_account<br>            webauthn:<br>                authentication:<br>                    routes:<br>                        options_path: /login/passkey/options<br>                        result_path: /login/passkey/result<br>            custom_authenticators:<br>                - MattLeads\PasskeysBundle\Security\RecoveryCodeAuthenticator<br>            login_throttling:<br>                max_attempts: 5<br>            logout:<br>                path: app_logout<br>                target: app_login<br>    access_control:<br>        - { path: ^/account, roles: ROLE_USER }</pre><p>Three authenticators live on this firewall: password form, WebAuthn assertion and recovery code. Symfony needs entry_point to know where to send anonymous visitors. Forget it and the container refuses to compile with a long message about &quot;multiple authenticators&quot;.</p><p>There is no registration: block under webauthn:, and that is deliberate. That block is for passwordless <em>sign-up</em> 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&#39;s standalone creation controllers instead:</p><pre># config/packages/webauthn.yaml<br>webauthn:<br>    credential_repository: App\Repository\CredentialRepository<br>    user_repository: App\Repository\UserRepository<br>    allowed_origins: [&#39;http://localhost:8765&#39;, &#39;http://127.0.0.1:8765&#39;]<br>    creation_profiles:<br>        default:<br>            rp:<br>                name: &#39;%env(RELYING_PARTY_NAME)%&#39;<br>                id: &#39;%env(RELYING_PARTY_ID)%&#39;<br>            authenticator_selection_criteria:<br>                resident_key: required        # discoverable credential → shows up in browser autofill<br>                user_verification: preferred<br>    request_profiles:<br>        default:<br>            rp_id: &#39;%env(RELYING_PARTY_ID)%&#39;<br>            user_verification: preferred<br>    controllers:<br>        enabled: true<br>        creation:<br>            add_passkey:<br>                options_path: /account/passkeys/add/options<br>                result_path: /account/passkeys/add/result<br>                user_entity_guesser: Webauthn\Bundle\Security\Guesser\CurrentUserEntityGuesser<br>                profile: default</pre><p>resident_key: required makes the passkey <em>discoverable</em>, which lets the browser offer it from the username field&#39;s autofill (conditional UI). Without it you get a credential that only works when the server names it first.</p><p>The creation controllers above are registered as routes named webauthn.controller.creation.request.add_passkey and …response.add_passkey. Tell the passkeys bundle about them so its management page can render the &quot;Add a passkey&quot; button, and import its routes:</p><pre># config/packages/mattleads_passkeys.yaml<br>mattleads_passkeys:<br>    recovery:<br>        default_target_path: /account<br>    management:<br>        add_passkey:<br>            options_route: webauthn.controller.creation.request.add_passkey<br>            result_route: webauthn.controller.creation.response.add_passkey</pre><pre># config/routes/mattleads_passkeys.yaml<br>mattleads_passkeys:<br>    resource: &#39;@MattLeadsPasskeysBundle/config/routes.php&#39;</pre><p>That gives you /login/flow, /login/recovery, /account/passkeys, /account/passkeys/revoke and /account/passkeys/recovery-codes.</p><h3>6. Controllers</h3><p>Two of ours. A security controller for the login page, logout and the account page:</p><pre>&lt;?php<br>// src/Controller/SecurityController.php<br>namespace App\Controller;<br> <br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\Response;<br>use Symfony\Component\Routing\Attribute\Route;<br>use Symfony\Component\Security\Http\Attribute\IsGranted;<br>use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;<br> <br>final class SecurityController extends AbstractController<br>{<br>    #[Route(&#39;/login&#39;, name: &#39;app_login&#39;)]<br>    public function login(AuthenticationUtils $utils): Response<br>    {<br>        if ($this-&gt;getUser()) {<br>            return $this-&gt;redirectToRoute(&#39;app_account&#39;);<br>        }<br>        return $this-&gt;render(&#39;security/login.html.twig&#39;, [<br>            &#39;error&#39; =&gt; $utils-&gt;getLastAuthenticationError(),<br>            &#39;last_username&#39; =&gt; $utils-&gt;getLastUsername(),<br>        ]);<br>    }<br> <br>    #[Route(&#39;/logout&#39;, name: &#39;app_logout&#39;)]<br>    public function logout(): never { throw new \LogicException(&#39;Handled by the firewall.&#39;); }<br> <br>    #[Route(&#39;/&#39;, name: &#39;app_home&#39;)]<br>    public function home(): Response<br>    {<br>        return $this-&gt;redirectToRoute($this-&gt;getUser() ? &#39;app_account&#39; : &#39;app_login&#39;);<br>    }<br> <br>    #[Route(&#39;/account&#39;, name: &#39;app_account&#39;)]<br>    #[IsGranted(&#39;ROLE_USER&#39;)]<br>    public function account(): Response { return $this-&gt;render(&#39;account/index.html.twig&#39;); }<br>}</pre><p>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.</p><pre>$user = new User($email);<br>$user-&gt;setPassword($hasher-&gt;hashPassword($user, $password));<br>$users-&gt;save($user);</pre><p>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.</p><h3>7. Templates</h3><p>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:</p><pre>{# templates/security/login.html.twig #}<br>{% extends &#39;base.html.twig&#39; %}<br>{% block body %}<br>    &lt;h1&gt;Sign in&lt;/h1&gt;<br>    {{ include(&#39;@MattLeadsPasskeys/login/hybrid.html.twig&#39;, {<br>        login_check_path: path(&#39;app_login&#39;),<br>        options_url: path(&#39;webauthn.controller.security.main.request.options&#39;),<br>        result_url: path(&#39;webauthn.controller.security.main.request.result&#39;),<br>        flow_url: path(&#39;mattleads_passkeys_login_flow&#39;),<br>        recovery_url: path(&#39;mattleads_passkeys_recovery_login&#39;),<br>        csrf_token: csrf_token(&#39;authenticate&#39;),<br>        last_identifier: last_username,<br>        error: error,<br>    }) }}<br>    &lt;p&gt;&lt;a href=&quot;{{ path(&#39;app_register&#39;) }}&quot;&gt;No account yet? Create one&lt;/a&gt;&lt;/p&gt;<br>{% endblock %}</pre><p>The two webauthn.controller.security.main.request.* routes are created by the firewall&#39;s authentication: block. main is the firewall name.</p><p>The bundle’s own pages (passkey list, recovery codes, recovery login) extend @MattLeadsPasskeys/layout.html.twig. Override that one file to pull them into your layout:</p><pre>{# templates/bundles/MattLeadsPasskeysBundle/layout.html.twig #}<br>{% extends &#39;base.html.twig&#39; %}</pre><p>base.html.twig needs {{ importmap(&#39;app&#39;) }} in the head and, for the demo, a nav with links to app_account, mattleads_passkeys_manage and app_logout.</p><h3>8. Frontend without Node</h3><p>Enable the bundle’s Stimulus controllers:</p><pre>// assets/controllers.json<br>{<br>    &quot;controllers&quot;: {<br>        &quot;@mattleads/passkeys-bundle&quot;: {<br>            &quot;hybrid-login&quot;: { &quot;enabled&quot;: true, &quot;fetch&quot;: &quot;eager&quot; },<br>            &quot;passkey&quot;: { &quot;enabled&quot;: true, &quot;fetch&quot;: &quot;lazy&quot; },<br>            &quot;confirm&quot;: { &quot;enabled&quot;: true, &quot;fetch&quot;: &quot;lazy&quot; }<br>        }<br>    },<br>    &quot;entrypoints&quot;: []<br>}</pre><pre>// assets/app.js<br>import &#39;./stimulus_bootstrap.js&#39;;</pre><p>StimulusBundle reads the bundle’s assets/package.json, AssetMapper serves the files from vendor/, and the browser imports @simplewebauthn/browser from the importmap you populated in step 1. Check with php bin/console debug:asset-map | grep passkeys. You should see the three controllers and webauthn_service.js.</p><h3>9. Run it</h3><pre>php bin/console doctrine:schema:create<br>php -S localhost:8765 -t public public/index.php</pre><p>Open <a href="http://localhost:8765">http://localhost:8765</a> and walk through:</p><ol><li><em>Create account</em>, then sign in with the password. The flow endpoint returned password, so the form revealed a password field.</li><li><em>Passkeys</em>, then <em>Add a passkey to this device</em>, then approve with Touch ID or Windows Hello. The table shows the new credential, its transports (hybrid, internal for a synced platform passkey), whether it is backed up, and <em>Last used: never</em>.</li><li>Sign out. Type the email and press <em>Continue</em>. This time the flow endpoint says passkey, the browser prompts, and you land on /account without ever seeing a password field. Back on the passkeys page, <em>Last used</em> now has a timestamp.</li><li><em>Generate new recovery codes</em>. Ten codes, shown once. Sign out, open <em>Lost access?</em> and enter one. Each code works exactly once, and after five bad attempts the firewall’s throttling kicks in.</li><li><em>Revoke</em>, which takes two clicks because the button changes to <em>Confirm revoke</em>. Sign out and in again, and you are back to the password field.</li></ol><p>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.</p><h3>10. The three errors you will hit if you skip a step</h3><p><strong>Error:</strong> <em>“has no identity/no id values set”</em> on registration<br> <strong>Cause:</strong> persisting the validator’s plain CredentialRecord<br> <strong>Fix:</strong> convert to your entity in saveCredentialRecord() (section 4)</p><p><strong>Error:</strong> <em>“Unable to find the user entity”</em> when adding a passkey<br> <strong>Cause:</strong> using the firewall’s registration: block, which reads the username from the body<br> <strong>Fix:</strong> webauthn.controllers.creation with CurrentUserEntityGuesser (section 5)</p><p><strong>Error:</strong> Ceremony fails with an origin / RP id error<br> <strong>Cause:</strong> opened via 127.0.0.1, or a port not in allowed_origins<br> <strong>Fix:</strong> use http://localhost:&lt;port&gt; and list that exact origin</p><p>A fourth problem raises no error at all. Without resident_key: required, passkeys never appear in the browser&#39;s autofill, and users keep typing passwords.</p><h3>Where to go from here</h3><ul><li><strong>Passwordless sign-up</strong>: the firewall’s registration: block with RequestBodyUserEntityGuesser and a CanRegisterUserEntity repository.</li><li><strong>Production</strong>: HTTPS, RELYING_PARTY_ID set to your apex domain so passkeys work on all subdomains, allowed_origins listing every origin that will call the endpoints, migrations instead of schema:create, and a real session storage.</li><li><strong>Styling</strong>: override any template under templates/bundles/MattLeadsPasskeysBundle/. The Stimulus controllers dispatch error, authenticated and armed events if you want your own UI instead of the built-in error line.</li></ul><p>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 registration: block instead. Either way, ship recovery codes and login throttling together, because a short code without a rate limit is a brute-force target.</p><p>Issues and pull requests on the demo or the bundle are welcome.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/passkeys-demo">https://github.com/mattleads/passkeys-demo</a></p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac82f456701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7.7x Smaller and Encrypted at Rest: Compressing Symfony Messenger Payloads Without Touching a…]]></title>
            <link>https://medium.com/@MattLeads/7-7x-smaller-and-encrypted-at-rest-compressing-symfony-messenger-payloads-without-touching-a-812de0184310?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/812de0184310</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 17:09:13 GMT</pubDate>
            <atom:updated>2026-11-02T17:09:13.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>7.7x Smaller and Encrypted at Rest: Compressing Symfony Messenger Payloads Without Touching a Handler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gx19FB0d1opEVE3PQ3koiA.jpeg" /></figure><p>Symfony Messenger serializes a message, hands the bytes to a transport and forgets about them. Two things routinely go wrong with those bytes:</p><ol><li><strong>They are too big.</strong> 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.</li><li><strong>They are readable.</strong> Names, emails, IBANs sit in plain text in messenger_messages, in a Redis RDB dump, on a RabbitMQ disk and in the dead-letter queue nobody has looked at since March.</li></ol><p><a href="https://github.com/mattleads/messenger-compress-bundle">mattleads/messenger-compress-bundle</a> 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&#39;ll walk through the whole thing on a small Doctrine (SQLite) transport, because then the queue is a table you can SELECT from and see what changed.</p><h3>Prerequisites</h3><ul><li>PHP 8.2 or newer. ext-zlib and ext-sodium ship with PHP, so there is nothing to install.</li><li>A Symfony 6.4, 7.x or 8.x application with symfony/messenger. The outputs below come from Symfony 8.1.</li><li>mattleads/messenger-compress-bundle v0.1.1.</li><li>To follow along exactly, clone <a href="https://github.com/mattleads/messenger-compress-demo">the demo</a>. It uses a Doctrine transport on SQLite.</li></ul><h3>1. Install</h3><pre>composer require mattleads/messenger-compress-bundle</pre><p>Symfony Flex registers the bundle. Without Flex, add it yourself:</p><pre>// config/bundles.php<br>return [<br>    // ...<br>    MattLeads\MessengerCompressBundle\MattLeadsMessengerCompressBundle::class =&gt; [&#39;all&#39; =&gt; true],<br>];</pre><p>Nothing happens yet. The bundle registers a serializer service, mattleads_messenger_compress.serializer, that wraps Messenger&#39;s default serializer. Until a transport uses it, your messages are untouched.</p><h3>2. Wire it to a transport</h3><p>You have two options. Start with <strong>one transport</strong>:</p><pre># config/packages/messenger.yaml<br>framework:<br>    messenger:<br>        failure_transport: failed<br>        transports:<br>            async:<br>                dsn: &#39;%env(MESSENGER_TRANSPORT_DSN)%&#39;<br>                serializer: mattleads_messenger_compress.serializer<br>            failed: &#39;doctrine://default?queue_name=failed&#39;<br>        routing:<br>            &#39;App\Message\GenerateInvoiceBatch&#39;: async<br>            &#39;App\Message\ExportCustomerData&#39;: async</pre><p>Or wrap the default serializer so <strong>every</strong> transport gets it:</p><pre># config/packages/mattleads_messenger_compress.yaml<br>mattleads_messenger_compress:<br>    decorate_default_serializer: true</pre><p>One tip for the walkthrough only: Messenger’s default serializer is PHP serialize(). If you switch the default to the JSON one, plain bodies become human-readable in the database, which makes the &quot;before&quot; picture much clearer:</p><pre>framework:<br>    messenger:<br>        serializer:<br>            default_serializer: messenger.transport.symfony_serializer</pre><p>The bundle doesn’t care which one you wrap. It compresses and encrypts bytes.</p><h3>3. See the problem first</h3><p>Here is a message you would not want sitting in a queue table:</p><pre>final readonly class ExportCustomerData<br>{<br>    public function __construct(<br>        public string $customerId,<br>        public string $fullName,<br>        public string $email,<br>        public string $iban,<br>    ) {}<br>}</pre><p>Dispatch it as usual and look at the row. In the demo, app:queue:inspect --grep &lt;string&gt; does this. By hand it&#39;s just SQL:</p><pre>SELECT id, length(body), substr(body, 1, 60), headers FROM messenger_messages;</pre><pre>id   message              X-Compression   X-Encryption   key   encoding   body bytes   body preview<br> 1    ExportCustomerData   -               -              -     -          119          {&quot;customerId&quot;:&quot;cust-4711&quot;,&quot;fullName&quot;:&quot;Nino Beri…<br> [ERROR] &quot;GE29NB0000000101904917&quot; is readable in 1 stored message(s).</pre><p>The IBAN is right there. Every backup of that database has it too.</p><h3>4. Encrypt it</h3><h4>Generate a key</h4><pre>bin/console messenger-compress:generate-key -v</pre><pre>k3Jm…(44 characters of base64)…=<br><br>Add to .env.local (never commit it):<br>  MESSENGER_ENCRYPTION_KEY_V1=k3Jm…<br>and to config/packages/mattleads_messenger_compress.yaml:<br>  encryption: { enabled: true, keys: { v1: &#39;%env(MESSENGER_ENCRYPTION_KEY_V1)%&#39; } }</pre><p>That’s 32 random bytes, base64-encoded. Put it in .env.local for development and in your secrets store for production. Symfony&#39;s own vault works fine:</p><pre>bin/console secrets:set MESSENGER_ENCRYPTION_KEY_V1</pre><h4>Configure</h4><pre># config/packages/mattleads_messenger_compress.yaml<br>mattleads_messenger_compress:<br>    encryption:<br>        enabled: true<br>        keys:<br>            v1: &#39;%env(MESSENGER_ENCRYPTION_KEY_V1)%&#39;</pre><h4>Dispatch with a stamp</h4><pre>use MattLeads\MessengerCompressBundle\Stamp\EncryptStamp;<br><br>$bus-&gt;dispatch(new ExportCustomerData(...), [new EncryptStamp()]);</pre><p>Same row, after:</p><pre>2    ExportCustomerData   -               xchacha20poly1305   v1    base64     212          jUa0PNnAtVBUT5+uTPOOxsbUrOTsIg9cYKnD1WAKsnRQEyN…</pre><p>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 <strong>the header rule: stamps travel as headers and are not encrypted.</strong> Put secrets in the message body, never in a stamp.</p><p>Notice the size went <em>up</em>: 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.</p><h4>Or encrypt everything on this transport</h4><p>If a transport only ever carries sensitive work, stop thinking about stamps:</p><pre>mattleads_messenger_compress:<br>    encryption:<br>        enabled: true<br>        always: true<br>        keys: { v1: &#39;%env(MESSENGER_ENCRYPTION_KEY_V1)%&#39; }</pre><p>A single message can opt out with PlainStamp. An explicit EncryptStamp always wins over policy.</p><h3>5. Compress the big ones</h3><p>Now the other problem. GenerateInvoiceBatch with 5,000 order lines serializes to 759 KB of JSON. Three ways to shrink it:</p><p><strong>Explicitly, per message:</strong></p><pre>use MattLeads\MessengerCompressBundle\Stamp\CompressStamp;<br> <br>$bus-&gt;dispatch($batch, [new CompressStamp()]);            // configured default: deflate<br>$bus-&gt;dispatch($batch, [new CompressStamp(&#39;gzip&#39;)]);<br>$bus-&gt;dispatch($batch, [new CompressStamp(&#39;zstd&#39;, 3)]);   // algorithm + level; zstd needs ext-zstd</pre><p><strong>Automatically above a size.</strong> This is the default to pick, because nobody remembers to add a stamp to the one message that grows:</p><pre>mattleads_messenger_compress:<br>    compression:<br>        default_algorithm: deflate     # deflate | gzip | zstd<br>        level: null                    # null = the algorithm&#39;s default<br>        auto_threshold: 4096           # any body &gt;= 4 KiB is compressed, no stamp needed</pre><p><strong>Always:</strong></p><pre>mattleads_messenger_compress:<br>    compression:<br>        always: true</pre><p>Two details of the automatic policies: they only <em>keep</em> the compressed body when it is actually smaller than the original (random blobs and already-compressed data pass through untouched) and PlainStamp opts a message out. An explicit CompressStamp is always honored even if the result is larger.</p><p>What it looks like with auto_threshold: 4096:</p><pre>Message               Stamps                  Raw         On the wire  Ratio<br>50 invoice lines      none (auto)             7.6 KB      1,416 B      18.6 %<br>5,000 invoice lines   none (auto)             758,571 B   98,060 B     12.9 %<br>5,000 invoice lines   CompressStamp(&#39;gzip&#39;),  758,571 B   98,136 B     12.9 %<br>                      EncryptStamp(&#39;v2&#39;)<br>Customer export       EncryptStamp()          119 B       212 B        178 %</pre><p>The third row is the common production combination: compress <em>and</em> 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.</p><blockquote><em>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.</em></blockquote><h3>6. What goes over the wire</h3><p>The bundle adds up to four headers to the encoded envelope. Everything else (the type header, the stamp headers) is whatever the inner serializer produced.</p><pre>Header                Value                   Meaning<br>X-Compression         deflate | gzip | zstd   body was compressed with this algorithm<br>X-Encryption          xchacha20poly1305       body was encrypted with this scheme<br>X-Encryption-Key-Id   e.g. v1                 which key, so consumers can rotate<br>X-Payload-Encoding    base64                  body is base64 text</pre><p>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 %:</p><pre>mattleads_messenger_compress:<br>    encoding: raw</pre><p>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.</p><h3>7. Consume and get metrics for free</h3><p>Nothing changes in the handler:</p><pre>#[AsMessageHandler]<br>final readonly class ExportCustomerDataHandler<br>{<br>    public function __invoke(ExportCustomerData $message): void<br>    {<br>        // $message is the plain object. Decryption happened in the transport serializer.<br>    }<br>}</pre><p>But the envelope your handler is wrapped in now carries a TransformedStamp describing what the serializer undid: compression, encryption, keyId, wireSize, rawSize and a ratio() helper. It implements NonSendableStampInterface, so it is never sent back out if the message is re-dispatched. A tiny listener turns it into logs or metrics:</p><pre>use MattLeads\MessengerCompressBundle\Stamp\TransformedStamp;<br>use Symfony\Component\EventDispatcher\Attribute\AsEventListener;<br>use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent;<br> <br>final readonly class TransformedStampLogger<br>{<br>    public function __construct(private LoggerInterface $logger) {}<br> <br>    #[AsEventListener]<br>    public function __invoke(WorkerMessageReceivedEvent $event): void<br>    {<br>        $stamp = $event-&gt;getEnvelope()-&gt;last(TransformedStamp::class);<br>        if (null === $stamp) {<br>            return; // message was neither compressed nor encrypted<br>        }<br> <br>        $this-&gt;logger-&gt;info(&#39;compression={c} encryption={e} key={k} wire={w} raw={r} ratio={ratio}&#39;, [<br>            &#39;c&#39; =&gt; $stamp-&gt;compression ?? &#39;-&#39;,<br>            &#39;e&#39; =&gt; $stamp-&gt;encryption ?? &#39;-&#39;,<br>            &#39;k&#39; =&gt; $stamp-&gt;keyId ?? &#39;-&#39;,<br>            &#39;w&#39; =&gt; $stamp-&gt;wireSize,<br>            &#39;r&#39; =&gt; $stamp-&gt;rawSize,<br>            &#39;ratio&#39; =&gt; sprintf(&#39;%.1f%%&#39;, 100 * $stamp-&gt;ratio()),<br>        ]);<br>    }<br>}</pre><pre>$ bin/console messenger:consume async --limit=5<br>Received ExportCustomerData: compression=- encryption=xchacha20poly1305 key=v1 wire=212 B raw=119 B ratio=178.2%<br>Handled export for cust-4711 (Nino Beridze, iban ends 4917)<br>Received GenerateInvoiceBatch: compression=deflate encryption=- key=- wire=98,060 B raw=758,571 B ratio=12.9%<br>Handled batch-5000: 5000 lines, total 15,537,656.65 EUR</pre><p>Push ratio() and wireSize into your metrics backend tagged by message class and you&#39;ve got a dashboard of what each job actually costs your broker.</p><h3>8. Rotate keys without draining the queue</h3><p>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.</p><p>The bundle’s answer is a key ring. Every encrypted message carries its key id in X-Encryption-Key-Id; consumers decode with whichever key the message names and active_key says which key <em>new</em> messages use.</p><pre>mattleads_messenger_compress:<br>    encryption:<br>        enabled: true<br>        active_key: &#39;%env(MESSENGER_ACTIVE_KEY)%&#39;<br>        keys:<br>            v1: &#39;%env(MESSENGER_ENCRYPTION_KEY_V1)%&#39;<br>            v2: &#39;%env(MESSENGER_ENCRYPTION_KEY_V2)%&#39;</pre><p>The procedure, in order:</p><ol><li>Generate v2 (messenger-compress:generate-key --id v2 -v) and deploy it to <strong>every consumer</strong> alongside v1. Nothing changes yet; active_key is still v1.</li><li>Flip active_key to v2 on producers. New messages are v2; consumers still decode the v1 backlog.</li><li>Once the queues (including the failure transport) have cycled, remove v1.</li></ol><p>You can watch it happen in the demo by running the producer with one key and the consumer with the other:</p><pre>php bin/console app:dispatch --export --encrypt                              # active_key=v1<br>MESSENGER_ACTIVE_KEY=v2 php bin/console app:dispatch --export --encrypt<br>MESSENGER_ACTIVE_KEY=v2 php bin/console messenger:consume async --limit=2</pre><pre>Received ExportCustomerData: … encryption=xchacha20poly1305 key=v1 …<br>Received ExportCustomerData: … encryption=xchacha20poly1305 key=v2 …</pre><p>If active_key is omitted, the last key in the map is used.</p><h3>9. When it goes wrong: wrong key, tampered body</h3><p>This is the part to understand <em>before</em> 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:</p><pre>php bin/console app:dispatch --export --encrypt<br>sqlite3 var/data.db &quot;UPDATE messenger_messages SET body = substr(body,1,40) || &#39;X&#39; || substr(body,42) WHERE delivered_at IS NULL;&quot;<br>php bin/console messenger:consume async --limit=3<br>php bin/console messenger:failed:show</pre><pre>Error thrown while handling message MessageDecodingFailedException. Sending for retry #1 using 93 ms delay. Error: &quot;Decryption failed: authentication tag mismatch (wrong key or tampered payload).&quot;<br>Error thrown while handling message MessageDecodingFailedException. Sending for retry #2 using 110 ms delay. …<br>Error thrown while handling message MessageDecodingFailedException. Removing from transport after 2 retries. …<br> <br>There is 1 message pending in the failure transport.<br>  Id   Class                                                                   Failed at             Error<br>  4    Symfony\Component\Messenger\Exception\MessageDecodingFailedException   2026-11-01 15:12:53   Decryption failed: authentication tag mismatch (wrong key or tampered payload).</pre><p>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 v2 and some v2 messages failed. Add the key and replay:</p><pre>php bin/console messenger:failed:retry --force</pre><pre>Handled export for cust-4711 (Nino Beridze, iban ends 4917)</pre><p>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.</p><p>A note on Symfony 8.1. Messenger 8.1 changed how a transport serializer must report a message it cannot decode: it has to <em>return</em> an envelope wrapping MessageDecodingFailedException instead of throwing, so the stamps that count retries survive. Bundle v0.1.0 threw and on 8.1 that meant &quot;retry #1&quot; 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 (<a href="https://github.com/symfony/symfony-docs/pull/23459">symfony-docs#23459</a>) and the throwing path itself is tracked in <a href="https://github.com/symfony/symfony/issues/67791">symfony/symfony#67791</a>, with a <a href="https://github.com/mattleads/messenger-decode-throw-repro">one-file reproducer</a>.</p><p>The errors you can see and what they mean:</p><ul><li>Decryption failed: authentication tag mismatch (wrong key or tampered payload). The key with that id exists on the consumer but is different from the producer&#39;s or the body was modified.</li><li>No encryption key with id &quot;v2&quot; is configured. Known ids: v1. The consumer has not received the new key yet. Rotation step 1 was skipped.</li><li>Received an encrypted message but encryption is not configured on this consumer. encryption.enabled is false on the consumer or it has no keys.</li><li>Message requested encryption but mattleads_messenger_compress.encryption is not enabled / has no keys. Producer side: you dispatched with EncryptStamp before configuring a key.</li><li>Unknown compression algorithm &quot;zstd&quot;. Available: deflate, gzip. ext-zstd is not loaded on this host.</li></ul><h3>10. Testing</h3><p>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:</p><pre># config/packages/test/messenger.yaml<br>framework:<br>    messenger:<br>        transports:<br>            async:<br>                dsn: &#39;in-memory://?serialize=true&#39;<br>                serializer: mattleads_messenger_compress.serializer</pre><p>Dispatch with stamps, consume, assert on the TransformedStamp of the received envelope. This is how the bundle&#39;s own functional tests work.</p><h3>11. Production checklist</h3><ul><li><strong>Keys come from a secrets store</strong>, never from the repository. secrets:set, Vault, SSM, whatever you already use.</li><li><strong>Consumers before producers.</strong> Install the bundle on consumers first; add keys to consumers first; only then stamp or switch active_key.</li><li><strong>Prefer a threshold over stamps.</strong> auto_threshold: 4096 catches the message that grows six months from now. Reserve explicit stamps for zstd/level tuning.</li><li><strong>Encrypt by transport if you can.</strong> A dedicated sensitive transport with encryption.always: true is easier to audit than stamps scattered through services.</li><li><strong>Headers are plain text.</strong> Message class, stamp contents, key id are all visible. Keep secrets in the body.</li><li><strong>Keep the failure transport in mind during rotation.</strong> Messages parked there may still be on the old key; do not remove it until the failure transport is empty or replayed.</li><li><strong>Watch </strong><strong>ratio().</strong> If a message class is consistently above 100 %, it&#39;s small and doesn&#39;t need compression; if it is consistently at 100 %, the data is already compressed (images, archives) and PlainStamp saves CPU.</li></ul><h3>Where to go from here</h3><p>The bundle is on <a href="https://packagist.org/packages/mattleads/messenger-compress-bundle">Packagist</a> and <a href="https://github.com/mattleads/messenger-compress-bundle">GitHub</a> (MIT, Symfony 6.4–8.x, PHP 8.2+). The runnable walkthrough with the inspect command, the listener and the tamper scenario is at <a href="https://github.com/mattleads/messenger-compress-demo">github.com/mattleads/messenger-compress-demo</a>.</p><p>Custom compressors (Brotli, LZ4) plug in by implementing CompressorInterface and are picked up by the mattleads_messenger_compress.compressor tag. Custom encryptors implement EncryptorInterface. 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&#39;s what the issue tracker is for.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: <a href="https://github.com/mattleads/messenger-compress-bundle">https://github.com/mattleads/messenger-compress-bundle</a></p><h4>Let’s Connect!</h4><p>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:</p><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a></li><li>X (Twitter): <a href="https://x.com/MattLeads">https://x.com/MattLeads</a></li><li>Telegram: <a href="https://t.me/MattLeads">https://t.me/MattLeads</a></li><li>GitHub: <a href="https://github.com/mattleads">https://github.com/mattleads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=812de0184310" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Symfony Security, Passports and Custom Authenticators #1]]></title>
            <link>https://medium.com/@MattLeads/mastering-symfony-security-passports-and-custom-authenticators-1-ee35b7487053?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee35b7487053</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 16:23:51 GMT</pubDate>
            <atom:updated>2026-06-19T16:23:51.823Z</atom:updated>
            <content:encoded><![CDATA[<p>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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MVAo8lENIs3JfajdGu7Hg.jpeg" /></figure><p>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.</p><p>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: <strong>Authenticators and Passports</strong>.</p><p>This modern system breaks authentication down into distinct, logical phases:</p><ol><li><strong>Request Interception:</strong> Deciding whether an authenticator should handle a request.</li><li><strong>Passport Creation:</strong> Extracting user identity credentials and packaging them into an object representation.</li><li><strong>Passport Validation:</strong> Processing security checks (e.g., matching password hashes, validating CSRF states, checking user account status) via modular, reusable “Badges”.</li><li><strong>Outcome Resolution:</strong> Directing the next steps of the HTTP pipeline based on success or failure.</li></ol><p>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.</p><p>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.</p><h3>The Modern Security Pipeline</h3><p>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.</p><pre>Incoming Request<br>       │<br>       ▼<br>┌─────────────────────────────────────────┐<br>│           Firewall Matching             │ (security.yaml rules)<br>└────────────────────┬────────────────────┘<br>                     │ Match<br>                     ▼<br>┌─────────────────────────────────────────┐<br>│         Authenticator Selection         │ (supports() loop)<br>└────────────────────┬────────────────────┘<br>                     │ Handled<br>                     ▼<br>┌─────────────────────────────────────────┐<br>│           Passport Creation             │ (authenticate())<br>└────────────────────┬────────────────────┘<br>                     │ Passport Created<br>                     ▼<br>┌─────────────────────────────────────────┐<br>│     Authentication Event Dispatch       │ (CheckPassportEvent)<br>└────────────────────┬────────────────────┘<br>                     │ Badges Resolved<br>                     ▼<br>┌─────────────────────────────────────────┐<br>│           User Resolution               │ (UserProvider / Badges)<br>└────────────────────┬────────────────────┘<br>                     │ Validated<br>                     ▼<br>┌─────────────────────────────────────────┐<br>│      Success or Failure Resolution      │ (onAuthenticationSuccess / <br>└─────────────────────────────────────────┘  Failure)</pre><h3>Firewall Matching</h3><p>The entry point of the pipeline is governed by the <strong>security.yaml</strong> configuration. When a request enters the application, the <strong>FirewallMap</strong> iterates through all configured firewalls in chronological order. A firewall is matched using a regular expression defined by the <strong>pattern</strong> key (e.g. ^/api/).<br>If a match is found, the security system activates the firewall&#39;s corresponding request listener. If the firewall is marked with <strong>security: false</strong> (such as for assets or profiler paths), the security interceptor is bypassed completely.</p><h3>Authenticator Selection (The supports() Loop)</h3><p>Once a firewall is selected, it gathers all registered authenticators associated with it. The firewall loops through these authenticators and executes their <strong>supports(Request $request)</strong> method.<br>This method acts as a high-speed HTTP guard rail. It must return <strong>true</strong> if the authenticator knows how to extract credentials from the given request and <strong>false</strong> (or <strong>null</strong>) otherwise. Because this loop runs on every single request matched by the firewall, the <strong>supports</strong> 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.</p><h3>Passport Creation (The authenticate() Phase)</h3><p>If an authenticator’s <strong>supports()</strong> method returns <strong>true</strong>, the security system halts the selection loop and delegates responsibility to that authenticator’s <strong>authenticate(Request $request)</strong> method.<br>The sole responsibility of <strong>authenticate</strong> is to extract authentication tokens or credentials from the request and package them into a <strong>Passport</strong> object. If the request is missing essential criteria (e.g. an empty token header), the authenticator should throw an <strong>AuthenticationException</strong>. This terminates the process and routes execution to the failure handler.</p><h3>Passport Validation &amp; Events</h3><p>Once a Passport is returned Symfony’s security manager takes over. It fires a <strong>CheckPassportEvent</strong> in the event dispatcher. A series of system listeners hook into this event to validate the badges attached to the Passport:</p><ul><li>The user account status is checked (e.g. verifying if the user is enabled, locked or expired).</li><li>Credentials are validated (e.g. checking password hashes).</li><li>Custom security assertions are processed.</li></ul><p>If any listener throws an <strong>AuthenticationException</strong> during this event-driven phase, validation is aborted and the authentication fails.</p><h3>Success or Failure Resolution</h3><p>After validation concludes the pipeline branches depending on the outcome:</p><ul><li><strong>On Failure</strong>: The authenticator’s <strong>onAuthenticationFailure(Request $request, AuthenticationException $exception)</strong> method is triggered. It is responsible for returning a <strong>Response</strong> (such as a 401 JSON object or a redirected login form with error flash messages).</li><li><strong>On Success</strong>: The authenticator’s <strong>onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName)</strong> method is called. In a stateful web application, it typically returns a <strong>RedirectResponse</strong> to a dashboard. In a stateless API, it returns <strong>null</strong>, telling Symfony to bypass further security handling and allow the request to proceed seamlessly to the matched controller.</li></ul><h3>Deep Dive into Passports and Badges</h3><p>The genius of Symfony’s modern security architecture lies in its separation of concerns via <strong>Passports</strong> and <strong>Badges</strong>.</p><p>A <strong>Passport</strong> 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.</p><p>A <strong>Badge</strong> 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.</p><p>Symfony ships with several core Passports and Badges:</p><h3>Core Passports</h3><ol><li><strong>Passport</strong>: The generic implementation. It requires a UserBadge (to locate the user) and a <strong>CredentialsBadge</strong> (to verify the identity proof, such as a password).</li><li><strong>SelfValidatingPassport</strong>: A highly useful specialized subclass. It only requires a <strong>UserBadge</strong>. 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).</li></ol><h3>Core Badges</h3><ul><li><strong>UserBadge</strong>: The absolute minimum requirement for any Passport. It accepts a <strong>userIdentifier</strong> (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 <strong>UserInterface</strong> object. If no callback is specified, Symfony falls back on the default configured <strong>UserProvider</strong>.</li><li><strong>PasswordCredentials</strong>: 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.</li><li><strong>CsrfTokenBadge</strong>: 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.</li><li><strong>RememberMeBadge</strong>: Tells Symfony to generate a remember-me cookie on successful authentication, enabling automated persistent logins across sessions.</li></ul><h3>The Extensibility of Badges</h3><p>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 <strong>MfaPassedBadge</strong> to your Passport. A security event listener can then listen to <strong>CheckPassportEvent</strong>, inspect if the <strong>MfaPassedBadge</strong> is present and valid and reject the authentication if the badge is missing. This extensibility ensures your core authenticator logic remains simple and reusable.</p><h3>Deep Code Walkthrough</h3><p>Let us carefully analyze each method of our <strong>ApiKeyAuthenticator</strong> to understand the underlying mechanics:</p><h4>supports()</h4><p>The framework executes this method first. By using <strong>$request-&gt;headers-&gt;has(‘X-API-KEY’)</strong>, we cleanly scope the authenticator. If an external client requests <strong>/api/test</strong> but uses a standard browser session or JWT, this authenticator quietly steps aside (<strong>returns false</strong>), allowing other authenticators (like the JWT Authenticator) to evaluate the request instead.</p><h4>authenticate()</h4><p>If selected, we extract the header. We validate that the token is not empty. If it is empty, throwing <strong>CustomUserMessageAuthenticationException</strong> immediately halts execution.<br>If it is present, we instantiate <strong>SelfValidatingPassport</strong> and wrap our logic in a <strong>UserBadge</strong>.</p><p>The closure passed to the <strong>UserBadge</strong> is <strong>lazy-evaluated</strong>. 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.</p><h4>onAuthenticationSuccess()</h4><p>In typical session login forms, on success, you redirect users to <strong>/dashboard</strong>. However, for APIs, redirection is a massive anti-pattern. By returning <strong>null</strong>, we instruct Symfony’s Firewall listener to let the request continue down the pipeline to the matched Controller.</p><h4>onAuthenticationFailure()</h4><p>If any step of the <strong>authenticate()</strong> 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 <strong>strtr</strong> and output a clean, unified JSON structure with a HTTP 401 status.</p><h3>Testing &amp; Debugging Custom Authenticators</h3><p>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.</p><h3>Debugging Routes and Security via CLI</h3><p>Symfony includes a suite of command-line utilities that allow developers to inspect how security rules match against URLs without running a web server.</p><p>To check which firewall and authenticator will match a specific route, run the <strong>router:match</strong> debug utility:</p><pre>php bin/console router:match /api/test</pre><p>This output tells you exactly which controller and route matches your path.</p><p>To inspect your entire security configuration, including registered providers, hashers and firewalls, run the <strong>debug:security</strong> command:</p><pre>php bin/console debug:security</pre><p>This is extremely valuable for verifying that your custom authenticator has been correctly registered under the <strong>custom_authenticators</strong> key of your target firewall.</p><h3>Writing Automated Integration Tests</h3><p>To ensure our custom authenticator operates correctly under both successful and failing states, we can write automated integration tests using Symfony’s <strong>WebTestCase</strong>.</p><pre>namespace App\Tests\Security;<br><br>use App\Entity\User;<br>use Doctrine\ORM\EntityManagerInterface;<br>use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;<br>class ApiKeyAuthenticatorTest extends WebTestCase<br>{<br>    private EntityManagerInterface $entityManager;<br>    protected function setUp(): void<br>    {<br>        parent::setUp();<br>        // Boot the kernel and retrieve the entity manager<br>        self::bootKernel();<br>        $this-&gt;entityManager = self::getContainer()-&gt;get(EntityManagerInterface::class);<br>    }<br>    public function testRequestWithoutHeaderFails(): void<br>    {<br>        $client = static::createClient();<br>        $client-&gt;request(&#39;GET&#39;, &#39;/api/test&#39;);<br>        $this-&gt;assertResponseStatusCodeSame(401);<br>        $this-&gt;assertJson($client-&gt;getResponse()-&gt;getContent());<br>        $data = json_decode($client-&gt;getResponse()-&gt;getContent(), true);<br>        $this-&gt;assertArrayHasKey(&#39;message&#39;, $data);<br>        $this-&gt;assertSame(&#39;JWT Token not found&#39;, $data[&#39;message&#39;]);<br>    }<br>    public function testRequestWithInvalidTokenFails(): void<br>    {<br>        $client = static::createClient();<br>        $client-&gt;request(&#39;GET&#39;, &#39;/api/test&#39;, [], [], [<br>            &#39;HTTP_X-API-KEY&#39; =&gt; &#39;invalid_token_123&#39;<br>        ]);<br>        $this-&gt;assertResponseStatusCodeSame(401);<br>        $this-&gt;assertJson($client-&gt;getResponse()-&gt;getContent());<br>        $data = json_decode($client-&gt;getResponse()-&gt;getContent(), true);<br>        $this-&gt;assertSame(&#39;Invalid API Token&#39;, $data[&#39;message&#39;]);<br>    }<br>    public function testRequestWithValidTokenSucceeds(): void<br>    {<br>        $client = static::createClient();<br>        $user = new User();<br>        $user-&gt;setEmail(&#39;api_test_user@example.com&#39;);<br>        $user-&gt;setPassword(&#39;any_hashed_password&#39;);<br>        $user-&gt;setApiToken(&#39;valid_test_token_xyz&#39;);<br>        $this-&gt;entityManager-&gt;persist($user);<br>        $this-&gt;entityManager-&gt;flush();<br>        $client-&gt;request(&#39;GET&#39;, &#39;/api/test&#39;, [], [], [<br>            &#39;HTTP_X-API-KEY&#39; =&gt; &#39;valid_test_token_xyz&#39;<br>        ]);<br>        $this-&gt;assertResponseStatusCodeSame(200);<br>        $this-&gt;assertJson($client-&gt;getResponse()-&gt;getContent());<br>        $data = json_decode($client-&gt;getResponse()-&gt;getContent(), true);<br>        $this-&gt;assertSame(&#39;success&#39;, $data[&#39;status&#39;]);<br>        $this-&gt;assertSame(&#39;api_test_user@example.com&#39;, $data[&#39;user&#39;]);<br>        $this-&gt;entityManager-&gt;remove($user);<br>        $this-&gt;entityManager-&gt;flush();<br>    }<br>}</pre><h3>Why Automated Verification is Mandatory</h3><p>Manual browser testing is slow, error-prone and cannot easily be automated in CI/CD pipelines. By writing these integration tests, we prove that:</p><ol><li>The routing matches correctly.</li><li>The firewall is correctly enforcing security.</li><li>The database matches correctly under SQLite.</li><li>Edge cases (invalid keys, missing keys and valid keys) behave exactly as specified.</li></ol><h3>Best Practices for API Security</h3><p>When designing custom security components for production applications, several strict security rules must be enforced to protect your users and infrastructure.</p><h3>Use stateless: true Aggressively</h3><p>For any pure API firewall (e.g. JWT endpoints, API keys, OAuth endpoints), always specify <strong>stateless: true</strong> in your <strong>security.yaml</strong>.<br>By default, Symfony starts a PHP session and sends a <strong>PHPSESSID</strong> 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 <strong>CSRF (Cross-Site Request Forgery)</strong> attacks.<br>Setting <strong>stateless: true</strong> 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.</p><h3>Protect Exception Traces</h3><p>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.</p><ul><li><strong>Always</strong> throw <strong>CustomUserMessageAuthenticationException</strong> 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.</li><li>Ensure <strong>APP_ENV=prod</strong> is set in production to instantly disable debug logs and stack trace rendering in HTTP outputs.</li></ul><h3>Enforce SSL/TLS</h3><p>API keys and JWT tokens are sent in plaintext HTTP headers (<strong>X-API-KEY</strong>, <strong>Authorization: Bearer</strong>). If a client requests your API over an unencrypted <strong>http://</strong> connection, anyone on the network can sniff the packets and steal the token, completely compromising the account.</p><ul><li>Configure your web server (Nginx, Apache) to force redirect all traffic to <a href="https://."><strong>https://</strong>.</a></li><li>In <strong>security.yaml</strong>, enforce HTTPS matching using the <strong>requires_channel</strong> parameter:</li></ul><pre>access_control:<br>      - { path: ^/api, roles: ROLE_USER, requires_channel: https }</pre><h3>Token Salting &amp; Hashing</h3><p>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.</p><ul><li><strong>Actionable Advice</strong>: Treat API tokens exactly like passwords. When creating an API key, generate a cryptographically secure random string, output it to the user <em>once</em> but store only the <strong>SHA-256 hash</strong> of that key in your database.</li><li>In your custom authenticator, when extracting the key from the header, hash it before running your query:</li></ul><pre>$hashedToken = hash(&#39;sha256&#39;, $apiToken);<br>  $user = $this-&gt;userRepository-&gt;findOneBy([&#39;apiToken&#39; =&gt; $hashedToken]);</pre><p>This guarantees that even if your database is entirely breached, no API keys are compromised.</p><h3>Conclusion</h3><p>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 <strong>Passports</strong> and <strong>Badges</strong>, the framework empowers developers to write code that is clean, secure, testable and highly maintainable.</p><p>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.</p><h3>Next Up — Scaling to Enterprise Security</h3><p>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.</p><p>In our next article, <strong>“Mastering Enterprise Authentication: JWT Customization and OAuth2 Pipelines in Symfony”</strong>, we will take this application to the next level:</p><ul><li>We will implement cryptographically signed <strong>JSON Web Tokens (JWT)</strong> with custom payload data.</li><li>We will integrate <strong>JWT Refresh Tokens</strong> to build seamless session persistence with robust <strong>Refresh Token Rotation (RTR)</strong> to prevent replay attacks.</li><li>We will wire up a full <strong>Google OAuth2 Social Login</strong> pipeline, demonstrating how to keep our authentication DRY by decoupling registration logic into a specialized reusable <strong>User Provisioning Service</strong>.</li></ul><p>Source Code: Please DM me if you need access to the project’s GitHub repository.</p><h3>Let’s Connect!</h3><p>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:</p><ul><li>LinkedIn: [<a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a>]</li><li>X (Twitter): [<a href="https://x.com/MattLeads">https://x.com/MattLeads</a>]</li><li>Telegram: [<a href="https://t.me/MattLeads">https://t.me/MattLeads</a>]</li><li>GitHub: [<a href="https://github.com/mattleads">https://github.com/mattleads</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee35b7487053" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOC 2 Blueprint: Beyond RBAC with AppLevel Infrastructure Isolation & Key Sharding. Part #2]]></title>
            <link>https://medium.com/@MattLeads/the-soc-2-blueprint-beyond-rbac-with-applevel-infrastructure-isolation-key-sharding-part-2-31b43c660e4d?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b43c660e4d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 14:47:15 GMT</pubDate>
            <atom:updated>2026-06-04T14:47:15.881Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@MattLeads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-a146e8a57b12">Part 1</a>, 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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utunOJa8-F8tYIIKlMBoUQ.jpeg" /></figure><p>Under SOC 2, two critical principles often challenge developers:</p><ol><li><strong>Log Integrity (Audit Trail):</strong> You must prove that security logs are immutable and cannot be tampered with, even if the primary database is compromised.</li><li><strong>Key Lifecycle Management:</strong> 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.</li></ol><p>In this deep dive, we will implement <strong>Audit Trail Isolation</strong> using the <strong>Outbox Pattern</strong> and a <strong>Distributed Key Management Service (KMS)</strong> with <strong>Master Key Sharding</strong>.</p><h3>Physical Isolation - The Three-Database Architecture</h3><p>To fulfill SOC 2 requirements, we move away from a monolithic data store. We will configure three physically and logically separate SQLite databases:</p><ol><li><strong>Primary DB (data.db):</strong> Stores users, encrypted documents and envelopes.</li><li><strong>Audit DB (audit.db):</strong> Stores immutable log entries. It should ideally be on a separate mount point with <strong>“Append-Only”</strong> permissions in production.</li><li><strong>Keys DB (keys.db):</strong> Stores the encrypted pool of Master Keys.</li></ol><h4>Configuring Multiple Entity Managers</h4><p>In Symfony’s <strong>doctrine.yaml</strong>, we define three connections and three entity managers. This allows us to inject a specific manager (e.g., <a href="http://twitter.com/doctrine">@doctrine</a>.orm.audit_entity_manager) into our services, ensuring they can only “see” their designated database.</p><pre># config/packages/doctrine.yaml<br>doctrine:<br>    dbal:<br>        connections:<br>            default:<br>                url: &#39;%env(resolve:DATABASE_URL)%&#39;<br>            audit:<br>                url: &#39;%env(resolve:AUDIT_DATABASE_URL)%&#39;<br>            keys:<br>                url: &#39;%env(resolve:KEYS_DATABASE_URL)%&#39;<br><br>    orm:<br>        entity_managers:<br>            default:<br>                connection: default<br>                mappings:<br>                    App: { type: attribute, dir: &#39;%kernel.project_dir%/src/Entity&#39;, prefix: &#39;App\Entity&#39; }<br>            audit:<br>                connection: audit<br>                mappings:<br>                    gedmo_loggable: { type: attribute, dir: &#39;%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Loggable/Entity&#39;, prefix: &#39;Gedmo\Loggable\Entity&#39; }<br>            keys:<br>                connection: keys<br>                mappings:<br>                    KeyStore: { type: attribute, dir: &#39;%kernel.project_dir%/src/Entity/KeyStore&#39;, prefix: &#39;App\Entity\KeyStore&#39; }</pre><h3>The Immutable Audit Trail - Outbox Pattern</h3><p>A common mistake is to write logs to a separate database synchronously. This creates two problems:</p><ul><li><strong>Performance:</strong> Every document save now waits for two database writes.</li><li><strong>Atomicity:</strong> If the primary DB saves but the Audit DB fails, you have an unlogged action — a major SOC 2 violation.</li></ul><h4>Symfony Messenger + Outbox Pattern</h4><p>The Outbox Pattern ensures that business data and the intent to log are saved in the same atomic SQL transaction.</p><ol><li><strong>Capture:</strong> During the primary Entity Manager’s onFlush event, we identify new LogEntry entities.</li><li><strong>Queue:</strong> We dispatch an <strong>AuditLogMessage</strong> to the Symfony Messenger bus.</li><li><strong>Outbox:</strong> We use the doctrine://default transport (or any other). This saves the message into a messenger_messages table in the Primary DB.</li><li><strong>Process:</strong> A background worker consumes the message and uses the <strong>Audit Entity Manager</strong> to move the data to <strong>audit.db</strong>.</li></ol><p>This architecture provides Asynchronous Persistence with Synchronous Reliability.</p><pre>// src/EventListener/AuditLogMoverListener.php<br>public function onFlush(OnFlushEventArgs $args): void<br>{<br>    $uow = $args-&gt;getObjectManager()-&gt;getUnitOfWork();<br><br>    foreach ($uow-&gt;getScheduledEntityInsertions() as $entity) {<br>        if ($entity instanceof LogEntry) {<br>            // Track logs to be moved to the audit database<br>            $this-&gt;logsToMove-&gt;attach($entity);<br>        }<br>    }<br>}<br><br>public function postFlush(PostFlushEventArgs $args): void<br>{<br>    foreach ($this-&gt;logsToMove as $log) {<br>        // Dispatch to Messenger for asynchronous processing<br>        $this-&gt;messageBus-&gt;dispatch(new AuditLogMessage(...$log-&gt;getData()));<br>        <br>        // Remove from primary DB to keep it clean<br>        $args-&gt;getObjectManager()-&gt;remove($log);<br>    }<br>    $args-&gt;getObjectManager()-&gt;flush();<br>}</pre><h3>Distributed Key Management (KMS)</h3><p>The <strong>“Server Master Key”</strong> used in <a href="https://medium.com/@MattLeads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-a146e8a57b12">Part 1</a> is a liability. If it’s stored in a <strong>.env</strong> file and that file is leaked, your entire backup recovery system is compromised.</p><h4>The “Dual Lock” Root Key Strategy</h4><p>We store our <strong>Master Keys </strong>in the <strong>keys.db</strong>. However, we never store them in plain text. Every Master Key is encrypted using a <strong>ROOT_KEY</strong> stored in the server’s environment.</p><ul><li>To access a document’s DEK, you need the Keys DB AND the Environment ROOT_KEY.</li><li>This fulfills the SOC 2 requirement for “<strong>Separation of Duties”</strong> and <strong>“Layered Defense”.</strong></li></ul><h4>Master Key Sharding - Reducing the Blast Radius</h4><p>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.</p><p>We maintain a pool of 10 active Master Keys. When creating a document, we pick one deterministically:</p><pre>// src/Security/MasterKeyStore.php<br>public function getActiveKeyData(): array<br>{<br>    $activeKeys = $this-&gt;getActiveKeyEntities();<br>    <br>    // Selection Algorithm: Pick one deterministically based on current millisecond<br>    $index = (int) (microtime(true) * 1000) % count($activeKeys);<br>    $selectedKey = $activeKeys[$index];<br><br>    return [<br>        &#39;id&#39; =&gt; $selectedKey-&gt;getId(),<br>        &#39;key&#39; =&gt; $this-&gt;decryptWithRootKey($selectedKey-&gt;getEncryptedKey())<br>    ];<br>}</pre><p>By using millisecond-precision timestamps, we ensure a near-perfect distribution.</p><h4>The Blast Radius Math</h4><p>In a standard system, a compromised Master Key = <strong>100% data loss</strong>.<br>In our sharded system, a compromised Master Key = <strong>~10% data loss</strong>.<br>This 90% reduction in risk is exactly what SOC 2 auditors look for in high-maturity organizations.</p><h3>Key Lifecycle &amp; Rotation</h3><p>Master Keys are not eternal. They have a lifecycle defined by <strong>activatedAt</strong> and <strong>deactivatedAt</strong> timestamps.</p><h4>Automatic Selection for Encryption</h4><p>When <strong>encryptDekForServer</strong> is called, the <strong>MasterKeyStore</strong> always provides a key from the currently active pool.</p><h4>Versioned Decryption</h4><p>Every encrypted payload in our system is prefixed with its <strong>Key ID: keyId:initializationVector:authenticationTag:cipherText</strong></p><p>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.</p><pre>// src/Security/EnvelopeCryptoService.php<br>public function decryptDekFromServer(string $serverEncryptedDek): ?string<br>{<br>    [$keyId, $encryptedPayload] = explode(&#39;:&#39;, $serverEncryptedDek, 2);<br>    <br>    // Fetch the specific key used for THIS record<br>    $masterKey = $this-&gt;masterKeyStore-&gt;getKeyById((int) $keyId);<br>    <br>    return $this-&gt;decryptContent($encryptedPayload, $masterKey);<br>}</pre><h3>Security Performance -The Stateful Listener</h3><p>Moving logs and managing sharded keys can be computationally expensive. In our <strong>AuditLogMoverListener</strong>, we use an optimized Stateful Tracking pattern:</p><ol><li>We use SplObjectStorage to track entities within a single request.</li><li>We only process the exact logs created in that request.</li><li>We avoid findAll() or heavy database scans, ensuring our security layer adds only negligible millisecond overhead to the user experience.</li></ol><h3>Final Architecture Summary</h3><p>We have built a “Fortress” application:</p><ul><li><strong>Record-Level Privacy:</strong> Every document has a unique AES-256 key.</li><li><strong>Zero Trust Logs</strong>: Audit trails are physically isolated and moved asynchronously via the Outbox pattern.</li><li><strong>Sharded Authority:</strong> Master Keys are pooled and distributed, reducing the impact of any single failure.</li><li><strong>Dual-Lock Protection:</strong> The KMS database is itself encrypted by an environment-level Root Key.</li></ul><h3>Closing Thoughts</h3><p>SOC 2 compliance is often viewed as a “check-the-box” exercise in documentation. But we have the power to make it a <strong>technical reality</strong>. By using the patterns described in these two articles — <strong>Envelope Encryption</strong>, <strong>Outbox Isolation</strong> and <strong>Key Sharding</strong> — 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.</p><p><strong>Source Code:</strong> You can find the full implementation and follow the project’s progress on GitHub: [<a href="https://github.com/mattleads/SOC2Database">https://github.com/mattleads/SOC2Database</a>]</p><h4>Let’s Connect!</h4><p>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:</p><ul><li>LinkedIn: [<a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a>]</li><li>X (Twitter): [<a href="https://x.com/MattLeads">https://x.com/MattLeads</a>]</li><li>Telegram: [<a href="https://t.me/MattLeads">https://t.me/MattLeads</a>]</li><li>GitHub: [<a href="https://github.com/mattleads">https://github.com/mattleads</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b43c660e4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOC 2 Blueprint: Beyond RBAC with AppLevel Encryption and Audit Isolation. Part #1]]></title>
            <link>https://medium.com/@MattLeads/the-soc-2-blueprint-beyond-rbac-with-applevel-encryption-and-audit-isolation-part-1-a146e8a57b12?source=rss-a50875c323fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a146e8a57b12</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Matt Mochalkin]]></dc:creator>
            <pubDate>Wed, 27 May 2026 11:49:57 GMT</pubDate>
            <atom:updated>2026-05-27T11:56:22.071Z</atom:updated>
            <content:encoded><![CDATA[<p>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: <strong>How can you prove that only authorized users accessed specific data and how do you protect that data if your perimeter fails?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5KrPoMQEm64z-_Kg_aR5g.jpeg" /></figure><p>Most developers believe that standard <strong>Role-Based Access Control (RBAC)</strong> 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.</p><p>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 <strong>data is cryptographically isolated</strong> at the record level.</p><h3>The Architectural Strategy - Hybrid Cryptography</h3><p>Before writing a single line of code we must define our cryptographic strategy. We face a classic dilemma:</p><ol><li><strong>Symmetric Encryption (AES):</strong> 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.</li><li><strong>Asymmetric Encryption (RSA):</strong> Great for sharing secrets securely using Public/Private key pairs, but incredibly slow for large data and has strict limits on payload size.</li></ol><h4>The Hybrid Solution - The Envelope Pattern</h4><p>Envelope Encryption combines the best of both worlds.</p><ul><li><strong>Step A: </strong>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.</li><li><strong>Step B:</strong> We take that small DEK and “wrap” (encrypt) it using the recipient’s RSA Public Key (The KEK — Key Encrypting Key).</li><li><strong>Step C:</strong> We store the encrypted content and the “wrapped” DEK (the Envelope) in the database.</li></ul><p>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.</p><h3>Deep Dive into the Primitives</h3><p>Standard AES modes like <strong>CBC (Cipher Block Chaining)</strong> 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).</p><p><strong>GCM (Galois/Counter Mode)</strong> 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.</p><p>When wrapping keys, we use <strong>OAEP (Optimal Asymmetric Encryption Padding)</strong>. 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.</p><h3>Data Modeling for Cryptographic Isolation</h3><p>We need a database schema that supports this hybrid model. We will use Symfony’s Doctrine ORM with Attribute-based mapping.</p><h4>The User Entity - The Key Custodian</h4><p>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.</p><pre>namespace App\Entity;<br><br>use Doctrine\ORM\Mapping as ORM;<br>use Symfony\Component\Security\Core\User\UserInterface;<br><br>#[ORM\Entity]<br>#[ORM\Table(name: &#39;users&#39;)]<br>class User implements UserInterface<br>{<br>    #[ORM\Id, ORM\GeneratedValue, ORM\Column(type: &#39;integer&#39;)]<br>    private ?int $id = null;<br><br>    #[ORM\Column(type: &#39;string&#39;, length: 180, unique: true)]<br>    private ?string $email = null;<br><br>    // The KEK (Key Encrypting Key) Public Component<br>    #[ORM\Column(type: &#39;text&#39;)]<br>    private ?string $publicKey = null;<br><br>    // ... standard getters and setters ...<br>}</pre><h4>The Document Entity - The Encrypted Payload</h4><p>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.</p><pre>#[ORM\Entity]<br>#[ORM\Table(name: &#39;documents&#39;)]<br>class Document<br>{<br>    #[ORM\Id, ORM\GeneratedValue, ORM\Column(type: &#39;integer&#39;)]<br>    private ?int $id = null;<br><br>    #[ORM\ManyToOne(targetEntity: User::class)]<br>    #[ORM\JoinColumn(nullable: false)]<br>    private ?User $owner = null;<br><br>    // The AES-256-GCM Encrypted Content<br>    #[ORM\Column(type: &#39;text&#39;)]<br>    private ?string $encryptedContent = null;<br><br>    // The DEK encrypted with the Server&#39;s Master Key (Backup/Audit)<br>    #[ORM\Column(type: &#39;string&#39;, length: 255)]<br>    private ?string $serverEncryptedDek = null;<br>}</pre><h4>The DocumentShare Entity - The Envelope Store</h4><p>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.</p><pre>#[ORM\Entity]<br>#[ORM\Table(name: &#39;document_shares&#39;)]<br>class DocumentShare<br>{<br>    #[ORM\ManyToOne(targetEntity: Document::class, inversedBy: &#39;shares&#39;)]<br>    #[ORM\JoinColumn(nullable: false, onDelete: &#39;CASCADE&#39;)]<br>    private ?Document $document = null;<br><br>    #[ORM\ManyToOne(targetEntity: User::class)]<br>    #[ORM\JoinColumn(nullable: false, onDelete: &#39;CASCADE&#39;)]<br>    private ?User $sharedWith = null;<br><br>    // The DEK encrypted specifically for $sharedWith&#39;s RSA Public Key<br>    #[ORM\Column(type: &#39;text&#39;)]<br>    private ?string $userEncryptedDek = null;<br>}</pre><h3>Implementing the Cryptographic Engine</h3><p>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.</p><h4>The Interface - EnvelopeCryptoServiceInterface</h4><p>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 <strong>services.yaml</strong>.</p><pre>interface EnvelopeCryptoServiceInterface {<br>    public function generateDek(): string;<br>    public function encryptContent(string $plainText, string $dek): string;<br>    public function decryptContent(string $payload, string $dek): ?string;<br>    public function encryptDekForUser(string $dek, string $publicKey): string;<br>    public function decryptDekWithUserKey(string $wrappedDek, string $privateKey): string;<br>}</pre><h4>The Implementation - EnvelopeCryptoService</h4><p>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.</p><pre>public function encryptContent(string $plainText, string $dek): string {<br>    $ivLength = openssl_cipher_iv_length(&#39;aes-256-gcm&#39;);<br>    $iv = random_bytes($ivLength);<br>    <br>    // GCM handles the $tag automatically<br>    $cipherText = openssl_encrypt($plainText, &#39;aes-256-gcm&#39;, $dek, OPENSSL_RAW_DATA, $iv, $tag);<br>    <br>    // Package: [IV][TAG][CIPHERTEXT]<br>    return base64_encode($iv . $tag . $cipherText);<br>}</pre><h3>The Orchestrator - DocumentManager</h3><p>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.</p><p>It has three main responsibilities:</p><ol><li><strong>Creation:</strong> Orchestrates DEK generation, content encryption and the creation of the primary owner’s envelope.</li><li><strong>Sharing:</strong> Retrieves the DEK (using the server’s backup envelope) and re-wraps it for a new recipient.</li><li><strong>Reading:</strong> Locates the user’s specific envelope and performs the multi-stage decryption.</li></ol><p>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.</p><h3>Logical Security - Symfony Voters</h3><p>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 <strong>Symfony Voter</strong>.</p><p>The <strong>DocumentVoter</strong> checks two conditions:</p><ol><li>Does the user own the document?</li><li>Is there a <strong>DocumentShare</strong> record mapping the document to the user?</li></ol><p>By placing this check in a Voter, we can use the <strong>#[IsGranted]</strong> attribute in our controllers, keeping them incredibly clean.</p><pre>#[Route(&#39;/documents/{id}&#39;, name: &#39;document_view&#39;)]<br>#[IsGranted(&#39;DOCUMENT_VIEW&#39;, subject: &#39;document&#39;)]<br>public function view(Document $document, DocumentManagerInterface $manager): Response {<br>    // If the code execution gets here, we KNOW the user has logical access.<br>    // Now we just need to verify they have the cryptographic key.<br>}</pre><h3>Conclusion</h3><p>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.</p><p>However, we still have two problems:</p><ol><li><strong>Log Leakage:</strong> If we log every change, do the logs themselves contain sensitive data?</li><li><strong>Key Centralization:</strong> If the server’s Master Key is stolen, all document DEKs can be recovered.</li></ol><p>In Part 2, we will solve these issues by implementing <strong>Asynchronous Audit Isolation</strong> and a <strong>Sharded Key Management Service (KMS) </strong>and share full implementation GitHub repo.</p><h4>Let’s Connect!</h4><p>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:</p><ul><li>LinkedIn: [<a href="https://www.linkedin.com/in/matthew-mochalkin/">https://www.linkedin.com/in/matthew-mochalkin/</a>]</li><li>X (Twitter): [<a href="https://x.com/MattLeads">https://x.com/MattLeads</a>]</li><li>Telegram: [<a href="https://t.me/MattLeads">https://t.me/MattLeads</a>]</li><li>GitHub: [<a href="https://github.com/mattleads">https://github.com/mattleads</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a146e8a57b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>