<?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 Igor Bulygin on Medium]]></title>
        <description><![CDATA[Stories by Igor Bulygin on Medium]]></description>
        <link>https://medium.com/@boehpyk?source=rss-8c51ffe11fdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YkcevDJVwg_mRLTb.</url>
            <title>Stories by Igor Bulygin on Medium</title>
            <link>https://medium.com/@boehpyk?source=rss-8c51ffe11fdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:21:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@boehpyk/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[Searching for Dostoyevsky: How I Chose a Search Stack in Postgres]]></title>
            <link>https://medium.com/@boehpyk/searching-for-dostoyevsky-how-i-chose-a-search-stack-in-postgres-e2afedcfe8dd?source=rss-8c51ffe11fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2afedcfe8dd</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[full-text-search]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Igor Bulygin]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:11:01 GMT</pubDate>
            <atom:updated>2026-11-03T10:11:01.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Dostoevsky. Dostoyevsky. Dostoevskii. Dostoevski.</p><p>Same man. Four spellings. Every English bookshelf has at least two of them, and every reader is sure theirs is the right one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SirroZuWU4DD2UBEJy8_TA.jpeg" /></figure><p>Samolit.com, a self-publishing platform I work on, had 6,568 published books and no way to search them. If you landed on a book page and half-remembered “that Dostoevsky novel about the brothers”, you had to open a category and scroll. And hope.</p><p>The author list did have a search box. It used ILIKE &#39;%dostoyevsky%&#39;. Our catalog spells him &quot;Dostoevsky&quot;. You can guess how that went.</p><p>So I had to add search. It sounds like a checkbox. It’s actually a fork in the road. There are three different technologies with the word “search” attached to them, and they fail in completely different ways. This is how I picked between them, and what I’d tell myself before I started.</p><h3>The whole spec is three inputs</h3><p>Before comparing anything, I wrote down what a visitor actually types. Three things:</p><ol><li>An author’s name. “Dostoevsky”, or “Fyodor Dostoyevsky”.</li><li>A book title. “The Brothers Karamazov”.</li><li>Something they half-remember from the description.</li></ol><p>That’s the spec. Every decision below follows from it.</p><p>Two more facts matter. The first: words change shape. “Brothers” and “brother”. “Running” and “runs”. ILIKE matches letters, not words, so it finds one shape and misses the others. The user sees &quot;no results&quot; and decides the site is broken. They&#39;re not wrong.</p><p>English is the gentle case here. Most of Samolit’s catalog is in Russian, which has six grammatical cases, so a single noun can come in a dozen forms. I’ll stick to English examples. The mechanics are identical, the stakes are just higher.</p><p>The second fact I almost missed. I’ll get to it.</p><h3>Option one: Postgres full-text search</h3><p>It’s already inside Postgres. Nothing to install.</p><p>Full-text search turns a document into normalized <em>lexemes</em>. That process is called stemming, and it’s the whole point. Here’s real output from Postgres 16:</p><pre>SELECT to_tsvector(&#39;english&#39;, &#39;The Brothers Karamazov&#39;);<br>--   &#39;brother&#39;:2 &#39;karamazov&#39;:3<br>SELECT to_tsvector(&#39;english&#39;, &#39;The Running Man&#39;);<br>--   &#39;man&#39;:3 &#39;run&#39;:2</pre><p>“Brothers” became brother. &quot;Running&quot; became run. &quot;The&quot; disappeared, because it&#39;s a stopword and carries nothing.</p><p>Now the payoff. A visitor types “runs”. That word isn’t in the title anywhere. Postgres stems the query through the same English dictionary, gets run, and matches:</p><pre>SELECT &#39;The Running Man&#39; ILIKE &#39;%runs%&#39;;                                      -- false<br>SELECT to_tsvector(&#39;english&#39;, &#39;The Running Man&#39;) @@ to_tsquery(&#39;english&#39;, &#39;runs&#39;);  -- true</pre><p>The user typed a word we never stored and found the book anyway. In English that’s a nice bonus. In Russian it’s the difference between search that works and search that doesn’t.</p><p><strong>Where it falls over: spelling.</strong> Type “Dostoyevsky” and look at what each side turns into:</p><pre>SELECT to_tsvector(&#39;english&#39;, &#39;Fyodor Dostoevsky&#39;);   -- &#39;dostoevski&#39;:2 &#39;fyodor&#39;:1<br>SELECT to_tsquery(&#39;english&#39;, &#39;Dostoyevsky&#39;);          -- &#39;dostoyevski&#39;</pre><p>dostoevski and dostoyevski. One letter apart, and to full-text search they are two unrelated words. Zero rows. The stemmer takes endings off. It was never built to fix spelling, and transliterated Russian names are basically spelling problems wearing a coat.</p><h3>Option two: pg_trgm</h3><p>This extension covers exactly that gap.</p><p>pg_trgm cuts strings into overlapping three-letter pieces called trigrams:</p><pre>SELECT show_trgm(&#39;tolstoy&#39;);<br>--   {&quot;  t&quot;,&quot; to&quot;,lst,ols,&quot;oy &quot;,sto,tol,toy}</pre><p>Similarity is just counting. How many pieces do two strings share, out of all the pieces they have? “Dostoyevsky” and “Dostoevsky” differ by one letter. One letter breaks at most three trigrams. The rest survive:</p><pre>SELECT similarity(&#39;dostoyevsky&#39;, &#39;dostoevsky&#39;);   -- 0.64, comfortably over the 0.3 bar</pre><p>The variant spelling is caught. Not because anything understood the name. Because the strings <em>look</em> alike.</p><p><strong>Where it falls over: it knows nothing about language.</strong> It doesn’t know “run” and “running” are the same word. It just notices they share some letters, which sometimes works and sometimes doesn’t. It will also happily tell you “listen” and “silent” have something in common.</p><p>That’s when it clicked for me. These two aren’t competitors:</p><ul><li>Full-text search answers <em>“you typed a real word, maybe in a different form.”</em></li><li>Trigrams answer <em>“you typed it differently.”</em></li></ul><p>Neither can do the other’s job.</p><h3>Option three: pgvector</h3><p>The one everyone wants to talk about in 2026.</p><p>You run the text through an embedding model and store a few hundred numbers per book. The model places similar meanings close together. To search, you embed the query and look for the nearest neighbours.</p><p>When it works, it’s spooky. Type “a man kills a pawnbroker and goes mad with guilt” and get <em>Crime and Punishment</em>. Not one of those words is in the title.</p><p>So why not this?</p><p>Because two of my three inputs are about exact words, and vector search is bad at exact words.</p><p>Type “Tolstoy”. The system embeds it, finds the nearest neighbours in meaning, and returns Dostoevsky. Turgenev. Chekhov. All nineteenth-century Russian novelists. All very <em>similar</em> to Tolstoy. All wrong. The user typed a name and got a literature seminar.</p><p>No setting fixes this. The tool is working correctly. Embeddings only know what things are <em>like</em>. They have no idea that you typed this exact string and meant it.</p><p>Semantic search is for “recommend something like X”. I was building “find X”. Different feature.</p><p>There was a boring reason too. I checked which extensions our database could install:</p><pre>SELECT name FROM pg_available_extensions WHERE name IN (&#39;pg_trgm&#39;,&#39;unaccent&#39;,&#39;vector&#39;);<br>--   pg_trgm  | 1.6 | not installed<br>--   unaccent | 1.1 | not installed</pre><p>vector isn&#39;t even on the list. The stock postgres:16-alpine image doesn&#39;t ship it. Solvable, but I wasn&#39;t going to swap the database image for a tool that returns the wrong author.</p><h3>And the one you buy</h3><p>There’s a fourth option: Algolia, Meilisearch, Typesense, Elasticsearch. Usually through Laravel Scout.</p><p>The case for it is real. Typo tolerance, synonyms and highlighting on day one. Fast enough for a type-ahead box.</p><p>Here’s why it lost:</p><ul><li><strong>A second datastore to keep in sync</strong>, across a network, through queued jobs that fail quietly.</li><li><strong>The pricing is shaped the wrong way.</strong> Algolia charges per search. A type-ahead box over 8,700 records makes lots of searches against very few records. That’s the expensive axis.</li><li><strong>Self-hosting means another container.</strong> Another backup, another upgrade, on top of the eight services already in the compose file.</li><li><strong>We’d be buying scale we don’t have.</strong></li></ul><h3>The scorecard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*tSUyronshzMw0LWsxWSwoQ.png" /></figure><h3>The verdict</h3><p>Full-text search goes first. If it returns fewer than three rows, trigrams try to catch the spelling. Merge the results, drop duplicates, full-text hits on top.</p><p>The smart tool goes first. The forgiving one catches what falls through.</p><p>Is it fast? Yes, but that wasn’t the question. The primary query takes 2.4 ms. A full reindex of everything takes 14 seconds. At 8,713 rows, every option on that table is fast. Even ILIKE with no index would answer in milliseconds. Size argued for nothing. Language argued for everything.</p><h3>The box that only speaks query language</h3><p>The search box searches as you type. You’ve typed “dosto” and you expect Dostoevsky to show up already. Full-text search only matches whole words, unless you mark the last word as a prefix with :*:</p><pre>SELECT to_tsvector(&#39;english&#39;, &#39;Fyodor Dostoevsky&#39;) @@ to_tsquery(&#39;english&#39;, &#39;dosto&#39;);    -- false<br>SELECT to_tsvector(&#39;english&#39;, &#39;Fyodor Dostoevsky&#39;) @@ to_tsquery(&#39;english&#39;, &#39;dosto:*&#39;);  -- true</pre><p>The catch is that to_tsquery doesn&#39;t take plain text. It takes a little query language with its own operators: &amp; for AND, | for OR, ! for NOT, brackets, :*. Give it what a normal person types and it throws an error:</p><pre>SELECT to_tsquery(&#39;english&#39;, &#39;fyodor dosto&#39;);  -- ERROR: syntax error in tsquery<br>SELECT to_tsquery(&#39;english&#39;, &#39;war (&#39;);         -- ERROR: syntax error in tsquery<br>SELECT to_tsquery(&#39;english&#39;, &#39;!&#39;);             -- ERROR: no operand in tsquery</pre><p>In a box that fires on every keystroke, that’s a 500 error waiting for the first person who types two words or a bracket.</p><p>Postgres has a friendlier function for exactly this, websearch_to_tsquery. It accepts anything a user types and never throws. But it also throws away :*, so &quot;dosto&quot; finds nothing until you&#39;ve typed the whole name. Useless for a live dropdown.</p><p>So I wrote the translation myself. A small class takes whatever the user typed, removes every character that means something in the query language, joins the words with &amp;, and adds :* to the last word only. &quot;fyodor dosto&quot; becomes fyodor &amp; dosto:*. A bracket, a | or a stray ! just disappears.</p><p>That little class sits between the user’s keyboard and the database, so I treat it as the most security-sensitive code in the feature. It has 23 tests, most of them nasty inputs. If you take one thing from this section: whenever a database function has its own mini-language, user input needs translating before it gets there, even when your SQL parameters are bound correctly.</p><h3>The second fact</h3><p>Remember the second fact I almost missed?</p><p>The original plan was written against a corpus with three languages and <strong>8</strong> published books that weren’t in Russian. Then we synced production, and I re-ran the numbers.</p><p><strong>1,050.</strong> Twelve languages. 983 of them in English.</p><p>A number that moves 130 times usually kills a design. This one made it stronger, because of the next thing.</p><h3>What I’d tell my past self</h3><p><strong>Read the database’s refusals carefully. They design your schema.</strong></p><p>The obvious way to store the search data is a generated column on books:</p><pre>ALTER TABLE books ADD COLUMN search_vector tsvector<br>  GENERATED ALWAYS AS (to_tsvector(&#39;russian&#39;, title)) STORED;</pre><p>Postgres keeps it fresh for free. Lovely. Except &#39;russian&#39; is hardcoded, and now I have twelve languages. So you try to read the language from the row:</p><pre>GENERATED ALWAYS AS (to_tsvector(language_code, title)) STORED   -- rejected</pre><p>Postgres says no. A generated column has to be IMMUTABLE, and to_tsvector with a language from a column is only STABLE, because someone could change a dictionary tomorrow. The language has to be a literal. One stemmer for every row. The Russian stemmer chewing on English books.</p><p>So Samolit has a separate search_documents table, written from PHP, which picks the stemmer per row. Not because a table is elegant. Because the elegant option is illegal. With 8 non-Russian books that was a mild preference. With 1,050 it&#39;s obviously correct, and I found out by running a query instead of by shipping.</p><p><strong>Write and read have to mangle text the same way.</strong> We use unaccent, so &quot;Selma Lagerlöf&quot; is stored as lagerlof. That only works if the search query goes through unaccent too. Then &quot;Lagerlof&quot; and &quot;Lagerlöf&quot; both find her. Do it on one side only and search returns nothing. No error. No log line. Just an empty dropdown.</p><p><strong>Check the fallback actually fires.</strong> Although using similarity() looks right, it never once matched anything:</p><pre>SELECT similarity     (&#39;dostoevksy&#39;, &#39;fyodor mikhailovich dostoevsky&#39;);   -- 0.20, under the 0.3 bar<br>SELECT word_similarity(&#39;dostoevksy&#39;, &#39;fyodor mikhailovich dostoevsky&#39;);   -- 0.64, matches</pre><p>similarity() compares against the whole string, and the stored string is always a full name. One short typo against three words never gets past the bar. word_similarity() looks for the best matching <em>word</em>. Same index, same data, and now a feature that works instead of one that&#39;s just decoration.</p><p><strong>Translate user input before it reaches a query language.</strong> Bound SQL parameters protect you from SQL injection. They don’t protect a function that has its own syntax, like to_tsquery in the section above.</p><p><strong>Leave the door open.</strong> Search sits behind one interface. If we ever outgrow Postgres, swapping in Meilisearch is one line in a service provider. The Livewire components won’t know. That’s what made it cheap to start simple: being wrong later costs one binding.</p><p>And the short version, for anyone standing at the same fork:</p><p>Find the three things your users actually type. Then pick the tools that fail on the fewest of them. Mine weren’t the fashionable ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2afedcfe8dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Can’t Tell the AI Not To: One Interview Question About Agent Security]]></title>
            <link>https://medium.com/@boehpyk/you-cant-tell-the-ai-not-to-one-interview-question-about-agent-security-39f9b8484324?source=rss-8c51ffe11fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f9b8484324</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai-security]]></category>
            <category><![CDATA[sandbox]]></category>
            <category><![CDATA[prompt-injection-attack]]></category>
            <dc:creator><![CDATA[Igor Bulygin]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 10:16:01 GMT</pubDate>
            <atom:updated>2026-10-30T10:16:01.560Z</atom:updated>
            <content:encoded><![CDATA[<p>I came across a short post the other day. A friend of mine (of course) failed an AI Engineer interview on a single question. Here it is, almost word for word:</p><blockquote><em>Let’s say you’re building an AI agent that can use a computer and browse websites. What if a website runs malicious JavaScript in the background that tries to steal data or do something it shouldn’t?</em></blockquote><blockquote><em>You can’t just tell the AI not to do it through a system prompt.</em></blockquote><blockquote><em>How would you design the system so that even if the malicious code runs, it can’t cause any real damage?</em></blockquote><p>Stop for a second and answer it yourself. I did, and my first answer was fine. My second answer, the one the follow-up was fishing for, took longer.</p><p>What I like about this question is that it isn’t about AI at all. It’s about a mistake I have already made twice in plain old PHP.</p><h3>The sentence that does all the work</h3><p>Look at the middle line again. “You can’t just tell the AI not to do it.”</p><p>The interviewer throws away the obvious answer before you can reach for it. Good. Because the obvious answer is a sticky note on the fridge that says “you’re on a diet, so don’t open it”.</p><p>The numbers are not on the sticky note’s side. Prompt injection is not solved. The best published result for a top model in browser use is about one percent attack success against an adaptive attacker. One percent sounds small until you remember the attacker gets to try again. And again. Your agent visits thousands of pages. The attacker only needs one of them.</p><p>So the model will be tricked. Not might. Will. The question is what happens next.</p><h3>I’ve been here before</h3><p>The first time I learned this lesson it was a Livewire component.</p><p>It had an authorize() call on the first line of a delete method. The policy was correct. The check ran before anything else. And anyone could delete any file in the database, because the ID it checked came from the browser, and the browser belongs to whoever is holding it. I trusted a round trip through hostile territory and called it security (more details here: <a href="https://medium.com/@boehpyk/the-authorize-that-couldnt-how-a-green-check-let-anyone-delete-any-file-253efee5e28a">https://medium.com/@boehpyk/the-authorize-that-couldnt-how-a-green-check-let-anyone-delete-any-file-253efee5e28a</a>).</p><p>The second time it was Docker. I had UFW on the server. Deny by default. I felt protected. Then the hosting provider wrote to say our Redis was exposed. Docker publishes ports by writing iptables rules directly, and walks straight past UFW. I had a wall. It just wasn’t standing where I thought it was.</p><p>Both bugs have the same shape. I put the rule in a place that the other side controls, or can walk around. A system prompt is that place. The model reads your instructions and the attacker’s instructions with the same eyes. Whoever writes more convincingly wins.</p><p>So the defense has to live somewhere the model can’t argue with.</p><h3>Round one: put it in a box</h3><p>The first answer is isolation. Run the agent in a sandbox. Not a plain container, a real one: a microVM, or gVisor. When the task is done, destroy it. Next task, fresh box.</p><p>Now the malicious JavaScript runs. Fine. It runs inside a throwaway machine that holds nothing and is gone in ten minutes. There are no keys to steal because there are no keys. There is no history to read because the box was born an hour ago.</p><p>For an agent that writes and runs its own code, add one more thing: zero internet egress. Letting an LLM call os.system() on your host is how you end up writing a postmortem.</p><p>This is the answer the friend presumably gave, or something close. And the interviewer had a follow-up ready.</p><h3>Round two: the box needs a door</h3><blockquote><em>But what if the agent needs access to the host machine’s files or credentials to complete the task? How would you prevent the sandbox from becoming a bridge to the host?</em></blockquote><p>This is the real question. The first one was the warm-up.</p><p>Real tasks need real things. “Book me a flight” needs a card. “Fix the bug” needs the repo and a token to push. The moment you mount the home directory or pass the API key into the box, the box is decoration. The JavaScript doesn’t need to escape the sandbox. You handed it what it came for.</p><p>The answer is a broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORDhFGph98BUCMKgGVwvpA.png" /><figcaption>It’s actually a diagram but in a funny way</figcaption></figure><p>The agent never touches the host. It sends requests to a broker that sits outside the sandbox, and the broker decides. Four rules make it work:</p><p><strong>Credentials stay with the broker.</strong> The agent says “push this branch”. The broker holds the token and does the push. The token never enters the box, so there is nothing to exfiltrate.</p><p><strong>Outbound traffic goes through an allowlist.</strong> The agent can reach the three hosts the task needs. Not evil.example. A stolen secret with nowhere to go is just a string.</p><p><strong>Every action is logged.</strong> Outside the agent, where the agent can’t edit it. When something does go wrong, you want the record written by someone who wasn’t involved.</p><p><strong>Sensitive operations wait for a human.</strong> Pay, delete, deploy: the broker stops and asks. The agent can propose. It can’t approve.</p><p>In code it’s less exotic than it sounds. Here is the whole idea in Python, stripped to the bones. It runs outside the sandbox. The agent talks to it over one HTTP endpoint and never sees anything else.</p><pre>from urllib.parse import urlparse<br><br># Deny by default: anything not listed here doesn&#39;t exist for the agent.<br>ACTIONS = {<br>    &quot;fetch_page&quot;:  {&quot;approval&quot;: False},<br>    &quot;push_branch&quot;: {&quot;approval&quot;: False},<br>    &quot;pay_invoice&quot;: {&quot;approval&quot;: True},<br>}<br>ALLOWED_HOSTS = {&quot;github.com&quot;, &quot;api.example-airline.com&quot;}<br><br>class Broker:<br>    def __init__(self, secrets, log, approvals, executor):<br>        self.secrets = secrets      # tokens live here, never in the sandbox<br>        self.log = log              # append-only, outside the agent&#39;s reach<br>        self.approvals = approvals<br>        self.executor = executor<br>    def handle(self, action: str, params: dict) -&gt; dict:<br>        self.log.record(action, params)<br>        rule = ACTIONS.get(action)<br>        if rule is None:<br>            return {&quot;error&quot;: f&quot;Unknown action: {action}&quot;}<br>        host = urlparse(params.get(&quot;url&quot;, &quot;&quot;)).hostname<br>        if host is not None and host not in ALLOWED_HOSTS:<br>            return {&quot;error&quot;: f&quot;Host not allowed: {host}&quot;}<br>        if rule[&quot;approval&quot;]:<br>            approval_id = self.approvals.request(action, params)<br>            return {&quot;status&quot;: &quot;waiting_for_human&quot;, &quot;approval_id&quot;: approval_id}<br>        # The broker attaches the credential itself. The agent never had it.<br>        token = self.secrets.for_action(action)<br>        return self.executor.run(action, params, token)</pre><p>That’s it. No AI in it anywhere. A list of actions, a list of hosts, a log, a queue and a vault. The hijacked agent can ask for send_cookies_to_evil_example as politely as it likes. The answer is a string that says no.</p><p>Two details matter more than they look. The log is written <em>before</em> any decision, so refused requests are recorded too. Those are exactly the ones you’ll want to read later. And the egress allowlist in the broker only covers what goes through the broker. The sandbox itself still needs its network locked down, or the agent will simply skip the broker and call curl.</p><h3>Plugging it into the agent</h3><p>The broker sits outside. The agent sits inside. Something has to connect them, and it should be the thinnest thing possible.</p><p>The easiest way today is an MCP server. Most agents speak MCP, Claude Code included. The server runs inside the sandbox, exposes exactly one tool, and forwards every call to the broker over HTTP. It holds no secrets and makes no decisions. It’s a mail slot.</p><pre># broker_tool.py runs inside the sandbox<br>import json<br>import os<br>import urllib.request<br><br>from mcp.server.fastmcp import FastMCP<br>BROKER_URL = os.environ[&quot;BROKER_URL&quot;]  # e.g. http://broker.internal:8080/handle<br>mcp = FastMCP(&quot;broker&quot;)<br><br>@mcp.tool()<br>def request_action(action: str, params: dict) -&gt; dict:<br>    &quot;&quot;&quot;Ask the broker to do something outside the sandbox.<br>    Available actions: fetch_page, push_branch, pay_invoice.<br>    pay_invoice needs human approval and returns an approval_id.<br>    &quot;&quot;&quot;<br>    body = json.dumps({&quot;action&quot;: action, &quot;params&quot;: params}).encode()<br>    req = urllib.request.Request(<br>        BROKER_URL, data=body, headers={&quot;Content-Type&quot;: &quot;application/json&quot;}<br>    )<br>    with urllib.request.urlopen(req, timeout=30) as resp:<br>        return json.load(resp)<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run()</pre><p>On the other side, the broker needs one HTTP endpoint that reads action and params and returns whatever Broker.handle() returns. Any framework does that in ten lines.</p><p>Then you register the tool with the agent. For Claude Code that’s .mcp.json in the project:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;broker&quot;: {<br>      &quot;command&quot;: &quot;python&quot;,<br>      &quot;args&quot;: [&quot;broker_tool.py&quot;],<br>      &quot;env&quot;: { &quot;BROKER_URL&quot;: &quot;http://broker.internal:8080/handle&quot; }<br>    }<br>  }<br>}</pre><p>If you wrap the work in a skill, the skill only has to say where the door is. A few lines in SKILL.md:</p><pre>## Outside access<br>You run in a sandbox with no network and no credentials.<br>For anything outside it (web pages, git push, payments),<br>call the `request_action` tool. If it returns an error, report it.<br>Do not try another way around it.</pre><p>Read that last line again, and then remember the title of this article. “Do not try another way around it” is a request, not a control. It saves you tokens on an honest day. On a bad day the agent will try anyway. So two more things have to be true, and neither of them is in the prompt:</p><p><strong>The agent’s own network tools are off.</strong> In Claude Code, deny WebFetch and Bash(curl:*) in the settings, or the broker is a suggestion.</p><p><strong>The sandbox can reach only the broker.</strong> One host, one port, enforced by the network, not by the agent. If the hijacked model finds a way to run curl anyway, it gets a connection refused.</p><p>The whole chain looks like this. The agent calls a tool. The tool posts to the broker. The broker checks, logs, maybe asks you, and only then reaches the outside world with a token the agent has never seen.</p><p>Notice that none of these rules depends on the model behaving. That’s the point. The model can be completely, enthusiastically hijacked and the broker still says no.</p><h3>Why this works: three legs</h3><p>There is a name for this. The lethal trifecta. An agent session with all three of these can be made to leak data:</p><ol><li>private data,</li><li>untrusted content,</li><li>a way to send data out.</li></ol><p>A browsing agent has untrusted content by definition. That’s the internet. You can’t remove that leg. So you remove the other two. The broker takes away private data, because the secrets never enter the session. The allowlist takes away the exit. Two legs out of three, and the table falls over.</p><p>The rule I keep from this: <strong>give each session at most two legs.</strong> If a task genuinely needs all three, split it into two sessions, or put a human in the middle.</p><h3>What doesn’t count as a wall</h3><p>I’ve seen lists of “agent projects you must build” that include an inter-agent sanitization proxy. Middleware that reads messages between agents and strips out malicious instructions.</p><p>It’s not useless. But think about what it is. A filter that tries to recognize bad text. That’s the sticky note again, just moved into middleware. It will catch the clumsy attacks and miss the clever one. Use it as an extra layer, never as the thing standing between the attacker and your database.</p><p>Same with “the model is really good at spotting injections now”. Lower, not zero. The wall is what the agent <em>cannot</em> do. Everything else is depth.</p><h3>The verdict</h3><p>If I were in that chair, this is what I’d say:</p><ul><li>Assume the model gets hijacked. Design for the moment after.</li><li>Isolate: disposable microVM or gVisor per task, destroyed at the end, no egress unless needed.</li><li>Broker everything outside the box. Credentials stay with the broker, outbound goes through an allowlist, every action is logged outside the agent, risky actions wait for a human.</li><li>Never give one session private data, untrusted content and a way out at the same time.</li></ul><p>And then I’d add the part about Livewire and Docker. Not because the interviewer asked, but because it’s the honest answer. The interviewer wasn’t testing whether I know gVisor. They were testing whether I know that a rule the attacker can read is not a rule.</p><p>I learned that the expensive way, twice, before anyone asked me about agents. The agent just makes the lesson cheaper to repeat and more expensive to forget.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f9b8484324" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The authorize() That Couldn’t: How a Green Check Let Anyone Delete Any File]]></title>
            <link>https://medium.com/@boehpyk/the-authorize-that-couldnt-how-a-green-check-let-anyone-delete-any-file-253efee5e28a?source=rss-8c51ffe11fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/253efee5e28a</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[livewire]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Igor Bulygin]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-12T08:01:02.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>A green keycard at room 302, and nobody asking about the luggage in 303</h4><figure><img alt="A guest swipes a card at room 302 and gets a green check, while luggage is thrown out of room 303 next door, whose reader was never asked" src="https://cdn-images-1.medium.com/max/1024/1*Y7XYSwKGd8JMf4WBVZT0bw.png" /></figure><p>Read this method and decide whether it is safe.</p><pre>public function deleteFile(int $fileId, DeleteBookFileHandler $handler): void<br>{<br>    $this-&gt;authorize(&#39;editContent&#39;, Book::query()-&gt;findOrFail($this-&gt;bookId));<br>    $handler-&gt;handle(new DeleteBookFile(fileId: $fileId));<br>}</pre><p>There is an authorization check on the very first line. It uses the framework’s blessed API. It calls a policy that correctly returns false for people who do not own the book. It runs before anything else happens.</p><p>And it does nothing at all to stop an attacker from deleting any file in the database.</p><p>I found this during a security pass on a project I maintain. Some context. It is a self-publishing platform for authors: you write a book, upload a cover, attach a few files, publish. Laravel, Livewire on the front, Postgres underneath. Every author has their own books and, in theory, can only touch their own books. That “in theory” is what this article is about.</p><p>I want to walk through exactly why the method above is broken, because the reason is not a Livewire quirk or an exotic exploit. It is a mistake about what the check is checking. And it is available in every framework you will ever use.</p><h3>First, a hotel</h3><p>Livewire sells itself as “server-rendered components that feel like a SPA.” Good pitch. Slightly dangerous one, because it invites you to imagine the component living on the server between clicks. An object sitting in memory, holding its $bookId, waiting for the next method call.</p><p>It does not. PHP does not work that way, and Livewire does not pretend otherwise.</p><p>Here is what actually happens. Think of a hotel.</p><p>You check in. You show ID at the front desk, the clerk verifies you and hands you a keycard for room 302. This is mount(). It authorizes you, then writes $this-&gt;bookId = 302.</p><p>Then the hotel forgets you. The clerk goes home. There is no ledger, no memory, no session. The PHP process dies and the component is garbage collected.</p><p>The keycard is in your pocket. Not in the hotel’s safe. Yours. The component’s state is serialized into a snapshot and sent to the browser.</p><p>Every time you want anything, you hand the card back. A new clerk reads it and reconstructs who you are entirely from what is written on it. Every action posts the snapshot back, and HandleComponents::update() rebuilds the component from client-supplied data.</p><p>That last step is the whole story. The server’s knowledge of your component is whatever the browser just told it. There is no other copy.</p><p>Which raises the obvious question: what stops you from writing “room 303” on your own keycard?</p><h3>Who owns a component</h3><p>The phrase “owning a component” means two different things, and the gap between them is where the bug lived.</p><p>Sense one: whose component is it? You mounted it. mount() authorized you for that book. It is your session, your book, your edit page. Nothing wrong here.</p><p>Sense two: who controls its state? You do. The client. Always. Between any two requests the component’s entire state sits in the browser in a wire:snapshot attribute, and the browser belongs to whoever is holding it.</p><p>Sense two is true regardless of sense one. Even for a perfectly honest user editing their own book, the server is trusting a round trip through hostile territory. This is not a design flaw. It is the only way stateless HTTP can fake statefulness. But it means every public Livewire property is, by default, an input parameter from the client, dressed up to look like an object attribute.</p><p>When you read this:</p><pre>public int $bookId;</pre><p>your instinct says “a field on my object.” The truth is closer to this:</p><pre>public function anyActionMethod($bookId_from_the_request_body) { … }</pre><p>Once that clicks, you start reading Livewire components differently.</p><h3>Two locked doors and one open one</h3><p>So can an attacker just take over someone else’s component? No. Livewire is not naive about this. Two mechanisms stand in the way.</p><p>The snapshot is signed. Every snapshot carries an HMAC checksum, verified on the way back in:</p><pre>if (! hash_equals($comparitor = self::generate($snapshot), $checksum)) {<br>    trigger(&#39;checksum.fail&#39;, $checksum, $comparitor, $snapshot);<br>    static::recordFailure();<br>    throw new CorruptComponentPayloadException;<br>}</pre><p>Scribble “303” onto your keycard and the magnetic strip stops matching the printing. You get an exception, and Livewire rate-limits IPs that fail this repeatedly. Nice touch.</p><p>And mount() guards the front desk. You cannot mount a component against a victim&#39;s book:</p><pre>public function mount(int $bookId): void<br>{<br>    $book = Book::query()-&gt;findOrFail($bookId);<br>    $this-&gt;authorize(&#39;editContent&#39;, $book);   // attacker gets 403 right here<br>    $this-&gt;bookId = $bookId;<br>}</pre><p>Two doors, both locked.</p><p>But there is a third door, and it is supposed to be open. wire:model has to work. When you type in a text box, the browser must be able to say &quot;set $title to this.&quot; So alongside the signed snapshot, the client sends a separate updates array. A legitimate channel for &quot;change these properties.&quot; And Livewire applies it to any public property, no questions asked, unless you say otherwise.</p><p>Look at the order of operations in HandleComponents::update(). This is verbatim from the vendor source:</p><pre>[ $component, $context ] = $this-&gt;fromSnapshot($snapshot);       // 1. rebuild from client data<br>trigger(&#39;hydrate&#39;, $component, $memo, $context);                 // 2. hooks run<br>$this-&gt;updateProperties($component, $updates, $data, $context);  // 3. client&#39;s changes applied<br>$this-&gt;callMethods($component, $calls, $context);                // 4. your action finally runs</pre><p>Step 3 happens before step 4. The attacker mounts their own book, passing mount()&#39;s check honestly, then posts updates: { bookId: 654321 }. By the time save() executes, $this-&gt;bookId is the victim&#39;s.</p><p>That was finding number one, and it has a clean fix. #[Locked]. Its entire implementation is four lines:</p><pre>class BaseLocked extends LivewireAttribute<br>{<br>    public function update()<br>    {<br>        throw new CannotUpdateLockedPropertyException($this-&gt;getName());<br>    }<br>}</pre><p>It hooks the update channel and slams it shut. A tamper-evident keycard. Before the security pass, #[Locked] appeared zero times in this codebase.</p><p>One aside, because I tried it first. A hydrate() hook cannot save you here. Hooks run at step 2; the tampering lands at step 3. A hydrate hook would authorize the pre-tamper bookId. It does not check less, it checks the wrong value entirely.</p><h3>The bug that all of that does not fix</h3><p>Here is the attack we actually ran against the live app.</p><p>The attacker does not forge a snapshot. Does not tamper with a property. Does not touch bookId at all. They do something completely legitimate.</p><p>They create their own book, 123456. It is genuinely theirs. They open their own Files tab. mount() authorizes them, correctly. Then they call deleteFile(23183), where 23183 is the victim&#39;s file.</p><p>Walk it through:</p><pre>public function deleteFile(int $fileId, DeleteBookFileHandler $handler): void<br>{<br>    // &quot;May you edit book 123456?&quot; Yes. It&#39;s their book. The check passes.<br>    $this-&gt;authorize(&#39;editContent&#39;, Book::query()-&gt;findOrFail($this-&gt;bookId));</pre><pre>    // $fileId = 23183, which belongs to book 654321. Nobody has looked at this. Ever.<br>    $handler-&gt;handle(new DeleteBookFile(fileId: $fileId));<br>}</pre><p>The authorization check passes, and it is right to pass. It asks an honest question and gets an honest answer. The attacker may edit book 123456. That is simply true.</p><p>The check just has nothing whatsoever to do with the file being deleted.</p><p>Back to the hotel. You are standing at the door of room 302 with a valid, untampered keycard. The reader flashes green, correctly. Then you lean over to the intercom and say “while I’m here, please throw out all the luggage in room 303.” Nobody checked that sentence. The door check passed. The door was never the point.</p><p>Now count what is useless here.</p><p>#[Locked]? Irrelevant. It protects properties. $fileId is a method argument. It arrives through the calls channel, not the updates channel, so BaseLocked::update() never fires.</p><p>The checksum? Irrelevant. Nothing was forged.</p><p>mount()&#39;s check? Irrelevant. It passed honestly.</p><p>The per-action authorize()? Also irrelevant. It also passed honestly.</p><p>Every control we had added was working perfectly, and the file would still have died.</p><h3>The fix</h3><p>An invariant in the application layer, one level below the component:</p><pre>// DeleteBookFileHandler<br>public function handle(DeleteBookFile $command): void<br>{<br>    $file = $this-&gt;bookFileRepository-&gt;findById($command-&gt;fileId);</pre><pre>    if ($file === null) {<br>        return;<br>    }</pre><pre>    if ($file-&gt;bookId !== $command-&gt;bookId) {   // this is what saved the victim&#39;s file<br>        return;<br>    }</pre><pre>    Storage::disk($file-&gt;disk)-&gt;delete($file-&gt;path);<br>    $this-&gt;bookFileRepository-&gt;delete($command-&gt;fileId);<br>}</pre><p>$file-&gt;bookId is 654321. $command-&gt;bookId is 123456. They disagree, so nothing happens.</p><p>Note carefully what this is not. It is not an authorization check. It never asks who you are. It asks a question about data consistency: does this file actually belong to the book this command claims to be operating on? That is a domain invariant. It imports nothing from infrastructure, touches no Auth::id(), and would be just as correct in a CLI script or a queued job. That is why it is allowed to live in the application layer without breaking the hexagonal layering.</p><p>Putting an ownership check there instead would have been the wrong call. It would drag Auth::id() into the application layer and invert the dependency direction. Authorization belongs in the component. The invariant belongs in the handler. Different jobs.</p><p>We proved the ordering in the browser. The attacker sailed through authorize() and was stopped by the !==. The check that looks like security was not. The check that looks like a data-integrity nicety was.</p><h3>Four controls, four blind spots</h3><p>ControlChannel it guardsCatchesBlind toSnapshot checksumsnapshotForged component stateLegitimate updates; method args#[Locked]updatesProperty tamperingMethod arguments; new unlocked propsauthorize() in the actionNon-owners of the component&#39;s entityArguments naming other entitiesInvariant in the handlerArguments that do not belong togetherNothing, for this class of bug</p><p>They fail independently. That is why we shipped all four rather than picking the best one. #[Locked] is only as good as your discipline about every future property. authorize() is only as good as the object you hand it. The invariant is the only one that closes the delete-by-bare-id footgun permanently, even if a future contributor forgets both of the others.</p><h3>The verdict</h3><p>An authorization check secures the object you pass to it. Nothing else.</p><p>authorize(&#39;editContent&#39;, $book) reads, to a tired reviewer at 6pm, like &quot;this method is secured.&quot; It is not. It says &quot;the component&#39;s book is editable by you.&quot; If the method then operates on some other entity, named by an argument, looked up by an id, resolved from a relation, that entity is unguarded. And the reassuring green check at the top is actively harmful, because it makes the method look reviewed.</p><p>The tell is a mismatch between what you authorize and what you mutate:</p><pre>$this-&gt;authorize(&#39;editContent&#39;, $book);          // authorizing: $this-&gt;bookId<br>$handler-&gt;handle(new DeleteBookFile($fileId));   // mutating: something else entirely</pre><p>Any time those two lines do not name the same thing, you have this bug. Go looking for it:</p><pre>grep -rn &quot;public function.*(int \$.*Id&quot; app/Infrastructure/Http/Livewire/</pre><p>Every method taking a bare entity id as an argument is a candidate. Ask of each: is this id constrained to something the caller already proved they own? If the answer involves the word “probably,” it is a bug.</p><p>And the corollary, the thing I would actually tattoo somewhere: a test that mounts as the victim tests nothing. Mount as the attacker, then reach for the victim’s data.</p><p>Before the security pass, this suite had exactly one cross-tenant test in the entire codebase, and it only covered mount(), the one door that was already locked. Eight findings walked through the other doors for months, past a green test suite, because every test politely asked permission first.</p><h3>Footnote: the trap that nearly ate the fix</h3><p>Worth knowing, because it is the same shape of mistake one level up.</p><p>Livewire merges validation rules like this:</p><pre>array_merge($rulesFromComponent, $rulesFromOutside)   // attributes are $rulesFromOutside. They win.</pre><p>So when we scoped authorId to the current user by adding a rules() method, the pre-existing attribute on the property silently beat it:</p><pre>#[Validate(&#39;required|integer|exists:authors,id&#39;)]   // unscoped, and it overrides rules()<br>public int $authorId = 0;</pre><p>Validation passes. The IDOR remains. And the shiny new test asserting assertHasErrors(&#39;authorId&#39;) passes anyway, because the attribute&#39;s rule happens to reject the malformed cases the test used.</p><p>The attribute had to be deleted, not supplemented. A fix that looks right, plus a test that looks right and passes, over a vulnerability that is still wide open. That is the worst outcome available in security work, and it was two lines away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253efee5e28a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s Not a Leak: How My Symfony App Ran Out of Memory Five Ways]]></title>
            <link>https://medium.com/@boehpyk/its-not-a-leak-how-my-symfony-app-ran-out-of-memory-five-ways-a9b956f6418b?source=rss-8c51ffe11fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b956f6418b</guid>
            <category><![CDATA[eloquent]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[doctrine]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Igor Bulygin]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 17:32:24 GMT</pubDate>
            <atom:updated>2026-09-07T17:32:24.562Z</atom:updated>
            <content:encoded><![CDATA[<h4>Five boring Doctrine patterns, one of which was a denial-of-service primitive sitting in production for years.</h4><p>My containers crashed. At night, of course, when nobody was expecting it. I was too lazy to go looking for the cause in the dark, so I restarted the containers and went back to sleep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgL2NsEMFG8IX-KaA4f8kA.png" /></figure><p>It did not end there. In the morning they crashed again.</p><p>So I set up a health check with an automatic restart. If the app does not answer a curl, restart the containers. And log it. Twenty-four hours later I read the log and was a bit shocked. It was crashing often and for no apparent reason. Or rather there was a reason, and a very obvious one. It was called memory exhaustion.</p><p>Some context. I maintain a small news project that aggregates IT news. Modest is the right word. It earns enough to buy bread and butter for a small team of editors and authors. Since it is small, we never needed complex infrastructure for it. A few containers: the app, the database, Nginx, a couple of utility ones. Symfony 7.2, PHP 8.4, MySQL, PHP-FPM in front.</p><p>While the volume of content was low, everything ran fast. I was adding features, fixing minor bugs, mostly kicking back and feeling great. Then the content grew and the problems started. The sneakiest part about this kind of situation is that it does not pop up out of nowhere. It arrives gradually. Something starts slowing down somewhere. Something stops working as quickly as it should. And in the end it all lands on memory exhaustion.</p><p>At that point you have two choices. Work on the infrastructure: add RAM, expand the disk, migrate to Amazon or something like it. Or grit your teeth and start optimizing the code.</p><p>I chose the latter. Here is what I found and how I fixed it.</p><h3>The log line that started it</h3><pre>WARNING: [pool www] server reached pm.max_children setting (5), consider raising it</pre><p>The obvious move is to raise it. I did not raise it. Good thing, because the number 5 was never the problem.</p><p>The numbers: memory limit 512 MB per worker, five workers, so the whole pool tops out around 2.5 GB. The site would go quiet for a few minutes, come back, then go quiet again. Fatal errors landed in different files every time. Template.php once, Parser.php the next. That randomness is a clue. A real leak dies in the same place. Different places mean the memory was already gone before the fatal error picked a victim.</p><p>So not a leak. Fat requests. Each one eating 400 to 512 MB, five of them at once, pool full, site down, stakeholders screaming, my messengers flying.</p><h3>Analysis</h3><p>Before touching code I added two subscribers. MemoryDebugSubscriber logs CRITICAL when peak memory passes 400 MB. ProductionMemoryMonitor logs a warning before controller execution and catches OOM errors on the way out. Then I read var/log/prod.log for HIGH MEMORY USAGE and let it tell me which routes were the pigs.</p><p>Instrument first. Guessing which route is heavy is a great way to spend a weekend optimizing the wrong one.</p><p>Five patterns came out of it. All of them Doctrine. None of them exotic.</p><h3>1. Full hydration where I needed three columns</h3><p>SitemapController, which builds the sitemap.xml file, assembled it from four repository methods of the same shape: getAllArticlesForSitemap(), getAllCategoriesForSitemap(), getAllTagsForSitemap(), getAllAuthorsForSitemap(). Every one of them did -&gt;select(&#39;e&#39;). No PARTIAL, no LIMIT. Doctrine dutifully hydrated every column of every row into managed entity objects.</p><p>The sitemap uses id, title and one date. That is it.</p><p>With a few thousand articles, that single request goes past 400 MB. And who hits /sitemap.xml? Crawlers. Repeatedly. Five bots at the same time is a full house and nobody else gets in.</p><p>Doctrine entities are not cheap. Rough rule from this codebase: an entity costs about 3x the raw row size once you count the identity map and unit of work. Hydrating a table you only want to read is paying object tax on data you will throw away in the next line.</p><h3>2. An identity map that nobody ever cleared</h3><p>Next one: a console command that sends newsletters to subscribers.</p><p>NewsletterSendCommand loads all subscribers at once, then loops:</p><pre>$subscribers = $this-&gt;getSubscribers(); // ALL of them, full hydration<br>foreach ($to as $value) {<br>    $this-&gt;sendNotificationEmails(...);<br>    $this-&gt;updateSentStatus($value[&#39;subscriber&#39;]); // flush() after every email<br>}</pre><p>flush() on every iteration, clear() never. So every Subscriber, every Article, every related entity Doctrine touched during the run stayed in the identity map until the process died. Memory grows in a straight line with the length of your subscriber list.</p><p>And one more newsletter-sending command, NewsDigestSendCommand, had the same shape, with a bonus: one or two article queries per subscriber, also fully hydrated, also inside the loop.</p><p>I did the napkin math for a similar command with 100 subscribers:</p><ul><li>100 subscribers x ~2 KB = 200 KB</li><li>100 subscribers x 50 articles x ~5 KB = 25 MB</li><li>articles x 10 authors x ~1 KB = 50 MB</li><li>articles x 5 tags x ~0.5 KB = 12.5 MB</li><li>Doctrine overhead, 3x = 263 MB</li><li>Total around 550 MB</li></ul><p>The limit is 512. The command was never going to finish; it was only ever a question of which subscriber number killed it.</p><h3>3. N+1 on the busiest page in the app</h3><p>The homepage fetched the 20 latest articles with PARTIAL, which is the right thing, and then did this:</p><pre>foreach ($articles as $article) {<br>    $authors = $article-&gt;getArticleAuthors(); // lazy load fires here<br>    ...<br>}</pre><p>21 queries on every homepage hit, and the second loop over authors made it worse. N+1 is usually filed under “slow”. It is also a memory problem, because every entity that lazy load pulls in stays pinned in the identity map for the rest of the request. Slow and fat, on the page every visitor sees first.</p><h3>4. Two uncached queries on every single render</h3><p>The visitor could select articles by category and tag, so I needed &lt;select&gt; dropdowns for them, populated with the actual tags and categories. TwigExtension::getGlobalsSelects() returned the category and tag filter lists for the sidebar. getGlobals() runs on every page render. One of those was a raw SQL GROUP BY across categories and sections. Neither was cached.</p><p>That data changes when an admin edits it. Roughly never.</p><h3>5. flush() inside a Doctrine post-event</h3><p>All changes made by admins were recorded, so I had a listener for that: EntityLogListener called $em-&gt;flush($log) inside postPersist, postUpdate and postRemove. That is a flush inside an already running flush cycle. It can re-enter the same listener and cascade. Under load it spirals. As a bonus, flush($entity) with an argument is gone in Doctrine ORM 3, so the code was living on borrowed time anyway.</p><h3>The fix</h3><p>Nothing clever. Five small changes, one per pattern.</p><p><strong>Select what you use.</strong> Sitemap and mailing queries went from findBy() and -&gt;getResult() to targeted QueryBuilder queries with -&gt;getArrayResult(). Doctrine never builds an object at all; you get plain arrays. The only work is swapping getters for array keys:</p><pre>// before<br>$article-&gt;getTitle();<br>// after<br>$article[&#39;title&#39;];</pre><p>Where I still needed real entities I used -&gt;select(&#39;PARTIAL e.{id}&#39;) and called $entityManager-&gt;clear() after each sitemap section.</p><p><strong>Clear the identity map, or never fill it.</strong> In NewsDigestSendCommand, getSubscribers() went from -&gt;getResult() to -&gt;toIterable(), which streams rows off a database cursor one at a time instead of materializing the whole list. Then, at the bottom of the loop:</p><pre>foreach ($subscribers as $subscriber) {<br>    // ... build and send the letter, updateSentStatus() flushes<br>    $this-&gt;entityManager-&gt;clear();<br>}</pre><p>Order matters. clear() goes after the flush; otherwise you throw away writes that were never persisted. Where clearing everything was too blunt, detach($value[&#39;subscriber&#39;]) on the one entity did the job.</p><p><strong>Kill the N+1 with one join.</strong> New method, ArticleAuthorRepository::getAuthorsForArticleIds(array $articleIds), one JOIN query for all 20 articles, returning plain arrays. 21 queries became 2.</p><p><strong>Cache the static stuff.</strong> The category and tag lists moved into Redis with a 5-minute TTL, and the request-varying selected flag is stamped in memory afterwards. Cache hit means zero DB queries per render.</p><p><strong>Move the flush out of the event.</strong> EntityLogListener now buffers Log objects during the request and writes them all in one flush() on kernel.terminate, after the response has already gone to the browser.</p><h3>Conclusion</h3><p>The five patterns are boring and that is the point. Every one of them is a thing I would nod along to in a code review and then write myself on a Tuesday.</p><p>What I would tell my past self:</p><p><strong>Read the error message literally.</strong> max_children reached means requests are not finishing fast enough. It does not mean you need more children. I would have raised it to 20, given each of those 512 MB, and turned a crash into a swap death.</p><p><strong>Different crash locations mean the memory was already gone.</strong> A real leak is boringly repeatable. Randomness points at fat requests.</p><p><strong>Hydration is a cost you opt into.</strong> getArrayResult(), PARTIAL, and toIterable() are three ways to opt out, and most read-only code paths should.</p><p><strong>Loops need an exit strategy for memory.</strong> clear() at the end, detach() per item, or stream and never accumulate. Pick one, but pick one.</p><p><strong>When result set size is attacker-controlled, </strong>setMaxResults()<strong> stops being a performance tweak and becomes a security control.</strong> That is the real lesson of the % bug. Everything else on this list is a bug I would eventually find under my own load. That one was a denial-of-service primitive sitting in production, and the only thing standing between it and a bored teenager was that nobody had typed % into the URL bar yet.</p><p>And make the anti-patterns grep-able so the next one shows up before the logs do:</p><pre>grep -rn &quot;findAll()&quot; app/src/ --include=&quot;*.php&quot;<br>grep -rn &quot;-&gt;getResult()&quot; app/src/Repository/ --include=&quot;*.php&quot;<br>grep -rn &quot;like :&quot; app/src/Repository/ --include=&quot;*.php&quot;<br>grep -rL &quot;memory_get_usage&quot; app/src/Command/*.php</pre><p>Four lines of grep would have found all of this in about a minute. It took me two months and two outages.</p><p>I packaged the checks into a Claude Code skill, so I do not have to remember them. It works out whether the project is Doctrine or Eloquent, runs the sweep, then reads the candidates and ranks them by memory cost times how often the code runs times who can trigger it. That last multiplier is the one that matters. It is MIT licensed and it lives here: <a href="https://github.com/boehpyk/boehpyk-skills">github.com/boehpyk/boehpyk-skills</a></p><p>Even if everything is fine for you right now and life is easy and serene, I would still go check the points above against your own code. It might buy you another few years of exactly that quiet, carefree life you are enjoying at the moment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b956f6418b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>