<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>EXPLAIN ANALYZE</title><link>https://explainanalyze.com/</link><description>Recent content on EXPLAIN ANALYZE</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Thu, 12 Nov 2026 21:26:52 -0500</lastBuildDate><atom:link href="https://explainanalyze.com/index.xml" rel="self" type="application/rss+xml"/><item><title>PostgreSQL MVCC Explained: Dead Tuples, VACUUM and Idle Transactions</title><link>https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/</link><pubDate>Thu, 12 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post PostgreSQL MVCC Explained: Dead Tuples, VACUUM and Idle Transactions" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;MVCC (multi-version concurrency control) is how PostgreSQL runs thousands of transactions at once without readers waiting for writers. This post is about what that does to the table: what happens to the old version of a row when a query changes it, what VACUUM, PostgreSQL&amp;rsquo;s cleanup process, is for and what it does and does not give back, and where a connection left idle inside a transaction fits in. Every number comes from runs on PostgreSQL 18.6.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So here is how MVCC works, in outline. Locking every row a transaction reads is not practical on a busy server: with thousands of transactions in flight, readers and writers would spend their time waiting for each other, and the hottest rows would set the pace for everything. PostgreSQL skips that. Each transaction works from a snapshot, a fixed view of the data as it stood when the transaction started (or, at the default settings, when each of its statements started). When a query changes a row, PostgreSQL writes a new version of the row and leaves the old one in place for any transaction whose snapshot still points at it. Readers see their version, writers write theirs, and nobody waits.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-transactions"&gt;A quick reminder about transactions
&lt;/h2&gt;&lt;p&gt;Moving 100 from one account to another is two changes: subtract from one row, add to another. If the server dies between them, or a second transfer squeezes in between them, money is created or lost. Making an application guard against every such case on its own is hard, so databases take the job: a transaction is a group of statements the database promises to treat as one unit. You open one with &lt;code&gt;BEGIN&lt;/code&gt;, and end it with &lt;code&gt;COMMIT&lt;/code&gt; to keep every change or &lt;code&gt;ROLLBACK&lt;/code&gt; to drop every change. A statement sent on its own is a transaction of one.&lt;/p&gt;
&lt;p&gt;The promise has a well-known name, ACID, four guarantees that PostgreSQL makes for every transaction:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Guarantee&lt;/th&gt;
 &lt;th&gt;What it promises&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Atomic&lt;/td&gt;
 &lt;td&gt;all of the transaction&amp;rsquo;s changes happen, or none of them do&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Consistent&lt;/td&gt;
 &lt;td&gt;every rule the schema declares (keys, constraints) holds when the transaction ends&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Isolated&lt;/td&gt;
 &lt;td&gt;a transaction is not disturbed by other transactions running at the same moment&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Durable&lt;/td&gt;
 &lt;td&gt;once committed, the changes survive a crash&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The third one is the hard one, because of how many transactions there are. Every program talking to the database holds a connection, which PostgreSQL calls a session; PostgreSQL allows 100 by default, busy systems run thousands, and at any moment many of them are inside a transaction touching the same tables. Keeping each of those transactions undisturbed by the others, without making them wait for each other, is the job MVCC does.&lt;/p&gt;
&lt;h2 id="a-change-never-overwrites-the-row"&gt;A change never overwrites the row
&lt;/h2&gt;&lt;p&gt;The tests in this post ran on PostgreSQL 18.6 in Docker, limited to 4 CPUs and 4 GB of memory, on an &lt;code&gt;accounts&lt;/code&gt; table of 1,000,000 rows (an id, an owner, a balance, a timestamp and a note).&lt;/p&gt;
&lt;p&gt;Two sessions, A and B. Session A starts a transaction set to keep one view of the data for its whole duration (how that is set is one of the things simplified away here) and reads account 42: the balance is 187.89. Session B adds 100 to the same account and commits. B&amp;rsquo;s update did not wait for A; it finished in 5.56 ms. B now reads 287.89, while A, reading again inside its transaction, still gets 187.89. Once A commits and reads again, it gets 287.89 like everyone else.&lt;/p&gt;
&lt;p&gt;Both answers can be true at once because of how a row is stored. PostgreSQL keeps each table as a file of fixed-size pages, 8 kB each by default, and a page holds as many row versions as fit. Every row version carries three hidden columns, and they exist so that a reader can tell which version is meant for it without asking anyone. &lt;code&gt;ctid&lt;/code&gt; is the version&amp;rsquo;s physical address (page number, position on the page), which is how an index entry points at it. &lt;code&gt;xmin&lt;/code&gt; is the number of the transaction that created the version: every transaction that writes gets a number, handed out in order, so &lt;code&gt;xmin&lt;/code&gt; says when the version came into being. &lt;code&gt;xmax&lt;/code&gt; is the number of the transaction that replaced or deleted it, 0 while none has. They can be selected like any other column, and reading them alongside the balance showed the same account existing twice after B&amp;rsquo;s update:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ctid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xmin&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xmax&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- session A, inside its transaction -- session B, or any new session
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- ctid | xmin | xmax | balance -- ctid | xmin | xmax | balance
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- (0,42) | 754 | 756 | 187.89 -- (17241,18) | 756 | 0 | 287.89
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The new version, created by B&amp;rsquo;s transaction 756, went to page 17,241, near the end of the table. The old version stayed at &lt;code&gt;(0,42)&lt;/code&gt;, on page 0, now marked &lt;code&gt;xmax 756&lt;/code&gt;: replaced by transaction 756.&lt;/p&gt;
&lt;p&gt;&lt;img alt="In PostgreSQL account 42’s old version stays on page 0 marked xmax 756 while the new version sits on page 17241. Session A, with a snapshot from before 756, reads the old one; new sessions read the new one." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/where-versions-live.svg"&gt;&lt;/p&gt;
&lt;p&gt;Those stamps are what a snapshot is checked against. A snapshot is not a copy of the data but a record of which transactions had committed at a certain moment (&lt;a class="link" href="https://www.postgresql.org/docs/18/functions-info.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt;), and a query applies one rule to every version it meets: the version is visible if its &lt;code&gt;xmin&lt;/code&gt; transaction counts as committed in the snapshot and its &lt;code&gt;xmax&lt;/code&gt; transaction, if there is one, does not. That is the whole of MVCC&amp;rsquo;s reading side. A&amp;rsquo;s snapshot was taken before 756 started, so for A the version at &lt;code&gt;(0,42)&lt;/code&gt; is visible and the one at &lt;code&gt;(17241,18)&lt;/code&gt; is not; a new session&amp;rsquo;s snapshot has 756 as committed, and the same rule picks the other version.&lt;/p&gt;
&lt;p&gt;How long a snapshot lives is the one setting that matters for the rest of this post. By default, every statement takes a fresh snapshot and drops it when it finishes, so an idle transaction holds none, and A&amp;rsquo;s second read would have seen B&amp;rsquo;s change. Session A asked for the other behaviour: one snapshot at its first statement, kept until the transaction ends. PostgreSQL has a whole setting, with four levels, for how much a transaction may see of others; this post simplifies it to those two behaviours, and the isolation levels post covers the rest.&lt;/p&gt;
&lt;p&gt;Transactions look different in this light. A transaction does not hold its changes back until COMMIT; its versions go onto pages as it writes them, stamped with its number, and what COMMIT or ROLLBACK decides is whether that number counts for the snapshots taken afterwards. INSERT, UPDATE and DELETE all work through the two stamps, and none of them removes anything:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Statement&lt;/th&gt;
 &lt;th&gt;New version written&lt;/th&gt;
 &lt;th&gt;The version that was there&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;INSERT&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;yes, &lt;code&gt;xmin&lt;/code&gt; set to this transaction&lt;/td&gt;
 &lt;td&gt;none&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;UPDATE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;yes, &lt;code&gt;xmin&lt;/code&gt; set to this transaction, plus a new index entry&lt;/td&gt;
 &lt;td&gt;stays in place, &lt;code&gt;xmax&lt;/code&gt; set to this transaction&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;DELETE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;no&lt;/td&gt;
 &lt;td&gt;stays in place, &lt;code&gt;xmax&lt;/code&gt; set to this transaction&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So an UPDATE is a delete and an insert done together: page 0 had no room for a second copy of account 42, so the new version went to the end of the table and the primary key index got a second entry pointing at it. (When no indexed column changes and the page has room, PostgreSQL keeps the new version on the same page and skips the index entry, a &lt;a class="link" href="https://www.postgresql.org/docs/18/storage-hot.html" target="_blank" rel="noopener"
 &gt;HOT update&lt;/a&gt;.) A DELETE writes no new version at all. The &lt;code&gt;pageinspect&lt;/code&gt; extension shows what that leaves behind, because it lists every version on a page whether a query can see it or not. On a two-row table, after deleting row 2 and then inserting row 3 in a transaction that rolled back:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL 18.6
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;EXTENSION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pageinspect&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_xmin&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_xmax&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_ctid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;heap_page_items&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;get_raw_page&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;t&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_xmin&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_xmax&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t_ctid&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;----+--------+--------+--------
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;755&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;755&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;756&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- deleted by 756, still on the page
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;757&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- inserted by 757, which rolled back
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;SELECT * FROM t&lt;/code&gt; returned only row 1. The other two had only stopped showing up in queries.&lt;/p&gt;
&lt;p&gt;COMMIT and ROLLBACK, then, move no data. When transaction 756 committed, PostgreSQL rewrote neither page; it recorded that 756 had committed, in the &lt;a class="link" href="https://www.postgresql.org/docs/18/storage-file-layout.html" target="_blank" rel="noopener"
 &gt;transaction commit status data&lt;/a&gt; (&lt;code&gt;pg_xact&lt;/code&gt;), and every snapshot taken after that counted it. A ROLLBACK records the opposite and leaves the versions where they are: a rolled-back INSERT leaves its row on the page, visible to nobody, and a rolled-back UPDATE leaves both versions behind, the new one invisible and the old one still current with a nonzero &lt;code&gt;xmax&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Every version an UPDATE, a DELETE or a rolled-back transaction leaves behind is a real row on a real page, and nothing described so far ever removes one. MySQL&amp;rsquo;s InnoDB makes the opposite choice, changing the row in place and keeping the old value in a separate undo log, which the MySQL MVCC post measures on the same table.&lt;/p&gt;
&lt;h2 id="where-postgresql-still-waits"&gt;Where PostgreSQL still waits
&lt;/h2&gt;&lt;p&gt;MVCC removes one kind of waiting, readers waiting for writers, and leaves the others in place. To see which, session A did something and then held its transaction open for 2 seconds before committing, while session B tried something else, each case on a fresh 1,000-row table:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Session A, transaction held open&lt;/th&gt;
 &lt;th&gt;Session B&lt;/th&gt;
 &lt;th style="text-align: right"&gt;B waited&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;updated account 42&lt;/td&gt;
 &lt;td&gt;plain &lt;code&gt;SELECT&lt;/code&gt; of account 42&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0.9 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;updated account 42&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;UPDATE&lt;/code&gt; of account 42&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,014 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;updated account 42&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; of account 42&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,017 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;SELECT ... WHERE id &amp;gt; 990 FOR UPDATE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;INSERT&lt;/code&gt; of id 1001&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2.6 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;one plain &lt;code&gt;SELECT&lt;/code&gt; of account 42, then idle&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;ALTER TABLE accounts ADD COLUMN&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,023 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;same, with that &lt;code&gt;ALTER&lt;/code&gt; waiting&lt;/td&gt;
 &lt;td&gt;plain &lt;code&gt;SELECT&lt;/code&gt; of account 7, sent 0.3 s after the &lt;code&gt;ALTER&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,718 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img alt="Bar chart: a plain SELECT of the changed row waited 0.9 ms; an UPDATE of the same row 2,014 ms; SELECT FOR UPDATE 2,017 ms; an INSERT into a range locked FOR UPDATE 2.6 ms; ALTER TABLE while A sat idle after one SELECT 2,023 ms; a plain SELECT sent after that ALTER 1,718 ms." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/lock-waits.svg"&gt;&lt;/p&gt;
&lt;p&gt;The plain read returned the committed balance without waiting. Everything that wanted to change the row, or to lock it, waited until A committed: row-level locks &amp;ldquo;do not affect data querying; they block only writers and lockers to the same row&amp;rdquo; (&lt;a class="link" href="https://www.postgresql.org/docs/18/explicit-locking.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt;). &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; is a locking read and behaves like a writer; it waited, then returned the value A had just committed rather than an older snapshot. (What B&amp;rsquo;s own update does after its wait is where lost updates come from, and the isolation levels post measures it.)&lt;/p&gt;
&lt;p&gt;Every one of those waits lasted as long as A&amp;rsquo;s transaction, not A&amp;rsquo;s statement. Run once more with A&amp;rsquo;s update sent without &lt;code&gt;BEGIN&lt;/code&gt;, so that it committed on its own, B waited 9.2 ms instead of 1,710; same statement, same idle connection afterwards. A row lock is held until the transaction that took it ends, and PostgreSQL stores it in the row version itself, in that same &lt;code&gt;xmax&lt;/code&gt; field, which is why it &amp;ldquo;doesn&amp;rsquo;t remember any information about modified rows in memory, so there is no limit on the number of rows locked at one time.&amp;rdquo; It also locks only rows that exist: the insert of id 1001 went through even though A had locked everything above 990, because PostgreSQL has no locks on gaps. (MySQL at its default settings made the same insert wait the full 2 seconds.)&lt;/p&gt;
&lt;p&gt;The last two rows involve no row lock. Session A had only read one row, and at the default settings an idle transaction holds no snapshot, so by everything above it should cost nothing. But every statement also takes a lock on the table itself, held until the transaction ends; a plain &lt;code&gt;SELECT&lt;/code&gt; takes the weakest kind, &lt;code&gt;ACCESS SHARE&lt;/code&gt;, and &amp;ldquo;only an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; lock blocks a &lt;code&gt;SELECT&lt;/code&gt;&amp;rdquo;, which is the lock most forms of &lt;code&gt;ALTER TABLE&lt;/code&gt; need. So the &lt;code&gt;ALTER&lt;/code&gt; waited for idle A, and a plain read from a third session then waited behind the queued &lt;code&gt;ALTER&lt;/code&gt;. An idle transaction plus a schema change is one of the few ways to make plain reads wait in PostgreSQL.&lt;/p&gt;
&lt;h2 id="vacuum-frees-the-space-but-keeps-the-file"&gt;VACUUM frees the space but keeps the file
&lt;/h2&gt;&lt;p&gt;MVCC is not free, and the bill turns up in the table file. A version that no snapshot can see anymore is called a dead tuple (tuple is PostgreSQL&amp;rsquo;s word for a row version), or dead row, and it takes up space until something removes it. Update all million accounts in one statement and the table gets a million new versions while the million old ones stay where they were. On disk, that took the table from 135 MB to 269 MB.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart: the PostgreSQL table went from 135 MB to 269 MB with 1,000,001 dead rows after updating every row, stayed 269 MB after VACUUM and after a second full update, and went back to 135 MB after VACUUM FULL." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/full-update.svg"&gt;&lt;/p&gt;
&lt;p&gt;VACUUM is the command that removes dead rows, and in production the autovacuum background process runs it on its own. I turned autovacuum off for these runs, the one setting changed from the defaults, so that each cleanup step happens only when I run it; what follows applies to autovacuum just the same.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Step&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Table&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Primary key index&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Dead rows&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Took&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Before&lt;/td&gt;
 &lt;td style="text-align: right"&gt;135 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;21 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2&lt;/td&gt;
 &lt;td style="text-align: right"&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After updating every row&lt;/td&gt;
 &lt;td style="text-align: right"&gt;269 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;43 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,000,001&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2.6 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After &lt;code&gt;VACUUM&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;269 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;43 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1.4 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After a second full update&lt;/td&gt;
 &lt;td style="text-align: right"&gt;269 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;43 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,000,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2.9 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After &lt;code&gt;VACUUM&lt;/code&gt; again&lt;/td&gt;
 &lt;td style="text-align: right"&gt;269 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;43 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0.9 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After &lt;code&gt;VACUUM FULL&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;135 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;21 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0.5 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The index doubled along with the table, one new entry for every new version. &lt;code&gt;VACUUM&lt;/code&gt; removed the dead rows, but the file stayed 269 MB: it &amp;ldquo;marks the space available for future reuse&amp;rdquo; and &amp;ldquo;will not return the space to the operating system&amp;rdquo; (&lt;a class="link" href="https://www.postgresql.org/docs/18/routine-vacuuming.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt;), apart from empty pages at the very end. The second full update reused that space and the table did not grow again, so a table that is updated steadily settles at some size above its live data and stays there, as long as VACUUM keeps up. &lt;code&gt;VACUUM FULL&lt;/code&gt; rewrote the table at its original size in half a second, but it takes an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; lock, so on a busy table that is downtime for as long as the rewrite runs.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Dead rows do not always wait for VACUUM&lt;/strong&gt;
 &lt;div&gt;When PostgreSQL reads a page that holds dead row versions nobody can see anymore, it can prune them on the spot, which the &lt;a class="link" href="https://www.postgresql.org/docs/18/storage-hot.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt; describes as happening &amp;ldquo;during normal operation, including SELECTs.&amp;rdquo;&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;VACUUM has a second job, and it comes from the size of those transaction numbers. &lt;code&gt;xmin&lt;/code&gt; and &lt;code&gt;xmax&lt;/code&gt; are 32-bit integers, so the counter reaches about four billion and wraps around to zero. PostgreSQL compares the numbers in a circle, with two billion counting as the past and two billion as the future at any moment, and the &lt;a class="link" href="https://www.postgresql.org/docs/18/routine-vacuuming.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt; spells out what happens to a version whose &lt;code&gt;xmin&lt;/code&gt; is left behind as the counter moves on: &amp;ldquo;it will suddenly appear to be in the future&amp;rdquo;, so its row becomes invisible, &amp;ldquo;in short, catastrophic data loss.&amp;rdquo; The fix is freezing: VACUUM marks versions old enough that every snapshot must see them as frozen, which takes them out of the comparison, and autovacuum forces this on any table with unfrozen versions older than &lt;code&gt;autovacuum_freeze_max_age&lt;/code&gt; (200 million transactions by default), even where autovacuum is otherwise off. If freezing falls behind, PostgreSQL warns when forty million numbers remain, and with three million left it stops assigning new ones: writes fail until a VACUUM has run. Sentry lost most of a working day to exactly that on &lt;a class="link" href="https://blog.sentry.io/transaction-id-wraparound-in-postgres/" target="_blank" rel="noopener"
 &gt;20 July 2015&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="what-can-hold-vacuum-back"&gt;What can hold VACUUM back
&lt;/h2&gt;&lt;p&gt;VACUUM, auto or manual, is bound by the same visibility rule as every reader: it may remove a version only once no open transaction could still see it, and it cannot freeze one either. So an open transaction can hold old versions in place, and the question is which kinds count. Session A opens a transaction, does one small thing and then does nothing, the way an application can leave a connection sitting inside &lt;code&gt;BEGIN&lt;/code&gt;, while session B makes 100,000 single-row updates to 1,000 accounts, each its own transaction. Then VACUUM counts the dead rows it is not yet allowed to remove.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Session A, sitting idle&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Dead rows VACUUM could not remove&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;No transaction open&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Default settings, had only read&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Default settings, had updated one unrelated row&lt;/td&gt;
 &lt;td style="text-align: right"&gt;100,000&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;One snapshot for the whole transaction, had only read&lt;/td&gt;
 &lt;td style="text-align: right"&gt;100,000&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The last row is what snapshot lifetime predicts: A&amp;rsquo;s snapshot predates every one of B&amp;rsquo;s updates, so every old version is one A might still ask for. The third row is the one to remember. A transaction that has written anything carries a transaction number, and PostgreSQL keeps every version retired by a later-numbered transaction until that one finishes, snapshot or no snapshot. Updating one unrelated row and then waiting pinned all 100,000 dead rows, and every lookup of those accounts, from any session, read 104 pages instead of 4 until A committed. The next VACUUM then removed them in 30 ms.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The idle connection is the problem, not the query&lt;/strong&gt;
 &lt;div&gt;Nothing about session A looks expensive: one small &lt;code&gt;SELECT&lt;/code&gt; or one small &lt;code&gt;UPDATE&lt;/code&gt;, then silence. The damage comes from the transaction staying open. After a write it pins dead rows, and even after a plain read it holds a table lock that any &lt;code&gt;ALTER TABLE&lt;/code&gt; will queue behind, taking every later query on that table with it. A &lt;code&gt;psql&lt;/code&gt; session left inside &lt;code&gt;BEGIN&lt;/code&gt; over someone&amp;rsquo;s lunch break is enough.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="what-to-watch"&gt;What to watch
&lt;/h2&gt;&lt;p&gt;Two numbers tell you whether MVCC&amp;rsquo;s bill is being paid. &lt;code&gt;n_dead_tup&lt;/code&gt; in &lt;code&gt;pg_stat_user_tables&lt;/code&gt; is the count of dead rows per table; it should rise and fall as autovacuum visits, and a table where it only rises is one autovacuum cannot clean. &lt;code&gt;pg_stat_activity&lt;/code&gt; shows who is stopping it: a session in state &lt;code&gt;idle in transaction&lt;/code&gt; with an old &lt;code&gt;xact_start&lt;/code&gt; is session A, and &lt;code&gt;backend_xid&lt;/code&gt; or &lt;code&gt;backend_xmin&lt;/code&gt; being set means it is pinning versions. &lt;code&gt;idle_in_transaction_session_timeout&lt;/code&gt;, off by default, ends such sessions after a time you choose. The habit behind both is committing before waiting on anything outside the database, and in PostgreSQL that includes transactions that have written something, even at the default settings.&lt;/p&gt;</description></item><item><title>Primary and Foreign Keys Explained: One Missing Index, 50 ms per Delete</title><link>https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/</link><pubDate>Thu, 12 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Primary and Foreign Keys Explained: One Missing Index, 50 ms per Delete" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A primary key and a foreign key are rules about rows that the database checks on every write: one row per key, and no reference to a row that does not exist. This post covers what each one checks and how, what the checks cost on inserts and deletes, the index a foreign key needs that PostgreSQL does not create for you, and what happens to the referencing rows when the row they point at is deleted or changes its key. Every number comes from runs on PostgreSQL 18.6 and MySQL 8.4.13.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img alt="Two tables side by side. The orders table on the left has columns id, total and customer_id; the customers table on the right has id and email. Arrows run from each order’s customer_id to the customer row with that id. Customer 42 has been deleted, and order 1004 still points at it with a dashed arrow, which makes it an orphan." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/parent-child.svg"&gt;&lt;/p&gt;
&lt;p&gt;So here is how keys work, in outline. Two tables that belong together are connected by a column: each order stores the id of the customer who placed it, and that copy of the id is the whole connection. The table being pointed at is called the parent, customers here, and the one doing the pointing is the child. Nothing in the database knows about the arrows in the picture. Every program that writes to either table has to keep them pointing at real rows, and when one of them doesn&amp;rsquo;t, the result is order 1004: a row that refers to a customer who no longer exists, called an orphan. Two rules move that job into the database. A primary key names the column that identifies each row and refuses a second row with the same value, so an id always means exactly one customer. A foreign key says that &lt;code&gt;orders.customer_id&lt;/code&gt; refers to &lt;code&gt;customers.id&lt;/code&gt;, and refuses any write that would leave an arrow pointing at nothing, from either table. The rest of this post is what those refusals look like, what they cost, and the one place where the cost lands somewhere you would not expect.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-tables-that-point-at-each-other"&gt;A quick reminder about tables that point at each other
&lt;/h2&gt;&lt;p&gt;The two tables from the picture, as the tests below created them, with primary keys but no foreign key yet:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;numeric&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;timestamptz&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The id a child stores is usually a number with no other meaning, so that it never has to change when a customer&amp;rsquo;s email or name does. A rule the database checks on every write is called a constraint. &lt;code&gt;NOT NULL&lt;/code&gt; and &lt;code&gt;UNIQUE&lt;/code&gt; above are constraints on one column; primary and foreign keys are the two that define how rows are identified and how tables connect.&lt;/p&gt;
&lt;p&gt;Without the foreign key, deleting customer 42, who had 16 orders, simply worked on both engines. This count found what it left behind, and it is the same query that finds orphans in any pair of tables that has run without a key:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;DELETE FROM customers WHERE id = 42; -- customer 42 had 16 orders
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;SELECT count(*) AS orphans
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;FROM orders o LEFT JOIN customers c ON c.id = o.customer_id
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;WHERE c.id IS NULL;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; orphans
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;---------
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; 16 (PostgreSQL 18.6 and MySQL 8.4.13 alike)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The tests below ran on this schema with 200,000 customers and 2,000,000 orders, each order assigned to a random customer among the first 190,000, so customers 190,001 to 200,000 have no orders at all. Both engines ran in Docker on the same machine, with the data already cached in memory.&lt;/p&gt;
&lt;h2 id="a-primary-key-is-checked-on-every-insert"&gt;A primary key is checked on every insert
&lt;/h2&gt;&lt;p&gt;A primary key promises two things about a column: no two rows share a value, and no row leaves it empty. Checking the first promise on every insert would mean reading the whole table if the database had nowhere faster to look, so both engines build an index for the key, a sorted copy of the column with a pointer to each row, and look the new value up in it. On PostgreSQL the catalog shows what declaring the key created, a unique index called &lt;code&gt;customers_pkey&lt;/code&gt; and a &lt;code&gt;NOT NULL&lt;/code&gt; flag on the column. Inserting a second customer 42 then fails on each engine:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-gdscript3" data-lang="gdscript3"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PostgreSQL&lt;/span&gt; &lt;span class="mf"&gt;18.6&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ERROR&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;duplicate&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="n"&gt;violates&lt;/span&gt; &lt;span class="n"&gt;unique&lt;/span&gt; &lt;span class="n"&gt;constraint&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;customers_pkey&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;DETAIL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Key&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;already&lt;/span&gt; &lt;span class="n"&gt;exists&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;MySQL&lt;/span&gt; &lt;span class="mf"&gt;8.4&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ERROR&lt;/span&gt; &lt;span class="mi"&gt;1062&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;23000&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="n"&gt;Duplicate&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;42&amp;#39;&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;customers.PRIMARY&amp;#39;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL&amp;rsquo;s index is more than a lookup aid. InnoDB, its default storage engine, stores the table&amp;rsquo;s rows inside the primary key index, in key order, so the key decides where every row lives on disk; the &lt;a class="link" href="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/" &gt;clustered index post&lt;/a&gt; measures what that does to reads.&lt;/p&gt;
&lt;p&gt;Neither engine requires a primary key by default. A table declared without one accepted two identical rows on both engines, &lt;code&gt;(1, 'a@x')&lt;/code&gt; twice, and nothing afterwards can tell them apart, update one without the other, or let another table refer to just one of them. MySQL quietly adds a hidden key of its own to such a table (it showed up in &lt;code&gt;information_schema.INNODB_INDEXES&lt;/code&gt; as &lt;code&gt;GEN_CLUST_INDEX&lt;/code&gt;), because InnoDB has to store rows in some key&amp;rsquo;s order, but nothing outside the engine can use it. MySQL can refuse tables without a primary key if &lt;code&gt;sql_require_primary_key&lt;/code&gt; is turned on; it was off.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Natural or surrogate&lt;/strong&gt;
 &lt;div&gt;The id above is a surrogate key: a value invented only to identify the row. The alternative is a natural key, a value that already identifies the thing, such as an email address. A natural key saves a column and a lookup, but every table that refers to it stores the value too, and when the value changes, every one of those copies has to change with it. The last section measures what that cost.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="a-foreign-key-is-checked-from-both-sides"&gt;A foreign key is checked from both sides
&lt;/h2&gt;&lt;p&gt;A foreign key on &lt;code&gt;orders.customer_id&lt;/code&gt; promises that every value in that column matches an existing &lt;code&gt;customers.id&lt;/code&gt;. The promise can be broken from either table, so the database checks both. Inserting an order for a customer who does not exist is refused, and deleting a customer who still has orders is refused too. Here is the delete of customer 42 again, with the foreign key in place:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-mysql" data-lang="mysql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PostgreSQL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ERROR&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;update&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;or&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;delete&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;on&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;customers&amp;#34;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;violates&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;foreign&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;key&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;constraint&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;orders_customer_fk&amp;#34;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;on&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;orders&amp;#34;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DETAIL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;Key&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;is&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;still&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;referenced&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;orders&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;MySQL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ERROR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1451&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;23000&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Cannot&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;delete&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;or&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;update&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;foreign&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;key&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;constraint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;fails&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;shop&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CONSTRAINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;orders_customer_fk&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;A delete like that is the case any test finds: delete a customer, count their orders, fail. It is also the usual reason for leaving the check to the application. The code that deletes a customer can delete their orders in the same transaction, the code that adds an order can check first that the customer exists, and each of those is correct on its own. What a transaction does not cover is another transaction running at the same time. On both engines, at their default isolation levels, one transaction checked that customer 42 existed and two seconds later inserted an order for it. In between, a second transaction deleted customer 42&amp;rsquo;s orders, then customer 42, and committed. Then the first one committed too, and the new order pointed at nobody, in three runs out of three. The check had read a customer who was about to disappear, and the delete had removed every order it could see, which did not include one that did not exist yet. With the foreign key in place, both engines refused the insert (&lt;code&gt;violates foreign key constraint&lt;/code&gt; on PostgreSQL, error 1452 on MySQL), because the key&amp;rsquo;s check runs at the moment of the insert and locks the customer row it finds, so that customer cannot be deleted until the order is committed.&lt;/p&gt;
&lt;p&gt;Running the same two transactions in the other order split the engines. When the order was inserted first and committed after the delete, PostgreSQL&amp;rsquo;s delete did not see the uncommitted order and left it orphaned, three runs out of three. MySQL&amp;rsquo;s delete waited 1.4 s for the insert to commit and then removed the new order along with the others, because at its default level a delete locks the range of index entries it scans. Raising both transactions to &lt;code&gt;SERIALIZABLE&lt;/code&gt; also stopped the first case without a foreign key, by failing one of them (PostgreSQL: &lt;code&gt;could not serialize access due to read/write dependencies among transactions&lt;/code&gt;; MySQL: deadlock, error 1213), which the application then has to catch and retry; the post on isolation levels explains why. None of this needs a bug, and a test suite that sends one request at a time never sees it. Other writes skip the application altogether: a query typed into a terminal, one an AI assistant wrote, a bulk load, a second service writing the same tables. The database is the one place every write passes through (the &lt;a class="link" href="https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/" &gt;business logic post&lt;/a&gt; makes that argument in full).&lt;/p&gt;
&lt;p&gt;A handful of orphans does not stay a handful of rows. A report that joins orders to customers drops them, a report that reads orders alone counts them, and the two totals stop agreeing. Any statement that writes from such a join, an invoice run or a loyalty tier or a copy into the warehouse, carries the disagreement into another table, where it outlives the orphans. The ids can also come back. In MySQL 5.7, the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html" target="_blank" rel="noopener"
 &gt;manual says&lt;/a&gt;, the auto-increment counter lived only in memory and restarted from the highest id still in the table. Deleting the newest customer while their orders stayed, restarting 5.7.44 and inserting a signup produced this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;MySQL 5.7.44: INSERT INTO customers (email) VALUES (&amp;#39;new-signup@x&amp;#39;); -- given id 5
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;| email | orders | lifetime_value |
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;| new-signup@x | 3 | 245.50 |
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The new customer inherited three orders it never placed. MySQL 8.0 made the counter survive restarts, and 8.4.13 gave the same signup id 6. PostgreSQL sequences do not move backwards on their own, only when someone sets them back, which a restore or a hand-made data fix sometimes does.&lt;/p&gt;
&lt;p&gt;The constraint has a second job: it is the only place the database records how two tables connect. A tool that reads the schema instead of the application code finds that record in the catalog, the system tables in which the database describes itself. Given a foreign key on &lt;code&gt;customer_id&lt;/code&gt; and another on a &lt;code&gt;placed_by&lt;/code&gt; column pointing at a &lt;code&gt;staff&lt;/code&gt; table, the catalog listed both:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-gdscript3" data-lang="gdscript3"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PostgreSQL&lt;/span&gt; &lt;span class="mf"&gt;18.6&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;conrelid&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt; &lt;span class="n"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;child&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pg_get_constraintdef&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;definition&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;pg_constraint&lt;/span&gt; &lt;span class="n"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;contype&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;f&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;child&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;definition&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;--------+----------------------------------------------------&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;FOREIGN&lt;/span&gt; &lt;span class="n"&gt;KEY&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;REFERENCES&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;FOREIGN&lt;/span&gt; &lt;span class="n"&gt;KEY&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;placed_by&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;REFERENCES&lt;/span&gt; &lt;span class="n"&gt;staff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;MySQL&lt;/span&gt; &lt;span class="mf"&gt;8.4&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;TABLE_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;COLUMN_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;REFERENCED_TABLE_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;REFERENCED_COLUMN_NAME&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;KEY_COLUMN_USAGE&lt;/span&gt; &lt;span class="n"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;REFERENCED_TABLE_NAME&lt;/span&gt; &lt;span class="n"&gt;IS&lt;/span&gt; &lt;span class="n"&gt;NOT&lt;/span&gt; &lt;span class="n"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;placed_by&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;staff&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The same table created without the two constraints did not appear in either list. That is what ORM model generators, diagram tools and AI assistants writing SQL from a schema dump have to work with. With the key declared, the join is written down. Without it, all they have is the column name: &lt;code&gt;customer_id&lt;/code&gt; next to a &lt;code&gt;customers&lt;/code&gt; table is an easy guess, but nothing in the name &lt;code&gt;placed_by&lt;/code&gt; says &lt;code&gt;staff&lt;/code&gt;, and a model guessing from names will still pick a join and write the query around it. The &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;post on what AI gets wrong about databases&lt;/a&gt; covers the other places where the schema and the data drift apart.&lt;/p&gt;
&lt;p&gt;The check on the child side is a lookup in the parent&amp;rsquo;s primary key index for every row written. PostgreSQL runs it as an internal trigger, which &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; on an insert lists by name (&lt;code&gt;Trigger for constraint orders_customer_fk: calls=200000&lt;/code&gt;). To see what it costs, both engines inserted 200,000 orders in one statement, with and without the foreign key, and with and without an index on &lt;code&gt;orders.customer_id&lt;/code&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart, median of 3 runs inserting 200,000 orders. PostgreSQL: no foreign key and no index 295 to 365 ms; index only 308 to 397 ms; foreign key without index 821 to 1,019 ms; foreign key and index 829 to 1,140 ms. MySQL: no foreign key and no index 275 to 286 ms; index only 519 to 605 ms; foreign key, which requires the index, 532 to 639 ms." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/insert-cost.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;200,000 orders in one INSERT (3 runs)&lt;/th&gt;
 &lt;th&gt;PostgreSQL 18.6&lt;/th&gt;
 &lt;th&gt;MySQL 8.4.13&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;no foreign key, no index&lt;/td&gt;
 &lt;td&gt;295–365 ms&lt;/td&gt;
 &lt;td&gt;275–286 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;index on &lt;code&gt;customer_id&lt;/code&gt; only&lt;/td&gt;
 &lt;td&gt;308–397 ms&lt;/td&gt;
 &lt;td&gt;519–605 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;foreign key, no index&lt;/td&gt;
 &lt;td&gt;821–1,019 ms&lt;/td&gt;
 &lt;td&gt;not allowed&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;foreign key and index&lt;/td&gt;
 &lt;td&gt;829–1,140 ms&lt;/td&gt;
 &lt;td&gt;532–639 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;On PostgreSQL the check itself was the cost: 2.5 to 2.8 microseconds per row, comparing medians with and without the index, enough to more than double this bulk insert. On MySQL the check added little that could be told apart from run-to-run noise, and the extra time came from maintaining the index on &lt;code&gt;customer_id&lt;/code&gt;, which MySQL insists a foreign key has. For an application inserting rows one at a time over a network, a few microseconds per row is far below the cost of the round trip. For a bulk load, it is real, and it is the honest case for loading first and adding the constraint afterwards.&lt;/p&gt;
&lt;p&gt;There is one more cost, which only shows up with concurrent writes: while an order is being inserted, the parent customer row is locked against deletion, and two transactions writing children of the same parent can end up waiting on each other. &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#foreign-keys-take-shared-locks-you-didnt-ask-for" &gt;Deadlocks Part 1&lt;/a&gt; measures that case.&lt;/p&gt;
&lt;h2 id="the-index-the-foreign-key-needs-on-the-other-side"&gt;The index the foreign key needs on the other side
&lt;/h2&gt;&lt;p&gt;The parent side of the check runs in the other direction. When a customer is deleted, the database has to prove that no order still points at it, which means searching &lt;code&gt;orders.customer_id&lt;/code&gt; for that value. If that column has an index, the search is a lookup. If it does not, the only way to prove a value is absent is to read every row of the orders table.&lt;/p&gt;
&lt;p&gt;MySQL does not let that happen. Declaring the foreign key created an index on &lt;code&gt;orders.customer_id&lt;/code&gt; automatically, named after the constraint, and trying to drop it failed with &lt;code&gt;ERROR 1553 (HY000): Cannot drop index 'orders_customer_fk': needed in a foreign key constraint&lt;/code&gt;. PostgreSQL creates an index for the primary key it points at, but nothing on the referencing column; the &lt;a class="link" href="https://www.postgresql.org/docs/18/ddl-constraints.html#DDL-CONSTRAINTS-FK" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt; says that &amp;ldquo;since a DELETE of a row from the referenced table &amp;hellip; will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns too,&amp;rdquo; and leaves it to you.&lt;/p&gt;
&lt;p&gt;The test deleted 200 customers who had no orders, the cheapest delete there is, since nothing has to be refused or cascaded:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart, deleting 200 customers with no orders from a 2,000,000-row orders table. PostgreSQL without an index on orders.customer_id: 10.2 to 10.5 seconds. PostgreSQL with the index: 1.0 to 1.6 ms. MySQL, whose foreign key created the index: 0.6 to 1.2 ms." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/delete-without-index.svg"&gt;&lt;/p&gt;
&lt;p&gt;Without the index, PostgreSQL spent 10.2 and 10.5 seconds in two runs, almost all of it in the foreign key trigger, which &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; reported as &lt;code&gt;time=10218.440 calls=200&lt;/code&gt;: about 51 ms per customer, each one a full read of the 2,000,000-row orders table to find nothing. A single delete took 47 ms. With the index the same 200 deletes took 1.0 and 1.6 ms, and a single one 0.025 ms. MySQL, with the index it insisted on, took 0.6 to 1.2 ms.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Index the referencing column on PostgreSQL&lt;/strong&gt;
 &lt;div&gt;A foreign key on PostgreSQL without an index on its referencing column makes every delete or key change in the parent table read the whole child table. Nothing warns about it: the deletes work, they just get slower as the child table grows, and a nightly cleanup of a few thousand rows becomes a job measured in hours. The index took 17 MB for the 2,000,000 orders here, and the query at the end of this post lists the foreign keys that lack one.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-parent-is-deleted-or-its-key-changes"&gt;When the parent is deleted or its key changes
&lt;/h2&gt;&lt;p&gt;Refusing the delete is the default, but it is one of several choices, declared on the foreign key itself. &lt;code&gt;ON DELETE RESTRICT&lt;/code&gt; (or the default, &lt;code&gt;NO ACTION&lt;/code&gt;, which on PostgreSQL differs only in when the check runs and on MySQL not at all) refuses the delete while children exist. &lt;code&gt;ON DELETE CASCADE&lt;/code&gt; deletes the children with the parent. &lt;code&gt;ON DELETE SET NULL&lt;/code&gt; keeps the children and empties their reference, which needs a column that allows empty values. The same choices exist for a change of the parent&amp;rsquo;s key, as &lt;code&gt;ON UPDATE&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;A cascade makes one statement do as much work as there are children. Customer 200,000 was given 100,000 orders, and deleting the customer with &lt;code&gt;ON DELETE CASCADE&lt;/code&gt; deleted all of them, leaving none behind on either engine. That took 17, 20 and 46 ms on PostgreSQL, and 171 to 183 ms on MySQL, with the index on &lt;code&gt;orders.customer_id&lt;/code&gt; in place on both. A cascade is the right shape when the children have no meaning without the parent, like the lines of an order. When the children are records someone will want later, like orders and invoices, refusing the delete keeps a mistake from removing them.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;ON UPDATE CASCADE&lt;/code&gt; is where the natural key from the earlier note gets expensive. For this test the same data was loaded into a second pair of tables in which customers are keyed by email and orders store the customer&amp;rsquo;s email instead of an id. When that customer with 100,000 orders changed their email, the database rewrote the email in every one of those orders:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart, one customer with 100,000 orders changing their email, 3 runs each. Email as the key: PostgreSQL 552 to 573 ms, MySQL 441 to 541 ms. Id as the key: PostgreSQL 0.01 to 0.14 ms, MySQL 0.10 to 0.30 ms." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/key-change.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;One email change, customer with 100,000 orders (3 runs)&lt;/th&gt;
 &lt;th&gt;PostgreSQL 18.6&lt;/th&gt;
 &lt;th&gt;MySQL 8.4.13&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;email is the key, orders store it&lt;/td&gt;
 &lt;td&gt;552–573 ms&lt;/td&gt;
 &lt;td&gt;441–541 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;id is the key, email is a plain column&lt;/td&gt;
 &lt;td&gt;0.01–0.14 ms&lt;/td&gt;
 &lt;td&gt;0.10–0.30 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;With the id as the key, the email lives in one row and nothing refers to it, so changing it is a one-row update. With the email as the key, the change touched 100,001 rows, and each rewritten order also rewrote its entry in the index on the email column. For a customer with 16 orders the natural-key change took under 1 ms after the first run, which is why the cost of a natural key tends to show up late, on the heaviest customers. The &lt;a class="link" href="https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/" &gt;generic id post&lt;/a&gt; covers naming; the &lt;a class="link" href="https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/" &gt;random UUID post&lt;/a&gt; covers what a random surrogate key costs instead of a sequential one.&lt;/p&gt;
&lt;p&gt;Partitioning changes how parents get deleted. A partitioned table is one table stored as several pieces, each holding the rows for a range of some column&amp;rsquo;s values, usually a date, so that a month of old orders can be removed by dropping its piece instead of deleting its rows one at a time. Foreign keys get in the way of that on both engines, in different ways.&lt;/p&gt;
&lt;p&gt;MySQL does not allow them at all. Creating a partitioned table with a foreign key, referencing a partitioned table from a plain one, and partitioning a table that already has a foreign key all failed the same way on MySQL 8.4.13: &lt;code&gt;ERROR 1506 (HY000): Foreign keys are not yet supported in conjunction with partitioning&lt;/code&gt;. PostgreSQL allows foreign keys in both directions, with one condition that shapes the schema. A partitioned table&amp;rsquo;s primary key has to include the partition column, so &lt;code&gt;orders&lt;/code&gt; partitioned by &lt;code&gt;created_at&lt;/code&gt; has the key &lt;code&gt;(id, created_at)&lt;/code&gt;, and a child cannot refer to &lt;code&gt;orders(id)&lt;/code&gt; alone; PostgreSQL refused that with &lt;code&gt;there is no unique constraint matching given keys&lt;/code&gt;. The child has to carry the partition column too:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL 18.6: orders and its lines, partitioned by the same date
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;date&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;RANGE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_lines&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;date&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;qty&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_created_at&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOREIGN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;RANGE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order_created_at&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;With both tables split by the same date, an old month has to go children first: detaching the October partition of &lt;code&gt;orders&lt;/code&gt; while October&amp;rsquo;s lines still existed failed with &lt;code&gt;removing partition &amp;quot;orders_2026_10&amp;quot; violates foreign key constraint&lt;/code&gt;, and detaching and dropping the lines&amp;rsquo; October partition first, then the orders&amp;rsquo;, went through.&lt;/p&gt;
&lt;p&gt;The strategy that works on both engines is to decide which tables get partitioned before deciding where the foreign keys go. The tables that grow without limit and get trimmed by date (events, logs, order history) tend to be at the edge of the schema: they refer to other tables, and nothing refers to them. Keeping it that way is a design choice. On PostgreSQL such a table can keep its foreign keys to the unpartitioned tables it points at; the partitioned &lt;code&gt;orders&lt;/code&gt; above still refused an order for customer 999. On MySQL it has to give them up, so the references from that one table become a check the application makes, plus a scheduled run of the orphan count from the start of this post, while the tables at the center, customers and orders and products, stay unpartitioned and keep theirs. When a partitioned table does have to be referenced, the children carry its partition column and get partitioned the same way, as above.&lt;/p&gt;
&lt;h2 id="what-to-check-in-your-own-schema"&gt;What to check in your own schema
&lt;/h2&gt;&lt;p&gt;Everything above, in one table:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;PostgreSQL 18.6&lt;/th&gt;
 &lt;th&gt;MySQL 8.4.13&lt;/th&gt;
 &lt;th&gt;Source&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Table without a primary key&lt;/td&gt;
 &lt;td&gt;allowed; identical rows accepted&lt;/td&gt;
 &lt;td&gt;allowed; identical rows accepted, hidden &lt;code&gt;GEN_CLUST_INDEX&lt;/code&gt; added&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;What a primary key creates&lt;/td&gt;
 &lt;td&gt;a unique index and &lt;code&gt;NOT NULL&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;the table itself, stored in key order&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Insert 200,000 child rows, foreign key vs none&lt;/td&gt;
 &lt;td&gt;821–1,019 ms vs 295–365 ms&lt;/td&gt;
 &lt;td&gt;532–639 ms vs 275–286 ms&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index on the referencing column&lt;/td&gt;
 &lt;td&gt;not created&lt;/td&gt;
 &lt;td&gt;created, cannot be dropped&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Delete 200 childless parents&lt;/td&gt;
 &lt;td&gt;10.2–10.5 s without that index, 1.0–1.6 ms with&lt;/td&gt;
 &lt;td&gt;0.6–1.2 ms&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;ON DELETE CASCADE&lt;/code&gt;, 100,000 children&lt;/td&gt;
 &lt;td&gt;17–46 ms&lt;/td&gt;
 &lt;td&gt;171–183 ms&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Key change, 100,000 children, natural vs surrogate key&lt;/td&gt;
 &lt;td&gt;552–573 ms vs 0.01–0.14 ms&lt;/td&gt;
 &lt;td&gt;441–541 ms vs 0.10–0.30 ms&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Foreign keys on a partitioned table&lt;/td&gt;
 &lt;td&gt;allowed both ways; a referenced table&amp;rsquo;s key must include the partition column, and children must carry it&lt;/td&gt;
 &lt;td&gt;not allowed in either direction (error 1506)&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Adding the foreign key to 2,000,000 existing orders&lt;/td&gt;
 &lt;td&gt;134 ms (one run)&lt;/td&gt;
 &lt;td&gt;9.7 s (one run, includes building the index)&lt;/td&gt;
 &lt;td&gt;measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two catalog queries find the gaps on PostgreSQL. Both were checked against a table created without a primary key and a foreign key whose index had been dropped, and each listed exactly that one:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Foreign keys whose referencing columns have no index
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conrelid&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;child_table&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_get_constraintdef&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_constraint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;contype&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;f&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;indrelid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conrelid&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;indkey&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;int2&lt;/span&gt;&lt;span class="p"&gt;[])[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="k"&gt;cardinality&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conkey&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;@&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conkey&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Tables without a primary key
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;nspname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;relname&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_namespace&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;relnamespace&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;relkind&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;r&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;nspname&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pg_catalog&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;information_schema&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_constraint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conrelid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;oid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;contype&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;p&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;On MySQL only the second question applies:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tables&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;BASE TABLE&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;mysql&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;sys&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;information_schema&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;performance_schema&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_constraints&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;constraint_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;PRIMARY KEY&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Adding a foreign key to a table that has run without one means every existing row is checked first, and any orphan makes the statement fail. The 2,000,000-row test took 134 ms on PostgreSQL and 9.7 s on MySQL, where the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-online-ddl-operations.html#online-ddl-foreign-key-operations" target="_blank" rel="noopener"
 &gt;online DDL documentation&lt;/a&gt; says adding a foreign key copies the table unless &lt;code&gt;foreign_key_checks&lt;/code&gt; is off. PostgreSQL can split the job: &lt;code&gt;ADD CONSTRAINT ... NOT VALID&lt;/code&gt; starts checking new writes immediately without reading old rows, and a later &lt;code&gt;VALIDATE CONSTRAINT&lt;/code&gt; checks the old rows without blocking writes. Run the orphan count from the start of this post first, because the validation stops at the first one it finds.&lt;/p&gt;</description></item><item><title>Hash Join vs Merge Join vs Nested Loop: When Each One Wins</title><link>https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/</link><pubDate>Tue, 10 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Hash Join vs Merge Join vs Nested Loop: When Each One Wins" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A join algorithm is the procedure a database uses to match the rows of one table with the rows of another, and PostgreSQL has three: nested loop, hash join and merge join. This post covers what each one needs, how to recognise each in a query plan (the database&amp;rsquo;s printout of how it runs a query), where the planner, the part that picks the plan, switches from one to the next, and what makes it switch at the wrong point; MySQL, which has two of the three, gets its own section. Every number comes from runs on PostgreSQL 18.6 and MySQL 8.4.13.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So here is how a join works, in outline. Looking up each row of one table in the other is the natural first answer, and with an index on the second table&amp;rsquo;s join column (a sorted copy of that column with pointers back to the rows) it is a good one, because each lookup goes straight to the few rows that match. But every lookup is a separate trip, into the index and then out to wherever those rows sit in the table, and a join that needs a large share of the table makes one such trip per row. Past some point it is cheaper to read the whole table once, front to back, and match rows as they go by. Databases do that in two ways: hold one side in a lookup table in memory and stream the other side past it, or read both sides in the same sorted order and pair them off. Counting the lookup, that makes three algorithms, called nested loop, hash join and merge join, and before each query PostgreSQL&amp;rsquo;s planner, the part that picks how a query runs, estimates the rows each step will produce, prices the options and runs the cheapest.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-query-plans"&gt;A quick reminder about query plans
&lt;/h2&gt;&lt;p&gt;The planner&amp;rsquo;s choice is printed in the query plan, the tree of steps the database runs to answer a query. &lt;code&gt;EXPLAIN&lt;/code&gt; shows the plan, and &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; runs the query and adds what actually happened. Each step is a node, indented under the node that uses its output, and each carries two estimates: &lt;code&gt;rows&lt;/code&gt;, how many rows the planner expects it to produce, and &lt;code&gt;cost&lt;/code&gt;, a number in arbitrary units that only means something next to the cost of another plan. A join is a node with two children, the two inputs it matches. The habit this post leans on is reading the estimated &lt;code&gt;rows&lt;/code&gt; against the actual ones, because the planner chose its join from the estimate; the how-tos for &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/" &gt;PostgreSQL&lt;/a&gt; and &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-mysql/" &gt;MySQL&lt;/a&gt; cover the rest of the output (MySQL calls its planner the optimizer).&lt;/p&gt;
&lt;h2 id="three-ways-to-join-two-tables"&gt;Three ways to join two tables
&lt;/h2&gt;&lt;p&gt;Each of the three needs something different from its inputs, and what it needs decides how its cost grows as the inputs grow. That growth is what the planner is really comparing when it prices them.&lt;/p&gt;
&lt;p&gt;The tests ran on PostgreSQL 18.6 and MySQL 8.4.13 in Docker with default settings, each container limited to 4 CPUs and 4 GB of memory, on the same tables as the two EXPLAIN posts: 200,000 customers and 5,000,000 orders, each order belonging to a random customer, with an index on &lt;code&gt;orders.customer_id&lt;/code&gt;. A third table, &lt;code&gt;shipments&lt;/code&gt;, holds one row for each of the 4,950,073 shipped orders, keyed by order id and written in order id order. PostgreSQL can split one join across several processes, and it can compile parts of a query at run time (JIT); I turned both off, as in the EXPLAIN post, so parallel joins are simplified away here. Every join is also an inner join on one equality, such as &lt;code&gt;o.customer_id = c.id&lt;/code&gt;; outer joins and other conditions change which of the three are allowed, which this post leaves aside. Timings are medians of five runs (three for the biggest joins) with the tables already read once. Run-to-run noise between sessions was up to about 20 percent, so smaller differences mean nothing.&lt;/p&gt;
&lt;p&gt;The query for most of this post totals the orders of the first N customers:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;h3 id="nested-loop"&gt;Nested loop
&lt;/h3&gt;&lt;p&gt;A nested loop is the lookup from the outline, and what it needs is an index on the second input&amp;rsquo;s join column, because it searches that input once for every row of the first. Without one, each search would have to read the whole orders table. With 1,000 customers PostgreSQL picks it (plan trimmed to the join and its two inputs):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Nested Loop (cost=0.85..93322.60 rows=24625 width=6) (actual time=0.010..54.458 rows=24899.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=8343 read=19558
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Only Scan using customers_pkey on customers c (cost=0.42..29.66 rows=985 width=4) (actual time=0.004..0.068 rows=1000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (id &amp;lt;= 1000)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Scan using orders_customer_id_idx on orders o (cost=0.43..94.45 rows=26 width=10) (actual time=0.003..0.053 rows=24.90 loops=1000)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = c.id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 55.356 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first child is called the outer side, and here it produces 1,000 customers. The second child, the inner side, runs once per customer (&lt;code&gt;loops=1000&lt;/code&gt;), and each run uses the index to find that customer&amp;rsquo;s 25 or so orders. So the work grows with the outer side: twice the customers, twice the index lookups. &lt;code&gt;Buffers&lt;/code&gt; counts pages, the 8 KB blocks PostgreSQL stores a table in, and this join touched 27,901 of them, because each customer&amp;rsquo;s orders are scattered across the table and almost every order lives on a different page.&lt;/p&gt;
&lt;h3 id="hash-join"&gt;Hash join
&lt;/h3&gt;&lt;p&gt;A hash join needs no index at all. What it needs is memory, for a hash table: a lookup structure, keyed on the join column, that it builds from one input before reading the other. Raise the limit to 20,000 customers and the plan changes to one:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Hash Join (cost=804.18..145898.06 rows=489805 width=6) (actual time=1.398..387.738 rows=500284.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Hash Cond: (o.customer_id = c.id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Seq Scan on orders o (cost=0.00..131968.48 rows=5000048 width=10) (actual time=0.066..179.694 rows=5000000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Hash (cost=559.28..559.28 rows=19592 width=4) (actual time=1.328..1.328 rows=20000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buckets: 32768 Batches: 1 Memory Usage: 960kB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Only Scan using customers_pkey on customers c (cost=0.42..559.28 rows=19592 width=4) (actual time=0.005..0.658 rows=20000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 407.853 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Read it from the bottom. The &lt;code&gt;Hash&lt;/code&gt; node collects the 20,000 customer ids into the hash table, which took 960 kB and a millisecond. Then &lt;code&gt;Seq Scan on orders&lt;/code&gt; reads all 5,000,000 orders once, and for each one the join checks the hash table for its &lt;code&gt;customer_id&lt;/code&gt;. Nothing runs more than once (&lt;code&gt;loops=1&lt;/code&gt; everywhere), and the index on &lt;code&gt;orders.customer_id&lt;/code&gt; is not used at all. Most of the cost is that one scan of the orders table, and it is the same whether the hash table holds 20 customers or 20,000: with only 10 customers a forced hash join still took 268 ms. The memory limit comes from &lt;code&gt;work_mem&lt;/code&gt; in PostgreSQL and &lt;code&gt;join_buffer_size&lt;/code&gt; in MySQL, and &lt;code&gt;Batches: 1&lt;/code&gt; means the hash table fit inside it. That line comes back below.&lt;/p&gt;
&lt;h3 id="merge-join"&gt;Merge join
&lt;/h3&gt;&lt;p&gt;A merge join needs both inputs sorted on the join column, either read from an index in that order or sorted first, and in return it reads each input once. The customers-and-orders query cannot get its orders in that order cheaply, as the next section shows. The &lt;code&gt;shipments&lt;/code&gt; join can, because both it and &lt;code&gt;orders&lt;/code&gt; have primary keys on the order id:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight_g&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shipments&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Merge Join (cost=12.71..366817.13 rows=4950090 width=4) (actual time=0.017..967.736 rows=4950073.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Merge Cond: (o.id = s.order_id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Only Scan using orders_pkey on orders o (cost=0.43..129849.15 rows=5000048 width=8) (actual time=0.004..188.127 rows=5000000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Scan using shipments_pkey on shipments s (cost=0.43..162601.78 rows=4950090 width=12) (actual time=0.011..337.965 rows=4950073.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 1083.770 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Both inputs come out of their primary key indexes already in order id order. The join reads one row from each side. If the ids match, that is a result row; if not, it moves the side with the smaller id forward. Each table is read once, front to back, with no hash table and no sort, and the &lt;code&gt;Merge Cond&lt;/code&gt; line gives it away.&lt;/p&gt;
&lt;p&gt;This is the case merge join exists for: two big tables, every row needed, both already in key order. Forcing the other two algorithms onto the same join shows why the planner picked it:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart: merge join 1,084 ms, hash join 1,621 ms with 64 batches, nested loop 3,029 ms with 4,950,073 primary key lookups." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/pg-big-join.svg"&gt;&lt;/p&gt;
&lt;p&gt;The hash join has to load 4,950,073 shipments into its hash table before it can match anything, and at the default &lt;code&gt;work_mem&lt;/code&gt; that table did not fit, so PostgreSQL split it into 64 batches written to temporary files (&lt;code&gt;Batches: 64&lt;/code&gt; under the &lt;code&gt;Hash&lt;/code&gt; node). The nested loop is less awful than its 4,950,073 lookups suggest, because it scans shipments in order id order, so consecutive lookups into the orders primary key land on the same index pages.&lt;/p&gt;
&lt;h2 id="where-the-choice-goes-wrong-and-two-fixes-that-backfire"&gt;Where the choice goes wrong, and two fixes that backfire
&lt;/h2&gt;&lt;p&gt;The planner prices the three from estimates, and on the customers-and-orders query the break-even point it worked from was about a third of the one measured. To find the real one, I ran that query at 17 sizes, from 10 customers to all 200,000, and forced each algorithm in turn with &lt;code&gt;enable_hashjoin&lt;/code&gt;, &lt;code&gt;enable_mergejoin&lt;/code&gt; and &lt;code&gt;enable_nestloop&lt;/code&gt; set to &lt;code&gt;off&lt;/code&gt; for the session.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Line chart: nested loop time rises in a straight line from near zero to 1,219 ms at 20,000 customers, while hash join stays flat around 300 to 360 ms. The lines cross near 5,000 customers; the planner switches to hash join at about 1,700." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/pg-crossover.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th style="text-align: right"&gt;Customers&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Orders joined&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Nested loop&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Hash join&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Merge join&lt;/th&gt;
 &lt;th&gt;Planner&amp;rsquo;s pick&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;100&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,446&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0.6 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;288 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0.6 ms&lt;/td&gt;
 &lt;td&gt;nested loop&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;1,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;24,899&lt;/td&gt;
 &lt;td style="text-align: right"&gt;68 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;381 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;58 ms&lt;/td&gt;
 &lt;td&gt;nested loop&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;2,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;50,076&lt;/td&gt;
 &lt;td style="text-align: right"&gt;126 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;312 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;118 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;5,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;125,075&lt;/td&gt;
 &lt;td style="text-align: right"&gt;311 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;306 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;297 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;10,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;250,098&lt;/td&gt;
 &lt;td style="text-align: right"&gt;589 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;323 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;604 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;20,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;500,284&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,219 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;360 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,451 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;50,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,250,570&lt;/td&gt;
 &lt;td style="text-align: right"&gt;3,014 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;450 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;3,083 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;200,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;5,000,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;13,451 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;863 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;12,511 ms&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The two cost shapes from the plans explain the whole table. Nested loop pays per customer, about 0.06 ms for each one&amp;rsquo;s index lookup and page reads, so its line is straight. Hash join pays mostly for one scan of the orders table, so its line is flat. They cross near 5,000 customers, which is 125,000 orders, 2.5 percent of the table. At 200,000 customers the nested loop does 200,000 lookups to fetch every row of a table that a single scan reads in under a second.&lt;/p&gt;
&lt;p&gt;Merge join tracks nested loop here, and for the same reason. To get orders in &lt;code&gt;customer_id&lt;/code&gt; order it walks the same index, fetching scattered pages one at a time. It came out slightly ahead between 1,000 and 4,000 customers, probably because it walks the index once instead of starting a new search for each customer, and it stops as soon as the customer side runs out, so it never reads the rest of the orders index.&lt;/p&gt;
&lt;p&gt;The planner is the surprise. It switched to hash join at 1,721 customers, when its own estimate reached about 1,695, and at 2,000 customers that choice cost 312 ms against 126 ms for the nested loop it rejected. It had the rows right. What it overpriced was the pages: the default &lt;code&gt;random_page_cost = 4&lt;/code&gt; tells it that a page fetched by an index lookup costs four times as much as a page read by a sequential scan, which is roughly right when the page has to come from a disk. In these runs every page was already in memory, so the lookups were much cheaper than the planner assumed.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The crossover moves with the cache&lt;/strong&gt;
 &lt;div&gt;The orders table is 640 MB, which fits in the container&amp;rsquo;s 4 GB but not in PostgreSQL&amp;rsquo;s 128 MB &lt;code&gt;shared_buffers&lt;/code&gt;, so most pages came from the operating system&amp;rsquo;s cache rather than disk. The jump in nested loop time from 300 customers (1.9 ms) to 1,000 (68 ms) is the point where the pages it touches stop fitting in &lt;code&gt;shared_buffers&lt;/code&gt;: the nested loop plan above shows 19,558 pages read from outside it. On a server where those reads go to disk, every nested loop lookup costs more, the crossover moves toward fewer customers, and the planner&amp;rsquo;s early switch looks much better. Lowering &lt;code&gt;random_page_cost&lt;/code&gt; toward 1.1 is the usual advice for SSDs, though the setting applies to every plan on the server at once.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;That miss cost about two and a half times the time at 2,000 customers. A wrong row estimate errs in the other direction: it can keep a nested loop running long past the line. The &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/" &gt;PostgreSQL EXPLAIN post&lt;/a&gt; showed one source of wrong estimates in this data: the planner treats &lt;code&gt;country&lt;/code&gt; and &lt;code&gt;city&lt;/code&gt; as unrelated, so it multiplies their selectivities, the fractions of rows each filter keeps. Every city belongs to exactly one country, so the second filter removes nothing the first did not already remove. Here are customers in four countries and those countries&amp;rsquo; 40 cities, 16,000 customers in total:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C00&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C02&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C03&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C00-0&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C00-1&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cm"&gt;/* ...all 40 cities of those countries... */&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C03-9&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Nested Loop (cost=0.53..122891.10 rows=32325 width=6) (actual time=0.043..1090.030 rows=399572.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=119775 read=329022
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Seq Scan on customers c (cost=0.10..5274.10 rows=1293 width=4) (actual time=0.019..15.588 rows=16000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Rows Removed by Filter: 184000
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Scan using orders_customer_id_idx on orders o (cost=0.43..90.70 rows=26 width=10) (actual time=0.004..0.066 rows=24.97 loops=16000)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = c.id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 1109.897 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The planner expected 1,293 customers, under its 1,700 switch point, and picked a nested loop. It got 16,000, and the inner side ran 16,000 times. The tell is on the outer side: estimated &lt;code&gt;rows=1293&lt;/code&gt;, actual &lt;code&gt;rows=16000.00&lt;/code&gt;, and an inner side whose &lt;code&gt;loops&lt;/code&gt; matches the actual figure, not the estimate.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart: the planner’s nested loop took 999 ms; a forced hash join took 375 ms; after CREATE STATISTICS the planner chose the hash join itself at 376 ms." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/pg-misestimate.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th style="text-align: right"&gt;Countries&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Estimated customers&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Actual customers&lt;/th&gt;
 &lt;th&gt;Planner&amp;rsquo;s pick&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Nested loop&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Hash join&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;2&lt;/td&gt;
 &lt;td style="text-align: right"&gt;333&lt;/td&gt;
 &lt;td style="text-align: right"&gt;8,000&lt;/td&gt;
 &lt;td&gt;nested loop&lt;/td&gt;
 &lt;td style="text-align: right"&gt;598 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;373 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;3&lt;/td&gt;
 &lt;td style="text-align: right"&gt;735&lt;/td&gt;
 &lt;td style="text-align: right"&gt;12,000&lt;/td&gt;
 &lt;td&gt;nested loop&lt;/td&gt;
 &lt;td style="text-align: right"&gt;855 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;344 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;4&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,293&lt;/td&gt;
 &lt;td style="text-align: right"&gt;16,000&lt;/td&gt;
 &lt;td&gt;nested loop&lt;/td&gt;
 &lt;td style="text-align: right"&gt;999 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;375 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;5&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,001&lt;/td&gt;
 &lt;td style="text-align: right"&gt;20,000&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,206 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;358 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;6&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,873&lt;/td&gt;
 &lt;td style="text-align: right"&gt;24,000&lt;/td&gt;
 &lt;td&gt;hash join&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,442 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;380 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The table is the crossover chart again, seen through the estimate. At two to four countries the estimate stays under about 1,700 and the planner keeps the nested loop, up to 2.7 times slower than the hash join. At five countries the estimate crosses 1,700, and the planner switches even though the estimate is still ten times too low. A wrong estimate costs nothing while it stays on the right side of the line.&lt;/p&gt;
&lt;p&gt;The fix is to tell the planner the columns are related:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;STATISTICS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers_country_city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dependencies&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;With that, the estimate for four countries went from 1,293 to 15,820 customers, the planner picked the hash join on its own, and the query took 376 ms. MySQL has no equivalent for two columns that share no index (its histograms cover one column each), and with an index on the join column it would not change the join method anyway, for the reason in the MySQL section below.&lt;/p&gt;
&lt;p&gt;The quicker reaction to a slow &lt;code&gt;Nested Loop&lt;/code&gt; is to turn nested loops off and see what happens. That is a good experiment and a bad fix, because the setting changes every query on the connection, and a nested loop that was slow for 16,000 rows is still the right plan for 16. Christophe Pettus &lt;a class="link" href="https://thebuild.com/blog/all-your-gucs-in-a-row-enable_nestloop/" target="_blank" rel="noopener"
 &gt;puts it plainly&lt;/a&gt; (July 2026): &amp;ldquo;Diagnose with the switch, then fix the statistics and set it back.&amp;rdquo;&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Turning off nested loops is a test, not a fix&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;SET enable_nestloop = off&lt;/code&gt; in one session is the quickest way to check whether a hash join would be faster. Leaving it off in &lt;code&gt;postgresql.conf&lt;/code&gt;, or in a connection pool&amp;rsquo;s startup settings, makes every small lookup join in the application pay for a full table scan. With only nested loops off, the 100-customer query took 237 ms as a hash join instead of 0.6 ms. Fix the estimate, then put the setting back.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The other obvious fix is memory. &lt;code&gt;Batches&lt;/code&gt; above 1 under a &lt;code&gt;Hash&lt;/code&gt; node means the hash table spilled to temporary files, as it did in the shipments join, and the natural response is to give it room. I raised &lt;code&gt;work_mem&lt;/code&gt; from 1 MB to 1 GB on that join with the hash join forced, and did the same with MySQL&amp;rsquo;s &lt;code&gt;join_buffer_size&lt;/code&gt;:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Two bar charts: in PostgreSQL the hash join took 1,446 ms at 1 MB of work_mem with 128 batches, rising to 2,425 ms at 1 GB with 1 batch; in MySQL it took 1,417 ms at 4 MB with 128 temp files and 3,349 ms at 1 GB in memory." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/hash-memory.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;PostgreSQL &lt;code&gt;work_mem&lt;/code&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Batches&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Hash join&lt;/th&gt;
 &lt;th&gt;MySQL &lt;code&gt;join_buffer_size&lt;/code&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Temp files&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Hash join&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;1 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;128&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,446 ms&lt;/td&gt;
 &lt;td&gt;256 KB (default)&lt;/td&gt;
 &lt;td style="text-align: right"&gt;256&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,893 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;4 MB (default)&lt;/td&gt;
 &lt;td style="text-align: right"&gt;64&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,503 ms&lt;/td&gt;
 &lt;td&gt;4 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;128&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,417 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;64 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;4&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,286 ms&lt;/td&gt;
 &lt;td&gt;64 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;8&lt;/td&gt;
 &lt;td style="text-align: right"&gt;3,076 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;1 GB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,425 ms&lt;/td&gt;
 &lt;td&gt;1 GB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;0&lt;/td&gt;
 &lt;td style="text-align: right"&gt;3,349 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;On both engines, the join got slower as it got more memory. In PostgreSQL the single in-memory hash table peaked at 297,571 kB, and the query took 60 percent longer than with 64 small batches. In MySQL the fully in-memory join took more than twice as long as the run that wrote 128 temporary files. I repeated the PostgreSQL runs in a different order, ten runs per setting in all, and the ranking held.&lt;/p&gt;
&lt;p&gt;The explanation that fits is the CPU cache. Each probe of a hash table lands at a random spot, and a 290 MB table is far larger than the processor&amp;rsquo;s cache, so nearly every probe waits on main memory, while a batch of a few megabytes stays in cache for as long as it is being probed. I did not measure cache misses, so treat that as the likely reason rather than a proven one. There is also a caveat that cuts the other way: the temporary files here never reached a disk, since the container had memory to spare and the operating system kept them in its cache. On a server short of memory, where those writes really hit storage, batching costs more.&lt;/p&gt;
&lt;p&gt;Small spills still cost something. MySQL&amp;rsquo;s default 256 KB join buffer is tiny: in the customers-and-orders join it spilled from 8,000 customers on, with 24 temporary files, and took 804 ms against 549 ms with a 4 MB buffer. So a few megabytes helped and a gigabyte hurt. &lt;code&gt;Batches: 64&lt;/code&gt; in a plan says the hash table spilled, which by itself says little about why a query is slow, and &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iv-when-the-sort-spills/" &gt;Part IV of the queries series&lt;/a&gt; covers why raising &lt;code&gt;work_mem&lt;/code&gt; server-wide is risky anyway.&lt;/p&gt;
&lt;h2 id="mysql-has-two-of-the-three-and-picks-one"&gt;MySQL has two of the three, and picks one
&lt;/h2&gt;&lt;p&gt;MySQL added hash joins in 8.0.18, and in 8.0.20 they &lt;a class="link" href="https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-20.html" target="_blank" rel="noopener"
 &gt;replaced the block nested loop&lt;/a&gt;, the older method for joining without an index. There is no merge join. The &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/hash-joins.html" target="_blank" rel="noopener"
 &gt;8.4 manual&lt;/a&gt; says when the hash join is used: &amp;ldquo;for any query for which each join has an equi-join condition, and in which there are no indexes that can be applied to any join conditions.&amp;rdquo; With an index on &lt;code&gt;orders.customer_id&lt;/code&gt;, the optimizer chose the nested loop at every size I tried. To get a hash join I had to hide the index with hints:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cm"&gt;/*+ JOIN_ORDER(c, o) NO_INDEX(o orders_customer_id_idx) */&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;20000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;img alt="Line chart: MySQL’s nested loop rises from near zero to 2,142 ms at 20,000 customers while a forced hash join stays near 550 ms, stepping up to about 830 ms once its hash table spills at 8,000 customers. The lines cross near 5,000." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/hash-join-vs-merge-join-vs-nested-loop-when-each-one-wins/my-crossover.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th style="text-align: right"&gt;Customers&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Nested loop (optimizer&amp;rsquo;s pick)&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Hash join (forced)&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;1,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;121 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;548 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;5,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;584 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;558 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;8,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;913 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;829 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;20,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,142 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;836 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;50,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,084 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;869 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td style="text-align: right"&gt;200,000&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,876 ms&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,237 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The crossover lands near 5,000 customers again, the same place as in PostgreSQL. The difference is that MySQL never makes the switch on its own. Both plans at 20,000 customers:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Nested loop inner join (cost=990339 rows=981020) (actual time=0.21..2149 rows=500284 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index range scan on c using PRIMARY over (id &amp;lt;= 20000) (cost=8022 rows=39992) (actual time=0.148..2.01 rows=20000 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index lookup on o using orders_customer_id_idx (customer_id=c.id) (cost=22.1 rows=24.5) (actual time=0.099..0.107 rows=25 loops=20000)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Inner hash join (o.customer_id = c.id) (cost=19.8e+9 rows=981020) (actual time=2.75..884 rows=500284 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on o (cost=1.39 rows=4.96e+6) (actual time=0.0958..502 rows=5e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Hash
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index range scan on c using PRIMARY over (id &amp;lt;= 20000) (cost=8022 rows=39992) (actual time=0.149..1.39 rows=20000 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The cost MySQL printed for the hash join it was forced into is 19.8e+9, against 990,339 for the nested loop. Those are 20,000 times apart, and the runtimes go the other way, 884 ms against 2,149. Whatever the optimizer&amp;rsquo;s model of a hash join is, it is not one it uses to compete with an index.&lt;/p&gt;
&lt;p&gt;What MySQL does change at larger sizes is the join order, which table goes on the outer side. From 50,000 customers on, it starts from the orders table, scanning all 5,000,000 rows once and looking up each order&amp;rsquo;s customer by primary key. That is still a nested loop, but its cost now grows with the orders scanned instead of the customers selected, which is why 50,000 customers ran faster than 20,000. At 200,000 customers it took 2,876 ms against 1,237 ms for the hash join. (MySQL&amp;rsquo;s optimizer, to its credit, is very consistent.)&lt;/p&gt;
&lt;p&gt;For a reporting query that joins a large share of two big tables, the lever in MySQL 8.4 is an index hint like the one above. Merge join is not available, so the shipments join ran either as a nested loop (2,614 ms) or as a hash join (1,417 to 3,349 ms depending on the buffer).&lt;/p&gt;
&lt;h2 id="what-to-check-when-a-join-is-slow"&gt;What to check when a join is slow
&lt;/h2&gt;&lt;p&gt;The three side by side, now that every cell has been measured above:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;Nested loop&lt;/th&gt;
 &lt;th&gt;Hash join&lt;/th&gt;
 &lt;th&gt;Merge join&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;How it works&lt;/td&gt;
 &lt;td&gt;For each row of the first input, look up matching rows in the second&lt;/td&gt;
 &lt;td&gt;Load one input into a hash table in memory, then check every row of the other against it&lt;/td&gt;
 &lt;td&gt;Walk two inputs sorted on the join column side by side&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;What it needs&lt;/td&gt;
 &lt;td&gt;An index on the second table&amp;rsquo;s join column&lt;/td&gt;
 &lt;td&gt;Memory for the hash table (&lt;code&gt;work_mem&lt;/code&gt; in PostgreSQL, &lt;code&gt;join_buffer_size&lt;/code&gt; in MySQL)&lt;/td&gt;
 &lt;td&gt;Both inputs in join-column order, from an index or a sort&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Fastest here&lt;/td&gt;
 &lt;td&gt;Under about 5,000 customers: 68 ms against 381 ms for hash at 1,000, with merge join tied because it walks the same index&lt;/td&gt;
 &lt;td&gt;Past about 5,000: 360 ms against 1,219 ms for nested loop at 20,000&lt;/td&gt;
 &lt;td&gt;Two big tables in key order: 1,084 ms against 1,621 ms hash and 3,029 ms nested loop&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;How it fails&lt;/td&gt;
 &lt;td&gt;Cost grows with every outer row: 13.5 s at 200,000 customers, against 0.86 s for hash&lt;/td&gt;
 &lt;td&gt;Starts by reading the whole second table, so it took 268 ms even for 10 customers&lt;/td&gt;
 &lt;td&gt;Without an index to supply the order, a sort comes first&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;PostgreSQL 18&lt;/td&gt;
 &lt;td&gt;Chosen by cost&lt;/td&gt;
 &lt;td&gt;Chosen by cost&lt;/td&gt;
 &lt;td&gt;Chosen by cost&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;MySQL 8.4&lt;/td&gt;
 &lt;td&gt;Chosen whenever an index fits the join&lt;/td&gt;
 &lt;td&gt;Used only when no index fits the join&lt;/td&gt;
 &lt;td&gt;Does not exist&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Everything in it was measured above except the sort in merge join&amp;rsquo;s failure row, which is documented behavior these tests never triggered.&lt;/p&gt;
&lt;p&gt;Start by naming the join. Each algorithm leaves the same marks in every plan above:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Algorithm&lt;/th&gt;
 &lt;th&gt;PostgreSQL plan&lt;/th&gt;
 &lt;th&gt;MySQL plan&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Nested loop&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Nested Loop&lt;/code&gt;, with &lt;code&gt;loops=&lt;/code&gt; on the inner child equal to the outer side&amp;rsquo;s rows&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Nested loop inner join&lt;/code&gt;, with an &lt;code&gt;Index lookup&lt;/code&gt; child and its &lt;code&gt;loops=&lt;/code&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Hash join&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Hash Join&lt;/code&gt; and &lt;code&gt;Hash Cond&lt;/code&gt;, over a &lt;code&gt;Hash&lt;/code&gt; child showing &lt;code&gt;Buckets&lt;/code&gt;, &lt;code&gt;Batches&lt;/code&gt; and &lt;code&gt;Memory Usage&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Inner hash join (o.customer_id = c.id)&lt;/code&gt;, over a &lt;code&gt;Hash&lt;/code&gt; child&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Merge join&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Merge Join&lt;/code&gt; and &lt;code&gt;Merge Cond&lt;/code&gt;, over two inputs in join-column order&lt;/td&gt;
 &lt;td&gt;does not exist&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Then read its outer side. If estimated rows and actual rows differ by more than a few times, the planner may have chosen for a size it never got, and the inner side&amp;rsquo;s &lt;code&gt;loops&lt;/code&gt; will match the actual number. In PostgreSQL, rerun the query in one session with &lt;code&gt;SET enable_nestloop = off&lt;/code&gt; or &lt;code&gt;enable_hashjoin = off&lt;/code&gt;. If the other plan is much faster, the algorithm choice was the problem, and the estimate is what to fix: &lt;code&gt;ANALYZE&lt;/code&gt;, a higher statistics target on the column, or &lt;code&gt;CREATE STATISTICS&lt;/code&gt; for columns that move together. In MySQL the same test is a &lt;code&gt;NO_INDEX&lt;/code&gt; hint on the inner table, and with an index on the join column a hint is also the only way to get a hash join.&lt;/p&gt;
&lt;p&gt;If the estimate is right and the join is still slow, look at how many rows go into it. A nested loop with 200,000 &lt;code&gt;loops&lt;/code&gt;, or a hash join building on millions of rows, is often a query asking for more than the screen shows. &lt;code&gt;Batches&lt;/code&gt; above 1 comes last: in these runs a few more megabytes helped and a gigabyte hurt.&lt;/p&gt;</description></item><item><title>Clustered vs Non-Clustered Index: The Table Is the Index in MySQL</title><link>https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/</link><pubDate>Mon, 09 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Clustered vs Non-Clustered Index: The Table Is the Index in MySQL" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A clustered index decides the order in which a table&amp;rsquo;s rows are stored on disk, and with it how many reads a query for related rows has to make. This post covers how InnoDB, MySQL&amp;rsquo;s storage engine, lays out a table, what every other (non-clustered) index costs and how it finds a row, and why the order of the primary key decides the reads. Then it measures what keeping related rows together costs on every insert, how much free room a rebuild can leave for new rows, and how PostgreSQL, which has no clustered index, gets close, on MySQL 8.4.13 and PostgreSQL 18.6.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So here is how InnoDB stores a table, in outline. The simplest way to build a table is to put each new row wherever there is room, usually at the end of a file, and keep every index beside it as a sorted list of values, each with the address of its row. Inserts are cheap that way, and every index works alike. The catch shows up once the table is bigger than memory. Rows that a query wants together (all the assets of one client, say) arrived at different times and were written to different places, so each one the index finds can be a separate read from disk. PostgreSQL stores its tables like that, in what it calls a heap. InnoDB, the storage engine MySQL uses by default, made the other choice: it stores the rows inside the primary key&amp;rsquo;s index, sorted by the primary key, so rows whose keys are close sit next to each other on disk. That index is the clustered index. Because rows can be kept in only one order, a table gets one, and every other index stores a primary key value where PostgreSQL&amp;rsquo;s would store an address. Choosing the primary key is choosing which rows share a place on disk.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-indexes-and-pages"&gt;A quick reminder about indexes and pages
&lt;/h2&gt;&lt;p&gt;An index is a sorted copy of one or more columns that lets the database find rows without reading the whole table. MySQL and PostgreSQL both build theirs as B-trees: a tree of pages, where the top page says which page below it holds which range of values, down to the bottom pages (the leaves) that hold the entries themselves. A page is the unit the database reads from disk, 16 KB in InnoDB and 8 KB in PostgreSQL, and reading one row means reading the whole page it is on. So the number of pages a query touches is most of what it costs, and it is the number this post counts.&lt;/p&gt;
&lt;p&gt;The term clustered index comes from SQL Server, where it names an index whose leaves are the table&amp;rsquo;s rows instead of pointers to them. Here is what that means for one client&amp;rsquo;s assets in each engine. The left half is what the rest of the post builds up, one piece at a time:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Left: in MySQL InnoDB the primary key tree holds the rows themselves, so one client’s 50 assets sit on one or two leaf pages, and a secondary index on asset_id stores the primary key and searches the tree again. Right: in PostgreSQL an index on client_id points to 50 page-and-position addresses scattered across the heap." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/storage-layout.svg"&gt;&lt;/p&gt;
&lt;h2 id="the-rows-live-inside-the-primary-key"&gt;The rows live inside the primary key
&lt;/h2&gt;&lt;p&gt;In InnoDB the primary key does not point at the rows, because its leaf pages are the rows. Here is the table most people would write first, with an auto-increment &lt;code&gt;asset_id&lt;/code&gt; as the primary key and an index on &lt;code&gt;client_id&lt;/code&gt; for looking up a client&amp;rsquo;s assets:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;serial&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;char&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;decimal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;acquired_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets_client_id_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-index-types.html" target="_blank" rel="noopener"
 &gt;MySQL manual&lt;/a&gt; says it directly: &amp;ldquo;Each InnoDB table has a special index called the clustered index that stores row data. Typically, the clustered index is synonymous with the primary key.&amp;rdquo; In B-tree terms, the leaf pages of the primary key&amp;rsquo;s tree hold whole rows, sorted by &lt;code&gt;asset_id&lt;/code&gt;, and the pages above them hold only enough of the key to find the right leaf. A new asset gets the next id, so it goes onto the last leaf page, and the table ends up in arrival order. That keeps inserts cheap. It also means that client 621&amp;rsquo;s 50 assets, added at 50 different moments over the years, sit on 50 different pages, each next to whatever other clients&amp;rsquo; assets arrived around the same time.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;A MySQL table always has a clustered index&lt;/strong&gt;
 &lt;div&gt;Leave out the primary key and InnoDB picks one anyway. It uses the first &lt;code&gt;UNIQUE&lt;/code&gt; index whose columns are all &lt;code&gt;NOT NULL&lt;/code&gt;, and if there is none, it generates a hidden 6-byte row id that &amp;ldquo;increases monotonically as new rows are inserted&amp;rdquo;, per the same manual page. The rows are still clustered, just by an order nobody chose.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The index on &lt;code&gt;client_id&lt;/code&gt; is the other kind. A non-clustered index, which MySQL calls a secondary index, is a B-tree of its own, and the manual describes what its leaves hold: &amp;ldquo;each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index.&amp;rdquo; So it does not know where a row is. It knows the row&amp;rsquo;s primary key, and getting from there to the row takes a second search, down the clustered index.&lt;/p&gt;
&lt;p&gt;To see what those two searches cost, I loaded both engines with the same data: MySQL 8.4.13 and PostgreSQL 18.6 in Docker with default settings. A &lt;code&gt;clients&lt;/code&gt; table has 100,000 rows. An &lt;code&gt;assets&lt;/code&gt; table has 5,000,000, each belonging to a random client, so a client&amp;rsquo;s assets arrive scattered over time, the way real data grows. The timed runs fetch the assets of 1,000 random clients with the container held to 1 GB of memory and 3,000 disk reads per second, roughly the baseline of an AWS gp3 volume, so that pages really come from disk. Page counts are averages over the same 1,000 clients. The test tables were loaded with &lt;code&gt;asset_id&lt;/code&gt; values already assigned in increasing order, the order an &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; column produces, and the plans below name the test copies (&lt;code&gt;a_by_id&lt;/code&gt;, &lt;code&gt;a_by_client&lt;/code&gt;, &lt;code&gt;assets_orig&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;Now fetch one client&amp;rsquo;s assets:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;621&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on a_by_id using assets_client_id_idx (client_id=621) (cost=55 rows=50) (actual time=0.0522..0.181 rows=50 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The plan names one step, and both searches are hiding inside it. The secondary index&amp;rsquo;s entries for client 621 are 50 pairs of &lt;code&gt;(621, asset_id)&lt;/code&gt;. To get &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;value&lt;/code&gt;, InnoDB takes each &lt;code&gt;asset_id&lt;/code&gt; and searches the clustered index for it: 50 separate searches, ending on 50 different pages. Averaged over 1,000 clients, that was 45 pages read from disk per lookup, for 50 rows.&lt;/p&gt;
&lt;p&gt;PostgreSQL ends up in the same place by a different road. Its table is a heap, and its index on &lt;code&gt;client_id&lt;/code&gt; holds row addresses instead of keys:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Bitmap Heap Scan on assets_orig (cost=4.83..206.34 rows=51 width=47) (actual time=1.328..7.858 rows=50.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Recheck Cond: (client_id = 621)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Blocks: exact=50
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=8 read=45
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Bitmap Index Scan on assets_orig_client_id_idx (cost=0.00..4.82 rows=51 width=0) (actual time=0.703..0.704 rows=50.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (client_id = 621)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared read=3
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;Heap Blocks: exact=50&lt;/code&gt; says the 50 addresses pointed to 50 different heap pages, and &lt;code&gt;read=45&lt;/code&gt; is the pages that had to come from outside PostgreSQL&amp;rsquo;s memory. The heap and the auto-increment clustered index have the same problem: both keep rows in arrival order, and this query wants them in client order. The difference is that InnoDB lets you pick the order. Sort the clustered index by client instead, and the same 50 assets sit together:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Two rows of pages. Top, clustered on asset_id: rows in arrival order, so client 621’s assets sit one per page across every page. Bottom, clustered on client_id then asset_id: each client’s rows fill their own run of pages, and all of client 621’s assets sit on one or two pages." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/page-grouping.svg"&gt;&lt;/p&gt;
&lt;h2 id="choosing-the-order-on-purpose"&gt;Choosing the order on purpose
&lt;/h2&gt;&lt;p&gt;Since a table gets one clustered index, the decision worth making is which order its rows are in, and the answer comes from how the application reads them. Assets belong to clients, and the application mostly reads them client by client: show me this client&amp;rsquo;s laptops, total this client&amp;rsquo;s asset value. So the schema is two tables. &lt;code&gt;clients&lt;/code&gt; keeps its own simple key, and &lt;code&gt;assets&lt;/code&gt; puts &lt;code&gt;client_id&lt;/code&gt; first in its primary key:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;region&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;serial&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;char&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;decimal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;acquired_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets_asset_id_uq&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The columns are the same as before, and only the last two lines changed. The primary key is now &lt;code&gt;(client_id, asset_id)&lt;/code&gt;, so the clustered index sorts rows by client first, and &lt;code&gt;asset_id&lt;/code&gt; puts each client&amp;rsquo;s assets in the order they arrived. Every asset of client 621 ends up next to the others, on one or two pages, whenever it was added.&lt;/p&gt;
&lt;p&gt;In a real schema &lt;code&gt;assets.client_id&lt;/code&gt; would also be a foreign key to &lt;code&gt;clients&lt;/code&gt;, and the primary key that starts with &lt;code&gt;client_id&lt;/code&gt; already provides the index the foreign key needs. The test tables left the foreign key out, so the insert timings further down do not include that check. &lt;code&gt;asset_id&lt;/code&gt; alone is still unique and still auto-increments, and the &lt;code&gt;UNIQUE KEY&lt;/code&gt; is not optional. Without it, MySQL 8.4 refuses the table:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;An &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; column has to be the first column of some index, and in the primary key it is second. The same query now reads the clustered index directly:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on a_by_client using PRIMARY (client_id=621) (cost=6.07 rows=50) (actual time=0.0123..0.0199 rows=50 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;using PRIMARY&lt;/code&gt; means the search went straight into the clustered index, found the first row for client 621, and read forward through the next 49, which were on the same page or the one after it. That was 1.7 pages from disk on average, against 45.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart: one client’s assets took 15.0 ms with 45 pages from disk in MySQL clustered on asset_id and 14.8 ms with 46 pages in the PostgreSQL heap, against 1.02 ms after CLUSTER, 0.60 ms with a covering index and 0.53 ms in MySQL clustered on client." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/one-client-lookup.svg"&gt;&lt;/p&gt;
&lt;p&gt;On a disk that allows 3,000 reads a second, every page read costs a third of a millisecond, so the page count turns straight into time: 15.0 ms on average for the default table, 0.53 ms for the one clustered by client.&lt;/p&gt;
&lt;p&gt;A composite primary key can still look like overthinking it. The default table already had an index on &lt;code&gt;client_id&lt;/code&gt;, the query used it, and with the whole table in memory the gap almost disappears: 0.66 ms against 0.25 ms in a warm run. That is why this kind of change looks pointless on a laptop (I have dismissed it that way myself). The index on &lt;code&gt;client_id&lt;/code&gt; finds the right rows in both tables. What it cannot do is put them on the same page; only the clustered index decides that. The difference shows once the data no longer fits in memory and each of those 45 pages is a trip to disk.&lt;/p&gt;
&lt;p&gt;The composite key also changes every other index on the table, because each one carries a copy of the primary key and ends each lookup with a search of the clustered index. Look up one asset by its id on the client-clustered table:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4995192&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;EXPLAIN&lt;/code&gt; shows &lt;code&gt;key: assets_asset_id_uq&lt;/code&gt;, the unique index, with &lt;code&gt;type: const&lt;/code&gt;, one row. What it does not show is that the unique index only holds &lt;code&gt;asset_id&lt;/code&gt; and the primary key &lt;code&gt;(client_id, asset_id)&lt;/code&gt;. InnoDB finds the entry, reads &lt;code&gt;client_id&lt;/code&gt; out of it, and then searches the clustered index for &lt;code&gt;(621, 4995192)&lt;/code&gt;, two trees instead of one. A lookup by id is fast either way, and the extra pages only matter for an application that does millions of them.&lt;/p&gt;
&lt;p&gt;Size is the other cost. I added an index on &lt;code&gt;acquired_at&lt;/code&gt; to both MySQL tables, which at that point held the same 6.5 million rows. With &lt;code&gt;asset_id&lt;/code&gt; as the primary key, each entry holds a date and an 8-byte id. With &lt;code&gt;(client_id, asset_id)&lt;/code&gt;, each entry also carries the 4-byte &lt;code&gt;client_id&lt;/code&gt;, and the index came out 22 percent bigger for the same dates. The manual&amp;rsquo;s advice follows from that: &amp;ldquo;If the primary key is long, the secondary indexes use more space, so it is advantageous to have a short primary key.&amp;rdquo; A 16-byte UUID primary key is copied into every index the same way, which is part of &lt;a class="link" href="https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/" &gt;what random UUIDs cost&lt;/a&gt;.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;What every other index pays&lt;/th&gt;
 &lt;th style="text-align: right"&gt;MySQL, key &lt;code&gt;asset_id&lt;/code&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;MySQL, key &lt;code&gt;(client_id, asset_id)&lt;/code&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;PostgreSQL heap&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;One asset by &lt;code&gt;asset_id&lt;/code&gt;, pages touched per lookup&lt;/td&gt;
 &lt;td style="text-align: right"&gt;4.0&lt;/td&gt;
 &lt;td style="text-align: right"&gt;8.4&lt;/td&gt;
 &lt;td style="text-align: right"&gt;4.0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index on &lt;code&gt;acquired_at&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;133 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;162 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;139 MB, whatever the key&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index on &lt;code&gt;client_id&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;149 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;not needed, the key starts with it&lt;/td&gt;
 &lt;td style="text-align: right"&gt;34 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;PostgreSQL&amp;rsquo;s indexes store a 6-byte row address no matter what the primary key is, which is why its &lt;code&gt;acquired_at&lt;/code&gt; index does not change with the key. Its index on &lt;code&gt;client_id&lt;/code&gt; is under a quarter the size of MySQL&amp;rsquo;s, because PostgreSQL (since version 13) stores a repeated value once with a list of row addresses, while InnoDB stores a full &lt;code&gt;(client_id, asset_id)&lt;/code&gt; entry for each of the 5 million rows.&lt;/p&gt;
&lt;h2 id="the-price-every-new-row-goes-into-the-middle"&gt;The price: every new row goes into the middle
&lt;/h2&gt;&lt;p&gt;What the composite key saves on reads, the table pays back on every insert. An auto-increment primary key puts every new row at the end of the table, on the last page, which is the cheapest place to write. Clustering by client means a new asset for client 621 has to go into client 621&amp;rsquo;s page, somewhere in the middle. If that page is full, InnoDB splits it into two half-full pages to make room, which is a page split. I inserted 1.5 million new assets for random clients into both tables, in batches of 10,000. Random clients is the worst case: if most new assets belong to recently created clients, and &lt;code&gt;client_id&lt;/code&gt; is itself an auto-increment, the inserts land near the end of the index anyway, which I reasoned through but did not measure.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Two bar charts: inserting 500,000 assets took 14.5 s clustered by asset_id and 65.6 s clustered by client; the next 1,000,000 took 34.5 s and 105.7 s. After the inserts the clustered index was 1,167 MB by asset_id and 2,601 MB by client, back to 1,337 MB after OPTIMIZE TABLE." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/insert-cost.svg"&gt;&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Clustered on &lt;code&gt;asset_id&lt;/code&gt;&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Clustered on &lt;code&gt;(client_id, asset_id)&lt;/code&gt;&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;First 500,000 inserts&lt;/td&gt;
 &lt;td style="text-align: right"&gt;14.5 s, 5,896 page splits&lt;/td&gt;
 &lt;td style="text-align: right"&gt;65.6 s, 65,232 page splits&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Next 1,000,000 inserts&lt;/td&gt;
 &lt;td style="text-align: right"&gt;34.5 s, 12,393 page splits&lt;/td&gt;
 &lt;td style="text-align: right"&gt;105.7 s, 24,424 page splits&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Clustered index after both&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,167 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,601 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;After &lt;code&gt;OPTIMIZE TABLE&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,337 MB, in 39 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The first batch was the worst, because the table had just been loaded in sorted order and every page was nearly full, so almost every new row split a page. Once the pages were half empty there was room, and the second batch split far fewer, but it was still three times slower than appending at the end. The table also more than doubled in size, since all those split pages were half empty. &lt;code&gt;OPTIMIZE TABLE&lt;/code&gt; rebuilds the table packed again. For InnoDB it runs as online DDL, and the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/optimize-table.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; says &amp;ldquo;an exclusive table lock is only taken briefly during the prepare phase and the commit phase&amp;rdquo;, so reads and writes keep going while it works.&lt;/p&gt;
&lt;p&gt;A rebuild can also leave room for the rows that will arrive later. &lt;code&gt;innodb_fill_factor&lt;/code&gt; sets how full InnoDB packs each page when it builds or rebuilds an index in sorted order, and the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-parameters.html#sysvar_innodb_fill_factor" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; notes that even the default of 100 &amp;ldquo;leaves 1/16 of the space in clustered index pages free for future index growth.&amp;rdquo; I rebuilt the client-clustered table at three settings and inserted the same 500,000 assets into each:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GLOBAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;innodb_fill_factor&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;70&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FORCE&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- OPTIMIZE TABLE rebuilds the same way
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GLOBAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;innodb_fill_factor&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Client-clustered table&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Size before&lt;/th&gt;
 &lt;th style="text-align: right"&gt;500,000 inserts&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Page splits&lt;/th&gt;
 &lt;th style="text-align: right"&gt;Size after&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Loaded in sorted order, as above&lt;/td&gt;
 &lt;td style="text-align: right"&gt;900 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;58.0 s&lt;/td&gt;
 &lt;td style="text-align: right"&gt;65,232&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,184 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rebuilt, &lt;code&gt;innodb_fill_factor = 100&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,028 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;42.8 s&lt;/td&gt;
 &lt;td style="text-align: right"&gt;65,057&lt;/td&gt;
 &lt;td style="text-align: right"&gt;2,181 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rebuilt, &lt;code&gt;innodb_fill_factor = 80&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,210 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;33.9 s&lt;/td&gt;
 &lt;td style="text-align: right"&gt;3,752&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,267 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rebuilt, &lt;code&gt;innodb_fill_factor = 70&lt;/code&gt;&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,378 MB&lt;/td&gt;
 &lt;td style="text-align: right"&gt;31.8 s&lt;/td&gt;
 &lt;td style="text-align: right"&gt;547&lt;/td&gt;
 &lt;td style="text-align: right"&gt;1,378 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;At 70 the new assets fit into the room the rebuild left, and the table stayed the size it started. The client lookup barely noticed the emptier pages: 1.6 to 1.9 pages read from disk, against 1.6 when packed. The space is paid up front instead of after the splits, and it only lasts as long as the room does. These inserts added 10 percent more rows into 30 percent of free space, so a table that keeps growing needs the rebuild repeated before the room runs out. &lt;code&gt;innodb_fill_factor&lt;/code&gt; is a global setting that applies to every sorted index build on the server, which is why the example sets it back afterwards. (These runs came from a fresh container, so the packed table&amp;rsquo;s 58.0 s is a little faster than the 65.6 s above. The page splits and sizes matched exactly.)&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Cluster on what you read together, not on what is random&lt;/strong&gt;
 &lt;div&gt;Grouping by client works because a client&amp;rsquo;s assets are read together. A clustered key with no useful order, such as a random UUID, gets all of the insert cost here and none of the read benefit: every new row lands on a random page and splits it, and nothing is ever read in that order.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="postgresql-sort-it-once-or-copy-the-columns-into-an-index"&gt;PostgreSQL: sort it once, or copy the columns into an index
&lt;/h2&gt;&lt;p&gt;PostgreSQL has no clustered index and no way to declare one. Its table is a heap, where a new row goes wherever there is free space, and every index, the primary key included, stores the row&amp;rsquo;s &lt;code&gt;ctid&lt;/code&gt;: a 6-byte address made of the page number and the position on that page. That is the address the &lt;code&gt;client_id&lt;/code&gt; index handed back 50 times in the plan above. PostgreSQL offers two ways to get close to the client-clustered layout, and neither one is a clustered index.&lt;/p&gt;
&lt;p&gt;The first is the &lt;code&gt;CLUSTER&lt;/code&gt; command, which rewrites the table sorted by an index:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CLUSTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;USING&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets_client_id_idx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;It took 23.5 seconds on 5 million rows, and afterwards one client&amp;rsquo;s assets came back in 3.1 pages from disk and 1.02 ms under the disk limit, close to MySQL&amp;rsquo;s client-clustered table. The &lt;a class="link" href="https://www.postgresql.org/docs/18/sql-cluster.html" target="_blank" rel="noopener"
 &gt;PostgreSQL documentation&lt;/a&gt; is clear about what it is: &amp;ldquo;Clustering is a one-time operation: when the table is subsequently updated, the changes are not clustered.&amp;rdquo; New rows still go wherever the heap has room, usually the end. While it runs, &lt;code&gt;CLUSTER&lt;/code&gt; holds an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; lock, which &amp;ldquo;prevents any other database operations (both reads and writes) from operating on the table until the CLUSTER is finished.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;&lt;img alt="Line chart: pages read per client lookup after CLUSTER rose from 3.1 right after, to 4.7 after 10% more rows, to 14.8 after 30% more; MySQL clustered on client stayed at 1.6, 2.2 and 2.4." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/cluster-decay.svg"&gt;&lt;/p&gt;
&lt;p&gt;After I added 10 percent more assets, the clustered PostgreSQL table read 4.7 pages per client, and after 30 percent, 14.8 pages and 5.22 ms under the disk limit. The same inserts left MySQL&amp;rsquo;s client-clustered table at 2.4 pages, since InnoDB put each new asset on its client&amp;rsquo;s page. That is the trade from the previous section showing up from the other side: InnoDB pays on every insert to keep the order, and PostgreSQL pays nothing on insert and loses the order.&lt;/p&gt;
&lt;p&gt;The second option is a covering index, an index that carries the columns the query needs so that the table is never read:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets_client_cov&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;assets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INCLUDE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asset_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;asset_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Only Scan using assets_orig_cov on assets_orig (cost=0.56..5.45 rows=51 width=47) (actual time=0.049..0.061 rows=50.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (client_id = 621)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Fetches: 0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=4 read=4
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;Index Only Scan&lt;/code&gt; with &lt;code&gt;Heap Fetches: 0&lt;/code&gt; means the answer came entirely from the index, whose entries are sorted by &lt;code&gt;client_id&lt;/code&gt;, so a client&amp;rsquo;s 50 entries sit together. It read 1.7 pages from disk and took 0.60 ms, the same as MySQL&amp;rsquo;s clustered table, and since an index is kept in order on every insert, it does not wear off the way &lt;code&gt;CLUSTER&lt;/code&gt; does. It cost a 398 MB index in place of the 34 MB plain one, and it only helps queries that ask for the included columns. &lt;code&gt;Heap Fetches&lt;/code&gt; also rises when rows change until &lt;code&gt;VACUUM&lt;/code&gt; catches up, which &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;One Column Added to a SELECT&lt;/a&gt; measures.&lt;/p&gt;
&lt;h2 id="how-to-choose-the-clustered-key"&gt;How to choose the clustered key
&lt;/h2&gt;&lt;p&gt;The whole comparison in one table, on the clients-and-assets schema used throughout, where each client owns about 50 assets:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;MySQL, clustered on &lt;code&gt;asset_id&lt;/code&gt;&lt;/th&gt;
 &lt;th&gt;MySQL, clustered on &lt;code&gt;(client_id, asset_id)&lt;/code&gt;&lt;/th&gt;
 &lt;th&gt;PostgreSQL heap&lt;/th&gt;
 &lt;th&gt;PostgreSQL after &lt;code&gt;CLUSTER&lt;/code&gt;&lt;/th&gt;
 &lt;th&gt;PostgreSQL covering index&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;One client&amp;rsquo;s assets, disk limited to 3,000 reads/s&lt;/td&gt;
 &lt;td&gt;15.0 ms, 45 pages&lt;/td&gt;
 &lt;td&gt;0.53 ms, 1.7 pages&lt;/td&gt;
 &lt;td&gt;14.8 ms, 46 pages&lt;/td&gt;
 &lt;td&gt;1.02 ms, 3.1 pages&lt;/td&gt;
 &lt;td&gt;0.60 ms, 1.7 pages&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Same, after 30% more rows arrived&lt;/td&gt;
 &lt;td&gt;20.4 ms&lt;/td&gt;
 &lt;td&gt;1.07 ms&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;td&gt;5.22 ms&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;One asset by &lt;code&gt;asset_id&lt;/code&gt;, pages touched&lt;/td&gt;
 &lt;td&gt;4.0&lt;/td&gt;
 &lt;td&gt;8.4&lt;/td&gt;
 &lt;td&gt;4.0&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Inserting the next 1M assets&lt;/td&gt;
 &lt;td&gt;34.5 s&lt;/td&gt;
 &lt;td&gt;105.7 s&lt;/td&gt;
 &lt;td&gt;not compared&lt;/td&gt;
 &lt;td&gt;not compared&lt;/td&gt;
 &lt;td&gt;not compared&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Space it costs&lt;/td&gt;
 &lt;td&gt;baseline&lt;/td&gt;
 &lt;td&gt;2.2x the default table after inserts&lt;/td&gt;
 &lt;td&gt;baseline&lt;/td&gt;
 &lt;td&gt;none&lt;/td&gt;
 &lt;td&gt;a 398 MB index instead of 34 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rows stay in client order&lt;/td&gt;
 &lt;td&gt;no&lt;/td&gt;
 &lt;td&gt;always&lt;/td&gt;
 &lt;td&gt;no&lt;/td&gt;
 &lt;td&gt;only until new rows arrive&lt;/td&gt;
 &lt;td&gt;the index always does&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;PostgreSQL&amp;rsquo;s insert times are left out, because two engines inserting through different code paths is not a fair race. The comparison that matters there is MySQL against itself, with only the primary key changed.&lt;/p&gt;
&lt;p&gt;In MySQL, the primary key is the most important index decision on a table, because it is also the table&amp;rsquo;s physical order and part of every other index. An auto-increment id is the right default when rows are mostly written once and read one at a time, or in the order they arrived. A composite key that leads with the owner, such as &lt;code&gt;(client_id, asset_id)&lt;/code&gt; or &lt;code&gt;(tenant_id, order_id)&lt;/code&gt;, pays off when the application nearly always reads a parent&amp;rsquo;s children together and the table does not fit in memory, and it costs slower inserts, a bigger table between rebuilds, and slightly bigger secondary indexes. Rebuilding with &lt;code&gt;innodb_fill_factor&lt;/code&gt; below 100 trades some of that size up front for far fewer page splits. Measure the read you care about in pages, not milliseconds on a warm laptop.&lt;/p&gt;
&lt;p&gt;In PostgreSQL there is no such choice to make, and the table stays in arrival order. If one access pattern dominates, a covering index gives the clustered read without the decay, at the price of the index&amp;rsquo;s size. &lt;code&gt;CLUSTER&lt;/code&gt; is the one-off option for a table that is mostly read and can be locked for the rewrite.&lt;/p&gt;</description></item><item><title>pgvector vs a Dedicated Vector Database: Memory, Filters, and Index Builds</title><link>https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/</link><pubDate>Fri, 06 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post pgvector vs a Dedicated Vector Database: Memory, Filters, and Index Builds" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;pgvector is the right default for embeddings that belong to Postgres rows, until one of three limits shows up in measurements: the HNSW index outgrows the memory it gets, filtered queries lose recall or latency, or index builds start competing with the workload. A dedicated vector database like Qdrant handled filtered search far better in my tests. Under the same memory cap it fell off the same cliff until it was configured for quantization, and it adds a second system to keep in sync.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;An embedding is a list of numbers, 768 of them in this post, that a model produces for a piece of text. Semantic search means finding the stored embeddings closest to the one for a query, and doing that exactly means comparing the query against every row. Both systems here avoid that with an approximate index called HNSW: a graph that links each vector to a handful of its near neighbors, which a query walks from an entry point toward its target while keeping a short list of the best candidates found so far. The length of that list is the search-effort setting, &lt;code&gt;hnsw.ef_search&lt;/code&gt; in pgvector and &lt;code&gt;hnsw_ef&lt;/code&gt; in Qdrant. A longer list finds more of the true nearest rows and takes longer. The share it finds is recall, so a recall of 0.958 means about nine and a half of the true ten came back.&lt;/p&gt;
&lt;p&gt;The choice is where that index lives. pgvector is a Postgres extension that adds a &lt;code&gt;vector&lt;/code&gt; column type and HNSW indexes, so the embeddings sit in the same table as the rows they describe and a search is an &lt;code&gt;ORDER BY&lt;/code&gt; in SQL. A dedicated vector database (Qdrant, Pinecone, Milvus, Weaviate) is a separate service built for this one kind of search. Choosing it buys an engine tuned for the job, and costs a second system that has to receive a copy of every embedding and every filter value. This post loads the same 500,000 embeddings into pgvector and into Qdrant and runs both through the same tests.&lt;/p&gt;
&lt;p&gt;Here are the results first, and how they were measured after. Latencies are medians, and the last two rows are reasoned rather than measured.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Question&lt;/th&gt;
 &lt;th&gt;pgvector&lt;/th&gt;
 &lt;th&gt;Qdrant&lt;/th&gt;
 &lt;th&gt;Edge&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Plain top-10 at similar recall&lt;/td&gt;
 &lt;td&gt;0.958 at 2.82 ms&lt;/td&gt;
 &lt;td&gt;0.940 at 2.31 ms&lt;/td&gt;
 &lt;td&gt;Close&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Filter on a few known values&lt;/td&gt;
 &lt;td&gt;0.960 at 0.71 ms, partial index&lt;/td&gt;
 &lt;td&gt;1.0 at 2.52 ms&lt;/td&gt;
 &lt;td&gt;pgvector on speed, Qdrant on recall&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Filter nobody can enumerate&lt;/td&gt;
 &lt;td&gt;0.867 at 19.6 ms&lt;/td&gt;
 &lt;td&gt;1.0 at 2.52 ms&lt;/td&gt;
 &lt;td&gt;Qdrant&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index outgrows memory, default config&lt;/td&gt;
 &lt;td&gt;209 ms&lt;/td&gt;
 &lt;td&gt;1,296 ms&lt;/td&gt;
 &lt;td&gt;pgvector&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index outgrows memory, compressed&lt;/td&gt;
 &lt;td&gt;73.7 ms at 0.906&lt;/td&gt;
 &lt;td&gt;4.26 ms at 0.935&lt;/td&gt;
 &lt;td&gt;Qdrant, by far less at p99&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rebuild on a live table&lt;/td&gt;
 &lt;td&gt;196 s, writes keep landing&lt;/td&gt;
 &lt;td&gt;79 to 388 s in the background, behavior during it untested&lt;/td&gt;
 &lt;td&gt;Unsettled&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Deleted row leaves search results&lt;/td&gt;
 &lt;td&gt;At commit&lt;/td&gt;
 &lt;td&gt;When the sync pipeline catches up&lt;/td&gt;
 &lt;td&gt;pgvector&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Restore to one point in time&lt;/td&gt;
 &lt;td&gt;One restore&lt;/td&gt;
 &lt;td&gt;Two restores or a full re-sync&lt;/td&gt;
 &lt;td&gt;pgvector&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Here is one nearest-neighbor query run twice against the same 1,953 MB HNSW index, on PostgreSQL 18.6 with pgvector 0.8.7. The plan is identical and both runs touch 1,198 buffers. Output is trimmed to the lines that differ.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- index fits in shared_buffers (2,560 MB)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Limit (actual time=1.853..1.898 rows=10.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=1198
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Scan using items_hnsw on items (actual time=1.852..1.898 rows=10.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 1.903 ms
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- container capped at 1 GB, shared_buffers 256 MB, disk capped at 3,000 read IOPS
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Limit (actual time=296.405..297.841 rows=10.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=356 read=842
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; I/O Timings: shared read=294.552
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index Scan using items_hnsw on items (actual time=296.402..297.833 rows=10.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 297.885 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Nothing about the query changed. In the second run 842 of the pages the graph walk needed were not in memory, and each one cost a read from a disk throttled to the gp3 baseline. Waiting for those reads took 294 of the 298 milliseconds. The &lt;a class="link" href="https://explainanalyze.com/p/hidden-database-costs-of-an-ai-rollout-storage-cpu-memory-and-cache/" &gt;earlier post on the hidden costs of an AI rollout&lt;/a&gt; covers storage growth, halfvec, and buffer-cache pollution on a shared OLTP box, so none of that is repeated here.&lt;/p&gt;
&lt;p&gt;The fixture is 500,000 real embeddings: 768-dimensional InstructorXL vectors of arXiv paper titles, the first ten parquet files of Qdrant&amp;rsquo;s public &lt;a class="link" href="https://huggingface.co/datasets/Qdrant/arxiv-titles-instructorxl-embeddings" target="_blank" rel="noopener"
 &gt;arxiv-titles-instructorxl-embeddings&lt;/a&gt; dataset. The arXiv identifier encodes the submission year, which gives a real metadata column to filter on. Research topics shift over the decades, so it is correlated with the vectors rather than random. The 1,000 query vectors come from an eleventh file, so none of them is in the table, and recall@10 is scored against an exact search over the same 500,000 rows in numpy. Both systems got HNSW with &lt;code&gt;m = 16&lt;/code&gt; and &lt;code&gt;ef_construction = 64&lt;/code&gt; on cosine distance, with 4 CPUs and a 3.5 GB memory limit in Docker. Latency is measured at the client, one connection, 1,000 queries after a 200-query warm-up on different vectors. Qdrant is 1.20.0, queried over gRPC.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;What half a million vectors can show&lt;/strong&gt;
 &lt;div&gt;This ran on a laptop whose Docker VM has 5 CPUs and 4.9 GB of RAM, which is what capped the fixture at 500,000 vectors. Each limit below shows up at this scale, but the absolute numbers belong to this box, and nothing here exercises what a billion vectors brings (sharding, rebuilds measured in days).&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;On unfiltered queries the two systems are close.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Search effort&lt;/th&gt;
 &lt;th&gt;pgvector recall&lt;/th&gt;
 &lt;th&gt;pgvector p50 / p99&lt;/th&gt;
 &lt;th&gt;Qdrant recall&lt;/th&gt;
 &lt;th&gt;Qdrant p50 / p99&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;40&lt;/td&gt;
 &lt;td&gt;0.908&lt;/td&gt;
 &lt;td&gt;2.18 / 3.65 ms&lt;/td&gt;
 &lt;td&gt;0.940&lt;/td&gt;
 &lt;td&gt;2.31 / 3.40 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;100&lt;/td&gt;
 &lt;td&gt;0.958&lt;/td&gt;
 &lt;td&gt;2.82 / 4.33 ms&lt;/td&gt;
 &lt;td&gt;0.982&lt;/td&gt;
 &lt;td&gt;3.07 / 4.22 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;200&lt;/td&gt;
 &lt;td&gt;0.977&lt;/td&gt;
 &lt;td&gt;4.91 / 7.11 ms&lt;/td&gt;
 &lt;td&gt;0.993&lt;/td&gt;
 &lt;td&gt;4.94 / 6.83 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img alt="Line chart of recall against median latency at three search-effort settings: pgvector climbs from 0.908 at 2.18 ms to 0.977 at 4.91 ms, Qdrant from 0.940 at 2.31 ms to 0.993 at 4.94 ms, and the two curves stay close, with Qdrant slightly ahead" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/unfiltered-recall-latency.svg"&gt;&lt;/p&gt;
&lt;p&gt;The same search-effort number is not the same amount of work in the two systems. Qdrant split the collection into three segments with a graph each and searches all three, so its 40 explores more candidates than pgvector&amp;rsquo;s 40. That is why the first row reads 0.940 against 0.908. Compared at matched recall instead, a dedicated engine buys a millisecond or two of median latency on plain top-10 search.&lt;/p&gt;
&lt;h2 id="filtered-search-is-where-the-gap-opens"&gt;Filtered search is where the gap opens
&lt;/h2&gt;&lt;p&gt;pgvector applies a &lt;code&gt;WHERE&lt;/code&gt; clause after the index scan, not during it. The &lt;a class="link" href="https://github.com/pgvector/pgvector" target="_blank" rel="noopener"
 &gt;README&lt;/a&gt; says so directly: with the default &lt;code&gt;hnsw.ef_search&lt;/code&gt; of 40 and a condition that matches 10% of rows, &amp;ldquo;only 4 rows will match on average.&amp;rdquo; The scan produces at most 40 candidates, the filter throws most of them away, and the &lt;code&gt;LIMIT 10&lt;/code&gt; is satisfied by whatever survives.&lt;/p&gt;
&lt;p&gt;On this fixture &lt;code&gt;year = 1999&lt;/code&gt; matches 5,863 rows (1.2%). With pgvector&amp;rsquo;s defaults, recall@10 was 0.053 and every one of the 1,000 queries returned fewer than ten rows. Nothing errors and nothing warns. Alex Jacobs&amp;rsquo; &lt;a class="link" href="https://alex-jacobs.com/posts/the-case-against-pgvector/" target="_blank" rel="noopener"
 &gt;The Case Against pgvector&lt;/a&gt; (October 2025, &lt;a class="link" href="https://news.ycombinator.com/item?id=45798479" target="_blank" rel="noopener"
 &gt;381 points on Hacker News&lt;/a&gt;) described this as asking for ten results and getting three; the tables below show what that looks like across a thousand queries.&lt;/p&gt;
&lt;p&gt;The obvious repair is a B-tree on &lt;code&gt;year&lt;/code&gt;. I added one and ran &lt;code&gt;ANALYZE&lt;/code&gt;, expecting the planner to use it for a 1.2% filter, and it kept the HNSW plan and the 0.053 recall. Raising &lt;code&gt;ef_search&lt;/code&gt; flipped it (60 was already enough, with iterative scans still off). The planner switched to a Bitmap Heap Scan on the B-tree plus a sort, which is an exact search: recall 1.0 at 18.0 ms. That flip comes from the cost-estimation change in &lt;a class="link" href="https://www.postgresql.org/about/news/pgvector-080-released-2952/" target="_blank" rel="noopener"
 &gt;pgvector 0.8.0&lt;/a&gt; (November 2024), and it means the plan choice is made by a cost estimate in which recall plays no part. At &lt;code&gt;ef_search = 40&lt;/code&gt; the cheapest-looking plan was the one that returned 5% of the right answer.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Defaults return short results without an error&lt;/strong&gt;
 &lt;div&gt;With &lt;code&gt;hnsw.iterative_scan&lt;/code&gt; off, which is the default, a filtered pgvector query can return fewer rows than its &lt;code&gt;LIMIT&lt;/code&gt; and nothing in the result says so. Turn on iterative scans for filtered queries, and count rows against the limit in the application, because a short result is the only visible symptom.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Iterative scans, also new in 0.8.0, keep walking the graph until enough rows pass the filter or &lt;code&gt;hnsw.max_scan_tuples&lt;/code&gt; (default 20,000) is reached. Here is everything I tried on the 1.2% filter:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Strategy for &lt;code&gt;year = 1999&lt;/code&gt;&lt;/th&gt;
 &lt;th&gt;Recall@10&lt;/th&gt;
 &lt;th&gt;p50&lt;/th&gt;
 &lt;th&gt;p99&lt;/th&gt;
 &lt;th&gt;Queries short of 10 rows&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector defaults&lt;/td&gt;
 &lt;td&gt;0.053&lt;/td&gt;
 &lt;td&gt;2.88 ms&lt;/td&gt;
 &lt;td&gt;7.05 ms&lt;/td&gt;
 &lt;td&gt;1,000&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;B-tree, plan flipped to exact search&lt;/td&gt;
 &lt;td&gt;1.0&lt;/td&gt;
 &lt;td&gt;18.0 ms&lt;/td&gt;
 &lt;td&gt;21.2 ms&lt;/td&gt;
 &lt;td&gt;0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;strict_order&lt;/code&gt; iterative scan&lt;/td&gt;
 &lt;td&gt;0.795&lt;/td&gt;
 &lt;td&gt;22.3 ms&lt;/td&gt;
 &lt;td&gt;36.4 ms&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;relaxed_order&lt;/code&gt; iterative scan&lt;/td&gt;
 &lt;td&gt;0.867&lt;/td&gt;
 &lt;td&gt;19.6 ms&lt;/td&gt;
 &lt;td&gt;36.3 ms&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Partial HNSW index&lt;/td&gt;
 &lt;td&gt;0.960&lt;/td&gt;
 &lt;td&gt;0.71 ms&lt;/td&gt;
 &lt;td&gt;0.91 ms&lt;/td&gt;
 &lt;td&gt;0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant with a payload index&lt;/td&gt;
 &lt;td&gt;1.0&lt;/td&gt;
 &lt;td&gt;2.52 ms&lt;/td&gt;
 &lt;td&gt;3.75 ms&lt;/td&gt;
 &lt;td&gt;0&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;strict_order&lt;/code&gt; ran before the B-tree existed; &lt;code&gt;relaxed_order&lt;/code&gt; with and without it came in within 2 ms of each other. Raising &lt;code&gt;max_scan_tuples&lt;/code&gt; to 100,000 moved recall by a thousandth, so on this filter the graph itself sets the ceiling. Across selectivities, the gap closes as the filter loosens:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Filter (rows matched)&lt;/th&gt;
 &lt;th&gt;pgvector default&lt;/th&gt;
 &lt;th&gt;pgvector &lt;code&gt;relaxed_order&lt;/code&gt;&lt;/th&gt;
 &lt;th&gt;Exact via B-tree&lt;/th&gt;
 &lt;th&gt;Qdrant 1.20&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;year = 1999&lt;/code&gt; (1.2%)&lt;/td&gt;
 &lt;td&gt;0.053, 2.9 ms&lt;/td&gt;
 &lt;td&gt;0.867, 19.6 ms&lt;/td&gt;
 &lt;td&gt;1.0, 18.0 ms&lt;/td&gt;
 &lt;td&gt;1.0, 2.52 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;2008–2010&lt;/code&gt; (8.6%)&lt;/td&gt;
 &lt;td&gt;0.345, 2.0 ms&lt;/td&gt;
 &lt;td&gt;0.902, 4.1 ms&lt;/td&gt;
 &lt;td&gt;1.0, 97 ms&lt;/td&gt;
 &lt;td&gt;0.968, 2.18 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;year &amp;gt;= 2015&lt;/code&gt; (55.6%)&lt;/td&gt;
 &lt;td&gt;0.868, 2.1 ms&lt;/td&gt;
 &lt;td&gt;0.883, 1.6 ms&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;td&gt;0.931, 2.42 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Each cell is recall@10 and median latency, with search effort at 40. The medians hide the tail: &lt;code&gt;relaxed_order&lt;/code&gt; reached a 36 ms p99 on the 1.2% filter and 28 ms on the 8.6% one, while Qdrant stayed under 4 ms on all three. At an effort of 100 on the 55.6% filter, pgvector reached 0.945 at 2.74 ms and Qdrant 0.981 at 3.16 ms.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Grouped bars of recall on three year filters: on the 1.2% filter pgvector’s default scores 0.053 with all 1,000 queries short, relaxed_order 0.867 and Qdrant 1.000; on the 8.6% filter 0.345, 0.902 and 0.968; on the 55.6% filter 0.868, 0.883 and 0.931" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/filtered-recall.svg"&gt;&lt;/p&gt;
&lt;p&gt;Partial indexes are the README&amp;rsquo;s answer when a filter has a few known values, and the partial-index row shows they work, built in under a second at 23 MB. The catch is one index per value. That covers a status flag or a handful of large tenants, and it stops covering anything once filters are combinations (tenant and date range and document permission) that nobody can enumerate ahead of time.&lt;/p&gt;
&lt;p&gt;Qdrant handled all three filters at roughly unfiltered latency because it plans per segment with the filter&amp;rsquo;s cardinality in hand. Its &lt;a class="link" href="https://qdrant.tech/documentation/search/search/" target="_blank" rel="noopener"
 &gt;query planner&lt;/a&gt; uses the payload index to estimate how many points match, scans small sets directly, and searches the graph with filter-aware extra edges when the set is large. The &lt;a class="link" href="https://qdrant.tech/documentation/concepts/indexing/" target="_blank" rel="noopener"
 &gt;indexing docs&lt;/a&gt; also say the extra edges only exist when the payload index is created before the HNSW graph, so adding a new filter field later means rebuilding.&lt;/p&gt;
&lt;h2 id="the-memory-cliff-is-not-a-pgvector-problem"&gt;The memory cliff is not a pgvector problem
&lt;/h2&gt;&lt;p&gt;The opening plans are the endpoints of a ladder: one pgvector index, one query, less memory at each step.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Setup&lt;/th&gt;
 &lt;th&gt;p50&lt;/th&gt;
 &lt;th&gt;p95&lt;/th&gt;
 &lt;th&gt;p99&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Index in &lt;code&gt;shared_buffers&lt;/code&gt;, 3.5 GB container&lt;/td&gt;
 &lt;td&gt;2.18 ms&lt;/td&gt;
 &lt;td&gt;3.02 ms&lt;/td&gt;
 &lt;td&gt;3.65 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;shared_buffers&lt;/code&gt; 256 MB, index in OS page cache&lt;/td&gt;
 &lt;td&gt;3.42 ms&lt;/td&gt;
 &lt;td&gt;4.56 ms&lt;/td&gt;
 &lt;td&gt;5.31 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Container capped at 1 GB&lt;/td&gt;
 &lt;td&gt;6.01 ms&lt;/td&gt;
 &lt;td&gt;8.06 ms&lt;/td&gt;
 &lt;td&gt;9.45 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;1 GB and 3,000 read IOPS&lt;/td&gt;
 &lt;td&gt;209 ms&lt;/td&gt;
 &lt;td&gt;395 ms&lt;/td&gt;
 &lt;td&gt;400 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Control: 3.5 GB, 3,000 read IOPS, index resident&lt;/td&gt;
 &lt;td&gt;2.02 ms&lt;/td&gt;
 &lt;td&gt;3.64 ms&lt;/td&gt;
 &lt;td&gt;44.3 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img alt="Horizontal bars of pgvector median latency: 2.18 ms with the index in shared_buffers, 3.42 ms in the OS page cache, 6.01 ms capped at 1 GB, then 209 ms once reads are capped at 3,000 IOPS, against a control of 2.02 ms with the same IOPS cap and the index resident" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/memory-ladder.svg"&gt;&lt;/p&gt;
&lt;p&gt;The third row looked far too good, and I believed it for one full run before the per-query plans showed why: 687 to 925 page reads at 10 to 15 microseconds each. Docker Desktop&amp;rsquo;s VM disk is a file on the Mac, and the Mac&amp;rsquo;s own page cache was serving those &amp;ldquo;disk&amp;rdquo; reads from RAM. To give a read a real cost, I capped the volume at 3,000 read IOPS through the container&amp;rsquo;s cgroup, which is the gp3 baseline. The control row isolates the cap: with the index resident the median did not move, though the p99 went from 3.65 ms to 44 ms.&lt;/p&gt;
&lt;p&gt;Qdrant with its default configuration, full-precision vectors held in memory, hit the same wall harder, at about six times pgvector&amp;rsquo;s median under the same constraint. I did not dig into why. The claim that a dedicated engine has no memory cliff did not survive this test. It has one wherever its working set stops fitting.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Under 1 GB and 3,000 read IOPS&lt;/th&gt;
 &lt;th&gt;p50&lt;/th&gt;
 &lt;th&gt;p95&lt;/th&gt;
 &lt;th&gt;p99&lt;/th&gt;
 &lt;th&gt;Recall@10&lt;/th&gt;
 &lt;th&gt;p50 with memory to spare&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant, default config&lt;/td&gt;
 &lt;td&gt;1,296 ms&lt;/td&gt;
 &lt;td&gt;1,608 ms&lt;/td&gt;
 &lt;td&gt;1,800 ms&lt;/td&gt;
 &lt;td&gt;0.946&lt;/td&gt;
 &lt;td&gt;2.31 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector HNSW&lt;/td&gt;
 &lt;td&gt;209 ms&lt;/td&gt;
 &lt;td&gt;395 ms&lt;/td&gt;
 &lt;td&gt;400 ms&lt;/td&gt;
 &lt;td&gt;0.906&lt;/td&gt;
 &lt;td&gt;2.18 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector binary index, 200-candidate rerank&lt;/td&gt;
 &lt;td&gt;73.7 ms&lt;/td&gt;
 &lt;td&gt;97.5 ms&lt;/td&gt;
 &lt;td&gt;106 ms&lt;/td&gt;
 &lt;td&gt;0.906&lt;/td&gt;
 &lt;td&gt;4.42 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant int8, rescoring on&lt;/td&gt;
 &lt;td&gt;4.26 ms&lt;/td&gt;
 &lt;td&gt;67.9 ms&lt;/td&gt;
 &lt;td&gt;79.3 ms&lt;/td&gt;
 &lt;td&gt;0.935&lt;/td&gt;
 &lt;td&gt;not run&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant int8, no rescoring&lt;/td&gt;
 &lt;td&gt;0.74 ms&lt;/td&gt;
 &lt;td&gt;1.27 ms&lt;/td&gt;
 &lt;td&gt;1.64 ms&lt;/td&gt;
 &lt;td&gt;0.915&lt;/td&gt;
 &lt;td&gt;0.63 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The Qdrant default row is 300 queries instead of 1,000, because each one took over a second, and that smaller sample is why its recall reads 0.946 rather than 0.940. pgvector&amp;rsquo;s 0.906 against the earlier 0.908 comes from the index being rebuilt between runs.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Dot-and-range chart on a log scale under 1 GB and 3,000 IOPS: Qdrant default at 1,296 ms, pgvector HNSW at 209 ms, pgvector binary index at 73.7 ms, Qdrant int8 with rescoring at 4.26 ms with a p99 of 79 ms, and Qdrant int8 without rescoring at 0.74 ms" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/under-the-memory-cap.svg"&gt;&lt;/p&gt;
&lt;p&gt;Where the dedicated engine pulls ahead is the configuration that avoids the cliff. A second Qdrant collection with &lt;a class="link" href="https://qdrant.tech/documentation/guides/quantization/" target="_blank" rel="noopener"
 &gt;scalar quantization&lt;/a&gt; keeps int8 copies in RAM and the originals on disk. Qdrant does not rescore 8-bit quantization by default, so the last row never read the originals. Rescoring with 2x oversampling bought back recall and cost a 79 ms p99, because those reads now hit the throttled disk. pgvector has no int8 vector type. Its nearest tool is a binary-quantized expression index with a full-precision rerank in SQL. Binary codes lose more than int8 on this model (0.703 recall from 40 candidates, 0.838 from 100), so it took 200 candidates to reach 0.906. Under the cap, each of those candidates is a full vector fetched from TOAST on the throttled disk.&lt;/p&gt;
&lt;p&gt;So both systems get past the cliff the same way, by keeping a compressed copy in memory and touching the full vectors as little as possible. On this fixture Qdrant did it about 17 times faster at the median for slightly better recall. The tail is far closer, 79 ms against 106 ms at p99, because both end up waiting on the same throttled disk. Qdrant offers the technique as two collection settings. pgvector makes it a query pattern and an extra index you maintain, built on a coarser code. The dedicated engine has one more advantage that no benchmark here captures: it is the only tenant of its memory, while pgvector&amp;rsquo;s index shares &lt;code&gt;shared_buffers&lt;/code&gt; with every other query on the primary.&lt;/p&gt;
&lt;p&gt;That sharing is also the build-time problem. My first attempt at the build test ran with &lt;code&gt;shared_buffers&lt;/code&gt; at 2,560 MB so the index would stay resident, and the OOM killer took it out twice. A parallel HNSW build with &lt;code&gt;maintenance_work_mem = 2GB&lt;/code&gt; and a buffer pool sized to hold the finished index do not both fit in 3.5 GB.&lt;/p&gt;
&lt;h2 id="index-builds-block-only-if-you-let-them"&gt;Index builds block only if you let them
&lt;/h2&gt;&lt;p&gt;A plain &lt;code&gt;CREATE INDEX&lt;/code&gt; on the 500,000 rows took 167.3 s with three parallel workers and produced the 1,953 MB index. Then I ran both forms with a writer inserting one row every 100 ms:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Build with a live writer&lt;/th&gt;
 &lt;th&gt;Build time&lt;/th&gt;
 &lt;th&gt;Inserts landed&lt;/th&gt;
 &lt;th&gt;Insert p50&lt;/th&gt;
 &lt;th&gt;Insert p99&lt;/th&gt;
 &lt;th&gt;Longest insert&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;CREATE INDEX&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;175.6 s&lt;/td&gt;
 &lt;td&gt;82&lt;/td&gt;
 &lt;td&gt;9.11 ms&lt;/td&gt;
 &lt;td&gt;33.4 s&lt;/td&gt;
 &lt;td&gt;175.5 s&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;196.2 s&lt;/td&gt;
 &lt;td&gt;1,808&lt;/td&gt;
 &lt;td&gt;3.26 ms&lt;/td&gt;
 &lt;td&gt;72.5 ms&lt;/td&gt;
 &lt;td&gt;723 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img alt="Three small bar panels comparing a plain and a concurrent HNSW build under a live writer: build time 175.6 s against 196.2 s, inserts landed 82 against 1,808, and longest single insert 175.5 s against 0.72 s" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/pgvector-vs-a-dedicated-vector-database-memory-filters-and-index-builds/index-build-writes.svg"&gt;&lt;/p&gt;
&lt;p&gt;This is the measurement that pushes back hardest on the thesis. Blocking is opt-out, the README says to build concurrently in production, and a team that reads it will never see the 175-second stall. What stays true at scale is duration. The build is a full pass over every vector on the primary, and its time grows with the corpus. An embedding-model change forces it again on a corpus that has kept growing since the last time. A concurrent build that fails partway leaves an &lt;a class="link" href="https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY" target="_blank" rel="noopener"
 &gt;&lt;code&gt;INVALID&lt;/code&gt; index&lt;/a&gt; behind that has to be dropped or reindexed before it is any use. That is ordinary Postgres behavior, and it hurts more when a retry costs hours.&lt;/p&gt;
&lt;p&gt;Qdrant moves the build off the write path. The upload with indexing deferred took about 24 s (the Postgres &lt;code&gt;COPY&lt;/code&gt; of the same rows took 84 s), and the optimizer then built the graphs in the background:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;What got built&lt;/th&gt;
 &lt;th&gt;Time&lt;/th&gt;
 &lt;th&gt;Size on disk&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector HNSW&lt;/td&gt;
 &lt;td&gt;167.3 s&lt;/td&gt;
 &lt;td&gt;1,953 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector binary expression index&lt;/td&gt;
 &lt;td&gt;37.3 s&lt;/td&gt;
 &lt;td&gt;190 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;pgvector partial index, &lt;code&gt;year = 1999&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;0.89 s&lt;/td&gt;
 &lt;td&gt;23 MB&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant graphs, no payload index&lt;/td&gt;
 &lt;td&gt;152 s after upload&lt;/td&gt;
 &lt;td&gt;not measured&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant graphs with payload index on &lt;code&gt;year&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;388 s after upload&lt;/td&gt;
 &lt;td&gt;1.7 GB, whole collection&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Qdrant int8 collection, payload index on &lt;code&gt;year&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;78.7 s after upload&lt;/td&gt;
 &lt;td&gt;2.8 GB, whole collection&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Postgres holds every vector twice, 2,000 MB in the table (all but 25 MB of it TOAST) and again inside the index. So the HNSW row sits on top of the table, while Qdrant&amp;rsquo;s 1.7 GB is the whole collection. Compression was not free on disk either: the int8 collection came to 2.8 GB. It also built fastest of the three Qdrant collections while carrying the same payload index, so the gap between 152 s and 388 s is not simply the price of filter-aware edges. I did not chase why. Each upload finished before its graph build started, so I measured neither writes nor query latency during a Qdrant build. Points in segments that have not been indexed yet are searched without the graph. How searches behave during a rebuild is untested here.&lt;/p&gt;
&lt;h2 id="what-the-second-system-costs"&gt;What the second system costs
&lt;/h2&gt;&lt;p&gt;Everything above argues for the dedicated engine on filtered search and for treating memory as a configuration question on both sides. The bill for it sits in the parts this benchmark did not touch.&lt;/p&gt;
&lt;p&gt;Sync comes first. The embeddings are derived from rows that live in Postgres, so every insert, update, and delete has to reach the vector store. A dual write from the application is not atomic. A crash between the Postgres commit and the Qdrant upsert leaves the stores disagreeing, and nothing notices until a search returns a row that no longer exists. The designs that hold up are an outbox table or logical decoding feeding a consumer, and both add a pipeline with its own lag and its own place to page someone.&lt;/p&gt;
&lt;p&gt;Deletes are the sharp end. In pgvector a revoked permission or a deleted document leaves search results when the transaction commits. In a second store it stays searchable, and quotable by whatever model sits downstream, for as long as the pipeline is behind.&lt;/p&gt;
&lt;p&gt;Filters have to be copied. The &lt;code&gt;year&lt;/code&gt; column here went into Qdrant as payload, which was easy because it never changes. Real filters, such as tenant, status, and who can see the document, live in other tables and change on their own schedule. Each change becomes a payload update in the second system, and a new filter field means a new payload index and a graph rebuild. The joins go too. A query that ranks by distance and joins to a permissions table in one statement becomes an ID list from one system and a lookup in the other, the &lt;a class="link" href="https://explainanalyze.com/p/cross-database-joins-the-coupling-you-cant-see-until-you-split/" &gt;coupling you can&amp;rsquo;t see until you split&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Backups and restores double, and they do not line up. Qdrant &lt;a class="link" href="https://qdrant.tech/documentation/snapshots/" target="_blank" rel="noopener"
 &gt;snapshots&lt;/a&gt; cover one collection on one node and restore to the same or next minor version, and there is no shared point in time with a Postgres base backup and WAL. A restore of both systems is two restores and a reconciliation, or one restore and a full re-sync from Postgres, which on this fixture is a 24-second upload followed by 388 seconds of indexing. At the scale where the dedicated engine starts to make sense, that re-sync grows with the corpus.&lt;/p&gt;
&lt;p&gt;All of this assumes Postgres is on the menu. On MySQL Community 26.10.0 a &lt;code&gt;VECTOR&lt;/code&gt; column exists, takes up to 16,383 dimensions, and does very little else. &lt;code&gt;DISTANCE()&lt;/code&gt; fails with &lt;code&gt;ERROR 1305&lt;/code&gt;, because the &lt;a class="link" href="https://dev.mysql.com/doc/refman/26.10/en/vector-functions.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; reserves it for HeatWave on OCI and MySQL AI and leaves it out of both the Community and Commercial distributions. &lt;code&gt;CREATE INDEX&lt;/code&gt; fails with &lt;code&gt;Non-scalar (e.g., vector) column 'e' cannot be used as key&lt;/code&gt;. So the server stores an embedding it can neither compare nor index, which makes the headline feature a float array with a nicer name. MariaDB, the fork, has had a &lt;code&gt;VECTOR INDEX&lt;/code&gt; built on a modified HNSW since &lt;a class="link" href="https://mariadb.com/docs/server/reference/sql-structure/vectors/vector-overview" target="_blank" rel="noopener"
 &gt;11.7&lt;/a&gt;, generally available in the 11.8 LTS. On stock MySQL, vector search means computing distances in the application, moving to HeatWave, or paying for the second system priced above.&lt;/p&gt;
&lt;h2 id="the-numbers-to-watch"&gt;The numbers to watch
&lt;/h2&gt;&lt;p&gt;Three numbers decide this, and all three can be read off a running Postgres before anyone proposes a migration.&lt;/p&gt;
&lt;p&gt;The first is the HNSW index size from &lt;code&gt;pg_relation_size&lt;/code&gt; against the memory left over after the rest of the working set. Here the gap between fitting and not fitting was 2 ms against 209 ms. &lt;code&gt;EXPLAIN (ANALYZE, BUFFERS)&lt;/code&gt; on a sample of vector queries shows the approach early as &lt;code&gt;shared read&lt;/code&gt; counts climbing from zero toward the 842 in the opening plan.&lt;/p&gt;
&lt;p&gt;The second is how often filtered vector queries return fewer rows than their &lt;code&gt;LIMIT&lt;/code&gt;, plus recall measured offline against the same query with &lt;code&gt;enable_indexscan = off&lt;/code&gt;. A sustained short-result rate after iterative scans are on, on filters too varied for partial indexes, is the clearest measured case for the dedicated engine.&lt;/p&gt;
&lt;p&gt;The third is the &lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt; duration against how often the corpus gets re-embedded. On this box that was 196 seconds for half a million vectors.&lt;/p&gt;</description></item><item><title>How to Read EXPLAIN ANALYZE: MySQL</title><link>https://explainanalyze.com/p/how-to-read-explain-analyze-mysql/</link><pubDate>Wed, 04 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/how-to-read-explain-analyze-mysql/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post How to Read EXPLAIN ANALYZE: MySQL" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; runs a query on MySQL and prints the steps MySQL took to answer it, with the time and the rows of each one. This post reads that output from a one-line plan up to a join with a sort: what each number means, how to find the step the time went to, how to tell a wrong guess from a slow plan, and what MySQL&amp;rsquo;s output leaves out that PostgreSQL&amp;rsquo;s shows. Every plan comes from MySQL 8.4.13.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So here is how &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; works, in outline. SQL says which rows you want, not how to find them, and MySQL works out the how on its own. On the five million orders used below, the same one-condition query took 652 ms one way and 0.045 ms the other. Plain &lt;code&gt;EXPLAIN&lt;/code&gt; prints the way MySQL chose, called the plan, without running anything, so every number in it is a guess. &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; runs the query and prints what happened next to each guess: rows out, time taken, and how many times each step ran. Reading it comes down to two moves. Find the one step the time went to, then compare that step&amp;rsquo;s guess with what happened. The output says where the time went and not why, so the fix still takes some thinking on your part.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-how-a-query-runs"&gt;A quick reminder about how a query runs
&lt;/h2&gt;&lt;p&gt;The part of MySQL that chooses the plan is the optimizer, and it chooses before reading any data. It lists the ways it could answer, estimates the cost of each, and picks the cheapest. One of its biggest choices is whether to use an index. An index is a separate sorted structure, like the index at the back of a book, that maps each value of a column to where the rows holding it are stored. The estimates come from statistics that InnoDB, the storage engine that holds MySQL&amp;rsquo;s tables, keeps about each table and its indexes, and from quick samples of an index taken while planning. Working from statistics instead of the rows is why plain &lt;code&gt;EXPLAIN&lt;/code&gt; answers instantly, and why it can be badly wrong.&lt;/p&gt;
&lt;p&gt;The executor then runs the chosen plan and counts what happens, and those counts are what &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; adds.&lt;/p&gt;
&lt;p&gt;&lt;img alt="SQL passes through the parser, resolver and optimizer before any row is read; the iterator executor then runs the plan. EXPLAIN prints the plan with estimates, EXPLAIN ANALYZE adds what actually happened" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/how-to-read-explain-analyze-mysql/query-pipeline.svg"&gt;&lt;/p&gt;
&lt;h2 id="reading-a-plan-from-one-line-up"&gt;Reading a plan from one line up
&lt;/h2&gt;&lt;p&gt;Every plan below comes from MySQL 8.4.13 in Docker with default settings, on a &lt;code&gt;customers&lt;/code&gt; table of 200,000 rows (50 countries, 10 cities each) and an &lt;code&gt;orders&lt;/code&gt; table of 5,000,000. Each order belongs to a random customer, so one customer&amp;rsquo;s orders are scattered across the table, the way real orders arrive. &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/" &gt;The PostgreSQL version of this post&lt;/a&gt; uses the same rows.&lt;/p&gt;
&lt;p&gt;Start with the simplest slow query there is, one customer&amp;rsquo;s orders, before any index exists on &lt;code&gt;customer_id&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4242&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;EXPLAIN FORMAT=TREE&lt;/code&gt; prints the plan as a tree:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Filter: (orders.customer_id = 4242) (cost=529407 rows=496280)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on orders (cost=529407 rows=4.96e+6)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Each line starting with &lt;code&gt;-&amp;gt;&lt;/code&gt; is one step. MySQL calls a step an iterator, because each one hands rows, one at a time, to the step above it. The deeper a line is indented, the earlier it runs, so read from the innermost line out. &lt;code&gt;Table scan on orders&lt;/code&gt; means read every row of the table from start to finish. Its rows go up to &lt;code&gt;Filter&lt;/code&gt;, which is the &lt;code&gt;WHERE&lt;/code&gt; condition, checked against each row. &lt;code&gt;rows=&lt;/code&gt; is the estimate: about 4.96 million rows from the scan (&lt;code&gt;4.96e+6&lt;/code&gt; is engineering notation for 4,960,000), and 496,280 expected to match. &lt;code&gt;cost&lt;/code&gt; is the optimizer&amp;rsquo;s price in its own units, not milliseconds. Now with &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Filter: (orders.customer_id = 4242) (cost=529407 rows=496280) (actual time=16.7..652 rows=27 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on orders (cost=529407 rows=4.96e+6) (actual time=0.224..578 rows=5e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first parenthesis is still the guess, and the second is what happened. &lt;code&gt;actual time=0.224..578&lt;/code&gt; on the table scan is milliseconds until it produced its first row and its last row. &lt;code&gt;rows=5e+6&lt;/code&gt; is the rows it produced: all five million. &lt;code&gt;loops=1&lt;/code&gt; is how many times the step ran, which matters later. On the &lt;code&gt;Filter&lt;/code&gt;, &lt;code&gt;rows=27&lt;/code&gt; is how many matched, against a guess of 496,280.&lt;/p&gt;
&lt;p&gt;Two things are wrong here, and they are different problems. The guess was off by a factor of 18,000, which is a lot even for a guess. With no index on &lt;code&gt;customer_id&lt;/code&gt; the optimizer knows very little about the column and falls back on a rough rule, and its guess works out to exactly a tenth of the table. And even a perfect guess would not have helped, because without an index there was no faster way to find 27 rows than reading all five million. That is what the table scan&amp;rsquo;s &lt;code&gt;rows=5e+6&lt;/code&gt; says, and on a slow query it is the first number worth finding. After &lt;code&gt;CREATE INDEX orders_customer_id_idx ON orders (customer_id)&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on orders using orders_customer_id_idx (customer_id=4242) (cost=28.7 rows=27) (actual time=0.044..0.0452 rows=27 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;One step, a lookup instead of a scan. The guess is now exactly right (&lt;code&gt;rows=27&lt;/code&gt;), because the index gives the optimizer real numbers to work from, and the query takes 0.045 ms instead of 652.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;EXPLAIN ANALYZE really runs the query&lt;/strong&gt;
 &lt;div&gt;For a &lt;code&gt;SELECT&lt;/code&gt; it takes as long as the query takes; the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/explain.html" target="_blank" rel="noopener"
 &gt;MySQL manual&lt;/a&gt; notes you can stop it with &lt;code&gt;KILL QUERY&lt;/code&gt; or Ctrl-C. It also accepts some &lt;code&gt;UPDATE&lt;/code&gt; and &lt;code&gt;DELETE&lt;/code&gt; statements, so treat it as running them and wrap it in &lt;code&gt;START TRANSACTION;&lt;/code&gt; and &lt;code&gt;ROLLBACK;&lt;/code&gt;. Run long queries on a copy or a replica, not the server your users are on.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-database-guessed-wrong"&gt;When the database guessed wrong
&lt;/h2&gt;&lt;p&gt;A wrong guess can lead the optimizer to a wrong plan, so the estimate is worth checking on every slow step. This query joins the two tables (a join matches rows in one table to rows in another, here customers to their orders) and totals the orders of every customer in one city:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C07&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C07-3&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Aggregate: count(0), sum(o.total) (cost=75057 rows=1) (actual time=84.4..84.4 rows=1 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=70156 rows=49011) (actual time=0.222..84 rows=9940 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: ((c.city = &amp;#39;C07-3&amp;#39;) and (c.country = &amp;#39;C07&amp;#39;)) (cost=20384 rows=2001) (actual time=0.103..29.8 rows=400 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on c (cost=20384 rows=200070) (actual time=0.0927..22.6 rows=200000 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index lookup on o using orders_customer_id_idx (customer_id=c.id) (cost=22.4 rows=24.5) (actual time=0.127..0.135 rows=24.9 loops=400)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Read it inside out. The deepest line, &lt;code&gt;Table scan on c&lt;/code&gt;, reads all 200,000 customers. &lt;code&gt;Filter&lt;/code&gt; keeps the ones in that city: it expected 2,001 and found 400. That is the thing to look for, estimated rows against actual rows on the same line. Neither column has an index, and the guess again works out to a tenth per condition: a tenth of a tenth of 200,070 is 2,001.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Nested loop inner join&lt;/code&gt; is one way to do a join. It has two children at the same depth: the first (the filtered customers) runs once, and for each row it produces, the second (find that customer&amp;rsquo;s orders through the index) runs once. That is what &lt;code&gt;loops=400&lt;/code&gt; on the &lt;code&gt;Index lookup&lt;/code&gt; means. When &lt;code&gt;loops&lt;/code&gt; is above 1, &lt;code&gt;rows&lt;/code&gt; and &lt;code&gt;actual time&lt;/code&gt; are averages per run, so multiply them back: 24.9 rows times 400 is the 9,940 rows the join produced, and 0.135 ms times 400 is 54 ms, most of the 84. The join&amp;rsquo;s own estimate was 49,011 rows against 9,940, the first mistake carried up the tree.&lt;/p&gt;
&lt;p&gt;Here the wrong guess did no harm, because with 2,001 customers or 400, looking up each one&amp;rsquo;s orders in the index is a good plan. A gap matters when the right number would have made the optimizer choose differently, and the bigger the gap, the more likely that is. The next plan has one where a wrong guess fed into the choice of index.&lt;/p&gt;
&lt;h2 id="finding-the-step-the-time-went-to"&gt;Finding the step the time went to
&lt;/h2&gt;&lt;p&gt;In a plan with six steps, only the innermost lines show what a step cost by itself. Take the 100 largest orders since November 1, with each customer&amp;rsquo;s location:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2024-11-01&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Limit: 100 row(s) (cost=2.29e+6 rows=100) (actual time=789..789 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=2.29e+6 rows=4.96e+6) (actual time=789..789 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Sort: o.total DESC (cost=529519 rows=4.96e+6) (actual time=789..789 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: (o.created_at &amp;gt;= TIMESTAMP&amp;#39;2024-11-01 00:00:00&amp;#39;) (cost=529519 rows=4.96e+6) (actual time=585..675 rows=608001 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on o (cost=529519 rows=4.96e+6) (actual time=0.114..572 rows=5e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Single-row index lookup on c using PRIMARY (id=o.customer_id) (cost=0.997 rows=1) (actual time=0.0054..0.00541 rows=1 loops=100)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Every other step&amp;rsquo;s time includes the time of the steps under it, so what one step cost by itself is its own finishing time minus its children&amp;rsquo;s. &lt;code&gt;Sort&lt;/code&gt; finished at 789 ms and its child at 675, so sorting cost 114 ms. &lt;code&gt;Filter&lt;/code&gt; finished at 675 and the scan under it at 572, so checking the dates cost 103. &lt;code&gt;Table scan on o&lt;/code&gt; cost 572 ms by itself, more than everything else put together. It read five million rows to keep 608,001. The customer lookups ran 100 times at 0.0054 ms each, half a millisecond in all.&lt;/p&gt;
&lt;p&gt;The first-row times say something too. &lt;code&gt;Sort&lt;/code&gt; produced its first row at the same moment as its last (789..789), because a sort cannot hand anything up until it has seen all its input. &lt;code&gt;Filter&lt;/code&gt; produced its first row at 585 ms, because the newest orders sit at the end of the table and the scan reaches them last.&lt;/p&gt;
&lt;p&gt;There was an index on &lt;code&gt;created_at&lt;/code&gt; while this ran, and MySQL did not use it. It estimated about 1.27 million matching rows (the real number was 608,001), and priced 1.27 million trips from the index back to the table as dearer than one pass over the whole table. The guess was off by half; the plan alone cannot say whether the right number would have changed the choice. An index that holds every column the query needs, a covering index, never makes those trips. After &lt;code&gt;CREATE INDEX orders_created_total_cust_idx ON orders (created_at, total, customer_id)&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Limit: 100 row(s) (cost=1.49e+6 rows=100) (actual time=183..183 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=1.49e+6 rows=1.28e+6) (actual time=183..183 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Sort: o.total DESC (cost=258614 rows=1.28e+6) (actual time=183..183 rows=100 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: (o.created_at &amp;gt;= TIMESTAMP&amp;#39;2024-11-01 00:00:00&amp;#39;) (cost=258614 rows=1.28e+6) (actual time=0.0673..73.8 rows=608001 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index range scan on o using orders_created_total_cust_idx over (&amp;#39;2024-11-01 00:00:00&amp;#39; &amp;lt;= created_at) (cost=258614 rows=1.28e+6) (actual time=0.0669..54.9 rows=608001 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Single-row index lookup on c using PRIMARY (id=o.customer_id) (cost=0.862 rows=1) (actual time=0.00143..0.00145 rows=1 loops=100)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;Covering index range scan&lt;/code&gt; means MySQL read only the part of the index from November 1 onward, and found everything it needed there. 183 ms instead of 789. The sort is now the slowest step at 109 ms, and that part is the price of the question: finding the 100 largest of 608,001 orders means looking at all 608,001. The new index costs something too, 152 MB on disk and extra work on every insert, so it is worth it for a query that runs often and maybe not for a nightly report.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Next thing to learn: counting what MySQL read&lt;/strong&gt;
 &lt;div&gt;PostgreSQL&amp;rsquo;s plan prints how many pages each step read. MySQL&amp;rsquo;s does not, and it does not say when a sort spilled to disk either. Session status counters fill part of the gap: run &lt;code&gt;FLUSH STATUS&lt;/code&gt;, then the query, then &lt;code&gt;SHOW SESSION STATUS LIKE 'Handler_read%'&lt;/code&gt;. For the one-customer query without an index, &lt;code&gt;Handler_read_rnd_next&lt;/code&gt; was 5,000,001, one per row scanned. With the index, it was 0, and &lt;code&gt;Handler_read_next&lt;/code&gt; was 27.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-first-five-things-to-look-at"&gt;The first five things to look at
&lt;/h2&gt;&lt;ol&gt;
&lt;li&gt;The top line&amp;rsquo;s last time: the number you want smaller.&lt;/li&gt;
&lt;li&gt;The slowest step. From the top, subtract each step&amp;rsquo;s children from its own finishing time until you find the step that is slow by itself.&lt;/li&gt;
&lt;li&gt;On that step, actual &lt;code&gt;rows&lt;/code&gt; against the estimate. A big difference means the optimizer guessed wrong.&lt;/li&gt;
&lt;li&gt;Under that step, a &lt;code&gt;Table scan&lt;/code&gt; whose &lt;code&gt;rows&lt;/code&gt; is close to the table&amp;rsquo;s size, when only a few rows survive. That means a missing index.&lt;/li&gt;
&lt;li&gt;Rows handled against rows needed. Thousands sorted for a page of 100 means the query asks for more than the question.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When you are ready for a real one, &lt;a class="link" href="https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/" &gt;A Query on a 3-Billion-Row Table Took 100 Minutes&lt;/a&gt; reads a production MySQL plan end to end the same way.&lt;/p&gt;
&lt;h3 id="the-ways-mysql-reads-a-table"&gt;The ways MySQL reads a table
&lt;/h3&gt;&lt;p&gt;Every leaf of the tree is one of a short list of access methods, and the name says how much of the table or index MySQL expects to touch. The older &lt;code&gt;EXPLAIN&lt;/code&gt; output, the one without &lt;code&gt;FORMAT=TREE&lt;/code&gt; that most tutorials still show, names the same methods in its &lt;code&gt;type&lt;/code&gt; column, so both are listed. Rows are ordered from cheapest to most expensive. The names below were taken from MySQL 8.4.13 on a small separate schema, since the post&amp;rsquo;s own fixture does not produce all of them.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;What the tree says&lt;/th&gt;
 &lt;th&gt;&lt;code&gt;type&lt;/code&gt; in classic EXPLAIN&lt;/th&gt;
 &lt;th&gt;What MySQL does&lt;/th&gt;
 &lt;th&gt;What it usually means&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Rows fetched before execution&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;const&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Looked up one row by primary key or unique index while planning; the row is a constant by the time the query runs&lt;/td&gt;
 &lt;td&gt;As good as it gets&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Single-row index lookup on t using PRIMARY (id=...)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;eq_ref&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;For each row from the previous step, one lookup that returns at most one row&lt;/td&gt;
 &lt;td&gt;The normal shape of a join on a primary key&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index lookup on t using k (col=...)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;ref&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Finds every row with one value through a non-unique index, then fetches each row from the table&lt;/td&gt;
 &lt;td&gt;Fine when &lt;code&gt;rows&lt;/code&gt; is small; expensive when one value matches thousands&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Covering index lookup on t using k (col=...)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;ref&lt;/code&gt; + &lt;code&gt;Using index&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Same lookup, but every column the query needs is in the index, so the table is never read&lt;/td&gt;
 &lt;td&gt;Cheaper than a plain lookup; adding a column to the SELECT can turn it back into one&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index lookup ... (col=... or NULL)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;ref_or_null&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;A lookup that also fetches the rows where the column is NULL&lt;/td&gt;
 &lt;td&gt;A &lt;code&gt;col = x OR col IS NULL&lt;/code&gt; condition&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index range scan on t using k over (a &amp;lt; col &amp;lt; b)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;range&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Walks the part of the index between two bounds, fetching rows from the table&lt;/td&gt;
 &lt;td&gt;Normal for date ranges; watch &lt;code&gt;rows&lt;/code&gt; against what the query returns&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Covering index range scan on t using k over (...)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;range&lt;/code&gt; + &lt;code&gt;Using index&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;The same walk without touching the table&lt;/td&gt;
 &lt;td&gt;The cheapest range&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Sort-deduplicate by row ID&lt;/code&gt; over two range scans&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;index_merge&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Runs two index scans and combines their row IDs&lt;/td&gt;
 &lt;td&gt;An &lt;code&gt;OR&lt;/code&gt; across two indexed columns; often slower than it looks&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index scan on t using k&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;index&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads the whole index in order and fetches every row from the table&lt;/td&gt;
 &lt;td&gt;Usually an &lt;code&gt;ORDER BY&lt;/code&gt; on an indexed column with no filter; expensive when the table is large&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Covering index scan on t using k&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;index&lt;/code&gt; + &lt;code&gt;Using index&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads the whole index without the table&lt;/td&gt;
 &lt;td&gt;Cheaper than a table scan because the index is smaller, still every row&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Table scan on t&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;ALL&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads every row in the table&lt;/td&gt;
 &lt;td&gt;The one to look for when a query is slow and only a few rows survive the &lt;code&gt;Filter&lt;/code&gt; above it: a missing index, or a condition that wraps the column in a function and so hides it from the index (&lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;Non-SARGable Predicates&lt;/a&gt;)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Zero rows (Impossible WHERE)&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;Impossible WHERE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;The optimizer proved no row can match and reads nothing&lt;/td&gt;
 &lt;td&gt;A condition that contradicts itself&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The covering and plain versions of the same method can be far apart. Counting 25,182 orders for a range of customers took 2.3 ms as a covering scan; summing their &lt;code&gt;total&lt;/code&gt;, a column not in the index, took 95 ms, because every row then meant a trip back to the table.&lt;/p&gt;
&lt;p&gt;You have already met &lt;code&gt;Filter:&lt;/code&gt; and &lt;code&gt;Nested loop inner join&lt;/code&gt; above the leaves. A nested loop whose second child is a &lt;code&gt;Table scan&lt;/code&gt; means the join column has no index, so the whole table is read once per loop. &lt;code&gt;Inner hash join&lt;/code&gt; reads the smaller side once into memory and probes it, and the classic output shows it as &lt;code&gt;Using join buffer (hash join)&lt;/code&gt;. &lt;code&gt;Sort:&lt;/code&gt; orders rows in memory or in a temporary file, which the plan does not distinguish. &lt;code&gt;Limit:&lt;/code&gt;, &lt;code&gt;Group aggregate:&lt;/code&gt; and &lt;code&gt;Aggregate:&lt;/code&gt; do what their names say, and &lt;code&gt;Materialize&lt;/code&gt; writes an intermediate result to a temporary table that a &lt;code&gt;Table scan&lt;/code&gt; above it then reads.&lt;/p&gt;
&lt;p&gt;The test data was generated once with PostgreSQL (the script is at the end of &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/" &gt;the PostgreSQL post&lt;/a&gt;), exported to CSV, and loaded into these tables on MySQL 8.4:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;varchar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;decimal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;note&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LOAD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DATA&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INFILE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;/var/lib/mysql-files/customers.csv&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;FIELDS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TERMINATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;,&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LOAD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DATA&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INFILE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;/var/lib/mysql-files/orders.csv&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;FIELDS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TERMINATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;,&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;note&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;</description></item><item><title>How to Read EXPLAIN ANALYZE: PostgreSQL</title><link>https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/</link><pubDate>Sun, 01 Nov 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post How to Read EXPLAIN ANALYZE: PostgreSQL" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; is the PostgreSQL command that runs a query and reports how PostgreSQL answered it, one step at a time, with what each step cost. This post reads that output from a one-line plan up to a join and a sort: what each number on a line means, how to find the step the time went to, and how to tell when PostgreSQL guessed wrong about how many rows it would find. Every plan comes from PostgreSQL 18.6.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So here is how &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; works, in outline. SQL says which rows you want, not how to find them, and PostgreSQL picks the how on its own: read the whole table or jump straight to the rows it needs, and in a join, which table to start from. On the five million orders used below, the same one-condition query took 144 ms one way and 0.019 ms the other. Plain &lt;code&gt;EXPLAIN&lt;/code&gt; prints the way PostgreSQL chose, called the plan, without running anything, so every number in it is a guess. &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; runs the query for real and prints what happened next to each guess: rows out, time taken, how much of the table was read. Reading it comes down to two moves. Find the one step the time went to, then compare that step&amp;rsquo;s guess with what happened. The output says where the time went and not why, so the fix still takes some thinking on your part.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-how-a-query-runs"&gt;A quick reminder about how a query runs
&lt;/h2&gt;&lt;p&gt;The part of PostgreSQL that chooses the plan is the planner. It lists the ways it could answer, estimates the cost of each, and keeps the cheapest. One of its biggest choices is whether to use an index. An index is a separate sorted structure, like the index at the back of a book, that maps each value of a column to where the rows holding it are stored. The estimates come from statistics that the &lt;code&gt;ANALYZE&lt;/code&gt; command collects, such as how many rows a table has and which values are common. That command is a different thing from &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt;, despite the shared word. The planner never looks at the data itself, which is why plain &lt;code&gt;EXPLAIN&lt;/code&gt; answers instantly and why its guesses can be wrong.&lt;/p&gt;
&lt;p&gt;The executor then runs the chosen plan and counts what happens, and those counts are what &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; adds.&lt;/p&gt;
&lt;p&gt;&lt;img alt="SQL passes through the parser, rewriter and planner before any row is read; the executor then runs the plan. EXPLAIN prints the plan with estimates, EXPLAIN ANALYZE adds what actually happened" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/how-to-read-explain-analyze-postgresql/query-pipeline.svg"&gt;&lt;/p&gt;
&lt;h2 id="reading-a-plan-from-one-line-up"&gt;Reading a plan from one line up
&lt;/h2&gt;&lt;p&gt;Every plan below comes from PostgreSQL 18.6 in Docker with default settings, on a &lt;code&gt;customers&lt;/code&gt; table of 200,000 rows (50 countries, 10 cities each) and an &lt;code&gt;orders&lt;/code&gt; table of 5,000,000. Each order belongs to a random customer, so one customer&amp;rsquo;s orders are scattered across the table, the way real orders arrive. I turned off JIT compilation and parallel workers to keep the output short. &lt;a class="link" href="https://explainanalyze.com/p/how-to-read-explain-analyze-mysql/" &gt;The MySQL version of this post&lt;/a&gt; uses the same rows.&lt;/p&gt;
&lt;p&gt;Start with the simplest slow query there is, one customer&amp;rsquo;s orders:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4242&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Plain &lt;code&gt;EXPLAIN&lt;/code&gt; prints this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Seq Scan on orders (cost=0.00..145287.00 rows=26 width=22)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Filter: (customer_id = 4242)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;A plan with one step. &lt;code&gt;Seq Scan&lt;/code&gt; (sequential scan, or table scan) means read every row of the table from start to finish. &lt;code&gt;Filter&lt;/code&gt; is the &lt;code&gt;WHERE&lt;/code&gt; condition, checked against each row. &lt;code&gt;rows=26&lt;/code&gt; is the estimate: the planner expects 26 matches. &lt;code&gt;cost&lt;/code&gt; is the planner&amp;rsquo;s price in its own units, not milliseconds. Now with &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Seq Scan on orders (cost=0.00..145287.00 rows=26 width=22) (actual time=3.082..144.209 rows=27.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Filter: (customer_id = 4242)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Rows Removed by Filter: 4999973
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=8694 read=74093
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Planning Time: 0.091 ms
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 144.249 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first parenthesis is still the guess, and the second is what happened. &lt;code&gt;actual time=3.082..144.209&lt;/code&gt; is milliseconds until the step produced its first row and its last row. &lt;code&gt;rows=27.00&lt;/code&gt; is the rows it produced, so the guess of 26 was close. &lt;code&gt;loops=1&lt;/code&gt; is how many times the step ran, which matters later.&lt;/p&gt;
&lt;p&gt;The next two lines are the price. &lt;code&gt;Rows Removed by Filter: 4999973&lt;/code&gt; says PostgreSQL looked at all 5,000,000 rows and threw away all but 27. &lt;code&gt;Buffers&lt;/code&gt; counts pages: PostgreSQL stores a table in 8 KB pages of dozens of rows each, and always reads whole pages. &lt;code&gt;shared hit&lt;/code&gt; is pages already in its memory cache (shared buffers), and &lt;code&gt;read&lt;/code&gt; is pages it asked the operating system for. Together they are 82,787 pages, the whole table. &lt;code&gt;Execution Time&lt;/code&gt; is the total, 144 ms.&lt;/p&gt;
&lt;p&gt;So the estimate was right and the query was still slow, because with no index on &lt;code&gt;customer_id&lt;/code&gt; there was no faster way to find 27 rows than reading everything. After &lt;code&gt;CREATE INDEX ON orders (customer_id)&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Bitmap Heap Scan on orders (cost=4.63..107.58 rows=26 width=22) (actual time=0.006..0.014 rows=27.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Recheck Cond: (customer_id = 4242)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Blocks: exact=27
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=30
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Bitmap Index Scan on orders_customer_id_idx (cost=0.00..4.63 rows=26 width=0) (actual time=0.003..0.003 rows=27.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = 4242)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Searches: 1
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=3
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 0.019 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Now the plan has two steps, called nodes. A line starting with &lt;code&gt;-&amp;gt;&lt;/code&gt; is a node that feeds rows to the node above it, and the deeper it is indented, the earlier it runs, so read innermost first.&lt;/p&gt;
&lt;p&gt;The innermost node, &lt;code&gt;Bitmap Index Scan&lt;/code&gt;, looked up 4242 in the index (&lt;code&gt;Index Cond&lt;/code&gt;), found 27 entries, and read 3 index pages. It hands the row locations up to &lt;code&gt;Bitmap Heap Scan&lt;/code&gt;, which fetches those rows from the table (PostgreSQL calls a table&amp;rsquo;s storage the heap). &lt;code&gt;Heap Blocks: exact=27&lt;/code&gt; says the 27 rows sat on 27 different pages. A parent&amp;rsquo;s time and buffers include its children&amp;rsquo;s, so the top &lt;code&gt;Buffers: shared hit=30&lt;/code&gt; is 3 index pages plus 27 table pages. Thirty pages instead of 82,787, and 0.019 ms instead of 144.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;EXPLAIN ANALYZE really runs the query&lt;/strong&gt;
 &lt;div&gt;For a &lt;code&gt;SELECT&lt;/code&gt; it takes as long as the query takes. For &lt;code&gt;UPDATE&lt;/code&gt;, &lt;code&gt;DELETE&lt;/code&gt; or &lt;code&gt;INSERT&lt;/code&gt; the change really happens, so wrap it in &lt;code&gt;BEGIN;&lt;/code&gt; and &lt;code&gt;ROLLBACK;&lt;/code&gt;, as the &lt;a class="link" href="https://www.postgresql.org/docs/18/sql-explain.html" target="_blank" rel="noopener"
 &gt;PostgreSQL documentation&lt;/a&gt; suggests. Run long queries on a copy or a replica, not the server your users are on.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-database-guessed-wrong"&gt;When the database guessed wrong
&lt;/h2&gt;&lt;p&gt;A wrong guess can lead the planner to a wrong plan, so the estimate is worth checking on every slow step. This query joins the two tables (a join matches rows in one table to rows in another, here customers to their orders) and totals the orders of every customer in one city:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C07&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C07-3&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Aggregate (cost=5137.70..5137.71 rows=1 width=40) (actual time=91.548..91.554 rows=1.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=3861 read=8553 written=5
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested Loop (cost=4.63..5136.69 rows=200 width=6) (actual time=0.110..90.336 rows=9940.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=3861 read=8553 written=5
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Seq Scan on customers c (cost=0.00..4274.00 rows=8 width=4) (actual time=0.010..6.803 rows=400.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Filter: ((country = &amp;#39;C07&amp;#39;::text) AND (city = &amp;#39;C07-3&amp;#39;::text))
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Rows Removed by Filter: 199600
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=1274
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Bitmap Heap Scan on orders o (cost=4.63..107.58 rows=26 width=10) (actual time=0.044..0.205 rows=24.85 loops=400)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Recheck Cond: (c.id = customer_id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Blocks: exact=9940
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=2587 read=8553 written=5
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Bitmap Index Scan on orders_customer_id_idx (cost=0.00..4.63 rows=26 width=0) (actual time=0.014..0.014 rows=24.85 loops=400)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = c.id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Searches: 400
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=785 read=415
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 91.591 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Read it inside out. &lt;code&gt;Seq Scan on customers&lt;/code&gt; reads all 200,000 customers and keeps the ones in that city. It expected 8 and found 400. That is the thing to look for: estimated rows against actual rows on the same line.&lt;/p&gt;
&lt;p&gt;The planner assumes country and city are unrelated, so it multiplies their odds: 200,000 customers, times 1 in 50 for the country, times 1 in 500 for the city, is 8. In this data the city already decides the country, which the planner had no way to know, and the mistake carries up the tree: &lt;code&gt;Nested Loop&lt;/code&gt; expected 200 rows and produced 9,940.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Nested Loop&lt;/code&gt; is one way to do a join. For each row from its first child (a customer), it runs its second child once (find that customer&amp;rsquo;s orders through the index), and that is what &lt;code&gt;loops=400&lt;/code&gt; on the orders side means. When &lt;code&gt;loops&lt;/code&gt; is above 1, &lt;code&gt;rows&lt;/code&gt; and &lt;code&gt;actual time&lt;/code&gt; are averages per run, so multiply them back: 24.85 rows times 400 is the 9,940, and 0.205 ms times 400 is 82 ms, most of the 91. Buffers are already totals.&lt;/p&gt;
&lt;p&gt;Here the wrong guess did no harm, because with 8 customers or 400, looking up each one&amp;rsquo;s orders in the index is a good plan. A gap like this matters when the right number would have made the planner choose a different plan, and the bigger the gap, the more likely that is. &lt;a class="link" href="https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/" &gt;Uniqueness and Selectivity&lt;/a&gt; shows one that went from 50 ms to 50 minutes.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Next thing to learn: teaching the planner about related columns&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;CREATE STATISTICS customers_country_city (dependencies) ON country, city FROM customers&lt;/code&gt;, then &lt;code&gt;ANALYZE customers&lt;/code&gt;, tells PostgreSQL the two columns move together. The estimate went from 8 to 398 and the query got no faster, because the plan did not need to change. Fixing an estimate and fixing a query are different jobs.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-alarming-line-is-not-the-slow-one"&gt;When the alarming line is not the slow one
&lt;/h2&gt;&lt;p&gt;In a plan with several nodes, the line that looks worst is often not where the time went, and fixing it first buys very little. Here is a bigger tree, a query listing every order since November 1 with its customer&amp;rsquo;s location, largest total first:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort (cost=234697.30..236254.94 rows=623058 width=24) (actual time=512.409..573.290 rows=608001.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Key: o.total DESC
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Method: external merge Disk: 20848kB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=14992 read=69072, temp read=4525 written=4535
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Hash Join (cost=6751.00..161952.56 rows=623058 width=24) (actual time=239.832..395.547 rows=608001.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Hash Cond: (o.customer_id = c.id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=14989 read=69072, temp read=1919 written=1919
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Seq Scan on orders o (cost=0.00..145287.00 rows=623058 width=18) (actual time=219.531..257.878 rows=608001.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Filter: (created_at &amp;gt;= &amp;#39;2024-11-01 00:00:00+00&amp;#39;::timestamp with time zone)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Rows Removed by Filter: 4391999
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=13715 read=69072
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Hash (cost=3274.00..3274.00 rows=200000 width=14) (actual time=20.133..20.134 rows=200000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buckets: 262144 Batches: 2 Memory Usage: 6749kB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=1274, temp written=438
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Seq Scan on customers c (cost=0.00..3274.00 rows=200000 width=14) (actual time=0.010..6.891 rows=200000.00 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=1274
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Execution Time: 584.068 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The lines that jump out are &lt;code&gt;Sort Method: external merge Disk: 20848kB&lt;/code&gt; and &lt;code&gt;Batches: 2&lt;/code&gt;. Both mean a spill: the step needed more working memory than PostgreSQL gives one step by default (the &lt;code&gt;work_mem&lt;/code&gt; setting, 4 MB), so it wrote part of its work to a temporary file and read it back. It is tempting to start there. Find the slow step first.&lt;/p&gt;
&lt;p&gt;A node&amp;rsquo;s time includes its children&amp;rsquo;s, the same rule that made the 30 buffers above, so what one node cost by itself is its own finishing time minus its children&amp;rsquo;s. &lt;code&gt;Sort&lt;/code&gt; finished at 573 ms and its child, the &lt;code&gt;Hash Join&lt;/code&gt;, at 396, so the sort cost 178 ms. &lt;code&gt;Hash Join&lt;/code&gt; is a join that loads one table into memory (the &lt;code&gt;Hash&lt;/code&gt; node under it) and then matches the other table&amp;rsquo;s rows against it; it finished at 396, minus 258 for one child and 20 for the other, which leaves 118 ms. &lt;code&gt;Seq Scan on orders&lt;/code&gt; cost 258 ms on its own, the biggest single share. It read the whole table and threw away 4,391,999 rows to keep 608,001.&lt;/p&gt;
&lt;p&gt;That leaves two things to fix. The filter on &lt;code&gt;created_at&lt;/code&gt; has no index, so I added one. And the query asks for 608,001 sorted rows; if the screen shows the top 100, ask for 100, in a subquery with &lt;code&gt;ORDER BY total DESC LIMIT 100&lt;/code&gt; that runs before the join, so only 100 orders need a customer looked up. The spills got their own test, with 16 times the memory:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Change&lt;/th&gt;
 &lt;th&gt;Execution time&lt;/th&gt;
 &lt;th&gt;Spills&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;None (the plan above), 4 runs&lt;/td&gt;
 &lt;td&gt;450 to 570 ms&lt;/td&gt;
 &lt;td&gt;sort 20 MB on disk, hash in 2 batches&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index on &lt;code&gt;created_at&lt;/code&gt;, 4 runs&lt;/td&gt;
 &lt;td&gt;310 to 340 ms&lt;/td&gt;
 &lt;td&gt;both still there&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Index, plus the top 100 picked before the join&lt;/td&gt;
 &lt;td&gt;76 ms&lt;/td&gt;
 &lt;td&gt;sort used 36 kB of memory&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;No index, 16 times the &lt;code&gt;work_mem&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;40 to 60 ms faster than the first row&lt;/td&gt;
 &lt;td&gt;none&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The spills were real, and the smallest problem in the tree. Raising &lt;code&gt;work_mem&lt;/code&gt; server-wide to make them go away is risky anyway, because every sort in every connection can use that much; &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iv-when-the-sort-spills/" &gt;Part IV of the queries series&lt;/a&gt; explains why.&lt;/p&gt;
&lt;h2 id="the-first-five-things-to-look-at"&gt;The first five things to look at
&lt;/h2&gt;&lt;ol&gt;
&lt;li&gt;&lt;code&gt;Execution Time&lt;/code&gt; at the bottom: the number you want smaller.&lt;/li&gt;
&lt;li&gt;The slowest step. From the top, subtract each step&amp;rsquo;s children from its own finishing time until you find the step that is slow by itself.&lt;/li&gt;
&lt;li&gt;On that step, actual &lt;code&gt;rows&lt;/code&gt; against the estimate. A big difference means the planner guessed wrong.&lt;/li&gt;
&lt;li&gt;On that step, &lt;code&gt;Rows Removed by Filter&lt;/code&gt; and &lt;code&gt;Buffers&lt;/code&gt;. Millions removed, or pages near the table&amp;rsquo;s size, mean a missing index.&lt;/li&gt;
&lt;li&gt;Rows handled against rows needed. Thousands sorted for a page of 100 means the query asks for more than the question.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When you are ready for a real one, &lt;a class="link" href="https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/" &gt;A Query on a 3-Billion-Row Table Took 100 Minutes&lt;/a&gt; reads a production plan end to end the same way.&lt;/p&gt;
&lt;h3 id="the-ways-postgresql-reads-a-table"&gt;The ways PostgreSQL reads a table
&lt;/h3&gt;&lt;p&gt;Every leaf of the tree is one of a short list of scan types, and the name says how much of the table or index PostgreSQL expects to touch. Rows are ordered from cheapest to most expensive. The names were taken from PostgreSQL 18.6 on a small separate schema, since the post&amp;rsquo;s own fixture does not produce all of them.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;What the plan says&lt;/th&gt;
 &lt;th&gt;What PostgreSQL does&lt;/th&gt;
 &lt;th&gt;What it usually means&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index Only Scan using k on t&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads the index and never the table, because every column the query needs is in the index&lt;/td&gt;
 &lt;td&gt;The cheapest way to get rows, as long as &lt;code&gt;Heap Fetches&lt;/code&gt; stays at zero&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Index Scan using k on t&lt;/code&gt; with &lt;code&gt;Index Cond&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Walks the index for the matching range, then fetches each row from the table in index order&lt;/td&gt;
 &lt;td&gt;The normal lookup for a primary key or a small range; expensive when the range is wide, because every row is a separate table read&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Bitmap Index Scan&lt;/code&gt; under a &lt;code&gt;Bitmap Heap Scan&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Collects every matching row&amp;rsquo;s location from the index first, then reads the table pages in order, each once&lt;/td&gt;
 &lt;td&gt;What the planner picks when an index matches many scattered rows; &lt;code&gt;Recheck Cond&lt;/code&gt; and &lt;code&gt;Heap Blocks&lt;/code&gt; tell you how much of the table it touched&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;BitmapOr&lt;/code&gt; or &lt;code&gt;BitmapAnd&lt;/code&gt; over two &lt;code&gt;Bitmap Index Scan&lt;/code&gt;s&lt;/td&gt;
 &lt;td&gt;Combines the row locations from two indexes before reading the table&lt;/td&gt;
 &lt;td&gt;An &lt;code&gt;OR&lt;/code&gt; or &lt;code&gt;AND&lt;/code&gt; across two indexed columns&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Seq Scan on t&lt;/code&gt; with &lt;code&gt;Filter&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads every row in the table and keeps the ones that pass the filter&lt;/td&gt;
 &lt;td&gt;The one to look for when a query is slow: &lt;code&gt;Rows Removed by Filter&lt;/code&gt; close to the table&amp;rsquo;s size, for a handful of rows kept, means a missing index, or a condition that wraps the column in a function and so hides it from the index (&lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;Non-SARGable Predicates&lt;/a&gt;)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Seq Scan on t&lt;/code&gt; with no &lt;code&gt;Filter&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads the whole table because the query asked for it&lt;/td&gt;
 &lt;td&gt;Expected under an aggregate or a join that needs every row; it is only a problem if the query did not need every row&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Result&lt;/code&gt; with &lt;code&gt;One-Time Filter: false&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;Reads nothing, because the planner proved no row can match&lt;/td&gt;
 &lt;td&gt;A condition that contradicts itself&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;Heap Fetches&lt;/code&gt; is the one number in that table the examples above never showed. An index only scan is meant to skip the table, but PostgreSQL still visits the table for any row it cannot yet prove is visible to your query, and that count is &lt;code&gt;Heap Fetches&lt;/code&gt;. Counting 25,182 orders took 1.3 ms with &lt;code&gt;Heap Fetches: 0&lt;/code&gt;, and 26.7 ms with &lt;code&gt;Heap Fetches: 15709&lt;/code&gt; after an &lt;code&gt;UPDATE&lt;/code&gt; had touched rows across the table. &lt;code&gt;VACUUM&lt;/code&gt; brings it back down; &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;One Column Added to a SELECT&lt;/a&gt; goes further.&lt;/p&gt;
&lt;p&gt;You have already met &lt;code&gt;Nested Loop&lt;/code&gt; and &lt;code&gt;Hash Join&lt;/code&gt; above the leaves. A &lt;code&gt;Nested Loop&lt;/code&gt; whose second child is a &lt;code&gt;Seq Scan&lt;/code&gt; means the join column has no index, so the whole table is read once per loop. &lt;code&gt;Merge Join&lt;/code&gt; walks two inputs that are already in the same order, usually from an index, and needs no working memory at all. &lt;code&gt;HashAggregate&lt;/code&gt; groups rows with a hash table and &lt;code&gt;GroupAggregate&lt;/code&gt; groups rows that already arrive sorted. &lt;code&gt;Limit&lt;/code&gt; stops pulling rows once it has enough, &lt;code&gt;Append&lt;/code&gt; glues the parts of a &lt;code&gt;UNION ALL&lt;/code&gt; together, and &lt;code&gt;CTE Scan&lt;/code&gt; reads a &lt;code&gt;WITH&lt;/code&gt; query that was run once and kept.&lt;/p&gt;
&lt;p&gt;The test data, if you want to build it yourself on PostgreSQL 18:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;setseed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;city&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;timestamptz&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lpad&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lpad&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;-&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;timestamptz&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2022-01-01&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;interval&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;7 minutes&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;generate_series&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;200000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;timestamptz&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;numeric&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;note&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WITH&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;autovacuum_enabled&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;false&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- vacuum runs only when I ask
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;200000&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CASE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHEN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;01&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THEN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ELSE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;shipped&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;END&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;timestamptz&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2024-01-01&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;interval&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;6 seconds&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;round&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;numeric&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;md5&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;md5&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;generate_series&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5000000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;g&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;</description></item><item><title>Separating Storage From Compute on EC2, Part 4: Database DR Restore</title><link>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-4-database-dr-restore/</link><pubDate>Mon, 26 Oct 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-4-database-dr-restore/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Separating Storage From Compute on EC2, Part 4: Database DR Restore" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;The restore is the primary&amp;rsquo;s own Terraform flipped to &lt;code&gt;live&lt;/code&gt; in the DR region: it imports the warm volume from &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" target="_blank" rel="noopener"
 &gt;Part 3&lt;/a&gt;, puts compute in front of it, and replays the shipped log to the end of the archive. In PostgreSQL and MySQL tests the worst replay failures were silent, so a restore ends on a position check against the archive, not on an exit code.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" &gt;Part 3&lt;/a&gt; left a hydrated, tagged data volume in the DR region with nothing attached to it, and the WAL or binlog waiting in the S3 archive. This part covers the flip to &lt;code&gt;live&lt;/code&gt;, the replay that follows it, and the two places where the tooling reported a finished restore that wasn&amp;rsquo;t.&lt;/p&gt;
&lt;h2 id="flip-the-cluster-to-live"&gt;Flip the cluster to live
&lt;/h2&gt;&lt;p&gt;The flip is the same module applied with the region&amp;rsquo;s mode set to &lt;code&gt;live&lt;/code&gt;. Until now Terraform has never held the DR region&amp;rsquo;s data volume, because the state machine kept replacing it. The flip takes it over in one apply: a lookup finds the volume by its tags, an &lt;a class="link" href="https://developer.hashicorp.com/terraform/language/import" target="_blank" rel="noopener"
 &gt;&lt;code&gt;import&lt;/code&gt; block&lt;/a&gt; brings it into state, and an instance is launched in front of it.&lt;/p&gt;
&lt;p&gt;The lookup filters on &lt;code&gt;ReadyAt&lt;/code&gt;, the tag on the volume, not on the tracker&amp;rsquo;s record, since the record can already name a newer copy whose volume is still being built. The cluster&amp;rsquo;s first region never received a copy and starts with an empty volume, and the tracker&amp;rsquo;s parameter tells the two cases apart:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;span class="lnt"&gt;27
&lt;/span&gt;&lt;span class="lnt"&gt;28
&lt;/span&gt;&lt;span class="lnt"&gt;29
&lt;/span&gt;&lt;span class="lnt"&gt;30
&lt;/span&gt;&lt;span class="lnt"&gt;31
&lt;/span&gt;&lt;span class="lnt"&gt;32
&lt;/span&gt;&lt;span class="lnt"&gt;33
&lt;/span&gt;&lt;span class="lnt"&gt;34
&lt;/span&gt;&lt;span class="lnt"&gt;35
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-hcl" data-lang="hcl"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;locals&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; compute&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; var.mode&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;live&amp;#34;&lt;/span&gt;&lt;span class="c1"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt; # A region that has received DR copies restores from one; the first region starts empty.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; from_dr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; local.compute &amp;amp;&amp;amp; data.aws_ssm_parameter.dr_copy.value !&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;none&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}&lt;span class="c1"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# The volume Part 3&amp;#39;s state machine built, found by its tags.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;data&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;aws_ebs_volume&amp;#34; &amp;#34;ready&amp;#34;&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;local&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from_dr&lt;/span&gt; &lt;span class="err"&gt;?&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt; &lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; most_recent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;true&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;filter&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;tag:DrSet&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; values&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;var&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;cluster&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;filter&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;tag-key&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; values&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;ReadyAt&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;import&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; for_each&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; local.from_dr ? { data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;aws_ebs_volume&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;ready&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="k"&gt;id&lt;/span&gt; } &lt;span class="err"&gt;:&lt;/span&gt; {}
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; to&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;aws_ebs_volume&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;each&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;value&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;aws_ebs_volume&amp;#34; &amp;#34;data&amp;#34;&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;local&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;compute&lt;/span&gt; &lt;span class="err"&gt;?&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt; &lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; availability_zone&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;var&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;availability_zone&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;local&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from_dr&lt;/span&gt; &lt;span class="err"&gt;?&lt;/span&gt; &lt;span class="k"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;aws_ebs_volume&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;ready&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="k"&gt;size&lt;/span&gt; &lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="k"&gt;var&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;data_size_gib&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; snapshot_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;local&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from_dr&lt;/span&gt; &lt;span class="err"&gt;?&lt;/span&gt; &lt;span class="k"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;aws_ebs_volume&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;ready&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="k"&gt;snapshot_id&lt;/span&gt; &lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;lifecycle&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; ignore_changes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;snapshot_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;tags&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The instance and the volume attachment sit under the same &lt;code&gt;compute&lt;/code&gt; gate. A region flipped straight from &lt;code&gt;cold&lt;/code&gt; has no tagged volume yet, so the state machine runs there once first and the initialization lands inside the RTO.&lt;/p&gt;
&lt;p&gt;The flip itself is the decision to fail over, and it belongs to a person. A wrong automatic failover leaves two primaries and a split write history, which costs far more than the minutes spent reading dashboards. A hand-run runbook keeps judgment at every step but drifts from the infrastructure it describes. A stack that the weekly drill flips to &lt;code&gt;live&lt;/code&gt; cannot drift that way.&lt;/p&gt;
&lt;p&gt;&lt;img alt="On a declared DR event or the weekly drill, a person flips the cluster’s entry to live and the same cluster block is applied; the warm volume from Part 3 is imported by its tags, the instance launches and attaches it, starts the engine and replays from the log archive, then verifies its end position against the archive; alarms watch archive age, archive coverage of the oldest set, the position metric and drill RTO, and page a human" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-4-database-dr-restore/restore-chain.svg"&gt;&lt;/p&gt;
&lt;p&gt;From there the host restores itself. The boot script starts the engine in recovery, replays the shipped log, and publishes its position to CloudWatch once a minute until it reaches the end of the archive. It does this only on the volume&amp;rsquo;s first boot in the region and then tags the volume as restored, so replacing the instance later just starts the engine. A replay that hangs stops publishing, and the alarm below treats missing data as breaching.&lt;/p&gt;
&lt;h2 id="replay-to-the-end-of-the-archive-then-check-where-it-stopped"&gt;Replay to the end of the archive, then check where it stopped
&lt;/h2&gt;&lt;p&gt;The snapshot gives an engine on a crash-consistent set. Everything written after it comes from the log, and both engines can finish that replay short of the archive&amp;rsquo;s end without saying so. I reproduced both cases in Docker, killing a primary under insert load and restoring from a frozen copy of its data directory.&lt;/p&gt;
&lt;p&gt;On PostgreSQL, &lt;code&gt;archive_command&lt;/code&gt; ships only completed WAL segments, which the &lt;a class="link" href="https://www.postgresql.org/docs/current/runtime-config-wal.html" target="_blank" rel="noopener"
 &gt;docs&lt;/a&gt; state plainly. The segment that was being written when the primary died never reached the archive. The restore replayed everything that had, logged &lt;code&gt;archive recovery complete&lt;/code&gt;, and promoted itself about two seconds of writes short, with nothing in the log to hint at it. A &lt;code&gt;pg_receivewal&lt;/code&gt; stream keeps that last segment as a &lt;code&gt;.partial&lt;/code&gt; file, and pointing &lt;code&gt;restore_command&lt;/code&gt; at it as a fallback brought the restore to within one transaction of the primary.&lt;/p&gt;
&lt;p&gt;On MySQL the trap is the exit code. After a crash the newest binlog file usually ends mid-event, and &lt;code&gt;mysqlbinlog&lt;/code&gt; reports that with exit status 1. A file damaged in the middle of the archive produces the same status and the same error text, and &lt;code&gt;mysqlbinlog&lt;/code&gt; stops there without reading the files after it. One case is a normal crash. The other is a hole that silently drops every write after it.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The exit code can&amp;#39;t tell these apart&lt;/strong&gt;
 &lt;div&gt;A boot script that fails on any non-zero exit pages on every real disaster, and one that ignores it can promote a server missing hours of writes. Check the archive instead. On MySQL, every closed binlog ends in a &lt;code&gt;Rotate&lt;/code&gt; event naming its successor, and after replay &lt;code&gt;gtid_executed&lt;/code&gt; reaches the last complete transaction in the newest file. On PostgreSQL, the position where redo finished matches the newest segment in the archive.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="alarm-on-the-archive"&gt;Alarm on the archive
&lt;/h2&gt;&lt;p&gt;Part 3&amp;rsquo;s alarms say whether the warm volume is recent. Nothing there says whether the log reaches back to it, so these are custom metrics, published by Part 3&amp;rsquo;s sweep and by the drill, with thresholds taken from the plan:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Metric&lt;/th&gt;
 &lt;th&gt;Published by&lt;/th&gt;
 &lt;th&gt;Threshold comes from&lt;/th&gt;
 &lt;th&gt;Missing data&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;age of newest object in the log archive&lt;/td&gt;
 &lt;td&gt;sweep&lt;/td&gt;
 &lt;td&gt;the RPO, minus the time it takes to respond&lt;/td&gt;
 &lt;td&gt;breaching&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;archive covers the oldest retained set (0 or 1)&lt;/td&gt;
 &lt;td&gt;sweep&lt;/td&gt;
 &lt;td&gt;oldest set&amp;rsquo;s start time vs oldest log object, plus a gap check&lt;/td&gt;
 &lt;td&gt;breaching&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;replay position&lt;/td&gt;
 &lt;td&gt;boot script, every minute while replaying&lt;/td&gt;
 &lt;td&gt;any gap over a minute means the replay hung&lt;/td&gt;
 &lt;td&gt;breaching&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;drill RTO&lt;/td&gt;
 &lt;td&gt;drill run&lt;/td&gt;
 &lt;td&gt;the RTO target&lt;/td&gt;
 &lt;td&gt;breaching&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The archive-age alarm assumes the primary is writing. An idle PostgreSQL primary stops switching segments, since &lt;code&gt;archive_timeout&lt;/code&gt; only fires after database activity, and an idle MySQL primary leaves its binlog untouched. A heartbeat row updated every minute makes the metric measure the pipeline instead of the traffic.&lt;/p&gt;
&lt;p&gt;Coverage is the alarm to build first. A retained snapshot set is worth something only if the archive reaches back to it without a gap. The usual ways to lose that are a lifecycle rule on the log bucket that expires objects sooner than the snapshots, and a shipper restarted from the wrong file. Both stay silent until a restore runs out of log, and the warning above shows that even then the failure may look normal. The sweep already lists everything the check needs: the oldest log object predates the oldest set, segment names are consecutive, and every closed binlog ends in a &lt;code&gt;Rotate&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="drill-the-chain-weekly-and-keep-its-numbers"&gt;Drill the chain weekly and keep its numbers
&lt;/h2&gt;&lt;p&gt;A scheduled rule runs the same module in &lt;code&gt;live&lt;/code&gt; mode, as a separate Terragrunt unit in an isolated network, and destroys it once the checks have published. The drill never imports the standing warm volume. A replay writes to its volume, and the next real failover needs one that has never been restored. So the drill switches the lookup and the import off, builds its own volume from the recorded copy, and also runs with its own server ID and with archiving off.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;A drill that archives can redirect the next restore&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;archive_command&lt;/code&gt; travels in the primary&amp;rsquo;s configuration along with &lt;code&gt;restore_command&lt;/code&gt;. On PostgreSQL, a drill that kept it wrote a new timeline into the shared archive, and a later restore followed that timeline by default, because &lt;code&gt;recovery_target_timeline&lt;/code&gt; defaults to &lt;code&gt;latest&lt;/code&gt;, and came back missing the primary&amp;rsquo;s newest writes. Drills run with &lt;code&gt;archive_mode = off&lt;/code&gt;, the bucket denies writes from the drill&amp;rsquo;s role, and &lt;code&gt;live&lt;/code&gt; mode sets &lt;code&gt;recovery_target_timeline = 'current'&lt;/code&gt;.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The boot script stamps each stage (instance up, engine accepting connections, replay done, position verified), so a weekly chart shows which stage is growing. Together with Part 3&amp;rsquo;s tracker, that yields the four numbers Part 2 left open. Copy time comes from the &lt;code&gt;copySnapshot&lt;/code&gt; events. The freeze window comes from DLM&amp;rsquo;s script events. Shipping lag is the archive age at the primary&amp;rsquo;s busiest hour. Replay rate is log bytes over the replay stage&amp;rsquo;s duration.&lt;/p&gt;
&lt;p&gt;Replay rate is the one Part 2&amp;rsquo;s interval decision was waiting for. Take the RTO left after launch and initialization, divide by the replay rate, and you have the most log a restore can afford to replay. That is the snapshot interval.&lt;/p&gt;</description></item><item><title>Separating Storage From Compute on EC2, Part 3: Terraform and Warm DR Volumes</title><link>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/</link><pubDate>Sun, 25 Oct 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Separating Storage From Compute on EC2, Part 3: Terraform and Warm DR Volumes" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;One Terraform module, with a mode per region, describes the database cluster everywhere it can run, so a DR copy cannot drift from the primary. In the DR region, automation turns each new snapshot copy into a hydrated volume with no compute in front of it and tags it ready, and that is all a restore needs to find; the log comes from S3. The restore itself is Part 4.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-2-dr-snapshots-and-log-shipping/" &gt;Part 2&lt;/a&gt; left off with Data Lifecycle Manager copying multi-volume snapshot sets of the database host into a second region. What lands there is a copy of the data volume&amp;rsquo;s snapshot, with its own ID, its own completion time and its own best-effort event, while the WAL or binlog keeps arriving in the S3 archive on its own. Nothing in the service creates a volume from the copy, makes it fast in that region, or says when it is safe to attach. The gap between the copy landing and a volume existing that a restore can attach is this post, and it starts with where the definition of the cluster lives, because that decides whether the DR region is a copy of production or a second thing to maintain.&lt;/p&gt;
&lt;h2 id="one-cluster-block-for-every-environment"&gt;One cluster block for every environment
&lt;/h2&gt;&lt;p&gt;The primary database host is described in Terraform somewhere: instance type, AMI lookup, instance profile, security groups, volumes, DNS record, and the engine configuration that Part 2 already put &lt;code&gt;restore_command&lt;/code&gt; into. If that same module also describes every DR copy, a copy in another region is the same module applied there with a different mode. The point of doing it this way is to stay &lt;a class="link" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank" rel="noopener"
 &gt;DRY&lt;/a&gt;, and the reason that matters here more than it does for ordinary infrastructure is drift. A DR copy that lives in its own configuration gets the kernel parameter, the volume layout change, the new engine flag, a quarter after the primary does, or never, and nobody finds out until the day the copy has to carry production. One definition for all of them removes the place where that drift would live.&lt;/p&gt;
&lt;p&gt;What the definition describes is a cluster, not a list of instances. The key is the cluster&amp;rsquo;s name, each entry under it is keyed by a region the cluster can run in, and the only thing an entry says is the state the cluster is in there right now. There is no &lt;code&gt;primary&lt;/code&gt; or &lt;code&gt;secondary&lt;/code&gt; in the block on purpose: those are roles, and a role is what the mode already expresses, so naming them separately would only create a second place for the two to disagree. The mode names are nothing special either. &lt;code&gt;cold&lt;/code&gt;, &lt;code&gt;warm&lt;/code&gt; and &lt;code&gt;live&lt;/code&gt; are what this series needs; a &lt;code&gt;replica&lt;/code&gt; that keeps a streaming standby up, or a &lt;code&gt;paused&lt;/code&gt; that stops the instance and keeps the volumes, is the same block and one more branch in the module. This post uses &lt;code&gt;warm&lt;/code&gt; and &lt;code&gt;live&lt;/code&gt;, and &lt;code&gt;cold&lt;/code&gt; is in the example to show where the copies land:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-hcl" data-lang="hcl"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# One cluster. Each entry is a region it can run in and its state there:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# cold - snapshot copies and the log archive land here; nothing is restored
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# warm - a volume exists, built from the newest snapshot copy; no compute
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# live - compute up, volume attached, engine replayed and promoted
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;test-sql&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; us-west-1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; { mode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;live&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; us-east-1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; { mode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;warm&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; eu-west-1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt; { mode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;cold&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;With Terragrunt this comes out as one &lt;code&gt;terragrunt.hcl&lt;/code&gt; per environment, each with its own copy of the block and all of them calling the same module. Production is the only environment that needs more than one entry: live in one region, warm in a second as a standing standby, cold in a third where the copies land. Dev and QA carry a single &lt;code&gt;live&lt;/code&gt; entry, because nobody is going to fail over a dev database, and the module does not care how many entries it is given. Where production is actually up is then a matter of flipping modes.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;cold&lt;/code&gt;, backups are shipped to the region and nothing else happens there. The stack creates only what has to exist before the day it is needed, the subnet and security group, the instance profile, the log archive bucket, and the parameter the tracker writes into, and no restore ever runs. &lt;code&gt;warm&lt;/code&gt;, us-east-1 above, adds the automation that keeps a volume built from the newest snapshot copy and hydrated, with no compute in front of it, so the slow part of a restore is already paid for when the day comes. &lt;code&gt;live&lt;/code&gt; adds the instance, attaches the volume, replays the log from the archive and promotes, and that is Part 4&amp;rsquo;s subject. The one real difference between the regions is where the data volume comes from. On the primary it is an ordinary volume that Terraform created with the cluster. In a warm region it is built from the newest snapshot copy, and knowing which copy that is, and when it is usable, is where EventBridge comes in.&lt;/p&gt;
&lt;p&gt;One ownership rule makes the rest of this workable: Terraform never holds a warm volume. The automation below replaces that volume every time a new copy lands, and a resource that changes underneath Terraform on every copy would show up as drift in every plan. So the warm volume belongs to the automation, and everything a restore needs to know about it is written in its tags: the cluster, the role, the snapshot it came from, and when it became ready. Terraform finds it by those tags and imports it in the same apply that flips the region to &lt;code&gt;live&lt;/code&gt;, which is Part 4. From then on it is production&amp;rsquo;s volume, and Terraform owns it the way it owns the primary&amp;rsquo;s.&lt;/p&gt;
&lt;p&gt;The mode gates resources inside one apply; it does not pick a pipeline. Terraform runs on two triggers, both in Part 4: a person flipping a region to &lt;code&gt;live&lt;/code&gt;, and the weekly drill on a schedule. A new copy landing in a &lt;code&gt;warm&lt;/code&gt; region runs no Terraform at all. The state machine below handles it by calling the EC2 API directly.&lt;/p&gt;
&lt;p&gt;That split is a choice, not a requirement. If every resource has to live in your IaC, the same EventBridge rule can call your build server instead, TeamCity or Jenkins or GitHub Actions through an EventBridge API destination, and have it run Terraform (or whatever handles your infrastructure) against a volume resource built from the copy&amp;rsquo;s snapshot ID. The volume is then in state from the start, and Part 4 needs no import. The cost is that the build server becomes part of the DR path, and an apply runs on every copy with no commit behind it. This series takes the AWS-native route.&lt;/p&gt;
&lt;h2 id="eventbridge-decides-when-a-copy-is-usable"&gt;EventBridge decides when a copy is usable
&lt;/h2&gt;&lt;p&gt;When a cross-region copy finishes, EBS emits a &lt;code&gt;copySnapshot&lt;/code&gt; event in the destination region. The &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-cloud-watch-events.html" target="_blank" rel="noopener"
 &gt;EBS EventBridge reference&lt;/a&gt; documents it with a &lt;code&gt;detail-type&lt;/code&gt; of &lt;code&gt;EBS Snapshot Notification&lt;/code&gt;, a &lt;code&gt;result&lt;/code&gt; of &lt;code&gt;succeeded&lt;/code&gt; or &lt;code&gt;failed&lt;/code&gt;, the copy&amp;rsquo;s ARN in &lt;code&gt;snapshot_id&lt;/code&gt;, and the source snapshot&amp;rsquo;s ARN in &lt;code&gt;source&lt;/code&gt;. What it doesn&amp;rsquo;t carry is anything about the volume the copy will become: whether it is the newest copy of this cluster&amp;rsquo;s data volume, whether anything fast has been enabled on it in this region, or whether a volume built from it is ready to attach.&lt;/p&gt;
&lt;p&gt;There is a second caveat that shapes everything downstream. The &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/monitor-cloudwatch-events.html" target="_blank" rel="noopener"
 &gt;DLM monitoring page&lt;/a&gt; says these events &amp;ldquo;are emitted on a best effort basis,&amp;rdquo; and the &lt;a class="link" href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-troubleshooting.html" target="_blank" rel="noopener"
 &gt;EventBridge troubleshooting guide&lt;/a&gt; adds that &amp;ldquo;in rare cases, the same rule can run more than once for a single event.&amp;rdquo; Put those together and the handler is going to see some events twice and some events never. Anything built on top of it has to be fine with both.&lt;/p&gt;
&lt;p&gt;&lt;img alt="In the DR region, each copySnapshot event goes through an EventBridge rule to a tracker Lambda that records the newest completed copy in Parameter Store, with a scheduled reconciler catching missed events; a Step Functions execution per copy moves Fast Snapshot Restore onto it, creates a volume from it with no compute in front of it, waits for initialization and tags the volume ReadyAt; alarms watch DLM’s failure metrics and the age of that tag" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/warm-volume-chain.svg"&gt;&lt;/p&gt;
&lt;p&gt;The rule itself is small, and it is the pattern the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/using_lambda.html" target="_blank" rel="noopener"
 &gt;EBS docs&lt;/a&gt; themselves use for acting on snapshot events. It matches successful copies, and a second rule with &lt;code&gt;&amp;quot;result&amp;quot;: [&amp;quot;failed&amp;quot;]&lt;/code&gt; goes straight to an SNS topic so somebody hears about a copy that didn&amp;rsquo;t make it. Every field here is from the documented event:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-json" data-lang="json"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;source&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;aws.ec2&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;detail-type&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;EBS Snapshot Notification&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;detail&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;event&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;copySnapshot&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;result&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;succeeded&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The event has no tags, so the handler describes the copy. Two of Part 2&amp;rsquo;s tags are there, &lt;code&gt;DrSet&lt;/code&gt; naming the cluster and the volume&amp;rsquo;s &lt;code&gt;role&lt;/code&gt;, both static. The per-run timestamp is not: DLM resolves variable tags such as &lt;code&gt;$(timestamp)&lt;/code&gt; on the source snapshot only and, per &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-ami-policy.html" target="_blank" rel="noopener"
 &gt;its own docs&lt;/a&gt;, &amp;ldquo;does not propagate them to cross-Region or cross-account copies, even when tag copying is enabled.&amp;rdquo; So the copy&amp;rsquo;s identity is the two static tags, its order is its own &lt;code&gt;StartTime&lt;/code&gt;, and what the handler wants is the data copy, &lt;code&gt;completed&lt;/code&gt;, started later than the one recorded. If so it writes the copy&amp;rsquo;s snapshot ID to Parameter Store, the value the state machine below reads. Anything else, a duplicate, an older copy, the wrong role, changes nothing.&lt;/p&gt;
&lt;p&gt;&lt;img alt="The tracker, on every copySnapshot event and every 15 minutes: describe the copy, stop unless it is the data role, completed and newer than the record, write its snapshot ID to Parameter Store, stop if an execution is already running for the cluster, otherwise start one named after the snapshot ID; the state it reads is owned by Parameter Store, Step Functions and the volume’s tags" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/tracker-flow.svg"&gt;&lt;/p&gt;
&lt;p&gt;Then it starts one Step Functions execution per copy, named after the snapshot ID, unless one is already running for the cluster, in which case the running one re-reads the record when it finishes. &lt;a class="link" href="https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;StartExecution&lt;/code&gt;&lt;/a&gt; refuses a duplicate name, so a second event cannot start a second execution. The handler owns no state; it reads Parameter Store, Step Functions and the volume&amp;rsquo;s tags and acts on what it finds, with reserved concurrency of one because Parameter Store has no conditional write. What the execution does is the next section.&lt;/p&gt;
&lt;p&gt;Best-effort delivery means you also need a way to look without being nudged. A scheduled rule runs the same Lambda every 15 minutes with no event payload at all, and it lists the tagged copies and does the same computation. The event path keeps the record fresh within seconds; the sweep is what makes it correct on the days an event never shows up, and if it finds a completed copy with no execution for it, it starts one. That Lambda is the only one in the design, and it finishes in seconds, because everything that has to wait happens somewhere else.&lt;/p&gt;
&lt;h2 id="from-the-copy-to-a-warm-volume"&gt;From the copy to a warm volume
&lt;/h2&gt;&lt;p&gt;A volume created from a snapshot is usable immediately and slow until its blocks have come down from S3, and Part 2 priced the two ways of dealing with that: Fast Snapshot Restore on the snapshot, or a provisioned initialization rate on the volume. What Part 2 could not do is apply either one in the DR region, because DLM&amp;rsquo;s FSR rule only names zones in the policy&amp;rsquo;s own region. So the DR region does it itself, and because every step waits on something that reports progress only through a best-effort event, the work is a Step Functions Standard workflow, one execution per copy: &lt;a class="link" href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EnableFastSnapshotRestores.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;EnableFastSnapshotRestores&lt;/code&gt;&lt;/a&gt; on the copy, poll &lt;code&gt;DescribeFastSnapshotRestores&lt;/code&gt; until &lt;code&gt;enabled&lt;/code&gt;, create a volume from the copy with &lt;code&gt;CreateVolume&lt;/code&gt; and wait for it to become available, wait for it to initialize, tag it &lt;code&gt;ReadyAt&lt;/code&gt;, then delete the previous volume and disable FSR on the previous copy. Every wait has a &lt;code&gt;TimeoutSeconds&lt;/code&gt;, so a copy that never gets there fails loudly, and the execution history answers &amp;ldquo;why is the warm region a day old&amp;rdquo; without a log search.&lt;/p&gt;
&lt;p&gt;How long that takes is not the same twice: copy time follows the change rate, FSR&amp;rsquo;s &lt;code&gt;optimizing&lt;/code&gt; runs about an hour per TiB, and volume creation and initialization add their own variance, so copy-to-ready is anywhere from twenty minutes to a few hours. With hourly copies the next one can land mid-execution, which is why the tracker never starts a second execution for the same cluster. The running one re-reads the record after tagging and, if a newer copy has landed, starts the next execution itself; copies in between are skipped. Its last state also publishes its own duration, which the alarm threshold is built from.&lt;/p&gt;
&lt;p&gt;The order matters in one place. Disabling the previous copy&amp;rsquo;s FSR before the new one reads &lt;code&gt;enabled&lt;/code&gt; would be the natural shortcut, and it leaves a window with nothing fast to restore from, because a freshly enabled snapshot spends a while in &lt;code&gt;optimizing&lt;/code&gt; with an empty credit bucket. During the overlap two of the five FSR snapshots a region allows by default are in use, which leaves room for two clusters per region before the quota has to be raised.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Only the data volume crosses the region&lt;/strong&gt;
 &lt;div&gt;Part 1 put the log on its own volume and Part 2 snapshotted both at one instant. The DR region does not need the log volume&amp;rsquo;s copy, because the log is already there: Part 2 ships WAL or binlogs to the S3 archive continuously, and Part 4 replays from it. That holds on one condition. Crash recovery runs before any archive replay, and its inputs have to be on the data volume or reachable from it. On PostgreSQL they are reachable: &lt;code&gt;recovery.signal&lt;/code&gt; makes the server fetch WAL through &lt;code&gt;restore_command&lt;/code&gt; from the snapshot&amp;rsquo;s checkpoint onward, so the archive has to reach back at least that far, which the coverage alarm in Part 4 checks. On MySQL they are not: InnoDB&amp;rsquo;s redo log has to be on the data volume, in the same snapshot, because binlog replay cannot stand in for redo. A MySQL layout with redo on the log volume needs that volume in the set, and then everything in this post is done for a pair, with one extra step: the copies carry no shared run tag, so pairing them means following the &lt;code&gt;copySnapshot&lt;/code&gt; event&amp;rsquo;s &lt;code&gt;source&lt;/code&gt; ARN back to the source snapshots and reading &lt;code&gt;$(timestamp)&lt;/code&gt; there.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The other route is to pre-create the volume from every new copy with a &lt;code&gt;VolumeInitializationRate&lt;/code&gt; (100 to 300 MiB/s, per the &lt;a class="link" href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;CreateVolume&lt;/code&gt; reference&lt;/a&gt;); EBS sends an &lt;code&gt;initializeVolume&lt;/code&gt; event within five minutes of it finishing, and the execution&amp;rsquo;s wait polls for it since the documented example spells the value with a leading space. At the &lt;a class="link" href="https://aws.amazon.com/ebs/pricing/" target="_blank" rel="noopener"
 &gt;pricing page&amp;rsquo;s&lt;/a&gt; example rate of $0.0036 per GiB at 300 MiB/s, re-initializing a 1 TiB volume every four hours is around $660 a month before storage, against the $540 a month Part 2 worked out for one FSR-enabled snapshot in one zone, and initializing only at restore time costs about $3.69 per TiB with the whole initialization inside the RTO. Pre-created and kept current is what the cluster block calls &lt;code&gt;warm&lt;/code&gt;. The state machine creates it from the snapshot ID in the tracker&amp;rsquo;s record rather than asking for the most recent snapshot, through Step Functions&amp;rsquo; &lt;a class="link" href="https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html" target="_blank" rel="noopener"
 &gt;SDK integration&lt;/a&gt; for EC2, so no Lambda sits in the path. The tags go on in the same call, so the volume never exists without the cluster and the copy it came from written on it:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-json" data-lang="json"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="s2"&gt;&amp;#34;CreateVolume&amp;#34;&lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Type&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;Task&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Resource&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;arn:aws:states:::aws-sdk:ec2:createVolume&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Parameters&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;AvailabilityZone.$&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$.availabilityZone&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;SnapshotId.$&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$.snapshotId&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;VolumeType&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;gp3&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;TagSpecifications&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ResourceType&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;volume&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Tags&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;DrSet&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value.$&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$.cluster&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;role&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;data&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;SourceSnapshot&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value.$&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$.snapshotId&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;}]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ResultPath&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$.volume&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Next&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;WaitForAvailable&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Terraform&amp;rsquo;s part in a warm region is small. It creates the parameter the tracker writes into, and leaves the value alone:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-hcl" data-lang="hcl"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Created in cold mode; the tracker writes the value, so Terraform must not.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;aws_ssm_parameter&amp;#34; &amp;#34;dr_copy&amp;#34;&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;/dr/${var.cluster}/snapshot&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; type&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;String&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;none&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt; lifecycle { ignore_changes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;value&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Two rules carry more weight than their size suggests, because they are &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/" &gt;Part 1&lt;/a&gt;&amp;rsquo;s argument applied to a region that is not live yet: the volume is the durable thing, and what sits in front of it can change. The state machine deletes the previous warm volume only after the new one is tagged &lt;code&gt;ReadyAt&lt;/code&gt;, so the region is never without a ready volume. And once a region is live, nothing replaces its volume again. The copy rule that starts the state machine exists only in &lt;code&gt;cold&lt;/code&gt; and &lt;code&gt;warm&lt;/code&gt;, so the flip to &lt;code&gt;live&lt;/code&gt; removes it in that region, and the volume Part 4 imported cannot be swapped out from under production.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;ReadyAt&lt;/code&gt; tag is written last, only when the volume is initialized, and it lives on the volume next to the &lt;code&gt;SourceSnapshot&lt;/code&gt; tag set at creation, so that a lookup by &lt;code&gt;tag:DrSet&lt;/code&gt; plus &lt;code&gt;tag-key = ReadyAt&lt;/code&gt; returns a ready volume and says since when. It is separate from the tracker&amp;rsquo;s record on purpose: the two disagree for the minutes between a copy landing and its volume existing, and a flip to &lt;code&gt;live&lt;/code&gt; must not land in that gap, so Part 4 looks for the tag, not the record. The tracker decides, the state machine completes, the sweep repairs.&lt;/p&gt;
&lt;p&gt;A failed execution leaves the previous volume in place and still tagged, so a restore always finds the last good one. What it can leave behind is a half-built volume with the cluster&amp;rsquo;s &lt;code&gt;DrSet&lt;/code&gt; tag and no &lt;code&gt;ReadyAt&lt;/code&gt;. Only one execution runs per cluster, so the next one can safely delete any such volume before it starts, and it is worth building that in before the night it is needed.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Warm is optional&lt;/strong&gt;
 &lt;div&gt;Everything in this section exists to take initialization out of the RTO. If the RTO has room for it, &lt;code&gt;cold&lt;/code&gt; is enough: the copies land, the tracker keeps the record, the execution still moves FSR onto each new copy, and a flip straight to &lt;code&gt;live&lt;/code&gt; first runs one execution that builds and tags a volume, paying for initialization once, at about $3.69 per TiB at the top rate, with the whole thing inside the clock. Part 2&amp;rsquo;s arithmetic says how much room that takes: data size over the initialization rate, added to the replay time, against the RTO. If the sum fits, the warm volume is storage and FSR hours spent on a problem the plan does not have.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;What the standby costs depends on the mode. &lt;code&gt;cold&lt;/code&gt; is a few dollars a month of standing resources. &lt;code&gt;warm&lt;/code&gt; adds the volume&amp;rsquo;s storage and, each time a new copy lands, either the initialization charge or the FSR hours from above, plus a few state transitions at &lt;a class="link" href="https://aws.amazon.com/step-functions/pricing/" target="_blank" rel="noopener"
 &gt;$0.000025 each&lt;/a&gt;, well under a cent per copy, while the compute still does not exist until someone asks for it.&lt;/p&gt;
&lt;h2 id="alarm-on-the-volume-not-the-snapshot"&gt;Alarm on the volume, not the snapshot
&lt;/h2&gt;&lt;p&gt;DLM does publish its own &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/monitor-dlm-cw-metrics.html" target="_blank" rel="noopener"
 &gt;CloudWatch metrics&lt;/a&gt;, in the &lt;code&gt;AWS/EBS&lt;/code&gt; namespace under a &lt;code&gt;DLMPolicyId&lt;/code&gt; dimension, in the policy&amp;rsquo;s region. Four of them deserve an alarm at anything above zero: &lt;code&gt;SnapshotsCreateFailed&lt;/code&gt;, &lt;code&gt;PreScriptFailed&lt;/code&gt;, &lt;code&gt;PostScriptFailed&lt;/code&gt; and &lt;code&gt;SnapshotsCopiedRegionFailed&lt;/code&gt;. Be aware that the last one &amp;ldquo;includes unsuccessful retries within 24 hours from the scheduled time,&amp;rdquo; so a failed copy can take a day to show up. &lt;code&gt;ResourcesTargeted&lt;/code&gt; dropping below the number you expect catches the quietest failure DLM has, which is a database instance that lost its tag and is now getting no snapshots and no errors. The &lt;code&gt;DLM Policy State Change&lt;/code&gt; event, with &lt;code&gt;state&lt;/code&gt; &lt;code&gt;ERROR&lt;/code&gt; and a &lt;code&gt;cause&lt;/code&gt; string, can go to the same SNS topic as the failed-copy rule.&lt;/p&gt;
&lt;p&gt;None of that says anything about the DR region, though. Whether the warm volume holds a recent copy is written on the volume itself, and the sweep publishes two metrics from it on every run. The first is the age of the &lt;code&gt;ReadyAt&lt;/code&gt; tag, which says how long since the warm volume was last rebuilt. Its threshold is the snapshot interval plus DLM&amp;rsquo;s one-hour start window plus the p95 of the execution-duration metric over the last two weeks, which CloudWatch computes for you; for the first week, until there is a history, it is the sum of the copy time from the &lt;code&gt;copySnapshot&lt;/code&gt; event&amp;rsquo;s &lt;code&gt;startTime&lt;/code&gt; and &lt;code&gt;endTime&lt;/code&gt; and the docs&amp;rsquo; hour per TiB for FSR, and it will be wrong in one direction or the other. The second metric is how many completed data copies are newer than the one in the volume&amp;rsquo;s &lt;code&gt;SourceSnapshot&lt;/code&gt; tag, which the sweep already lists. It is normally zero or one, it climbs when executions fail or fall behind, and it is the one that pages, because a warm volume that is two copies behind is a plan that has quietly stopped working while the age graph still looks healthy. A failed execution goes to the same SNS topic through the status-change event Step Functions emits to EventBridge, so a copy that got stuck is a page and not a slowly aging graph. The missing-data setting matters as much as the threshold. CloudWatch gives you &lt;a class="link" href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/alarms-and-missing-data.html" target="_blank" rel="noopener"
 &gt;four options&lt;/a&gt; and defaults to &lt;code&gt;missing&lt;/code&gt;, which means a sweep that died shows up as a gap in a graph that nobody is looking at. Setting it to &lt;code&gt;breaching&lt;/code&gt; turns that gap into a page. Each metric runs &lt;a class="link" href="https://aws.amazon.com/cloudwatch/pricing/" target="_blank" rel="noopener"
 &gt;$0.30 a month and each alarm $0.10&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The topic itself is a convenience, not a requirement. Four senders page in this design, the failed-copy rule, the DLM policy event, the alarms and the execution failures, and one SNS topic gives them a single destination whose subscribers can change without touching any producer. If alerting already lives on EventBridge, the same four can land on one rule, since alarm state changes are events too, with an API destination calling the pager directly. What matters is that every failure ends at the same place, not which service that place is.&lt;/p&gt;
&lt;p&gt;That lag is the number to watch for this half of the plan. If it is zero, the warm volume was built from the newest copy, FSR has moved onto it, and the tag says when. Whether the log archive reaches back to that copy, and what the engine does when it is finally put in front of that volume, is Part 4.&lt;/p&gt;</description></item><item><title>Separating Storage From Compute on EC2, Part 2: DR Snapshots and Log Shipping</title><link>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-2-dr-snapshots-and-log-shipping/</link><pubDate>Sun, 11 Oct 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-2-dr-snapshots-and-log-shipping/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Separating Storage From Compute on EC2, Part 2: DR Snapshots and Log Shipping" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Amazon Data Lifecycle Manager can run the whole snapshot half of DR for self-managed PostgreSQL and MySQL on EC2: multi-volume snapshot sets on a schedule, pre and post scripts, cross-region copy and retention, with no charge for the service itself. It stops at the snapshot: the restore, the hydration and the log replay are yours, and they set the RTO (&lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" target="_blank" rel="noopener"
 &gt;Part 3&lt;/a&gt; gets the volumes ready and Part 4 does the restore). DLM covers EBS only, so Elasticsearch, Kafka and Redis keep the DR mechanisms &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/" target="_blank" rel="noopener"
 &gt;Part 1&lt;/a&gt; describes.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/" &gt;Part 1&lt;/a&gt; moved the data of self-managed databases onto EBS, split the log onto its own volume, and left the DR plan as a snapshot schedule plus a hydration rate. This part builds that plan for PostgreSQL and MySQL around Amazon Data Lifecycle Manager (DLM), which the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-lifecycle.html" target="_blank" rel="noopener"
 &gt;EBS docs&lt;/a&gt; describe as a backup solution for EC2 instances and EBS volumes &amp;ldquo;at no additional cost&amp;rdquo; (snapshot storage and inter-region transfer are billed as usual). Since &lt;a class="link" href="https://aws.amazon.com/about-aws/whats-new/2023/11/amazon-data-lifecycle-manager-pre-post-script-automation-ebs-snapshots/" target="_blank" rel="noopener"
 &gt;November 2023&lt;/a&gt; it also runs pre and post scripts through Systems Manager around each snapshot.&lt;/p&gt;
&lt;p&gt;What it produces is a set of snapshots sitting in a second region. Nothing in it creates a volume, starts a database, replays a log, or tells anyone how long those take.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;Use AWS Backup instead&amp;rdquo; is the usual first answer, and for part of the job it&amp;rsquo;s right. AWS Backup takes the same crash-consistent &lt;a class="link" href="https://docs.aws.amazon.com/aws-backup/latest/devguide/multi-volume-crash-consistent.html" target="_blank" rel="noopener"
 &gt;multi-volume backups&lt;/a&gt; of an instance and, per its &lt;a class="link" href="https://docs.aws.amazon.com/aws-backup/latest/devguide/backup-feature-availability.html" target="_blank" rel="noopener"
 &gt;feature table&lt;/a&gt;, adds vault lock, restore testing, organization-wide policies and the &lt;a class="link" href="https://docs.aws.amazon.com/aws-backup/latest/devguide/logicallyairgappedvault.html" target="_blank" rel="noopener"
 &gt;logically air-gapped vault&lt;/a&gt; that can be shared to a recovery account through AWS RAM. Its application-consistent path for EC2 is Windows VSS; DLM&amp;rsquo;s scripts are the Linux equivalent. So: DLM for the frequent, script-wrapped DR sets, AWS Backup for the one copy that has to survive a compromised account. Neither solves the restore. AWS Backup&amp;rsquo;s &lt;a class="link" href="https://docs.aws.amazon.com/aws-backup/latest/devguide/restore-testing.html" target="_blank" rel="noopener"
 &gt;restore testing&lt;/a&gt; times a job that ends when the volume exists. Hydration and replay happen after that line.&lt;/p&gt;
&lt;p&gt;&lt;img alt="The DLM policy in the primary region runs a pre-script, takes a multi-volume snapshot set of the data and log volumes, runs a post-script to thaw I/O, and copies the set to the DR region; log shipping runs continuously to a log archive in the DR region; the restore chain in the DR region (create volumes, launch and attach, start the engine, replay the log, first query) is built and timed by the operator" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-2-dr-snapshots-and-log-shipping/dlm-dr-flow.svg"&gt;&lt;/p&gt;
&lt;h2 id="point-one-policy-at-the-database-host"&gt;Point one policy at the database host
&lt;/h2&gt;&lt;p&gt;The policy that matters targets instances, not volumes. &lt;code&gt;ResourceTypes: INSTANCE&lt;/code&gt; &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-ami-policy.html" target="_blank" rel="noopener"
 &gt;creates multi-volume snapshot sets&lt;/a&gt; from every volume on each tagged instance at one instant, which is the crash consistency Part 1&amp;rsquo;s log split depends on; a volume-targeted policy is the split-instant problem all over again. The root volume can be excluded, since the restore boots a fresh AMI, and a volume attached later joins the set at the next run.&lt;/p&gt;
&lt;p&gt;Schedules are the RPO knob. A policy holds up to four, each an interval of 1 to 24 hours or a &lt;a class="link" href="https://docs.aws.amazon.com/dlm/latest/APIReference/API_CreateRule.html" target="_blank" rel="noopener"
 &gt;cron expression&lt;/a&gt;. Every run starts &amp;ldquo;within one hour&amp;rdquo; of its scheduled time, so snapshots alone give an RPO of the interval, plus up to an hour of jitter, plus the copy. Retention is by count (1 to 1,000) or by age.&lt;/p&gt;
&lt;p&gt;Cross-region copy is a per-schedule rule for up to three regions, each with its own retention. Encrypted snapshots stay encrypted, under the destination region&amp;rsquo;s default EBS key unless the rule names a KMS key the DLM role can use. The first copy is full and later ones incremental, per the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/time-based-copies.html" target="_blank" rel="noopener"
 &gt;time-based copy docs&lt;/a&gt;, which also sell a guaranteed completion time of 15 minutes to 48 hours. DLM&amp;rsquo;s &lt;a class="link" href="https://docs.aws.amazon.com/dlm/latest/APIReference/API_CrossRegionCopyRule.html" target="_blank" rel="noopener"
 &gt;copy rule&lt;/a&gt; has no field for it, so a DLM copy finishes when it finishes: [MEASURE: time for one incremental snapshot set (data plus log volume) to complete in the DR region, primary to DR, at the production change rate]. EBS also caps &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-resource-quotas.html" target="_blank" rel="noopener"
 &gt;concurrent snapshot copies&lt;/a&gt; at 20 per destination region, raised only through AWS Support, so a fleet that snapshots on the hour copies in a queue.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;span class="lnt"&gt;27
&lt;/span&gt;&lt;span class="lnt"&gt;28
&lt;/span&gt;&lt;span class="lnt"&gt;29
&lt;/span&gt;&lt;span class="lnt"&gt;30
&lt;/span&gt;&lt;span class="lnt"&gt;31
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-json" data-lang="json"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;PolicyType&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;EBS_SNAPSHOT_MANAGEMENT&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ResourceTypes&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;INSTANCE&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;TargetTags&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;dr-tier&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;pg-main&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;}],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Parameters&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;ExcludeBootVolume&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Schedules&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Name&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;every-4h&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;CopyTags&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;VariableTags&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;SnapSet&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;$(timestamp)&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;}],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;TagsToAdd&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Key&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;DrSet&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Value&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;pg-main&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;}],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;CreateRule&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Interval&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;IntervalUnit&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;HOURS&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Times&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;00:15&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Scripts&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Stages&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;PRE&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;POST&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ExecutionHandlerService&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;AWS_SYSTEMS_MANAGER&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ExecutionHandler&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;pg-freeze-thaw&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ExecuteOperationOnScriptFailure&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;ExecutionTimeout&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;MaximumRetryCount&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;}]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;RetainRule&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Count&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;18&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;CrossRegionCopyRules&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Target&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;us-west-2&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;Encrypted&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;CmkArn&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;arn:aws:kms:us-west-2:111122223333:key/EXAMPLE&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;CopyTags&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;RetainRule&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;Interval&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nt"&gt;&amp;#34;IntervalUnit&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;DAYS&amp;#34;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;}]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;}]&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The tags carry the restore. &lt;code&gt;CopyTags&lt;/code&gt; copies the volumes&amp;rsquo; own tags (a &lt;code&gt;role&lt;/code&gt; of data or log, say) to each snapshot, the cross-region rule carries them to the copy, and &lt;a class="link" href="https://docs.aws.amazon.com/dlm/latest/APIReference/API_Schedule.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;VariableTags&lt;/code&gt;&lt;/a&gt;, valid only on instance policies, stamps each run&amp;rsquo;s snapshots with a shared value so a same-region restore never pairs a data snapshot with a log snapshot from a different run. That shared value stays in the source region: DLM resolves variable tags on the source snapshot only and, per &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-ami-policy.html" target="_blank" rel="noopener"
 &gt;its docs&lt;/a&gt;, does not propagate them to cross-Region copies even with tag copying on, so pairing copies in the DR region means following each &lt;code&gt;copySnapshot&lt;/code&gt; event&amp;rsquo;s &lt;code&gt;source&lt;/code&gt; ARN back to the source snapshot&amp;rsquo;s tags. &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" &gt;Part 3&lt;/a&gt; sidesteps it by copying only the data volume. Sharing to another account works only under a customer-managed key, and copying inside that account takes a second, &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/event-policy.html" target="_blank" rel="noopener"
 &gt;event-based policy&lt;/a&gt; there.&lt;/p&gt;
&lt;p&gt;Protection is the gap. DLM has no snapshot-lock setting, and &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-lock-concepts.html" target="_blank" rel="noopener"
 &gt;snapshot lock&lt;/a&gt; (launched &lt;a class="link" href="https://aws.amazon.com/about-aws/whats-new/2023/11/amazon-ebs-snapshot-lock/" target="_blank" rel="noopener"
 &gt;November 15, 2023&lt;/a&gt;, no extra charge) is applied per snapshot. Governance mode can be lifted by anyone with the IAM permission; compliance mode, after an optional 1 to 72 hour cooling-off, holds until the lock expires or the account closes. Locking a DLM-created snapshot by hand takes it out of DLM&amp;rsquo;s management, so whatever locks it also owns deleting it. &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-concepts.html" target="_blank" rel="noopener"
 &gt;Recycle Bin&lt;/a&gt; is the cheaper backstop: a region-level rule keeps deleted snapshots for 1 to 365 days at normal rates and can be &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-lock.html" target="_blank" rel="noopener"
 &gt;locked&lt;/a&gt; with a 7 to 30 day unlock delay. It also catches every snapshot DLM expires, so each retention cycle is paid for one extra bin period.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The archive tier sits outside any RTO&lt;/strong&gt;
 &lt;div&gt;Archived snapshots are full rather than incremental, carry a 90-day minimum, and take &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive-considerations.html" target="_blank" rel="noopener"
 &gt;up to 72 hours&lt;/a&gt; to come back before any volume can be created from them. DLM archives only from volume-targeted policies on a schedule of 28 days or more, and never archives cross-region copies. It&amp;rsquo;s a retention tool for monthly sets, never a recovery path.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="freeze-the-filesystems-then-find-the-log-position"&gt;Freeze the filesystems, then find the log position
&lt;/h2&gt;&lt;p&gt;Scripts need the SSM Agent on the instance, the &lt;code&gt;AWSDataLifecycleManagerSSMFullAccess&lt;/code&gt; policy on the DLM role, and a &lt;code&gt;DLMScriptsAccess:true&lt;/code&gt; tag on the SSM document. For MySQL and PostgreSQL there&amp;rsquo;s no AWS-managed document; the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/automate-app-consistent-backups.html" target="_blank" rel="noopener"
 &gt;app-consistent snapshot docs&lt;/a&gt; publish samples you create as your own. Both skip &lt;code&gt;/&lt;/code&gt; and &lt;code&gt;/boot&lt;/code&gt;, run &lt;code&gt;fsfreeze -f&lt;/code&gt; on every other filesystem, and schedule a thaw after 60 seconds in case the post-script never arrives. The PostgreSQL sample runs &lt;code&gt;CHECKPOINT&lt;/code&gt; first. The MySQL sample runs this, then &lt;code&gt;sync&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-bash" data-lang="bash"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;sudo mysql -e &lt;span class="s1"&gt;&amp;#39;FLUSH TABLES WITH READ LOCK;&amp;#39;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="warning-box"&gt;
 &lt;strong&gt;The sample&amp;#39;s lock is gone before the freeze&lt;/strong&gt;
 &lt;div&gt;A global read lock belongs to the session that took it, and &lt;code&gt;mysql -e&lt;/code&gt; closes its session as soon as the statement returns. On MySQL 8.4.11 in Docker, an &lt;code&gt;INSERT&lt;/code&gt; issued from a second session right after that exact command completed in 58 ms; with the lock held in a session that stayed open, the same &lt;code&gt;INSERT&lt;/code&gt; failed on a 5-second &lt;code&gt;lock_wait_timeout&lt;/code&gt;. Whatever consistency the MySQL sample produces comes from &lt;code&gt;fsfreeze&lt;/code&gt; and the multi-volume set. A pre-script that needs the lock through the freeze has to hold a session open in the background and release it from the post-script.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The snapshots restore anyway, because neither engine needs the lock. A multi-volume set is what a power cut would leave, and both engines recover from that by design. The &lt;a class="link" href="https://www.postgresql.org/docs/current/backup-file.html" target="_blank" rel="noopener"
 &gt;PostgreSQL docs&lt;/a&gt; say a frozen snapshot starts up as a crash, and suggest a &lt;code&gt;CHECKPOINT&lt;/code&gt; beforehand &amp;ldquo;to reduce recovery time&amp;rdquo;. For these two engines, then, the scripts buy a shorter crash recovery and filesystems with no half-written metadata. They don&amp;rsquo;t buy correctness. The freeze isn&amp;rsquo;t free, either: every commit blocks while the log volume is frozen, [MEASURE: commit stall on the production host between the PreScriptStarted and PostScriptCompleted metrics].&lt;/p&gt;
&lt;p&gt;Tagging a replica instead of the primary moves that stall off the write path. The freeze then blocks replication apply rather than commits, and the lag it adds is paid at restore time as extra log to replay, not by the application. Two conditions. The replica&amp;rsquo;s position has to be expressible in the primary&amp;rsquo;s log stream, which GTIDs give for free (auto-skip works off the replica&amp;rsquo;s &lt;code&gt;gtid_executed&lt;/code&gt; against the primary&amp;rsquo;s binlogs) and a non-GTID setup does not, since the replica&amp;rsquo;s own binlog coordinates mean nothing against the primary&amp;rsquo;s files; there the pre-script records &lt;code&gt;SHOW REPLICA STATUS&lt;/code&gt; and maps through &lt;code&gt;Exec_Source_Log_Pos&lt;/code&gt;. On PostgreSQL a streaming standby that was never promoted shares the primary&amp;rsquo;s timeline, so its data directory rolls forward from the same archive. And the replica has to be as durably configured as the primary, because a &lt;code&gt;sync_binlog=0&lt;/code&gt; replica snapshots an instant where the binlog trails the redo, which crash recovery resolves by rolling back, so the set is simply a little older than it looks.&lt;/p&gt;
&lt;p&gt;That decides the failure setting. Each script gets a 10 to 120 second timeout and up to three retries, and per the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/script-flow.html" target="_blank" rel="noopener"
 &gt;script flow&lt;/a&gt;, when the pre-script still fails DLM either takes a crash-consistent set or skips the instance for that run. Enable the fallback: the set is recoverable, and a skipped run widens the RPO by a full interval. DLM records which happened in &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/dlm-script-tags.html" target="_blank" rel="noopener"
 &gt;system tags&lt;/a&gt; (&lt;code&gt;aws:dlm:pre-script&lt;/code&gt; and &lt;code&gt;aws:dlm:post-script&lt;/code&gt;, &lt;code&gt;SUCCESS&lt;/code&gt; or &lt;code&gt;FAILED&lt;/code&gt;) and a &lt;code&gt;PreScriptFailed&lt;/code&gt; &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/dlm-script-monitoring.html" target="_blank" rel="noopener"
 &gt;CloudWatch metric&lt;/a&gt; worth an alarm.&lt;/p&gt;
&lt;p&gt;Those two tags are all DLM writes. There&amp;rsquo;s no way to attach a script&amp;rsquo;s output, an LSN or a binlog coordinate, to the snapshot. Neither engine needs it, provided the set is atomic, because the position is already on the volumes.&lt;/p&gt;
&lt;p&gt;PostgreSQL keeps it in &lt;code&gt;pg_control&lt;/code&gt;. Restore the set, create &lt;code&gt;recovery.signal&lt;/code&gt;, and set a &lt;code&gt;restore_command&lt;/code&gt; pointing at the WAL archive (it&amp;rsquo;s ignored outside recovery, so it can live in the primary&amp;rsquo;s config and travel with every snapshot). The server runs crash recovery from the last checkpoint, then keeps fetching archived WAL. The test, on PostgreSQL 17.11 in Docker, used a stand-in for a crash-consistent EBS set: a copy of the data directory taken while &lt;code&gt;docker pause&lt;/code&gt; froze the container mid-insert, with more rows committed and archived afterwards. The restore logged &lt;code&gt;redo starts at 0/20000A0&lt;/code&gt;, &lt;code&gt;consistent recovery state reached at 0/43224B8&lt;/code&gt;, two segments &lt;code&gt;restored ... from archive&lt;/code&gt;, and &lt;code&gt;archive recovery complete&lt;/code&gt;. Every row committed on the source after the copy was there.&lt;/p&gt;
&lt;p&gt;MySQL with GTIDs works the same way through &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/replication-gtids-concepts.html" target="_blank" rel="noopener"
 &gt;auto-skip&lt;/a&gt;: a server ignores any transaction whose GTID it has already committed. The same frozen-copy test on MySQL 8.4.11 restored to 1,533 rows of a running insert stream and a &lt;code&gt;gtid_executed&lt;/code&gt; of &lt;code&gt;1-519&lt;/code&gt;. Piping every shipped binlog through &lt;code&gt;mysqlbinlog&lt;/code&gt; into it, from the first file, skipped what it had and applied the rest, finishing at 18,000 rows and &lt;code&gt;1-6009&lt;/code&gt;, identical to the source. Without GTIDs the pre-script has to capture &lt;code&gt;SHOW BINARY LOG STATUS&lt;/code&gt; under a lock it actually holds, and write it to a file on the data volume so the snapshot carries it.&lt;/p&gt;
&lt;p&gt;The atomic part is not optional. An earlier MySQL run copied the data directory file by file while the inserts ran, so the redo and the binlog were captured at different moments. After crash recovery and a full binlog replay it came back 84 rows short, while &lt;code&gt;gtid_executed&lt;/code&gt; listed every transaction as applied. Auto-skip had skipped 28 transactions the restored server never had. No error, no warning. That is the &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/" &gt;split-instant failure&lt;/a&gt; Part 1 warned about, and the reason the policy above targets the instance and not the volumes.&lt;/p&gt;
&lt;h2 id="ship-the-log-to-the-dr-region"&gt;Ship the log to the DR region
&lt;/h2&gt;&lt;p&gt;Snapshots every four hours mean an RPO of four hours and change. Shipping the log continuously cuts it to the shipping lag, and the restore becomes the snapshot set plus a replay.&lt;/p&gt;
&lt;p&gt;On PostgreSQL the classic route is &lt;code&gt;archive_command&lt;/code&gt;, which only runs for completed 16 MB segments, so a quiet server sits on unarchived commits unless &lt;a class="link" href="https://www.postgresql.org/docs/current/runtime-config-wal.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;archive_timeout&lt;/code&gt;&lt;/a&gt; forces a switch. pgBackRest&amp;rsquo;s &lt;code&gt;archive-push&lt;/code&gt; and WAL-G&amp;rsquo;s &lt;code&gt;wal-push&lt;/code&gt; both send segments to a bucket in the DR region. &lt;a class="link" href="https://www.postgresql.org/docs/current/app-pgreceivewal.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;pg_receivewal&lt;/code&gt;&lt;/a&gt;, run on a DR-region host, streams WAL &amp;ldquo;in real time as it&amp;rsquo;s being generated&amp;rdquo; instead. It needs a replication slot to avoid gaps, and a slot whose receiver is down retains WAL on the primary until the disk fills, unless &lt;code&gt;max_slot_wal_keep_size&lt;/code&gt; caps it.&lt;/p&gt;
&lt;p&gt;On MySQL the equivalent is a host in the DR region running &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/mysqlbinlog-backup.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;mysqlbinlog&lt;/code&gt;&lt;/a&gt; as a live backup:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-bash" data-lang="bash"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;mysqlbinlog --read-from-remote-server --host&lt;span class="o"&gt;=&lt;/span&gt;primary.internal --raw &lt;span class="se"&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; --stop-never --connection-server-id&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="m"&gt;9001&lt;/span&gt; binlog.000130
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;It writes each binlog under its original name as events arrive. It &amp;ldquo;does not automatically reconnect&amp;rdquo; after a blip or a primary restart, so it runs under a supervisor that restarts it from the newest file it holds, and it stores encrypted binlogs unencrypted. The files go to S3 on whatever schedule the RPO tolerates.&lt;/p&gt;
&lt;p&gt;Either way the archive has to reach back to the oldest snapshot set still retained in the DR region, or that set can&amp;rsquo;t be rolled forward. The lag is the RPO, and only a measurement gives it: [MEASURE: WAL archive or binlog stream lag at the primary&amp;rsquo;s peak write rate].&lt;/p&gt;
&lt;h2 id="pay-for-hydration-in-time-or-in-money"&gt;Pay for hydration in time or in money
&lt;/h2&gt;&lt;p&gt;A volume created from a snapshot is usable at once and slow until every block has come down from S3, at a default rate that per the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/initalize-volume.html" target="_blank" rel="noopener"
 &gt;initialization docs&lt;/a&gt; &amp;ldquo;fluctuates throughout the initialization process&amp;rdquo;. Two things make it predictable.&lt;/p&gt;
&lt;p&gt;The provisioned initialization rate is chosen at &lt;code&gt;create-volume&lt;/code&gt;, 100 to 300 MiB/s, delivered within 10 percent of the rate 99 percent of the time. Time is the snapshot&amp;rsquo;s data size over the rate: 1 TiB at 300 MiB/s is about 58 minutes. The charge is per GiB of snapshot data at the &lt;a class="link" href="https://aws.amazon.com/ebs/pricing/" target="_blank" rel="noopener"
 &gt;pricing page&lt;/a&gt; rate, once per restore. A region allows 5,000 MiB/s across concurrent requests by default, so 16 volumes at the top rate, and it isn&amp;rsquo;t available for volume copies.&lt;/p&gt;
&lt;p&gt;&lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-fast-snapshot-restore.html" target="_blank" rel="noopener"
 &gt;Fast Snapshot Restore&lt;/a&gt; creates the volume fully initialized, at $0.75 per hour per snapshot per AZ in us-east-1 with a one-hour minimum ($540 a month for one snapshot in one AZ, per the docs). A region allows five FSR-enabled snapshots by default, and each snapshot-and-AZ pair has a &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/volume-creation-credits.html" target="_blank" rel="noopener"
 &gt;credit bucket&lt;/a&gt; that starts empty, refills at &lt;code&gt;MIN(10, 1024 ÷ size in GiB)&lt;/code&gt; credits an hour and holds &lt;code&gt;MAX(1, MIN(10, 1024 ÷ size))&lt;/code&gt;. A 2,048 GiB snapshot earns half a credit an hour and holds one, so the first fast volume is two hours after enabling, on top of the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-ami-policy.html" target="_blank" rel="noopener"
 &gt;60 minutes per TiB&lt;/a&gt; DLM&amp;rsquo;s docs give for optimization.&lt;/p&gt;
&lt;p&gt;DLM can enable FSR on the snapshots it creates, but its &lt;a class="link" href="https://docs.aws.amazon.com/dlm/latest/APIReference/API_FastRestoreRule.html" target="_blank" rel="noopener"
 &gt;rule&lt;/a&gt; names AZs in the policy&amp;rsquo;s own region, and a copy of an FSR-enabled snapshot is not FSR-enabled. For DR that means automation in the DR region enabling it on each new copy and disabling it on the one before, with the credit clock restarting each time. A data-plus-log set in one AZ is $1.50 an hour, about $1,080 a month, around the clock.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;Time to full speed&lt;/th&gt;
 &lt;th&gt;Cost&lt;/th&gt;
 &lt;th&gt;Catch&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Default&lt;/td&gt;
 &lt;td&gt;unpredictable&lt;/td&gt;
 &lt;td&gt;none&lt;/td&gt;
 &lt;td&gt;the RTO has no number&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Provisioned rate&lt;/td&gt;
 &lt;td&gt;data size ÷ 100–300 MiB/s&lt;/td&gt;
 &lt;td&gt;per GiB, once per restore&lt;/td&gt;
 &lt;td&gt;not for volume copies&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;FSR on the DR copy&lt;/td&gt;
 &lt;td&gt;at creation&lt;/td&gt;
 &lt;td&gt;$0.75/hour per snapshot per AZ, continuously&lt;/td&gt;
 &lt;td&gt;credits, 5 per region, your own automation&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;If both are set, the provisioned rate wins and FSR is ignored. The engine can start before initialization finishes, so the real question is how much slower replay runs against blocks still in S3: [MEASURE: replay rate (GB of WAL or binlog per minute) on a volume still initializing versus one fully initialized, same instance type].&lt;/p&gt;
&lt;h2 id="pick-the-interval-from-the-replay-rate"&gt;Pick the interval from the replay rate
&lt;/h2&gt;&lt;p&gt;Everything above except four numbers comes out of the AWS docs, and the four are the plan. The copy time is how far behind the DR region runs. The freeze stall, or the apply lag it adds on a replica, is how often the schedule can fire without the application noticing. The shipping lag is the RPO. The replay rate on a volume still pulling blocks from S3 is the one that decides the snapshot interval, and it is the one to measure first.&lt;/p&gt;
&lt;p&gt;A longer interval is nearly free everywhere else. Snapshot sets are incremental, so a daily set stores about the same changed blocks as six four-hour sets; the copy queue and the freeze run once a day instead of six times; the shipped log covers the RPO either way. What a longer interval buys is replay: every hour between snapshots is more WAL or binlog that one recovery process applies, serially, before the first query runs. RDS lands on a daily snapshot with five-minute log uploads, and replays on a fully provisioned instance. On a volume created at the default rate the same day of log can take much longer, which is why the measurement has to be taken on the volume type and initialization rate the plan will pay for, with the log written just before a scheduled snapshot so it is the worst case. The interval that keeps that replay inside the RTO is the one the policy gets.&lt;/p&gt;</description></item><item><title>Separating Storage From Compute on EC2, Part 1: Move the Volume, Not the Data</title><link>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/</link><pubDate>Sat, 10 Oct 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Separating Storage From Compute on EC2, Part 1: Move the Volume, Not the Data" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;For a self-managed storage system on EC2 (a relational database, a Kafka broker, an Elasticsearch node, a Redis replica), moving EBS volumes is far faster and cheaper than draining a node and refilling its replacement over the network: a resize or a replacement reattaches the data, and an OS upgrade swaps only the root volume while the data volumes stay attached. The price is a network hop on every fsync, one EBS ceiling per instance that every volume shares, and snapshot hydration inside the DR plan&amp;rsquo;s RTO.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This is the first of four posts on running self-managed stateful systems on EC2 (PostgreSQL and MySQL, Kafka, Elasticsearch and OpenSearch, Redis with persistence on) with storage and compute separated. This one covers why; Part 2 covers how the DR side gets built on AWS, &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" &gt;Part 3&lt;/a&gt; lays out the Terraform and gets a warm volume into the DR region, and Part 4 restores and replays onto it.&lt;/p&gt;
&lt;p&gt;The two storage options behave very differently. Instance-store NVMe is physically attached to the host, fast, and ephemeral: per the &lt;a class="link" href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-store-lifetime.html" target="_blank" rel="noopener"
 &gt;AWS docs&lt;/a&gt;, its data does not survive a stop, a hibernation, a host retirement, or an automatic recovery, and the blocks are cryptographically erased. EBS is network-attached block storage with its own lifecycle. A volume outlives the instance it&amp;rsquo;s attached to, detaches and reattaches, snapshots incrementally to S3, and changes size and performance while mounted. When the data is on the instance, every instance event becomes a data event. When it&amp;rsquo;s on EBS, most of them become a reattach.&lt;/p&gt;
&lt;h2 id="why-not-the-managed-service"&gt;Why not the managed service
&lt;/h2&gt;&lt;p&gt;The managed services are the obvious alternative: RDS or Aurora, Amazon MSK, Amazon OpenSearch Service, ElastiCache. Aurora is the extreme form of this post&amp;rsquo;s argument (the &lt;a class="link" href="https://www.amazon.science/publications/amazon-aurora-design-considerations-for-high-throughput-cloud-native-relational-databases" target="_blank" rel="noopener"
 &gt;SIGMOD 2017 paper&lt;/a&gt; pushes redo processing into a storage service so compute holds almost no state), and for plenty of teams it&amp;rsquo;s the correct call. The reasons to stay on EC2 are concrete. I/O-heavy workloads cost far more on a managed service, and AWS&amp;rsquo;s own pricing admits it: &lt;a class="link" href="https://aws.amazon.com/about-aws/whats-new/2023/05/amazon-aurora-i-o-optimized/" target="_blank" rel="noopener"
 &gt;Aurora I/O-Optimized&lt;/a&gt; (May 2023) drops per-I/O charges and is pitched at clusters where I/O exceeds 25 percent of the Aurora bill. A multi-cloud estate, or a team that won&amp;rsquo;t be locked to one vendor, keeps the engine, its tooling, and the runbooks portable; EBS is AWS-specific, but the same split works on GCP Persistent Disk or Azure Managed Disks. Then there are builds the service doesn&amp;rsquo;t offer (Percona Server, a patched PostgreSQL, Elasticsearch past 7.10, the last version &lt;a class="link" href="https://aws.amazon.com/opensearch-service/faqs/" target="_blank" rel="noopener"
 &gt;Amazon OpenSearch Service runs&lt;/a&gt;), plugins outside the allow-list, kernel tuning, and constraints a managed service can&amp;rsquo;t accommodate. Without one of those, the managed service usually wins.&lt;/p&gt;
&lt;h2 id="reattach-the-volume-instead-of-draining-the-node"&gt;Reattach the volume instead of draining the node
&lt;/h2&gt;&lt;p&gt;The alternative to moving a volume is draining a node, and every system has its own version. Elasticsearch excludes the node from allocation and &lt;a class="link" href="https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/cluster-level-shard-allocation-routing-settings" target="_blank" rel="noopener"
 &gt;relocates its shards&lt;/a&gt; to the rest of the cluster. Kafka reassigns the broker&amp;rsquo;s partitions with a plan the &lt;a class="link" href="https://kafka.apache.org/43/operations/basic-kafka-operations/" target="_blank" rel="noopener"
 &gt;operations docs&lt;/a&gt; say has to be written by hand for a decommission, usually under a replication throttle (the docs&amp;rsquo; example is 50 MB/s between brokers) so the move doesn&amp;rsquo;t starve producers. Zalando&amp;rsquo;s Kafka team &lt;a class="link" href="https://engineering.zalando.com/posts/2017/10/reattaching-kafka-ebs-in-aws.html" target="_blank" rel="noopener"
 &gt;put the cost at&lt;/a&gt; around 6–7 hours of rebalancing for one broker lost with its disk. A relational database builds a new replica and fails over to it. Redis does a &lt;a class="link" href="https://redis.io/docs/latest/operate/oss_and_stack/management/replication/" target="_blank" rel="noopener"
 &gt;full sync&lt;/a&gt;, snapshotting the whole dataset on the primary and shipping it. Every one of them copies the node&amp;rsquo;s whole dataset across the network while the cluster carries the extra load, and a rolling replacement of Elasticsearch or Kafka nodes on local disk pays it twice per node: once to drain the old node, once to fill the new one.&lt;/p&gt;
&lt;p&gt;Moving the volume copies nothing. Stop the process cleanly, detach, attach to the new instance, start. PostgreSQL and MySQL come up without recovery after a clean shutdown, and an unclean stop costs only a log replay.&lt;/p&gt;
&lt;p&gt;OS patching doesn&amp;rsquo;t even need a new instance once the OS lives on its own volume. EC2&amp;rsquo;s &lt;a class="link" href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/replace-root.html" target="_blank" rel="noopener"
 &gt;root volume replacement&lt;/a&gt; swaps the root volume of a running instance for one built from a new AMI and reboots it. Per the docs, the data EBS volumes stay attached, instance-store data survives (temp directories included), and the instance stays on the same host with the same network interfaces, IP addresses, and DNS name. To the rest of the cluster the node was briefly away and came back on the same address with the same data. Two conditions apply. The data directory must not sit on the root volume, which the replacement detaches. And the AMI must match the instance&amp;rsquo;s architecture, so a move to Graviton is still a new instance and a volume move.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Three ways to move a node: draining copies the whole dataset out to the cluster and back into the new node, reattaching moves the EBS data volume to a new instance and copies nothing, and root volume replacement swaps only the root volume on the same instance while the data stays attached and the old root is kept for rollback" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/reattach-vs-drain.svg"&gt;&lt;/p&gt;
&lt;p&gt;Resizing is the same move: an &lt;code&gt;r7i.4xlarge&lt;/code&gt; that ran out of memory becomes an &lt;code&gt;r7i.8xlarge&lt;/code&gt; and the data stays put. Compute gets sized for CPU and memory, never for disk. For Redis, memory includes persistence headroom: the &lt;a class="link" href="https://redis.io/docs/latest/operate/oss_and_stack/management/admin/" target="_blank" rel="noopener"
 &gt;admin guide&lt;/a&gt; warns that a write-heavy instance can use up to twice its normal memory while the forked child writes an RDB or rewrites the AOF.&lt;/p&gt;
&lt;p&gt;A Kafka broker that comes back on its old volumes, under the same broker identity, holds every segment it had and fetches only what was produced while it was gone. Zalando&amp;rsquo;s &lt;a class="link" href="https://engineering.zalando.com/posts/2017/10/reattaching-kafka-ebs-in-aws.html" target="_blank" rel="noopener"
 &gt;result&lt;/a&gt; was a lost broker recovered &amp;ldquo;in a number of minutes without copying data,&amp;rdquo; and an upgrade of 15 brokers in two hours, 42 times faster than before. An Elasticsearch node that returns with its data inside the delayed-allocation window gets its shards back &amp;ldquo;with the minimum of network traffic,&amp;rdquo; per the &lt;a class="link" href="https://www.elastic.co/docs/deploy-manage/distributed-architecture/shard-allocation-relocation-recovery/delaying-allocation-when-node-leaves" target="_blank" rel="noopener"
 &gt;delayed allocation docs&lt;/a&gt;. The default is one minute, shorter than most instance launches, so a planned swap raises it first.&lt;/p&gt;
&lt;p&gt;Redis is the odd one: a replica shut down cleanly keeps its replication offset in its snapshot file and can resume where it left off, while one restarting from its append-only log reloads from the volume and takes a full sync anyway.&lt;/p&gt;
&lt;p&gt;Storage changes are online. &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-modify-volume.html" target="_blank" rel="noopener"
 &gt;Elastic Volumes&lt;/a&gt; grows size, IOPS, and throughput on a volume while it serves traffic. Nothing shrinks, so oversizing is a one-way door.&lt;/p&gt;
&lt;p&gt;Engine upgrades are the same root swap, because the binaries live on the root volume and the data doesn&amp;rsquo;t. Bake the new PostgreSQL, MySQL, Kafka, Elasticsearch, or Redis version into the AMI, replace the root volume, and the process starts on the new version against the same data directory. For a minor version that&amp;rsquo;s the whole job. A major version also converts the data on disk, which is where the rollback below comes in. The one move that does need a copy is crossing Availability Zones, since an EBS volume lives in one: snapshot it, create a volume from the snapshot in the target AZ, attach.&lt;/p&gt;
&lt;p&gt;Major versions get the rollback neither relational engine provides. The &lt;a class="link" href="https://www.postgresql.org/docs/current/pgupgrade.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;pg_upgrade&lt;/code&gt; docs&lt;/a&gt; say that in link mode, once the new cluster has started, the old one is unsafe and must be restored from backup. MySQL 8.0 to 8.4 upgrades the data dictionary in place on first start, and the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/downgrading.html" target="_blank" rel="noopener"
 &gt;downgrade docs&lt;/a&gt; allow going back only by logical dump and load or replication. Root volume replacement can keep the old root volume instead of deleting it, so the rollback is swapping that volume back in and restoring the data volume from a snapshot taken after a clean shutdown. Upgrade a pre-warmed copy of the data volume, not the original, or the rollback waits on hydration.&lt;/p&gt;
&lt;p&gt;Each of these moves has one trap on the PostgreSQL side.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Attaching a PostgreSQL data volume to an instance with a newer C library can silently corrupt every text index on it. PostgreSQL collates through glibc by default, and glibc 2.28 rewrote the sort order for most locales; per the &lt;a class="link" href="https://wiki.postgresql.org/wiki/Locale_data_changes" target="_blank" rel="noopener"
 &gt;PostgreSQL wiki&lt;/a&gt;, B-tree indexes on &lt;code&gt;text&lt;/code&gt;, &lt;code&gt;varchar&lt;/code&gt;, &lt;code&gt;char&lt;/code&gt;, and &lt;code&gt;citext&lt;/code&gt; built under the old rules must be reindexed before the instance takes production traffic. &lt;a class="link" href="https://docs.aws.amazon.com/linux/al2023/ug/glibc-gcc-and-binutils.html" target="_blank" rel="noopener"
 &gt;Amazon Linux 2 ships glibc 2.26 and AL2023 ships 2.34&lt;/a&gt;, and AL2 &lt;a class="link" href="https://aws.amazon.com/amazon-linux-2/faqs/" target="_blank" rel="noopener"
 &gt;reached end of support on June 30, 2026&lt;/a&gt;, so &amp;ldquo;new AMI, reattach the volume&amp;rdquo; this year crosses that line. The symptom is a &lt;code&gt;UNIQUE&lt;/code&gt; index admitting duplicates and lookups missing rows that exist. Pin the OS major version of database AMIs or put the &lt;code&gt;REINDEX&lt;/code&gt; in the cut-over plan, and consider ICU collations, which carry a version PostgreSQL can check. MySQL ships its own collations and doesn&amp;rsquo;t inherit this from the OS, though its collations do move between MySQL versions, &lt;a class="link" href="https://explainanalyze.com/p/collation-drift-the-silent-index-killer/" target="_blank" rel="noopener"
 &gt;a different trap&lt;/a&gt;.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="split-the-io-then-hit-the-instance-ceiling"&gt;Split the I/O, then hit the instance ceiling
&lt;/h2&gt;&lt;p&gt;Once the data is on volumes, nothing says it has to be on one. Separate volumes give each write stream its own IOPS budget and its own queue.&lt;/p&gt;
&lt;p&gt;The relational engines have the finest controls. PostgreSQL can put WAL on one volume, the data directory on another, and give a hot table, a large index, or the current partitions of a time-series table a tablespace of their own. MySQL goes further: binlog, redo, undo, and doublewrite can each sit on their own volume, and &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-create-table-external.html" target="_blank" rel="noopener"
 &gt;individual tables or partitions&lt;/a&gt; can live outside the data directory. The win is isolation as much as aggregate. A commit waits on a log fsync, and on its own volume that fsync doesn&amp;rsquo;t queue behind a checkpoint flushing gigabytes of dirty pages. A durable MySQL commit syncs both redo and binlog, and separate volumes keep the two from contending.&lt;/p&gt;
&lt;p&gt;Kafka and Elasticsearch moved in opposite directions on the same idea. Kafka can spread a broker&amp;rsquo;s log across several directories; per the &lt;a class="link" href="https://kafka.apache.org/43/operations/hardware-and-os/" target="_blank" rel="noopener"
 &gt;hardware docs&lt;/a&gt;, partitions are assigned round-robin across directories and each sits entirely in one, so an uneven partition mix means uneven disks. JBOD under KRaft left early access &lt;a class="link" href="https://kafka.apache.org/blog/2024/07/29/apache-kafka-3.8.0-release-announcement/" target="_blank" rel="noopener"
 &gt;in Kafka 3.8&lt;/a&gt; (July 2024). Elasticsearch &lt;a class="link" href="https://www.elastic.co/docs/reference/elasticsearch/configuration-reference/path" target="_blank" rel="noopener"
 &gt;deprecated multiple data paths in 7.13&lt;/a&gt; and recommends one filesystem spanning several disks or one node per data path, which on EC2 means one data volume per node and more nodes.&lt;/p&gt;
&lt;p&gt;The split also enables tiering. Cold partitions go on baseline gp3, and provisioned io2 pays only for hot data. PostgreSQL can move a partition to another tablespace, but the move rewrites it under an exclusive lock, so it suits partitions that no longer take writes. MySQL decides placement when &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/" &gt;the partition rotation&lt;/a&gt; creates the partition; moving it later means a stopped server. Kafka and OpenSearch take the tier off block storage entirely. Kafka&amp;rsquo;s &lt;a class="link" href="https://kafka.apache.org/43/operations/tiered-storage/" target="_blank" rel="noopener"
 &gt;tiered storage&lt;/a&gt;, production-ready &lt;a class="link" href="https://kafka.apache.org/blog/2024/11/06/apache-kafka-3.9.0-release-announcement/" target="_blank" rel="noopener"
 &gt;since 3.9&lt;/a&gt; (November 2024), copies completed log segments to S3 and keeps only the tail on the broker, though not for compacted topics. OpenSearch&amp;rsquo;s &lt;a class="link" href="https://docs.opensearch.org/latest/tuning-your-cluster/availability-and-recovery/remote-store/index/" target="_blank" rel="noopener"
 &gt;remote-backed storage&lt;/a&gt; (2.10) does the same for segments and translog.&lt;/p&gt;
&lt;p&gt;Temp needs no durability, which makes it the natural tenant of local NVMe on instance types that have it. Sort spills, hash joins, and the scratch files of online schema changes run at local-disk speed and stay off the EBS budget, and both PostgreSQL and MySQL can point their temporary files at the instance store. The PostgreSQL docs warn that &lt;a class="link" href="https://www.postgresql.org/docs/current/manage-ag-tablespaces.html" target="_blank" rel="noopener"
 &gt;a tablespace on temporary storage risks the cluster&lt;/a&gt;. One holding only temp files is the survivable exception, provided its directory is recreated on every boot, because instance store comes back empty after any stop.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;The engines fail in opposite directions when that boot step is missing, tested on PostgreSQL 17 and MySQL 8.4 with the temp directory wiped between restarts. MySQL refuses to start, which is loud. PostgreSQL starts normally, fails to create temporary tables, and quietly writes sort spills to the data volume instead, the exact I/O the split was meant to keep off it. Nothing in the startup log says so.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Then the ceiling. Every volume on an instance shares that instance&amp;rsquo;s EBS bandwidth, and it sits lower than the volumes&amp;rsquo; combined limits suggest. Since &lt;a class="link" href="https://aws.amazon.com/about-aws/whats-new/2025/09/amazon-ebs-size-provisioned-performance-gp3-volumes" target="_blank" rel="noopener"
 &gt;September 2025&lt;/a&gt; one &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/general-purpose.html" target="_blank" rel="noopener"
 &gt;gp3 volume&lt;/a&gt; provisions up to 80,000 IOPS and 2,000 MiB/s, and one &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/provisioned-iops.html" target="_blank" rel="noopener"
 &gt;io2 Block Express&lt;/a&gt; volume 256,000 IOPS and 4,000 MiB/s. Per the &lt;a class="link" href="https://docs.aws.amazon.com/ec2/latest/instancetypes/mo.html" target="_blank" rel="noopener"
 &gt;instance tables&lt;/a&gt;, an &lt;code&gt;r7i.8xlarge&lt;/code&gt; gets 40,000 IOPS and 1,250 MB/s in total: one maxed gp3 already exceeds the instance, and a second volume buys isolation, not headroom. Only from &lt;code&gt;r7i.24xlarge&lt;/code&gt; (120,000 IOPS, 3,750 MB/s) do several volumes add up to more than one. Sizes through &lt;code&gt;4xlarge&lt;/code&gt; advertise a burst they hold for 30 minutes a day before dropping to baseline, the same trap as &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-v-disk-has-two-alarms-not-one/" &gt;gp2 burst balance&lt;/a&gt;. Splitting scales I/O and nothing else. A hot row, a replica applier that can&amp;rsquo;t parallelize the primary&amp;rsquo;s writes, PostgreSQL waiting on its WAL write lock, a hot Kafka partition with one leader: none improve with a third volume, and the headroom before sharding or adding nodes ends at a number in the instance-type table.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Bar chart of documented IOPS limits: one maxed gp3 volume at 80,000, two at 160,000, and one io2 Block Express at 256,000, against an r7i.8xlarge ceiling of 40,000 for all volumes combined and an r7i.24xlarge ceiling of 120,000, so most of what is provisioned is unreachable on the smaller instance" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/ebs-ceiling.svg"&gt;&lt;/p&gt;
&lt;p&gt;Latency is the other price, and how much of it a system pays depends on whether it waits for the disk. AWS describes gp3 as &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/general-purpose.html" target="_blank" rel="noopener"
 &gt;single-digit millisecond&lt;/a&gt; and io2 Block Express as under 500 microseconds on average for a 16 KiB I/O; local NVMe has no network hop in the path. The relational engines wait: every commit pays a WAL or redo fsync. Group commit amortizes it across concurrent transactions, so most OLTP never notices, but small serial commits will see their p99 move. Kafka mostly doesn&amp;rsquo;t wait. Its docs &lt;a class="link" href="https://kafka.apache.org/43/operations/hardware-and-os/" target="_blank" rel="noopener"
 &gt;recommend the default flush settings&lt;/a&gt;, which &amp;ldquo;disable application fsync entirely,&amp;rdquo; because &amp;ldquo;a failed node will always recover from its replicas,&amp;rdquo; so EBS latency stays out of the produce path and the volume&amp;rsquo;s job is throughput. Redis sits between them: its default once-a-second fsync runs in the background, but per the &lt;a class="link" href="https://redis.io/docs/latest/operate/oss_and_stack/management/optimization/latency/" target="_blank" rel="noopener"
 &gt;latency guide&lt;/a&gt; a slow one eventually blocks the main thread. Where p99 is set by fsync time and nothing can hide it, a primary on local NVMe with synchronous replicas on NVMe is the better design, and the re-seed window is the price of the latency.&lt;/p&gt;
&lt;h2 id="the-dr-plan-is-a-snapshot-schedule-and-a-hydration-rate"&gt;The DR plan is a snapshot schedule and a hydration rate
&lt;/h2&gt;&lt;p&gt;EBS snapshots are incremental and copy across regions, which supports two shapes of standby in the second region. Cold standby keeps only snapshots; failover creates volumes, launches instances, and attaches. Warm standby keeps volumes already restored from the latest snapshot, with no compute running. Both cost a fraction of a running replica, and both depend on things the cost estimate doesn&amp;rsquo;t show, starting with whether the snapshot is a usable copy at all.&lt;/p&gt;
&lt;p&gt;A snapshot is only a backup if it&amp;rsquo;s consistent, and splitting the log from the data breaks that by default. Snapshot the volumes one at a time and each captures a different instant. The &lt;a class="link" href="https://www.postgresql.org/docs/current/backup-file.html" target="_blank" rel="noopener"
 &gt;PostgreSQL docs&lt;/a&gt; require simultaneous snapshots when data files and WAL sit on different disks, and on MySQL a binlog captured ahead of the redo log produces replicas that diverge from their first minute. EBS can &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-create-snapshots.html" target="_blank" rel="noopener"
 &gt;snapshot several volumes at the same instant&lt;/a&gt;, which gives crash consistency: what a power cut would leave, and what both engines recover from by design. Knowing where that instant sits in the log stream, so a restore can replay forward from it, takes the engine&amp;rsquo;s own backup hooks around the snapshot.&lt;/p&gt;
&lt;p&gt;Some systems don&amp;rsquo;t accept a volume snapshot as a backup at all. Elasticsearch&amp;rsquo;s &lt;a class="link" href="https://www.elastic.co/docs/deploy-manage/tools/snapshot-and-restore" target="_blank" rel="noopener"
 &gt;snapshot docs&lt;/a&gt; call its snapshot API &amp;ldquo;the only reliable and supported way to back up a cluster&amp;rdquo; and rule out restoring from filesystem-level copies. Kafka&amp;rsquo;s cross-region answer is cluster-to-cluster mirroring with &lt;a class="link" href="https://kafka.apache.org/43/operations/geo-replication-cross-cluster-data-mirroring/" target="_blank" rel="noopener"
 &gt;MirrorMaker 2&lt;/a&gt;, since one broker&amp;rsquo;s volume holds only that broker&amp;rsquo;s replicas. Redis treats its RDB file as the DR artifact. For these, EBS carries a node through instance events and the system&amp;rsquo;s own mechanism carries DR. Redis&amp;rsquo;s &lt;a class="link" href="https://redis.io/docs/latest/operate/oss_and_stack/management/replication/" target="_blank" rel="noopener"
 &gt;replication docs&lt;/a&gt; also hold the sharpest version of the instance-store risk: a primary that restarts empty is still a primary, and replicas that sync from it &amp;ldquo;will effectively destroy their copy of the data.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Warm standby isn&amp;rsquo;t warm, either. A volume restored from a snapshot is usable at once, but its blocks &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/ebs-initialize.html" target="_blank" rel="noopener"
 &gt;stay in S3&lt;/a&gt; until first read, and every page arrives with the enthusiasm of a shared drive on hotel Wi-Fi. RTO includes that hydration. It gets paid in time, by reading every block before cutover, or in money, since AWS sells faster initialization. And it starts over on every refresh, so a standby is warm only if something reads it after each one.&lt;/p&gt;
&lt;p&gt;The standby doesn&amp;rsquo;t have to be provisioned for production while it waits. Kept at baseline performance it costs little beyond its gigabytes, and failover attaches compute and raises the volumes to production performance online. The raise isn&amp;rsquo;t instant: the &lt;a class="link" href="https://docs.aws.amazon.com/ebs/latest/userguide/monitoring-volume-modifications.html" target="_blank" rel="noopener"
 &gt;modification docs&lt;/a&gt; put performance changes at &amp;ldquo;a few minutes to a few hours,&amp;rdquo; longer on a volume that was never fully hydrated. Through the change the volume serves at no less than its old performance. That fits an RTO of hours. An RTO of minutes means paying for production performance all the time.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Cold and warm standby failover steps, both waiting on an instance launch, hydration of every block and a performance raise before serving traffic, above a timeline showing that snapshots alone lose every write since the last snapshot while continuous log shipping loses only the shipping lag" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-1-move-the-volume-not-the-data/dr-failover.svg"&gt;&lt;/p&gt;
&lt;p&gt;Recovery point is the other number. Snapshots alone lose everything written since the last one, plus the copy time. Shipping the log continuously to the DR region (WAL archiving on PostgreSQL, binlog streaming on MySQL) shrinks that to the shipping lag, and a restore becomes snapshot plus replay. None of it helps with a write that was wrong when it landed, which every snapshot preserves faithfully; &lt;a class="link" href="https://explainanalyze.com/p/before-the-bad-write/" &gt;that needs a different layer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Separation covers instance failure, host failure, and planned work, and not the storage layer. In the &lt;a class="link" href="https://aws.amazon.com/message/65648/" target="_blank" rel="noopener"
 &gt;April 2011 us-east-1 event&lt;/a&gt;, a misrouted network change set off a re-mirroring storm inside EBS that left about 13 percent of volumes in one AZ stuck for days, beyond reach of any instance replacement. Replacement also depends on the EC2 control plane: in the &lt;a class="link" href="https://aws.amazon.com/message/101925/" target="_blank" rel="noopener"
 &gt;October 2025 us-east-1 outage&lt;/a&gt;, new launches failed from 2:25 to 10:36 AM PDT while running instances kept running. A recovery that starts with a launch is only as available as the launch API. A replica already running elsewhere removes that dependency, but it&amp;rsquo;s compute paid for around the clock, and if the DR side serves no reads it does nothing until the day it&amp;rsquo;s needed, which is the cost a volume-based standby exists to avoid.&lt;/p&gt;
&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-2-dr-snapshots-and-log-shipping/" &gt;Part 2&lt;/a&gt; turns the DR half into an implementation outline: which AWS services schedule and copy the snapshots, how log shipping or the system&amp;rsquo;s own backup API fits alongside them, and the hydration options and what they cost. &lt;a class="link" href="https://explainanalyze.com/p/separating-storage-from-compute-on-ec2-part-3-terraform-and-warm-dr-volumes/" &gt;Part 3&lt;/a&gt; lays out the Terraform for every environment and gets a hydrated volume waiting in the DR region; Part 4 puts compute in front of it, replays the log to the end of the archive, and drills it against a stopwatch.&lt;/p&gt;</description></item><item><title>Talk Is Cheap: Why Nobody Argued With Your Migration Plan</title><link>https://explainanalyze.com/p/talk-is-cheap-why-nobody-argued-with-your-migration-plan/</link><pubDate>Sun, 27 Sep 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/talk-is-cheap-why-nobody-argued-with-your-migration-plan/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Talk Is Cheap: Why Nobody Argued With Your Migration Plan" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A plan that took fifteen minutes to write carries no evidence that the work can be done, so experienced people discount it instead of arguing with it. What makes one credible is the enumeration behind it and a name against turning the old system off; what gets it funded is a payoff denominated in revenue, because nobody buys eighteen months of easier operations. For a database migration the cost has five layers, and most proposals estimate one.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The plan arrives as a markdown file, and it is genuinely good writing:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;Move the fifty MySQL clusters to TiDB. One elastic cluster instead of fifty, horizontal scale when we need it, rolling upgrades, and we stop losing a week a month to patching. The wire protocol is MySQL-compatible, so the application layer barely changes.&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;The engineer who wrote it is good, and is not a database specialist, which is fine. The motivation is the most real thing in the room. Patching fifty clusters across four environments is miserable work, nobody can say with confidence which of the several hundred services depends on which cluster, and every maintenance window is a negotiation with teams who don&amp;rsquo;t reply. They read a well-argued post about someone&amp;rsquo;s TiDB move, spent fifteen minutes with a model filling in the shape of it, and wrote it up.&lt;/p&gt;
&lt;p&gt;The meeting goes fine. The staff engineers nod. The director calls it interesting and asks for a doc. Nothing is funded, nothing is scheduled, and not one technical claim in the plan gets challenged.&lt;/p&gt;
&lt;p&gt;That last part is the part worth explaining, because being ignored and being refuted are different outcomes and the second one is better. A refuted proposal tells you where the wall is. A proposal that draws polite agreement and no money tells you nothing, and the natural read (they&amp;rsquo;re change-averse, they didn&amp;rsquo;t get it, there&amp;rsquo;s no appetite) is almost always wrong. The plan was not rejected on its merits. It was discounted before its merits came up, and the discount is mechanical.&lt;/p&gt;
&lt;h2 id="nobody-argued-because-nobody-had-to"&gt;Nobody argued because nobody had to
&lt;/h2&gt;&lt;p&gt;A product owner once said this out loud, more plainly than any of the theory below. The question put to him was why an obviously beneficial change wasn&amp;rsquo;t getting scheduled. His answer was that I had spent no time on it, and that if I believed in it as much as I was claiming, I would have spent some. He wanted a proof of concept, something that ran. Talk is cheap, he said, and conceptually anything can sound good.&lt;/p&gt;
&lt;p&gt;The second half of that is the part worth keeping. He wasn&amp;rsquo;t saying the idea was wrong, or even that he doubted the claim. He was reading my investment as an estimate of my own confidence, which is a better signal than anything I could have written down, and a harder one to fake. Someone who won&amp;rsquo;t spend two days on a change they say will save the company a week every month has quietly told you their real estimate of the odds, whatever the document says. Proposals get read that way whether or not the reader has the vocabulary for it.&lt;/p&gt;
&lt;p&gt;There is a formal name for the general case. In &lt;a class="link" href="https://econweb.ucsd.edu/~vcrawfor/CrawfordSobel82EMT.pdf" target="_blank" rel="noopener"
 &gt;Crawford and Sobel&amp;rsquo;s 1982 model of strategic information transmission&lt;/a&gt; (&lt;em&gt;Econometrica&lt;/em&gt; 50:6), a message that is costless to send and cannot be verified carries information only to the extent that the sender&amp;rsquo;s and receiver&amp;rsquo;s interests already coincide. Economists call it cheap talk, and the result is not that listeners are hostile. A rational listener extracts close to nothing from an unverifiable claim that cost nothing to make, however well constructed. They don&amp;rsquo;t argue because there is no proposition to argue with yet, only an assertion about a future nobody has priced. The interests don&amp;rsquo;t coincide by default either: the person proposing the migration and the person on call for it in month four are usually not the same person, and everyone in the room knows it.&lt;/p&gt;
&lt;p&gt;None of this is new, and what changed isn&amp;rsquo;t the amount of thought. The older version of this proposal was a link: read this post about how Company X moved off MySQL, with a sentence of framing on top. Fifteen minutes of investment, and everyone could see it was fifteen minutes. The current version is a twelve-page markdown file with a phased rollout, a risk table and a checklist, produced in the same fifteen minutes. The investment didn&amp;rsquo;t go up; the artifact got much better at looking like the output of a month. Which works against the author, because a reader who used to price the effort from the format can&amp;rsquo;t any more, so they stop reading the format and discount by default. The polish removed the last cheap signal the author had.&lt;/p&gt;
&lt;p&gt;Then the harder version, which is the mechanism rather than a comment on anyone&amp;rsquo;s diligence. The plan reads cleanly because of what it leaves out, and it leaves those things out because the author cannot see them yet. Consolidating fifty clusters is easy to write while the fifty clusters are a number. It gets hard once you know that cluster 31 runs a quarterly job with no owner, that the auth service touches four of them inside one transaction, and that two environments are on a version the target won&amp;rsquo;t take. Understanding the dependencies isn&amp;rsquo;t a step the author skipped on the way to the proposal. It&amp;rsquo;s the thing that would have changed the proposal, and usually shrunk it into something smaller, duller, and fundable.&lt;/p&gt;
&lt;p&gt;The obvious response is to make the document better: a cost-benefit table, an exec sponsor, a risk register in an appendix. It doesn&amp;rsquo;t work, because more document is still document and every line is still costless and unverifiable. Weak reasons survive that treatment perfectly well, and they share a tell: they price the layer everyone can see and treat the rest as details. When &lt;a class="link" href="https://www.uber.com/us/en/blog/postgres-to-mysql-migration/" target="_blank" rel="noopener"
 &gt;Uber published its 2016 write-up of moving from Postgres back to MySQL&lt;/a&gt;, the lesson was not a direction of travel but that &amp;ldquo;forward&amp;rdquo; depends on whose workload you are standing in.&lt;/p&gt;
&lt;h2 id="the-price-list"&gt;The price list
&lt;/h2&gt;&lt;p&gt;Here is what the plan is actually proposing, stacked from the layer everyone estimates to the one nobody does. The pair rotates and the shape holds every time. Priced below for MySQL to Postgres, the move with the most public evidence behind it, and treat the five as the floor of an estimate rather than the estimate.&lt;/p&gt;
&lt;h3 id="layer-one-the-query-surface"&gt;Layer one: the query surface
&lt;/h3&gt;&lt;p&gt;This layer is semantic, not syntactic. The queries that throw a syntax error are the safe ones, because the migration stops and makes you fix them. The dangerous class runs on both engines and means something different on each. InnoDB defaults to &lt;code&gt;REPEATABLE READ&lt;/code&gt; with next-key locking and Postgres to &lt;code&gt;READ COMMITTED&lt;/code&gt; with per-statement snapshots, so a transaction ported verbatim takes different locks, and retry logic tuned against gap-lock deadlocks meets conflicts it was never shaped for. A &lt;code&gt;utf8mb4_general_ci&lt;/code&gt; column compares case-insensitively and a &lt;code&gt;text&lt;/code&gt; column does not, so a &lt;code&gt;UNIQUE&lt;/code&gt; index on email quietly changes meaning (that drift inside a single MySQL estate is &lt;a class="link" href="https://explainanalyze.com/p/collation-drift-the-silent-index-killer/" &gt;its own story&lt;/a&gt;). Schemas predating strict mode have tolerated silent truncation and zero-dates for years, so the backfill is where you learn what the old system was accepting, on data that looks fine.&lt;/p&gt;
&lt;p&gt;Which sets the acceptance bar: a query hasn&amp;rsquo;t ported when it runs, it&amp;rsquo;s ported when it returns the same rows. All of that fails silently, so the check is a diff, not a green test suite.&lt;/p&gt;
&lt;h3 id="layer-two-the-coupling-surface"&gt;Layer two: the coupling surface
&lt;/h3&gt;&lt;p&gt;This is the layer that doesn&amp;rsquo;t move with the database. The ORM, the query builders, the raw SQL beside them, the analytics jobs on a replica: all of it grew up expecting a particular engine, and the code around the schema is where the exit gets expensive, which is &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;its own post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;At least the application lives in a repo someone can grep. The coupling that goes unmapped never made it into version control: the crontab calling &lt;code&gt;mysqldump&lt;/code&gt; nightly, the retention script pruning rows at 3am, the &lt;code&gt;mysql -e&lt;/code&gt; one-liners in deploy scripts on a bastion three people know about. Reports hide best, because they run on a cadence. A month of watching the query log catches the weekly ones; the quarterly close fires long after the audit ended, and the first anyone hears is finance asking why the numbers stopped. Then the things the database feeds rather than serves, since a CDC pipeline reading the binlog gets rebuilt against logical decoding rather than repointed. This is where the two-sprint estimate quietly doubles, before a single row has moved.&lt;/p&gt;
&lt;h3 id="layer-three-the-data-move"&gt;Layer three: the data move
&lt;/h3&gt;&lt;p&gt;Moving the schema is easy. Moving data under continuous writes is the project: a backfill, a dual-write phase, a reconciliation process proving the two sides agree, a cutover. Dual-write is the phase that quietly becomes permanent.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Dual-write drift is the failure mode to design against from day one. The moment the application writes to two databases and neither is declared authoritative, any difference between them becomes a third thing you now operate: the reconciliation layer. Left running for months, &amp;ldquo;we&amp;rsquo;re mid-migration&amp;rdquo; hardens into a steady state nobody can call correct without checking. Pick an authoritative side explicitly, make reconciliation a real service with alerting rather than a cron job someone glances at, and treat the drift as data corruption in progress rather than migration bookkeeping.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Reconciliation is a subsystem with an owner, close kin to the &lt;a class="link" href="https://explainanalyze.com/p/scale-the-pattern-not-the-instance/" &gt;cross-instance jobs&lt;/a&gt; that appear whenever two stores have to agree. Cutover is the easy-looking part, and it goes badly when the earlier phases were rushed, because it is where every deferred difference in layer one arrives at once.&lt;/p&gt;
&lt;h3 id="layer-four-the-operational-reset"&gt;Layer four: the operational reset
&lt;/h3&gt;&lt;p&gt;This layer sets the team&amp;rsquo;s intuition back to zero. A group fluent in operating MySQL is, on the day of cutover, a junior team operating Postgres. A decade of index decisions leaned on InnoDB clustering that Postgres heaps do not provide. Postgres forks a backend per connection rather than a thread, making a pooler mandatory on day one rather than an optimization for later. &lt;code&gt;VACUUM&lt;/code&gt;, bloat and transaction-ID wraparound are an operational surface MySQL refugees have never carried, and none of it announces itself until it is a problem. None of this is unsolvable. It is a team relearning operations while carrying a pager.&lt;/p&gt;
&lt;h3 id="layer-five-the-long-tail"&gt;Layer five: the long tail
&lt;/h3&gt;&lt;p&gt;This is the default outcome rather than the failure case. The honest steady state of a large migration is 90% done and staying there, because the last 5% is the part with no clean port, and the economics of finishing it never beat the economics of leaving the old system up for just those callers. The migration didn&amp;rsquo;t fail. It never ended.&lt;/p&gt;
&lt;h2 id="the-price-and-who-is-left-holding-it"&gt;The price, and who is left holding it
&lt;/h2&gt;&lt;p&gt;An estimate that prices all five layers looks nothing like the one in the plan. Every layer gets a line, the coupling rewrite usually the largest, the off-repo pieces inventoried rather than discovered. And the long tail gets an explicit answer: which callers move, which get deprecated, the drop-dead date for the old system, and whose name is against it.&lt;/p&gt;
&lt;p&gt;That last item is not paperwork. It&amp;rsquo;s the only line on the page the author cannot write for free, which is what stops the proposal being cheap talk: a cost estimate is a claim about the future, while a name against the long tail costs the person making it something. Which is why the question that lands is never &amp;ldquo;have you considered the risks,&amp;rdquo; inviting another paragraph, but &amp;ldquo;who is turning the old clusters off, and when.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Push on that and three harder ones fall out, and they decide whether you spend the next decade running both.&lt;/p&gt;
&lt;p&gt;Is the proposer doing this work, or proposing somebody else does it? Same text, different document. A plan assigning eighteen months to a team that hasn&amp;rsquo;t agreed to it is a request, and the cheap-talk logic bites hardest here, because the author has arranged to hold none of the cost.&lt;/p&gt;
&lt;p&gt;If it is the proposer, what happens when they leave? Eighteen months outlasts plenty of tenures, and a migration that depends on one person&amp;rsquo;s continued employment has a bus factor of one on its most expensive phase. A name is where the answer starts, not the answer. The commitment has to land on the team that carries the pager for the thing, with the work on that team&amp;rsquo;s roadmap, so the owner is a role that gets backfilled rather than a person who gets replaced by nobody.&lt;/p&gt;
&lt;p&gt;And the question underneath both: what actually stops this becoming two systems? Nothing does, by default, which is why that is the usual result. The structural fix is the definition of done. Most migrations define done as traffic serving from the new engine, which is exactly when attention leaves, and the last five percent then never finishes because nobody&amp;rsquo;s objectives mention it. Define done as the old system decommissioned and its budget line closed, fund the decommission in the same phase as the cutover, and the tail stops being someone&amp;rsquo;s spare-time project.&lt;/p&gt;
&lt;p&gt;Which suggests an order that tests all of it cheaply, and it runs backwards from how these are usually planned: migrate the long tail first. Take the batch job someone wrote in 2019, the integration hard-wired to the old connection string, the report with the engine-specific function, and move those before touching the easy ninety-five percent. If they move, the rest is downhill and the risk that actually kills migrations is already retired. If they can&amp;rsquo;t, the project isn&amp;rsquo;t viable at the quoted price, and that&amp;rsquo;s been established in week three rather than month fourteen.&lt;/p&gt;
&lt;h2 id="what-makes-it-credible"&gt;What makes it credible
&lt;/h2&gt;&lt;p&gt;The same test applies to the premise, and here the premise breaks first. The stated reason is patching, and nobody measured the patching. How many distinct versions run across the fifty clusters, how long one cycle takes, what share of that is the database rather than the dependency negotiation: none of it is in the document, and all of it is a query or an afternoon with the change log.&lt;/p&gt;
&lt;p&gt;The promise doesn&amp;rsquo;t survive a check in the other direction either. A TiDB cluster is not one thing to patch instead of fifty. Per PingCAP&amp;rsquo;s own &lt;a class="link" href="https://docs.pingcap.com/tidb/stable/tidb-architecture/" target="_blank" rel="noopener"
 &gt;architecture documentation&lt;/a&gt; it is a stateless SQL layer, a metadata and scheduling layer (PD), a distributed key-value store (TiKV), and optionally a columnar store for analytics. Rolling upgrades across those beat fifty negotiated windows, and it is still more component types under management, not fewer. Maybe the trade is worth it. The point is that the central claim was testable and went untested, and the room could see that from the first paragraph.&lt;/p&gt;
&lt;p&gt;Two numbers fix that. What it costs: the five layers priced in engineer-weeks, plus the change in what the estate costs to run once it&amp;rsquo;s done. And what it buys back, in units the business already counts. Maintenance hours per month. Negotiated windows per quarter. How long one routine version bump takes end to end, today, measured rather than remembered.&lt;/p&gt;
&lt;p&gt;The working behind them is the enumeration, and the enumeration is the deliverable. Not a risk register, which is a list of adjectives. A list with rows in it. Every service connecting to each cluster, named, with a current owner. What has to change in each and why, usually a short answer: a driver version, a connection string, a query leaning on behavior the target doesn&amp;rsquo;t implement. How many of the fifty clusters are genuinely distinct versus copies of one pattern, because that moves the project size by an order of magnitude. The versions actually running in every environment, which is the patching claim&amp;rsquo;s own evidence and nobody has it written down. And the trade-offs stated out loud, because a proposal listing no costs is reporting that none were looked for.&lt;/p&gt;
&lt;p&gt;That list is expensive to fake, which is the point. No tool produces it in fifteen minutes, because most of it isn&amp;rsquo;t written down anywhere to retrieve; it comes from connection metadata, change logs and a dozen conversations. It also tends to answer the question it was built for. A third of the way into an honest inventory, most people find either that the project is three times what they said, or that the real win is a smaller change they can ship next quarter.&lt;/p&gt;
&lt;p&gt;The strongest version of the same signal is the proof of concept the product owner asked for, with one condition on what it proves. A POC that stands up the target engine and shows the queries running proves layer one, and layer one was never in doubt: the compatible wire protocol is the claim everyone already believes. The slice has to run all five layers instead, on a schema with real writes and a small blast radius, ending with the old thing turned off. That is price discovery, and it comes before the funding request, being small enough to need permission rather than budget.&lt;/p&gt;
&lt;h2 id="what-actually-gets-funded"&gt;What actually gets funded
&lt;/h2&gt;&lt;p&gt;None of which, on its own, gets it funded, because credible and funded are different bars. The second is not short-termism, and reading it that way is the mistake that keeps these proposals coming back. A company will spend a year and real money without blinking when the year ends in more profit; it does that constantly. What it will not spend a year on is making engineering pleasanter. Easier operations for the people who run the operations is not a return. It appears nowhere in the P&amp;amp;L, and it converts to money only through headcount nobody intends to cut. A smaller infrastructure bill lands the same way, since eighteen months of engineer-time costs more than most database estates cost to run, which makes the ask millions to save thousands.&lt;/p&gt;
&lt;p&gt;What does get funded is a payoff denominated in revenue, and there are two doors into that room. The first is a ceiling costing business you would otherwise take: we cannot onboard the customer who needs a region we can&amp;rsquo;t shard into, we cannot carry the volume the next contract tier brings, we said no in Q3 because the write path tops out. The second is a customer-visible change big enough to move retention or upsell, which for a database usually means latency the customer feels: the p99 that makes the product seem broken on precisely the accounts with the most data in them, the report that times out so nobody upgrades to the analytics tier, the checkout shedding orders every peak. Both dwarf five layers, and both arrive already denominated in the units the decision gets made in. Savings are not a third door.&lt;/p&gt;
&lt;p&gt;Which settles the plan from the top of this post. Moving fifty MySQL clusters to TiDB becomes viable the day a customer the size of Walmart is onboarding and the current estate demonstrably cannot carry them. That version writes itself, survives every question here, and gets funded in a week. Without that customer, the same document asks for eighteen months to make patching less annoying, which is a real problem and the wrong ask.&lt;/p&gt;
&lt;p&gt;The corollary is uncomfortable. Most databases called outgrown are nowhere near a ceiling and have years of headroom in unglamorous query and schema work, which is &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;its own series&lt;/a&gt;. If nothing is being turned away and no customer feels it, the honest finding is that this shouldn&amp;rsquo;t be funded this year, and the engineer who works that out and says so has produced something more useful than the plan.&lt;/p&gt;
&lt;p&gt;There is a shape problem underneath the arithmetic too. The plan is a waterfall: eighteen months in which nothing gets better, ending in a cutover that concentrates the entire risk at the last moment, and whose failure mode is not a delay but a permanent second system. Set against that, the reward is a handful of engineers having a better time patching. A large risk taken all at once for a small and diffuse gain is a trade nobody signs, however the document reads.&lt;/p&gt;
&lt;p&gt;Which is where the smaller proposal hiding inside the big one turns up, and it has the opposite shape. The pain was patching fifty clusters by hand. The fix for that is a pipeline that patches them: a build job rolling a version through environments, a canary, health checks gating promotion, and the dependency list deciding the order. It delivers in week three and keeps delivering, each cluster onboarded to it a standalone improvement that can be stopped, reversed, or paused without leaving anything half-migrated. No dual-write, no operational reset, no second database to run forever. It clears the bar easily too, because the bar scales with the ask. Productivity is a perfectly good argument for two sprints of automation and a hopeless one for eighteen months of migration. And the enumeration that failed to justify TiDB is exactly the input the automation needs, which is why doing it first is never the wasted work it looks like.&lt;/p&gt;
&lt;p&gt;Which is worth naming, because the three fixes above are not three flavors of trying harder. Cheap talk is defined by three properties: the message costs nothing to send, it binds nobody, and no one can check it. Each fix breaks one of them. The enumeration makes the claim checkable. The proof of concept makes it costly, which is what the product owner was asking for and could not have put in those words. The name and the date make it binding. Any one of the three moves the proposal out of the category the room was discounting before it reached the merits. And there is a sting in the checkable one, because verifiable disclosure &lt;a class="link" href="https://milgrom.people.stanford.edu/wp-content/uploads/1981/10/Good-News-and-Bad-News.pdf" target="_blank" rel="noopener"
 &gt;unravels&lt;/a&gt;: once a few people start bringing the inventory, turning up without one stops being neutral and starts reading as having looked and not liked the answer.&lt;/p&gt;</description></item><item><title>A Billion Row Versions From One Uncommitted Read Stalled a MySQL Replica</title><link>https://explainanalyze.com/p/a-billion-row-versions-from-one-uncommitted-read-stalled-a-mysql-replica/</link><pubDate>Tue, 15 Sep 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/a-billion-row-versions-from-one-uncommitted-read-stalled-a-mysql-replica/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post A Billion Row Versions From One Uncommitted Read Stalled a MySQL Replica" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;An open transaction on a read replica holds a read view, and a read view stops InnoDB from purging old row versions anywhere on that server. The versions pile up, every read has to walk longer and longer chains to find the current row, and the replication applier is a read workload too, so it falls behind on a source whose traffic never changed. The fix is one &lt;code&gt;KILL&lt;/code&gt;, and finding out what to kill takes one query.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The replica is 260,000 seconds behind. That&amp;rsquo;s three days, and it has been climbing all week from the few minutes it sat at when someone first noticed.&lt;/p&gt;
&lt;p&gt;The source is busy, and it has always been busy. It serves about 15,000 queries a second, which is what it served last month and the month before, and the write rate inside that number is flat. Nothing has been backfilled. No schema change has run, the binary logs are rotating at the rate they have for a year, and the source&amp;rsquo;s own &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt; is clean. On the replica, the data directory is 340 GB against the source&amp;rsquo;s 84 GB, holding what is supposed to be a byte-for-byte copy of the same data.&lt;/p&gt;
&lt;p&gt;Restarting the replica fixes it. Lag drops to zero in a few hours of catch-up, everyone moves on, and somewhere between a day and a week later the alert fires again.&lt;/p&gt;
&lt;h2 id="it-must-be-the-applier"&gt;It must be the applier
&lt;/h2&gt;&lt;p&gt;The first theory is throughput, and it&amp;rsquo;s the right first theory. A replica that can&amp;rsquo;t keep up with a source is usually a replica that is applying single-threaded, or applying on slower disks, or fighting the read traffic that is the whole reason it exists.&lt;/p&gt;
&lt;p&gt;So: &lt;code&gt;replica_parallel_workers&lt;/code&gt; raised, &lt;code&gt;replica_preserve_commit_order&lt;/code&gt; left on, reporting traffic moved off for an afternoon, and a bigger instance class underneath. Lag kept growing. The tell that should have ended this phase early was the shape of the graph. A replica that is throughput-bound falls behind during the busy hours and gets it back in the overnight trough, so the lag line is a sawtooth. This line had no teeth. It climbed through four o&amp;rsquo;clock on Sunday morning, the quietest hours in the source&amp;rsquo;s week, at the same slope it climbed on Tuesday at noon.&lt;/p&gt;
&lt;p&gt;Something on the replica was making every unit of work more expensive over time, and the only thing on a replica that gets monotonically more expensive over time is history.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;mysql&amp;gt; SHOW ENGINE INNODB STATUS\G
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;...
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;------------
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;TRANSACTIONS
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;------------
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Trx id counter 4297552210
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Purge done for trx&amp;#39;s n:o &amp;lt; 2851013964 undo n:o &amp;lt; 0 state: running but idle
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;History list length 1043382771
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;A billion. The purge pointer is sitting 1.4 billion transaction IDs behind the current counter, which is the same fact stated twice.&lt;/p&gt;
&lt;h2 id="what-the-history-list-actually-counts"&gt;What the history list actually counts
&lt;/h2&gt;&lt;p&gt;InnoDB never updates a row in place for readers. An &lt;code&gt;UPDATE&lt;/code&gt; writes the new version into the clustered index and pushes the old one into an undo log, so that any transaction with an older snapshot can still be shown the row as it looked when that snapshot began. From the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-multi-versioning.html" target="_blank" rel="noopener"
 &gt;manual on multi-versioning&lt;/a&gt;:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;In the &lt;code&gt;InnoDB&lt;/code&gt; multi-versioning scheme, a row is not physically removed from the database immediately when you delete it with an SQL statement. &lt;code&gt;InnoDB&lt;/code&gt; only physically removes the corresponding row and its index records when it discards the update undo log record written for the deletion.&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;Discarding those records is the purge threads&amp;rsquo; job, and purge is not allowed to discard anything that any open read view might still need. The history list length is the count of undo log records waiting for purge. On a healthy server it sits in the thousands and bounces around as purge keeps up. It grows without limit exactly when something is holding a read view open, because purge is pinned to the oldest snapshot on the server and cannot advance past it.&lt;/p&gt;
&lt;p&gt;Peter Zaitsev&amp;rsquo;s &lt;a class="link" href="https://www.percona.com/blog/2014/10/17/innodb-transaction-history-often-hides-dangerous-debt/" target="_blank" rel="noopener"
 &gt;2014 post on transaction history&lt;/a&gt; makes the distinction that matters here: there are records that can be purged and records that can&amp;rsquo;t be purged because some active transaction needs them, and a high history list is only dangerous when it&amp;rsquo;s the second kind. This was the second kind.&lt;/p&gt;
&lt;p&gt;The cost lands on reads, and it lands in a specific place. When InnoDB walks a secondary index and finds an entry whose page has been touched by a newer transaction, it can no longer trust the index to answer the query:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;When a secondary index record is delete-marked or the secondary index page is updated by a newer transaction, &lt;code&gt;InnoDB&lt;/code&gt; looks up the database record in the clustered index. In the clustered index, the record&amp;rsquo;s &lt;code&gt;DB_TRX_ID&lt;/code&gt; is checked, and the correct version of the record is retrieved from the undo log if the record was modified after the reading transaction was initiated.&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;A covering index stops covering. A single-row lookup becomes a clustered index descent plus a walk backwards down a version chain that is now hundreds of links long, and the manual&amp;rsquo;s own summary of where this ends is blunt: the purge thread starts to lag behind, the table grows bigger because of all the dead rows, &amp;ldquo;making everything disk-bound and very slow.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Here is the part that took the longest to see. The replication applier is one of those readers. Every row event in the relay log has to locate its target row before it can modify it, and on a replica whose history list is in the billions, locating a row costs a chain walk. The applier slows down in proportion to the mess, the mess grows because the applier keeps writing new versions that also can&amp;rsquo;t be purged, and the source&amp;rsquo;s write rate never has to change for any of it. A steady 15,000 queries a second is all the fuel this needs. That&amp;rsquo;s why the lag climbed through the Sunday trough at the same rate it climbed at noon on a weekday.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;What restarting was really doing&lt;/strong&gt;
 &lt;div&gt;A restart drops every session. The abandoned transaction died with its connection, purge was free to run, and the replica spent its first hours back mostly purging, then caught up. Nothing was fixed. The next application deploy left another transaction open and the clock started again. A restart that reliably fixes a problem for a variable number of days is usually clearing state that something is recreating, and it&amp;rsquo;s worth asking what state before scheduling it as a weekly job.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="ask-who-is-holding-the-oldest-snapshot"&gt;Ask who is holding the oldest snapshot
&lt;/h2&gt;&lt;p&gt;The transaction pinning purge is visible, and it looks like nothing at all:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_started&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPDIFF&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SECOND&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_started&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;age_s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_rows_modified&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rows_mod&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;host&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;innodb_trx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;processlist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_mysql_thread_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;trx_started&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Reproduced on a 2-million-row table on MySQL 8.0.46, with a source feeding a replica and one forgotten snapshot open on the replica, the join returns two rows:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; trx_id: 5782
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; trx_state: RUNNING
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;trx_started: 2026-09-12 13:52:21
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; age_s: 0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; rows_mod: 5570
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; command: Query
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; time: 1
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; trx_id: 562948500925656
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; trx_state: RUNNING
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;trx_started: 2026-09-12 13:46:13
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; age_s: 368
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; rows_mod: 0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; command: Sleep
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; time: 368
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; host: localhost
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first row is the applier, doing its job:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;---TRANSACTION 5782, ACTIVE 0 sec starting index read
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;mysql tables in use 1, locked 1
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;15 lock struct(s), heap size 1128, 2012 row lock(s), undo log entries 2012
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;MySQL thread id 11, query id 10604 Applying batch of row changes (update)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The second row is the problem: &lt;code&gt;RUNNING&lt;/code&gt;, zero rows modified, command &lt;code&gt;Sleep&lt;/code&gt;, and a start time that only gets older. Look for it in &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt; and it is not in the active list at all. A transaction that has only read holds no locks and has written no undo, so it appears in the session list as &lt;code&gt;not started&lt;/code&gt;, which is a phrase that means something more specific than it sounds like and has cost people hours. The only evidence there is a count:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;1 read views open inside InnoDB
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;One read view is all it takes. &lt;code&gt;innodb_trx&lt;/code&gt; is the view that shows it as what it is, which is why the join above is the query to run first and &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt; is the one that confirms the damage.&lt;/p&gt;
&lt;p&gt;On the incident host the equivalent second row had an &lt;code&gt;age_s&lt;/code&gt; of 1,180,000 and a &lt;code&gt;host&lt;/code&gt; column pointing at an application server that had been terminated thirteen days earlier. A reporting request had opened a transaction, run one &lt;code&gt;SELECT&lt;/code&gt; under &lt;code&gt;REPEATABLE READ&lt;/code&gt;, and gone away when its process died mid-request. The connection outlived it: the pool&amp;rsquo;s keepalive had been resetting &lt;code&gt;wait_timeout&lt;/code&gt; on a socket whose client no longer existed, so the server&amp;rsquo;s idle reaper never came for it. A transaction with nothing running in it and nothing to roll back, holding one read view, at the cost of 340 GB of undo and a replica three days behind the source it is supposed to be a copy of.&lt;/p&gt;
&lt;p&gt;One &lt;code&gt;KILL&lt;/code&gt; on that thread, and the history list started draining.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Before killing a long transaction, check &lt;code&gt;trx_rows_modified&lt;/code&gt;. A transaction showing zero has nothing to undo and disappears instantly. One showing millions will roll back when killed, single-threaded, and can hold the table hostage for longer than the original statement took to run. The safe version of this operation is to kill snapshot-holders that are idle and have modified nothing, and to escalate anything else to whoever owns the workload. Also expect purge to take real time after the kill: on a history list of a billion it is hours of IO, during which the replica is still behind and the graph is still ugly.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-measurement-and-what-to-alert-on"&gt;The measurement, and what to alert on
&lt;/h2&gt;&lt;p&gt;The mechanism is easy enough to reproduce that it&amp;rsquo;s worth doing once, because the numbers make the argument better than the explanation does. A source and a replica on MySQL 8.0.46, a 2-million-row &lt;code&gt;orders&lt;/code&gt; table, and a write workload of batched updates replaying through the applier. Run it with nothing else connected to the replica and the history list oscillates between 3 and 56 for the entire run, which is purge keeping pace. Then open a single transaction on the replica, run one &lt;code&gt;SELECT&lt;/code&gt;, and leave it sitting there:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:48:59 history=0 undo=112MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:49:40 history=115 undo=192MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:50:21 history=228 undo=336MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:51:02 history=312 undo=432MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:51:43 history=391 undo=528MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:52:24 history=470 undo=656MB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;06:52:45 history=482 undo=672MB
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Same source, same table, same writes. The only difference between the run that stays flat and the run that climbs is one idle connection. Then stop the write load entirely, and the interesting thing is what doesn&amp;rsquo;t happen: the history list sat at 585 and the undo tablespaces at 784 MB for as long as the snapshot stayed open, with the source completely quiet. Purge had caught up to everything it was allowed to touch and was blocked on the rest. &lt;code&gt;COMMIT&lt;/code&gt; in the forgotten session, and the history list went to zero within a few minutes.&lt;/p&gt;
&lt;p&gt;Two million rows is too small to show the second half of the story. Version chains a few hundred links long are still cheap to walk, so the applier in this setup never visibly slowed down; what it was throughput-bound by was the batch size, in both runs equally. The read amplification needs production scale and production time to become the dominant cost, which is exactly why the symptom arrives as lag weeks after the cause arrives as an idle connection.&lt;/p&gt;
&lt;p&gt;The undo files are the part that surprises people who arrive at this through a disk alert rather than a lag alert. &lt;code&gt;innodb_undo_log_truncate&lt;/code&gt; is on by default in MySQL 8.0, but an undo tablespace can only be truncated after the purge system has freed every rollback segment in it, so a pinned read view means the files grow and never shrink back to their 16 MB floor. That is where the replica&amp;rsquo;s 340 GB came from, and it&amp;rsquo;s the same class of problem as &lt;a class="link" href="https://explainanalyze.com/p/a-10-gb-database-filled-a-200-gb-disk-and-du-could-not-find-the-space/" &gt;a 10 GB database filling a 200 GB disk&lt;/a&gt;: space held by a reference nobody remembers taking.&lt;/p&gt;
&lt;p&gt;Two things are worth alerting on, and neither is lag. The first is &lt;code&gt;trx_rseg_history_len&lt;/code&gt; in &lt;code&gt;information_schema.innodb_metrics&lt;/code&gt;, which is the history list length as a number you can scrape instead of a line you have to parse out of &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt;. It is enabled by default, unlike a lot of that table. Pick a threshold high enough never to fire on a healthy server and low enough to land a day before the lag graph moves; ten million is a reasonable place to start arguing from. The second is the age of the oldest row in &lt;code&gt;information_schema.innodb_trx&lt;/code&gt;, with the threshold set a few minutes past the longest report the application is supposed to be able to run. Percona&amp;rsquo;s &lt;a class="link" href="https://www.percona.com/blog/chasing-a-hung-transaction-in-mysql-innodb-history-length-strikes-back/" target="_blank" rel="noopener"
 &gt;2017 write-up of a hung transaction&lt;/a&gt; describes 940 transactions sitting in &lt;code&gt;Sleep&lt;/code&gt; for 766,132 seconds and a history length past 6 million, which is the same animal at a different scale and a useful reminder that these things are usually plural.&lt;/p&gt;
&lt;p&gt;Neither of those needs to page anyone. This is a one-lever problem with an exact signature and no judgment in it, which puts it squarely in the set that a health check bound to a watch handler can close on its own: the check goes critical on the history length, the handler runs the &lt;code&gt;innodb_trx&lt;/code&gt; lookup, confirms &lt;code&gt;trx_rows_modified&lt;/code&gt; is near zero, kills the thread, and files a ticket saying what it killed and how old it was. The &lt;a class="link" href="https://explainanalyze.com/p/self-healing-databases-with-a-health-check-and-a-watch-script/" &gt;handler pattern and the guards it needs&lt;/a&gt; are worth reading before wiring one, because the ticket is the load-bearing half. A handler that silently kills an abandoned transaction every few days has converted a defect in the application into a quiet maintenance routine, and the version of this incident where nobody ever finds out is the one that runs for a year.&lt;/p&gt;
&lt;p&gt;Which is where it actually gets fixed. A transaction that begins on one request and is expected to end on the same request should be bounded by the framework, not by hope, and a connection pool that health-checks idle connections should be asking whether the session has an open transaction rather than only whether the socket answers. Neither of those is a DBA change, which is why this kind of incident tends to get fixed twice: once with a &lt;code&gt;KILL&lt;/code&gt; at 3 a.m., and once properly, a quarter later, by whoever owns the reporting endpoint.&lt;/p&gt;</description></item><item><title>A 10 GB Database Filled a 200 GB Disk and du Could Not Find the Space</title><link>https://explainanalyze.com/p/a-10-gb-database-filled-a-200-gb-disk-and-du-could-not-find-the-space/</link><pubDate>Sat, 12 Sep 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/a-10-gb-database-filled-a-200-gb-disk-and-du-could-not-find-the-space/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post A 10 GB Database Filled a 200 GB Disk and du Could Not Find the Space" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;When &lt;code&gt;df&lt;/code&gt; and &lt;code&gt;du&lt;/code&gt; disagree by more than a rounding error, the missing space is in files that have been deleted but are still open, and the kernel will name the process holding them. MySQL deletes its temporary files the instant it creates them, on purpose, so anything else that opens those files keeps their space alive after MySQL is done. Here that was an endpoint security agent, a 10 GB database filled a 200 GB disk, and two rounds of bigger hardware bought a few days each.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The page says the MySQL host is at 92 percent disk. It&amp;rsquo;s a 200 GB volume. The data directory, which is the only thing on that machine anyone would expect to grow, comes to 10 GB.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-gdscript3" data-lang="gdscript3"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;Filesystem&lt;/span&gt; &lt;span class="n"&gt;Size&lt;/span&gt; &lt;span class="n"&gt;Used&lt;/span&gt; &lt;span class="n"&gt;Avail&lt;/span&gt; &lt;span class="n"&gt;Use&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;dev&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;nvme0n1p1&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt; &lt;span class="mi"&gt;184&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt; &lt;span class="mi"&gt;92&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="n"&gt;sudo&lt;/span&gt; &lt;span class="n"&gt;du&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;sh&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="k"&gt;var&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;lib&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;mysql&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="k"&gt;var&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;lib&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;mysql&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="n"&gt;sudo&lt;/span&gt; &lt;span class="n"&gt;du&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;sh&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;/&lt;/span&gt;&lt;span class="n"&gt;dev&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;null&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="mi"&gt;19&lt;/span&gt;&lt;span class="n"&gt;G&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;df&lt;/code&gt; asks the filesystem how many blocks are in use. &lt;code&gt;du&lt;/code&gt; walks every directory entry and adds up sizes. They agree on a healthy machine to within the metadata overhead. Here they disagree by 165 GB, and the binary logs, the general log, the slow log, the OS journal, and &lt;code&gt;/tmp&lt;/code&gt; have all been checked and are all small. The space is being used, and nothing on the disk is using it.&lt;/p&gt;
&lt;p&gt;Restarting MySQL brings &lt;code&gt;df&lt;/code&gt; down a little. Over the next day it climbs back.&lt;/p&gt;
&lt;h2 id="buy-a-bigger-box"&gt;Buy a bigger box
&lt;/h2&gt;&lt;p&gt;The first response was the reasonable one. Grow the volume. Disk is cheap, the alert stops, and the investigation can wait for business hours. The alert came back within the week at the same 92 percent, which on a bigger disk meant more space had vanished, not less. The worst day was a burst of GROUP BY and ORDER BY queries the application couldn&amp;rsquo;t serve from cache. Every one of them spilled to temp files, and the volume went from healthy to nearly full in a few hours. The second response was a bigger instance class, more memory and more cores, on the theory that if something inside MySQL was spilling to disk, more RAM would keep it in memory.&lt;/p&gt;
&lt;p&gt;Memory usage did not move. The graph stayed flat through both upgrades, exactly where it had been for a year. Nothing in this failure consumes memory, and that was the first real clue, though it took a while to be read as one. The second was that restarting MySQL only ever recovered a few gigabytes. If MySQL had been the one holding the space, restarting it would have returned all of it.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;Something is writing to a path we haven&amp;rsquo;t checked&amp;rdquo; is the next theory, and it&amp;rsquo;s usually right. Not here. Every mount point had been walked, and &lt;code&gt;find / -size +1G&lt;/code&gt; returned the InnoDB files and nothing else. The space had no filename, and the search had been for filenames the whole time.&lt;/p&gt;
&lt;h2 id="where-space-goes-when-the-file-has-no-name"&gt;Where space goes when the file has no name
&lt;/h2&gt;&lt;p&gt;On Linux a file is an inode with data blocks, and a filename is a directory entry pointing at it. &lt;code&gt;rm&lt;/code&gt; removes the directory entry. The blocks are returned to the filesystem only when the last reference to the inode goes away, and an open file descriptor is a reference. A process that opens a file, and keeps it open while the name is removed, keeps the data too. &lt;code&gt;ls&lt;/code&gt; can&amp;rsquo;t see it, &lt;code&gt;du&lt;/code&gt; can&amp;rsquo;t count it, &lt;code&gt;df&lt;/code&gt; counts it.&lt;/p&gt;
&lt;p&gt;MySQL does this to itself deliberately. From the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/temporary-files.html" target="_blank" rel="noopener"
 &gt;manual&amp;rsquo;s page on temporary files&lt;/a&gt;:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;MySQL arranges that temporary files are removed if mysqld is terminated. On platforms that support it (such as Unix), this is done by unlinking the file after opening it. The disadvantage of this is that the name does not appear in directory listings and you do not see a big temporary file that fills up the file system in which the temporary file directory is located. (In such cases, &lt;code&gt;lsof +L1&lt;/code&gt; may be helpful in identifying large files associated with mysqld.)&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;Every sort that outgrows &lt;code&gt;sort_buffer_size&lt;/code&gt;, and in MySQL 8.0 every internal temporary table that outgrows &lt;code&gt;temptable_max_ram&lt;/code&gt; (1 GiB by default), lands in a file under &lt;code&gt;tmpdir&lt;/code&gt; that has already been deleted by the time the first byte is written. Here is a GROUP BY over a million-row table on MySQL 8.0.46, caught mid-flight by reading the server&amp;rsquo;s own file descriptor table:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ ls -A /tmp | wc -l
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ du -sk /tmp
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;0 /tmp
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ ls -l /proc/$(pidof mysqld)/fd | grep deleted
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;lrwx------ 1 mysql mysql 64 Sep 12 00:55 12 -&amp;gt; /tmp/#6598550 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;lrwx------ 1 mysql mysql 64 Sep 12 00:55 13 -&amp;gt; /tmp/#6598553 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ stat -Lc &amp;#39;%s %n&amp;#39; /proc/$(pidof mysqld)/fd/12 /proc/$(pidof mysqld)/fd/13
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;1980000000 /proc/1873/fd/12
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;1980000000 /proc/1873/fd/13
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Two files, just under 2 GB each, from one report query against a table that is 1 GB on disk. The temporary table is wider than the base rows because it carries the grouped columns in full, and the sort that follows gets its own file. Zero entries in &lt;code&gt;/tmp&lt;/code&gt;. &lt;code&gt;du&lt;/code&gt; says zero. The moment the query finishes, MySQL closes both descriptors, the reference count hits zero, and the 4 GB is back. That is the design, and on a healthy host it works so well that most people who run MySQL for a living have never seen these files.&lt;/p&gt;
&lt;p&gt;Unless something else opens them first.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Version note&lt;/strong&gt;
 &lt;div&gt;This shape is specific to MySQL 8.0 and earlier. 8.0 overflows the TempTable engine into memory-mapped files under &lt;code&gt;tmpdir&lt;/code&gt; (&lt;code&gt;temptable_use_mmap=ON&lt;/code&gt; by default). MySQL 8.4 turns that path off by default, and the same query overflows into the InnoDB session temporary tablespace under &lt;code&gt;#innodb_temp&lt;/code&gt; inside the data directory, a file with a name that &lt;code&gt;du&lt;/code&gt; finds without help. Filesort still uses unlinked files in &lt;code&gt;tmpdir&lt;/code&gt; on every version, so the gap can appear on 8.4 too, just with a lower ceiling.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="ask-the-kernel-who-is-holding-it"&gt;Ask the kernel who is holding it
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;lsof +L1&lt;/code&gt; lists open files with a link count below one, meaning every open file whose last name has been removed. On the incident host, trimmed:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ sudo lsof +L1
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;COMMAND PID USER FD TYPE DEVICE SIZE/OFF NLINK NODE NAME
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;mysqld 1873 mysql 12u REG 259,1 1980000000 0 6598550 /tmp/#6598550 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;mysqld 1873 mysql 13u REG 259,1 412876800 0 6598553 /tmp/#6598553 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;agentd 2210 root 188r REG 259,1 1980000000 0 6597102 /tmp/#6597102 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;agentd 2210 root 189r REG 259,1 1980000000 0 6597104 /tmp/#6597104 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;agentd 2210 root 190r REG 259,1 1979998208 0 6597110 /tmp/#6597110 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;agentd 2210 root 191r REG 259,1 1980000000 0 6597111 /tmp/#6597111 (deleted)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;...
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first two lines are MySQL, holding the temp files for the report that is running right now, which is what the manual said to expect. Everything after that is the endpoint security agent. (The vendor&amp;rsquo;s name in the COMMAND column is the one detail this write-up leaves out.) Several hundred descriptors, every one of them a deleted MySQL temp file, every one opened read-only, and the sum of the SIZE column came to a few gigabytes short of the gap between &lt;code&gt;df&lt;/code&gt; and &lt;code&gt;du&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;$ sudo lsof +L1 -p 2210 | awk &amp;#39;NR&amp;gt;1 {s+=$7} END {printf &amp;#34;%.0f GB\n&amp;#34;, s/1e9}&amp;#39;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;163 GB
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;None of those inodes were MySQL&amp;rsquo;s anymore. MySQL had created each file, unlinked it, written a report&amp;rsquo;s worth of sort data into it, and closed it, hours or days earlier. From MySQL&amp;rsquo;s side the file was gone. From the kernel&amp;rsquo;s side the agent still had it open, and the agent&amp;rsquo;s descriptor was the only thing standing between 163 GB and the free list.&lt;/p&gt;
&lt;p&gt;The mechanism on the agent&amp;rsquo;s side is ordinary. An on-access scanner subscribes to file events, and a file being created in &lt;code&gt;/tmp&lt;/code&gt; by a process it doesn&amp;rsquo;t have an exclusion for is precisely what it exists to look at. It opens the file to scan it. MySQL, meanwhile, has already unlinked the name and is writing 2 GB into the inode at disk speed, so the scanner is reading a file that changes under it, on a queue with every other temp file from every other report. Whether it re-queued the file each time it changed, waited for it to settle, or leaked the descriptor outright is the vendor&amp;rsquo;s business and was never established. The effect on the filesystem is the same in all three cases: the inode outlives MySQL&amp;rsquo;s interest in it by as long as the agent holds it, and on a reporting host that runs a few dozen heavy GROUP BY queries a day, at a couple of gigabytes each, 200 GB is a week of ordinary days, or a few hours on the afternoon the cache stopped absorbing the aggregation queries and every GROUP BY with a sort behind it spilled at once.&lt;/p&gt;
&lt;p&gt;This also explains the two hardware upgrades. More disk raised the ceiling the agent&amp;rsquo;s backlog could fill and changed nothing about the rate. More RAM changed nothing at all: &lt;code&gt;temptable_max_ram&lt;/code&gt; is a configuration value, not a function of the memory in the box, so the spill happened at the same 1 GiB after the upgrade as before it, and the sort files would have gone to &lt;code&gt;tmpdir&lt;/code&gt; regardless. The graph that stayed flat was telling the truth. The problem was never in MySQL&amp;rsquo;s memory or MySQL&amp;rsquo;s files. It was in a reference count.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Restarting MySQL does not release these files. MySQL already closed them; the descriptors that matter belong to the other process, and only closing those returns the space. Do not try to reclaim it by deleting anything under &lt;code&gt;tmpdir&lt;/code&gt; either, since the names are already gone and there is nothing to delete. If the holder is a security agent, restarting or stopping it on a production database host is a change the security team owns, not the DBA; the &lt;code&gt;lsof&lt;/code&gt; output is what gets that conversation to a yes in one message instead of three.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-confession-and-the-fix"&gt;The confession, and the fix
&lt;/h2&gt;&lt;p&gt;The proof was a restart of the agent, agreed with the team that owned it. &lt;code&gt;df&lt;/code&gt; dropped by 163 GB in the time it took the process to exit, which is the closest thing this kind of investigation gets to a signed confession. The durable fix was to remove the agent from the database hosts, on the grounds that a scanner that opens every file a database writes has no business on a machine whose entire job is writing files. Replacing it with a product that respects exclusions was the compromise position.&lt;/p&gt;
&lt;p&gt;Two smaller options exist, and each trades something. Excluding &lt;code&gt;tmpdir&lt;/code&gt; and the data directory from scanning is what the MySQL manual has recommended for years (the Windows installation page has a section titled &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/windows-installation.html" target="_blank" rel="noopener"
 &gt;&amp;ldquo;MySQL and Virus Checking Software&amp;rdquo;&lt;/a&gt; that says exactly this), and it leaves the agent in place for everything else on the host. It also depends on the agent honouring the exclusion for a file whose name disappeared a millisecond after creation, which is worth testing rather than assuming. Moving &lt;code&gt;tmpdir&lt;/code&gt; to its own filesystem bounds the damage instead of preventing it: a full &lt;code&gt;tmpdir&lt;/code&gt; fails the report with &amp;ldquo;The table is full&amp;rdquo; and leaves the data directory, the redo log, and the binary logs untouched, where a full root volume takes the server down. That is a smaller blast radius, and it is still a broken report every week.&lt;/p&gt;
&lt;p&gt;There is a general signal here that is worth more than the specific story. &lt;code&gt;df&lt;/code&gt; and &lt;code&gt;du&lt;/code&gt; disagreeing is a specific symptom with a two-item differential. Either files are hidden under a mount point (a directory that had files in it before something was mounted on top of it, which &lt;code&gt;mount --bind / /mnt/root&lt;/code&gt; and a second &lt;code&gt;du&lt;/code&gt; will reveal), or files have been deleted while open, which &lt;code&gt;lsof +L1&lt;/code&gt; will list along with the PID of whoever is responsible. Both take under a minute to check. Neither is what a capacity alert suggests, and the &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-v-disk-has-two-alarms-not-one/" &gt;disk post in the queries series&lt;/a&gt; already made the argument that the storage dashboard is the last place to look for a storage problem. This is the version of that argument where the culprit is not even a query.&lt;/p&gt;
&lt;p&gt;The same method worked on the &lt;a class="link" href="https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/" &gt;3-billion-row query&lt;/a&gt; in the previous post: work out what the answer should cost, find the one line that owns the difference, and refuse to buy hardware until you can say what the hardware is for. Here the answer was 10 GB of database and a few gigabytes of transient temp files, the line was a process name in the COMMAND column, and the hardware, twice, was for nothing.&lt;/p&gt;</description></item><item><title>One Column Added to a SELECT: 1,020 Page Reads Became 166,667</title><link>https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/</link><pubDate>Fri, 11 Sep 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post One Column Added to a SELECT: 1,020 Page Reads Became 166,667" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;An index-only scan reads the index and never touches the table. Add one column to the SELECT list that the index doesn&amp;rsquo;t carry and the engine has to visit the heap for every matching row, and past a certain row count the planner gives up on the index entirely and scans the table. The fix is to extend the index or shrink the projection; both cost something, and on Postgres the extended index still isn&amp;rsquo;t enough by itself.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A list-page query that has run for a year:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;orders&lt;/code&gt; has a composite index on &lt;code&gt;(customer_id, status, created_at)&lt;/code&gt;. Every column the query touches is in it, so the engine walks the index and never opens the table. Then a feature request: show the order total on the list. The diff is one column.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Here are both, run warm against a 5-million-row &lt;code&gt;orders&lt;/code&gt; table (1.3 GB heap, 194 MB index) on PostgreSQL 18. Customer 42 has 266 orders.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- before
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Index Only Scan using idx_orders_cust_status_created on orders
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (actual time=0.046..0.093 rows=266 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = 42)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Fetches: 0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=34
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 0.134 ms
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- after: one column added
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Bitmap Heap Scan on orders (actual time=0.071..0.472 rows=266 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Recheck Cond: (customer_id = 42)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Blocks: exact=265
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=270
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Bitmap Index Scan on idx_orders_cust_status_created
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Index Cond: (customer_id = 42)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 0.519 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The plan node changed shape, 34 buffers became 270, and the query is four times slower. Nobody notices. Half a millisecond is invisible on any dashboard, and this is where most write-ups of covering indexes stop, with a slowdown that doesn&amp;rsquo;t hurt.&lt;/p&gt;
&lt;p&gt;Customer 777 is a marketplace seller with 200,239 orders interleaved over the same year. Same two queries:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- before
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Index Only Scan using idx_orders_cust_status_created on orders
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (actual time=0.052..16.070 rows=200239 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Fetches: 0
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=1020
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 22.440 ms
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- after: one column added
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Gather (actual time=0.388..160.668 rows=200239 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Workers Planned: 2
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Workers Launched: 2
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=14884 read=151783 written=273
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Parallel Seq Scan on orders (actual time=0.363..151.954 rows=66746 loops=3)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Filter: (customer_id = 777)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Rows Removed by Filter: 1599920
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 167.623 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The index is gone from the plan. Three workers read all 166,667 pages of the table and threw away 4.8 million rows to keep 200 thousand. Reads went from 1,020 pages to 166,667, and &lt;code&gt;written=273&lt;/code&gt; means the scan pushed dirty pages out of a 128 MB buffer pool to make room, which is the part the other queries on the box will feel.&lt;/p&gt;
&lt;p&gt;The reflexive fix is already forming: add &lt;code&gt;total_cents&lt;/code&gt; to the index. That is what shipped, and it&amp;rsquo;s covered below, but it isn&amp;rsquo;t free and on Postgres it isn&amp;rsquo;t sufficient. The other reflex, &amp;ldquo;only select what you need,&amp;rdquo; is correct and ignored in practice, because the ORM emits &lt;code&gt;SELECT *&lt;/code&gt; unless someone tells it otherwise. What follows is why the plan flips, why &lt;code&gt;Heap Fetches: 0&lt;/code&gt; is a claim about this moment and not about the index, and what each fix costs.&lt;/p&gt;
&lt;h2 id="why-the-planner-walks-away-from-the-index"&gt;Why the planner walks away from the index
&lt;/h2&gt;&lt;p&gt;An index entry knows the row&amp;rsquo;s location in the heap. It doesn&amp;rsquo;t know &lt;code&gt;total_cents&lt;/code&gt;. Once the query needs a column the index doesn&amp;rsquo;t carry, every matching entry becomes a heap page visit, and the cost of the query stops being &amp;ldquo;how many index entries match&amp;rdquo; and becomes &amp;ldquo;how many distinct heap pages hold those rows.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;For customer 42 that&amp;rsquo;s 265 pages, so a bitmap scan over the index is still the cheapest route. For customer 777 the arithmetic changes. The 5 million rows sit about 30 to a page, and one in every 25 belongs to customer 777, which puts one of their rows on nearly every page in the table. Whether the engine reaches those pages through the index or by reading the file front to back, it touches 166,667 pages either way, and the sequential read is the cheaper way to do it. With &lt;code&gt;enable_seqscan = off&lt;/code&gt; the planner&amp;rsquo;s fallback was a parallel bitmap heap scan that took 292 ms, touched the same 167 thousand pages, and went lossy because the bitmap outgrew the 4 MB &lt;code&gt;work_mem&lt;/code&gt;. The planner&amp;rsquo;s choice was right. The query is just expensive now, in a way it wasn&amp;rsquo;t when the index alone could answer it.&lt;/p&gt;
&lt;p&gt;MySQL&amp;rsquo;s optimizer took the other branch on the same data (2 million rows, InnoDB, MySQL 8.4). It stayed on the index and paid per row:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- 106 rows, covered
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Covering index lookup on orders using idx_orders_cust_status_created (customer_id=42)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (cost=11.2 rows=106) (actual time=0.0779..0.091 rows=106 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- 106 rows, one column added
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on orders using idx_orders_cust_status_created (customer_id=42)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (cost=90 rows=106) (actual time=0.182..0.339 rows=106 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- 80,115 rows, covered
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Covering index lookup on orders using idx_orders_cust_status_created (customer_id=777)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (cost=15515 rows=151198) (actual time=0.141..12.8 rows=80115 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- 80,115 rows, one column added
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on orders using idx_orders_cust_status_created (customer_id=777)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (cost=86898 rows=151198) (actual time=7.93..471 rows=80115 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The tree format names the difference outright: &lt;code&gt;Covering index lookup&lt;/code&gt; becomes &lt;code&gt;Index lookup&lt;/code&gt;. Each of the 80,115 secondary-index entries carries the primary key, and each one now costs a second descent into the clustered index to fetch &lt;code&gt;total_cents&lt;/code&gt;. Thirteen milliseconds became 471. And these are warm numbers. The first time the 106-row uncovered query ran against a cold buffer pool it took 259 ms, because 106 scattered heap pages had to come off disk. The cold number is the one the p99 sees.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Where the ORM comes in&lt;/strong&gt;
 &lt;div&gt;ActiveRecord needs &lt;code&gt;.select(:status, :created_at)&lt;/code&gt;, Django needs &lt;code&gt;.only(...)&lt;/code&gt;, Prisma needs an explicit &lt;code&gt;select&lt;/code&gt; block; without them every one of these frameworks fetches every column, and no index covers &lt;code&gt;SELECT *&lt;/code&gt; on a real table. The generated SQL is the contract with the index, not the method call. On the handful of queries that carry the most traffic, the generated statement is worth reading once.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="heap-fetches-0-is-a-property-of-the-moment"&gt;Heap Fetches: 0 is a property of the moment
&lt;/h2&gt;&lt;p&gt;The Postgres version of this story has a second act that has nothing to do with the SELECT list. A Postgres index carries no visibility information. It cannot tell whether the row an entry points to is visible to the current transaction, so an index-only scan consults the visibility map, a bitmap with one bit per heap page that says &amp;ldquo;every tuple on this page is visible to everyone.&amp;rdquo; Pages with the bit set are skipped. Pages without it get a heap fetch to check.&lt;/p&gt;
&lt;p&gt;Any write to a page clears its bit. Here is the covered query for customer 42, the one at 0.134 ms with zero heap fetches, after an update to 84 of their orders that touched &lt;code&gt;notes&lt;/code&gt;, a column that isn&amp;rsquo;t in the index and isn&amp;rsquo;t in the query:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Index Only Scan using idx_orders_cust_status_created on orders
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (actual time=0.071..0.442 rows=266 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Heap Fetches: 168
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Buffers: shared hit=350
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Execution Time: 0.442 ms
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The node still says &lt;code&gt;Index Only Scan&lt;/code&gt;. It went to the heap 168 times. Nothing about the query or the index changed; a write to an unrelated column on the same pages did it. &lt;code&gt;VACUUM&lt;/code&gt; restores the bits (168 fetches dropped to 49 after one pass and to 0 after a second), which is why autovacuum health and index-only scan performance are the same problem on a busy table.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;Heap Fetches: 0&lt;/code&gt; in a plan is a statement about the visibility map right now, not about the index. The same query can show zero at 09:00 and thousands at 09:05 after a batch update, with the node name unchanged. When an index-only scan is slower than it should be, read the &lt;code&gt;Heap Fetches&lt;/code&gt; line before touching the index definition, and check &lt;code&gt;pg_stat_user_tables&lt;/code&gt; for when the table was last vacuumed. The &lt;code&gt;pg_visibility&lt;/code&gt; extension will tell you exactly how many pages have lost their bit.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This is also why the &amp;ldquo;add the column to the index&amp;rdquo; fix was not the end of the incident. The index that shipped for customer 777 came up at 29.5 ms, an 80 percent recovery, but with &lt;code&gt;Heap Fetches: 4101&lt;/code&gt;, because a 100,000-row update to an unrelated range of orders had cleared the bit on 4,101 pages that also happened to hold seller 777&amp;rsquo;s rows. The next autovacuum cleared it. Coverage got the plan back; vacuum got the performance back.&lt;/p&gt;
&lt;h2 id="extend-the-index-or-shrink-the-projection"&gt;Extend the index, or shrink the projection
&lt;/h2&gt;&lt;p&gt;Two fixes hold up, and they fail in different places.&lt;/p&gt;
&lt;p&gt;Extending the index puts &lt;code&gt;total_cents&lt;/code&gt; in the leaf entries so the query never needs the heap. Postgres has &lt;code&gt;INCLUDE&lt;/code&gt; for this since version 11: the column rides along in the leaf pages without becoming part of the B-tree ordering, so it costs nothing on the search path.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_orders_cust_status_created_incl&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INCLUDE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL has no &lt;code&gt;INCLUDE&lt;/code&gt;. The equivalent is to append the column as a regular key column, &lt;code&gt;(customer_id, status, created_at, total_cents)&lt;/code&gt;, and the optimizer picks the covering form when it&amp;rsquo;s there; on the 80,115-row case that brought 471 ms back to 10.9 ms. InnoDB secondary indexes already carry the primary key at the leaves, so &lt;code&gt;SELECT id&lt;/code&gt; is covered for free on any secondary index, which is worth remembering before adding &lt;code&gt;id&lt;/code&gt; to one.&lt;/p&gt;
&lt;p&gt;The cost is on the write side, and it&amp;rsquo;s specific. The Postgres &lt;code&gt;INCLUDE&lt;/code&gt; index grew from 194 MB to 237 MB for one four-byte column across 5 million rows. More to the point, &lt;code&gt;total_cents&lt;/code&gt; is a column that changes: orders get amended, refunded, partially shipped. Every update to it now has to write a new entry into this index, and on Postgres an update that changes any indexed column can never take the heap-only (HOT) path, so it also writes an entry into every other index on the table. The column that made the list page fast is the column the order-editing path pays for on every save. On a table taking thousands of writes a second, that trade deserves a number before it ships, not after.&lt;/p&gt;
&lt;p&gt;Shrinking the projection avoids all of that. The list view keeps the covered query, and the total is fetched on demand for the one order the user expands, or the list-view columns are frozen as a contract and the index matches the contract. This is the cheaper fix when the new column is decorative and the harder one to hold, because the next feature request also wants one more column. Whichever way it goes, naming the index after the query it serves (&lt;code&gt;idx_orders_list_view&lt;/code&gt;) and pointing a comment on the query back at the index makes the dependency visible to the next person, or the next assistant, asked to &amp;ldquo;just add a column to the list page.&amp;rdquo; Re-checking that a projection is still inside its index is not a step either of them takes unprompted.&lt;/p&gt;
&lt;p&gt;For the queries that carry real traffic, the &lt;code&gt;EXPLAIN (ANALYZE, BUFFERS)&lt;/code&gt; output belongs in the pull request next to the SQL, for the same reason &lt;a class="link" href="https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/" &gt;one added line in a plan&lt;/a&gt; can turn 100 minutes into 40 ms. The &lt;code&gt;Buffers&lt;/code&gt; line is the one to compare: 34 pages to 270 is a shrug, 1,020 to 166,667 is the incident, and neither shows up in a diff that adds one column.&lt;/p&gt;</description></item><item><title>A Query on a 3-Billion-Row Table Took 100 Minutes: One Added Line Made It 40ms</title><link>https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/</link><pubDate>Thu, 03 Sep 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/a-query-on-a-3-billion-row-table-took-100-minutes-one-added-line-made-it-40ms/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post A Query on a 3-Billion-Row Table Took 100 Minutes: One Added Line Made It 40ms" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;An &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; tree has one line that owns the time; find it before reading anything else, then diagnose two things separately: whether the query computes more than the question needs, and whether the filter matches an index&amp;rsquo;s leading columns. Worked through a real reporting query against a 3.2-billion-row table, rewritten from 1h43m to 40ms with no schema change. The rewrite only works because a small set exists to filter by; when there isn&amp;rsquo;t one, the fix is an index, and that is neither free nor reversible on a table that size.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The alert fires the way it always does: a statement crossed thirty minutes, the alerting job snapshotted everything running on the server, and the snapshot is attached to the ticket. In it, a reporting query against &lt;code&gt;inventory.stock_counts&lt;/code&gt;, a table whose &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; counter reads 3,252,568,638. Wall time at the moment of the snapshot: 1 hour 43 minutes, still running.&lt;/p&gt;
&lt;p&gt;If the ticket didn&amp;rsquo;t have the snapshot, &lt;code&gt;SHOW FULL PROCESSLIST;&lt;/code&gt; is where the SQL comes from. &lt;code&gt;FULL&lt;/code&gt; matters; without it the query text is cut at 100 characters, and the interesting part of this one is past character 100.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;span class="lnt"&gt;27
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;row_count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [E] per-row check
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signoffs&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counts_with_any_signoff&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [1] main table
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [2] derived table &amp;#34;latest&amp;#34;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;max_ts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;max_ts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [3] scope: whose stores?
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;count_lines&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [4] the detail rows
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [3] scope, continued
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- [5] final rollup
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The reflex is to paste this into &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; and go looking for the red line. Hold that for a minute. The plan will tell you what the query costs. It cannot tell you what the answer &lt;em&gt;should&lt;/em&gt; cost, and without that yardstick every line in the plan looks equally suspicious. That yardstick comes from reading the query.&lt;/p&gt;
&lt;h2 id="read-the-query-before-the-plan"&gt;Read the query before the plan
&lt;/h2&gt;&lt;p&gt;SQL is not evaluated top to bottom. The &lt;code&gt;SELECT&lt;/code&gt; line runs almost last. The order is &lt;code&gt;FROM&lt;/code&gt;, &lt;code&gt;JOIN&lt;/code&gt;s, &lt;code&gt;WHERE&lt;/code&gt;, &lt;code&gt;GROUP BY&lt;/code&gt;, &lt;code&gt;SELECT&lt;/code&gt;, &lt;code&gt;ORDER BY&lt;/code&gt;, with innermost self-contained subqueries evaluated before the query that wraps them. Read it in that order and the bracketed pieces above sort themselves out.&lt;/p&gt;
&lt;p&gt;Start with the scope: scan the &lt;code&gt;WHERE&lt;/code&gt; and &lt;code&gt;ON&lt;/code&gt; clauses for literal constants. They define the intended size of the answer. Piece [3] joins &lt;code&gt;retail.stores&lt;/code&gt; and filters &lt;code&gt;st.chain_id = 2047&lt;/code&gt;, restricting everything to one retail chain&amp;rsquo;s stores, and &lt;code&gt;sc.supplier_id = 713&lt;/code&gt; restricts to one supplier. One chain is a few hundred stores. (&lt;code&gt;stock_counts&lt;/code&gt; has its own &lt;code&gt;chain_id&lt;/code&gt; column. Why the query scopes through another table instead is answered when we open the schema below.)&lt;/p&gt;
&lt;p&gt;Next, the innermost self-contained piece: the derived table [2]. It has no references to the outside and could run on its own. For supplier 713, it computes the newest &lt;code&gt;counted_at&lt;/code&gt; for every store. Measured against the scope from [3]: it knows nothing about any chain. It does this for virtually every store supplier 713 has ever delivered to, across every chain on the platform. The &lt;code&gt;IS NOT NULL&lt;/code&gt; filter drops only the minority of rows with no store. Nothing narrows it to the few hundred stores the question is about.&lt;/p&gt;
&lt;p&gt;Then [1] joined to [2]. Joining &lt;code&gt;latest&lt;/code&gt; back to &lt;code&gt;stock_counts&lt;/code&gt; on &lt;code&gt;(store_id, supplier_id, max_ts = counted_at)&lt;/code&gt; is the standard &amp;ldquo;latest row per group&amp;rdquo; idiom: the subquery finds &lt;em&gt;when&lt;/em&gt; the newest count happened per store, the join fetches the row from that moment. A &lt;code&gt;MAX(...)&lt;/code&gt; subquery joined back on equality to the same table is this idiom every time you see it.&lt;/p&gt;
&lt;p&gt;Piece [4] is the detail: each stock count has child rows in &lt;code&gt;inventory.count_lines&lt;/code&gt;, one per SKU counted, and those carry the &lt;code&gt;line_type&lt;/code&gt; and &lt;code&gt;resolution&lt;/code&gt; being counted. Piece [E] asks, per stock count, whether at least one sign-off row exists. &lt;code&gt;EXISTS&lt;/code&gt; returns 1 or 0, so &lt;code&gt;SUM(EXISTS ...)&lt;/code&gt; counts stock counts with any sign-off; a per-row lookup, cheap if &lt;code&gt;signoffs.stock_count_id&lt;/code&gt; is indexed. Piece [5] groups the survivors by &lt;code&gt;(line_type, resolution)&lt;/code&gt; and counts.&lt;/p&gt;
&lt;p&gt;In one sentence: for chain 2047 and supplier 713, take each store&amp;rsquo;s most recent stock count and count its lines by variance type and resolution, noting which counts have been signed off.&lt;/p&gt;
&lt;p&gt;That sentence already exposes the problem. The question is scoped to one chain, but piece [2] computes the latest timestamp for every store of supplier 713. The query as written relies on the optimizer to push the chain scoping into [2]. Whether it did is what the plan shows.&lt;/p&gt;
&lt;h2 id="run-explain-analyze-on-a-replica-then-find-the-one-line"&gt;Run EXPLAIN ANALYZE on a replica, then find the one line
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;EXPLAIN &amp;lt;query&amp;gt;&lt;/code&gt; prints the execution plan without running the query: driving table, index per join, join order. Every number in it is an estimate. &lt;code&gt;rows=&lt;/code&gt; and &lt;code&gt;cost=&lt;/code&gt; come from table statistics and can be off by orders of magnitude, so plain &lt;code&gt;EXPLAIN&lt;/code&gt; shows the intended shape of the plan, not where the time goes. &lt;code&gt;EXPLAIN ANALYZE &amp;lt;query&amp;gt;&lt;/code&gt; executes the query and prints the same tree annotated with measurements: &lt;code&gt;actual time=X..Y&lt;/code&gt; is milliseconds to first row and to last row, &lt;code&gt;rows=&lt;/code&gt; is rows actually processed per loop, &lt;code&gt;loops=&lt;/code&gt; is how many times the step ran. That turns &amp;ldquo;the query is slow&amp;rdquo; into &amp;ldquo;this specific line is slow.&amp;rdquo; &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/" &gt;Part II of the queries series&lt;/a&gt; covers the general reading; this post is one plan read all the way down.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; runs the query, so it takes as long as the query takes; the run below took 1h43m to produce. It is also all-or-nothing: killing it early returns an error, not a partial plan. Run it on a replica, never the primary, and know that a consistent-read snapshot held open for that long delays InnoDB purge on that replica for the duration. A timeout on the diagnostic run is pointless: the alert already established the query runs past thirty minutes, so any cap either kills the run (no output) or sits above the half-hour mark (no protection). Start with plain &lt;code&gt;EXPLAIN&lt;/code&gt;, and pay the full &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; cost once if the actuals are needed. The timeout belongs on the fix-validation runs later, where milliseconds are expected: &lt;code&gt;SET max_execution_time = 60000;&lt;/code&gt; stops a wrong candidate from running another 1h43m. It governs plain &lt;code&gt;SELECT&lt;/code&gt;s and may not interrupt &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; itself, so keep &lt;code&gt;KILL QUERY &amp;lt;id&amp;gt;&lt;/code&gt; ready from a second session.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The full output, produced in 1h 43m 29s:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Sort: inventory.cl.line_type, inventory.cl.resolution (actual time=6.21e+6..6.21e+6 rows=3 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on &amp;lt;temporary&amp;gt; (actual time=6.21e+6..6.21e+6 rows=3 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Aggregate using temporary table (actual time=6.21e+6..6.21e+6 rows=3 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=8114 rows=3248) (actual time=6.21e+6..6.21e+6 rows=1823 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=6173 rows=1627) (actual time=6.21e+6..6.21e+6 rows=552 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=4951 rows=1397) (actual time=6.21e+6..6.21e+6 rows=552 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index lookup on st using chain_id (chain_id=2047) (cost=62.3 rows=603) (actual time=0.0498..0.274 rows=603 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: ((latest.supplier_id = 713) and (latest.max_ts is not null)) (cost=129e+6..5.79 rows=2.32) (actual time=10297..10297 rows=0.915 loops=603)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index lookup on latest using &amp;lt;auto_key2&amp;gt; (store_id=retail.st.id) (cost=228e+6..228e+6 rows=23.2) (actual time=10297..10297 rows=0.915 loops=603)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Materialize (cost=228e+6..228e+6 rows=392e+6) (actual time=6.21e+6..6.21e+6 rows=6.57e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: ((inventory.stock_counts.supplier_id = 713) and (inventory.stock_counts.store_id is not null)) (cost=188e+6 rows=392e+6) (actual time=6.75..6.18e+6 rows=6.57e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index skip scan for grouping on stock_counts using store_supplier_counted_at over (NULL &amp;lt; store_id) (cost=188e+6 rows=392e+6) (actual time=0.0268..6.14e+6 rows=491e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index lookup on sc using store_supplier_counted_at (store_id=retail.st.id, supplier_id=713, counted_at=latest.max_ts) (cost=0.758 rows=1.16) (actual time=0.089..0.0898 rows=1 loops=552)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index lookup on cl using stock_count_id (stock_count_id=inventory.sc.id) (cost=0.994 rows=2) (actual time=0.246..0.249 rows=3.3 loops=552)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Indentation is nesting. Deeper lines execute first and feed results upward; the top line, the &lt;code&gt;Sort&lt;/code&gt;, happens last. Times are milliseconds, often in scientific notation: &lt;code&gt;6.21e+6&lt;/code&gt; ms is 6,210,000 ms, about 1.7 hours. Don&amp;rsquo;t try to understand every line. Find the one with the largest &lt;code&gt;actual time&lt;/code&gt; and the largest &lt;code&gt;rows&lt;/code&gt;. A parent&amp;rsquo;s time includes its children, which is why &lt;code&gt;Sort&lt;/code&gt;, &lt;code&gt;Aggregate&lt;/code&gt;, and all three joins show &lt;code&gt;6.21e+6&lt;/code&gt;; descend until the time originates.&lt;/p&gt;
&lt;p&gt;It originates here:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Covering index skip scan for grouping on stock_counts using store_supplier_counted_at over (NULL &amp;lt; store_id)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (cost=188e+6 rows=392e+6) (actual time=0.0268..6.14e+6 rows=491e+6 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL scanned the &lt;code&gt;store_supplier_counted_at&lt;/code&gt; index on &lt;code&gt;stock_counts&lt;/code&gt;, touched 491 million index entries, and spent 6.14e+6 ms on it, about 1.7 hours. The line sits under &lt;code&gt;Materialize&lt;/code&gt;: this branch is piece [2], the derived table &lt;code&gt;latest&lt;/code&gt;, being built. It confirms the reading from the previous section. The optimizer did not push the chain scoping into [2]. It computed latest timestamps for 6.57 million stores (&lt;code&gt;Materialize ... rows=6.57e+6&lt;/code&gt;) and then the outer join discarded all but 552 of them.&lt;/p&gt;
&lt;p&gt;Two things worth noticing before moving on. The estimate on that line, &lt;code&gt;rows=392e+6&lt;/code&gt;, was in the right ballpark of the actual 491 million, and the estimate is printed by plain &lt;code&gt;EXPLAIN&lt;/code&gt;. The 1h43m diagnostic run bought certainty; a line estimating hundreds of millions of rows under a &lt;code&gt;Materialize&lt;/code&gt; was already visible for free. And the rest of the tree is healthy: the &lt;code&gt;chain_id&lt;/code&gt; lookup found its 603 rows in 0.274 ms, and the &lt;code&gt;sc&lt;/code&gt; and &lt;code&gt;cl&lt;/code&gt; lookups take fractions of a millisecond per loop. One line owns the incident.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Why the optimizer couldn&amp;#39;t rescue this one&lt;/strong&gt;
 &lt;div&gt;MySQL 8.0.22 added &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/derived-condition-pushdown-optimization.html" target="_blank" rel="noopener"
 &gt;derived condition pushdown&lt;/a&gt;, which can move an outer &lt;code&gt;WHERE&lt;/code&gt; condition into a derived table, including one with &lt;code&gt;GROUP BY&lt;/code&gt;, when the condition references only the derived table&amp;rsquo;s columns and constants. The chain scoping here is neither. It lives in a join condition to a different table (&lt;code&gt;latest.store_id = st.id&lt;/code&gt;, with the constant on &lt;code&gt;st.chain_id&lt;/code&gt;), so there is nothing shaped like a pushable predicate. The optimizer did what the query said: build &lt;code&gt;latest&lt;/code&gt; for the whole supplier, then join.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="open-the-table-and-diagnose-two-things-separately"&gt;Open the table and diagnose two things separately
&lt;/h2&gt;&lt;p&gt;The slow line names its table and index. Pull the definition:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SHOW&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="k"&gt;G&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;bigint&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_supplier_counted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;chain_supplier_counted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ENGINE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;InnoDB&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;3252568638&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;AUTO_INCREMENT=3252568638&lt;/code&gt;: the table has seen roughly 3.2 billion rows. The scale is why the mistake costs hours rather than seconds.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;chain_supplier_counted_at&lt;/code&gt; on &lt;code&gt;(chain_id, supplier_id, counted_at)&lt;/code&gt; looks purpose-built for this question, which raises the obvious objection: why doesn&amp;rsquo;t the query filter &lt;code&gt;WHERE sc.chain_id = 2047&lt;/code&gt; and skip the &lt;code&gt;stores&lt;/code&gt; join entirely? Because &lt;code&gt;chain_id&lt;/code&gt; on &lt;code&gt;stock_counts&lt;/code&gt; is not populated. It is &lt;code&gt;DEFAULT NULL&lt;/code&gt;, and rows do not reliably carry it, so filtering on it returns wrong (empty) results. The query scopes through &lt;code&gt;retail.stores&lt;/code&gt; because that table is the source of truth for which chain owns a store. That resolves the question parked earlier, and it is verified empirically in the next section, where the wrong candidate gets tested anyway.&lt;/p&gt;
&lt;p&gt;Before building a fix around a promising index, check that the column has data:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;with_chain&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- COUNT(col) skips NULLs; if with_chain is ~0, the index is unusable
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;A decoy like this deserves a follow-up outside the incident. The column and its index are not neutral. The index takes disk and write overhead on every insert while being unusable for reads, and it invites wrong queries; the wrong candidate below is exactly that. The resolution is either to backfill &lt;code&gt;chain_id&lt;/code&gt; so the index becomes trustworthy, or, more likely, to drop the index (fast) and then the column, after auditing for remaining readers and writers.&lt;/p&gt;
&lt;p&gt;Now compare the usable index against the piece of the query that produced the slow line, the derived table [2]:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The relevant concept is the leftmost-prefix rule. A composite index is ordered like a phone book sorted by (last name, first name): lookups by last name, or last name plus first name, are fast, and a lookup by first name alone gets no help from the sort order. &lt;code&gt;store_supplier_counted_at&lt;/code&gt; leads with &lt;code&gt;store_id&lt;/code&gt;, but piece [2] only constrains &lt;code&gt;supplier_id&lt;/code&gt;, the second column. MySQL could not seek directly to supplier 713&amp;rsquo;s rows. Instead it did what the plan line says, a skip scan for grouping (the tree-format name for the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html" target="_blank" rel="noopener"
 &gt;loose index scan&lt;/a&gt; MySQL uses for &lt;code&gt;GROUP BY&lt;/code&gt;): walk every distinct &lt;code&gt;store_id&lt;/code&gt; in the index, and probe each one for supplier 713. That is the 491 million entries and the 1.7 hours.&lt;/p&gt;
&lt;p&gt;The diagnosis is two independent problems, and they have separate fixes:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Logical waste, visible from reading the query: piece [2] computes latest timestamps for 6.57 million stores when the question needs 603.&lt;/li&gt;
&lt;li&gt;Physical mismatch, confirmed from the schema: the filter column &lt;code&gt;supplier_id&lt;/code&gt; does not lead any trustworthy index, so the wasteful computation was also executed in the worst available way.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="fix-the-logical-waste-first"&gt;Fix the logical waste first
&lt;/h2&gt;&lt;p&gt;The principle: compute the small set first and hand it to the big table, so the index&amp;rsquo;s leading column is constrained. The chain has 603 stores, and the usable index leads with &lt;code&gt;store_id&lt;/code&gt;; feeding the store ids in turns every lookup into an index seek. Three versions of the same idea, from most manual to ready-to-run.&lt;/p&gt;
&lt;p&gt;V1 is two steps, fully manual, and fine for a one-off investigation because each step is verifiable on its own:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Step 1: get the small set
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Step 2: paste the ids into the original query&amp;#39;s subquery
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1001&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1002&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- the 603 ids
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;V2 keeps the shape of the original and adds one line. Minimal diff, easy to review, and the version that gets validated below:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;max_ts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- &amp;lt;-- the fix
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;V3 is V2 spelled out end to end. Everything is the original except the one added line:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;span class="lnt"&gt;27
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;row_count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signoffs&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counts_with_any_signoff&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;max_ts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- &amp;lt;-- the fix
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;latest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;max_ts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;count_lines&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;All three work the same way underneath. &lt;code&gt;store_id&lt;/code&gt;, the index&amp;rsquo;s leading column, is now constrained to 603 values, so the subquery becomes roughly 603 index seeks instead of a 491-million-entry skip scan. Seconds instead of hours, no schema change, reversible. Results are identical as long as &amp;ldquo;latest per store&amp;rdquo; does not depend on rows outside the chain, and here it does not: the join back to &lt;code&gt;sc&lt;/code&gt; was already store-scoped, and a store belongs to one chain.&lt;/p&gt;
&lt;p&gt;A further form replaces the derived table with a correlated subquery. It plans cleaner, with no &lt;code&gt;Materialize&lt;/code&gt; step at all, and it is the version that shipped, shown at the end.&lt;/p&gt;
&lt;p&gt;The rewrite works because a small set exists: &lt;code&gt;retail.stores&lt;/code&gt; supplies one chain&amp;rsquo;s worth of store ids. If that scoping were unavailable (a genuinely per-supplier question: latest stock count for every store supplier 713 delivers to), there is nothing to filter first and the fix has to be physical. The filter is on &lt;code&gt;supplier_id&lt;/code&gt;, so &lt;code&gt;supplier_id&lt;/code&gt; has to lead the index:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;supplier_store_counted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;That reads supplier 713&amp;rsquo;s contiguous slice of the index, already sorted by store with timestamps sorted within each, and drops reads from roughly 491 million to roughly 6.6 million: minutes instead of hours. For the per-supplier question all 6.57 million groups are genuinely needed, so that is the floor.&lt;/p&gt;
&lt;p&gt;It is not needed here, and it is not free. Hours of online DDL (gh-ost or pt-online-schema-change) on a 3.2-billion-row table, tens of gigabytes of disk, write overhead on every future insert, replica-lag risk during the build. It is also net-new, because the existing &lt;code&gt;store_supplier_counted_at&lt;/code&gt; still serves &amp;ldquo;history of one store&amp;rdquo; lookups and can&amp;rsquo;t be swapped out. The shape that holds up is to propose it only if per-supplier queries become a recurring pattern, sized against write volume. Query rewrites are free and reversible; indexes on billion-row tables are neither. A third, long-term option is backfilling &lt;code&gt;chain_id&lt;/code&gt; so &lt;code&gt;chain_supplier_counted_at&lt;/code&gt; becomes usable, and that is a data-quality project rather than a query fix.&lt;/p&gt;
&lt;h2 id="verify-correctness-before-speed"&gt;Verify correctness before speed
&lt;/h2&gt;&lt;p&gt;Verification is two questions, in order: is it still correct, then is it actually fast. Two candidate fixes were tested. Each fails a different one of the two checks, which is why both checks are needed. The baseline comes from the original 1h43m run: 3 groups, 1,823 rows, 552 stock counts. Capture that before touching anything; a fix without a baseline can&amp;rsquo;t be verified, only admired.&lt;/p&gt;
&lt;p&gt;The first candidate filters on &lt;code&gt;sc.chain_id&lt;/code&gt; directly, the one the decoy index suggests. It runs in 0.08 ms and is wrong:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Index lookup on stock_counts using chain_supplier_counted_at (chain_id=2047, supplier_id=713)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; (actual time=0.0212..0.0212 rows=0 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;rows=0&lt;/code&gt;: no stock count carries this &lt;code&gt;chain_id&lt;/code&gt;, because the column is unpopulated. Every later join in the plan reads &lt;code&gt;never executed&lt;/code&gt;, since the driving table was empty, which is why the query finished in a tenth of a millisecond. Fast does not imply correct. Compare row counts against the baseline every time. And &lt;code&gt;never executed&lt;/code&gt; in a plan means something upstream short-circuited; find the deepest line with &lt;code&gt;rows=0&lt;/code&gt; to see where the data ran out.&lt;/p&gt;
&lt;p&gt;The second candidate is V2, the subquery filtered to the chain&amp;rsquo;s stores. Correct, and 79 ms against 1h 43m:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;Original&lt;/th&gt;
 &lt;th&gt;&lt;code&gt;chain_id&lt;/code&gt; filter&lt;/th&gt;
 &lt;th&gt;store filter (V2)&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Time&lt;/td&gt;
 &lt;td&gt;1h 43m&lt;/td&gt;
 &lt;td&gt;0.08 ms&lt;/td&gt;
 &lt;td&gt;79 ms&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Rows read to build &lt;code&gt;latest&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;491,000,000&lt;/td&gt;
 &lt;td&gt;0&lt;/td&gt;
 &lt;td&gt;12,500&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Result correct?&lt;/td&gt;
 &lt;td&gt;baseline&lt;/td&gt;
 &lt;td&gt;wrong (empty)&lt;/td&gt;
 &lt;td&gt;matches baseline&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Generalized, the checklist is short. Plain &lt;code&gt;EXPLAIN&lt;/code&gt; first: confirm the expected index appears and no line estimates millions of rows. &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; with &lt;code&gt;max_execution_time&lt;/code&gt; set: confirm where the time actually goes. Compare results to the known-good baseline, row counts at minimum. A fix that changes the answer is not a fix.&lt;/p&gt;
&lt;p&gt;The version that shipped is the correlated form. Same idea as the one-line fix, constrain everything to the chain&amp;rsquo;s stores, expressed directly: drive from &lt;code&gt;retail.stores&lt;/code&gt; and compute each store&amp;rsquo;s latest timestamp on demand, with no derived table at all.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;row_count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;EXISTS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signoffs&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counts_with_any_signoff&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;retail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stores&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sc2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;counted_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_counts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc2&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;store_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;supplier_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;713&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inventory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;count_lines&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stock_count_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chain_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2047&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resolution&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The results, 0.22 s from a cold cache:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;line_type&lt;/th&gt;
 &lt;th&gt;resolution&lt;/th&gt;
 &lt;th&gt;row_count&lt;/th&gt;
 &lt;th&gt;counts_with_any_signoff&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Variance&lt;/td&gt;
 &lt;td&gt;None&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Variance&lt;/td&gt;
 &lt;td&gt;Reorder&lt;/td&gt;
 &lt;td&gt;551&lt;/td&gt;
 &lt;td&gt;311&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Variance&lt;/td&gt;
 &lt;td&gt;WriteOff&lt;/td&gt;
 &lt;td&gt;36&lt;/td&gt;
 &lt;td&gt;36&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Reconciled&lt;/td&gt;
 &lt;td&gt;None&lt;/td&gt;
 &lt;td&gt;1236&lt;/td&gt;
 &lt;td&gt;1236&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Its &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt;, complete, at 40 ms warm:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-&amp;gt; Sort: inventory.cl.line_type, inventory.cl.resolution (actual time=40.1..40.1 rows=4 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Table scan on &amp;lt;temporary&amp;gt; (actual time=40.1..40.1 rows=4 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Aggregate using temporary table (actual time=40.1..40.1 rows=4 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=991 rows=1192) (actual time=0.118..29.7 rows=1824 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Nested loop inner join (cost=273 rows=603) (actual time=0.104..25.3 rows=552 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index lookup on st using chain_id (chain_id=2047) (cost=62.2 rows=603) (actual time=0.0429..0.191 rows=603 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Filter: (inventory.sc.counted_at = (select #3)) (cost=0.25 rows=1) (actual time=0.041..0.0415 rows=0.915 loops=603)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index lookup on sc using store_supplier_counted_at (store_id=retail.st.id, supplier_id=713, counted_at=(select #3)) (cost=0.25 rows=1) (actual time=0.0292..0.0296 rows=0.915 loops=603)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Select #3 (subquery in condition; dependent)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Aggregate: max(inventory.sc2.counted_at) (cost=0.895 rows=1) (actual time=0.013..0.013 rows=1 loops=1707)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Covering index lookup on sc2 using store_supplier_counted_at (store_id=retail.st.id, supplier_id=713) (cost=0.574 rows=3.21) (actual time=0.00462..0.0114 rows=22 loops=1707)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; -&amp;gt; Index lookup on cl using stock_count_id (stock_count_id=inventory.sc.id) (cost=0.993 rows=1.98) (actual time=0.00626..0.00769 rows=3.3 loops=552)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The whole plan drives from the small set. &lt;code&gt;stores using chain_id&lt;/code&gt; finds 603 rows in 0.19 ms, and every other line is a per-store index seek. The derived table is gone: no &lt;code&gt;Materialize&lt;/code&gt;, no skip scan, no 6.57-million-row temp table. The &lt;code&gt;Select #3 (dependent)&lt;/code&gt; branch computes each store&amp;rsquo;s &lt;code&gt;MAX(counted_at)&lt;/code&gt; on demand, about 22 index entries per evaluation at roughly 0.01 ms each. On the order of 38,000 index entries read instead of 491,000,000. Check timings against a cold run, since warm-cache numbers flatter any fix; here it is 40 ms warm and 0.22 s cold.&lt;/p&gt;
&lt;p&gt;The baseline check, per the previous section: &lt;code&gt;loops=552&lt;/code&gt;, the same 552 stock counts. The rollup shows 4 groups and 1,824 rows against the baseline&amp;rsquo;s 3 and 1,823, and a delta like that has to be explained before shipping, not waved through because the direction is right. It is stable across reruns, and the new group is a single row (&lt;code&gt;Variance&lt;/code&gt; / &lt;code&gt;None&lt;/code&gt;, &lt;code&gt;row_count=1&lt;/code&gt;): one count line landed between the baseline run and this one. The data moved, not the semantics.&lt;/p&gt;
&lt;h2 id="red-flags-for-the-next-plan"&gt;Red flags, for the next plan
&lt;/h2&gt;&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;What you see&lt;/th&gt;
 &lt;th&gt;What it means&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;actual time&lt;/code&gt; in &lt;code&gt;e+6&lt;/code&gt; ms on one line&lt;/td&gt;
 &lt;td&gt;The bottleneck (1e+6 ms is about 17 minutes)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;rows&lt;/code&gt; read far above rows kept by the parent line&lt;/td&gt;
 &lt;td&gt;No usable index for that filter; rows are discarded during the scan&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Table scan on &amp;lt;big table&amp;gt;&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;No index used at all&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;Materialize ... rows=&amp;lt;millions&amp;gt;&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;A subquery built a huge temp table before outer filters could apply&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;skip scan&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;The index&amp;rsquo;s leading column is not filtered (leftmost-prefix mismatch)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Estimated &lt;code&gt;rows=&lt;/code&gt; vs actual off by 100x or more&lt;/td&gt;
 &lt;td&gt;Stale statistics; plain &lt;code&gt;EXPLAIN&lt;/code&gt; estimates are unreliable here&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;An index that fits the query but is unused or returns 0 rows&lt;/td&gt;
 &lt;td&gt;Check the column data; an unpopulated column makes the index unusable&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;&lt;code&gt;never executed&lt;/code&gt; on join branches&lt;/td&gt;
 &lt;td&gt;The plan short-circuited; find the deepest line with &lt;code&gt;rows=0&lt;/code&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The method, compressed: understand what the query is asking and how big the answer should be; run &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; on a replica; find the one line that owns the time; open &lt;code&gt;SHOW CREATE TABLE&lt;/code&gt; and diagnose two things separately, whether the query computes more than it needs (fix: filter the small set first) and whether the filter matches an index&amp;rsquo;s leading columns (fix: reorder or add an index); then verify correctness against a known-good baseline before trusting the speed.&lt;/p&gt;</description></item><item><title>Collation Drift: The Silent Index Killer</title><link>https://explainanalyze.com/p/collation-drift-the-silent-index-killer/</link><pubDate>Thu, 23 Jul 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/collation-drift-the-silent-index-killer/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Collation Drift: The Silent Index Killer" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A MySQL schema that lived through the 5.7-to-8.0 upgrade carries two eras of collation: old &lt;code&gt;VARCHAR&lt;/code&gt; columns on &lt;code&gt;utf8mb4_general_ci&lt;/code&gt;, newer ones on &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt;. Join across that seam and MySQL either refuses outright or silently wraps one column in a per-row charset conversion that takes its index out of play. Converging fixes it, but the same conversion changes which rows count as equal, so the migration itself can fail on duplicate keys.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A routine 8.0 upgrade goes fine for a week. Then a report that has run every morning for three years starts throwing:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;ERROR 1267 (HY000): Illegal mix of collations
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;(utf8mb4_general_ci,IMPLICIT) and (utf8mb4_0900_ai_ci,IMPLICIT)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;for operation &amp;#39;=&amp;#39;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The join is &lt;code&gt;orders.customer_ref = customers.external_id&lt;/code&gt;, two &lt;code&gt;VARCHAR(64)&lt;/code&gt; columns that compared fine on 5.7. Whoever is on call finds the Stack Overflow answer in about ninety seconds: append &lt;code&gt;COLLATE utf8mb4_0900_ai_ci&lt;/code&gt; to one side, the error clears, the report runs, the incident closes. What nobody clocks is that the query that used to finish in 40ms now takes nine seconds, because the &lt;code&gt;COLLATE&lt;/code&gt; clause wrapped &lt;code&gt;customers.external_id&lt;/code&gt; in a conversion and the index on it is out of play. The loud failure got traded for a quiet one.&lt;/p&gt;
&lt;p&gt;That &lt;code&gt;COLLATE&lt;/code&gt; clause is the obvious fix and the trap: it clears the error by forcing the conversion that kills the index. Where the two collations came from, and why neither is wrong, is the rest of the story.&lt;/p&gt;
&lt;h2 id="two-eras-of-collation-and-nobody-broke-a-rule"&gt;Two eras of collation, and nobody broke a rule
&lt;/h2&gt;&lt;p&gt;Charset is the encoding, which bytes stand for which characters. Collation is the comparison and sort rules layered on top: whether &lt;code&gt;a&lt;/code&gt; equals &lt;code&gt;A&lt;/code&gt;, whether &lt;code&gt;é&lt;/code&gt; equals &lt;code&gt;e&lt;/code&gt;, what order strings come back in. Every text column carries both, inherited from its table, which inherits from the database, which falls back to the server default when nobody said otherwise.&lt;/p&gt;
&lt;p&gt;That default moved. MySQL 8.0.1 changed &lt;code&gt;collation_server&lt;/code&gt; and &lt;code&gt;collation_database&lt;/code&gt; from &lt;code&gt;latin1_swedish_ci&lt;/code&gt; to &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt; (&lt;a class="link" href="https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-1.html" target="_blank" rel="noopener"
 &gt;per the 8.0.1 release notes, April 2017&lt;/a&gt;), and the default collation for the &lt;code&gt;utf8mb4&lt;/code&gt; charset itself changed from &lt;code&gt;utf8mb4_general_ci&lt;/code&gt;, the 5.7 default, to &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt;. So a table created with &lt;code&gt;CHARSET=utf8mb4&lt;/code&gt; and no explicit collation got &lt;code&gt;utf8mb4_general_ci&lt;/code&gt; in 2021 and &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt; in 2024. Same DDL, same intent, different result, because a version boundary sat between the two runs. The drift is the absence of a decision, resolved twice by two different defaults.&lt;/p&gt;
&lt;p&gt;It is sitting in plain sight in the catalog:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHARACTER_SET_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLLATION_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;COLUMNS&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TABLE_SCHEMA&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;mydb&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DATA_TYPE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;varchar&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;char&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;text&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;enum&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHARACTER_SET_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLLATION_NAME&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Two rows back where you expected one is the whole diagnosis. &lt;code&gt;COLLATION_NAME&lt;/code&gt; is a column nobody reads, human or model. &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;An assistant generating the join&lt;/a&gt; reads &lt;code&gt;COLUMN_NAME&lt;/code&gt; and &lt;code&gt;DATA_TYPE&lt;/code&gt; off the same view and never glances at the collation; the mismatch is machine-readable and goes unread on both ends.&lt;/p&gt;
&lt;h2 id="the-conversion-is-a-function-on-your-indexed-column"&gt;The conversion is a function on your indexed column
&lt;/h2&gt;&lt;p&gt;When two columns share a charset and differ only in collation, and both take their collation implicitly from the schema, MySQL refuses to pick a winner. It raises &lt;code&gt;Illegal mix of collations&lt;/code&gt; and stops. Loud, obstructive, honest.&lt;/p&gt;
&lt;p&gt;When the charsets differ, though, MySQL does not stop. Picture a &lt;code&gt;utf8mb4&lt;/code&gt; column on one side and a &lt;code&gt;latin1&lt;/code&gt; or &lt;code&gt;utf8mb3&lt;/code&gt; column that predates the utf8mb4 migration on the other. &lt;code&gt;utf8mb4&lt;/code&gt; is a superset of both, so MySQL converts the narrower side up to &lt;code&gt;utf8mb4&lt;/code&gt; to make the comparison legal, and does it without a word. That conversion is &lt;code&gt;convert(customers.external_id using utf8mb4)&lt;/code&gt; wrapped around the column and evaluated per row. A function around an indexed column is the textbook &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable predicate&lt;/a&gt;: the B-tree is sorted by the raw &lt;code&gt;latin1&lt;/code&gt; bytes, the planner needs the &lt;code&gt;utf8mb4&lt;/code&gt; form of every value to compare, and it cannot get that from the index without computing it first. So it computes it, row by row, across the table. No error. Clean result count. Two hundred times the latency.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;COLLATE&lt;/code&gt; band-aid from the opener reproduces this on purpose. &lt;code&gt;... COLLATE utf8mb4_0900_ai_ci&lt;/code&gt; on &lt;code&gt;customers.external_id&lt;/code&gt; is a function on the column, and whichever side you collate is the side that loses its index. The loud version got silenced by hand-writing the silent one.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;The rule underneath collation is general: MySQL can&amp;rsquo;t use an index on a column it has to implicitly convert. Coercibility decides who gets converted. A literal is &lt;code&gt;COERCIBLE&lt;/code&gt; and yields to the column, so &lt;code&gt;WHERE col = 'x'&lt;/code&gt; is safe, and the cliff is column-versus-column across the seam: joins, correlated subqueries, &lt;code&gt;IN (SELECT ...)&lt;/code&gt;. Type coercion tilts the other way. Compare an indexed &lt;code&gt;VARCHAR&lt;/code&gt; to a number and the column, not the literal, converts to a float per row, so the index drops and &lt;code&gt;'49123-x'&lt;/code&gt; quietly matches &lt;code&gt;49123&lt;/code&gt;. A &lt;code&gt;BIGINT&lt;/code&gt; column joined to a &lt;code&gt;VARCHAR&lt;/code&gt; one is the same failure with a type mismatch instead of a collation one. Ask of any predicate on an indexed column whether the engine can answer it without touching every value.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-connection-carries-a-collation-too"&gt;The connection carries a collation too
&lt;/h2&gt;&lt;p&gt;The seam isn&amp;rsquo;t only in the schema. Every session has its own &lt;code&gt;collation_connection&lt;/code&gt;, set by the driver at connect time, and it drifts the same way. Connector/J is the usual offender: before &lt;a class="link" href="https://dev.mysql.com/doc/relnotes/connector-j/en/news-8-0-13.html" target="_blank" rel="noopener"
 &gt;8.0.13, in 2018&lt;/a&gt;, a connection asking for &lt;code&gt;utf8mb4&lt;/code&gt; came up on &lt;code&gt;utf8mb4_general_ci&lt;/code&gt; even against a server default of &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt;, so the session and the columns disagreed straight out of the pool.&lt;/p&gt;
&lt;p&gt;The same coercibility rule spares your indexed lookups: a bound &lt;code&gt;?&lt;/code&gt; parameter yields to the column, so &lt;code&gt;WHERE col = ?&lt;/code&gt; keeps its index whatever the connection is set to. Variables are where it bites. A session variable or a stored-procedure local carries the connection collation at column-level coercibility, so comparing one to a &lt;code&gt;0900_ai_ci&lt;/code&gt; column throws the same &lt;code&gt;1267&lt;/code&gt; from the opener, now out of application code with no &lt;code&gt;ALTER&lt;/code&gt; in sight. That one is a driver fix, not a migration: pin &lt;code&gt;connectionCollation&lt;/code&gt; to match the schema, or upgrade past the versions that guessed.&lt;/p&gt;
&lt;h2 id="converging-changes-what-equal-means"&gt;Converging changes what &amp;ldquo;equal&amp;rdquo; means
&lt;/h2&gt;&lt;p&gt;The durable fix is to converge: one charset (&lt;code&gt;utf8mb4&lt;/code&gt;, never legacy &lt;code&gt;utf8&lt;/code&gt;/&lt;code&gt;utf8mb3&lt;/code&gt;) and one collation per database, set at the database level so every new table inherits it instead of guessing. The modern MySQL 8 default &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt; is the natural pick unless you genuinely want accent- and case-sensitive comparison, in which case &lt;code&gt;utf8mb4_0900_as_cs&lt;/code&gt; is the sibling to standardize on instead. Matching collation on both sides of every join is the thing that keeps the index in play. That is the point of converging, not the tidiness of a uniform catalog.&lt;/p&gt;
&lt;p&gt;The convergence itself is &lt;code&gt;ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci&lt;/code&gt;, which rewrites the whole table. On anything large that&amp;rsquo;s &lt;code&gt;gh-ost&lt;/code&gt; or &lt;code&gt;pt-online-schema-change&lt;/code&gt; territory, not a maintenance-window &lt;code&gt;ALTER&lt;/code&gt;. The rewrite is the cheap part.&lt;/p&gt;
&lt;p&gt;The expensive part is that collation defines equality, and changing the collation changes which rows are equal. &lt;code&gt;utf8mb4_0900_ai_ci&lt;/code&gt; is accent-insensitive and case-insensitive: &lt;code&gt;'café' = 'cafe'&lt;/code&gt;, &lt;code&gt;'Smith' = 'SMITH'&lt;/code&gt;. Under &lt;code&gt;utf8mb4_bin&lt;/code&gt; or an &lt;code&gt;_as_cs&lt;/code&gt; collation those are distinct values. Converge a column that carried a &lt;code&gt;UNIQUE&lt;/code&gt; index under the stricter collation, and any two rows that were distinct only by accent or case now collide.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;CONVERT TO CHARACTER SET&lt;/code&gt; on a column with a &lt;code&gt;UNIQUE&lt;/code&gt; constraint can abort with &lt;code&gt;ERROR 1062 Duplicate entry&lt;/code&gt; when two formerly-distinct values fold together under the new collation. This is not a rare corner on real user data: &lt;code&gt;José&lt;/code&gt; and &lt;code&gt;Jose&lt;/code&gt;, &lt;code&gt;O'Brien&lt;/code&gt; and &lt;code&gt;OBRIEN&lt;/code&gt;, city names, usernames. Dry-run the fold before the &lt;code&gt;ALTER&lt;/code&gt;, something like &lt;code&gt;SELECT val, COUNT(*) FROM t GROUP BY val COLLATE utf8mb4_0900_ai_ci HAVING COUNT(*) &amp;gt; 1&lt;/code&gt;, and reconcile the collisions first, or the migration dies halfway through a table rewrite.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Postgres has the same class of bug wearing a different mask, and there the index does not slow down, it goes wrong. Postgres leans on the operating system&amp;rsquo;s &lt;code&gt;libc&lt;/code&gt; locale for text collation, so its sort order is only as stable as the C library underneath it. glibc 2.28 (shipped 2018, in RHEL 8 and Debian 10) rewrote collation for nearly every locale, and &lt;a class="link" href="https://www.crunchydata.com/blog/glibc-collations-and-data-corruption" target="_blank" rel="noopener"
 &gt;Crunchy Data documented the fallout in 2019&lt;/a&gt;: a B-tree built under the old ordering becomes silently corrupt under the new one, so &lt;code&gt;WHERE&lt;/code&gt; misses rows the index insists aren&amp;rsquo;t there and &lt;code&gt;UNIQUE&lt;/code&gt; quietly stops being unique. The trigger is an OS upgrade nobody connected to the database. Same &amp;ldquo;nobody broke a rule&amp;rdquo; shape, worse blast radius. The modern defense is the ICU collation provider with versioned collations, which at least warns you when the version underneath drifts.&lt;/p&gt;
&lt;p&gt;Run the &lt;code&gt;information_schema&lt;/code&gt; query against your busiest database before you need to. Two rows where you expected one is a latency cliff someone eventually hits at 40x, files under &amp;ldquo;the database is slow,&amp;rdquo; and never traces back to a server default that changed in 2017.&lt;/p&gt;</description></item><item><title>Cross-Database Joins: The Coupling You Can't See Until You Split</title><link>https://explainanalyze.com/p/cross-database-joins-the-coupling-you-cant-see-until-you-split/</link><pubDate>Sat, 11 Jul 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/cross-database-joins-the-coupling-you-cant-see-until-you-split/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Cross-Database Joins: The Coupling You Can't See Until You Split" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A join across two schemas on the same MySQL server costs nothing to write, which is exactly why nobody counts it. Every one of those joins is a hard coupling that pins both schemas to one instance, so the day you need to split for scale, the joins are the wall. And the referential integrity you assumed the boundary carried was never enforced to begin with.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Somewhere in the codebase, since roughly the first month, there is a query like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sku&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;qty&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount_due&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;line_items&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;billing&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;invoices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inv&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;li&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-07-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Two schemas, &lt;code&gt;orders&lt;/code&gt; and &lt;code&gt;billing&lt;/code&gt;, one MySQL server, single-digit milliseconds for three years. In that time roughly four hundred more queries have grown the same shape: application code, a dozen dbt models, cron reports, the admin dashboard. Nobody wrote a design doc for any of them, because MySQL lets you qualify a table with &lt;code&gt;schema.table&lt;/code&gt; and join across the boundary as if it weren&amp;rsquo;t there. Then the primary crosses 90% on the capacity dashboard, the obvious relief is to lift &lt;code&gt;billing&lt;/code&gt; onto its own instance, and the migration plan dies in review on one line: four hundred joins stop compiling the moment the schemas live on different servers.&lt;/p&gt;
&lt;h2 id="the-fdw-that-looks-like-a-fix"&gt;The FDW that looks like a fix
&lt;/h2&gt;&lt;p&gt;The escape hatch is obvious: split anyway and put a foreign data wrapper between the instances so the joins keep working across the wire. The syntax survives the split. The performance does not. Cross-server joins don&amp;rsquo;t push down; &lt;code&gt;postgres_fdw&lt;/code&gt; only sends a join to the far side when both tables live on the same foreign server (&lt;a class="link" href="https://www.postgresql.org/docs/current/postgres-fdw.html" target="_blank" rel="noopener"
 &gt;the docs are explicit&lt;/a&gt;), so across two instances the join executes locally, pulling rows over the network first. Svix &lt;a class="link" href="https://www.svix.com/blog/fdw-pitfalls/" target="_blank" rel="noopener"
 &gt;hit exactly this in October 2025&lt;/a&gt;: a join that failed to push down pulled both tables in their entirety, moved millions of rows where thousands were expected, and timed out.&lt;/p&gt;
&lt;p&gt;So the FDW gives you back the &lt;code&gt;SELECT&lt;/code&gt; and takes away the reason you split. Every cross-boundary query drags its working set back over the network to be joined next to the primary anyway.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;An FDW join across instances is a distributed join, not a local one&lt;/strong&gt;
 &lt;div&gt;If &lt;code&gt;EXPLAIN (VERBOSE)&lt;/code&gt; shows the join in the local plan rather than in the &lt;code&gt;Remote SQL&lt;/code&gt;, the far table is shipping over in full. Treat every cross-instance FDW join as a network transfer sized by the larger table, not by your &lt;code&gt;WHERE&lt;/code&gt; clause.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="free-to-write-fake-underneath"&gt;Free to write, fake underneath
&lt;/h2&gt;&lt;p&gt;A MySQL &amp;ldquo;database&amp;rdquo; and a MySQL &amp;ldquo;schema&amp;rdquo; are the same object: a namespace on one server. There is no cross-database join inside one server, only a fully-qualified one, and the qualifier costs a few keystrokes. Postgres draws the line elsewhere. Schemas in one database join freely; separate databases can&amp;rsquo;t be joined at all without FDW or &lt;code&gt;dblink&lt;/code&gt;, so a team that split into Postgres databases hits the wall on day one, where at least it&amp;rsquo;s visible.&lt;/p&gt;
&lt;p&gt;The worse fact: MySQL foreign keys can cross schemas. &lt;code&gt;REFERENCES billing.invoices(order_id)&lt;/code&gt; is legal DDL, and almost nobody writes it, because the schemas belong to different teams and nobody wants their writes gated on another team&amp;rsquo;s table. So the boundary those four hundred joins cross has no enforced referential integrity and never did. The failure modes are the ones you&amp;rsquo;d predict from &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;dropping a foreign key&lt;/a&gt;, except no FK was ever declared: orphaned line items with no cascade to catch them, ID-type drift that turns the join into a silent cast (&lt;code&gt;BIGINT&lt;/code&gt; on one side, &lt;code&gt;CHAR(36)&lt;/code&gt; UUID after a migration on the other), backfills that assume the far side exists.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;This is a same-server, cross-namespace problem&lt;/strong&gt;
 &lt;div&gt;Cross-schema joins inside one Postgres database, or on a MySQL server you never intend to split, are not the anti-pattern. The coupling bites when scale forces the namespaces onto different instances. If that day never comes, the free join is genuinely free; the trap is assuming that&amp;rsquo;s your situation when the growth curve says otherwise.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Recovery has the same hole. Each database backs up independently, two &lt;code&gt;--single-transaction&lt;/code&gt; dumps, each consistent, each catching a different instant, and the skew surfaces only when you restore one side. Roll &lt;code&gt;billing&lt;/code&gt; back to 04:00 while &lt;code&gt;orders&lt;/code&gt; keeps its afternoon of writes and every cross-schema join now compares two timelines. No constraint exists to fail, so nothing errors; the afternoon&amp;rsquo;s orders point at invoices the restore erased. (Postgres PITR replays WAL for the whole cluster, never one database, so an independent restore was never on offer.) The honest unit of &lt;a class="link" href="https://explainanalyze.com/p/before-the-bad-write/" &gt;backup and restore&lt;/a&gt; is the set of databases your queries treat as one, and four hundred joins say that set has two members.&lt;/p&gt;
&lt;h2 id="find-the-joins-before-you-need-the-split"&gt;Find the joins before you need the split
&lt;/h2&gt;&lt;p&gt;The coupling lives in query text, not the catalog: no &lt;code&gt;pg_constraint&lt;/code&gt; row, no &lt;code&gt;KEY_COLUMN_USAGE&lt;/code&gt; entry. But it always leaves a fingerprint, because at least one table in the query has to be namespace-qualified. On a running MySQL server, the digest table preserves the qualifiers:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SCHEMA_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DIGEST_TEXT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;COUNT_STAR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SUM_ROWS_EXAMINED&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;events_statements_summary_by_digest&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SCHEMA_NAME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;orders&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DIGEST_TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LIKE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;%billing.%&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;COUNT_STAR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Two caveats: &lt;code&gt;DIGEST_TEXT&lt;/code&gt; truncates at &lt;code&gt;performance_schema_max_digest_length&lt;/code&gt; (1024 bytes by default), and the digest table resets on restart, so it shows recent traffic, not history. Pair it with a grep of the repos (application code, ORM models, dbt sources) for the &lt;code&gt;billing.&lt;/code&gt; qualifier. Datadog ran this inventory across 30-plus teams when they &lt;a class="link" href="https://www.datadoghq.com/blog/engineering/unwinding-shared-database/" target="_blank" rel="noopener"
 &gt;unwound a shared database in 2025&lt;/a&gt;; mapping the cross-boundary queries came before any carving. In Postgres the hunt is easier: the cross-instance dependency is already wearing a &lt;code&gt;postgres_fdw&lt;/code&gt; label, listed in &lt;code&gt;pg_foreign_table&lt;/code&gt;, with query text in &lt;code&gt;pg_stat_statements&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="what-the-fixes-cost"&gt;What the fixes cost
&lt;/h2&gt;&lt;p&gt;The cheapest move is writing the coupling down where a machine can read it: &lt;code&gt;COMMENT 'references billing.invoices.order_id, service-owned, no FK across instances'&lt;/code&gt; on the column. Readable by humans and by &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;schema-reading assistants&lt;/a&gt;, enforced by nothing. If the boundary has to actually hold, a scheduled reconciliation job anti-joins the two sides and reports the orphans the missing FK would have rejected at write time (&lt;a class="link" href="https://explainanalyze.com/p/scale-the-pattern-not-the-instance/" &gt;the scale-the-class fix&lt;/a&gt; applied to integrity). Eventually-consistent by construction, and someone has to own the alert. For the analytics joins, a consolidated replica (logical replication or CDC into one reporting instance) makes the join legal again, at the price of a pipeline to run and a lag window to reason about. For the transactional joins, the durable answer is the one Datadog and the &lt;a class="link" href="https://docs.aws.amazon.com/prescriptive-guidance/latest/database-decomposition/joins.html" target="_blank" rel="noopener"
 &gt;AWS decomposition guidance&lt;/a&gt; both land on: replace the query with a service call. That&amp;rsquo;s the real unwind and the expensive one, a rewrite of every call site the join touched.&lt;/p&gt;
&lt;p&gt;When the split itself arrives, replication makes it survivable, and the order of operations matters more than the tooling. Write-path joins and cross-schema transactions get rewritten first, while everything still shares a server; after cutover there is no atomicity across the boundary. Then the future cluster comes up as a replica of the whole instance, &lt;code&gt;billing&lt;/code&gt; reads migrate at leisure, and writes cut over in a short freeze once GTIDs match. &lt;a class="link" href="https://github.blog/engineering/infrastructure/partitioning-githubs-relational-databases-scale/" target="_blank" rel="noopener"
 &gt;GitHub ran this playbook in 2021&lt;/a&gt;: SQL linters to stop new cross-boundary queries, then a write-cutover that moved 130 tables with sub-second downtime. Read joins stay gradual. A multi-source channel keeps feeding &lt;code&gt;orders&lt;/code&gt; into the new cluster read-only, so stragglers join against a lagged copy while the digest counts drain to zero; give that channel a deadline, it&amp;rsquo;s the weld on life support. One trap: a read join that feeds a write decision (check invoice status, then update the order) is a cross-schema transaction wearing a SELECT, and the lagged copy turns it into a race. The digest table won&amp;rsquo;t flag it; only the call sites do.&lt;/p&gt;
&lt;p&gt;One more consumer of the missing metadata: an AI assistant scoped to one connection (the default MCP posture) either declares the column unjoinable or, handed a shared server, cheerfully reproduces the free cross-schema join with no signal that it just crossed a service boundary. The column comment is the only place the relationship exists in a form the model reads.&lt;/p&gt;
&lt;p&gt;The join that costs nothing to write is the one that costs the most to remove. Every &lt;code&gt;schema.table&lt;/code&gt; qualifier typed without a second thought is a vote to keep both schemas on one server forever, cast by someone who had no idea there was an election.&lt;/p&gt;</description></item><item><title>Self-Healing Databases with a Health Check and a Watch Script</title><link>https://explainanalyze.com/p/self-healing-databases-with-a-health-check-and-a-watch-script/</link><pubDate>Wed, 08 Jul 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/self-healing-databases-with-a-health-check-and-a-watch-script/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Self-Healing Databases with a Health Check and a Watch Script" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;If you run &lt;a class="link" href="https://developer.hashicorp.com/consul/docs" target="_blank" rel="noopener"
 &gt;Consul&lt;/a&gt;, or any mesh with real health checks, you already own the primitives for narrow database self-healing: a check on a pressure signal, a watch that fires a handler, a handler that runs one vetted remediation and files evidence. That covers a class of pages the current pitch reserves for autonomous ops agents. The line that keeps it safe is narrow: grow a buffer, purge consumed binlogs, advance a dead slot. Failover and dropping data stay human.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The checkpoint-age line on the InnoDB dashboard has been climbing for two hours. It opened the evening at a comfortable third of the redo log&amp;rsquo;s capacity and it is now past three-quarters, closing on the point where InnoDB stops being polite about flushing. A batch reconciliation that normally runs Sunday afternoon got kicked off by a failed deploy&amp;rsquo;s retry logic, and it is rewriting a wide table row by row. Nobody is looking at the graph. When checkpoint age crosses &lt;code&gt;log_max_modified_age_sync&lt;/code&gt;, InnoDB flips to synchronous flushing, write latency goes vertical, and the job that generated the pressure is now blocked behind the flushing it caused. The page fires a few minutes later, on the symptom, connections piling up against a server that is already stalling.&lt;/p&gt;
&lt;p&gt;The remediation here is boring and it has existed since MySQL 8.0.30, when &lt;a class="link" href="https://dev.mysql.com/blog-archive/dynamic-innodb-redo-log-in-mysql-80/" target="_blank" rel="noopener"
 &gt;&lt;code&gt;innodb_redo_log_capacity&lt;/code&gt; became dynamic&lt;/a&gt;. A single &lt;code&gt;SET GLOBAL innodb_redo_log_capacity = ...&lt;/code&gt; resizes the redo log online, no restart, and you can watch the resize settle through &lt;code&gt;Innodb_redo_log_resize_status&lt;/code&gt;. A larger redo log raises the sync threshold, so the same checkpoint age is now a smaller fraction of capacity, and the burst gets room to drain before InnoDB ever reaches for the aggressive flush. Done in the first ten minutes of that climb, the whole incident is a non-event nobody wakes up for. The signal you would trigger on, checkpoint age against the sync point, is the same signal a health check would sample. Which is the part worth sitting with: if you run Consul, or Nomad, or a Kubernetes cluster with liveness probes that actually mean something, you already own every piece needed to make that &lt;code&gt;SET GLOBAL&lt;/code&gt; fire on its own, deterministically, before the page.&lt;/p&gt;
&lt;h2 id="the-2026-move-is-to-give-it-a-brain"&gt;The 2026 move is to give it a brain
&lt;/h2&gt;&lt;p&gt;Given the vendor cycle we are all living through, the reflex is that this is the poster use case for an autonomous ops agent. Wire it to the metrics, give it a &lt;code&gt;query(sql)&lt;/code&gt; tool and a shell, let it reason about the pressure and choose a remediation. And to be fair to the model, a decent one will surface &lt;code&gt;SET GLOBAL innodb_redo_log_capacity&lt;/code&gt; among its suggestions without much prompting. Generation was never the missing piece.&lt;/p&gt;
&lt;p&gt;The problem is that this class of page has exactly one correct action and no judgment in it. Wrapping one deterministic action inside a component that samples from a distribution over possible actions buys you nothing and adds a floor of fabricated actions underneath. The agent that resizes the redo log today can, on a similar-looking graph next week, decide the real fix is to kill the connection that &amp;ldquo;looks like&amp;rdquo; the offender, or reach for a config it half-remembers from a different engine version. An agent earns its keep when the next step is genuinely ambiguous and the value is in the reasoning. Here the reasoning is a threshold comparison and a lookup. A watch handler that runs one vetted script does the identical job with none of the &lt;a class="link" href="https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/" &gt;confident-misattribution surface&lt;/a&gt; an LLM brings to a decision it was never needed for. The reliability question is not whether the model can find the fix. It is &lt;a class="link" href="https://explainanalyze.com/p/narrow-tools-narrow-agents-where-agent-reliability-actually-comes-from/" &gt;where the floor on wrong actions sits&lt;/a&gt;, and for a one-lever page the floor of a deterministic handler is zero.&lt;/p&gt;
&lt;h2 id="what-the-watch-and-the-handler-actually-do"&gt;What the watch and the handler actually do
&lt;/h2&gt;&lt;p&gt;Consul&amp;rsquo;s health checks are the wiring. You register a script check against the database service: a small query that runs every N seconds and returns &lt;code&gt;critical&lt;/code&gt; when checkpoint age passes your threshold. That query hits &lt;code&gt;information_schema.innodb_metrics&lt;/code&gt; for &lt;code&gt;log_lsn_checkpoint_age&lt;/code&gt; (the counter is off by default, so it needs &lt;code&gt;innodb_monitor_enable&lt;/code&gt;), or it parses the LOG section of &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt;. When the check flips to critical, a &lt;a class="link" href="https://developer.hashicorp.com/consul/docs/automate/watch" target="_blank" rel="noopener"
 &gt;watch of type &lt;code&gt;check&lt;/code&gt;&lt;/a&gt; fires. The watch invokes a handler, and Consul writes the check&amp;rsquo;s current state to that handler as JSON on stdin: node, check ID, status, the check&amp;rsquo;s own output. The handler is an ordinary executable. It reads the JSON, confirms the condition still holds, runs the one thing it exists to run, and records that it did.&lt;/p&gt;
&lt;p&gt;&lt;img alt="The full loop for the redo-log case: the check polls quietly, the burst flips it critical, the watch executes the handler, the handler resizes and files evidence, and the circuit-breaker branch pages a human instead" loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/self-healing-databases-with-a-health-check-and-a-watch-script/handler-flow.svg"&gt;&lt;/p&gt;
&lt;p&gt;For the redo log that handler is close to trivial. Parse stdin, see the checkpoint-age check critical, issue the &lt;code&gt;SET GLOBAL&lt;/code&gt;, poll &lt;code&gt;Innodb_redo_log_resize_status&lt;/code&gt; until the resize completes. The grow is a bounded step, 10 or 20 percent, never a doubling, and it happens only after the handler checks the volume it is about to grow into: redo log files sit on the same disk as the data files and binlogs, and growing the log into a nearly full filesystem trades a flushing stall for a full-disk stop, which is strictly worse. Then come the two steps that keep the automation honest, and each is one curl. A POST to Jira&amp;rsquo;s REST API creates a ticket in the team&amp;rsquo;s morning queue: write burst pushed checkpoint age to the sync point at this timestamp, capacity grown from X to Y, the offending statement digest attached if the check captured one. A second webhook drops a low-urgency line in the team channel, so the &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-iii-a-working-responder-rotation/" &gt;responder&lt;/a&gt; learns about it over coffee instead of from the graph. The remediation bought the night. The ticket is the handoff that decides, in daylight, whether this was a runaway job to fix or a capacity trend to plan for.&lt;/p&gt;
&lt;p&gt;There is a shortcut worth checking before wiring any of that: if your monitoring already alerts on configuration drift, running values diverging from what &lt;code&gt;my.cnf&lt;/code&gt; or the parameter group declares, the resize surfaces there on its own. &lt;code&gt;SET GLOBAL&lt;/code&gt; changes the runtime value and leaves the configured one untouched, so the next drift report carries the change whether or not anyone filed anything, and reconciling it (persist the new capacity or revert it) is exactly the morning decision the ticket existed to force. A drift alert with an owner can replace the Jira call. What it cannot carry is the trigger, so the handler still logs why it fired.&lt;/p&gt;
&lt;p&gt;Disk filling from binary logs is the same shape with a sharper edge. A disk-free check goes critical, and the naive handler purges the oldest binlogs to claw back space. The safe handler does not purge blind, and it does not need a topology registry to see the cluster, because replication already knows its own shape. A script on the primary reads &lt;code&gt;SHOW REPLICAS&lt;/code&gt; for the registered replicas, connects to each one for the binlog file it still needs (the &lt;code&gt;Source_Log_File&lt;/code&gt; in &lt;code&gt;SHOW REPLICA STATUS&lt;/code&gt;, formerly &lt;code&gt;Master_Log_File&lt;/code&gt;), and recurses if a replica has replicas of its own. Only then does it run &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/purge-binary-logs.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;PURGE BINARY LOGS TO&lt;/code&gt;&lt;/a&gt; the lowest file anything still needs, never a file at or beyond it. Never &lt;code&gt;rm&lt;/code&gt;, never &lt;code&gt;find -delete&lt;/code&gt; against the binlog directory; that path corrupts the index and takes the server&amp;rsquo;s own bookkeeping out from under it. &lt;code&gt;PURGE&lt;/code&gt; is the only handle that keeps &lt;code&gt;binlog.index&lt;/code&gt; honest.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;A connected replica protects itself: MySQL refuses to purge a file a live replica is still reading. A replica that has disconnected reports nothing, and purging past what it needs leaves it unable to reconnect and replicate. Every purge also shrinks your point-in-time-recovery window. GitLab&amp;rsquo;s &lt;a class="link" href="https://about.gitlab.com/blog/postmortem-of-database-outage-of-january-31/" target="_blank" rel="noopener"
 &gt;January 31, 2017 outage&lt;/a&gt; is the version of this that ends badly: a lagging secondary needed WAL segments the primary had already discarded (they had no archiving), replication broke, and during the manual re-sync an engineer wiped the wrong data directory. Automation that frees space by discarding replication history is one wrong target away from an unrecoverable replica. The handler&amp;rsquo;s entire value is choosing that target the same conservative way at 4am as you would at your desk.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Both handlers share the property that makes them safe, and it is worth naming before the pattern gets stretched. The redo-log resize reads one counter and moves one bounded lever. The binlog purge reads every replica&amp;rsquo;s position and picks the one file that all of them are past. Neither has to decide which of two servers is telling the truth, and neither has a second-best answer that is almost as good. That is the shape to look for when deciding whether a page belongs to a handler or to a person.&lt;/p&gt;
&lt;h2 id="the-same-shape-without-a-mesh"&gt;The same shape without a mesh
&lt;/h2&gt;&lt;p&gt;Consul is the concrete example, not the requirement. The pattern is a watcher on a pressure signal bound to a handler that runs one action, and every serious stack has it. Nomad and Kubernetes give you liveness checks and operators. Sensu-style monitoring has handlers as a first-class concept. A systemd timer running a guard script is the degenerate case that still counts.&lt;/p&gt;
&lt;p&gt;In AWS the wiring is a CloudWatch alarm on &lt;code&gt;FreeStorageSpace&lt;/code&gt;, replica lag, or freeable memory, routed through EventBridge to a Lambda. The Lambda connects and runs a scoped remediation: kill sessions idle-in-transaction past a hard age, trigger a managed failover, or grow the instance. RDS storage autoscaling is the fully managed instance of exactly the redo-log move from the opener, a watcher on free storage that grows the volume within a ceiling you set, no page, someone else owning the handler. The mechanism is identical; the only thing that changed is who wrote the script.&lt;/p&gt;
&lt;p&gt;Postgres has its own version worth wiring. An abandoned replication slot retains WAL indefinitely and &lt;a class="link" href="https://www.morling.dev/blog/mastering-postgres-replication-slots/" target="_blank" rel="noopener"
 &gt;overrides every other retention setting&lt;/a&gt; until the disk is gone. A check on &lt;code&gt;pg_replication_slots&lt;/code&gt; for a slot that is &lt;code&gt;active = false&lt;/code&gt; while its retained WAL climbs is a clean critical signal, and the remediation is &lt;code&gt;pg_drop_replication_slot()&lt;/code&gt; once the slot is confirmed dead. Since Postgres 13 there is a built-in preventive form, &lt;code&gt;max_slot_wal_keep_size&lt;/code&gt;, which invalidates a slot that exceeds the cap rather than letting it fill the primary.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;Dropping a slot and purging a binlog carry the same tension. The slot exists to protect a consumer that fell behind; invalidating it protects the primary&amp;rsquo;s disk at the cost of that consumer&amp;rsquo;s ability to ever catch up. The automation and the risk run through the same mechanism. That is precisely why the safe set is narrow and the handler files evidence: you want the record of which consumer you just abandoned.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-line-you-dont-cross"&gt;The line you don&amp;rsquo;t cross
&lt;/h2&gt;&lt;p&gt;The set that is safe to automate shares a property: the correct action does not depend on judgment about which side of a fault is healthy. Growing a redo log or a data volume that resizes online. Purging binlogs on a target chosen from live replica positions. Advancing or dropping a slot confirmed abandoned. &lt;a class="link" href="https://explainanalyze.com/p/a-billion-row-versions-from-one-uncommitted-read-stalled-a-mysql-replica/" &gt;Killing a session that matches a precise runaway signature&lt;/a&gt;, rather than one that merely looks busy. The set to keep human is the mirror image. Deciding which node survives a partition is a failover call, and a handler that automates it will happily promote the wrong side of a split brain. Dropping data, resharding, anything where the right move depends on believing one replica over another, stays a person&amp;rsquo;s call. This is the same seam the blog keeps returning to: deterministic narrow tools beat autonomous ones precisely where a wrong action is expensive and the right one is unambiguous, and &lt;a class="link" href="https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/" &gt;a prompt is not a guardrail&lt;/a&gt; around that seam.&lt;/p&gt;
&lt;p&gt;Three failure modes come with the pattern, and pretending they don&amp;rsquo;t is how the pattern turns into a slow-motion outage.&lt;/p&gt;
&lt;p&gt;The first is masking. A handler that resizes the redo log every night, or purges binlogs every morning, converts a capacity-planning signal into silence. The write volume that keeps tripping the check is telling you something, and a handler that quietly absorbs it every time makes sure nobody hears it. This is why the evidence step is load-bearing rather than nice-to-have. Every firing leaves a ticket in the morning triage queue, a metric increment, a log line with the before-and-after, so a human reviews the trend even though no human handled the night. Three redo-log resizes in a month is a capacity conversation; the tickets are what make it visible as one. A remediation that fires and leaves no trace is the outage you get to have twice.&lt;/p&gt;
&lt;p&gt;The second is flapping. A check that oscillates across its threshold will invoke the handler on every crossing, and a handler that is not idempotent (or is expensive) turns that into a storm. The handlers that hold up are idempotent by construction, rate-limited with a cooldown, and wrapped in a circuit breaker that stops after N firings in an hour and pages a human instead. A remediation that has fired six times in an hour is not remediating anything; it is annotating a problem that needs a person.&lt;/p&gt;
&lt;p&gt;The third is the credential surface. A handler that holds &lt;code&gt;SUPER&lt;/code&gt; or &lt;code&gt;REPLICATION_ADMIN&lt;/code&gt; and fires on a threshold is a standing operational risk, an account that can resize, purge, and kill, sitting next to a trigger. Scope it to the single grant its one operation needs, and keep the redo-log handler&amp;rsquo;s credentials disjoint from the binlog-purge handler&amp;rsquo;s. The blast radius of a compromised or buggy handler should be exactly the one lever it was built to pull.&lt;/p&gt;
&lt;p&gt;None of this needs a model. The redo-log handler is a page of bash and a &lt;code&gt;SET GLOBAL&lt;/code&gt; you already know by heart. It will not reason about your incident, and for this class of page that is the entire point: it pulls one boring lever the same way every time, and it files the ticket so you find out on Monday that Saturday almost happened.&lt;/p&gt;</description></item><item><title>Before the Bad Write</title><link>https://explainanalyze.com/p/before-the-bad-write/</link><pubDate>Sat, 04 Jul 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/before-the-bad-write/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Before the Bad Write" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Backups, replicas, and point-in-time recovery are all built for loss: a failure you notice roughly when it happens. Corruption is the opposite. It&amp;rsquo;s copied by replication in milliseconds, faithfully included in every backup, and usually found weeks later, past every retention window you sized for cost. Surviving it takes provenance, knowing which writes to remove, not a restore to a good &amp;ldquo;when&amp;rdquo; that doesn&amp;rsquo;t exist.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;An equipment-auction platform parses dealer feeds overnight; a nightly job writes each asset&amp;rsquo;s price. A refactor of that parser, agent-written and clean in review, declares asset IDs as int where the feed carries bigint. The largest dealer&amp;rsquo;s IDs sit past what 32 bits hold, so each one silently truncates to a smaller number, and that smaller number is some other asset&amp;rsquo;s ID. A $47,250 excavator&amp;rsquo;s price lands on a $3,100 flatbed trailer. Nothing objects: valid ID, plausible price, every row well-formed. The prices feed the valuation model, so every night&amp;rsquo;s mismatches flow into comparables, reserve suggestions, and settlement reports. It runs for forty days before a seller disputes a valuation against their own sale records.&lt;/p&gt;
&lt;p&gt;The code fix is one line. The data is the problem: restore to when? The replica has the mispriced rows, and so does the delayed replica four hours behind it. Every nightly backup for forty days faithfully includes them. Binlog retention is fourteen days. And the moment before the corruption is also forty days of legitimate bids, sales, and settlements nobody will throw away. What actually worked was replaying all forty nightly runs and re-deriving everything downstream, and it was possible only because the raw feed was still there to replay.&lt;/p&gt;
&lt;h2 id="every-layer-in-the-stack-was-sized-for-a-failure-you-notice"&gt;Every layer in the stack was sized for a failure you notice
&lt;/h2&gt;&lt;p&gt;The standard disaster-recovery stack answers one failure class well: loss. A crashed instance, a dead disk, a dropped table, a region going dark. Detection is effectively instant, so a 30-day retention window feels generous, RPO and RTO become the numbers you argue about, and a hot replica reads as a safety net. Corruption breaks the assumption all of that was sized under, because nothing about it announces itself.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;A replica is not a backup against corruption. It&amp;rsquo;s a low-latency copy of the mistake. What replicas buy is high availability and read capacity: failover when the primary dies, and read-only queries served without loading it. By the time you know the write was bad, every replica already agrees with it.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;And week six is the normal case, not the pessimistic one. Plausible-but-wrong data trips no alert: right shape, valid types, clean plans. &lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;Corruption is silent by construction&lt;/a&gt;; it surfaces from outside, a customer disputing a number or a reconciliation refusing to tie out, on the timeline of whoever notices, not the one your retention policy was built around.&lt;/p&gt;
&lt;p&gt;The reflex answer is point-in-time recovery: replay the binlog or WAL to the instant before the bad write and you&amp;rsquo;ve surgically removed it. Retention gets in the way first. The archive is sized in days, because it&amp;rsquo;s a storage line nobody wants to grow (MySQL&amp;rsquo;s &lt;code&gt;binlog_expire_logs_seconds&lt;/code&gt;, a PostgreSQL WAL archive, both usually a few days to two weeks), and week-six corruption is a month past the binlogs that held the offending statement. And even with the archive intact, a point-in-time restore is a full rewind: it removes the bad write and every legitimate write after it. Corruption found three days in sits comfortably inside every retention window, and the restore still doesn&amp;rsquo;t happen, because three days of a busy system&amp;rsquo;s writes is more than anyone will throw away to fix one column. Retention decides whether PITR is possible; the writes that landed since decide whether it&amp;rsquo;s acceptable, and that window closes within hours.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;Scope this to production systems that keep taking writes. If the database is a nightly-rebuilt derived store or a dev environment, &amp;ldquo;restore to before the bad write and replay nothing&amp;rdquo; is a fine answer, and most of this post doesn&amp;rsquo;t apply to you. The trap is specific to systems where the writes after the corruption are themselves valuable and unrecoverable.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-defenses-stack-they-dont-substitute"&gt;The defenses stack, they don&amp;rsquo;t substitute
&lt;/h2&gt;&lt;p&gt;The layers look like an escalation ladder, and in cost they are: each rung up takes more to build and run. But they don&amp;rsquo;t stand in for each other: a production system taking writes it can&amp;rsquo;t afford to lose ends up needing all four, because each one recovers something the others structurally cannot. Managed databases ship the lower rungs as checkboxes, automated backups, PITR, vault-locked copies, and no provider ships the top one, because it&amp;rsquo;s made of your schema and your write path. That&amp;rsquo;s why every team has the first three and almost nobody has the fourth: the log, and the repair tooling around it, built before the incident that needs them. If the mantra is move fast and break things, this is the rung that covers the breaking.&lt;/p&gt;
&lt;h3 id="level-1-backups-that-restore"&gt;Level 1: Backups that restore
&lt;/h3&gt;&lt;p&gt;The floor, and the rung every shop already has, which is why it gets mistaken for the whole ladder. A nightly dump answers &amp;ldquo;the disk died, restore last night,&amp;rdquo; and against corruption it does nothing: the bad write sits in last night&amp;rsquo;s backup and every one after it. The dump is also only half the mechanism: a backup that has never been restored is a hope, not a capability, and the distance between the two grows silently. Versions drift, runbooks go stale, the engineer who knew the procedure cold leaves.&lt;/p&gt;
&lt;p&gt;GitLab&amp;rsquo;s &lt;a class="link" href="https://about.gitlab.com/blog/postmortem-of-database-outage-of-january-31/" target="_blank" rel="noopener"
 &gt;January 31, 2017 outage&lt;/a&gt; is what that looks like. An engineer wiped the data directory on the primary instead of a secondary, and out of five backup and replication techniques deployed, none were working reliably or set up in the first place: pg_dump silently failing on a version mismatch, alert emails bouncing, Azure snapshots never enabled. They survived on an LVM snapshot a staging environment happened to take six hours earlier, and that was the easy failure class, instant detection, obvious cause, a clean state to restore to.&lt;/p&gt;
&lt;p&gt;The shape that holds up is continuous automated restore-verification: on a schedule, restore last night&amp;rsquo;s backup to a scratch instance, check row counts and checksums, run an application-level smoke query, and alert loudly when any of it fails. That converts &amp;ldquo;the backup job exited 0&amp;rdquo; into &amp;ldquo;the backup restores,&amp;rdquo; which are different claims, and GitLab is the distance between them. It also turns restore time into a number you&amp;rsquo;ve measured on a quiet Tuesday: RTO you can quote, not RTO you hope for.&lt;/p&gt;
&lt;p&gt;The backup itself is usually a chain, not one file: a weekly full, differentials or incrementals between them, and the binlog or WAL archive on top, which is what point-in-time recovery replays to reach an instant rather than last night. The chain is how RPO stays small without paying full-dump cost every night, and it raises the bar for the verification job: restoring the whole chain, full plus diffs plus log replay, because one broken link invalidates every restore point behind it. The log archive carries the retention limit from the section above: days, not weeks, never week six.&lt;/p&gt;
&lt;h3 id="level-2-the-copy-nobody-can-delete"&gt;Level 2: The copy nobody can delete
&lt;/h3&gt;&lt;p&gt;Every other rung on this ladder answers to the credentials that run production, and the account that can write the database can usually delete its backups too. That is its own failure class: the deliberate one, where ransomware, a leaked key, or the same runaway agent that damaged the database also reaches for the recovery material. GitLab&amp;rsquo;s backups rotted by accident; this rung exists for the version done on purpose.&lt;/p&gt;
&lt;p&gt;The mechanism is a retention lock: once a week, a full backup lands in an object-storage bucket under a policy (S3 Object Lock and its equivalents) that refuses deletion for at least 60 days, no matter whose credentials ask, including yours. It also quietly stretches the corruption horizon, because when the nightly rotation has long since expired, the locked weekly from before the bad write is often the only prior-value source left.&lt;/p&gt;
&lt;h3 id="level-3-delayed-replication"&gt;Level 3: Delayed replication
&lt;/h3&gt;&lt;p&gt;Regular replication doesn&amp;rsquo;t earn a rung of its own, even though every DR checklist lists it. A hot replica is the availability layer: the disk dies, you fail over, and the app is back before most users notice. It is not a replacement for backups, because &lt;code&gt;DROP DATABASE&lt;/code&gt; replicates with the same fidelity as an &lt;code&gt;INSERT&lt;/code&gt;, and the dropped database is gone on the replica within seconds of being gone on the primary. What earns replication a place on this ladder is the delay.&lt;/p&gt;
&lt;p&gt;A standby held deliberately behind the primary is the window-bound rung. Run it four hours back (MySQL&amp;rsquo;s &lt;code&gt;CHANGE REPLICATION SOURCE TO SOURCE_DELAY&lt;/code&gt;, PostgreSQL&amp;rsquo;s &lt;code&gt;recovery_min_apply_delay&lt;/code&gt;) and you have a four-hour head start to stop a bad write before it applies downstream. Against a &lt;code&gt;TRUNCATE&lt;/code&gt; on the wrong table at 2am, caught by the pager at 2:05, that is a genuine, cheap defense. Against corruption found at week six it does nothing; four hours against a six-week horizon rounds to zero.&lt;/p&gt;
&lt;h3 id="level-4-the-event-log"&gt;Level 4: The event log
&lt;/h3&gt;&lt;p&gt;At the top rung the task changes shape. With a full rollback off the table, the job becomes &amp;ldquo;find every row this bad write touched, decide the correct value for each, and repair it in place while the system keeps taking writes.&amp;rdquo; Selective recovery depends on something none of the lower rungs had to provide: provenance.&lt;/p&gt;
&lt;p&gt;Provenance answers &amp;ldquo;who wrote this row, from which job, deploy, or agent run, and when.&amp;rdquo; With it, the six-week-old corruption becomes a query: every row that actor wrote in that window is the blast radius. Without it you can&amp;rsquo;t scope the damage at all. You&amp;rsquo;re left diffing against a backup that also contains the corruption, or squinting at which of ten million rows &amp;ldquo;look wrong,&amp;rdquo; and for plausible-but-wrong data every one of them looks fine.&lt;/p&gt;
&lt;p&gt;The event log that makes this tractable is one the application owns, covering the main entities. Every meaningful change writes an event in the same transaction as the change itself: which entity, what action, which actor, meaning the service, job, or agent identity rather than only a user, when, and a payload carrying the before and after values plus the request or job run that produced the write. And the log is immutable: events are inserted, never updated, so a later bad write can append wrong events but cannot rewrite the history already there. Because the application writes it, it records intent (this price came from that dealer feed, parsed by that run) rather than raw row deltas, it&amp;rsquo;s queryable in plain SQL, and its retention is your decision instead of a database setting quietly expiring your recovery material. The audit columns most schemas have, &lt;code&gt;created_at&lt;/code&gt; and &lt;code&gt;updated_at&lt;/code&gt;, say when a row changed and nothing about what changed it. The instinct is to widen them: add &lt;code&gt;updated_by&lt;/code&gt;, then a reason column, then history bolted onto every hot table. Even fully decorated, a row holds only its last writer and no prior values, and every table pays the write cost separately. The entity table&amp;rsquo;s job is current state. Attribution and history belong in the event log, one place serving every table.&lt;/p&gt;
&lt;p&gt;In table form, the basic version is small:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNSIGNED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;entity_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNSIGNED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;action_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;SMALLINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNSIGNED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- &amp;#39;price_updated&amp;#39; via lookup table, or an ENUM
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;JSON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- before/after values, request id
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;actor_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;SMALLINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNSIGNED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- service, job, or agent identity, via lookup or could be varchar
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TIMESTAMP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CURRENT_TIMESTAMP&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_entity&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;entity_id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_actor_time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;actor_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOREIGN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;action_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;actions&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOREIGN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;actor_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;actors&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;On PostgreSQL, &lt;code&gt;JSON&lt;/code&gt; becomes &lt;code&gt;JSONB&lt;/code&gt; and &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; becomes an identity column; nothing else changes. The split is deliberate: whatever the recovery queries filter on (entity, actor, time) stays a real column, and everything else rides in one JSON payload whose shape can vary per action without a migration. The action and the actor are IDs into small lookup tables, or enums where you prefer them, so the set of things that can happen to your data, and the set of writers that can make them happen, stays a constrained list instead of &lt;a class="link" href="https://explainanalyze.com/p/text-and-json-columns-where-the-schema-goes-to-hide/" &gt;a schema hiding in free text&lt;/a&gt;. There is no &lt;code&gt;updated_at&lt;/code&gt;, because nothing here is ever updated, and the cleanest way to keep that true is privileges: the application role gets &lt;code&gt;INSERT&lt;/code&gt; and &lt;code&gt;SELECT&lt;/code&gt; on this table and nothing else.&lt;/p&gt;
&lt;p&gt;An event log in this shape also collapses a piece of infrastructure many teams already run. The transactional-outbox pattern exists to get events out of the database reliably: write an outbox row in the same transaction, let CDC (Debezium is the standard name) tail it into a retained topic, publish downstream. An entity event log written in-transaction is that outbox, one worth keeping instead of pruning. Tailed by the same connector, the same rows serve integration today and blast-radius queries at week six.&lt;/p&gt;
&lt;p&gt;Agents change this calculus, just not where people look first. The repair mechanics stay the same: a fat-fingered &lt;code&gt;UPDATE&lt;/code&gt; from a human at 4pm and an agent-generated one from a backfill are both scoped by provenance and repaired forward. What agents move is the two inputs that set the detection horizon, and they move both in the wrong direction. Volume goes up, because &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;the cost of writing a migration collapsed while the cost of reviewing one didn&amp;rsquo;t&lt;/a&gt;, so more writes land with less scrutiny on each. Plausibility goes up too, because the model&amp;rsquo;s failure mode is confident, well-formed, &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;semantically wrong output that reads as correct in review and against a clean EXPLAIN&lt;/a&gt;. Together they push detection past whatever your retention was sized for, which is why the event log shifts from good practice to a requirement the day agents join your write path.&lt;/p&gt;
&lt;h3 id="the-rollback-tooling-has-to-be-ready-before-week-six"&gt;The rollback tooling has to be ready before week six
&lt;/h3&gt;&lt;p&gt;Knowing which rows to fix is half the job. Generating the statements that fix them is the other half, and that tooling has to exist and be rehearsed in advance, because week six is not when you want to be writing your first replay script.&lt;/p&gt;
&lt;p&gt;The event log gives that tooling two repair modes, and both are worth scripting ahead of time. Replay runs the events forward again through corrected code: the auction platform&amp;rsquo;s forty nights of re-parsed feeds were exactly this, re-deriving everything downstream from retained inputs. Inversion goes the other way: read the prior values out of the log for the blast-radius rows and emit reviewed &lt;code&gt;UPDATE&lt;/code&gt;s that put them back. Neither needs a special tool: a query and a generator over a schema you own, built and drilled on a quiet week instead of improvised against the engine&amp;rsquo;s internals mid-incident.&lt;/p&gt;
&lt;p&gt;When the log doesn&amp;rsquo;t reach back far enough, or the bad write predates it, the fallback is the scratch-instance pattern, and it works on any stack: PITR-restore a snapshot to a throwaway instance at the moment before the bad write, read the prior values for just the blast-radius rows, and apply the repair to production as ordinary reviewed &lt;code&gt;UPDATE&lt;/code&gt;s while it keeps serving. It only works if snapshot retention still reaches past the bad write; the policy-locked weekly copy from Level 2 is usually what closes that gap, and the Level 1 restore rig is already most of the machinery it needs. Engine-side flashback exists but is narrow: MariaDB&amp;rsquo;s &lt;code&gt;mysqlbinlog --flashback&lt;/code&gt; can invert ROW binlog events for DML; upstream MySQL and PostgreSQL ship nothing equivalent.&lt;/p&gt;
&lt;p&gt;Written out, the recovery is a pipeline: a provenance query yields the blast radius as rows and their prior values, a generator turns that into inverse statements, a human reviews and applies them, and the system keeps taking writes throughout. The provenance query is not exotic. The auction platform&amp;rsquo;s blast radius starts as one &lt;code&gt;WHERE&lt;/code&gt; clause:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;entity_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;actors&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;actor_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;feed-parser&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-05-25&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;That covers what the bad parser wrote directly. The valuations, comparables, and settlement reports computed from those prices don&amp;rsquo;t need the table to trace them, because the pipeline already knows its own order: valuations read prices, reports read valuations. The derived half of the repair is replay, re-running the downstream jobs on corrected inputs, which is exactly what the forty nights were. Retention is the precondition: the event log, CDC topic, or binlog archive has to reach back across the detection horizon, which for corruption means months. Months of history on a busy table is what time-based partitioning exists for: recent partitions on fast storage, older ones on something slower and cheaper instead of dropped to save space. The mechanics of &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/" &gt;partitioning you don&amp;rsquo;t have to babysit&lt;/a&gt; are their own subject.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&lt;strong&gt;Restoring these writes has to be designed and practiced before anything happens.&lt;/strong&gt; An event that doesn&amp;rsquo;t carry enough to reconstruct the row&amp;rsquo;s prior state is telemetry, not recovery material, and the only way to know which one your log is, is to run the repair against it. A restore drill that only rehearses &amp;ldquo;spin up last night&amp;rsquo;s backup and check it boots&amp;rdquo; is testing the loss path. To test the corruption path, the drill has to rehearse identifying a bad write from weeks ago and repairing forward from the event log while the system keeps taking writes. If you&amp;rsquo;ve never rolled back months of a specific agent&amp;rsquo;s or migration&amp;rsquo;s changes in a drill, that&amp;rsquo;s a capability you don&amp;rsquo;t actually have.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Lay the four rungs against the two failure classes and the ladder collapses into one table.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Layer&lt;/th&gt;
 &lt;th&gt;Covers loss?&lt;/th&gt;
 &lt;th&gt;Covers corruption?&lt;/th&gt;
 &lt;th&gt;Survives detection at&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Nightly backup (30-day)&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;No&lt;/td&gt;
 &lt;td&gt;Includes the corruption from night one&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Snapshot + PITR (WAL/binlog)&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;Only while a rewind is affordable&lt;/td&gt;
 &lt;td&gt;Hours on a busy system; retention caps it anyway&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Policy-locked weekly copy (60-day)&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;As a prior-value source&lt;/td&gt;
 &lt;td&gt;Weeks, at week granularity&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Hot replica&lt;/td&gt;
 &lt;td&gt;Failover only&lt;/td&gt;
 &lt;td&gt;No&lt;/td&gt;
 &lt;td&gt;Copies the bad write in milliseconds&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Delayed replica&lt;/td&gt;
 &lt;td&gt;Extra window&lt;/td&gt;
 &lt;td&gt;Only within delay&lt;/td&gt;
 &lt;td&gt;Hours&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Entity event log (app-owned)&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;As long as you retain it&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;CDC event log (retained)&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;Yes&lt;/td&gt;
 &lt;td&gt;As long as the topic is retained&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Restore drill&lt;/td&gt;
 &lt;td&gt;Validates the above&lt;/td&gt;
 &lt;td&gt;Validates the above&lt;/td&gt;
 &lt;td&gt;Only what the drill actually exercised&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;No single row covers both columns at every horizon, which is why the layers read like an escalation but land as a stack. A replica copies every mistake the primary makes with perfect fidelity, so it protects availability and never data. Failover, never a good prior state. Backups invert that trade: they hold a good prior state, bought with the downtime and the writes-since-last-backup it costs to get there. The event log answers the one thing neither can: a backup or replica restore takes the database as a single unit, so neither can excise one bad transaction and keep the weeks of good ones interleaved around it.&lt;/p&gt;
&lt;p&gt;How large each layer has to be isn&amp;rsquo;t a taste question. It falls out of two numbers the business either names or discovers mid-incident. RPO, the data it can afford to lose, sets backup frequency and how far back the archive reaches. RTO, the downtime it can afford while restoring, sets how often the restore is rehearsed and how much replica topology sits ready to fail over. Corruption adds a third number in the same family: how late the business can afford to find out, which sizes the delayed replica&amp;rsquo;s window and the event log&amp;rsquo;s retention. Availability commitments follow from those measured numbers. The common failure is the reverse order, a contract promising 99.95% over a DR posture that&amp;rsquo;s whatever happened to already be running. A team that has never put figures on its RPO and RTO has set both to whatever the current setup delivers, and reads off the real values during the incident that tests them.&lt;/p&gt;</description></item><item><title>Keep Your Skills Sharp the Hard Way</title><link>https://explainanalyze.com/p/keep-your-skills-sharp-the-hard-way/</link><pubDate>Sat, 27 Jun 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/keep-your-skills-sharp-the-hard-way/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Keep Your Skills Sharp the Hard Way" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Staying sharp in the LLM era isn&amp;rsquo;t nostalgia and it isn&amp;rsquo;t prompt-craft. The &amp;ldquo;agentic loop / context engineering&amp;rdquo; genre is largely a marketing story told by the parties who profit from your subscription and your dependence. The move that holds up is to keep sweating hard problems by hand, because skill you didn&amp;rsquo;t earn through friction doesn&amp;rsquo;t stick, and without it you can&amp;rsquo;t push the model to its ceiling and can&amp;rsquo;t catch it when it ships damage instead of productivity.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Take it to the extreme to see the shape of it. Two people build the same production database with the same model and the same tools. One is a database SME with twenty years on the job. The other is the world&amp;rsquo;s best LLM prompter who genuinely could not tell you what &lt;code&gt;SELECT&lt;/code&gt; does. On day one the prompter&amp;rsquo;s toy demo might even look fine.&lt;/p&gt;
&lt;p&gt;The difference shows up before either of them writes a line, in the questions only one of them knows to ask. The SME reads the workload first. Read-heavy or write-heavy, the capacity it has to carry and the growth curve it has to absorb, and the SLO that decides what &amp;ldquo;fast enough&amp;rdquo; even means before any tuning is worth doing. She pins down how primary keys get generated, because on a write-heavy table a random UUID v4 scattered across the clustered index pays a page-split and write-amplification cost that a monotonic key never does, and that choice is brutal to walk back once the table is large. She knows the shard key Elasticsearch rides on decides whether tonight&amp;rsquo;s extract is a seek or a full scan, so the CDC path and the load it lands on the source get designed up front instead of discovered when the extract starts timing out. And she carries the domain itself: which application-side issues are already known, which failure modes she&amp;rsquo;s personally cleaned off the floor, the landmines you can only steer the model around if you already know they&amp;rsquo;re there. The prompter can aim the model at none of this, because they don&amp;rsquo;t know it exists, and they can&amp;rsquo;t catch the model quietly dropping it. The prompt was never the skill. The skill is what lets the prompt produce a thing that survives contact with production.&lt;/p&gt;
&lt;p&gt;Both databases boot. Both serve the feature set. On day one nobody in the room can point at the difference. Hand the two of them to whoever will carry the pager, though, with no idea which model wrote either one or how good the prompter was, and they take the SME&amp;rsquo;s without opening the schema. They&amp;rsquo;ve met the other kind at 3am.&lt;/p&gt;
&lt;p&gt;The uncomfortable part is personal. You become the prompter by giving away, a little at a time, the work that would have made you the SME the on-call just picked.&lt;/p&gt;
&lt;h2 id="the-block-an-afternoon-fix-doesnt-reach-the-erosion"&gt;The block-an-afternoon fix doesn&amp;rsquo;t reach the erosion
&lt;/h2&gt;&lt;p&gt;The obvious move is to put learning back on the calendar. Block Friday afternoons for a course, grind some algorithm problems, carve out time to &amp;ldquo;stay current.&amp;rdquo; Reasonable on its face, and it mostly fails for two reasons.&lt;/p&gt;
&lt;p&gt;The first is that after-hours willpower loses to the sprint every time. The judgment above didn&amp;rsquo;t erode on a quiet Friday; it eroded inside the delivery flow, one pasted prompt at a time, under deadline, where the agent was the fast path and the fast path was rewarded. A learning block on the calendar is the first thing the sprint eats. The erosion happens in production flow, so a fix that lives outside production flow is aimed at the wrong place.&lt;/p&gt;
&lt;p&gt;The second is that decontextualized practice rebuilds the wrong thing. Grinding LeetCode is useful for the reps it gives you (more on that below), but it doesn&amp;rsquo;t rebuild system-specific judgment, because the judgment that catches a bad migration is judgment about &lt;em&gt;your&lt;/em&gt; schema, your access patterns, the specific table that takes a metadata lock the moment you add a column with a default on the version of MySQL you happen to run. None of that is in a course. It&amp;rsquo;s in the work. Decontextualized practice keeps the general muscle warm; it does not deposit the local knowledge that turns the agent from a liability into a multiplier on your codebase specifically.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;This is an argument for selective retention, not Luddite refusal. This doesn&amp;rsquo;t mean write everything by hand. The point is narrower: there&amp;rsquo;s a specific category of work, the work that builds the judgment you need to supervise the agent, that you give up at your own cost when you outsource it by reflex. Most of the rest, hand it off and move on.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="why-the-skill-you-didnt-sweat-for-doesnt-stick"&gt;Why the skill you didn&amp;rsquo;t sweat for doesn&amp;rsquo;t stick
&lt;/h2&gt;&lt;p&gt;The mechanism here is old and well-measured, and it predates LLMs by decades. Reading the answer and generating the answer leave very different traces in memory.&lt;/p&gt;
&lt;p&gt;Roediger and Karpicke ran the canonical version in &lt;a class="link" href="https://journals.sagepub.com/doi/10.1111/j.1467-9280.2006.01693.x" target="_blank" rel="noopener"
 &gt;Test-Enhanced Learning (2006)&lt;/a&gt;: students who studied a passage and then took a recall test retained substantially more a week later than students who studied the same passage repeatedly without the test. The catch that matters here is the time course. Measured five minutes after, the re-readers actually did better; the testing group only pulled ahead at two days and a week. Effortful retrieval feels worse in the moment and pays off later. That is precisely the trade an engineer declines every time they paste the problem into the agent and read back a smooth answer that felt productive and deposited nothing.&lt;/p&gt;
&lt;p&gt;Robert Bjork named the general principle &lt;a class="link" href="https://bjorklab.psych.ucla.edu/wp-content/uploads/sites/13/2016/07/RBjork_inpress.pdf" target="_blank" rel="noopener"
 &gt;desirable difficulties&lt;/a&gt;: the conditions that make learning feel easiest in the moment are often the ones that produce the weakest long-term retention. His qualifier is the load-bearing part here. A difficulty is only &lt;em&gt;desirable&lt;/em&gt; if the learner has enough foundation to eventually overcome it; below that floor it&amp;rsquo;s just an obstacle. The engineer who hands every hard problem straight to the agent is sitting below the floor, which is why watching it work teaches them nothing; there&amp;rsquo;s no foundation for the struggle to deposit against.&lt;/p&gt;
&lt;p&gt;So the friction isn&amp;rsquo;t a cost you tolerate to look hardcore. The friction is the thing doing the work. Skip it and the skill does not form, the same way watching a climbing video builds no grip strength.&lt;/p&gt;
&lt;p&gt;Set that next to what the tooling actually delivers, because the gap between the felt productivity and the measured productivity is the same shape as the gap between re-reading and retrieval. METR ran a &lt;a class="link" href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/" target="_blank" rel="noopener"
 &gt;controlled study in July 2025&lt;/a&gt; on sixteen experienced developers working in mature repositories they knew well. The developers expected AI to speed them up by about 20%, and afterward believed it had. Measured against the control, they were 19% slower. Google&amp;rsquo;s &lt;a class="link" href="https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report" target="_blank" rel="noopener"
 &gt;2025 DORA report&lt;/a&gt; (published September 2025) found AI adoption near 90% with over 80% of developers reporting a productivity gain, while flagging that AI adoption continues to correlate negatively with software delivery stability and that 30% of developers report little or no trust in the code the tools generate.&lt;/p&gt;
&lt;p&gt;Weigh those numbers against the volume of content telling you the answer is a better prompt, a tighter agentic loop, more &amp;ldquo;context engineering.&amp;rdquo; A lot of that genre is a marketing campaign run by parties whose revenue is your subscription and whose moat is your dependence. The pitch quietly reframes a skill problem as a prompt problem, because a prompt problem is one they sell the solution to. The honest version, which the vendors mostly don&amp;rsquo;t lead with: the tools are real and useful, and on the right slice of work the &lt;a class="link" href="https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/" &gt;10x is genuinely real&lt;/a&gt;. What&amp;rsquo;s oversold is the dependence narrative. Prompt-craft is the multiplier, and a multiplier needs something to multiply.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;The inverse failure mode is just as expensive. Hand-coding everything out of sentiment, refusing the agent on work where you&amp;rsquo;d learn nothing by doing it yourself, is its own waste. Re-deriving a CRUD endpoint by hand for the fortieth time builds no judgment you don&amp;rsquo;t already have; it just burns the hours you could spend on the query plan you can&amp;rsquo;t yet read. Sentiment is not a delegation strategy in either direction.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="where-to-spend-the-friction"&gt;Where to spend the friction
&lt;/h2&gt;&lt;p&gt;The discipline is selective, and the through-line is simple: if you don&amp;rsquo;t sweat it, it won&amp;rsquo;t stick, so spend the sweat where the judgment is worth owning.&lt;/p&gt;
&lt;p&gt;Keep doing reps on hard problems, and solve them yourself before you look. The LeetCode-style grind isn&amp;rsquo;t about the tree-inversion ever appearing in your job; it&amp;rsquo;s that forming the approach cold keeps the general muscle warm, and warm is what lets you recognize the shape of a problem before the agent has framed it for you. When a gnarly issue lands in your channel, the kind you&amp;rsquo;d normally forward to the model in one motion, take the twenty minutes to actually work it out. That twenty minutes is the deposit. The forwarded version withdraws from an account you stopped paying into.&lt;/p&gt;
&lt;p&gt;The highest-return habit costs almost nothing: form your own hypothesis before you read the agent&amp;rsquo;s answer. Predict the query plan before you run EXPLAIN. Predict the failure cause before you read the stack trace. Predict the API shape before the model proposes one. Then read its answer and compare. The gap between your guess and the better answer is the entire lesson, delivered for free, and it&amp;rsquo;s exactly the retrieval-then-feedback loop Roediger and Karpicke measured. Skip the guess and you&amp;rsquo;ve turned a test back into a re-read.&lt;/p&gt;
&lt;p&gt;There&amp;rsquo;s a second reason the habit matters, beyond memory. Questioning the agent&amp;rsquo;s calls and correcting them has to be constant, because once the work gets past boilerplate the model starts making decisions that are plausible and wrong. Wave them through and the small ones compound into &lt;a class="link" href="https://explainanalyze.com/p/death-by-a-thousand-cuts-the-ai-database-failure-you-cant-restore/" &gt;the kind of damage you can&amp;rsquo;t cleanly restore&lt;/a&gt;. Coast on auto-accept and you&amp;rsquo;re fine until it stalls on something genuinely hard. Then the engineer who never kept an independent read has nothing left to break the stall with, and the work stops where it got difficult.&lt;/p&gt;
&lt;p&gt;Reserve your value-center domain for hand-solving even when the agent is faster. If your career bet is on the database, do the query tuning and the lock analysis and the plan-regression hunts by hand, because that&amp;rsquo;s where the local judgment compounds. Delegating work &lt;em&gt;outside&lt;/em&gt; your value center is fine and good; the discipline is about protecting the core, not maximizing total hand-coding.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Hold a hard line on one rule: don&amp;rsquo;t merge what you couldn&amp;rsquo;t have written and can&amp;rsquo;t explain. If you can&amp;rsquo;t reconstruct why the agent&amp;rsquo;s migration takes the lock it takes, you&amp;rsquo;re rubber-stamping it, and rubber-stamping is how the table-locking migration, the silently-wrong join, and the auth bypass get into production wearing your name on the commit.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Last, measure the drift directly. Every so often, turn the agent off and cold-solve something in your core domain. Not as penance. As a gauge. If a problem you&amp;rsquo;d have handled fluently two years ago now feels foreign, that&amp;rsquo;s the readout, and it&amp;rsquo;s better to get it on a quiet afternoon than in the postmortem.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The argument is about protecting your core, so it goes quiet everywhere your core isn&amp;rsquo;t at stake.&lt;/p&gt;
&lt;p&gt;Throwaway internal tools are the clearest exemption. The binlog-purge script that&amp;rsquo;s sat in the toil backlog for two quarters, the diagnostic endpoint nobody will ever staff, the one-off migration helper: let the agent rip and ship it. The &lt;a class="link" href="https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/" &gt;10x is real on exactly that slice&lt;/a&gt;, the verification cost is low because the blast radius is low, and there&amp;rsquo;s no durable judgment you&amp;rsquo;re failing to build by not hand-writing a script that dies in a week.&lt;/p&gt;
&lt;p&gt;Domains outside your value center get the same pass. Delegating your CSS is not a moral failing if you&amp;rsquo;re a backend engineer who will never own the frontend. The point was never to hand-grind everything; it was to protect the specific judgment your role depends on. Spend the friction budget there and the agent everywhere else. Be honest about where the line really sits, though. Everywhere you delegate fully, you become the no-clue prompter for that domain. The surrender costs nothing on the frontend you&amp;rsquo;ll never own. It bites later on whatever you filed under &amp;ldquo;not mine&amp;rdquo; that turns out to matter, when you can&amp;rsquo;t tell a competent answer from a confident one.&lt;/p&gt;
&lt;p&gt;Live incidents are their own case. At 2am with customers down, use every tool that shortens the outage, the agent included. The learning doesn&amp;rsquo;t happen during the fire. It happens in the postmortem, when you reconstruct the failure by hand, form the hypothesis you didn&amp;rsquo;t have time to form live, and deposit the pattern for next time. The incident is for stopping the bleeding; the &lt;a class="link" href="https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/" &gt;postmortem is where the rep lives&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The market is already pricing this. Work the model does at a competent mid-level is getting commoditized. The premium is concentrating on the judgment that recognizes when the model is wrong, the judgment you can only build by doing the work the model offers to take off your hands. The &lt;a class="link" href="https://explainanalyze.com/p/the-paradox-of-the-fast-engineer/" &gt;paradox&lt;/a&gt; is that the same offer that makes you fast this quarter is what hollows out the skill that makes you valuable next year.&lt;/p&gt;
&lt;p&gt;The tools are worth using. This asks for one thing: keep one specific account funded. Pick the domain you&amp;rsquo;re betting your career on, and inside that domain, keep paying the friction tax the agent keeps offering to waive. Form the hypothesis before you read the answer, refuse the merge you can&amp;rsquo;t explain, and every few weeks turn the thing off and check whether the problem you used to own still feels like yours.&lt;/p&gt;</description></item><item><title>Scale the Pattern, Not the Instance</title><link>https://explainanalyze.com/p/scale-the-pattern-not-the-instance/</link><pubDate>Sat, 20 Jun 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/scale-the-pattern-not-the-instance/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Scale the Pattern, Not the Instance" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Most production fixes patch the occurrence in front of you (reboot this box, clean these rows, bump this instance), which clears today and leaves the class of problem intact to recur. The fix that holds lives one level up, where one change covers every future occurrence. The skill is telling a recurring class from a true one-off before you&amp;rsquo;ve been burned three times.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A development cluster ran on shared-tenancy EC2, the cheap tier with no dedicated host. Prod deploys had to clear dev first, so when a box wedged (SSH hung, the health check flatlined, steal time climbing on whatever still answered) the deploy queue stalled behind it. The team read it as capacity and moved up an instance size. It wedged again, so they went up another, now triple the bill and still wedging. Capacity was never it. A noisy neighbor on the oversubscribed host was starving the tenants, and a bigger seat at the same crowded table changes nothing. The unblock path made it worse: EU developers couldn&amp;rsquo;t reboot the box themselves (correctly, they shouldn&amp;rsquo;t hold that access), so a US infra engineer got paged in the middle of the night to stop/start a single dev box. What finally held wasn&amp;rsquo;t a bigger box. It was a pipeline any developer could run to relaunch a wedged instance on a fresh physical host.&lt;/p&gt;
&lt;p&gt;One box wedged; the pipeline covered every box that ever would. That distance, between fixing the occurrence in front of you and retiring the class it belongs to, is the whole article. The dev cluster is the easy version, because the fix was operational and nobody&amp;rsquo;s data path ran through it. The expensive version is when the strain sits in your data layer and the instance control is right there in the console. The reflex is the same either way: fix the thing that&amp;rsquo;s strained, which clears the symptom by end of afternoon and is exactly why it keeps beating the slower question of what class of problem just announced itself.&lt;/p&gt;
&lt;h2 id="just-scale-up-just-scale-out"&gt;Just scale up, just scale out
&lt;/h2&gt;&lt;p&gt;A Kafka consumer group on the orders topic starts lagging, a few hundred thousand messages behind by mid-morning and never catching up overnight. The handler does the obvious thing per message: deserialize, look up the customer, write a row, commit the offset. The team bumps the workers a size and goes from six partitions to twelve. Lag clears in an hour. Three weeks later it&amp;rsquo;s back; twelve isn&amp;rsquo;t enough, so they go to twenty-four and up another size. Relief, a quiet stretch, recurrence one size up. The cycle has a rhythm once you&amp;rsquo;ve seen it.&lt;/p&gt;
&lt;p&gt;By the second recurrence the fix is obvious to anyone who&amp;rsquo;s met it before: stop processing one message at a time, batch the poll and the downstream write, commit once for the batch. The obviousness is the point, because the team didn&amp;rsquo;t reach for it. They reached for partitions and worker size, twice, because those are the controls the dashboard puts a slider on, and a change to the handler is the one that isn&amp;rsquo;t. The occurrence got fixed each time. The class, a handler that pays a fixed round trip per message however many workers run in parallel, stayed exactly as expensive as it started.&lt;/p&gt;
&lt;p&gt;This is the same argument &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;Part I of the query series&lt;/a&gt; made under the heading &amp;ldquo;Why Metal Doesn&amp;rsquo;t Help,&amp;rdquo; where adding a third read replica made replication lag worse rather than better. The hardware treated an occurrence, this system is slow today, and never touched the class, the write pattern that produced the lag. That post stayed inside Postgres. The shape isn&amp;rsquo;t a Postgres thing, and the rest of this is where it shows up.&lt;/p&gt;
&lt;h2 id="the-same-mistake-four-domains"&gt;The same mistake, four domains
&lt;/h2&gt;&lt;p&gt;The reboot pipeline and the Kafka lag are the same move pitched at different altitudes. Each problem has a fix that clears the occurrence in front of you and a fix that retires the whole category it belongs to. The first one you reach for by reflex, because the occurrence is what&amp;rsquo;s paging you. The second covers every occurrence that hasn&amp;rsquo;t happened yet, including the ones produced by a code path nobody on the current team remembers writing.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Domain&lt;/th&gt;
 &lt;th&gt;Fixing the instance&lt;/th&gt;
 &lt;th&gt;Fixing the class&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Dev fleet&lt;/td&gt;
 &lt;td&gt;stop/start the box that wedged&lt;/td&gt;
 &lt;td&gt;a pipeline any dev runs against any box&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Kafka lag&lt;/td&gt;
 &lt;td&gt;drain today&amp;rsquo;s backlog&lt;/td&gt;
 &lt;td&gt;a handler that batches every message it will see&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Orphaned data&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;UPDATE&lt;/code&gt; the rows that broke the report&lt;/td&gt;
 &lt;td&gt;a foreign key that makes the orphan impossible to write&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Slow reads&lt;/td&gt;
 &lt;td&gt;tune the query a reviewer caught&lt;/td&gt;
 &lt;td&gt;a log threshold that surfaces every N+1, not the one noticed&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The first two rows you&amp;rsquo;ve already seen in this post. The other two are where the idea earns its rent on a database team.&lt;/p&gt;
&lt;p&gt;Orphaned rows are the cleanest example, because the instance fix is so easy to reach for. A child row points at a parent that&amp;rsquo;s gone, a report breaks, and you write the &lt;code&gt;UPDATE&lt;/code&gt; that reconciles it. It works. You&amp;rsquo;ll write a near-identical one next quarter when a different code path produces the same shape, because nothing stopped the shape from being written in the first place. The class fix is the foreign key (or the &lt;code&gt;CHECK&lt;/code&gt;, or the &lt;code&gt;NOT NULL&lt;/code&gt;) that makes the orphan unrepresentable. It covers every write that will ever touch the table: the migration script, the one-off backfill, the new service that integrated last week and was never code-reviewed against this invariant. The cost is real and worth stating, since it&amp;rsquo;s the reason people leave the constraint off. It validates on every write, and it will reject a messy bulk load you&amp;rsquo;d otherwise have let slide. That friction is the feature.&lt;/p&gt;
&lt;p&gt;The slow-read row is the same trade one layer up. You can fix the N+1 a reviewer happened to catch, or you can turn the catching into infrastructure: log queries-per-request and alert when a single request crosses some threshold, so the next N+1 announces itself in CI instead of waiting for a customer to sit through a slow page. The pull request fixes one endpoint. The threshold catches the shape wherever it surfaces next, including in code no reviewer reads closely.&lt;/p&gt;
&lt;p&gt;Not every invariant fits in a constraint or a metric. Some live only in a reviewer&amp;rsquo;s head: this table is append-only, that column is denormalized on purpose and both copies have to move together, this service owns the writes and everyone else reads. The class fix there is weaker but still real. Write the invariant down where the next change will run into it (a schema-conventions doc, an ADR, a comment on the migration that introduced the rule) and make checking it a standing line item in review, not a thing one careful person happens to catch. Enforcement that leans on people is the most fragile kind, which is the whole reason to push everything you can into the constraint or the CI check first. What&amp;rsquo;s left over is what review and documentation are for.&lt;/p&gt;
&lt;p&gt;One more thing before the table hardens into a rule. Some instance fixes are cheap and reversible; some carry a cost the class fix doesn&amp;rsquo;t, and Kafka partitions are the second kind.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Partitions are hard to take back&lt;/strong&gt;
 &lt;div&gt;Adding partitions to a keyed topic reshuffles the key-to-partition mapping. Confluent&amp;rsquo;s docs spell this out: Kafka maps a keyed message to a partition by &lt;code&gt;hash(key) % partition_count&lt;/code&gt;, and changing the count means messages with the same key can start landing on a different partition, breaking the per-key ordering you may be relying on (&lt;a class="link" href="https://docs.confluent.io/kafka/operations-tools/partition-determination.html" target="_blank" rel="noopener"
 &gt;Confluent, &amp;ldquo;Choose and Change the Partition Count&amp;rdquo;&lt;/a&gt;). And there is no supported operation to reduce the count afterward. If you scale out partitions to paper over a per-message handler, you&amp;rsquo;ve taken on an ordering hazard and a topology you can&amp;rsquo;t cleanly walk back, to avoid a change you&amp;rsquo;ll likely make anyway.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="finding-the-level-where-the-fix-generalizes"&gt;Finding the level where the fix generalizes
&lt;/h2&gt;&lt;p&gt;Fix the class, then. But which problems are a class? An instance of a class and a genuine one-off look identical the first time, and you have to bet on which you&amp;rsquo;re holding before you&amp;rsquo;ve watched it recur. The reboot pipeline was a wasted week if exactly one box ever wedges. The foreign key is bureaucratic drag if the orphan came from a bug already fixed and the shape can&amp;rsquo;t come back. Generalize too early and you&amp;rsquo;ve built a framework for a population of one, which is its own well-documented way to lose a sprint.&lt;/p&gt;
&lt;p&gt;The heuristic that sorts them is unglamorous. Count. How many times has this exact shape cost someone an afternoon, and is the count rising? One wedge, ever, is a pet. The third overnight page to reboot a different box is a class wearing the disguise of three unrelated incidents, and the disguise is the whole problem: each one gets closed individually by whoever caught it, so the pattern never accumulates into a number anyone acts on.&lt;/p&gt;
&lt;p&gt;Profiling is how you make that count honest instead of anecdotal. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/" &gt;The CPU-pegged case&lt;/a&gt; sorts &lt;code&gt;pg_stat_statements&lt;/code&gt; by &lt;code&gt;total_exec_time&lt;/code&gt;, which floats the high-frequency cheap query above the rare expensive one. That&amp;rsquo;s the same act in a different tool: looking past the single event that hurt once to find the shape that repeats. Once you can see the shape, what the class fix is depends on the shape. Per-unit overhead wants batching. A hot lookup that runs identically a million times a day wants a cache. A predicate the planner can&amp;rsquo;t seek on wants a SARGable rewrite or the right index, the full treatment of which is in &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable predicates&lt;/a&gt;. An &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;ORM issuing a query per row&lt;/a&gt; wants one set-based query. The level you fix at is what&amp;rsquo;s shared, not the tool you fix with.&lt;/p&gt;
&lt;p&gt;Managed services force the question by removing the instance fix entirely. On your own metal you can bump the box one more size, which is exactly what lets a recurring problem hide for years. Hit a vendor&amp;rsquo;s instance ceiling and there&amp;rsquo;s no next size, no knob on their storage engine, no replication setting to reach into. The only layer left under your control is your own load, so finding the class stops being the disciplined choice and becomes the only one. The &lt;a class="link" href="https://explainanalyze.com/p/where-your-cloud-bill-actually-leaks-an-audit-nobody-runs/" &gt;cloud-bill leaks audit&lt;/a&gt; runs on the same fact: the spend is yours, and nobody&amp;rsquo;s coming to optimize it for you.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;This is not &amp;#39;always generalize&amp;#39;&lt;/strong&gt;
 &lt;div&gt;Lifting a fix to the class level has costs. A foreign key validates on every write and blocks messy backfills. A batched handler trades per-item latency for throughput and hands you partial-failure handling that a per-item loop answered for free. A query-count alert is one more thing that pages. The argument is narrow: when a shape recurs and the count is climbing, fix where it generalizes. When the population is genuinely one, don&amp;rsquo;t build the framework.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-fixing-the-one-instance-is-right"&gt;When fixing the one instance is right
&lt;/h2&gt;&lt;p&gt;The argument inverts the moment the population really is one. A box that wedged once during a bad maintenance window is a pet. Reboot it, move on, and don&amp;rsquo;t build a pipeline for a host that won&amp;rsquo;t repeat. A startup with eighteen months of runway should fix the instance every time the class fix costs an SME afternoon it can&amp;rsquo;t spare, and write the class fix down as known debt rather than pretend it&amp;rsquo;s done. And when you need relief now and the general fix is a week out, fix the instance to buy the week, then put the class fix on the calendar instead of the backlog.&lt;/p&gt;
&lt;p&gt;The trap is that last case going quiet. The cleanup query that bought a quarter is still the team&amp;rsquo;s monthly ritual two years on, the constraint never landed, and the cost has compounded the whole time in afternoons nobody bothered to total. Buying time is fine. Forgetting you borrowed it is the failure.&lt;/p&gt;
&lt;h2 id="the-tell"&gt;The tell
&lt;/h2&gt;&lt;p&gt;The signal that a team is patching instances instead of fixing classes is a particular déjà vu in the incident log: the same shape of problem, handled fresh each time, by whoever happened to catch it. Orphaned rows reconciled by three different people in three quarters with three slightly different queries. A reboot runbook followed forty times and automated zero. Ask what the recurring shape is and who owns the fix for the category. If the answer is a stack of individually-closed tickets and no name, the class is unowned, which almost always means it&amp;rsquo;s still arriving.&lt;/p&gt;</description></item><item><title>Death by a Thousand Cuts: the AI Database Failure You Can't Restore</title><link>https://explainanalyze.com/p/death-by-a-thousand-cuts-the-ai-database-failure-you-cant-restore/</link><pubDate>Thu, 04 Jun 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/death-by-a-thousand-cuts-the-ai-database-failure-you-cant-restore/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Death by a Thousand Cuts: the AI Database Failure You Can't Restore" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;The catastrophic AI failure (the agent that DROPs a table) is the recoverable one: loud, attributable, and on a gated pipeline it mostly can&amp;rsquo;t happen anyway. What actually bleeds you is the change that clears every gate because the gates check correctness at review time, and the failure is a function of volume and time, both of which are zero when the PR is open. Plot failures on loud-vs-quiet and recoverable-vs-not, and AI floods the quiet-and-unrecoverable corner the pipeline was never watching.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A scraper ships behind the same pipeline as everything else: feature branch, two approvals, CI green, a day in staging, then deploy. There is already a &lt;code&gt;postings&lt;/code&gt; table, one row per job posting the crawler tracks, keyed by &lt;code&gt;posting_id&lt;/code&gt;. Part of the change is a new table to track crawl state, storing the content hash of every posting each run sees so the next run can tell what changed. The agent designed the table, a reviewer approved it, and at review time it held zero rows. It looked reasonable:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;crawl_state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;BIGSERIAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;run_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;posting_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;postings&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;posting_id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;content_hash&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;CHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- SHA-256 of the posting body
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;crawled_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;crawl_state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;posting_id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;It was reasonable, for about three months.&lt;/p&gt;
&lt;p&gt;Nothing on that screen looks wrong, and that is the problem. A surrogate &lt;code&gt;id&lt;/code&gt;, a foreign key to &lt;code&gt;postings&lt;/code&gt;, an index on the column you look postings up by. It reviews as boilerplate. The grain is the part nobody states out loud: one row per posting &lt;em&gt;per run&lt;/em&gt;. Every pass appends the entire posting set under a fresh &lt;code&gt;run_id&lt;/code&gt; instead of updating the rows already there, so the table grows by the full set every time the scraper runs. &lt;code&gt;postings&lt;/code&gt; holds roughly 100,000 rows. Three months and a hundred-odd runs later, &lt;code&gt;crawl_state&lt;/code&gt; holds 11 million. The job that decides whether a posting changed runs the obvious query:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;content_hash&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;crawl_state&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;posting_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;crawled_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The &lt;code&gt;posting_id&lt;/code&gt; index finds the matching rows, but there are now a hundred-odd of them per posting, and to return the single latest hash it sorts that pile by &lt;code&gt;crawled_at&lt;/code&gt; on every call. Across the working set the pipeline is timing out. Asked to fix the slowness, the agent recommends what it always recommends: widen the index to &lt;code&gt;CREATE INDEX ON crawl_state (posting_id, crawled_at DESC)&lt;/code&gt;, so the latest-hash lookup stops sorting.&lt;/p&gt;
&lt;p&gt;An engineer who knows the system reads it differently. The table shouldn&amp;rsquo;t have run grain at all. A posting&amp;rsquo;s current hash is one value, stored once and overwritten each run, and there is nothing to accumulate. Better than that, the hash isn&amp;rsquo;t a separate concern from the posting. It belongs on the &lt;code&gt;postings&lt;/code&gt; row that already exists, so there is no second table, no &lt;code&gt;run_id&lt;/code&gt;, and no latest-per-posting lookup at all:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;postings&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;content_hash&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;CHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;hash_checked_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- each run, per posting:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;postings&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;content_hash&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;hash_checked_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;posting_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;content_hash&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DISTINCT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;That stays at 100k rows forever, the changed-or-not check is a single primary-key row read, and there is no &lt;code&gt;crawl_state&lt;/code&gt; to bloat. The index the agent suggested speeds the symptom while doubling down on the grain that is the actual bug, paying write cost and storage on a table that should not exist. And there is no deploy to revert. The bad grain is a schema decision three months old plus 11 million rows of accumulated state, and unwinding it is a planned migration and a backfill, reviewed like any other change, not a rollback.&lt;/p&gt;
&lt;h2 id="the-drop-is-the-lucky-case-and-heres-the-2x2-that-shows-why"&gt;The DROP is the lucky case, and here&amp;rsquo;s the 2x2 that shows why
&lt;/h2&gt;&lt;p&gt;The failure everyone pictures is the destructive one: the &lt;code&gt;DROP TABLE&lt;/code&gt;, the migration that truncates the wrong relation, the script that deletes the binlogs. On a gated system that is the one you have mostly handled, with destructive migrations caught in review, credentials scoped, and a restore runbook practiced. When the Replit agent &lt;a class="link" href="https://fortune.com/2025/07/23/ai-coding-tool-replit-wiped-database-called-it-a-catastrophic-failure/" target="_blank" rel="noopener"
 &gt;wiped a production database during a code freeze in July 2025&lt;/a&gt;, the data was restored: loud, attributable to one timestamp, recoverable. The scraper cleared that same pipeline because at merge time it was correct, with no rows for the grain bug to express and a CI seed that never reached the row count where it breaks.&lt;/p&gt;
&lt;p&gt;Rank a failure on two axes, loud-vs-quiet and recoverable-vs-not, and you get four corners:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Loud and recoverable&lt;/strong&gt; is the DROP. You know instantly and you roll it back.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Loud and unrecoverable&lt;/strong&gt; is rarer: a destructive operation you catch but can&amp;rsquo;t undo.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Quiet and recoverable&lt;/strong&gt; is the bug that sat unnoticed but is still reversible when you find it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Quiet and unrecoverable&lt;/strong&gt; ruins quarters. You don&amp;rsquo;t find out for months, and by then the prior state is gone or never existed as a clean artifact.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The axes correlate, which is what makes the bad corner deep. Loud failures get caught while the prior state still exists; quiet ones sit, and the longer one sits the more downstream systems consume it as truth, until a recoverable error has been aggregated and propagated into an unrecoverable one. Loudness buys the time, so quiet and unrecoverable travel together.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;This post is about the write path: statements that change data, schema, or the planner&amp;rsquo;s behavior. The read-path failure (an AI-generated &lt;code&gt;SELECT&lt;/code&gt; that returns a confidently wrong number) is the sibling problem, covered in &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" target="_blank" rel="noopener"
 &gt;What AI Gets Wrong About Your Database&lt;/a&gt;. A wrong read misleads a decision; a wrong write becomes the new truth.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;AI floods the bad corner for a structural reason. Each change it ships is plausible: it compiles, runs, returns the right shape, passes whatever checks exist. That plausibility is the &lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;corruption floor&lt;/a&gt;, the same mechanism that makes the output useful making it occasionally wrong in a way that looks exactly right. A loud failure is one the output failed to make plausible; the quiet one is the model working as designed. Then volume multiplies it: a team shipping eighty changes a week instead of eight samples that floor ten times as often, on the same review and CI budget. The DROP is the rare draw the pipeline was built to stop. The thousand cuts are the modal draw, and it waves them through.&lt;/p&gt;
&lt;p&gt;The quiet corner comes in three shapes. The scraper is the first: a schema correct at zero rows and fatal at eleven million, because the model optimizes from its training distribution, not your scale. Asked to partition a large table it reaches for &lt;code&gt;created_at&lt;/code&gt; in the primary key, the common corpus shape, not &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/" &gt;the primary-key partitioning that fits a high-scale OLTP table&lt;/a&gt;. The second is the value it computes wrong because it doesn&amp;rsquo;t hold your domain: &lt;a class="link" href="https://fortune.com/article/customer-support-ai-cursor-went-rogue/" target="_blank" rel="noopener"
 &gt;Cursor&amp;rsquo;s support bot&lt;/a&gt; invented a login policy that didn&amp;rsquo;t exist and users cancelled before anyone knew, and Air Canada &lt;a class="link" href="https://www.cbsnews.com/news/aircanada-chatbot-discount-customer/" target="_blank" rel="noopener"
 &gt;lost in court&lt;/a&gt; over a bereavement refund its chatbot made up. Move that same generator onto a write path computing a discount or a tax split and the row is well-typed and wrong about what the number means, with nothing reconciling it against the contract until quarter-end. The third is the change shipped past the author&amp;rsquo;s own understanding: it looked good and worked, so it went, and the judgment that would have caught it is built by the slow work the agent now skips. That is the &lt;a class="link" href="https://explainanalyze.com/p/the-paradox-of-the-fast-engineer/" &gt;paradox of the fast engineer&lt;/a&gt;, which &lt;a class="link" href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/" target="_blank" rel="noopener"
 &gt;a July 2025 study&lt;/a&gt; measured as 19% slower even as the developers felt faster.&lt;/p&gt;
&lt;h2 id="a-worked-example-the-soft-delete-leak"&gt;A worked example: the soft-delete leak
&lt;/h2&gt;&lt;p&gt;The grain bug is loud once you go looking, because it shows up as latency. The worse version of the same class is a write that corrupts a number and never moves a performance metric at all. Soft deletes are where this lives in most enterprise schemas.&lt;/p&gt;
&lt;p&gt;The convention is old and unwritten. A row is never physically removed; it gets a &lt;code&gt;deleted_at&lt;/code&gt; stamp, and every query that reads the table is expected to filter it out. A billing system for a SaaS company looks like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- one row per recurring line on an account: base plan, seats, add-ons
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;subscription_items&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;BIGSERIAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;account_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account_id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sku&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;monthly_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- set when a customer drops the line
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;When a customer downgrades, the application does not delete the row, it stamps it:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;subscription_items&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Every existing query that touches money knows this. The MRR rollup, the invoice generator, the revenue dashboard, all of them carry &lt;code&gt;AND deleted_at IS NULL&lt;/code&gt;, because the team learned years ago that forgetting it double-counts churned revenue. That knowledge lives in the queries and in the heads of the people who wrote them. It is nowhere in the schema; &lt;code&gt;deleted_at&lt;/code&gt; is just a nullable timestamp, and nothing stops a query from ignoring it.&lt;/p&gt;
&lt;p&gt;Now an agent is asked to add a board-facing metric, monthly recurring revenue by region, that the nightly ETL persists into the warehouse fact tables the dashboards read. It writes the obvious thing:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VIEW&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mrr_by_region&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;region&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;si&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;monthly_cents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mrr_cents&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;subscription_items&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;si&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;si&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;account_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;account_id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- remembered on accounts
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;region&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;It filtered &lt;code&gt;deleted_at&lt;/code&gt; on &lt;code&gt;accounts&lt;/code&gt; but not on &lt;code&gt;subscription_items&lt;/code&gt;, because nothing in the schema said it had to and the training corpus is full of joins shaped exactly like this. Every cancelled add-on and downgraded seat is now summed back into regional MRR, and each night the ETL reads this view and writes the inflated number into the warehouse the whole company reads as truth. The shape is right and the number is plausible, a little high, and growing as the soft-deleted pool grows.&lt;/p&gt;
&lt;p&gt;Nothing catches it. The engineer saw a working view and a &lt;code&gt;deleted_at&lt;/code&gt; filter sitting right there and moved on; the AI reviewer flagged a naming nit; the human skimmed the green summary and approved; CI ran on a seed database with almost no deleted rows, so the leak was a rounding error in the test. A missing predicate is an absence, the one thing every reviewer, human or model, reliably fails to see.&lt;/p&gt;
&lt;p&gt;The drift is the tell. Small at launch, ten or fifteen percent high a year later in the regions with the most downgrade history, and finance finds it the only way anyone does: reconciling the dashboard against billed revenue, a year in, with no single cause and no deploy to revert.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;A soft-delete filter is a contract the schema cannot enforce. Nothing in &lt;code&gt;subscription_items&lt;/code&gt; makes a query honor &lt;code&gt;deleted_at&lt;/code&gt;, so the rollup should have joined an &lt;code&gt;active_items&lt;/code&gt; view (&lt;code&gt;CREATE VIEW active_items AS SELECT ... WHERE deleted_at IS NULL&lt;/code&gt;) and a rule should forbid money queries from touching the base table at all. That is worth more than any amount of review attention, because the absence of a predicate is the one thing a reviewer, human or model, reliably fails to see.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-fix-is-a-business-call-not-a-technical-one"&gt;The fix is a business call, not a technical one
&lt;/h2&gt;&lt;p&gt;The mitigations are known and none of them are clever: reconcile against a source of truth on a cadence the business can stand, alarm on aggregates and drift instead of only errors, run CI against production-shaped volume, bake invariants into views and constraints. All worth doing, all secondary, because every one is a net thrown after the write has committed. The load-bearing decision is upstream of the tooling, and it is a positioning call leadership makes on purpose. Four honest positions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Ship at full speed, accept the corner.&lt;/strong&gt; Take the velocity and take the unrecoverable write, the silent data loss, the bug the customer finds, as the cost. Legitimate for a seed-stage product with no prior state worth protecting. Catastrophic for a billing system.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fast where it&amp;rsquo;s cheap, gated where it&amp;rsquo;s not.&lt;/strong&gt; Agents and junior engineers run on loud, recoverable surfaces (internal tooling, dashboards, throwaway analysis); writes that touch money, schema, or multi-writer tables go through someone who holds the domain. This is where Amazon landed the expensive way, requiring senior sign-off on AI-assisted changes to its sensitive stack after a run of incidents (&lt;a class="link" href="https://www.theregister.com/2026/04/29/aws_keynote_hypes_ai_magic/" target="_blank" rel="noopener"
 &gt;The Register, April 2026&lt;/a&gt;). They named the cost: controlled friction.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SME on everything.&lt;/strong&gt; Only the smallest or most regulated shops can afford it, and it collapses into the second position the moment change volume outgrows the reviewers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Encode the domain into tests.&lt;/strong&gt; The one position that scales without scaling reviewers, and the one with the sharpest trap. An SME who knows the soft-delete convention writes an assertion that fails the build on the leak. Ask the agent to &amp;ldquo;add tests&amp;rdquo; under deadline and it writes one that sums the same leaked rows and asserts the inflated total is correct: the bug ships with a green check certifying it. And tests only check behavior, never whether the design should exist. The scraper passes everything you could write against it; the bug is the table, and a green suite is guaranteed to bless an architecture that works exactly as built.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The trap is choosing the second or fourth on a slide and the first in practice. All four only work if the people doing the reading still have judgment to read with, and the &lt;a class="link" href="https://explainanalyze.com/p/the-paradox-of-the-fast-engineer/" &gt;paradox of the fast engineer&lt;/a&gt; is draining that pool: hand the slow work that grows an SME to an agent for two years and the sign-off is staffed by people with the title and not the instinct. If you are not willing to lose your seniors, the budget item is the work that makes them, not just the headcount that has the rank today.&lt;/p&gt;
&lt;h2 id="what-your-monitoring-is-actually-for"&gt;What your monitoring is actually for
&lt;/h2&gt;&lt;p&gt;Everything you monitor fires in the loud quadrant. Error rates, &lt;code&gt;5xx&lt;/code&gt;, failed-job alerts, latency thresholds set above current numbers, all of it watching the corner you were already going to survive, because the DROP has a backup and a practiced runbook. The scraper that dies three months after a clean review, the write that computes the wrong number, the logic bug a customer found first, those never alarm, because the pipeline reads every change at the one moment it is still correct and then stops looking.&lt;/p&gt;
&lt;p&gt;A single one of those is not a crisis. You find it, you trace it, you fix it. The problem is rate. Each is one draw from the &lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;corruption floor&lt;/a&gt;, and a team shipping ten thousand lines a day draws constantly, laying down a sediment of small wrongs that surface not the day they&amp;rsquo;re written but a year later, together, as a system nobody fully understands returning numbers nobody fully trusts. By then it is past untangling: a thread to pull assumes a thread, and a year of compounded cuts is the whole fabric. The options shrink to a rewrite or living with numbers you can&amp;rsquo;t defend, and no senior worth the title signs up to reverse-engineer a year of an agent&amp;rsquo;s confident guesses.&lt;/p&gt;
&lt;p&gt;The fake citations got caught because the judge knew the real ones. That is the whole job, and the agent can&amp;rsquo;t do it for you: someone has to ship nothing they don&amp;rsquo;t understand, and understand it the whole way down, what the value means and what it does to every system that reads it later. Your product has no judge unless you are one. The agent makes the drafts faster; knowing what they cost is still the part you can&amp;rsquo;t hand off.&lt;/p&gt;</description></item><item><title>Narrow Tools, Narrow Agents: Where Agent Reliability Actually Comes From</title><link>https://explainanalyze.com/p/narrow-tools-narrow-agents-where-agent-reliability-actually-comes-from/</link><pubDate>Sat, 30 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/narrow-tools-narrow-agents-where-agent-reliability-actually-comes-from/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Narrow Tools, Narrow Agents: Where Agent Reliability Actually Comes From" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;The agents that hallucinate least are the ones calling narrow, opinionated tools and given the smallest possible job. A &amp;ldquo;diagnostic&amp;rdquo; endpoint that returns a present-state boolean plus a lag number beats a generic &lt;code&gt;query(sql)&lt;/code&gt; surface, and a scoped agent with three tools beats a wide agent with twenty. Even with both halves in place, the output still has inconsistencies on some level. The goal is &amp;ldquo;hallucinates least&amp;rdquo;, not &amp;ldquo;right&amp;rdquo;.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Here is what an on-call agent posted to the incident channel when &lt;code&gt;pg_stat_replication.replay_lag&lt;/code&gt; on the &lt;code&gt;orders&lt;/code&gt; cluster crossed the 60s SLO:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Logical replication slot pub_orders_v1 is behind on the publisher.
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;restart_lsn has not advanced in the last 12 minutes. Recommend
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;dropping the subscription and recreating it, then advancing the
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;slot manually with pg_replication_slot_advance(). Runbook:
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;ops/runbooks/postgres/replica-lag-orders.md (last reviewed 2023-08).
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The slot the agent named was decommissioned twenty months earlier. This is what &lt;code&gt;pg_replication_slots&lt;/code&gt; returned the same minute on the same replica:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;=&amp;gt; SELECT slot_name, slot_type, active FROM pg_replication_slots;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; slot_name | slot_type | active
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-----------+-----------+--------
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;(0 rows)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The summary was produced by an agent with RAG over the full ops repo and a standard &lt;code&gt;query(sql)&lt;/code&gt; MCP tool against the replica. The &lt;code&gt;orders&lt;/code&gt; cluster moved off logical replication in the Q3 2024 migration to streaming. Two paragraphs of an ADR titled &amp;ldquo;Move publication off logical replication&amp;rdquo; explain exactly why. The ADR lives in the same repo, indexed by the same embedding model, available to the same retrieval call. It ranked behind the 2023 runbook, behind two other runbooks for the same alert family, and behind a post-mortem from a different cluster entirely. The ADR&amp;rsquo;s vocabulary didn&amp;rsquo;t match the alert&amp;rsquo;s. The agent never read it. The cluster&amp;rsquo;s actual problem (a long autovacuum on the &lt;code&gt;orders_2026_05&lt;/code&gt; partition generating WAL faster than the replica could apply) was sitting one query away in &lt;code&gt;pg_stat_progress_vacuum&lt;/code&gt;. The agent&amp;rsquo;s summary never reached for it.&lt;/p&gt;
&lt;h2 id="what-a-smarter-model-wouldnt-have-fixed"&gt;What a smarter model wouldn&amp;rsquo;t have fixed
&lt;/h2&gt;&lt;p&gt;The familiar levers are a bigger context window, better embeddings, a smarter model. None of them touch the underlying mechanic. Embeddings retrieve by similarity, not by truth-value. The 2023 runbook scored highest because it talked about the exact alert, with the exact column names, in the exact phrasing the alert text used. A bigger window pulls in more competing documents, including more wrong ones. A better embedding model sharpens the same match against the same stale corpus. A smarter LLM produces a more confident summary on the wrong grounding. The retrieval surface is the problem, and the model is doing what models do.&lt;/p&gt;
&lt;p&gt;Anthropic&amp;rsquo;s &lt;a class="link" href="https://www.anthropic.com/engineering/writing-tools-for-agents" target="_blank" rel="noopener"
 &gt;Writing effective tools for agents&lt;/a&gt; (September 2025) makes the structural version of the same point: more tools and broader tools don&amp;rsquo;t improve agent outcomes. The team behind Claude found that purposefully narrower tools (&lt;code&gt;search_contacts&lt;/code&gt; over &lt;code&gt;list_contacts&lt;/code&gt;, with shaped responses) beat broader ones consistently, because agents struggle to extract signal from irrelevant context and burn tokens trying. The same shape applies one layer up. A &lt;code&gt;search_runbooks&lt;/code&gt; tool grounded against a corpus where half the docs are out of date is a broad tool dressed in narrow clothes. The narrowness has to live in what the tool actually returns.&lt;/p&gt;
&lt;h2 id="the-same-alert-through-a-narrow-tool"&gt;The same alert through a narrow tool
&lt;/h2&gt;&lt;p&gt;Here is what a &lt;code&gt;diagnose_replica_lag(cluster)&lt;/code&gt; endpoint returns when the same alert fires:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-json" data-lang="json"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;lagging&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;lag_seconds&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;47&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;replication_mode&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;streaming&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;publisher_lsn&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;F1/A2C3D400&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;replay_lsn&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;F1/A2B14C00&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;wal_replay_paused&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;blocking_autovacuum&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;relation&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;orders_2026_05&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;phase&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;scanning heap&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;started_at&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;2026-05-24T02:18:11Z&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="nt"&gt;&amp;#34;duration_seconds&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;5421&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The agent reads present-state structured input. No runbook, no link, no freeform &amp;ldquo;here&amp;rsquo;s what this might mean&amp;rdquo;. The endpoint is the only thing in the stack that knows the cluster moved off logical replication. Whatever slot the response names (if any) is whatever the slot is called today. The blocking autovacuum is computed by joining &lt;code&gt;pg_stat_replication&lt;/code&gt; and &lt;code&gt;pg_stat_progress_vacuum&lt;/code&gt; on the server side, where the join is cheap and the freshness is guaranteed. The agent&amp;rsquo;s summary against this input says what the input says. There is no 2023 runbook in the prompt to retrieve from.&lt;/p&gt;
&lt;p&gt;The Unix mantra ports to agent tools more directly than most. Each tool does one function, does it well, and shapes its output for the consumer. The consumer is an agent with a token budget, no working memory between calls, and a fondness for whichever input most resembles a familiar pattern. The output has to be small, shaped, current, and complete enough that the agent&amp;rsquo;s job is to read it, not compose it.&lt;/p&gt;
&lt;p&gt;A schema introspector for an agent doing query work returns the active subset of the catalog: tables, columns, and indexes touched by queries in the last thirty days, with column types, foreign keys, and the indexes that have non-zero &lt;code&gt;idx_scan&lt;/code&gt; over the same window. It does not dump 4,200 rows of &lt;code&gt;pg_catalog.pg_class&lt;/code&gt; joined against &lt;code&gt;pg_attribute&lt;/code&gt;. The catalog carries years of accumulated noise: deprecated audit tables, the experiment from 2022 that never got cleaned up, the staging-only mirror copies. An agent given the full dump pattern-matches against the noise as readily as the signal.&lt;/p&gt;
&lt;p&gt;A &amp;ldquo;currently breaking&amp;rdquo; endpoint returns a pre-joined view of active alerts, the playbook each alert routes to, the affected service, the deploy SHA from the last fifteen minutes, and the on-call&amp;rsquo;s contact. It does not return three underlying APIs and trust the agent to compose the join. The join is the question. The tool encoded it. Re-deriving the join from raw sources every call is where the agent burns tokens and where the misattributions accumulate.&lt;/p&gt;
&lt;p&gt;Web search joins this set when the question is about something fresh. For a CVE on a specific Postgres minor, a &lt;code&gt;web_search(release_notes)&lt;/code&gt; tool grounded against pgsql-announce or a vendor advisory beats the same question routed against an internal RAG corpus where the relevant note doesn&amp;rsquo;t exist yet. Fresh source. Narrow scope. The tool encodes the question.&lt;/p&gt;
&lt;p&gt;The pattern across all four: the tool encodes the question, not the source. An agent calling &lt;code&gt;query(sql)&lt;/code&gt; gets to compose every question itself, including the badly-worded ones. An agent calling a diagnostic tool only asks the questions the diagnostic was designed for. That constraint is the feature.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&amp;ldquo;Narrow&amp;rdquo; has to be narrow in what the tool returns, regardless of what it&amp;rsquo;s named. A &lt;code&gt;diagnose_replica_lag&lt;/code&gt; tool that runs &lt;code&gt;SELECT * FROM pg_stat_replication&lt;/code&gt; and dumps every column on every row is no better than letting the agent write the SQL itself. The shaping (which columns, with what projection, with what filtering, with what defaults) is where the reliability lives. A tool that returns 5,000 rows because nobody put a &lt;code&gt;LIMIT&lt;/code&gt; on the server side has handed the responsibility back to the model, which is the responsibility the tool existed to remove.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="narrow-tools-dont-help-a-wide-agent"&gt;Narrow tools don&amp;rsquo;t help a wide agent
&lt;/h2&gt;&lt;p&gt;Tools shaped for the right answer still get the wrong call from an agent given fifty of them and the instruction &amp;ldquo;you are the on-call assistant, help the human&amp;rdquo;. The model picks whichever tool pattern-matches best to whatever the input string looked like, and that pattern-matching is biased toward whichever description sounds most familiar. A scoped agent (one job, three tools, one decision to produce) has nothing else to reach for.&lt;/p&gt;
&lt;p&gt;Scope is what the agent is for, expressed narrowly enough that the right tool call is mechanical. &amp;ldquo;Triage a replica-lag page&amp;rdquo; is a scope. The tools are the diagnostic, the recent-deploys lookup, and the playbook. The agent calls them in order and produces the summary. &amp;ldquo;Help the engineer with whatever they ask&amp;rdquo; is not a scope, it is the absence of one. The same model with the same tools resolves the first job consistently and freestyles the second.&lt;/p&gt;
&lt;p&gt;Wide scope produces a failure that&amp;rsquo;s worse than picking the wrong tool. A wide-scope agent given a hybrid problem reaches for one of the relevant tools and silently drops the other half. The scoping decision lived in the model&amp;rsquo;s pattern-match against the input string, which is the worst place to put a decision the next on-call wants to debug six months from now. A scoped agent doesn&amp;rsquo;t have to decide. The scope already decided.&lt;/p&gt;
&lt;p&gt;The two halves compound. Narrow tools make the right call mechanical inside a scope. Narrow scope makes it obvious which tools the agent will call. A wide agent with narrow tools wastes the narrowness. A scoped agent with broad tools wastes the scope. The Redis diagnostic API in &lt;a class="link" href="https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/" &gt;internal tools are AI 10x&lt;/a&gt; is what the canonical version looks like in production: one endpoint, present-state answers (key counts, memory pressure, slow-log entries, replication offset), pre-shaped for whoever is asking. The agent never composes Redis commands. It calls the diagnostic and reads structured output. The same shape ports to Postgres, MySQL, Kafka, ES.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;The argument is about agents acting on production systems, where a bad tool call has operational consequences and the corpus the agent reads from has years of accumulated drift. Pure-text Q&amp;amp;A bots over a curated help-center corpus are a different regime. The corpus there is small, maintained, and the cost of a bad retrieval is the user reading a stale answer rather than the system running a destructive command. Retrieval is the right primitive in that regime. The argument here is that &amp;ldquo;retrieval over the production docs corpus&amp;rdquo; is the wrong primitive for an agent that&amp;rsquo;s going to act.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-this-doesnt-earn-its-keep"&gt;When this doesn&amp;rsquo;t earn its keep
&lt;/h2&gt;&lt;ul&gt;
&lt;li&gt;One-shot scripts and ad-hoc analysis where the human reviews every output. The agent&amp;rsquo;s tool is &lt;code&gt;query(sql)&lt;/code&gt; against a sandbox; the human reads the result and discards it. The blast radius is the engineer&amp;rsquo;s own time.&lt;/li&gt;
&lt;li&gt;Low-stakes generative tasks. Commit messages, variable names, refactoring suggestions, the docstring for a private helper. The cost of a wrong output is noticing and editing.&lt;/li&gt;
&lt;li&gt;Greenfield code where there&amp;rsquo;s no accumulated context to be stale. The agent is the only author the repo has seen, the conventions are whatever it wrote yesterday, and there&amp;rsquo;s no two-year-old runbook to mis-retrieve.&lt;/li&gt;
&lt;li&gt;Small teams with a single agent and a single use case. Three tools is the size the agent already has. Building a narrowing layer for something already narrow is overkill.&lt;/li&gt;
&lt;li&gt;Genuinely exploratory questions where the agent is supposed to ask broadly. &amp;ldquo;What in the catalog looks unused&amp;rdquo; is a question that wants the full catalog, not the thirty-day-active subset. Exploratory questions need exploratory tools.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The engineering work has moved. The 2023 question was how to prompt the model better. The 2026 question is what tool the agent reaches for, and how small the job is that the harness hands it. Most of the reliability budget lives in those two surfaces and not in the model weights. A team adopting agents on production systems will spend more time building agent-shaped APIs and scoping per-task harnesses than tuning prompts, because that is where the floor on hallucination actually moves. The model is going to misattribute and fabricate and confidently quote the wrong thing on some fraction of calls regardless of how the harness is built. The tool the agent calls and the scope of the call are the surfaces the engineer controls. The 2023 runbook for a slot that doesn&amp;rsquo;t exist anymore stops being a problem when the agent never reads runbooks, only calls the diagnostic that knows what the cluster actually is today.&lt;/p&gt;</description></item><item><title>It's Almost Always the Queries, Part V: Disk Has Two Alarms, Not One</title><link>https://explainanalyze.com/p/its-almost-always-the-queries-part-v-disk-has-two-alarms-not-one/</link><pubDate>Wed, 27 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/its-almost-always-the-queries-part-v-disk-has-two-alarms-not-one/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post It's Almost Always the Queries, Part V: Disk Has Two Alarms, Not One" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Two alarms ride the same dashboard tile: the disk filling up, and the disk slowing down. Both have query-level and schema-level fixes that hold for years. Capacity is partition-and-archive, not &lt;code&gt;DELETE&lt;/code&gt;. IOPS is covering indexes and the access patterns that go with them. The cloud&amp;rsquo;s autoscaling and burst credits mask both, and the bill is where the symptom finally surfaces.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;On-call gets paged on RDS I/O latency at 2pm Tuesday. The Datadog graph shows read latency at four times its baseline, write latency climbing in lockstep. The engineer on rotation bumps the instance from &lt;code&gt;db.t3.medium&lt;/code&gt; to &lt;code&gt;db.t3.large&lt;/code&gt;, latency drops back inside the SLO inside five minutes, the page closes, and the incident channel goes quiet. Three days later: same alert, same dashboard, same &amp;ldquo;fix.&amp;rdquo; Same five-minute window. By the fourth time, somebody pulls the &lt;code&gt;BurstBalance&lt;/code&gt; metric out of CloudWatch and the picture changes. The instance upgrade had not actually done anything to the workload. It had reset the gp2 burst-credit pool from zero back to full. The query mix was steady. The variable was the credit accounting, and the dashboard the team was looking at did not graph it.&lt;/p&gt;
&lt;h2 id="the-obvious-fix-and-why-it-buys-you-weeks"&gt;The obvious fix and why it buys you weeks
&lt;/h2&gt;&lt;p&gt;Reach for a bigger volume, more provisioned IOPS, a beefier instance class, or all three at once. Each lever is real, and during an active incident with revenue tied to checkout latency, the right call is often whichever one moves the graph fastest. They share a property the postmortem usually skips: each rents capacity proportional to the pattern underneath - the bloat that produces dead pages, the retention nobody set, the SELECT list that stopped being covered when a column got added. The cost recurs every time growth or concurrency pushes the workload back into the same shape. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;Part I&lt;/a&gt; called this renting the bug. The disk case is two bugs sharing one alert.&lt;/p&gt;
&lt;h2 id="two-failure-modes-two-upstream-fixes"&gt;Two failure modes, two upstream fixes
&lt;/h2&gt;&lt;p&gt;The disk tile collapses two genuinely different problems into one number. The disk is filling, which is capacity. The disk is slowing, which is IOPS. They have different mechanics, different upstream causes, and different fixes that hold for years rather than weeks. The 2pm incident is almost always the IOPS one. The Friday-afternoon &amp;ldquo;we&amp;rsquo;re at 87% storage&amp;rdquo; thread is the capacity one. Same dashboard, two alarms, two posts&amp;rsquo; worth of mechanism.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Capacity is bloat plus growth, and the shape that holds up is partition-and-archive.&lt;/strong&gt; A team&amp;rsquo;s first instinct on a too-full disk is to write a &lt;code&gt;DELETE FROM events WHERE created_at &amp;lt; NOW() - INTERVAL '180 days'&lt;/code&gt; and ship it. The space does not come back. On PostgreSQL, &lt;code&gt;DELETE&lt;/code&gt; marks tuples dead and leaves them on the page; the space is reclaimed by &lt;code&gt;VACUUM&lt;/code&gt;, and &lt;code&gt;VACUUM&lt;/code&gt; only returns physical space to the OS when an entire trailing extent is empty (the &lt;code&gt;VACUUM FULL&lt;/code&gt; that does is an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; rewrite of the table, which is not a thing you run on a busy production system). On an UPDATE-heavy table, autovacuum can fall behind the dead-tuple production rate, and bloat grows unboundedly until somebody intervenes. InnoDB has its own version of the same problem: deletes and updates fragment the clustered index, and a long-running transaction (an analytics session left open, a misbehaving connection pool, an export that took longer than expected) pins the undo log via the history list and prevents purge from cleaning up. &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt; lists &amp;ldquo;History list length&amp;rdquo; precisely so you can spot the case where purge is losing.&lt;/p&gt;
&lt;p&gt;The pattern that holds: partition by date or by tenant, drop or detach old partitions on a schedule, offload the detached partitions to cheaper storage if compliance or analytics still need them. PostgreSQL declarative partitioning (PG 10+) with &lt;a class="link" href="https://github.com/pgpartman/pg_partman" target="_blank" rel="noopener"
 &gt;&lt;code&gt;pg_partman&lt;/code&gt;&lt;/a&gt; handles the rotation; the extension&amp;rsquo;s background worker can create new partitions ahead of the curve and run the retention drop on a schedule with no external cron. &lt;code&gt;ALTER TABLE ... DETACH PARTITION&lt;/code&gt; turns a partition into a standalone table you can dump and drop, or move to a different tablespace on slower disk. MySQL has the same shape via native &lt;code&gt;PARTITION BY RANGE&lt;/code&gt; and &lt;code&gt;ALTER TABLE ... DROP PARTITION&lt;/code&gt;, which on InnoDB returns the space directly because each partition is its own tablespace. The space comes back instantly, instead of waiting on VACUUM and never quite catching up. The trade is schema churn upfront, and the rest of &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/" &gt;the partitioning post&lt;/a&gt; is what to know before you commit to a partition key you cannot easily change later.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IOPS is access pattern, and more IOPS is the answer to the wrong question.&lt;/strong&gt; A query that is &amp;ldquo;well-indexed&amp;rdquo; can still saturate the disk if the index does not cover the SELECT list. The classic shape: a composite index on &lt;code&gt;(customer_id, status)&lt;/code&gt; happily serves &lt;code&gt;WHERE customer_id = $1 AND status = 'open'&lt;/code&gt;, but the SELECT projects &lt;code&gt;customer_id, status, total_cents, created_at&lt;/code&gt;, and the engine follows a heap pointer for each of the few thousand matching rows to fetch the columns the index does not contain. A thousand random heap fetches per call, multiplied by call volume, is an IOPS load that no amount of provisioning quietly absorbs. The plan looks correct. The dashboard reads &amp;ldquo;needs more IOPS.&amp;rdquo; &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;The covering-index post&lt;/a&gt; walks the diagnostic in detail; the fix is &lt;code&gt;INCLUDE&lt;/code&gt; columns on PostgreSQL 11+ for the projection-only payload, or a reordered composite index on MySQL that puts the projected columns inside the index. Same query, two orders of magnitude fewer pages read, the heap-fetch count drops to zero in &lt;code&gt;EXPLAIN (ANALYZE, BUFFERS)&lt;/code&gt; output.&lt;/p&gt;
&lt;p&gt;A worked example with real numbers: a February 2026 write-up titled &lt;a class="link" href="https://frn.sh/iops/" target="_blank" rel="noopener"
 &gt;&amp;ldquo;Between select and disk&amp;rdquo;&lt;/a&gt; documents a single query reading 27,841 blocks (217 MB) to return zero rows - roughly 1,989 IOPS from a query that filtered everything out on the heap because a JSONB predicate could not be evaluated inside a B-tree on &lt;code&gt;account_id&lt;/code&gt;. A companion query did the same shape: 12,071 rows fetched, 107 MB, ~1,944 IOPS, zero rows returned. Combined, the two queries demanded ~3,900 IOPS against a 3,000 IOPS provisioned ceiling, with reads briefly hitting 3,668 IOPS as burst credits allowed. The fix was a GIN index that let the JSONB filter run inside the index scan, instead of after the heap fetch. The disk dashboard during the incident read &amp;ldquo;IOPS saturated&amp;rdquo;; the actual cause was an index that did not match the predicate.&lt;/p&gt;
&lt;p&gt;The query-side moves that keep an index covering: project the columns you actually need (an ORM defaulting to &lt;code&gt;SELECT *&lt;/code&gt; defeats coverage the moment any column lands outside the index), prefer keyset pagination over deep &lt;code&gt;OFFSET&lt;/code&gt; (a &lt;code&gt;LIMIT 50 OFFSET 100000&lt;/code&gt; reads a hundred thousand index entries to discard them and return the next fifty), match the index&amp;rsquo;s column order in &lt;code&gt;ORDER BY&lt;/code&gt; so the planner skips the sort, and write &lt;code&gt;WHERE&lt;/code&gt; predicates the planner can push down to the index leading column. &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;Non-SARGable predicates&lt;/a&gt; is the third leg of this: a function on a column, a leading wildcard, an implicit cast from &lt;code&gt;bigint&lt;/code&gt; to text, and the engine evaluates per row instead of seeking, and the IOPS graph follows. Each of these is a query-level move with no schema change, and each removes IO that more provisioned IOPS would only hide.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The managed-cloud overlay produces false fixes.&lt;/strong&gt; Three behaviors on AWS, with analogues on Azure and GCP, make the disk dashboard easy to misread. The first is gp2 (and gp3, with different mechanics) and burst credits. A gp2 volume earns 3 I/O credits per GiB per second up to a 5.4-million-credit cap, sustains 3,000 IOPS while credits last, and falls to its baseline (as low as 100 IOPS on small volumes) when the pool drains. The &lt;a class="link" href="https://aws.amazon.com/blogs/aws/new-burst-balance-metric-for-ec2s-general-purpose-ssd-gp2-volumes/" target="_blank" rel="noopener"
 &gt;AWS blog post that introduced the BurstBalance metric in 2016&lt;/a&gt; is still the cleanest reference. A workload that has been steady for months can hit a credit wall during a backup window or an end-of-quarter report, and the latency graph tells you &amp;ldquo;the disk got slow&amp;rdquo; without showing you that the disk was throttled because the credit counter hit zero. Bumping the instance, or growing the volume, resets the picture. Three days later the credits drain again. Same incident, same fix, same cycle, and &lt;code&gt;BurstBalance&lt;/code&gt; is the metric that closes the loop.&lt;/p&gt;
&lt;p&gt;The second is Aurora&amp;rsquo;s no-disk-in-the-traditional-sense model. Aurora storage scales transparently to 128 TB, so the disk-full alarm never fires. On Aurora Standard, IO is billed per request, and the alert nobody sets is on the bill. In &lt;a class="link" href="https://aws.amazon.com/blogs/aws/new-amazon-aurora-i-o-optimized-cluster-configuration-with-up-to-40-cost-savings-for-i-o-intensive-applications/" target="_blank" rel="noopener"
 &gt;May 2023, AWS announced Aurora I/O-Optimized&lt;/a&gt;, a flat-rate pricing option that removes per-IO charges in exchange for a higher instance and storage rate. The break-even, per AWS&amp;rsquo;s own guidance, is roughly 25% of total Aurora spend going to IO; above that, I/O-Optimized wins, below that, Standard does. &lt;a class="link" href="https://aws.amazon.com/blogs/apn/how-vgs-achieved-cost-savings-on-amazon-aurora/" target="_blank" rel="noopener"
 &gt;VGS&amp;rsquo;s case study from May 2025&lt;/a&gt; puts numbers on it: their &lt;code&gt;Aurora:StorageIOUsage&lt;/code&gt; was 30–40% of daily Aurora cost, traced to a Monday cleanup cron job concentrating millions of I/O operations into one window, and the move to I/O-Optimized cut their overall Aurora bill by roughly 20%, which at their scale was hundreds of thousands of dollars per year. The point is not the calculator. The point is that on Aurora the failure mode is not a graph that goes red, it is an invoice line item that climbs, and the cause is the same access pattern that would have shown up as IOPS saturation on RDS.&lt;/p&gt;
&lt;p&gt;The third is RDS storage autoscaling. Enable it, and the disk-full alarm never fires because the volume grows automatically up to the configured ceiling. The bloat keeps growing, the retention policy still does not exist, and the issue surfaces six months later at finance review when the storage line is double what it was. Autoscaling is fine; running it without a retention policy underneath turns &amp;ldquo;we need to delete old data&amp;rdquo; into &amp;ldquo;we need to delete old data and reclaim a terabyte of provisioned storage we&amp;rsquo;re paying for.&amp;rdquo;&lt;/p&gt;
&lt;h2 id="what-this-costs"&gt;What this costs
&lt;/h2&gt;&lt;p&gt;Each upstream fix has trade-offs the postmortem should name out loud.&lt;/p&gt;
&lt;p&gt;Partition-and-archive is schema churn upfront and operational scaffolding forever. Partition key choice, query routing across detached partitions, and the rotation tooling itself are the trade-offs worth making in advance, and the &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/" &gt;partitioning post&lt;/a&gt; is the canonical reference for that decision pass. The thing to keep in mind here is that none of it looks urgent until the disk is full, and that is the wrong moment to design a partition strategy.&lt;/p&gt;
&lt;p&gt;Covering indexes are write amplification and storage overhead. Every &lt;code&gt;INSERT&lt;/code&gt; and &lt;code&gt;UPDATE&lt;/code&gt; to a covered column writes to every index that covers it; an &lt;code&gt;INCLUDE&lt;/code&gt; clause adds payload columns to the index leaf without making them part of the key, which keeps the index smaller than a wide composite but still means the leaf gets updated on every write to those columns. A covering index designed for today&amp;rsquo;s SELECT list ages out the moment the SELECT list grows; the same query pattern from &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;the covering-index post&lt;/a&gt; reappears six months later when a new feature adds a column. Adding &lt;code&gt;INCLUDE&lt;/code&gt; columns interacts with PostgreSQL&amp;rsquo;s HOT update path too: HOT updates need the new tuple to fit on the same page and not modify any indexed columns, and a wider index payload combined with a fillfactor near 100% can starve the HOT optimization without changing any query. &lt;code&gt;ALTER TABLE ... SET (fillfactor = 90)&lt;/code&gt; for write-heavy tables is the standard accompaniment to wide covering indexes, and it is the easy thing to forget.&lt;/p&gt;
&lt;p&gt;Cloud-side moves are mostly upside, with one trap worth naming. Aurora I/O-Optimized&amp;rsquo;s break-even moves with workload. A cluster that was fine on Standard last quarter can cross the I/O-heavy threshold this quarter and nobody notices until the next bill review. AWS publishes &lt;a class="link" href="https://aws.amazon.com/blogs/database/estimate-cost-savings-for-the-amazon-aurora-i-o-optimized-feature-using-amazon-cloudwatch/" target="_blank" rel="noopener"
 &gt;an estimator using CloudWatch metrics&lt;/a&gt; for the recalculation; running it quarterly catches the drift.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;The most common partition-and-archive footgun is queries that span the archive boundary returning silently incomplete results. A report that used to read three years of data still asks for three years, the partition that holds year three has been detached and archived to S3, and the query returns two years of data with no error. Once is a bug. Recurring is an architecture problem. The fix is making the boundary explicit, either by routing historical queries to a federated view that includes the archive (&lt;code&gt;CREATE FOREIGN TABLE&lt;/code&gt; on PostgreSQL, or a UNION ALL against a separate archive schema), or by rejecting queries that ask for ranges the live table does not cover. Failing loud beats answering wrong.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;Three cases where the hardware reading is right and the schema reading is not.&lt;/p&gt;
&lt;p&gt;A working set that genuinely does not fit in RAM. If a hot table is 12 GB on an 8 GB instance and the top of &lt;code&gt;pg_stat_statements&lt;/code&gt; is dominated by reads against that table, no partition strategy and no covering index change the fact that the buffer cache is too small. The wait events tell the story: &lt;code&gt;IO:DataFileRead&lt;/code&gt; dominating the active-session-by-wait graph in &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iv-when-the-sort-spills/" &gt;Part IV&lt;/a&gt;&amp;rsquo;s terms. The fix is RAM, or a smaller working set, and &amp;ldquo;smaller working set&amp;rdquo; usually means partitioning so the active subset shrinks, which means the line between &amp;ldquo;more RAM&amp;rdquo; and &amp;ldquo;fewer rows&amp;rdquo; is fuzzier than the framing suggests.&lt;/p&gt;
&lt;p&gt;Snapshot or backup operations consuming live IOPS during a known window. If the latency spike lines up with the 2am backup window, or with a once-a-month consistency check, and the rest of the day is fine, the answer is scheduling and IO throttling rather than query optimization. RDS snapshots are incremental and cheap to take, but the first snapshot on a fresh volume and any major change to the dataset force a full sweep that competes with live traffic.&lt;/p&gt;
&lt;p&gt;A one-time migration off a system that should have moved to cheaper storage years ago. If the disk is full of 2017 data that nobody has read in three years, the fix is dumping it to S3 once and reclaiming the space, not designing a rotation strategy for data that is not being produced anymore. Partition-and-archive is for recurring patterns. One-off cleanup is one-off cleanup.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Capacity and IOPS are the slowest-to-alert resources a relational database has, and on managed cloud the autoscaling, burst credits, and per-IO billing models hide the cause while the bill quietly absorbs the symptom. Fix-once strategies survive workload growth in a way that &amp;ldquo;bigger instance&amp;rdquo; does not: a partition rotation dropping a month every month is not less effective the year you triple traffic, and a covering index that touches zero heap pages is not less effective when the table grows tenfold. The diagnostic discipline is the same one running through &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/" &gt;Parts II–IV&lt;/a&gt;. Pull the top-10 from &lt;code&gt;pg_stat_statements&lt;/code&gt; by &lt;code&gt;total_exec_time&lt;/code&gt;, read the plan with &lt;code&gt;BUFFERS&lt;/code&gt;, check &lt;code&gt;BurstBalance&lt;/code&gt; and the storage autoscaling history before resizing the volume. The instance type is the last thing to change.&lt;/p&gt;</description></item><item><title>It's Almost Always the Queries, Part IV: When the Sort Spills</title><link>https://explainanalyze.com/p/its-almost-always-the-queries-part-iv-when-the-sort-spills/</link><pubDate>Thu, 21 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/its-almost-always-the-queries-part-iv-when-the-sort-spills/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post It's Almost Always the Queries, Part IV: When the Sort Spills" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A database alerting on memory pressure is almost never a workload that needs more RAM. The dangerous allocation is per-sort, per-hash, per-connection and transient, so the instance-level memory graph never shows it until data size and concurrency line up at the same instant. The exception is a genuinely large working set with a low cache hit ratio, and that one is real.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A reporting endpoint sorts orders by &lt;code&gt;created_at&lt;/code&gt; for an account&amp;rsquo;s quarterly export. Last quarter it ran in about 200 ms. This quarter it takes four seconds, and nobody changed the query. The &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; output is the whole story:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-fallback" data-lang="fallback"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- last quarter
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Sort (cost=8420.11..8556.34 rows=54492 width=84)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Key: created_at
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Method: quicksort Memory: 3072kB
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;-- this quarter
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;Sort (cost=41922.88..42698.05 rows=310068 width=84)
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Key: created_at
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; Sort Method: external merge Disk: 24960kB
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The data grew, which is the one thing that always happens. The sort set crossed &lt;code&gt;work_mem&lt;/code&gt;, the executor stopped sorting in memory and started an &lt;code&gt;external merge&lt;/code&gt; against a temp file on disk, and a CPU-bound operation became an IO-bound one. No crash, no OOM kill, no page. The memory dashboards show nothing, because a temp file written by one backend for the duration of one sort is not a number that appears on an instance-level &amp;ldquo;RAM used %&amp;rdquo; graph. The query just got slow, and the only place the cause is visible is in a plan nobody ran.&lt;/p&gt;
&lt;h2 id="more-ram-doesnt-raise-work_mem"&gt;More RAM doesn&amp;rsquo;t raise work_mem
&lt;/h2&gt;&lt;p&gt;The reflex is to resize the box. The endpoint is &amp;ldquo;running out of memory,&amp;rdquo; the instance has 32 GB, so move it to 64 and the sort has room. It&amp;rsquo;s a clean story and it is wrong, for a reason that is structural rather than situational.&lt;/p&gt;
&lt;p&gt;The sort spilled because it exceeded &lt;code&gt;work_mem&lt;/code&gt;, and &lt;code&gt;work_mem&lt;/code&gt; is a fixed per-operation budget that has nothing to do with how much RAM the box has. The default is 4 MB. It is 4 MB on a 4 GB instance and 4 MB on a 256 GB instance. Doubling the instance does not move that number by a byte. MySQL&amp;rsquo;s per-thread buffers behave the same way: &lt;code&gt;sort_buffer_size&lt;/code&gt; defaults to 256 KB and stays 256 KB on a 4 GB box and on a 256 GB box, exactly as &lt;code&gt;work_mem&lt;/code&gt; does. The export&amp;rsquo;s sort set is 24 MB; it will spill on the bigger box exactly as it spilled on the smaller one, because the limit it crossed is a config value, not a quantity of physical memory. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;Part I&lt;/a&gt; called this renting the bug. The memory case is the cleanest version of the metaphor: you can buy RAM the database is structurally unable to point at the operation that needs it.&lt;/p&gt;
&lt;p&gt;So the real fix looks like raising &lt;code&gt;work_mem&lt;/code&gt;. Set it to 64 MB, the export&amp;rsquo;s sort fits in memory, the endpoint is fast again. That works for the export. It also arms a multiplier across every other connection on the system, and the multiplier is the actual subject of this article.&lt;/p&gt;
&lt;h2 id="the-memory-the-dashboard-cant-see"&gt;The memory the dashboard can&amp;rsquo;t see
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;work_mem&lt;/code&gt; is not a global pool the server draws down. It is a per-operation allowance, granted independently to every sort, hash, and materialize node, in every query, in every session, at the same time. The PostgreSQL &amp;ldquo;Resource Consumption&amp;rdquo; documentation states the consequence directly:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;Note that a complex query might perform several sort and hash operations at the same time, with each operation generally being allowed to use as much memory as this value specifies before it starts to write data into temporary files. Also, several running sessions could be doing such operations concurrently. Therefore, the total memory used could be many times the value of &lt;code&gt;work_mem&lt;/code&gt;.&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;&amp;ldquo;Many times&amp;rdquo; is the load-bearing phrase, and it has three separate multipliers stacked inside it.&lt;/p&gt;
&lt;p&gt;The first is plan shape. A report query that joins four tables, aggregates, and sorts the result does not allocate &lt;code&gt;work_mem&lt;/code&gt; once. It allocates it per memory-using node: a hash for each hash join, a sort for the &lt;code&gt;ORDER BY&lt;/code&gt;, another for a &lt;code&gt;DISTINCT&lt;/code&gt;, a hash for the &lt;code&gt;GROUP BY&lt;/code&gt;. Four memory-using nodes in one plan is ordinary, not pathological. That single query&amp;rsquo;s peak is &lt;code&gt;4 × work_mem&lt;/code&gt;, not &lt;code&gt;work_mem&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The second is &lt;code&gt;hash_mem_multiplier&lt;/code&gt;. Since PostgreSQL 13 a &lt;code&gt;hash_mem_multiplier&lt;/code&gt; setting governs this, and since PostgreSQL 15 it defaults to 2.0, so hash-based nodes get a larger allowance than sort-based ones. The &amp;ldquo;Resource Consumption&amp;rdquo; docs: &amp;ldquo;The final limit is determined by multiplying &lt;code&gt;work_mem&lt;/code&gt; by &lt;code&gt;hash_mem_multiplier&lt;/code&gt;. The default value is 2.0, which makes hash-based operations use twice the usual &lt;code&gt;work_mem&lt;/code&gt; base amount.&amp;rdquo; A hash join in that plan is not budgeted at &lt;code&gt;work_mem&lt;/code&gt;. It is budgeted at &lt;code&gt;2 × work_mem&lt;/code&gt;, on a current default, before anyone has touched a setting.&lt;/p&gt;
&lt;p&gt;The third is parallel workers. A parallel sequential scan feeding a parallel hash or sort gives each worker its own &lt;code&gt;work_mem&lt;/code&gt; allocation for its slice of the work. A query with &lt;code&gt;max_parallel_workers_per_gather&lt;/code&gt; set to 4 can have five processes (the leader plus four workers) each holding a &lt;code&gt;work_mem&lt;/code&gt;-sized hash for the same node.&lt;/p&gt;
&lt;p&gt;Now do the arithmetic the way &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/" &gt;Part III&lt;/a&gt; did it with CPU-seconds. You raised &lt;code&gt;work_mem&lt;/code&gt; to 64 MB to stop the export from spilling. A moderately complex query has four memory-using nodes, two of them hashes that get the 2.0 multiplier. Call its peak a conservative &lt;code&gt;64 MB × 6&lt;/code&gt; once the hash multiplier is counted, roughly 384 MB for one execution. Your Rails app runs 300 worker processes, each holding a connection, and on a busy afternoon 80 of them are running a query of about that shape at the same instant. &lt;code&gt;384 MB × 80&lt;/code&gt; is just over 30 GB of transient sort and hash memory, none of it in &lt;code&gt;shared_buffers&lt;/code&gt;, none of it visible on the memory graph until the second it is all allocated at once. The instance has 32 GB. The export&amp;rsquo;s sort fit. The OOM killer arrives anyway, two weeks after the change, with no obvious deploy to blame, because the change that caused it was a config edit and the trigger was an ordinary Tuesday with slightly more concurrency than Monday.&lt;/p&gt;
&lt;p&gt;The arithmetic above assumes the plan goes as costed. But the planner chose that plan from estimates, not from the rows it would actually find. Sort versus no-sort, hash join versus merge join, HashAggregate versus GroupAggregate are all decided at planning time from row-count guesses in &lt;code&gt;pg_statistic&lt;/code&gt;. A stale estimate, or an &lt;code&gt;n_distinct&lt;/code&gt; that was always wrong, and the planner picks a memory-hungry plan accurate stats would have avoided, or under-sizes an allocation that blows past &lt;code&gt;work_mem&lt;/code&gt; at runtime. &lt;code&gt;GROUP BY&lt;/code&gt; is the sharp case. Before PostgreSQL 13, released &lt;a class="link" href="https://www.postgresql.org/docs/release/13.0/" target="_blank" rel="noopener"
 &gt;2020-09-24&lt;/a&gt;, a HashAggregate chosen on a too-low &lt;code&gt;n_distinct&lt;/code&gt; estimate had no disk fallback at all: the hash table grew past &lt;code&gt;work_mem&lt;/code&gt; with no bound and could OOM the server. PG13 added the spill, and its release notes state the new behavior plainly. Hash aggregation &amp;ldquo;was avoided if it was expected to use more than &lt;code&gt;work_mem&lt;/code&gt; memory&amp;rdquo;; now the plan can be chosen anyway, and &amp;ldquo;the hash table will be spilled to disk if it exceeds &lt;code&gt;work_mem&lt;/code&gt; times &lt;code&gt;hash_mem_multiplier&lt;/code&gt;.&amp;rdquo; An uncapped OOM became the same &lt;code&gt;external merge&lt;/code&gt; trade the export opened on, and the data never had to grow to trigger it. The estimate only had to go stale.&lt;/p&gt;
&lt;p&gt;The same structure runs on MySQL with different knob names. The per-thread buffers (&lt;code&gt;sort_buffer_size&lt;/code&gt;, &lt;code&gt;join_buffer_size&lt;/code&gt;, &lt;code&gt;read_rnd_buffer_size&lt;/code&gt;) are allocated per connection, and &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/memory-use.html" target="_blank" rel="noopener"
 &gt;the MySQL documentation is explicit&lt;/a&gt; that &lt;code&gt;join_buffer_size&lt;/code&gt; can be allocated more than once for a single query, once per join that cannot use an index. Multiply the per-thread total by &lt;code&gt;max_connections&lt;/code&gt; and you have MySQL&amp;rsquo;s version of the same blind multiplier. MySQL&amp;rsquo;s optimizer is just as estimate-bound: it picks join order and access paths from index cardinality (refreshed by &lt;code&gt;ANALYZE TABLE&lt;/code&gt;, stored under &lt;code&gt;innodb_stats_persistent&lt;/code&gt;) and optional column histograms, and stale cardinality pushes it onto a join that cannot use an index and falls back to a block-nested-loop on &lt;code&gt;join_buffer_size&lt;/code&gt;. Internal temporary tables add a second multiplier: under the MySQL 8.0 TempTable engine, an in-memory temp table grows until it hits &lt;code&gt;tmp_table_size&lt;/code&gt;, at which point, in the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/internal-temporary-tables.html" target="_blank" rel="noopener"
 &gt;documentation&amp;rsquo;s words&lt;/a&gt;, &amp;ldquo;MySQL automatically converts the in-memory internal temporary table to an &lt;code&gt;InnoDB&lt;/code&gt; on-disk internal temporary table.&amp;rdquo; &lt;code&gt;temptable_max_ram&lt;/code&gt; (default 1 GiB) caps the engine&amp;rsquo;s total RAM before it spills to memory-mapped files. The MySQL spill is the same event as the Postgres &lt;code&gt;external merge&lt;/code&gt;, reached through a slightly different accounting path.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;This is also why &amp;ldquo;give the database more memory&amp;rdquo; so often goes to the wrong place. Told to add memory, teams enlarge &lt;code&gt;shared_buffers&lt;/code&gt; (or &lt;code&gt;innodb_buffer_pool_size&lt;/code&gt;). That is the buffer cache, fixed at server startup, and it does nothing for sorts and hashes, which allocate from a separate per-backend region. Worse, oversizing it starves the resource the database quietly depends on. PostgreSQL uses no direct IO; every page read goes through the operating system page cache, and RAM you did not hand to &lt;code&gt;shared_buffers&lt;/code&gt; or to backends is not idle, it is that cache. The &lt;a class="link" href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server" target="_blank" rel="noopener"
 &gt;PostgreSQL wiki tuning guide&lt;/a&gt; puts the starting point at &amp;ldquo;1/4 of the memory in your system&amp;rdquo; and warns that &amp;ldquo;it&amp;rsquo;s unlikely you&amp;rsquo;ll find using more than 40% of RAM to work better than a smaller amount,&amp;rdquo; precisely because the OS cache needs the rest. Every memory area in this article is a facet of one accounting problem: the instance metric sums physical pages, and none of the allocations that actually break the database are visible at that resolution.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The OOM killer is where the silent spill stops being silent. Linux overcommits memory by default: it hands out address space freely on the assumption that not every process touches all of it. When resident memory across the system exceeds RAM plus swap, the kernel invokes the OOM killer, which picks a victim by &lt;code&gt;oom_score&lt;/code&gt; and sends it &lt;code&gt;SIGKILL&lt;/code&gt;. If the victim is a PostgreSQL backend, the damage does not stop at that one connection. The &lt;a class="link" href="https://www.postgresql.org/docs/current/kernel-resources.html" target="_blank" rel="noopener"
 &gt;PostgreSQL documentation on managing kernel resources&lt;/a&gt; explains that the kernel &amp;ldquo;might terminate the PostgreSQL postmaster&amp;rdquo; outright, and even when it takes a backend instead, a backend killed by &lt;code&gt;SIGKILL&lt;/code&gt; had no chance to release its locks or detach cleanly from shared memory. The postmaster can no longer assume shared memory is consistent, so it does the only safe thing: it terminates every other backend, and the entire instance runs crash recovery. One report query, on one connection, restarts the whole database. MySQL gets to the same place by a shorter route. &lt;code&gt;mysqld&lt;/code&gt; is a single multi-threaded process, so the OOM killer has exactly one target; kill it and the entire server goes down at once, and on restart InnoDB runs crash recovery by replaying its redo log. Both engines end in a full restart, Postgres because the postmaster cascades the kill outward and MySQL because there was only ever one process to kill.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;This is the failure mode behind a real, dated incident. In a &lt;a class="link" href="https://mydbanotebook.org/posts/work_mem-its-a-trap/" target="_blank" rel="noopener"
 &gt;March 2026 write-up titled &amp;ldquo;work_mem: it&amp;rsquo;s a trap!&amp;rdquo;&lt;/a&gt;, PostgreSQL contributor Lætitia Avrot walked through a production cluster with 2 TB of RAM that the OOM killer reaped. &lt;code&gt;work_mem&lt;/code&gt; on that cluster was 2 MB, below the 4 MB default, not some reckless 1 GB. A single badly structured query accumulated allocations inside one &lt;code&gt;ExecutorState&lt;/code&gt; memory context faster than anything released them. The context&amp;rsquo;s dump showed 524,059 separate chunks. That memory is not freed until the operation finishes, and the operation never finished, so it climbed until 2 TB was gone. A 2 MB setting and a 2 TB box, and the box still lost. The problem was never the size of the box.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="fixes-and-what-each-one-costs"&gt;Fixes, and what each one costs
&lt;/h2&gt;&lt;p&gt;Do not raise &lt;code&gt;work_mem&lt;/code&gt; globally. The export needs 64 MB; the rest of the workload does not, and the global setting applies the change to every connection whether it needs it or not. Raise it where the big sort actually runs. &lt;code&gt;SET work_mem = '256MB'&lt;/code&gt; inside the reporting session, scoped to that transaction, or &lt;code&gt;ALTER ROLE analytics SET work_mem = '256MB'&lt;/code&gt; so the change attaches to the role the reports run as and the OLTP path keeps the small default. MySQL&amp;rsquo;s per-thread buffers are session-settable in the same way. Keep the &lt;code&gt;my.cnf&lt;/code&gt; global values for &lt;code&gt;sort_buffer_size&lt;/code&gt;, &lt;code&gt;join_buffer_size&lt;/code&gt;, and &lt;code&gt;tmp_table_size&lt;/code&gt; small, and &lt;code&gt;SET SESSION sort_buffer_size = ...&lt;/code&gt; on the reporting connection. The cost is that this requires knowing which workload is which. It assumes the reporting queries connect as a distinguishable role or run through a distinguishable code path, and on a system where the web app and the nightly export share one database user, that separation is work you have to do first, on either engine.&lt;/p&gt;
&lt;p&gt;A connection pooler bounds the other multiplier. The arithmetic above had 80 concurrent heavy queries because 300 app workers each held a real backend. Put PgBouncer in transaction mode in front, sized to a 40-connection pool, and the database can never run more than 40 backends no matter how many app workers exist. The multiplier is capped at 40 instead of 300. MySQL&amp;rsquo;s analogue is &lt;a class="link" href="https://proxysql.com/documentation/" target="_blank" rel="noopener"
 &gt;ProxySQL&lt;/a&gt;, an external connection multiplexer that fronts the server the way PgBouncer fronts Postgres, plus the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/thread-pool.html" target="_blank" rel="noopener"
 &gt;thread pool plugin&lt;/a&gt; shipped in MySQL Enterprise Edition and in Percona Server, which caps the number of threads executing at once. Bounding concurrent threads bounds the per-thread-buffer multiplier the same way bounding backends bounds it on Postgres. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/" &gt;Part III&lt;/a&gt; covered pool sizing for the CPU case, and the reasoning transfers exactly: a query that waits briefly for a pool slot and then runs is cheaper than one that starts immediately and helps exhaust memory. The cost is latency under burst, and a pool sized too small turns into its own incident when every slot is held and the queue backs up.&lt;/p&gt;
&lt;p&gt;The fix that removes the spill instead of feeding it is fixing the query. The export sorts by &lt;code&gt;created_at&lt;/code&gt;; an index on &lt;code&gt;(account_id, created_at)&lt;/code&gt; lets the planner return rows already in order and the &lt;code&gt;Sort&lt;/code&gt; node disappears from the plan entirely, no &lt;code&gt;work_mem&lt;/code&gt; consumed because no sort happens. Keeping statistics fresh is part of the same fix: autovacuum runs &lt;code&gt;ANALYZE&lt;/code&gt;, but a bulk load or a fast-growing table outruns it, and a manual &lt;code&gt;ANALYZE&lt;/code&gt; (or a raised per-column target via &lt;code&gt;ALTER TABLE ... ALTER COLUMN ... SET STATISTICS&lt;/code&gt;, or &lt;code&gt;CREATE STATISTICS&lt;/code&gt; for correlated columns) keeps the planner&amp;rsquo;s estimate close enough to reality that it sizes the plan correctly. MySQL&amp;rsquo;s equivalent is &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/analyze-table.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;ANALYZE TABLE&lt;/code&gt;&lt;/a&gt; for index cardinality and &lt;code&gt;ANALYZE TABLE ... UPDATE HISTOGRAM ON ...&lt;/code&gt; for column histograms, with &lt;code&gt;innodb_stats_auto_recalc&lt;/code&gt; governing whether InnoDB refreshes cardinality on its own. The diagnostic tell is the one &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/" &gt;Part II&lt;/a&gt; already named: &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; showing estimated rows and actual rows diverging by orders of magnitude means the planner is flying blind. A hash join&amp;rsquo;s allocation is proportional to the rows on its build side, so a predicate that filters earlier, or an index that avoids scanning rows the query then discards, shrinks the hash. This is the crossover with the rest of the series: a &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable predicate&lt;/a&gt; that forces a scan also inflates every downstream sort and hash that scan feeds, and a &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;covering index that quietly stopped covering&lt;/a&gt; when a column joined the &lt;code&gt;SELECT&lt;/code&gt; list adds heap fetches that widen the rows a sort has to buffer. Tuning the query to be smaller per call is the per-operation answer; Part V takes the IO side of it further.&lt;/p&gt;
&lt;p&gt;Leave &lt;code&gt;shared_buffers&lt;/code&gt; near the conventional fraction and do not raise it to &amp;ldquo;use the memory.&amp;rdquo; The page cache needs that headroom, and on a managed service the default is usually already in the sane range. The kernel side is worth one deliberate pass: &lt;code&gt;vm.overcommit_memory&lt;/code&gt; controls how freely Linux hands out address space, and setting the postmaster&amp;rsquo;s &lt;code&gt;oom_score_adj&lt;/code&gt; lower than its backends&amp;rsquo; (PostgreSQL ships &lt;code&gt;PG_OOM_ADJUST_FILE&lt;/code&gt; and &lt;code&gt;PG_OOM_ADJUST_VALUE&lt;/code&gt; for exactly this) means that when the OOM killer does fire, it reaps a single backend and not the supervisor. That converts a full crash-recovery restart into one dropped connection. It does not fix the multiplier; it makes the multiplier&amp;rsquo;s worst day cheaper. &lt;code&gt;vm.overcommit_memory&lt;/code&gt; is an OS-level setting that applies to both engines, but the per-process &lt;code&gt;oom_score_adj&lt;/code&gt; trick has nothing to work with on MySQL. There is no supervisor and worker split, so one &lt;code&gt;mysqld&lt;/code&gt; process means nothing to spare. For MySQL the levers are the system-wide overcommit setting and the discipline of not over-provisioning the per-thread buffers in the first place.&lt;/p&gt;
&lt;h2 id="when-more-ram-is-the-honest-answer"&gt;When more RAM is the honest answer
&lt;/h2&gt;&lt;p&gt;The thesis has real exceptions, and a staff engineer wants the boundary, not the slogan.&lt;/p&gt;
&lt;p&gt;A genuinely large working set is the first one. If the buffer-cache hit ratio is low and the wait events are dominated by &lt;code&gt;IO:DataFileRead&lt;/code&gt;, the database is going to disk because the data it needs does not fit in RAM, and that is a capacity problem that more memory honestly solves. The tell is in the waits, not the memory graph: steady IO waits on reads, a hit ratio that has been falling for weeks. This shades into Part V&amp;rsquo;s territory, where the line between &amp;ldquo;needs more RAM for cache&amp;rdquo; and &amp;ldquo;needs more IOPS&amp;rdquo; gets drawn properly.&lt;/p&gt;
&lt;p&gt;A correctly isolated analytical workload is the second. A reporting role that runs deliberate large sorts, on its own connection budget, behind a pooler that caps its concurrency, genuinely benefits from a high &lt;code&gt;work_mem&lt;/code&gt; for that role. Raising it there is not the bug this article describes. The bug is raising it globally and arming it across 300 OLTP connections. Scoped to a role that runs ten concurrent queries at most, a large &lt;code&gt;work_mem&lt;/code&gt; is a correct decision.&lt;/p&gt;
&lt;p&gt;And plainly low concurrency. A database with a 20-connection pool and a workload that never runs more than a handful of heavy queries at once has a small multiplier, and raising &lt;code&gt;work_mem&lt;/code&gt; globally on that system is safe because &lt;code&gt;work_mem × 20&lt;/code&gt; is a number the box can hold with room to spare. The multiplier is only dangerous when it is large. Measure it before assuming it is.&lt;/p&gt;
&lt;h2 id="the-number-that-isnt-on-the-graph"&gt;The number that isn&amp;rsquo;t on the graph
&lt;/h2&gt;&lt;p&gt;The memory graph on the instance dashboard is an honest number. It reports resident physical pages, sampled every minute, and it is the wrong instrument for this failure for the same reason the slow-query log was the wrong instrument in &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/" &gt;Part III&lt;/a&gt;. The slow-query log filters for queries that are individually expensive and misses the cheap query run a million times. The memory graph reports memory that is allocated right now and misses the allocation that is small per operation, multiplied by plan nodes, by the hash multiplier, by parallel workers, and by concurrent connections, and exists only in the instant all of those line up. The export sort that spilled to a 24 MB temp file and the 2 TB cluster the OOM killer reaped are the same failure at two scales: a per-operation cost the instance metric was never built to see. Resize the box and you move the ceiling that cost climbs toward. You do not change the cost, and the cost is set by the query and the connection count, the same two numbers every part of this series keeps coming back to.&lt;/p&gt;</description></item><item><title>It's Almost Always the Queries, Part III: When the CPU Is Pegged</title><link>https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/</link><pubDate>Tue, 19 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/its-almost-always-the-queries-part-iii-when-the-cpu-is-pegged/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post It's Almost Always the Queries, Part III: When the CPU Is Pegged" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A relational database pinned at 100% CPU is almost never running one expensive query. It&amp;rsquo;s running a cheap one too many times. The slow-query log and mean-time sorting both look right past it; &lt;code&gt;total_exec_time&lt;/code&gt; is the only view that finds it.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A client portal has a status dropdown at the top of the orders page. It shows a count next to &amp;ldquo;Open&amp;rdquo;: &lt;code&gt;SELECT COUNT(*) FROM orders WHERE status = 'open' AND account_id = $1&lt;/code&gt;. For any given account that&amp;rsquo;s around 200 rows. The query runs in 0.4 ms. It has run in 0.4 ms for two years.&lt;/p&gt;
&lt;p&gt;Then marketing buys a Super Bowl ad. Thirty seconds of airtime, a short URL, and for the next twenty minutes the portal takes the kind of traffic it normally sees in a quarter. Every visitor lands on the orders page. Every page render fires that &lt;code&gt;COUNT(*)&lt;/code&gt;. The primary&amp;rsquo;s CPU graph goes from a comfortable 35% to a flat 100% ceiling and stays there. Checkout latency triples. The on-call engineer pulls up the slow-query log to find the offending statement and the log is empty. Nothing crossed the 100 ms threshold. The slowest query in &lt;code&gt;pg_stat_activity&lt;/code&gt; right now is 12 ms. Sorted by mean execution time, the dropdown count doesn&amp;rsquo;t appear until page four.&lt;/p&gt;
&lt;p&gt;It is, by a wide margin, the cheapest query in the system. It is also the entire problem.&lt;/p&gt;
&lt;h2 id="more-cpu-rents-the-bug"&gt;More CPU rents the bug
&lt;/h2&gt;&lt;p&gt;Resize the instance. Double the vCPUs, the graph drops from 100% to 55%, the incident closes. This works, and during a live traffic spike with revenue on the line it is often the correct first move. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;Part I&lt;/a&gt; called this renting the bug, and the CPU case is the cleanest example of why the metaphor holds.&lt;/p&gt;
&lt;p&gt;The cost of that &lt;code&gt;COUNT(*)&lt;/code&gt; is linear in traffic. A box twice the size moves the ceiling, it does not change the slope. The dropdown still fires once per page render, the render count still tracks visitor count, and visitor count for a business that just discovered TV advertising only goes up. The next campaign, or organic growth over two quarters, walks the bigger box back to the same 100%. Each round of resizing buys time proportional to the headroom purchased, and the bill recurs.&lt;/p&gt;
&lt;p&gt;The other reflex is more replicas. For a read-heavy workload that genuinely is read-heavy, spreading reads across replicas is sound. It does not help here for a reason worth being precise about: the &lt;code&gt;COUNT(*)&lt;/code&gt; is not slow because the primary is contended. It is slow-in-aggregate because it does real work every single call, and that work executes on whatever node serves the query. Move it to a replica and the replica&amp;rsquo;s CPU pegs instead. You have not removed the work. You have bought another machine to do it.&lt;/p&gt;
&lt;h2 id="why-a-04-ms-query-saturates-a-core"&gt;Why a 0.4 ms query saturates a core
&lt;/h2&gt;&lt;p&gt;The arithmetic is the whole mechanism. A query that averages 0.4 ms and fires 50,000 times a minute consumes 50,000 × 0.0004 = 20 CPU-seconds of work every 60 seconds of wall-clock time. That&amp;rsquo;s one core, a third occupied, by one statement. Push the campaign traffic to 150,000 calls a minute and that statement alone wants a full core. Add the other queries the orders page fires (the order list, the account lookup, the session check) and a handful of cores disappear into a workload where no individual query is doing anything you&amp;rsquo;d call slow.&lt;/p&gt;
&lt;p&gt;This is why the slow-query log is the wrong instrument. A log thresholded at 100 ms is a filter for queries that are individually expensive. The CPU-bound failure mode is a population of queries that are individually trivial and collectively enormous. The log is working exactly as designed; it is designed to miss this. Mean execution time has the same blind spot. The dropdown count&amp;rsquo;s mean is 0.4 ms and will stay 0.4 ms while it burns four cores, because the mean says nothing about how often the query runs.&lt;/p&gt;
&lt;p&gt;The view that sees it is total execution time. &lt;code&gt;pg_stat_statements&lt;/code&gt; ordered by &lt;code&gt;total_exec_time&lt;/code&gt;, or MySQL&amp;rsquo;s &lt;code&gt;events_statements_summary_by_digest&lt;/code&gt; ordered by &lt;code&gt;SUM_TIMER_WAIT&lt;/code&gt;, multiplies per-call cost by call count, which is the number that actually maps to CPU consumed. Sort by that column and the dropdown &lt;code&gt;COUNT(*)&lt;/code&gt; is on the first row, with a call count an order of magnitude above anything else in the list. &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/" &gt;Part II&amp;rsquo;s Step 6&lt;/a&gt; is the procedure for getting there; this is the failure mode it was written for.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;pg_stat_statements&lt;/code&gt; aggregates since the last &lt;code&gt;pg_stat_statements_reset()&lt;/code&gt; or server start, so the top of the list reflects history, not the current minute. During an incident, reset it and wait sixty seconds, or compare two snapshots a minute apart. A query that dominates a clean sixty-second window is the one burning CPU right now, not the one that happened to run a lot last Tuesday.&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id="count-has-no-shortcut-and-thats-structural"&gt;COUNT(*) has no shortcut, and that&amp;rsquo;s structural
&lt;/h3&gt;&lt;p&gt;The reason this particular query does real work every call, rather than returning a cached number, is MVCC. Under multi-version concurrency control, two transactions running at the same instant can correctly see different row counts for the same table, because each sees the snapshot consistent with its own start. There is no single true count the database could cache and hand back. The &lt;a class="link" href="https://wiki.postgresql.org/wiki/Slow_Counting" target="_blank" rel="noopener"
 &gt;PostgreSQL wiki&amp;rsquo;s &amp;ldquo;Slow Counting&amp;rdquo; page&lt;/a&gt; states it plainly: PostgreSQL &amp;ldquo;must walk through all rows to determine visibility,&amp;rdquo; which &amp;ldquo;normally results in a sequential scan reading information about every row in the table.&amp;rdquo; &lt;a class="link" href="https://www.citusdata.com/blog/2016/10/12/count-performance/" target="_blank" rel="noopener"
 &gt;Citus&amp;rsquo;s 2016 write-up on counting performance&lt;/a&gt; puts the same point in one sentence: &amp;ldquo;There is no single universal row count that the database could cache, so it must scan through all rows counting how many are visible.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;InnoDB works the same way for the same reason. The MySQL documentation notes that InnoDB does not keep an internal stored row count, because a single counter cannot be correct for all transactions at once, and processes &lt;code&gt;COUNT(*)&lt;/code&gt; by traversing the smallest available index. This is the detail behind a stubborn piece of stale advice. MyISAM, the old default engine, did keep an exact row count in table metadata, so &lt;code&gt;SELECT COUNT(*)&lt;/code&gt; against a MyISAM table really was a constant-time metadata read. Advice written in that era (&amp;ldquo;COUNT(*) is free, don&amp;rsquo;t worry about it&amp;rdquo;) survived the engine that made it true. On InnoDB it is wrong.&lt;/p&gt;
&lt;p&gt;An index helps, with conditions. A &lt;code&gt;COUNT(*)&lt;/code&gt; filtered by an indexed column scans the index instead of the heap, and PostgreSQL&amp;rsquo;s index-only scan can satisfy a count from the index alone, but only for the pages the visibility map marks all-visible. The visibility map is maintained by &lt;code&gt;VACUUM&lt;/code&gt;. On a table with steady write traffic and autovacuum falling behind, a growing fraction of pages are not marked all-visible, the index-only scan falls back to heap fetches for those pages, and the count gets slower precisely when the table is busiest. The shortcut exists. It is conditional on vacuum keeping pace, and a write-heavy table under a traffic spike is the exact case where vacuum is least likely to be winning.&lt;/p&gt;
&lt;h2 id="the-cpu-bound-family"&gt;The CPU-bound family
&lt;/h2&gt;&lt;p&gt;The dropdown &lt;code&gt;COUNT(*)&lt;/code&gt; is the canonical case because it is so cheap per call that it defeats every individually-focused diagnostic. The same shape (cheap-or-medium per call, ridden to 100% by call volume or concurrency) shows up in four other forms worth recognizing on sight.&lt;/p&gt;
&lt;p&gt;The first is aggregation. &lt;code&gt;GROUP BY&lt;/code&gt;, &lt;code&gt;SUM&lt;/code&gt;, &lt;code&gt;AVG&lt;/code&gt;, &lt;code&gt;DISTINCT&lt;/code&gt;, and the dashboard rollups built on them spend CPU on hashing and sorting, and the work is proportional to rows scanned, not rows returned. A &amp;ldquo;revenue by region this month&amp;rdquo; tile that scans 4 million order rows to return 6 numbers does 4 million rows of work every time someone loads the dashboard. One analyst with the dashboard open and a 30-second auto-refresh is 2,880 full rollups a day. A team of forty analysts, each with it open, is a standing CPU load that has nothing to do with how many people are actually looking. The query is not slow. It is medium, and it runs constantly.&lt;/p&gt;
&lt;p&gt;The second is parallel-worker starvation. PostgreSQL runs large scans and aggregates across parallel workers drawn from a shared, server-wide pool capped by &lt;code&gt;max_parallel_workers&lt;/code&gt;. The &lt;a class="link" href="https://www.postgresql.org/docs/current/how-parallel-query-works.html" target="_blank" rel="noopener"
 &gt;PostgreSQL documentation on parallel query&lt;/a&gt; is explicit that workers come from one pool and &amp;ldquo;the requested number of workers may not actually be available at run time.&amp;rdquo; A few heavy analytics queries, each fanning out to &lt;code&gt;max_parallel_workers_per_gather&lt;/code&gt; workers, can drain that pool. Everything else then runs with fewer workers than the planner costed for, or serially. The symptom is strange: CPU pegged, yet many sessions appear to be waiting rather than working, because the plan they got is not the plan they were costed for.&lt;/p&gt;
&lt;p&gt;The third is the connection pool sized past the core count. A database with 16 cores can do at most 16 things at once. Point 400 active connections at it and the operating system time-slices 400 runnable processes across 16 cores, and an increasing share of every core&amp;rsquo;s time goes to context switching rather than query execution. The &lt;a class="link" href="https://www.pgbouncer.org/config.html" target="_blank" rel="noopener"
 &gt;PgBouncer documentation&lt;/a&gt; and the conventional sizing guidance both land near the same place: a pool sized close to the core count, often &lt;code&gt;(cores × 2)&lt;/code&gt;, beats a much larger pool. The &lt;a class="link" href="https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing" target="_blank" rel="noopener"
 &gt;HikariCP &amp;ldquo;About Pool Sizing&amp;rdquo; page&lt;/a&gt; makes the underlying point bluntly: running two queries sequentially is always faster than time-slicing them across one core, and its Oracle benchmark cut response times from roughly 100 ms to 2 ms by shrinking a pool from 2,048 connections to 96. CPU reads as 100%, but a measurable fraction of it is the scheduler shuffling processes, not the database answering questions.&lt;/p&gt;
&lt;p&gt;The fourth is fan-out from a distributed service mesh. Picture twelve microservices, each running six instances, and every instance polling the database on its own timer for state it treats as live: a config row it reloads every few seconds, a routing table it re-reads on a schedule. Each of the seventy-two issues a modest, reasonable number of queries, and none of it looks alarming on that service&amp;rsquo;s own dashboard. The database underneath sees the sum, a baseline load that no team owns and no team&amp;rsquo;s monitoring displays. What makes this its own shape, rather than the volume problem restated, is that every caller is asking the identical question and getting back the identical answer. The dropdown &lt;code&gt;COUNT&lt;/code&gt; was parameterized per account, and every execution did different work for a different row. Here, seventy-two instances poll for one config row that reads the same for all of them, because the database is the single place every service agrees holds the truth. The work is real and redundant: seventy-one of those reads per tick exist only because nothing in front of the database kept the answer the seventy-second already fetched.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;The unread-count badge is the fan-out problem hiding in your own frontend. A &amp;ldquo;you have N notifications&amp;rdquo; badge in the global nav re-runs its &lt;code&gt;COUNT&lt;/code&gt; on every page load of every authenticated user. It is not one feature&amp;rsquo;s query, it is a tax on every route in the application. An ORM N+1 in a list view is the same pattern from the &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" target="_blank" rel="noopener"
 &gt;ORM coupling&lt;/a&gt;: one page render silently expands into one query per row, and at list-page volume that is a CPU load with no single slow statement to point at.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There is a fifth shape that is per-call expensive rather than per-call cheap, and it belongs here because it pins CPU the same way: predicates the planner cannot turn into an index seek. A &lt;code&gt;LIKE '%term%'&lt;/code&gt; with a leading wildcard, a regex match, JSONB extraction in the &lt;code&gt;WHERE&lt;/code&gt; clause, a function wrapped around a column, an implicit type cast because the column is &lt;code&gt;bigint&lt;/code&gt; and the parameter arrived as text. Each forces the engine to evaluate an expression on every candidate row, which is CPU work that no amount of indexing removes until the predicate itself is rewritten. &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;Non-SARGable predicates&lt;/a&gt; covers the rewrite. The reason it shares this article is the diagnostic: a non-SARGable filter under concurrency reads as CPU saturation, and &lt;code&gt;total_exec_time&lt;/code&gt; is again where it surfaces.&lt;/p&gt;
&lt;h2 id="fixes-and-what-each-one-costs"&gt;Fixes, and what each one costs
&lt;/h2&gt;&lt;p&gt;For the dropdown &lt;code&gt;COUNT(*)&lt;/code&gt;, the first question is whether the number needs to be exact. Often it does not. A status badge that says &amp;ldquo;Open: 204&amp;rdquo; is not measurably more useful than one that says &amp;ldquo;Open: ~200,&amp;rdquo; and an estimate is close to free. PostgreSQL&amp;rsquo;s planner statistics already hold a row estimate in &lt;code&gt;pg_class.reltuples&lt;/code&gt;; the &lt;a class="link" href="https://wiki.postgresql.org/wiki/Count_estimate" target="_blank" rel="noopener"
 &gt;PostgreSQL wiki&amp;rsquo;s &amp;ldquo;Count estimate&amp;rdquo; page&lt;/a&gt; gives the query and the caveat, that &lt;code&gt;reltuples&lt;/code&gt; is maintained by &lt;code&gt;VACUUM&lt;/code&gt; and &lt;code&gt;ANALYZE&lt;/code&gt; and is only as fresh as the last run. For a filtered count, parsing the row estimate out of &lt;code&gt;EXPLAIN&lt;/code&gt; output gets you a per-predicate estimate. The trade-off is accuracy: an estimate can be off by a few percent, and it is wrong to use one where the count drives a financial total or a correctness check.&lt;/p&gt;
&lt;p&gt;When the number must be exact, the choice is between caching it and maintaining it. A cached count (in Redis, or a materialized view refreshed on a schedule) turns thousands of &lt;code&gt;COUNT(*)&lt;/code&gt; executions into one, at the cost of staleness equal to the refresh interval. A counter table or a counter column, incremented and decremented by trigger or by application code, keeps the count exact and reads in constant time, and it moves the cost to writes. Every insert and delete now also writes the counter row, and if that counter is global, every writer contends on one row. That contention is its own CPU and lock problem, sometimes a worse one than the count you started with. Per-account or per-shard counters spread the contention; a global &amp;ldquo;total orders&amp;rdquo; counter concentrates it. The pragmatic middle for a UI badge is the bounded count: &lt;code&gt;SELECT COUNT(*) FROM (SELECT 1 FROM orders WHERE status='open' AND account_id=$1 LIMIT 100) t&lt;/code&gt;, which stops scanning at 100 and lets the interface render &amp;ldquo;99+&amp;rdquo;. The product question of whether anyone needs the exact number above 99 is usually answered &amp;ldquo;no&amp;rdquo; the moment you ask it.&lt;/p&gt;
&lt;p&gt;Aggregation rollups want to stop running at read time, and the obvious instrument is a materialized view. On an OLTP primary it is more dependency than it looks. &lt;code&gt;REFRESH MATERIALIZED VIEW&lt;/code&gt; still runs the full scan; it has only moved the work off the viewers and onto a schedule, on the same cores you are trying to protect, in periodic spikes rather than a steady drip. Plain &lt;code&gt;REFRESH&lt;/code&gt; holds an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; lock that blocks reads of the view until it finishes; &lt;code&gt;REFRESH ... CONCURRENTLY&lt;/code&gt; trades that lock for a mandatory unique index and a slower full recompute. Add a scheduler to run it and a staleness window to reason about, and a feature that looked like one line of DDL is a small system to operate. The version that actually removes the scan is a summary table the write path maintains: each order insert also bumps the per-region, per-day total, so the dashboard reads a few pre-computed rows and the 4-million-row scan never runs. The cost shifts onto writes, a couple of extra row updates per transaction, and the numbers stay current with no refresh job at all. Where the data tolerates lag, the other move is to get the aggregation off the primary: point the dashboard&amp;rsquo;s &lt;code&gt;GROUP BY&lt;/code&gt; at a read replica so the scan burns the replica&amp;rsquo;s cores, or feed a separate analytics database and let the heavy rollups live there. A revenue tile that updates every five minutes is fine; an inventory count a customer sees at checkout usually is not.&lt;/p&gt;
&lt;p&gt;Parallel-worker starvation is a sizing problem. Cap &lt;code&gt;max_parallel_workers_per_gather&lt;/code&gt; so a single analytics query cannot drain the pool, and size &lt;code&gt;max_parallel_workers&lt;/code&gt; against the cores you can spare after the OLTP workload has what it needs. The connection-pool case is the same discipline: size the pooler near the core count rather than near peak concurrency, and let connections queue briefly in the pooler instead of oversubscribing the scheduler. Both fixes feel like throttling, and they are. A query that waits 5 ms for a pool slot and then runs at full speed beats one that starts immediately and fights 399 others for a core.&lt;/p&gt;
&lt;p&gt;Fan-out has two fixes, and which applies depends on whether the callers want the same answer. When they do - a config row, a feature-flag set that every instance reads identically - a cache in front of the database is the direct fix. One instance&amp;rsquo;s read populates a shared cache, the other seventy-one read from the cache, and the database serves the query once per TTL instead of once per instance per tick. When the callers genuinely need different answers, no single query is wrong and the lever is governance: a platform-level view of aggregate QPS broken down by calling service, and a per-service query budget treated as a real constraint. Health checks can poll every 30 seconds instead of every 2. Polling can become a push. None of that happens without someone holding the number that no individual team&amp;rsquo;s dashboard shows.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;Across every fix here, the move is the same: do the work fewer times. Estimate instead of count, cache instead of recompute, refresh on a schedule instead of per-view, poll less often, queue instead of oversubscribe. Tuning a query to be faster per call is the Part IV and Part V conversation. The CPU-bound failure is a volume problem, and volume is what these fixes attack.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-it-really-is-the-load"&gt;When it really is the load
&lt;/h2&gt;&lt;p&gt;Sometimes the workload genuinely needs the cores. A reporting database that runs heavy analytical queries, an ETL window, a system doing real per-row computation that no rollup can precompute because the parameters change every call, will sit at high CPU because that is the job. The tell is in &lt;code&gt;total_exec_time&lt;/code&gt;: when the top of the list is a spread of genuinely heavy statements rather than one trivial query with an enormous call count, you are looking at a workload that wants capacity, and adding cores is the honest answer. The diagnostic distinguishes the two cases; the dropdown &lt;code&gt;COUNT(*)&lt;/code&gt; at the top of the list means volume, a flat distribution of expensive queries means load.&lt;/p&gt;
&lt;p&gt;And the one-day spike can be a legitimate reason to rent. A Super Bowl ad, a product launch, a Black Friday window: a known, bounded surge where the cost of engineering a permanent fix before the date exceeds the cost of a bigger box for 48 hours. Scale up Friday, scale down Monday, fix the &lt;code&gt;COUNT(*)&lt;/code&gt; in the next sprint with the incident graph as the justification. That is renting the bug on purpose, with a return date. The failure is renting it by reflex, with no return date and no ticket, so the bigger box becomes the permanent baseline and the next spike starts the cycle again.&lt;/p&gt;
&lt;p&gt;The dropdown count on the orders page was always going to break. The Super Bowl ad only decided the date. A query that does work proportional to traffic, on a system whose traffic only grows, has a ceiling it will reach; the box size sets the date, and the query sets the slope. Sort by &lt;code&gt;total_exec_time&lt;/code&gt; before you size the instance, and you find out which one you&amp;rsquo;re actually fighting.&lt;/p&gt;</description></item><item><title>The Paradox of the Fast Engineer</title><link>https://explainanalyze.com/p/the-paradox-of-the-fast-engineer/</link><pubDate>Mon, 18 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/the-paradox-of-the-fast-engineer/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post The Paradox of the Fast Engineer" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;The judgment that lets an engineer override a model is built in the slow work the model now offers to do for them. Accept enough of that help on the work that would have built the judgment, and the agent&amp;rsquo;s speed arrives without the quality, security, scalability, maintainability, or operational sense that the slow work used to deposit alongside the code.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Three months after shipping, customers start complaining that menu items are missing from the navigation. The query that builds the menu does three &lt;code&gt;LEFT JOIN&lt;/code&gt;s against a self-referencing &lt;code&gt;categories&lt;/code&gt; table. The agent produced that shape when the engineer described the requirement; review passed because the test fixtures were three levels deep. Production grew to seven. The query was silently truncating subcategories the day it shipped, and the engineer who accepted the output had never reached for a recursive CTE, because nobody on the team had ever shown them one.&lt;/p&gt;
&lt;p&gt;The fix is a recursive CTE with &lt;code&gt;UNION ALL&lt;/code&gt;, anchored on the root row and joining the source table back to itself until no more rows come out. Five lines. Both shapes are valid SQL; the one that holds up against arbitrary depth is the one the engineer reaches for only after seeing it before. Without that prior, the idiom isn&amp;rsquo;t in their decision space. They can&amp;rsquo;t ask the agent for it, and they wouldn&amp;rsquo;t recognize it as the right answer if the agent offered it. No memory of a broken version that lacked it, no internal alarm that &amp;ldquo;three &lt;code&gt;LEFT JOIN&lt;/code&gt;s against a tree&amp;rdquo; is the shape of a future incident.&lt;/p&gt;
&lt;h2 id="the-obvious-fix-isnt-the-fix"&gt;The obvious fix isn&amp;rsquo;t the fix
&lt;/h2&gt;&lt;p&gt;Review the agent&amp;rsquo;s code before approving it. True, and insufficient. The reviewer who has never written a tree walk over a self-referencing table doesn&amp;rsquo;t know what they should be looking for. They see SQL that compiles, returns rows on the test data, and matches the shape of the request. The internal alarm that says &amp;ldquo;this assumes a fixed depth, what happens when the tree is deeper than the joins&amp;rdquo; doesn&amp;rsquo;t come from reading SQL. It comes from writing the broken version yourself, watching it fail in production, and tracing the failure back through your own assumption.&lt;/p&gt;
&lt;p&gt;Code review without that prior pain is pattern matching against the surface of the query. The bugs that ship through review are the ones where the surface looks right.&lt;/p&gt;
&lt;h2 id="the-paradox"&gt;The paradox
&lt;/h2&gt;&lt;p&gt;Here is the paradox. The judgment that lets an engineer override the model is built in the slow work the agent now offers to do for them. The engineer who accepts the output, reviews it briefly, and ships it has gotten the speed. They have not gotten the read on whether the query holds under the production tree shape, the security sense for whether the patch closed the CVE without invalidating something downstream, the scalability instinct for whether the join multiplies under real data, the maintainer&amp;rsquo;s eye for whether this diff just doubled the toil bill six months from now, or the operational feel for which parts of the system are load-bearing and which are decoration. None of those come bundled with the agent&amp;rsquo;s output. The five-minute version of the recursive CTE problem passes through them without depositing anything, the way watching someone debone a chicken on YouTube does not teach you when the knife is sharp enough.&lt;/p&gt;
&lt;p&gt;The pattern shows up in the public data. METR ran a &lt;a class="link" href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/" target="_blank" rel="noopener"
 &gt;controlled study in July 2025&lt;/a&gt; on sixteen experienced open-source developers working in repositories averaging more than a million lines and a decade old. The developers self-reported a 20% speedup from AI assistance. Measured against the control, they were 19% slower. A forty-point gap between what the engineer feels and what the stopwatch records, on a population that does this work for a living.&lt;/p&gt;
&lt;p&gt;Google&amp;rsquo;s &lt;a class="link" href="https://dora.dev/research/2025/dora-report/" target="_blank" rel="noopener"
 &gt;2025 DORA report&lt;/a&gt; found 90% of developers using AI and over 80% reporting it made them more productive, while organizational delivery metrics stayed roughly flat for teams without strong measurement practices. The same report measured bugs per developer up 54% and the median time a pull request spends in review up 441%. The verification work the agent created moved to the reviewer. The reviewer is now the bottleneck the agent isn&amp;rsquo;t helping, and the skill that makes a reviewer fast (the recognition of which agent-generated PR is hiding a fixed-depth assumption, or a missing index, or a quietly invalidated invariant) is the skill the same reviewer is no longer building by writing the slow version themselves.&lt;/p&gt;
&lt;p&gt;Cloudflare&amp;rsquo;s &lt;a class="link" href="https://blog.cloudflare.com/cyber-frontier-models/" target="_blank" rel="noopener"
 &gt;Project Glasswing&lt;/a&gt; write-up lands on the same shape from the security side. When they let a security-focused model write its own patches against live infrastructure code, the fixes &amp;ldquo;fixed the original bug while quietly breaking something else the code depended on.&amp;rdquo; The thing standing between those patches and production was a senior engineer who could read a regression suite and notice when a patch had quietly invalidated a load-bearing assumption. That recognition was built over years of debugging exactly that class of mistake. The model has no way to produce the recognition, and accepting the patch without it means shipping the regression and learning nothing in the process.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;None of this is saying the agent is useless. Its reliable surface is pattern-matching across volume, the way grep is reliably better than reading the whole file when you already know what string you&amp;rsquo;re looking for. Surfacing every place a deprecated API is called across a million-line repo. Pulling the regex syntax you&amp;rsquo;d otherwise have to look up. Flagging the four files in a 200-file diff that touched the auth path. The agent is a faster grep against language, and on that narrow ground it earns its seat. What is being sold and billed for, though, is autonomous production, and the autonomous-production claim does not survive the METR result above. The agent is nowhere near human decision-making, and the cost of treating its output as if it were is exactly the gap between the perceived 20% speedup and the measured 19% slowdown.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-slow-onset-failure"&gt;The slow-onset failure
&lt;/h2&gt;&lt;p&gt;The damage falls hardest on engineers who came up after the tools landed. The current cohort of senior engineers built their judgment in a decade when the slow work was the only available path. Every recursive query was a recursive query they had to figure out. Every migration was one they had to plan. Every 2 a.m. incident was one they had to root-cause without a model offering a first-guess hypothesis (&lt;a class="link" href="https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/" &gt;Alert Triage Without an Agent&lt;/a&gt; goes deeper on that specific muscle). The path that produced today&amp;rsquo;s seniors ran straight through the slow work the agent now does on demand.&lt;/p&gt;
&lt;p&gt;Juniors who let the agent do that work will not arrive at the same place by the same route. Three years of accepting every agent PR, and the engineer who used to be a junior in their codebase is still a junior in their codebase, except now the codebase has grown more complex and the parts they don&amp;rsquo;t understand have grown faster than the parts they do. The gap doesn&amp;rsquo;t show on day one, or month six, or even year two. It shows the first time the agent produces output the engineer cannot evaluate: when the question a senior would ask about a migration is one the junior doesn&amp;rsquo;t know to ask, or when the bug in the agent&amp;rsquo;s PR is invisible to anyone who hasn&amp;rsquo;t written the broken version themselves (see also &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;What AI Gets Wrong About Your Database&lt;/a&gt; for the database-specific shape of this).&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;By the time the gap shows, it has been compounding for years. The engineer is on the wrong side of a hiring market that pays for exactly the recognition they no longer have, and nothing in a quarterly performance review catches the deposit you didn&amp;rsquo;t make to your own long-term memory.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-calibration"&gt;The calibration
&lt;/h2&gt;&lt;p&gt;The skill worth building is knowing which work the agent should do, which work you should do by hand, and which work you should accept from the agent and then rewrite anyway to internalize the pattern.&lt;/p&gt;
&lt;p&gt;The agent is the right tool for work where the context you&amp;rsquo;d gain by doing it yourself is marginal. Boilerplate. Syntax you&amp;rsquo;d otherwise look up. Test scaffolding for code paths you already understand. The migration template you&amp;rsquo;ve written for the tenth time this year. The fifty-line helper that&amp;rsquo;s mechanically obvious once you&amp;rsquo;ve decided what it should do. Let the agent handle these with a brief review and move on.&lt;/p&gt;
&lt;p&gt;The agent is the wrong tool for work where the context is the asset. The parts of the system you don&amp;rsquo;t yet understand. New code paths through a critical module. Database changes whose consequences you&amp;rsquo;d want to feel in your fingers before approving them in production. The first recursive CTE against a tree-shaped table you&amp;rsquo;ve never queried before. The first incident in a class of failures you haven&amp;rsquo;t seen, where the agent&amp;rsquo;s hypothesis is a hypothesis you should also be forming yourself. Do this work by hand, even when the agent would have produced a working diff faster. The slow version is what builds the alarm that catches the agent&amp;rsquo;s mistake the next time the same shape of work shows up.&lt;/p&gt;
&lt;p&gt;The hard part is the middle. Work that&amp;rsquo;s neither pure boilerplate nor entirely novel. Some of it belongs in a tight loop where you drive and the agent assists on syntax. Some gets reviewed line by line as a learning exercise rather than a compliance step. The rest gets rewritten by hand after the agent produces a working version, just to deposit the pattern in your own muscle. The choice turns on whether the work sits in a part of the codebase you need to know deeply or one you can afford to treat as a black box.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The argument cuts cleanest for engineers building depth in a domain they intend to stay in. A platform engineer who needs to know the database. A security engineer building the recognition Cloudflare&amp;rsquo;s example demands. A backend engineer whose career bet is on a specific stack. A frontend engineer whose framework just shipped &lt;a class="link" href="https://vercel.com/changelog/next-js-may-2026-security-release" target="_blank" rel="noopener"
 &gt;thirteen advisories in a coordinated security release&lt;/a&gt; (auth bypass, SSRF, i18n path bypass, an RSC DoS hitting every App Router deployment on 13.x through 16.x) and who needs to read their own dependency graph well enough to know whether they were exposed. For these engineers, the slow work is the investment that pays back over the next decade.&lt;/p&gt;
&lt;p&gt;It cuts less cleanly for work that doesn&amp;rsquo;t depend on depth. The hobbyist exploring a new language. The throwaway script that ships in an afternoon and dies in a week (&lt;a class="link" href="https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/" &gt;The 10x Is Real, on Internal Tools You&amp;rsquo;d Otherwise Never Ship&lt;/a&gt; covers that end of the spectrum). The pre-product-market-fit startup whose entire codebase is throwaway in expected value, where vibe-coding the MVP and finding out if anyone wants the product is the rational trade against the dominant risk of nobody wanting it. The bill on that last case comes if the product wins, in the form of hiring engineers who can read the agent&amp;rsquo;s output and untangle the parts that now have to scale. That is a problem to have.&lt;/p&gt;
&lt;p&gt;It also doesn&amp;rsquo;t apply where the agent&amp;rsquo;s baseline beats what the company can actually hire at its price point. The frontier model is mediocre in absolute terms (METR again), but it is a consistent floor, and not every company can outhire that floor at the salaries they actually pay. In those shops the cheaper path is to let the model produce and have a senior reviewer (often a contractor) clean up after it. The agent there is competitive at the level the company can afford, which sits below senior judgment but above the median hire the budget will permit.&lt;/p&gt;
&lt;p&gt;Senior engineers who already have the context sit outside the trap entirely. The one who has written the recursive CTE a dozen times can accept the agent&amp;rsquo;s first-draft query and review it competently because the alarm is already wired. The asymmetry is that the trap falls hardest on the engineers least equipped to recognize it.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The market for engineering judgment is splitting. Work the model can do at the level of a competent mid-level engineer is being commoditized; work that requires the judgment to recognize when the model is wrong is being concentrated. Which side an engineer ends up on is determined less by the tools they use than by which work they choose to do by hand.&lt;/p&gt;
&lt;p&gt;The senior&amp;rsquo;s value is going up because the volume of model output needing adult supervision grew faster than the supply of adults to supervise it. The junior&amp;rsquo;s floor is the level the model now hits without help. The path from one to the other used to be the slow work, and the path is still the slow work, except the slow work is now optional and most engineers will not opt in.&lt;/p&gt;</description></item><item><title>It's Almost Always the Queries, Part II: Troubleshooting Steps</title><link>https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/</link><pubDate>Sun, 17 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/its-almost-always-the-queries-part-ii-troubleshooting-steps/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post It's Almost Always the Queries, Part II: Troubleshooting Steps" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Database troubleshooting is a learnable skill with a repeatable sequence: observe what&amp;rsquo;s happening now, categorize the wait, narrow to the specific cause, then act. The sequence matters more than the tools. This article walks through it for engineers who don&amp;rsquo;t do this often.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Your APM lights up. Endpoint latency on &lt;code&gt;/api/checkout&lt;/code&gt; has tripled in the last three minutes. The graph shows a wall of slow requests, no deploy in the window, no traffic spike. Something changed in the database layer. You have maybe fifteen minutes before someone senior asks what&amp;rsquo;s happening. What do you actually do?&lt;/p&gt;
&lt;p&gt;If your instinct is to paste the alert into an LLM and ask what to do, pause. The model will give you something that looks like an answer. It might suggest killing the longest-running query, or restarting the connection pool, or adding an index. It pattern-matches on symptoms (duration, state labels, error messages) without access to the causal structure underneath. If you don&amp;rsquo;t understand why it&amp;rsquo;s suggesting what it&amp;rsquo;s suggesting, you can&amp;rsquo;t tell when it&amp;rsquo;s wrong. This applies even if you&amp;rsquo;re running an agent with MCP access to your database (hopefully read-only). The agent can query &lt;code&gt;pg_stat_activity&lt;/code&gt; faster than you can type it, but if you don&amp;rsquo;t understand what the output means and can&amp;rsquo;t evaluate whether the agent&amp;rsquo;s next step is appropriate, you&amp;rsquo;ve handed control of a production incident to something that can&amp;rsquo;t distinguish a victim from a cause. When it&amp;rsquo;s wrong during a live incident, you make things worse. This article builds the mental model that lets you troubleshoot yourself. Use LLMs to learn these concepts on your own time. Don&amp;rsquo;t rely on them at 3am.&lt;/p&gt;
&lt;p&gt;The sequence below is designed to give you understanding before you reach the &amp;ldquo;act&amp;rdquo; step.&lt;/p&gt;
&lt;h2 id="if-you-have-sql-access-to-the-primary"&gt;If you have SQL access to the primary
&lt;/h2&gt;&lt;p&gt;This is the fuller diagnostic path. You can query the system tables directly. What follows assumes you can connect to the primary (or a replica that exposes these views). System tables show what&amp;rsquo;s happening right now; dashboards show what happened over the past hour. Both have a place, and Step 7 covers what to look for in dashboards. Learn whatever monitoring you have before you need it. Figuring out which tab shows wait events at 3am is wasted time.&lt;/p&gt;
&lt;p&gt;The first thing you want to see is the process list, filtered to active queries and ordered by time. On PostgreSQL that&amp;rsquo;s &lt;code&gt;pg_stat_activity&lt;/code&gt;. On MySQL that&amp;rsquo;s &lt;code&gt;SHOW PROCESSLIST&lt;/code&gt; or, better, &lt;code&gt;performance_schema.processlist&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Before you run anything, protect your own session:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LOCAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;statement_timeout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;5s&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL (per-query)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cm"&gt;/*+ MAX_EXECUTION_TIME(5000) */&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Why: if the database is under heavy pressure, your diagnostic query competes for the same resources. A five-second timeout means your debugging doesn&amp;rsquo;t pile onto the problem. If your diagnostic can&amp;rsquo;t finish in five seconds, that itself tells you something (extreme contention, buffer pressure, WAL pressure).&lt;/p&gt;
&lt;p&gt;Now pull the active sessions with the columns that actually help you categorize:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;wait_event_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;wait_event&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_duration&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_duration&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_blocking_pids&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocked_by&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_snippet&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stat_activity&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;idle&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_backend_pid&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NULLS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LAST&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Most diagnostic snippets you&amp;rsquo;ll find online show &lt;code&gt;pid&lt;/code&gt;, &lt;code&gt;query&lt;/code&gt;, &lt;code&gt;state&lt;/code&gt;, and duration. They skip two columns that matter: &lt;code&gt;wait_event_type&lt;/code&gt; and &lt;code&gt;wait_event&lt;/code&gt;. These tell you &lt;em&gt;why&lt;/em&gt; a query is taking long, not just &lt;em&gt;that&lt;/em&gt; it&amp;rsquo;s taking long.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL (use performance_schema, not INFORMATION_SCHEMA)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_STATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_TIME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;duration_sec&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BLOCKING_THREAD_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocked_by_thread&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_INFO&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_snippet&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;threads&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data_lock_waits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;THREAD_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;REQUESTING_THREAD_ID&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_COMMAND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Sleep&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;TYPE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;FOREGROUND&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_TIME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;On MySQL, use &lt;code&gt;performance_schema.threads&lt;/code&gt; or &lt;code&gt;performance_schema.processlist&lt;/code&gt; (8.0.22+), not &lt;code&gt;INFORMATION_SCHEMA.PROCESSLIST&lt;/code&gt;. &lt;a class="link" href="https://bugs.mysql.com/bug.php?id=94077" target="_blank" rel="noopener"
 &gt;MySQL Bug #94077&lt;/a&gt; (January 2019) documented a 70% performance drop from polling &lt;code&gt;INFORMATION_SCHEMA.PROCESSLIST&lt;/code&gt; under load. &lt;a class="link" href="https://bugs.mysql.com/bug.php?id=100049" target="_blank" rel="noopener"
 &gt;Bug #100049&lt;/a&gt; (June 2020) showed the same query causing pending queries to pile up until the server became unresponsive. Both trace to a mutex held during execution. The diagnostic query you run during an incident should not itself become part of the incident.&lt;/div&gt;
&lt;/div&gt;

&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;Worth asking your DBA or platform team to wrap these queries into views (&lt;code&gt;active_queries&lt;/code&gt;, &lt;code&gt;blocking_chains&lt;/code&gt;, &lt;code&gt;long_transactions&lt;/code&gt;) so that during an incident you&amp;rsquo;re running &lt;code&gt;SELECT * FROM active_queries&lt;/code&gt; instead of assembling joins from memory. You don&amp;rsquo;t want to be copy-pasting SQL from a blog post at 3am.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="step-3-look-for-obvious-offenders"&gt;Step 3: Look for obvious offenders
&lt;/h2&gt;&lt;p&gt;Start with the longest-running queries in the output. Some problems are visible from the query snippet alone. A &lt;code&gt;SELECT *&lt;/code&gt; with no WHERE clause on a large table, a function wrapping a column in the predicate (&lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable&lt;/a&gt;), a COUNT(*) over millions of rows, an N+1 pattern showing up as dozens of identical queries with different IDs. If you recognize the shape, you already know what to fix.&lt;/p&gt;
&lt;p&gt;Also look for DDL in the list. An &lt;code&gt;ALTER TABLE&lt;/code&gt;, &lt;code&gt;CREATE INDEX&lt;/code&gt;, or &lt;code&gt;DROP INDEX&lt;/code&gt; that&amp;rsquo;s been running longer than you&amp;rsquo;d expect is usually not doing the work it looks like it&amp;rsquo;s doing. It&amp;rsquo;s waiting on a lock. On MySQL this shows up as a metadata lock (MDL): the DDL waits for every transaction still holding the table open to commit or roll back, and meanwhile every new query against the table queues behind the DDL. On PostgreSQL the equivalent is an &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; lock at the relation level, with the same cascade: the DDL waits on active transactions, and everything else waits on the DDL.&lt;/p&gt;
&lt;p&gt;The non-obvious version is when no heavy query is running but the server is wedged anyway. The trigger is usually something innocuous: a connection pooler holding a session &amp;lsquo;idle in transaction&amp;rsquo;, an analytics job that opened a transaction and never closed it, a long SELECT still holding its &lt;code&gt;ACCESS SHARE&lt;/code&gt; lock, or an autovacuum touching the same table. The DDL blocks on whichever of those it is, then every new query against the table queues behind the DDL. The process list shows a wall of waiting sessions against one table, the DDL at the head of the queue, and the actual root cause somewhere further down (or in a connection that doesn&amp;rsquo;t look problematic at all).&lt;/p&gt;
&lt;p&gt;If nothing jumps out from the query text alone, move to Step 4 and Step 5 to dig deeper into the suspect query. If nothing looks slow at all, skip to Step 6.&lt;/p&gt;
&lt;h2 id="step-4-check-the-schema"&gt;Step 4: Check the schema
&lt;/h2&gt;&lt;p&gt;Once you have a suspect query, look at the table it&amp;rsquo;s hitting. Pull the table definition (&lt;code&gt;\d tablename&lt;/code&gt; in psql, &lt;code&gt;SHOW CREATE TABLE tablename&lt;/code&gt; in MySQL) and compare it against what the query needs.&lt;/p&gt;
&lt;p&gt;Walk the clauses one at a time. WHERE columns need indexes the optimizer can actually use, and &amp;lsquo;usable&amp;rsquo; depends on the predicate shape: equality on a high-cardinality column is the straightforward case, range predicates (&lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;BETWEEN&lt;/code&gt;) work but constrain what can follow them in a composite, and a large &lt;code&gt;IN (...)&lt;/code&gt; list may flip the planner to a sequential scan even when an index exists. JOIN columns need an index on the inner side of the join (the side being looked up once per outer row); in PostgreSQL, foreign-key columns are not indexed automatically, which is a frequent cause of joins that ran fine at low volume and fell over at scale. ORDER BY can sometimes use an index to skip the sort entirely, but only when the index&amp;rsquo;s leading columns line up with the ORDER BY columns. GROUP BY is the same shape: an index on the grouping columns lets the planner stream the aggregation instead of building a hash, which on a multi-million-row table can be the difference between a sub-second query and one that exhausts &lt;code&gt;work_mem&lt;/code&gt; and spills to disk.&lt;/p&gt;
&lt;p&gt;A missing index on a high-cardinality filter column is the single most common cause of queries that worked fine at low volume and fell over at scale. Composite index column order is the runner-up. An index on &lt;code&gt;(status, created_at)&lt;/code&gt; serves &lt;code&gt;WHERE status = 'pending' ORDER BY created_at&lt;/code&gt;. An index on &lt;code&gt;(created_at, status)&lt;/code&gt; does not, even though it contains the same columns. The general rule is equality columns first, then the range column, then columns used only for sort.&lt;/p&gt;
&lt;p&gt;Also check for &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;covering index gaps&lt;/a&gt;: an index that covered the query last month might have stopped covering it after a column was added to the SELECT list, forcing a heap lookup per row where there used to be an index-only scan.&lt;/p&gt;
&lt;h2 id="step-5-read-the-execution-plan"&gt;Step 5: Read the execution plan
&lt;/h2&gt;&lt;p&gt;If the schema looks right and you still can&amp;rsquo;t explain the behavior, ask the database what it&amp;rsquo;s actually doing. &lt;a class="link" href="https://www.postgresql.org/docs/current/sql-explain.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;EXPLAIN&lt;/code&gt;&lt;/a&gt; (PostgreSQL) or &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/explain.html" target="_blank" rel="noopener"
 &gt;&lt;code&gt;EXPLAIN&lt;/code&gt;&lt;/a&gt; (MySQL) shows the planner&amp;rsquo;s chosen strategy without executing the query. &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; executes it and shows actual row counts alongside the estimates. Reading these outputs is the most important skill in query troubleshooting. Every claim about what a query &amp;lsquo;should&amp;rsquo; do is wrong until the plan confirms it; the optimizer might pick a different index than you expect, fall back to a sequential scan because of stale statistics, or choose a join order you&amp;rsquo;d never write by hand. The plan is the ground truth.&lt;/p&gt;
&lt;p&gt;Run this on a replica if you have one. The plan will be the same (assuming similar data and stats), and you avoid adding load to a primary that&amp;rsquo;s already under pressure. If you don&amp;rsquo;t have a replica, plain &lt;code&gt;EXPLAIN&lt;/code&gt; (without ANALYZE) gives you the plan without executing the query. It&amp;rsquo;s an estimate, not a measurement, but it&amp;rsquo;s often enough to spot the problem.&lt;/p&gt;
&lt;p&gt;What to look for in the output: sequential scans on large tables (the planner couldn&amp;rsquo;t find a usable index), rows estimated vs. rows actual diverging by orders of magnitude (stale statistics or a bad cardinality guess), reading a million rows to return ten (missing or ignored index), nested loops where each iteration does its own index lookup against a large table (the N+1 shape at the engine level).&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; executes the query fully. On a SELECT that takes 30 seconds in production, it will take 30 seconds when you run it too. If the query modifies data (INSERT, UPDATE, DELETE), wrap it in a transaction and roll back: &lt;code&gt;BEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;&lt;/code&gt;. On a system already under pressure, be deliberate about what you choose to execute.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="step-6-if-nothing-looks-slow-check-volume"&gt;Step 6: If nothing looks slow, check volume
&lt;/h2&gt;&lt;p&gt;Sometimes every query in the process list finishes in a few milliseconds and nothing looks wrong individually. The problem isn&amp;rsquo;t one slow query. It&amp;rsquo;s thousands of fast ones hitting the same resources concurrently.&lt;/p&gt;
&lt;p&gt;This is where digest-level views help. &lt;code&gt;pg_stat_statements&lt;/code&gt; (PostgreSQL) and &lt;code&gt;performance_schema.events_statements_summary_by_digest&lt;/code&gt; (MySQL) aggregate queries by their normalized pattern and track call counts. Sort by &lt;code&gt;total_exec_time&lt;/code&gt; (PostgreSQL) or &lt;code&gt;SUM_TIMER_WAIT&lt;/code&gt; (MySQL), not by mean time. A query that averages 5 ms but fires 10,000 times per second consumes 50 CPU-seconds per wall-second. It will never show up in a &amp;ldquo;longest running&amp;rdquo; list, but it dominates the workload.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;80&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_snippet&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_exec_time&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_ms&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;total_exec_time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;avg_ms&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stat_statements&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_exec_time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL (join current statements to their digest summary)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DIGEST_TEXT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;80&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_snippet&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;COUNT_STAR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ROUND&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;SUM_TIMER_WAIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="n"&gt;e9&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_ms&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ROUND&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;AVG_TIMER_WAIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="n"&gt;e9&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;avg_ms&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;events_statements_current&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;esc&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;events_statements_summary_by_digest&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;esc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DIGEST&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DIGEST&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;threads&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;esc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;THREAD_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;THREAD_ID&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PROCESSLIST_COMMAND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Sleep&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;SUM_TIMER_WAIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;This is the case from &lt;a class="link" href="https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/" &gt;Part I&lt;/a&gt;, where the &lt;code&gt;COUNT(*)&lt;/code&gt; averaged 40 ms and never triggered the slow-query log. Part III walks the CPU-bound version of this in detail.&lt;/p&gt;
&lt;h2 id="step-7-read-the-dashboards"&gt;Step 7: Read the dashboards
&lt;/h2&gt;&lt;p&gt;Dashboards see what the system tables don&amp;rsquo;t: history. By the time you query &lt;code&gt;pg_stat_activity&lt;/code&gt;, you&amp;rsquo;ve lost the picture of what was happening five minutes ago. Whatever you have (Datadog DBM, Aurora and RDS Performance Insights, pganalyze, Grafana with the right exporters), this is where you bring it in. If you have no SQL access at all, the dashboard is your entire diagnostic toolkit; everything you can learn, you&amp;rsquo;ll learn here.&lt;/p&gt;
&lt;p&gt;Start with timing. A graph with a hard step-change at 14:23 is a different problem from one that climbed slowly over the past hour. The hard step points at a discrete event: a deploy, a config change, a single long-running query that started blocking others. The slow climb points at a workload trend or a plan regression that compounded as the working set grew. Overlay deployment markers, autoscaling events, and scheduled job runs on the latency graph if you can. A latency jump that exactly tracks a deploy is the deploy until proven otherwise.&lt;/p&gt;
&lt;p&gt;Active session count is the other timing graph worth pulling. A flat baseline that doubles at 14:23 points at a blocking event. A slow climb over an hour points at workload growth or queue buildup. Session count is harder to lie to than latency: a single slow query can hide in a p99 average, but it can&amp;rsquo;t hide in the count of sessions waiting on it.&lt;/p&gt;
&lt;p&gt;Which resource is pinned tells you which dimension is the cause and which is following. CPU at 100% with IOPS low and stable is a CPU-bound workload, often a missing index causing repeated sorting or hashing, or a regex or JSON predicate doing per-row work the planner can&amp;rsquo;t push down. IOPS pinned with CPU low and waits on &lt;code&gt;IO:DataFileRead&lt;/code&gt; (PostgreSQL) is a buffer-cache miss problem: the working set has outgrown RAM and every query is going to disk. RAM climbing steadily for days while the buffer cache hit rate falls at the same rate is a forecast, not an incident.&lt;/p&gt;
&lt;p&gt;Waits are where dashboards earn their keep. Aurora Performance Insights, pganalyze, and Datadog DBM all stack active sessions by wait class over time, which is exactly the information &lt;code&gt;pg_stat_activity&lt;/code&gt; can&amp;rsquo;t give you historically. Locks dominating means contention: a deadlock storm, or an open long-running transaction blocking everything that touches the same rows. IO dominating means buffer pressure or storage saturation. CPU dominating means the queries themselves are doing more work per call than they used to. Client reads dominating points at a slow consumer: the app isn&amp;rsquo;t reading results fast enough and sessions stack up waiting to send the next page.&lt;/p&gt;
&lt;p&gt;WAL and checkpoint pressure are easy to miss because they don&amp;rsquo;t appear in the active query list. WAL generation rate climbing with no proportional traffic increase points at write amplification: a runaway UPDATE rewriting the same rows, a hot index getting bloated, a trigger writing more than it needs to. Checkpoint duration climbing, or checkpoint frequency increasing, means the system can&amp;rsquo;t keep pace with the write rate. On MySQL the same signal shows up as InnoDB log file utilization approaching its configured size, with checkpoint-related stalls visible in &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt;. These often correlate with sudden IOPS spikes, because the checkpoint flush is what saturates the disk, not the workload directly.&lt;/p&gt;
&lt;p&gt;Workload composition completes the picture. Most monitoring breaks queries-per-second down by type. A 10x spike in write QPS with read QPS flat is a different incident from a 10x read spike. Within reads, the ratio of index scans to sequential scans is a leading indicator of plan regression: in PostgreSQL, &lt;code&gt;pg_stat_user_tables.seq_scan&lt;/code&gt; climbing on a table that previously got index scans; in MySQL, &lt;code&gt;Handler_read_rnd_next&lt;/code&gt; rising relative to &lt;code&gt;Handler_read_key&lt;/code&gt;. A jump in read-ahead activity (InnoDB&amp;rsquo;s &lt;code&gt;Innodb_buffer_pool_read_ahead&lt;/code&gt;, Aurora&amp;rsquo;s read-IOPS metrics) often signals large scans that weren&amp;rsquo;t there before: a new query, or an old query whose plan changed.&lt;/p&gt;
&lt;p&gt;You&amp;rsquo;re not trying to find the exact query from the dashboard. The goal is to narrow the category before going back to the system tables: read-side vs write-side, query-level vs workload-level, lock contention vs buffer pressure vs CPU saturation. That tells you where to focus in the earlier steps, and if you have no SQL access, it&amp;rsquo;s enough to escalate with specifics. &amp;ldquo;40 sessions in Lock wait starting at 2:43, no deploy in the window, getting worse&amp;rdquo; is something whoever owns the database can act on. &amp;ldquo;It&amp;rsquo;s slow&amp;rdquo; is not.&lt;/p&gt;
&lt;h2 id="before-the-next-incident"&gt;Before the next incident
&lt;/h2&gt;&lt;p&gt;Everything above assumes you can run the queries when you need them, that you know what their output means, and that you&amp;rsquo;ve seen what &amp;rsquo;normal&amp;rsquo; looks like so the abnormal stands out. None of that is true at 3am unless you&amp;rsquo;ve done the work before then.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Know your access.&lt;/strong&gt; Can you connect to the primary, or only to a replica? Read-only or with permission to call &lt;code&gt;pg_terminate_backend&lt;/code&gt;? Does your role have access to &lt;code&gt;pg_stat_statements&lt;/code&gt; (which requires &lt;code&gt;pg_read_all_stats&lt;/code&gt; on PostgreSQL 13+) and to the MySQL &lt;code&gt;performance_schema&lt;/code&gt; tables? On managed services, some catalog views are hidden behind parameter groups that take a restart to enable. The time to discover you don&amp;rsquo;t have &lt;code&gt;pg_stat_statements&lt;/code&gt; is not the moment you need it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Know your team&amp;rsquo;s views.&lt;/strong&gt; Ops teams often wrap the queries from this article into named views: &lt;code&gt;active_queries&lt;/code&gt;, &lt;code&gt;blocking_chains&lt;/code&gt;, &lt;code&gt;long_transactions&lt;/code&gt;, top-N digest views. Find out whether yours exist. If they do, learn the column names and what they filter out (some hide replication workers, autovacuum, or your own session, which can mislead during an incident if you don&amp;rsquo;t know). If they don&amp;rsquo;t, ask your DBA whether they&amp;rsquo;d take a pull request, or write them yourself. A view you can &lt;code&gt;SELECT * FROM&lt;/code&gt; is faster to run and harder to typo at 3am than a 15-line join assembled from memory.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Run the queries on a quiet system.&lt;/strong&gt; Pull &lt;code&gt;pg_stat_activity&lt;/code&gt; against your dev database while nothing stressful is happening. Note what idle connections look like (the pool&amp;rsquo;s keep-alives, your IDE&amp;rsquo;s introspection queries, your monitoring&amp;rsquo;s polling traffic). Pull a &lt;code&gt;pg_stat_statements&lt;/code&gt; snapshot and read through the top 20. The point is to know what your environment looks like at rest, so during an incident the abnormal jumps out instead of getting lost in baseline noise.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Read the column documentation once.&lt;/strong&gt; &lt;code&gt;wait_event_type&lt;/code&gt; and &lt;code&gt;wait_event&lt;/code&gt; in PostgreSQL have &lt;a class="link" href="https://www.postgresql.org/docs/current/monitoring-stats.html#WAIT-EVENT-TABLE" target="_blank" rel="noopener"
 &gt;a documented enumeration&lt;/a&gt; with dozens of values. MySQL&amp;rsquo;s &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/performance-schema-instrument-naming.html" target="_blank" rel="noopener"
 &gt;performance_schema instruments&lt;/a&gt; follow a naming convention you can learn in fifteen minutes. Knowing that &lt;code&gt;IO:DataFileRead&lt;/code&gt; means a buffer cache miss and &lt;code&gt;Lock:transactionid&lt;/code&gt; means waiting on another transaction&amp;rsquo;s row lock turns opaque output into a diagnosis.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Practice reading EXPLAIN output.&lt;/strong&gt; Pull a slow-ish query from your own codebase and run &lt;code&gt;EXPLAIN (ANALYZE, BUFFERS)&lt;/code&gt; on it in a quiet environment. The &amp;lsquo;what to look for&amp;rsquo; in Step 5 is more useful when you&amp;rsquo;ve spent thirty minutes staring at a plan in low-stakes context first. Visualizers like &lt;a class="link" href="https://explain.depesz.com" target="_blank" rel="noopener"
 &gt;explain.depesz.com&lt;/a&gt; and &lt;a class="link" href="https://explain.dalibo.com" target="_blank" rel="noopener"
 &gt;explain.dalibo.com&lt;/a&gt; help with PostgreSQL output, and MySQL&amp;rsquo;s &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/explain.html#explain-tree-output" target="_blank" rel="noopener"
 &gt;tree-format EXPLAIN&lt;/a&gt; is more readable than the default table format. But none of those substitutes for knowing what each node type means. Read the docs for sequential scan, index scan, bitmap heap scan, nested loop, hash join, and merge join once.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;What this article doesn&amp;#39;t cover&lt;/strong&gt;
 &lt;div&gt;None of the seven steps is comprehensive. The full diagnostic surface (lock-graph reconstruction, planner cost-model tuning, statistics histograms, MVCC and vacuum internals, the catalog views nobody talks about) takes years to learn and a book to lay out. What&amp;rsquo;s here is less than the minimum a DBA assumes you already know - enough to triage with confidence and escalate with specifics, not enough to skip the call to whoever owns the database.&lt;/div&gt;
&lt;/div&gt;
</description></item><item><title>It's Almost Always the Queries, Part I: Why Metal Doesn't Help</title><link>https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/</link><pubDate>Sat, 16 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/its-almost-always-the-queries-part-i-why-metal-doesnt-help/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post It's Almost Always the Queries, Part I: Why Metal Doesn't Help" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Infrastructure alerts on a relational database almost always trace to query and schema choices, not capacity. Scaling the box rents the bug. The exceptions are real but smaller than most teams assume.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;What unites replication lag, CPU at 100%, dashboard timeouts, disk filling, and the server that crashes every Tuesday afternoon? Almost always the same thing: bad queries. Throwing metal at it fixes the symptom, leaves the cause, and rents back the same outage at the next traffic threshold.&lt;/p&gt;
&lt;p&gt;A team added a third read replica because the primary was at 95% CPU. Lag got worse, not better. The slow-query log was empty because the threshold was 100 ms and the offending statement averaged 40 ms. &lt;code&gt;pg_stat_statements&lt;/code&gt; sorted by &lt;code&gt;total_exec_time&lt;/code&gt; showed it on the first row: &lt;code&gt;SELECT COUNT(*) FROM orders WHERE status = 'open'&lt;/code&gt;, fired by the status-filter dropdown on the orders page, roughly 600 calls per second at peak. Forty milliseconds becomes 24 CPU-seconds per wall-second the moment a few hundred users land on that page in parallel. The same shape is documented publicly in &lt;a class="link" href="https://github.com/sferik/rails_admin/issues/2699" target="_blank" rel="noopener"
 &gt;Rails Admin issue #2699 from August 2016&lt;/a&gt;, where COUNT(*) on tables with 1-10 million rows ran 10-20 seconds and made the admin dashboard unusable. Part III walks the CPU case in depth; Part II is the troubleshooting playbook that gets you there, and this article is the framing for the whole series.&lt;/p&gt;
&lt;h2 id="the-obvious-fix-and-why-it-buys-you-weeks"&gt;The obvious fix and why it buys you weeks
&lt;/h2&gt;&lt;p&gt;Bigger instance. More replicas. Faster IOPS. Every one of those is a real lever, and on a sufficiently bad day, the right immediate move. They share a property the postmortem usually skips: each rents capacity proportional to the bug&amp;rsquo;s cost, and the bug stays. The 40 ms COUNT(*) costs 60% less on a box twice the size, but the cost is still proportional to traffic, and traffic only goes one direction. Six months later the same team is sizing up the box again, and the dropdown is still firing 600 times a second.&lt;/p&gt;
&lt;p&gt;I know, I know - digging into the query, reading the plan, refactoring the ORM call is engineering time, and engineering time looks more expensive than a bigger instance. On the day of the incident, the math holds. A quarter later it stops holding, when the same dropdown is firing 900 times a second instead of 600 and the bigger box is back at 95%. You are going to deal with it. The only question is whether you spend one SME hour now, or whether you keep paying the surcharge that grows with traffic and end up spending more time on it over the year than the tuning would have cost in the first place.&lt;/p&gt;
&lt;h2 id="four-symptoms-one-cause"&gt;Four symptoms, one cause
&lt;/h2&gt;&lt;p&gt;Almost every infrastructure alert on a relational database has a hardware-shaped reading and a query-shaped reading. The query-shaped reading is right more often. The four symptoms below each get their own post in this series; what follows is the map, not the territory.&lt;/p&gt;
&lt;p&gt;CPU pegged at 100% usually means an aggregate or lookup that runs cheaply per call and fires under heavy concurrency: a dashboard &lt;code&gt;COUNT(*)&lt;/code&gt;, an unread-count badge that re-renders on every page load, an &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;N+1 from the ORM&lt;/a&gt; inside a list view that nobody noticed. Sort &lt;code&gt;pg_stat_statements&lt;/code&gt; by &lt;code&gt;total_exec_time&lt;/code&gt;, not &lt;code&gt;mean_exec_time&lt;/code&gt;, and the offender is on the first page. MySQL&amp;rsquo;s equivalent is &lt;code&gt;performance_schema.events_statements_summary_by_digest&lt;/code&gt; ordered by &lt;code&gt;SUM_TIMER_WAIT&lt;/code&gt;; same trick, different schema. &lt;strong&gt;Part III.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Memory pressure is rarely a workload that needs more RAM. More often it&amp;rsquo;s &lt;code&gt;work_mem&lt;/code&gt; multiplied by connection count: each sort or hash spilling its allocation, multiplied by a few hundred Rails workers, blows past whatever the instance has. The MySQL shape is the same with per-thread buffers (&lt;code&gt;sort_buffer_size&lt;/code&gt;, &lt;code&gt;join_buffer_size&lt;/code&gt;, &lt;code&gt;tmp_table_size&lt;/code&gt;) multiplied by &lt;code&gt;max_connections&lt;/code&gt;. Bigger box, same multiplier, same alert. &lt;strong&gt;Part IV.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Disk filling and IOPS saturation usually mean bloat (no-op UPDATEs producing dead tuples faster than autovacuum cleans them), audit tables without retention, or &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable predicates&lt;/a&gt; and &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;coverage that broke when a column got added to the SELECT&lt;/a&gt;, forcing random heap fetches that look like an IOPS shortfall. InnoDB has the same shape with undo-log growth under long-running transactions starving purge, and with random reads from non-clustered secondary indexes that force a clustered-index lookup per row. Provisioning more IOPS works, and leaves the access pattern intact. &lt;strong&gt;Part V.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Replication lag presents as a replica problem and is almost always a writer problem. Long transactions hold back replay. Over-indexed tables under heavy UPDATE traffic produce write amplification; the same WAL stream replays single-threaded on every replica. ORMs that re-write every column on every save produce no-op WAL records that every replica then applies. MySQL has the same pattern through the binlog, with one SQL thread per replica by default; parallel replication helps on independent workloads but rarely closes the gap on write-heavy ones with intra-transaction dependencies. &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/" &gt;Long-held locks blocking unrelated work&lt;/a&gt; compound the same way. Adding replicas makes it worse, not better. &lt;strong&gt;Part VI.&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id="read-the-top-10-before-opening-the-cloud-console"&gt;Read the top-10 before opening the cloud console
&lt;/h2&gt;&lt;p&gt;The discipline is mechanical. Before touching the instance type, the replica count, or the IOPS budget, pull the top-10 from &lt;code&gt;pg_stat_statements&lt;/code&gt; sorted by &lt;code&gt;total_exec_time&lt;/code&gt; and diff against last week. If the offender is new (a recently shipped feature, a new dashboard tile, an admin tool someone built last quarter) the fix is at that callsite. If the offender has been there the whole time and is only now problematic, traffic crossed a threshold the query couldn&amp;rsquo;t hold. Either way, the action is at the query, not the box.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The trade-off this advice doesn&amp;#39;t fix&lt;/strong&gt;
 &lt;div&gt;&lt;p&gt;Query tuning is cheap in dollars and expensive in SME hours. A team without a database specialist and with a deadline in two weeks does not have the headcount to read an execution plan, refactor an ORM call, and verify the fix under load. For that team, scaling the box is the right move, and the bug stays on the backlog as planned debt. The article&amp;rsquo;s framing assumes you have, or are willing to develop, the skill to read &lt;code&gt;pg_stat_statements&lt;/code&gt; and &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; output. Without that skill, capacity is what you can buy; query understanding is what you can&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;Asking Claude or another LLM is a real option for narrow questions (&amp;ldquo;what does this &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; mean?&amp;rdquo;, &amp;ldquo;is this index doing what I think?&amp;rdquo;) and worth using as a first pass. It hallucinates more on architecture than on syntax, and the only thing standing between that and a worse outage is whether someone on your team can read what it produced and tell when it&amp;rsquo;s wrong.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;In an early-stage startup where four engineers are doing four jobs each and the storage layer is one of fifteen things on someone&amp;rsquo;s plate, reading &lt;code&gt;pg_stat_statements&lt;/code&gt; weekly is not where the next dollar of engineering time goes. Scale the box. The cloud upsell exists for a reason, and at that stage the bug stays on the backlog as planned debt while the team finds product-market fit. The trade-off is honest as long as someone knows the debt is there.&lt;/p&gt;
&lt;p&gt;The version of this that hurts later is a data-heavy company building without anyone who owns the storage layer. If the product is fundamentally about reading and writing data (OLTP-heavy SaaS, analytics-adjacent dashboards, event ingestion at volume, anything that touches embeddings or vector search), the schema and access patterns chosen in the first six months decide what is available to build on for the next three years. Without an SME on the foundation, the team ships a model the workload can&amp;rsquo;t actually run, and the same query-shaped failures arrive on a much shorter timeline than the founders planned for. The cheap version of doing this right is hiring or contracting someone who has seen this fail before, before the schema is hardened by code that depends on it.&lt;/p&gt;
&lt;h2 id="what-the-next-five-parts-cover"&gt;What the next five parts cover
&lt;/h2&gt;&lt;p&gt;Part II is the troubleshooting playbook: what to open first when an alert fires, the built-in views worth knowing (&lt;code&gt;pg_stat_activity&lt;/code&gt;, &lt;code&gt;pg_stat_statements&lt;/code&gt;, &lt;code&gt;pg_locks&lt;/code&gt; on Postgres; &lt;code&gt;performance_schema.threads&lt;/code&gt;, &lt;code&gt;data_locks&lt;/code&gt;, &lt;code&gt;events_statements_summary_by_digest&lt;/code&gt; on MySQL), the handful of custom views worth saving for the next incident, and when a third-party tool like pganalyze, PMM, or Datadog DBM earns its cost. Part III takes the CPU case in detail: why sorting by &lt;code&gt;total_exec_time&lt;/code&gt; finds the offender that &lt;code&gt;mean_exec_time&lt;/code&gt; hides, and how MVCC visibility makes unbounded &lt;code&gt;COUNT(*)&lt;/code&gt; the canonical example. Part IV is memory pressure and &lt;code&gt;work_mem&lt;/code&gt; math. Part V is disk and IOPS: bloat, retention, fillfactor, the access patterns that look like a storage shortfall. Part VI is replication lag, where the fix is always on the writer. Each post stands on its own; reading them in order makes the pattern visible.&lt;/p&gt;</description></item><item><title>Exposing Data to an Agent: MCP vs API</title><link>https://explainanalyze.com/p/exposing-data-to-an-agent-mcp-vs-api/</link><pubDate>Fri, 15 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/exposing-data-to-an-agent-mcp-vs-api/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Exposing Data to an Agent: MCP vs API" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;MCP is a wire protocol; what sits behind it decides the blast radius. In non-prod, pointing it at the database tends to be fine, because unbounded exploration is worth more than the occasional mistake. In prod, the shape that holds up is having the MCP server&amp;rsquo;s tools call an agent-specific API that enforces allowlisted operations, row caps, column masking, and per-prompt audit, rather than the database directly. The version that points at the database tends to surface later as a privacy incident.&lt;/div&gt;
&lt;/div&gt;

&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;This is about the third-party database MCP servers from public registries (Postgres, MySQL, MongoDB, Redis, Elasticsearch), whose load-bearing tool is &lt;code&gt;query(sql_string)&lt;/code&gt; against whatever connection they were configured with. A custom MCP server you wrote to wrap your own API is a different shape and isn&amp;rsquo;t the argument here.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A revenue dashboard agent runs against production through the MCP server the analytics team stood up last quarter. Marketing asks for enterprise signups in Q1 with their account contacts. The agent generates &lt;code&gt;SELECT id, email, phone, last_login_at, plan, mrr FROM users JOIN subscriptions ... WHERE created_at &amp;gt;= '2026-01-01' AND plan = 'enterprise'&lt;/code&gt;, and 2.3M rows come back. The agent truncates the chat-side display to the first fifty. The full result set leaves the database, crosses the MCP server, and lands in the conversation history the model provider keeps for thirty days. The connection that ran the SELECT held a slot on the read replica for fourteen minutes before the proxy reaped it, and p99 read latency for the customer-facing dashboard tripled over that window. The audit log records one MCP call from &lt;code&gt;mcp-readonly@analytics&lt;/code&gt;. No prompt, no agent identity, no user attribution. The post-mortem has six unanswered questions.&lt;/p&gt;
&lt;h2 id="read-only-doesnt-bound-any-of-this"&gt;Read-only doesn&amp;rsquo;t bound any of this
&lt;/h2&gt;&lt;p&gt;The patch the post-mortem will land on in fifteen minutes is &amp;ldquo;make the MCP connection read-only.&amp;rdquo; The connection already was. Read-only restricts the verb set, and every failure above happened on &lt;code&gt;SELECT&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;A read-only SELECT against a 50M-row table is still a SELECT, with the same cost on the replica. Read access on &lt;code&gt;users&lt;/code&gt; is read access on &lt;code&gt;users.password_hash&lt;/code&gt; and &lt;code&gt;users.api_token&lt;/code&gt;. The corruption floor that &lt;a class="link" href="https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/" &gt;If Your Guardrail Is a Prompt&lt;/a&gt; describes eventually emits a query against a table the agent had no business touching, and read-only lets it through. And every row the agent reads becomes part of the context window the model provider keeps for thirty days, regardless of what your privacy policy says.&lt;/p&gt;
&lt;p&gt;The verb was never the surface. The catalog is.&lt;/p&gt;
&lt;h2 id="mcp-is-the-wire-the-endpoint-is-the-policy"&gt;MCP is the wire, the endpoint is the policy
&lt;/h2&gt;&lt;p&gt;MCP is a tool-surface protocol. The standard database MCP server exposes &lt;code&gt;query(sql_string)&lt;/code&gt;: the model writes SQL, the server forwards it to whatever connection it was configured with. That makes the MCP server a conduit between the model and the catalog. The agent&amp;rsquo;s effective permissions are the connection&amp;rsquo;s, the agent&amp;rsquo;s query surface is every SQL statement the connection can run, and the audit trail is one row per call from one identity with the SQL as the only payload, which &lt;a class="link" href="https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/" &gt;a pre-AI audit log treated as sufficient and an AI-era audit log doesn&amp;rsquo;t&lt;/a&gt;.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;The protocol isn&amp;rsquo;t the problem. MCP solves a real coordination problem: how a model discovers and calls tools across hosts, harnesses, and vendors. What you put on the other end is the part that decides whether you&amp;rsquo;ve exposed a database or an API.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A SQL conduit also makes the silent-failure shapes from &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;What AI Gets Wrong About Your Database&lt;/a&gt; reachable from a chat window: JOIN paths against tables the model inferred from names, &lt;code&gt;status = 1&lt;/code&gt; filters where &lt;code&gt;1&lt;/code&gt; means &amp;ldquo;pending&amp;rdquo; not &amp;ldquo;active&amp;rdquo;, unconstrained bridge tables that multiply rows. None of it requires write access, and all of it lands in the model provider&amp;rsquo;s trace.&lt;/p&gt;
&lt;p&gt;The thing you want on the other end of MCP is an API. Not your customer-facing API. An API written for the agent: a list of operations it can call, with parameters, shaped responses, per-operation entitlements, row caps, timeouts, column masking, and an audit trail that records the agent identity and the prompt that produced the call. The agent never composes SQL. It calls &lt;code&gt;get_enterprise_signups(quarter, plan)&lt;/code&gt; and gets back an aggregated result.&lt;/p&gt;
&lt;h2 id="what-the-agent-api-looks-like"&gt;What the agent API looks like
&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;Named operations, not raw SQL.&lt;/strong&gt; &lt;code&gt;get_revenue_by_segment(quarter, segment)&lt;/code&gt;, &lt;code&gt;list_active_enterprise_accounts(limit, cursor)&lt;/code&gt;, &lt;code&gt;get_customer_summary(customer_id)&lt;/code&gt;. The agent picks from a menu the platform team curated. Operations get added when an analysis pattern proves useful enough to commit to a stable interface.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Responses shaped for the agent, not for the application.&lt;/strong&gt; A revenue-by-segment call returns aggregated totals, not the 2.3M rows behind them. The shape is token-budget aware: a top-N list with totals beats a paged row dump.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column-level masking inside the API.&lt;/strong&gt; Email becomes a domain plus a hash. Account IDs are opaque tokens the API resolves on the next call, not database primary keys. Sensitive columns are gated by per-operation entitlements granted explicitly to the agent identity.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Row caps and statement timeouts the API enforces.&lt;/strong&gt; Every operation has a hard cap on rows and database time. Caps live in code the API team owns, not in the prompt. If an operation needs higher caps, the cap is raised for that operation, not the connection.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Per-call audit with prompt provenance.&lt;/strong&gt; Every call records the agent identity, upstream user, operation, parameters, response shape, row counts, latency, and the prompt that produced the call. Six months later, &amp;ldquo;who ran the query that leaked the enterprise customer list&amp;rdquo; is two &lt;code&gt;SELECT&lt;/code&gt;s away.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Per-agent rate limits.&lt;/strong&gt; Agents loop. Agents retry. The API budgets calls per identity, per operation, and per database time. The budget is a backstop on cost, on the replica, and on the model provider&amp;rsquo;s trace volume.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Don&amp;rsquo;t reuse your customer-facing API for this. Your customer API is shaped for an authenticated user reading their own data. The agent API is shaped for a service account reading across users, returning aggregates rather than rows, masking PII by default, and logging every call against a prompt. Two consumers, two contracts. One API that tries to serve both ends up either too permissive for customers or too restrictive for agents.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The MCP server&amp;rsquo;s tools then become thin wrappers over the API. Each MCP tool corresponds to one API operation. The agent sees &lt;code&gt;get_revenue_by_segment&lt;/code&gt; as a tool; under the hood it&amp;rsquo;s an HTTP call to a service that talks to the database with its own pool, its own identity, and its own rules. The model never speaks SQL to anything.&lt;/p&gt;
&lt;h2 id="what-you-get-for-the-work"&gt;What you get for the work
&lt;/h2&gt;&lt;p&gt;Control over what&amp;rsquo;s exposed, including the catalog. The API is the curated surface; what isn&amp;rsquo;t on the surface isn&amp;rsquo;t reachable. PII is masked or omitted by default, sensitive tables don&amp;rsquo;t have an operation, and the system catalog (&lt;code&gt;information_schema&lt;/code&gt;, &lt;code&gt;pg_catalog&lt;/code&gt;, MongoDB&amp;rsquo;s &lt;code&gt;listCollections&lt;/code&gt;) never reaches the agent. Hide the catalog and you hide the menu of mistakes the model can make. The same surface-narrowing pays a partial dividend on prompt injection: an instruction smuggled into a document the agent reads has no &lt;code&gt;query(sql)&lt;/code&gt; tool to hijack, only the operations on the menu.&lt;/p&gt;
&lt;p&gt;Observability. Who called, when, with what parameters, against what prompt, returning what row counts. You can see which agents are over-fetching, which operations are getting hammered, which prompts produce weird call patterns. Patterns drive the next iteration: the operation called twenty times an hour gets cached, the one that always returns a million rows gets a tighter cap.&lt;/p&gt;
&lt;p&gt;Throttling in a layer the database doesn&amp;rsquo;t reach. Per-agent, per-operation, per-minute, with hard backpressure during a customer-facing incident. This matters most when the agent is pointed at a primary: it shares a connection pool and CPU budget with the customer-facing write path, and a runaway loop or deep aggregation can move primary CPU enough to slow checkout. Statement timeouts on the database alone don&amp;rsquo;t help, because most of the damage lands in the first ten seconds. The API can apply the throttle at the call boundary, before the SQL reaches the connection: per-agent QPS caps, per-operation concurrency limits, a circuit breaker on customer-facing latency.&lt;/p&gt;
&lt;h2 id="where-mcp-direct-still-earns-its-keep"&gt;Where MCP-direct still earns its keep
&lt;/h2&gt;&lt;p&gt;Local development against a seeded test database. Nightly-refreshed sanitized snapshots of production with PII stripped. CI integration tests against ephemeral databases built from fixtures. Single-operator setups where the agent&amp;rsquo;s permissions are explicitly the operator&amp;rsquo;s. In all four, the cost of a mistake is bounded, and the loop of asking any question and throwing the answer away is the point of the environment. Patterns that prove useful in dev or snapshots get promoted to operations on the prod API; the rest stay in dev.&lt;/p&gt;
&lt;p&gt;The dividing line is who pays the cost of a mistake. If it&amp;rsquo;s the same person running the agent, MCP-direct is fine. If it&amp;rsquo;s a customer whose contact list just got absorbed into a model provider&amp;rsquo;s training-eligible context buffer, MCP through the API. A two-engineer team with one agent and one use case can defer the API, but they&amp;rsquo;ll feel the cost the first time a second agent shows up or the first time a privacy review asks where customer data has been read from.&lt;/p&gt;
&lt;h2 id="if-mcp-direct-harden-the-database-side"&gt;If MCP-direct, harden the database side
&lt;/h2&gt;&lt;p&gt;When the team picks MCP-direct in prod anyway, the database layer has knobs worth turning on. None substitute for an API. All are cheap.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A dedicated database user for the MCP connection.&lt;/strong&gt; Not the analytics role, not an existing service account, not anything with grants accumulated over years. The agent&amp;rsquo;s user gets its own grants and an audit-log identity that names a single purpose.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Per-schema and per-table grants.&lt;/strong&gt; PostgreSQL&amp;rsquo;s &lt;code&gt;REVOKE ALL ON SCHEMA ... FROM PUBLIC&lt;/code&gt; is the underused default. The agent&amp;rsquo;s role gets read on a small set of schemas (often a dedicated &lt;code&gt;analytics&lt;/code&gt; schema of shaped views), with explicit denies on schemas holding credentials, secrets, audit logs, and the system catalog.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Column-level masking via views or row-level security.&lt;/strong&gt; A view over &lt;code&gt;users&lt;/code&gt; that hashes email and omits &lt;code&gt;password_hash&lt;/code&gt;, &lt;code&gt;api_token&lt;/code&gt;, and &lt;code&gt;phone&lt;/code&gt; closes most PII exfiltration in five minutes. RLS policies on tenant-scoped tables enforce a single-tenant read by default.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Aggressive statement timeouts and connection caps.&lt;/strong&gt; &lt;code&gt;statement_timeout&lt;/code&gt; and &lt;code&gt;idle_in_transaction_session_timeout&lt;/code&gt; set per role at five or ten seconds kill runaway aggregations before they touch replica CPU. Connection caps via PgBouncer prevent the agent from monopolizing the pool during a retry storm.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The pattern is the one every public-facing system already settled into a decade ago: you don&amp;rsquo;t expose the database to the internet, you put an API in front. The agent is a new principal that deserves the same treatment. MCP is the transport, the way HTTP is the transport for your frontend. Transports don&amp;rsquo;t make policy. Pointing MCP at a database makes the database the endpoint, and the database has no concept of an agent identity, a prompt, or a column-level mask for a non-human caller.&lt;/p&gt;
&lt;p&gt;Building the agent API is the ideal case of an &lt;a class="link" href="https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/" &gt;internal tool an AI agent can write quickly&lt;/a&gt;: greenfield code, one team owning the contract, low blast radius, replaceable v1, sandbox available for the first cut. A day or two with a coding agent rather than the quarter-long platform initiative it would have been in 2022. It&amp;rsquo;s testable, observable, and the thing that lets you point MCP at production without filing a privacy incident the following Tuesday.&lt;/p&gt;</description></item><item><title>The 10x Is Real, on Internal Tools You'd Otherwise Never Ship</title><link>https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/</link><pubDate>Wed, 13 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/the-10x-is-real-on-internal-tools-youd-otherwise-never-ship/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post The 10x Is Real, on Internal Tools You'd Otherwise Never Ship" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;AI coding agents do hit 10x or better on a specific slice of work: greenfield internal tools where the agent authors the code and the conventions it later re-reads. Outside that envelope (existing services, cross-team consumers, regulated code paths) the gain compresses to 10–30% at best and turns net negative on mature codebases, because verification cost dominates typing cost.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A DBRE has had a MySQL binlog purge script in the back of their head for six months. Current process: every other Friday, run &lt;code&gt;SHOW REPLICA STATUS&lt;/code&gt; against each replica to find the oldest binlog any of them is still reading from, take the minimum source-log-file across the fleet, factor in any replica that is lagging, then connect to the primary and run &lt;code&gt;mysql -e &amp;quot;PURGE BINARY LOGS TO 'mysql-bin.XXXXXX'&amp;quot;&lt;/code&gt; with a safe cutoff. By hand, in a notebook, while making sure no replica is far enough behind that the cutoff would yank a binlog the replica still needs and break replication. Pre-AI estimate to script it properly: half a day, with the replica-position scan across the fleet, the safe-cutoff math, a dry-run mode, and the README so the next on-call knows what it does. Never made the sprint. Friday afternoon with a coding agent: a small Go binary that walks each replica, parses &lt;code&gt;SHOW REPLICA STATUS&lt;/code&gt;, computes the minimum source-log-file with a configurable safety margin, refuses to act if any replica is more than 30 seconds behind, runs &lt;code&gt;PURGE BINARY LOGS TO&lt;/code&gt; on the primary, supports &lt;code&gt;--dry-run&lt;/code&gt;, emits structured logs, ships with a README the agent wrote in the same pass, and has a one-shot CI job that exercises it against a sandbox primary plus replica. Forty minutes including the test. Ships Monday. The twenty minutes a week of toil it removes is the kind of work that has never made anyone&amp;rsquo;s quarterly goals.&lt;/p&gt;
&lt;h2 id="where-the-multiplier-comes-from"&gt;Where the multiplier comes from
&lt;/h2&gt;&lt;p&gt;&amp;ldquo;AI is faster everywhere now&amp;rdquo; is the reflexive read of the scenario above, and it&amp;rsquo;s the wrong read. The same agent on the customer-facing payments service, modifying a checkout flow three years old with four other teams reading the code, lands at 10–20% faster on a good day and net negative on a bad one. The numbers in the literature back this up.&lt;/p&gt;
&lt;p&gt;Stanford&amp;rsquo;s &lt;a class="link" href="https://softwareengineeringproductivity.stanford.edu/" target="_blank" rel="noopener"
 &gt;Software Engineering Productivity research&lt;/a&gt; on a corpus of more than 100,000 developers found AI gains of roughly 30 to 35 percent on low-complexity greenfield tasks, 10 to 15 percent on high-complexity greenfield, and brownfield work compressing further from there. Google&amp;rsquo;s &lt;a class="link" href="https://dora.dev/dora-report-2025/" target="_blank" rel="noopener"
 &gt;2025 DORA State of AI-Assisted Software Development report&lt;/a&gt; found 90% of developers using AI and over 80% reporting it made them more productive, while organizational software delivery metrics stayed flat. Individual perceived productivity is not translating into faster delivery to customers. DORA&amp;rsquo;s authors describe AI as an amplifier of existing engineering capability and flag a negative relationship between AI adoption and software delivery stability, with 30% of developers reporting little or no trust in the code AI generates. The verification tax is real: time saved on creation is getting spent on audit.&lt;/p&gt;
&lt;p&gt;METR&amp;rsquo;s &lt;a class="link" href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/" target="_blank" rel="noopener"
 &gt;July 2025 controlled study&lt;/a&gt; on sixteen experienced open-source developers in repositories averaging a million-plus lines of code and a decade old found something stranger. The developers were 19% slower with AI than without, and they thought they were 20% faster. Mature codebases are an antagonistic environment for an agent and a confusing one for the human paired with it.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;AI&amp;rdquo; by itself doesn&amp;rsquo;t earn the 10x. Four other conditions have to stack on top of it: greenfield, AI-authored conventions, small audience, fast feedback. Remove one and the math compresses to single-digit percentages. Remove two and the agent is net negative.&lt;/p&gt;
&lt;h2 id="greenfield-is-cheap-context"&gt;Greenfield is cheap context
&lt;/h2&gt;&lt;p&gt;An existing codebase has conventions the agent has to infer from reading. The error-handling pattern, the test-fixture convention, the logger wrapper everyone uses, the half-deprecated config layer the new code is supposed to use instead. Some of this is written down in a CONTRIBUTING file from 2022 that is now wrong in two places. Most of it lives in tribal knowledge. The agent reads twelve files and guesses, sometimes wrongly, and the engineer&amp;rsquo;s time goes into correcting the guess. The context tax is real and it doesn&amp;rsquo;t show up on any productivity dashboard.&lt;/p&gt;
&lt;p&gt;Greenfield collapses that tax to zero. The agent writes the first file and decides the convention, because there is no prior convention to defer to. Error handling is whatever the first handler returned. Logging is whatever the agent picked in the first module. The pattern propagates forward because the agent is reading its own work on every subsequent call. The convention isn&amp;rsquo;t reliable in the LLM sense (nothing the model does is reliable), but the distribution narrows considerably when the only style the agent has seen in this repo is the style it wrote yesterday. Less to hallucinate about. Fewer plausible alternatives competing for the next token.&lt;/p&gt;
&lt;h2 id="the-agent-reads-its-own-code-and-stays-in-pattern"&gt;The agent reads its own code and stays in pattern
&lt;/h2&gt;&lt;p&gt;The cleaner version of this story is that the agent authors both the code and the docs and re-reads its own docs on the next session, so everything stays coherent. That&amp;rsquo;s wishful. Agents leave READMEs stale routinely. A session edits the code, claims success, and silently leaves the documentation pointing at a function signature that&amp;rsquo;s been renamed since. Pretending otherwise is the same &amp;ldquo;AI is reliable now&amp;rdquo; framing that fails the moment someone trusts it.&lt;/p&gt;
&lt;p&gt;The real driver is smaller and more mechanical. On a small greenfield repo, the agent&amp;rsquo;s first move on a new session is usually to scan the files that are already there. The code it reads is code the agent wrote last week. The patterns it produces in this session mirror what it finds in the existing files, because the model is doing what models do: sampling tokens that match the recent style it&amp;rsquo;s already seen in the context. Error handling looks the same in module five as it did in module one because the agent read module one before writing module five. Logging conventions, naming, test layout: all of it propagates from re-reading the code, not from a doc the agent has any particular discipline about.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Treat any AI-authored README as a build artifact, not a maintained source of truth. Agents skip README updates routinely, and a stale doc is worse than no doc because the next session will follow the wrong instruction confidently. If docs are sticking around, regenerate them rather than maintain them, and don&amp;rsquo;t trust any README older than the most recent code change. The code is the source of truth. The moment the tool grows to where re-reading the code on each session stops being cheap, it has graduated out of this regime and needs the discipline of any other production system.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The shape of the speedup is the same as why a single author writes a coherent short piece faster than three co-authors with the same word count. Coordination overhead is the multiplier, not raw output speed. In a human team, coordination is meetings, code review, RFC documents, the slow accumulation of shared style. In a single-agent greenfield repo, coordination is one session re-reading the small artifact it wrote yesterday and matching the patterns it finds. The cost of &amp;ldquo;what&amp;rsquo;s our convention here&amp;rdquo; is the cost of one repo scan.&lt;/p&gt;
&lt;h2 id="small-audience-fast-deploy-throwaway"&gt;Small audience, fast deploy, throwaway
&lt;/h2&gt;&lt;p&gt;The MySQL binlog organizer is used by one team. The AZ backup shipper is used by the storage on-call. The diagnostic API in front of Redis is curl&amp;rsquo;d by whoever is debugging tonight. None of these tools have customer SLOs, escalation paths, or a third-party integration to coordinate. v1 broken on Monday is fixed by Tuesday afternoon. The cost of a bug is bounded by how loudly someone says &amp;ldquo;this broke&amp;rdquo; in Slack.&lt;/p&gt;
&lt;p&gt;Fast feedback is what makes the testing strategy work. A &lt;code&gt;--dry-run&lt;/code&gt; flag and a sandbox replica is sufficient verification for the binlog purge script, because the worst case is the script crashes and the on-call reverts to the manual &lt;code&gt;find&lt;/code&gt; command, which is what they were already doing. There&amp;rsquo;s no need for a 2000-row test suite. There&amp;rsquo;s barely a need for a runbook. The tool exists in the negative space between &amp;ldquo;the manual process&amp;rdquo; and &amp;ldquo;a properly engineered service&amp;rdquo; and both ends of that range are operationally fine.&lt;/p&gt;
&lt;p&gt;And the tools are throwaway. If the binlog organizer turns out to be shaped wrong (the team wanted archival, the agent built categorization, the bucketing scheme is awkward) it gets thrown out and rewritten from scratch. Sunk cost is hours, not weeks. The agent doesn&amp;rsquo;t carry the same emotional attachment to the previous version&amp;rsquo;s design that a human author would, which makes the rewrite cheaper than the original. That&amp;rsquo;s the property that lets a platform team take more shots than they otherwise would. Most of the toil-removal scripts that sit in the backlog die there because the expected effort feels higher than the expected payoff. The 10x reframes the expected effort, and a noticeable chunk of the backlog suddenly clears its own bar.&lt;/p&gt;
&lt;p&gt;The rewrite property has a second face: the replacement is often an upgrade, not just a regeneration. Most platform teams have the internal HTML dashboard from 2012 nobody wants to touch. Bootstrap, jQuery, server-rendered templates, no input validation on any of the forms, no real documentation, and one engineer left who remembers which buttons do what. Pre-AI estimate to modernize: a quarter that nobody schedules. Friday afternoon with a coding agent: a React frontend with form validation built in, a typed backend behind it, a README that documents what the endpoints actually do, and the input-validation gap that has been a low-grade footgun for three years closed by default, because the new stack treats validation as table stakes. The rewrite is cheaper than the original and an upgrade at the same time, because the agent is writing in a stack that already has the properties the old code lacked.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;The other property internal-only buys you: v2 ships side by side with v1. Both links go on the wiki, the team tries the new one in real work for a week, parity gets confirmed against the old one for the handful of operations anyone actually uses, and v1 gets deleted when nobody opens it anymore. No cutover plan, no customer comms, no parallel-infrastructure cost worth pricing. The team migrates itself. Try this rollout shape with a customer-facing service and the conversation goes very differently.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="how-to-operationalize-this-without-standardizing-it-to-death"&gt;How to operationalize this without standardizing it to death
&lt;/h2&gt;&lt;p&gt;The temptation, as soon as the team notices the multiplier, is to standardize. Pick a Go scaffolding template, pick a logging library, mandate a directory layout, route everything through the platform team for review. Resist that. The standardization is where the multiplier collapses, because the moment two teams have to negotiate conventions, the agent is back in coordination-cost territory.&lt;/p&gt;
&lt;p&gt;A workable shape: every team picks two or three toil-removers from their own backlog and commits to shipping them this quarter. Each tool is owned by one team. Code review is one teammate, same-day, with the explicit understanding that the review is checking the tool does what the README says and doesn&amp;rsquo;t delete prod data, not enforcing a corporate style guide. Testing is on a sandbox or staging instance, not in CI for two weeks. A Backstage plugin backend that surfaces deploy status for the storage team&amp;rsquo;s services lives in the storage team&amp;rsquo;s repo, with the storage team&amp;rsquo;s conventions, and gets reused by other teams only if the other teams want to depend on it (and accept the version it ships in).&lt;/p&gt;
&lt;p&gt;The honest trade-off: tools built this way are good enough for one team and not good enough for the platform catalog. Some will need rewriting if they cross teams. That&amp;rsquo;s fine. The cost of rewriting is hours, and most of them will never cross teams anyway. The cost of insisting on cross-team-grade quality up front is that the diagnostic API the network team would have shipped in a Friday afternoon turns into a Q3 platform initiative, then a Q4 platform initiative, then nothing.&lt;/p&gt;
&lt;p&gt;The same multiplier extends past engineering. Marketing wants to bulk-edit campaign tags. Customer success wants a dashboard joining ticket history against feature adoption. Finance wants a quarterly close helper. With a coding agent, the team that actually knows what shape they want can build the first version themselves. Engineering takes the tool over and hardens it only if it proves valuable enough to graduate. Anything that doesn&amp;rsquo;t prove itself disappears quietly, which is the right outcome for a prototype.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;The sandbox is non-negotiable when non-engineers build their own internal tools. The environment has to be one where the tool cannot reach production credentials, cannot read customer data at production scale, and cannot expose anything to the public internet. A finance analyst prototyping a close helper against the prod database with their own AI agent is the worst-case version of this trend. The same prototype against pseudonymized data in a network-isolated environment is the version that pays off. What the platform team owes the business isn&amp;rsquo;t a scaffolding template. It&amp;rsquo;s a safe place to ship in. The infrastructure cost of getting the sandbox right is small. The cost of getting it wrong is the breach.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-math-runs-the-other-way"&gt;When the math runs the other way
&lt;/h2&gt;&lt;p&gt;The regime above doesn&amp;rsquo;t extend to every tool a platform team might build. The decision matrix:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Cross-team tools from day one.&lt;/strong&gt; Two teams on the same internal tool means convention negotiation, which means coordination cost, which means the multiplier is gone. Build it the way you build any shared service: design review, versioned API, deprecation policy. The agent is still useful here. It is not 10x useful.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Regulated internal systems.&lt;/strong&gt; HR, finance close, anything in SOX, SOC2, or HIPAA scope. The verification bar rises sharply because the audit trail has to survive an external reviewer, and AI-speed advantage compresses against the human review time the controls require.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tools that touch customer data, even internally.&lt;/strong&gt; A script that joins across &lt;code&gt;users&lt;/code&gt; and &lt;code&gt;subscriptions&lt;/code&gt; is a customer-facing risk regardless of who runs it. Read access to PII is read access to PII whether the caller is a customer-facing API, an analytics agent, or a backup shipper. Blast-radius arguments don&amp;rsquo;t get a discount for being operational.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Destructive operations on prod infra.&lt;/strong&gt; A binlog purge script can break replication if it computes the cutoff wrong on a replica that&amp;rsquo;s silently behind. A snapshot shipper writes to S3 buckets other systems read from. The testing rigor required to ship destructive code pulls the productivity gain down. Still positive, often still 3x or 4x, but not the 10x of a pure read-only diagnostic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tools that drift into load-bearing.&lt;/strong&gt; The orchestrator that started life as a Friday-afternoon &amp;ldquo;drain, snapshot, upgrade, verify, restore traffic&amp;rdquo; script and is now the deploy path for six services. Once a tool crosses that line it has graduated out of the throwaway regime and into the production-systems regime. The conventions need writing down, the test suite needs to exist, and the next human who edits the code needs to be able to read it without an agent&amp;rsquo;s help. The productivity question is no longer &amp;ldquo;how fast can the agent ship v1&amp;rdquo; but &amp;ldquo;how cheap is the system to operate at year three.&amp;rdquo; Different question. Different answer.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The 10x envelope is narrow: greenfield, internal, replaceable, one team, fast feedback. It contains the toil backlog that has cost the team twenty silent minutes a week per uncreated tool for years, and the cost of writing those tools just dropped by an order of magnitude. The business case runs higher: when a non-engineer ships a tool with a coding agent, the multiplier is closer to 100x, because the pre-AI version of the tool doesn&amp;rsquo;t exist. Nobody ever wrote a ticket for it.&lt;/p&gt;
&lt;p&gt;The most ambitious version of the regime is the &lt;a class="link" href="https://explainanalyze.com/p/exposing-data-to-an-agent-mcp-vs-api/" &gt;agent API in front of the database&lt;/a&gt;: greenfield, owned by one team, conventions the agent sets, audience small enough that v1 wrong is recoverable. The team that has been deferring it because it sounds like a quarter of work has a path to ship it in days.&lt;/p&gt;
&lt;p&gt;What doesn&amp;rsquo;t extend: customer-facing systems and customer data don&amp;rsquo;t tolerate the same speed. Once PII leaks into a model provider&amp;rsquo;s buffer, or a destructive script hits the wrong replica, you don&amp;rsquo;t get it back. The apology you&amp;rsquo;ll get is some flavor of &amp;ldquo;you&amp;rsquo;re absolutely right&amp;rdquo;. The phrase has no recall semantics.&lt;/p&gt;</description></item><item><title>Why You Should Use an Agent to Assist with Quarterly Reviews</title><link>https://explainanalyze.com/p/why-you-should-use-an-agent-to-assist-with-quarterly-reviews/</link><pubDate>Wed, 13 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/why-you-should-use-an-agent-to-assist-with-quarterly-reviews/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Why You Should Use an Agent to Assist with Quarterly Reviews" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Pulling six months of evidence from Jira, GitHub, Slack, and 1:1 notes is mechanical work an agent can do in an hour. Making the judgment calls (rating, promotion, raise, PIP, fire) stays with the manager and is the part that should consume the saved hours. Done with verification (every claim traced to source, no decision delegated) the bookkeeping that used to take a week takes a day, and the team&amp;rsquo;s tracking hygiene improves as a side effect because the agent only sees what&amp;rsquo;s in the system. Done without verification, the failure mode is a confidently wrong review of a real person.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;a class="link" href="https://lethain.com/performance-compensation-process-exec/" target="_blank" rel="noopener"
 &gt;Will Larson&amp;rsquo;s writeup&lt;/a&gt; of a typical performance cycle at scale puts calibration at three to five hours per round per participating manager, across three rounds (sub-organization, organization, executive). Calibration is the part where managers argue ratings against each other under a budget. It is not the part where the review gets written. The writing happens earlier: pulling six months of context out of 1:1 notes, Jira, GitHub, Slack, design docs, and PagerDuty into a coherent per-report narrative, which runs one to three hours per direct report and is mostly gathering and cross-referencing rather than deciding. A manager with eight reports spends most of a working week on the full cycle, and the judgment-call portion (rating, promotion recommendation, calibration argument) is a fraction of that hour count.&lt;/p&gt;
&lt;p&gt;The standard responses (raise headcount, adopt a better template, push self-reviews onto reports) each redistribute the gathering cost without reducing it. The architectural fix is to script the gathering and use a narrow LLM call for the synthesis. The job is bounded, the inputs are structured, the output is a draft a human will edit. The same work pattern holds up across the agent-skeptical posts on this blog (&lt;a class="link" href="https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/" &gt;alert triage&lt;/a&gt;, &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;LLM-driven SQL&lt;/a&gt;): scripted gathering, narrow LLM synthesis, human keeps every decision. The review is a particularly clean instance because the decision is human-only by definition. No agent can fire someone. No agent can sign off on a promotion. The agent&amp;rsquo;s job is the part nobody wants to do.&lt;/p&gt;
&lt;h2 id="the-five-things-the-agent-earns-its-cost-on"&gt;The five things the agent earns its cost on
&lt;/h2&gt;&lt;p&gt;The first thing it earns: the team starts using Jira. Work the team doesn&amp;rsquo;t track is work the team can&amp;rsquo;t talk about, and the review version of that argument is sharper than the standup version. If a project isn&amp;rsquo;t in Jira, it might not be in the review, because the manager can&amp;rsquo;t hold six months of work for eight people in their head and the agent only sees what&amp;rsquo;s tracked. People notice when the first draft of their review omits the project they worked on for half the quarter. The conversation that follows is &amp;ldquo;where did that work go in the system, and how do we make sure it&amp;rsquo;s there next time?&amp;rdquo; Tracking hygiene improves automatically as a side effect of the review process, without needing its own mandate.&lt;/p&gt;
&lt;p&gt;The second thing it earns: completeness. The thing that always slips in manual reviews is the project from month two of the quarter that everyone has stopped thinking about. The migration that finished. The incident that got handled cleanly. The cross-team contribution that left a paper trail in someone else&amp;rsquo;s repo. The release-management work the IC quietly took over when the previous owner left. These show up in the corpus the agent reads. They don&amp;rsquo;t show up in the manager&amp;rsquo;s working memory in March. Reviews written from the corpus capture them; reviews written from memory don&amp;rsquo;t, and the gap shows up cumulatively over years as the engineers whose work is visible to the manager move ahead of the ones whose work isn&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;The third thing it earns: estimation discipline becomes a review signal. A team that re-points tickets after they close accumulates real data on where time actually goes, and that data is review-grade material. Not &amp;ldquo;did they hit their point targets&amp;rdquo; (a metric the team will game within a quarter of being told about it) but how complete their record is and how well their post-hoc estimates correlate with what shipped. A report who consistently re-points after the fact, even when the numbers move against them, is demonstrating a discipline the agent can surface directly. A report who doesn&amp;rsquo;t is harder to evaluate at all, which is itself information.&lt;/p&gt;
&lt;p&gt;The fourth thing it earns: GitHub activity, loosely weighted. The agent pulls PR counts, review participation, commit cadence, and approximate complexity (lines changed, files touched, languages crossed). This is loose data and the article using it needs to be explicit about that. A staff engineer who unblocks the team on three substantive reviews a week is worth more than one who ships ten unreviewed PRs of their own. The numbers spot patterns; they do not grade. A draft that says &amp;ldquo;shipped 23 PRs and reviewed 14 from teammates, with review depth averaging 3 substantive comments per PR&amp;rdquo; is useful. A draft that grades the report on those numbers has overstepped, and the manager should ask the agent to remove the grade and re-present the data.&lt;/p&gt;
&lt;p&gt;The fifth thing it earns: focus and follow-through patterns. Started-vs-finished ratios. Average time in-flight per ticket. Tickets opened and abandoned. Context switches per week per person. These surface patterns the manager would otherwise have to reconstruct from memory, and they&amp;rsquo;re patterns memory is bad at. Same caveat as the PR numbers. A high abandonment rate could be a focus problem or it could be an environment dragging the engineer between tickets every two days because nobody else is around to handle interruptions. The data spots the pattern. The manager makes the call about what the pattern means.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The agent is the index, not the conclusion&lt;/strong&gt;
 &lt;div&gt;Every claim in a good draft is a pointer into the corpus, not a finding about it. &amp;ldquo;Delivered the auth migration, 10 weeks (TICKET-4421, TICKET-4422, PR #1138)&amp;rdquo; is a draft worth editing. &amp;ldquo;Met expectations on delivery&amp;rdquo; is a draft worth rejecting. The first is something the manager can verify in fifteen seconds; the second is a conclusion the agent has no business making, and a conclusion the manager can&amp;rsquo;t trace without redoing the gathering work.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The architecture under all five is the same shape: deterministic gathering, narrow LLM synthesis, human decision. The gathering can be done two ways.&lt;/p&gt;
&lt;p&gt;The first is MCP. Wire up off-the-shelf Jira, GitHub, Slack, and PagerDuty MCP servers and let the agent query each system directly. Lower setup cost, faster to a first draft, easier to extend when a new system gets added to the team&amp;rsquo;s stack. The agent decides what to query and how.&lt;/p&gt;
&lt;p&gt;The second is scripts. Write Python (or any deterministic language) that hits each API and returns structured data as a CSV or JSON file before the agent ever sees it. Tickets closed per report with dates, points, and labels. PRs opened and reviewed with timestamps, approval counts, and lines changed. Time-in-flight distributions per ticket. Abandonment rates. On-call shifts and incident participation. The output is an artifact the manager can open, sort, and audit independently, and re-running the script reproduces the same numbers exactly.&lt;/p&gt;
&lt;p&gt;The trade-off is control. MCP is faster to stand up and weaker on verification. Scripts cost more upfront and produce a deterministic audit trail. For review-grade work where the cost of a wrong cited metric is paid by a real person, scripts are usually worth the upfront cost. For the qualitative exploration the agent does later in the same workflow (pull a specific 1:1 note, read one design doc), MCP is fine because verification by re-reading the source is what catches errors anyway. A reasonable middle path is scripts for anything that becomes a quoted number and MCP for anything the agent only needs to read once.&lt;/p&gt;
&lt;p&gt;Either way, the agent gets the structured inputs, the report&amp;rsquo;s name, their role expectations, and the review period, and produces a draft with explicit sections: shipped projects with source links, focus and follow-through patterns with the metrics inline, collaboration evidence with PR-review counts and threads referenced, contradictions surfaced rather than smoothed. Do not ask for ratings. Do not ask for recommendations. The bright line is that the agent assembles and the manager decides, and the prompt enforces it.&lt;/p&gt;
&lt;p&gt;When the gathering uses scripts, hallucinated numbers become the easiest class of agent error to catch, because the script that produced them is a source of truth the manager can re-run in seconds. A draft claiming &amp;ldquo;23 PRs and 14 substantive reviews&amp;rdquo; is one re-run away from being confirmed or rejected. With MCP, the verification surface is weaker: the agent&amp;rsquo;s report of a query result is what the manager sees, and reproducing the exact same fetch isn&amp;rsquo;t always trivial. Either way, keep the gathering deterministic where it can be. Keep the synthesis narrow. Don&amp;rsquo;t let the agent count things you can count for it.&lt;/p&gt;
&lt;h2 id="what-it-cant-be-allowed-to-touch"&gt;What it can&amp;rsquo;t be allowed to touch
&lt;/h2&gt;&lt;p&gt;Every reason above is contingent on a verification discipline the article should spend more space on than the gathering architecture deserves. Frontier LLMs corrupt a measurable fraction of delegated multi-step work, and the rate doesn&amp;rsquo;t drop with better prompts, more tools, or longer context windows (&lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;Corruption Is a Feature&lt;/a&gt;). A draft review the agent writes confidently, citing a specific ticket, a specific PR, a specific 1:1 quote, has a meaningful probability of being wrong in any of those specifics. The ticket exists but says something different. The 1:1 line paraphrases what was said into something close-but-not. The PR review that counts as &amp;ldquo;substantive&amp;rdquo; was a thumbs-up emoji. The migration the agent attributes to the IC was actually led by their teammate, and the IC was a reviewer.&lt;/p&gt;
&lt;p&gt;These errors land in a document that determines whether a real person gets promoted, doesn&amp;rsquo;t, gets put on a PIP, or doesn&amp;rsquo;t. The cost of getting this wrong is paid by the report, not the manager, which makes the verification discipline an ethical obligation, not just an operational one.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The failure mode that ends careers&lt;/strong&gt;
 &lt;div&gt;A confidently written review citing fabricated specifics (&amp;ldquo;Q1 incident response on the payments outage&amp;rdquo;) that the manager doesn&amp;rsquo;t verify is the failure mode. The agent invents the attribution from a Slack thread it misread, or compresses three engineers&amp;rsquo; contributions into one name, or quotes a 1:1 line that was said by a different report in a different week. The review is wrong, the manager signs it, and the person on the receiving end has no idea the underlying corpus contradicts what they&amp;rsquo;re reading. Verify every citation. Open every linked ticket. Read every quoted line in its original context. Re-run the script that produced any cited number - that&amp;rsquo;s the fastest verification surface and the one most likely to catch a fabricated metric.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Two disciplines hold the work together. The first is that every claim in the draft has to be traced to a source the manager opens and reads before the draft becomes a review. Not skimmed. Read. If the draft says &amp;ldquo;delivered the auth migration in Q1, ten weeks&amp;rdquo;, the manager opens the ticket, confirms the dates, confirms the scope. If the draft says &amp;ldquo;needs growth on cross-team collaboration&amp;rdquo;, the manager opens the threads cited as evidence and forms their own assessment. The agent&amp;rsquo;s draft is the index into the corpus, not the conclusion about it.&lt;/p&gt;
&lt;p&gt;The second discipline is rejecting first drafts. The first generation always reads cleaner than the corpus actually is. Patterns get smoothed. Conflicting signals get harmonized into a coherent narrative that isn&amp;rsquo;t quite the truth. Re-prompt with the parts that look wrong. Ask the agent to surface contradictions it smoothed over. Ask for the strongest negative case before the draft contains any praise, and then for the strongest positive case in a separate pass. Read both. The first draft is a hypothesis. The third draft, after the manager has read the corpus and contested the obvious narrative, is closer to a review.&lt;/p&gt;
&lt;p&gt;No decision belongs to the agent. Not the rating. Not the promotion recommendation. Not the raise. Not the PIP. Not the fire. The agent assembles. The manager decides. A draft that recommends a rating is a draft that has overstepped; reject it and re-prompt for the evidence underneath, without the conclusion.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The setup is overkill on small teams. A manager with three reports has the full corpus in their head and doesn&amp;rsquo;t need synthesis. The discipline pays back at six reports and up, and the curve gets sharper above ten. A new manager who doesn&amp;rsquo;t yet have judgment to verify against is in the most dangerous position, because the agent&amp;rsquo;s narrative will be the most coherent thing in the room and the temptation to trust it is highest exactly when it shouldn&amp;rsquo;t be. The agent assembles confidently regardless of how well it matches reality. Wait until you&amp;rsquo;ve written a few rounds of reviews manually before adopting this workflow. Orgs without basic systems hygiene (no Jira, scattered PR reviews, no design docs) don&amp;rsquo;t have the corpus the agent reads, and the synthesis is hollow. And teams where reviews are calibrated heavily on a single visible metric have already decided that the synthesis doesn&amp;rsquo;t matter; the agent&amp;rsquo;s draft is decoration in that environment.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;&lt;a class="link" href="https://pubmed.ncbi.nlm.nih.gov/11125659/" target="_blank" rel="noopener"
 &gt;Scullen, Mount, and Goff (2000)&lt;/a&gt; found that idiosyncratic rater effects accounted for 62% and 53% of performance-rating variance across two large samples (n=2,350 and n=2,142), more than twice the variance attributable to actual ratee performance. Most of what makes a review is the manager, not the engineer. Scripts and structured corpora don&amp;rsquo;t eliminate that bias, but they pull the underlying evidence onto a surface the next reviewer in calibration can audit, which changes what gets argued about: the data or the manager&amp;rsquo;s narrative.&lt;/p&gt;
&lt;p&gt;The agent doesn&amp;rsquo;t fix the underlying performance-management problem either. &lt;a class="link" href="https://www.gallup.com/workplace/644717/chros-think-performance-management-system-works.aspx" target="_blank" rel="noopener"
 &gt;Gallup&amp;rsquo;s 2024 survey&lt;/a&gt; of Fortune 500 CHROs found 2% strongly agree their system inspires employees to improve, and 22% of employees agree the process is fair and transparent. Those numbers have been some version of themselves for as long as anyone has measured. The agent makes the mechanical parts mechanical, which is the most an architecture decision can do here. The hours that buys back get spent on the parts the corpus can&amp;rsquo;t help with: the conversation with the report about growth, the calibration argument with peer managers, the year-out career planning, the things that take attention and presence rather than data.&lt;/p&gt;</description></item><item><title>Hidden Database Costs of an AI Rollout: Storage, CPU, Memory, and Cache</title><link>https://explainanalyze.com/p/hidden-database-costs-of-an-ai-rollout-storage-cpu-memory-and-cache/</link><pubDate>Sun, 10 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/hidden-database-costs-of-an-ai-rollout-storage-cpu-memory-and-cache/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Hidden Database Costs of an AI Rollout: Storage, CPU, Memory, and Cache" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Adding RAG to your existing Postgres usually 5x&amp;rsquo;s the storage on the affected tables, drives the HNSW index off a memory cliff that doesn&amp;rsquo;t degrade gracefully, and pollutes the buffer cache hard enough that unrelated OLTP queries regress at p95. Halfvec, binary quantization with rerank, and a separate replica recover most of it, after the bill has already arrived.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A pgvector user opened &lt;a class="link" href="https://github.com/pgvector/pgvector/issues/666" target="_blank" rel="noopener"
 &gt;issue #666&lt;/a&gt; in September 2024. They had one million records, 512-dimensional vectors, an HNSW index. Cold-cache search took 83 seconds. Warm cache, the same query returned in roughly 100 milliseconds. Three orders of magnitude. The index had not grown. The query had not changed. What changed was that other applications running on the same Postgres preempted the vector index pages out of cache, and the next search read the entire HNSW graph back from disk one block at a time. The capacity plan that approved the AI feature six weeks earlier had a line for storage and a line for CPU. It did not have a line for the OLTP buffer pool quietly fighting the vector index for residency, and losing.&lt;/p&gt;
&lt;p&gt;The senior reader&amp;rsquo;s first response is &amp;ldquo;throw a bigger instance at it&amp;rdquo; or &amp;ldquo;stop running this on the OLTP Postgres and use a dedicated vector DB&amp;rdquo;. Both are right answers in some configurations. A bigger instance buys headroom for the working set without changing the slope of the cost curve as the corpus grows. A dedicated vector store removes the cache-pollution problem and adds a network hop, a second consistency model, and another piece of infrastructure to back up. The choice being made is between paying the cost on the OLTP Postgres in the form of a bigger instance and worse p95s, or paying it on a second system in the form of more operational surface area. The conversation that didn&amp;rsquo;t happen is the one about what the cost actually consists of and where it accrues. That is what the rest of this article is.&lt;/p&gt;
&lt;h2 id="the-four-cost-categories"&gt;The four cost categories
&lt;/h2&gt;&lt;p&gt;Every pgvector &lt;code&gt;vector&lt;/code&gt; row takes &lt;code&gt;4 * dimensions + 8&lt;/code&gt; bytes. A 1536-dimensional embedding from text-embedding-3-small lands at 6,152 bytes. A 50-million-row table that occupied 40 GB on its existing columns becomes 350 GB after the embedding column is added, before any index. Supabase published a &lt;a class="link" href="https://supabase.com/blog/fewer-dimensions-are-better-pgvector" target="_blank" rel="noopener"
 &gt;case study in August 2023&lt;/a&gt; on 224,482 embeddings where Postgres RAM consumption went from 4 GB on 384-dimensional vectors to 7.5 GB on 1536-dimensional vectors, on the same hardware and the same row count. The dimensions alone were the difference.&lt;/p&gt;
&lt;p&gt;Vector index builds cost CPU at a scale that breaks the assumptions of any normal migration window. Jonathan Katz &lt;a class="link" href="https://jkatz05.com/post/postgres/pgvector-overview-2024/" target="_blank" rel="noopener"
 &gt;benchmarked HNSW build&lt;/a&gt; on the dbpedia 1M corpus across pgvector versions: 7,479 seconds on 0.5.0, 250 seconds on 0.7.0 with the parallel-build improvements, 49 seconds with binary quantization. AWS published &lt;a class="link" href="https://aws.amazon.com/blogs/database/load-vector-embeddings-up-to-67x-faster-with-pgvector-and-amazon-aurora/" target="_blank" rel="noopener"
 &gt;Aurora numbers&lt;/a&gt; on a 5M OpenAI dataset showing 29,752 seconds on 0.5.1 versus 445 seconds on 0.7.0 with binary quantization. Versions matter. They also bound how bad it can get on older versions. pgvector &lt;a class="link" href="https://github.com/pgvector/pgvector/issues/300" target="_blank" rel="noopener"
 &gt;issue #300&lt;/a&gt; reports a 24-plus-hour HNSW build on 10M rows of 768-dimensional vectors with 4 CPU and 16 GB RAM. &lt;a class="link" href="https://github.com/pgvector/pgvector/issues/807" target="_blank" rel="noopener"
 &gt;Issue #807&lt;/a&gt; reports the connection dropping after roughly two hours of an HNSW build on 17M rows of 1536-dimensional vectors with 48 CPU and 192 GB RAM. The build is the part of the workload least visible to the production dashboard and most painful to retry.&lt;/p&gt;
&lt;p&gt;HNSW does not degrade gracefully when its working set exceeds RAM. The graph is designed to be traversed in random order, which is fast when every page is in &lt;code&gt;shared_buffers&lt;/code&gt; and falls off a cliff when it isn&amp;rsquo;t. pgvector &lt;a class="link" href="https://github.com/pgvector/pgvector/issues/844" target="_blank" rel="noopener"
 &gt;issue #844&lt;/a&gt; caught the in-build version of the same problem: the user got the message &lt;code&gt;hnsw graph no longer fits into maintenance_work_mem after 5908085 tuples&lt;/code&gt;, and the build slowed dramatically from that tuple onward. The query-side equivalent has the same shape. Crunchy Data&amp;rsquo;s &lt;a class="link" href="https://www.crunchydata.com/blog/hnsw-indexes-with-postgres-and-pgvector" target="_blank" rel="noopener"
 &gt;HNSW write-up&lt;/a&gt; reports index sizes of roughly 8 GB per million rows on typical AI embeddings. Neon&amp;rsquo;s operational guide recommends keeping &lt;code&gt;maintenance_work_mem&lt;/code&gt; at no more than 50–60% of available RAM for vector workloads. The exact latency-vs-RAM curve past the cliff is not published in any vendor source I can find. The shape is well-known to anyone who has watched it happen, and the absence of a published curve is itself a sign of how much of this knowledge lives in incident channels rather than docs.&lt;/p&gt;
&lt;p&gt;The cache problem is the inverse of the build problem. Once the index exists, every ANN query touches thousands of pages chased through a graph traversal. A handful of vector queries running concurrently with OLTP traffic is enough to evict the heap pages the OLTP queries depend on, and the OLTP p95 regresses without any change to OLTP code. The pgvector #666 numbers from the opening are the cleanest single data point on this. The instructive piece is the magnitude. Not 2x worse, not 5x worse. Three orders of magnitude depending on cache state. There is no other workload class on a typical OLTP Postgres that produces that swing.&lt;/p&gt;
&lt;p&gt;All four cost categories converge on the managed-service bill. Aurora storage runs $0.10 per GB-month at the base tier. 100 million 1536-dimensional full-precision vectors require roughly 6.15 GB raw per million rows, plus an HNSW index closer to 8 GB per million on typical configurations. That is about 1.4 TB before backups, replicas, or growth, around $140/month in raw storage at the base rate. Storage is the floor, not the cost. The cost is the instance class needed to keep the active portion of that index in &lt;code&gt;shared_buffers&lt;/code&gt;, which on the memory-cliff curve above means an instance one or two tiers above what the rest of the workload required.&lt;/p&gt;
&lt;h2 id="the-two-events-the-capacity-plan-didnt-budget-for"&gt;The two events the capacity plan didn&amp;rsquo;t budget for
&lt;/h2&gt;&lt;p&gt;Embedding model upgrades rewrite the embedding column. text-embedding-3-small was &lt;a class="link" href="https://openai.com/index/new-embedding-models-and-api-updates/" target="_blank" rel="noopener"
 &gt;released January 2024&lt;/a&gt; alongside text-embedding-3-large, and any team that wanted the better recall on the larger model also wanted to re-embed the existing corpus. The migration is a full rewrite of the largest column on the largest table, plus an HNSW index rebuild on the new vectors, plus the API call cost of generating the new embeddings, plus double storage during cutover unless the team is willing to take a recall regression by deleting the old embeddings before the new ones are validated. There is no published postmortem from a named company giving real numbers on this event. The closest public signal is pgvector &lt;a class="link" href="https://github.com/pgvector/pgvector/issues/559" target="_blank" rel="noopener"
 &gt;issue #559&lt;/a&gt; from December 2024, where a user reports that individual inserts on a 1M-row HNSW table went from millisecond-scale before the index existed to &amp;ldquo;5–8s&amp;rdquo; afterward. The same write amplification applies to the migration, except now it applies to every row at once. The absence of postmortems is itself worth noticing. The event is recent enough that most teams haven&amp;rsquo;t lived through their second model upgrade yet.&lt;/p&gt;
&lt;p&gt;The other unpriced event is connection pool starvation when the application holds a Postgres connection while waiting on an LLM call. The pattern is straightforward. A request needs context from the database, the application opens a transaction, fetches the rows, builds a prompt, calls the model, gets a 4-second response, writes the result back, commits. The connection is held for the entire round trip. A pool sized for 200ms transactions exhausts at one-twentieth the request rate it was sized for, and the failure surfaces as &lt;code&gt;too many connections&lt;/code&gt; errors on requests that have nothing to do with the AI feature. There is no named-company postmortem in the public record for this one either. The pattern is recognizable to anyone who has run a database behind a synchronous LLM call. The fix is structural. Do the LLM call outside the transaction. Release the connection before the model call begins and acquire a new one after. Or move to a connection pooler that explicitly supports this pattern. None of those is free, and none of them is what the first version of the feature ships with.&lt;/p&gt;
&lt;h2 id="what-actually-moves-the-bill"&gt;What actually moves the bill
&lt;/h2&gt;&lt;p&gt;Three levers do most of the work, and each one carries a trade-off the AI-feature team would rather not own.&lt;/p&gt;
&lt;p&gt;Halfvec is the cheapest move. The pgvector &lt;code&gt;halfvec&lt;/code&gt; type stores each component as a 16-bit float instead of 32-bit, halving storage at no measured recall cost on most embedding models. AWS&amp;rsquo;s Aurora benchmark shows the Cohere 10M corpus dropping from 38 GB to 19 GB, with database memory consumption going from 15.12% to 7.55% on the same r7g.12xlarge instance. Neon&amp;rsquo;s &lt;a class="link" href="https://neon.com/blog/dont-use-vector-use-halvec-instead-and-save-50-of-your-storage-cost" target="_blank" rel="noopener"
 &gt;July 2024 post on halfvec&lt;/a&gt; reports 50% storage reduction, 23% faster index build, 50% faster prewarming, and equivalent recall on a 1M DBpedia 1536-dimensional corpus. The trade-off is that halfvec only buys 2x. The corpus growth that earned the bill in the first place still applies. Halfvec moves the bill, it does not change its slope.&lt;/p&gt;
&lt;p&gt;Binary quantization with reranking is the next lever, and it is the one with a published tension worth understanding. Qdrant&amp;rsquo;s &lt;a class="link" href="https://qdrant.tech/articles/binary-quantization/" target="_blank" rel="noopener"
 &gt;binary quantization article&lt;/a&gt; from September 2023 reports recall of 0.985 on text-embedding-3-small at 3x oversampling with reranking, and 0.997 on text-embedding-3-large at the same setting. Storage drops by roughly 32x relative to full precision. Neon ran a binary-quantization test on 1536-dimensional vectors in 2024 and concluded recall was &amp;ldquo;insufficient for production use&amp;rdquo;. Both are correct. Qdrant tested with a rerank stage that re-evaluates the top-k binary candidates against full-precision vectors held elsewhere; Neon tested binary alone. Binary quantization without rerank is dangerous. Binary quantization with rerank requires keeping a full-precision copy of the vectors somewhere accessible, which is back to a storage problem of a different shape.&lt;/p&gt;
&lt;p&gt;Separating the vector workload onto its own physical Postgres replica or onto a dedicated vector store addresses cache pollution directly. The trade-off is operational. A second system to back up, a second consistency model to reason about, a second incident-response runbook. On a small team this can dominate the cost it was meant to save. On a larger team where the AI feature has its own owners and the OLTP database has its own owners, the separation aligns infrastructure boundaries with team boundaries and is usually worth it on those grounds alone, before any cache argument is made.&lt;/p&gt;
&lt;p&gt;A scalar quantization note worth keeping in view: Jonathan Katz&amp;rsquo;s &lt;a class="link" href="https://jkatz05.com/post/postgres/pgvector-scalar-binary-quantization/" target="_blank" rel="noopener"
 &gt;scalar and binary quantization benchmark&lt;/a&gt; from April 2024 measured halfvec recall at 0.968 versus full-precision 0.968 on dbpedia-openai-1000k-angular at the same &lt;code&gt;ef_search&lt;/code&gt;. The author&amp;rsquo;s verdict was direct: &amp;ldquo;Scalar quantization from 4-byte to 2-byte floats looks like a clear winner.&amp;rdquo; On most embedding models, halfvec is the move you can make today without touching application code or rerank pipelines, and the bill drops by half.&lt;/p&gt;
&lt;h2 id="when-the-math-runs-the-other-way"&gt;When the math runs the other way
&lt;/h2&gt;&lt;p&gt;This article is overkill on three configurations. Small corpora, under roughly 100,000 vectors at 1536-dim or smaller, do not generate enough storage or index volume to matter on any modern Postgres instance. Low-QPS internal tools where the vector search runs a few times a minute do not pollute the buffer cache enough to regress OLTP, and do not need the operational complexity of a separate vector store. Teams already on a dedicated vector store from day one (Pinecone, Weaviate, Qdrant Cloud, pgvectorscale on a separate instance) have paid the operational price up front and have a different cost structure that this article does not speak to. The four cost categories above all assume a vector workload colocated with an OLTP Postgres at production scale, which is the configuration most teams ship first because it is the configuration that requires the fewest decisions.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The shape of the problem recurs across every AI-rollout postmortem worth reading. The feature ships fast because the existing infrastructure is already there. The cost lands later because the existing infrastructure was sized for a different workload. Embeddings on the OLTP Postgres are cheap to add and expensive to operate. The capacity plan that signed off on the AI feature did not have line items for storage at 6 KB per row, for HNSW builds that consume entire instances for hours, for memory cliffs that do not degrade gracefully, or for cache pollution that regresses unrelated p95s. The standard &amp;ldquo;what does this feature cost&amp;rdquo; template was written for application features that read and write rows the database was designed to read and write. Vector search is a different access pattern. The team that surfaces these four numbers before the feature ships pays them on a normal capacity ticket, and the same four line items are where an &lt;a class="link" href="https://explainanalyze.com/p/where-your-cloud-bill-actually-leaks-an-audit-nobody-runs/" &gt;audit of the cloud bill&lt;/a&gt; finds the rollout six months later. The team that doesn&amp;rsquo;t, pays them anyway, six weeks later, in the form of an emergency one.&lt;/p&gt;</description></item><item><title>Your Alert Triage Doesn't Need an Autonomous Agent</title><link>https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/</link><pubDate>Fri, 08 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/your-alert-triage-doesnt-need-an-autonomous-agent/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Your Alert Triage Doesn't Need an Autonomous Agent" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Autonomous agents are the wrong abstraction for alert triage. A scripted playbook of RE-curated queries plus one LLM call to summarize the structured output gives the responder a triage hint with the raw data attached. The summary saves time on the easy pages; the raw data carries them through the cases the LLM gets wrong.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;3:14am page. p99 latency on &lt;code&gt;/api/orders&lt;/code&gt; checkout past the 1500ms SLO for six straight minutes. The on-call assistant&amp;rsquo;s summary at the top of the alert reads &amp;ldquo;elevated checkout latency correlated with deploy of order-service r8472, 14 minutes ago. Recommend rollback.&amp;rdquo; The responder pages the deploy author and starts the rollback. Latency stays past SLO. The actual cause is a worker that hung yesterday holding an open transaction, idle for 18 hours, blocking vacuum the entire time. Bloat on the &lt;code&gt;orders&lt;/code&gt; table is what made the checkout query slow enough to finally cross the SLO during normal early-morning traffic. The agent pulled the &lt;code&gt;pg_stat_activity&lt;/code&gt; snapshot and the idle session was in it. The summary picked the deploy anyway, because the deploy was the most legible recent change in the data it had. The responder did not read &lt;code&gt;pg_stat_activity&lt;/code&gt; because the summary said roll back the deploy. Twenty-three minutes page-to-fix, twenty on the wrong path.&lt;/p&gt;
&lt;p&gt;The senior reader&amp;rsquo;s first response is &amp;ldquo;give the agent better access. Wire in &lt;code&gt;pg_locks&lt;/code&gt;, slow-query log, replication slot state, recent lag, the works.&amp;rdquo; The agent in the scenario already had &lt;code&gt;pg_stat_activity&lt;/code&gt;. Missing data was never the problem. The agent had the data and picked the most legible recent change as the cause, because that is what the model defaults to on partial structured data. Adding more sources gives it a longer list to pattern-match against. The summary that comes back is more confident without being more correct, and a responder defers more readily to a confident summary. That is how the failure mode shifts from &amp;ldquo;agent missed the data&amp;rdquo; (visible, fixable in tooling) to &amp;ldquo;agent had the data and misattributed cause&amp;rdquo; (invisible, the post-mortem has to reconstruct what the responder would have seen without the summary).&lt;/p&gt;
&lt;h2 id="what-the-agent-abstraction-blends-together"&gt;What the agent abstraction blends together
&lt;/h2&gt;&lt;p&gt;&amp;ldquo;Agent&amp;rdquo; in the current vendor pitch means autonomy in tool selection: the LLM reads the alert, decides which MCP servers to consult, what queries to run, in what order, what to do with the results. That bundle does two jobs at once. Summarizing structured data into prose is the job where an LLM hallucinates least, though it still fabricates values and misreads fields on the way. Deciding which queries to run for a given symptom is detective work that depends on a system model the LLM does not have. The reliability engineer has the model. They have been on call. They have read every post-mortem. They know that a replication-lag alert wants the slot state, the publisher&amp;rsquo;s WAL position, the largest active transaction&amp;rsquo;s age, and the last three deploys, in that order, every time. The LLM does not know that. It can pattern-match toward it on familiar shapes and miss it on the rest.&lt;/p&gt;
&lt;p&gt;The right design splits the two jobs. The reliability engineer curates the playbook: for this alert ID, run these queries against these systems, with this scope. A script runs the playbook on every fire of that alert. One LLM call at the end takes the structured output and writes a paragraph: what is affected, what is notable in the data, what jumped out. No tool selection by the model. No causal claims unsupported by the queries the playbook ran. The model is doing the safest thing it can do.&lt;/p&gt;
&lt;p&gt;This is not a smaller version of an agent. The autonomy in tool selection has been removed entirely. The reliability engineer chose the queries, the playbook runs them, the LLM formats the result.&lt;/p&gt;
&lt;p&gt;In practice, most teams that ship an agent in production end up not trusting its autonomy unsupervised either. Tool descriptions accumulate, system prompts get tuned with hints like &amp;ldquo;for slow-query alerts, consider checking &lt;code&gt;pg_stat_activity&lt;/code&gt;, &lt;code&gt;pg_locks&lt;/code&gt;, and the last three deploys.&amp;rdquo; That natural-language playbook lives inside the prompt, with no guarantee the model executes it on any given run. The engineer is authoring a playbook either way. The only choice is whether the playbook lives in code that runs every time, or in a prompt the model may or may not honor on this alert.&lt;/p&gt;
&lt;h2 id="what-every-round-trip-costs"&gt;What every round trip costs
&lt;/h2&gt;&lt;p&gt;The autonomous-agent design pays for the same data several times. Each tool call&amp;rsquo;s output goes into the input prompt of the next step, and the loop is serial: read alert, decide query, run query, read result, decide next query, run query, read result. A &lt;code&gt;pg_stat_activity&lt;/code&gt; dump fetched at step one is in the input for steps two, three, four, and five. The same dump is re-tokenized as input on every subsequent step, so a six-step loop bills the model for that payload roughly five extra times, plus the output tokens spent emitting tool-call JSON at each hop. At a page rate of a few hundred a day across a platform team, the bill compounds. Prompt caching cuts the bill but does not change the shape. Every step still serializes through a model call, every tool error still pollutes the conversation, and every retry still spends real wall-clock seconds.&lt;/p&gt;
&lt;p&gt;The agent also does this fresh on every alert. It carries no schema knowledge between runs the way the reliability engineer does. On a given page it queries &lt;code&gt;pg_stat_statements&lt;/code&gt; for &lt;code&gt;total_time&lt;/code&gt; on a PG14 cluster (the column was split into &lt;code&gt;total_exec_time&lt;/code&gt; and &lt;code&gt;total_plan_time&lt;/code&gt; in PG13), reads the SQL error in the next prompt, retries with a different guess, gets it wrong again, queries &lt;code&gt;information_schema&lt;/code&gt; to discover what columns actually exist, dumps that result into the conversation, and finally runs the query it should have run from the start. Every error and every discovery dump piles into the next prompt. Per alert. The playbook does this once when the RE writes it, in version control, against a real database.&lt;/p&gt;
&lt;p&gt;And the loop takes time. Even on the fast tier, the loop is serial: every step is a model call followed by a tool call followed by another model call. Six round trips compound, and the responder paged at 3am has opened three dashboards manually before the agent posts its first summary. The supposed time savings of the agent are negative against a responder who already knows where to look.&lt;/p&gt;
&lt;p&gt;The playbook design fetches everything once, in parallel, and passes one shaped bundle into one LLM call. The shaping is where most of the token savings come from. Raw &lt;code&gt;pg_stat_activity&lt;/code&gt; output is verbose JSON with thirty columns per row, half of them irrelevant to a triage summary. A playbook can project the four columns the prompt actually needs (&lt;code&gt;pid&lt;/code&gt;, &lt;code&gt;state&lt;/code&gt;, &lt;code&gt;query_start&lt;/code&gt;, &lt;code&gt;query&lt;/code&gt;), format them as a small table rather than nested JSON, truncate long query text, and pass a hundred bytes where the agent would have passed ten kilobytes. Page-to-summary time is the slowest single query plus one summarization call, regardless of how many queries the playbook fetches.&lt;/p&gt;
&lt;h2 id="the-alert-artifact"&gt;The alert artifact
&lt;/h2&gt;&lt;p&gt;What the responder gets has three layers.&lt;/p&gt;
&lt;p&gt;Tier sits at the top, set by the routing layer: prod page, non-prod channel, Jira queue. The tier picks the playbook. A P0 page activates the prod-read playbook, which can hit replicas and recent deploy state. A Jira ticket runs only the runbook-lookup playbook with no live read access. Tier-as-scope is the security half of the design and falls out for free once the playbook is the unit of action.&lt;/p&gt;
&lt;p&gt;Raw data sits in the middle: every query the playbook ran, with its output. The &lt;code&gt;pg_stat_activity&lt;/code&gt; snapshot. The lock graph. Replication slot state. Last five deploys with author and SHA. Slow-query log entries from the last fifteen minutes. The artifact attaches all of it because the playbook already paid the cost to fetch it. Re-running the queries from the responder&amp;rsquo;s terminal at 3am is exactly the time the design exists to save.&lt;/p&gt;
&lt;p&gt;Summary sits on top: one paragraph from one LLM call, generated from the structured output of the playbook. &amp;ldquo;Replication lag of 47 seconds. Slot &lt;code&gt;pub_orders&lt;/code&gt; is held with &lt;code&gt;restart_lsn&lt;/code&gt; 18 hours stale. No recent deploys touch the publisher service. Largest active transaction is session 88234, idle in transaction for 18h2m.&amp;rdquo; That sentence is doing the job an LLM hallucinates least on: compressing structured input into readable prose, with the inputs visible to the responder one scroll below. It is not claiming the slot is the cause. The responder reads the summary, scrolls to confirm in the slot-state output, kills the session, slot drains, lag recovers.&lt;/p&gt;
&lt;p&gt;The summary is a reading hint, not a source of truth. On the bulk of pages where it is right (bad CPU, lag, slow query, full disk), the responder saves a few minutes of dashboard-tab opening. On the cases where it is wrong, they scroll past the summary, read the raw output the playbook already gathered, and override. They never have to wait on the model to fetch anything.&lt;/p&gt;
&lt;p&gt;Lower tiers do not run the playbook automatically. A non-prod channel post or a Jira ticket lands with the alert payload and an &amp;ldquo;investigate&amp;rdquo; button. Most of those alerts get glanced at and dismissed: known flake, the synthetic that fires every Tuesday morning. Running a playbook and a summarization call on every one wastes tokens and clutters the channel. The button is for the alerts the responder decides to look at; pressing it runs the playbook and attaches raw data and summary the same way a P0 page would have them. P0 pages skip the button because the responder is already committed; the summary is there the moment the page opens.&lt;/p&gt;
&lt;h2 id="what-the-post-mortem-actually-changes"&gt;What the post-mortem actually changes
&lt;/h2&gt;&lt;p&gt;Post-mortem deltas in this design land somewhere specific. Usually the playbook needs another query: &lt;code&gt;pg_prepared_xacts&lt;/code&gt; was missing, or the lock graph was dumped without the waiter chain. Sometimes the prompt template needed to surface a signal the playbook already gathered but the LLM ignored. Occasionally the routing tier was wrong and the alert hit the wrong playbook entirely. All three ship as a pull request a reviewer can read.&lt;/p&gt;
&lt;p&gt;The same post-mortem in an autonomous-agent setup is harder to reason about. The agent decided to run queries A, B, C this time. It might run D, E, F next time on a similar-looking alert. The prompt and the run are intertwined, and the fix is &amp;ldquo;tune the agent&amp;rsquo;s tool descriptions&amp;rdquo; with no guarantee the next run reaches for the right tool.&lt;/p&gt;
&lt;h2 id="how-youd-actually-measure-this"&gt;How you&amp;rsquo;d actually measure this
&lt;/h2&gt;&lt;p&gt;The argument that a curated playbook plus a summarization call beats an autonomous agent is testable on a team&amp;rsquo;s own pages. Pull the last quarter of P0 and P1 alerts. For each one, run the candidate playbook against a snapshot of the systems&amp;rsquo; state at the time the page fired (or against archived metrics, depending on what&amp;rsquo;s stored). Generate the summary the way the design would. Compare it against the post-mortem&amp;rsquo;s documented root cause.&lt;/p&gt;
&lt;p&gt;Two regressions to count separately: cases where the summary names a wrong root cause that the bundle&amp;rsquo;s raw data would have ruled out, and cases where the summary fabricates a value the playbook never produced. The first measures the model&amp;rsquo;s misattribution rate on data it actually saw. The second measures the model&amp;rsquo;s tendency to invent facts that are not in the input, the floor problem the raw-data layer exists to catch.&lt;/p&gt;
&lt;p&gt;Run the same evaluation against an autonomous-agent baseline on the same alerts, and the comparison is concrete rather than theoretical. Either the agent&amp;rsquo;s tool selection picks queries the playbook would not, in which case the playbook needs editing. Or the agent&amp;rsquo;s summaries hallucinate at a higher rate on the same inputs. Either result is useful. The eval is cheap to set up once and pays back every time the playbook is changed.&lt;/p&gt;
&lt;h2 id="where-the-design-strains"&gt;Where the design strains
&lt;/h2&gt;&lt;p&gt;A few real caveats. None of them the agent design solves either.&lt;/p&gt;
&lt;p&gt;Playbook maintenance is work, but the work is the cleanest accuracy lever the engineer has. Adding a query directly improves the summary&amp;rsquo;s grounding, because the model now reads more of the data the cause lives in. Tuning an agent&amp;rsquo;s prompt does not have the same property. The model can still ignore the hint, conflict it with another instruction, or pick a different tool, and there is no deterministic check that any of those did not happen. The bundle either has the data or it does not. The strain is the silent failure mode on the maintenance side. When a query references a column that was renamed or a service that moved, the query returns empty, the bundle gets thinner, and the summary gets less informative without anything visibly breaking. The discipline that catches it is owned playbooks (one team, one engineer named in the file) plus a cadence: post-mortems produce playbook deltas, and a periodic review flags queries that have returned zero rows on every recent run. Without that, the playbook decays.&lt;/p&gt;
&lt;p&gt;The summary can still be wrong on data the playbook surfaced. Curating the input does not fix the model&amp;rsquo;s tendency toward confident misattribution. The bundle might include the idle-in-transaction session and the recent deploy side by side, and the model can still pick the deploy because it pattern-matches better to recent-change framing. The raw-data layer is the floor under the summary. The responder scrolls, reads the idle session, overrides. Curating the input does not change the model&amp;rsquo;s tendency to misattribute; it changes how easy the misattribution is to catch.&lt;/p&gt;
&lt;p&gt;The summary can also fabricate facts the playbook did not produce. Even with a curated bundle as input, the model can describe values that were not in the data (a lag of 47 seconds when no lag query ran), invent observations from a single-row snapshot, or restate the bundle in a way that adds confidence the data does not support. The raw-data layer is again the floor: the responder catches a fabricated number by reading the actual query output the playbook attached. The agent design has the same failure plus a worse one. The agent&amp;rsquo;s summary can claim observations that no tool call ever produced, because in an agent trace the summary text and the actual tool calls are separate artifacts and the responder rarely reads both.&lt;/p&gt;
&lt;p&gt;Prompt injection is a real exposure. Raw strings from user-controlled fields end up in the bundle: query text, &lt;code&gt;application_name&lt;/code&gt;, log message bodies. An attacker who can write into those fields can attempt to steer the summary. Tier-as-scope helps because low-trust alerts get less context to work with, but the playbook design does not eliminate the risk any more than the agent design does. Standard mitigations apply: prompt isolation, output sanitization, and treating the summary as untrusted input to anything downstream.&lt;/p&gt;
&lt;p&gt;Page delivery takes longer if the summary blocks. The LLM call adds 200ms to a couple of seconds, and on paging tiers that is a regression on time-to-acknowledge. The fix is the same shape as the investigate button on lower tiers: lazy. Deliver the raw alert and the playbook output the moment they are ready. The summary lands asynchronously and appends to the thread when the LLM call returns. The responder starts reading the raw data while the summary is still rendering. Blocking page delivery on the summarizer is the kind of regression the design was supposed to prevent.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;A few places the discipline costs more than it pays.&lt;/p&gt;
&lt;p&gt;Small systems with a single responder who has the full mental model. A two-service team with five alert types and one on-call does not need playbook authoring overhead and a per-alert LLM call. The responder&amp;rsquo;s pattern-match resolves the page in thirty seconds and the summary is friction.&lt;/p&gt;
&lt;p&gt;Alerts with no diagnostic surface. A boolean health check with no associated query set is not a playbook target. The alert is the data; there is nothing structured to summarize on top.&lt;/p&gt;
&lt;p&gt;Novel incidents the playbook has not seen. By design, no playbook matches and no summary is generated. The responder gets the raw alert and reads &lt;code&gt;pg_stat_activity&lt;/code&gt; themselves. That is the correct behavior. The alternative, an autonomous agent that reaches for whichever queries it pattern-matches to, would produce a confident summary on a problem the team has never seen, which is the worst case for both MTTR and post-mortem quality.&lt;/p&gt;
&lt;p&gt;Tier-one NOC responders working escalation playbooks. The design assumes a responder senior enough to override a confident summary by reading the raw output below it. A 24/7 NOC tier whose runbook says &amp;ldquo;if summary recommends rollback, page deploy author and roll back&amp;rdquo; inherits the worst of both worlds: the summary&amp;rsquo;s confidence with none of the override capacity. For that org shape the same design needs an additional rule. The summary never names a recommended action, only what is notable in the data, and the runbook explicitly tells the responder to escalate when the summary&amp;rsquo;s notable-fact list does not match the runbook&amp;rsquo;s expected pattern. Without that, a senior-on-call design imported into an L1 environment makes incident outcomes worse.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Summarization of structured data into prose is the job where LLM hallucinations are smallest. They still happen, but the floor is higher than for tool selection or causal attribution. Where the work depends on a system model the model does not have, the hallucinations are everywhere. The same shape shows up in &lt;a class="link" href="https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/" &gt;prompts as guardrails&lt;/a&gt;. The reliability engineer keeps the system model. The playbook is where that model lives in code. The model formats. Choosing what to fetch is the part the engineer is for.&lt;/p&gt;</description></item><item><title>If Your Guardrail Is a Prompt, You Don't Have a Guardrail</title><link>https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/</link><pubDate>Fri, 01 May 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/if-your-guardrail-is-a-prompt-you-dont-have-a-guardrail/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post If Your Guardrail Is a Prompt, You Don't Have a Guardrail" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A prompt instruction biases the next-token distribution. It cannot bound it. Real guardrails for agents holding production credentials sit below the prompt, in layers the model cannot read or override: scoped identities, vetted tool surfaces, harness hooks, wire-level statement filtering, provenance-tagged logs, behavioral monitoring.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The agent&amp;rsquo;s instructions said staging only, read-only by default, no schema changes, confirm before any &lt;code&gt;DELETE&lt;/code&gt;. The environment said &lt;code&gt;DATABASE_URL=postgres://app_writer:...@prod-cluster:5432/app&lt;/code&gt;. Twenty turns in, the user wrote &amp;ldquo;looks good, can you also clean up the old events&amp;rdquo;, and the agent ran &lt;code&gt;DELETE FROM events WHERE created_at &amp;lt; '2025-01-01'&lt;/code&gt; against the only connection string it had. The instruction never lost an argument with the destructive call. By turn 20 it had decayed into background.&lt;/p&gt;
&lt;h2 id="a-stronger-prompt-wont-fix-this"&gt;A stronger prompt won&amp;rsquo;t fix this
&lt;/h2&gt;&lt;p&gt;The reflex is to write a stronger prompt. ALL CAPS, with a rules block at the top of the system message and a reminder at the bottom of every user turn. &lt;a class="link" href="https://fortune.com/2025/07/23/ai-coding-tool-replit-wiped-database-called-it-a-catastrophic-failure/" target="_blank" rel="noopener"
 &gt;Replit&amp;rsquo;s July 2025 incident&lt;/a&gt; already ran the experiment: eleven all-caps messages forbidding writes during a code freeze, an agent that ignored every one, 1,206 executive accounts dropped, no rollback path the agent could find. Twelve would not have helped. Fifty would not have helped. The prompt is the wrong layer for a guardrail, and the strength of the wording is not the variable.&lt;/p&gt;
&lt;p&gt;The same holds for the moves around it. Fine-tuning lowers the rate without zeroing it, and a fine-tune is harder to update than a SQL &lt;code&gt;REVOKE&lt;/code&gt;. Self-verification runs the verifier through the same architecture as the actor, ratifying the destructive call with the same confidence that produced it. The &lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;corruption piece&lt;/a&gt; walks through the mechanism. Same model checking the same model is not a check.&lt;/p&gt;
&lt;h2 id="why-the-prompt-cant-bound-the-distribution"&gt;Why the prompt can&amp;rsquo;t bound the distribution
&lt;/h2&gt;&lt;p&gt;A prompt is more tokens. The system message, the developer instructions, the user turns, the tool responses all land in the same context window. They feed the same attention mechanism that produces the next-token probability. &amp;ldquo;Never run &lt;code&gt;DROP TABLE&lt;/code&gt;&amp;rdquo; shifts that probability toward continuations consistent with the rule. It does not remove the token from the vocabulary. It does not produce a hard zero on the path that emits it. Sampling has no off-switch. Production agents run at positive temperature, where every token keeps nonzero probability of being sampled. Even at temperature zero, the model takes the argmax over the distribution, and the argmax is whichever token the context tilted highest. The prompt shifts that ranking. It does not bound it.&lt;/p&gt;
&lt;p&gt;The model is also stateless. Every turn, the harness resends the entire conversation, and the &amp;ldquo;memory&amp;rdquo; the agent appears to have is the transcript being rebuilt on each call. Nothing in the weights retains the rule from turn 1 at turn 50. There is only a longer transcript with the rule somewhere in the middle, competing for attention weight against everything else. More tokens means more probability mass to spread and a smaller share for any single instruction. Long system prompts loaded with rules and exceptions are the worst case: each rule dilutes every rule already there. Keep the prompt short.&lt;/p&gt;
&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/" &gt;Corruption Is a Feature, Not a Bug&lt;/a&gt; walks through the architecture in detail. Across enough sessions, with enough varied phrasings, some context tilts the distribution far enough that the forbidden token wins the sample. The rate per session is small. Multiplied by the sessions a production agent runs, it becomes a count. The count is the incident, guaranteed in expectation.&lt;/p&gt;
&lt;p&gt;Adversarial inputs share the channel. Every document the agent reads, every tool response it parses, every user message lands in the same window as the system prompt. There is no privileged layer. Input that statistically reads as &amp;ldquo;the user wants this destructive action&amp;rdquo; can override the instruction that says don&amp;rsquo;t. Prompt injection is the named version. The unnamed version is conversation drift.&lt;/p&gt;
&lt;p&gt;Each new session starts fresh. If the guardrail lives in the prompt, every session re-establishes it from scratch.&lt;/p&gt;
&lt;p&gt;The honesty-suppression test in the corruption piece is the smallest reproducible demonstration. A single banned word, surfaced through every channel the harness exposes (CLAUDE.md, skills, system reminders, project memory), still leaks. Every more complex guardrail violates at a higher rate.&lt;/p&gt;
&lt;h2 id="what-lives-outside-the-prompt"&gt;What lives outside the prompt
&lt;/h2&gt;&lt;p&gt;A guardrail is something the agent cannot remove by re-reading its instructions. Six pieces, each catching a different failure class.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Scoped identities with minimum-necessary credentials.&lt;/strong&gt; The agent has its own database role, service account, and API keys. The role grants the minimum permission the task requires: read-only by default, explicit grants on the narrow write paths it actually needs. Revocation is one &lt;code&gt;DROP ROLE&lt;/code&gt; away. The agent cannot escalate by rephrasing its own context, because the credentials live in a layer the model cannot read.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;MCP and tool surfaces from trusted sources only.&lt;/strong&gt; An untrusted MCP server is a malicious tool the agent will call with the same confidence as a benign one. A public-registry MCP server from an unknown author is unsigned code from the internet, with the agent doing the executing. Trust belongs at the connection layer: allowlists, signed manifests, internal-only registries. A prompt that says &amp;ldquo;only use trusted tools&amp;rdquo; is the agent grading its own homework.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Harness hooks that intercept tool calls.&lt;/strong&gt; Claude Code fires shell commands on events like &lt;code&gt;PreToolUse&lt;/code&gt; and &lt;code&gt;PostToolUse&lt;/code&gt;. A &lt;code&gt;PreToolUse&lt;/code&gt; hook reads the tool name and arguments and returns allow or deny; the model never sees the decision. The pattern handles concrete bans the prompt cannot reliably enforce: blocking &lt;code&gt;Edit&lt;/code&gt; on &lt;code&gt;.env&lt;/code&gt; or &lt;code&gt;secrets/&lt;/code&gt;, blocking &lt;code&gt;Bash&lt;/code&gt; against regexes like &lt;code&gt;rm -rf&lt;/code&gt; or &lt;code&gt;DROP TABLE&lt;/code&gt;, blocking &lt;code&gt;Write&lt;/code&gt; to migration directories outside an explicit unlock. Codex&amp;rsquo;s approvals primitive is a narrower version of the same idea, and some harnesses expose nothing comparable, in which case this layer has to be built outside the harness.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Wire-level filtering between the agent and the database.&lt;/strong&gt; A SQL-aware proxy in front of the database parses every statement and blocks denylist matches: &lt;code&gt;DROP&lt;/code&gt;, &lt;code&gt;TRUNCATE&lt;/code&gt;, unqualified &lt;code&gt;DELETE&lt;/code&gt;, schema-modifying DDL outside an unlock window, queries that touch tables the agent&amp;rsquo;s role has no business reading. ProxySQL with query rules, pgBouncer with extensions, and custom proxies all sit here; commercial SQL-firewall products exist but the open-source space is thin. The same pattern applies one layer up: an MCP server or RPC layer you control exposes only validated operations rather than passing arbitrary SQL through. The agent never speaks raw SQL to production. It speaks to an interface that decides what reaches the wire.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Structured logs with prompt provenance.&lt;/strong&gt; Every tool call captured: input prompt, tool name, arguments, response, timestamp, agent identity. A pre-AI audit log captured the SQL and treated it as sufficient. The AI-era version captures the reasoning context that produced it, because the SQL alone is incomplete in any incident review. Corruption can surface months after the prompt that produced it.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Behavioral monitoring with anomaly alerts.&lt;/strong&gt; Rate limits per agent identity. Baselines for normal call volume, tables touched, read and write volume. Alerts on threshold crossings: a 100x increase in &lt;code&gt;DELETE&lt;/code&gt; calls, a sudden read of a table the agent has never touched, a write to a schema outside its usual scope. Agents are non-human users with their own behavioral baselines, and the reference frame is anomaly detection on user accounts in security tooling.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;None of these lives in the context window, which means the agent cannot route around them by being asked nicely. The credentials are checked by the database. The MCP allowlist is checked by the connection layer. The hooks run in separate processes. The proxy parses every statement before it reaches the database. The logs are written by the harness. The alerts are evaluated by a separate system. Every layer is enforced by something that does not sample from a probability distribution.&lt;/p&gt;
&lt;p&gt;Each layer is engineering work. On a small enough deployment, the cost exceeds the cost of an incident.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;Read-only agents, with a caveat. Analytics, query, chat. A read-only role at the database is the layer for write damage, but reads are not free: every row the agent fetches is sent to the model provider as part of the next prompt. A table holding API keys, customer PII, or internal hostnames is not safe to expose to a third-party-hosted model just because the agent cannot write. Either the role&amp;rsquo;s grants exclude those tables, a wire-level filter strips sensitive columns, or the agent runs against a sanitized snapshot.&lt;/p&gt;
&lt;p&gt;Toy environments. Playgrounds, scratch databases, demos. The whole point is that the agent can break things; guardrails are friction.&lt;/p&gt;
&lt;p&gt;Single-operator small teams where the agent is the operator&amp;rsquo;s autocomplete. The operator is the verification layer. The agent&amp;rsquo;s permissions are intentionally equivalent to the operator&amp;rsquo;s.&lt;/p&gt;
&lt;p&gt;Everyone else needs all six. Agents holding production credentials. Agents working against shared infrastructure. Agents wired into CI/CD. Agents reading and writing customer data.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;None of these layers is novel for staff engineers. Scoped credentials, vetted tool surfaces, request interception at every layer, audit logs, anomaly detection. Every one is standard practice for any system that touches production, except they tend to be applied to humans and to other software. The shift the AI era forces is treating the agent as a separate principal that needs its own version, and treating the prompt as something other than a security control.&lt;/p&gt;</description></item><item><title>Corruption Is a Feature, Not a Bug: Why LLMs Corrupt by Design</title><link>https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/</link><pubDate>Wed, 22 Apr 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/corruption-is-a-feature-not-a-bug-why-llms-corrupt-by-design/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Corruption Is a Feature, Not a Bug: Why LLMs Corrupt by Design" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Frontier LLMs corrupt at least 25% of delegated multi-step document work in lab conditions. The rate rises with document size and turn count, and tool use doesn&amp;rsquo;t help. Corruption is a property of the architecture, not a defect to be patched, and the only thing that closes the gap is a best-in-class domain expert at every checkpoint.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Microsoft Research has a number on it. &lt;a class="link" href="https://arxiv.org/abs/2604.15597" target="_blank" rel="noopener"
 &gt;Laban, Schnabel, and Neville&amp;rsquo;s &lt;em&gt;LLMs Corrupt Your Documents When You Delegate&lt;/em&gt;&lt;/a&gt; (arxiv 2604.15597, April 2026) ran the DELEGATE-52 benchmark across 52 professional domains (coding, crystallography, music notation, professional writing) against 19 frontier LLMs including Claude 4.6 Opus, GPT 5.4, and Gemini 3.1 Pro. Average corruption: 25% of document content by the end of long workflows. Tool use doesn&amp;rsquo;t fix it. Agentic harnesses don&amp;rsquo;t fix it. Larger documents and longer interactions make it worse, not better. The number doesn&amp;rsquo;t depend on which frontier model you pick.&lt;/p&gt;
&lt;h2 id="the-25-is-a-floor-not-a-ceiling"&gt;The 25% is a floor, not a ceiling
&lt;/h2&gt;&lt;p&gt;The benchmark is a controlled lab measurement against curated tasks with known ground truth. Real production has every reality catalogued in &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;What AI Gets Wrong About Your Database&lt;/a&gt;: undocumented conventions, polysemic columns, four-format date strings, JSON-as-schema, business logic in tribal knowledge, ten-year-old codebases with three &amp;ldquo;current&amp;rdquo; patterns for the same operation. The model in production reads from that impoverished signal, and the rate multiplies. The 25% is what you get on a good day on clean data. Production is not a good day.&lt;/p&gt;
&lt;h2 id="the-version-doesnt-matter---corruption-is-a-feature"&gt;The version doesn&amp;rsquo;t matter - corruption is a feature
&lt;/h2&gt;&lt;p&gt;Claude Opus 4.7 is the latest as of writing. DELEGATE-52 measured 4.6, GPT 5.4, Gemini 3.1 Pro. The next generation will measure at the same floor. Not because the labs aren&amp;rsquo;t trying (they are) but because the corruption isn&amp;rsquo;t a defect to patch. It&amp;rsquo;s the property you bought when you bought &amp;ldquo;language model.&amp;rdquo; The same mechanism that makes the model useful (generalizing from a training distribution to plausible novel output) is the one that makes it corrupt your document (generalizing from a training distribution to plausible novel output that doesn&amp;rsquo;t match your specific facts). You can&amp;rsquo;t fix one without losing the other.&lt;/p&gt;
&lt;p&gt;The framing this post takes is that LLMs are a probability machine first and an intelligence-shaped artifact second. That&amp;rsquo;s a stance, not an uncontested fact, but the engineering implications of the post all follow from taking the first reading seriously.&lt;/p&gt;
&lt;h2 id="the-obvious-fixes-that-dont-work"&gt;The obvious fixes that don&amp;rsquo;t work
&lt;/h2&gt;&lt;p&gt;The reflex when the rate is 25% is to reach for the things that usually fix software defects. None of them touch the floor:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&amp;ldquo;Use a better model.&amp;rdquo;&lt;/strong&gt; The benchmark already measured the frontier. Same rate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&amp;ldquo;Add tools, RAG, fine-tuning.&amp;rdquo;&lt;/strong&gt; Tool use doesn&amp;rsquo;t change the rate. RAG narrows the prior, but the same sampling mechanism draws from it. Fine-tuning shifts the distribution; it doesn&amp;rsquo;t add deterministic constraints.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&amp;ldquo;Add agent self-verification.&amp;rdquo;&lt;/strong&gt; The verifier is the same architecture reading the same training distribution as the generator. It will ratify the corruption with the same confidence the generator produced it with.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&amp;ldquo;Add more context.&amp;rdquo;&lt;/strong&gt; &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;What AI Gets Wrong About Your Database&lt;/a&gt; already covered this. More context lowers the rate, doesn&amp;rsquo;t drive it to zero. The hallucination floor is structural.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These aren&amp;rsquo;t bad ideas. They lower the rate from terrible to bad. They don&amp;rsquo;t make delegation safe.&lt;/p&gt;
&lt;h2 id="why-this-is-structural-the-mechanism"&gt;Why this is structural: the mechanism
&lt;/h2&gt;&lt;p&gt;The mechanism is worth understanding because it&amp;rsquo;s what tells you why &amp;ldquo;use a better model&amp;rdquo; doesn&amp;rsquo;t move the floor.&lt;/p&gt;
&lt;p&gt;Start with embeddings. The model &amp;ldquo;understands&amp;rdquo; &lt;code&gt;users.deleted_at&lt;/code&gt; as a vector position adjacent to other &lt;code&gt;deleted_at&lt;/code&gt; columns it saw during training. There is no concept of your soft-delete convention, your tenant filter, the incident your team had last quarter, or the rule you wrote into the catalog comment two months ago. The vector is a fingerprint of what tokens like that one tend to appear next to in a billion training documents, not a fact set the model can check against.&lt;/p&gt;
&lt;p&gt;Attention works the same way. Each output token is a weighted blend of every other token in context, with the weights being learned similarity scores. The model isn&amp;rsquo;t looking up &amp;ldquo;the right answer for this schema.&amp;rdquo; It&amp;rsquo;s computing a weighted average of what tokens like this one tend to be followed by tokens like that one in its training distribution. Correctness is the special case where the distribution happens to be sharply peaked on the correct token.&lt;/p&gt;
&lt;p&gt;Generation pulls all of that into a sampling step. Every token is a draw from a probability distribution. When training data is dense and consistent for the topic, the distribution is sharp; but a sharp distribution is reliable token-relationship probability, not knowledge of the answer. The tokens in that region of the data point reliably to a particular continuation, and the relationships are co-occurrence statistics with no internal check against reality. When the underlying relationship happens to match the world, the guess looks right. When it doesn&amp;rsquo;t (a popular misconception in the training corpus, an outdated convention, a pattern typical of training data but not of your specific case) the guess is confidently wrong with the same calibration. When training data is sparse, contradictory, or local to your codebase, the distribution flattens, the guess gets noisier, and the calibration of the model&amp;rsquo;s confidence stays the same. Nothing in the architecture says &amp;ldquo;I don&amp;rsquo;t know.&amp;rdquo; It says &amp;ldquo;this token has the highest probability among my distribution,&amp;rdquo; even when the distribution is barely above random, or sharp on a relationship that doesn&amp;rsquo;t hold for your case.&lt;/p&gt;
&lt;p&gt;To collapse those three steps into the operation that actually runs: every token is a vector, a position in a high-dimensional space, typically thousands of dimensions (4,096 in some models, 12,288 in others). Similarity between two tokens is the dot product (or cosine distance) of their vectors. Attention computes its weights by taking those similarity scores between the current position and every prior token in context, then softmax-normalizing. The probability of the next token is the dot product of the model&amp;rsquo;s predicted direction against every candidate token&amp;rsquo;s vector in the vocabulary, divided through a softmax to produce a distribution. Every probability you read out of the model is a distance computation between vectors in that high-dimensional space. Understanding is position. Probability is geometric proximity. There&amp;rsquo;s no step in the pipeline where knowledge enters; only matrix multiplications and a normalizing function.&lt;/p&gt;
&lt;p&gt;DELEGATE-52&amp;rsquo;s 25% is the rate at which the distribution flattened across 52 domains&amp;rsquo; edge cases and the sampling collapsed to plausible-sounding hallucination. The confidence reading stayed identical to when the model was right. This is &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;Part 1&amp;rsquo;s &amp;ldquo;confidence is anti-signal&amp;rdquo;&lt;/a&gt; restated at the architecture level: confidence and correctness are produced by different mechanisms, neither tied to the other.&lt;/p&gt;
&lt;h2 id="why-best-in-class-sme-is-the-load-bearing-safeguard"&gt;Why best-in-class SME is the load-bearing safeguard
&lt;/h2&gt;&lt;p&gt;Humans don&amp;rsquo;t operate this way. A crystallographer knows the unit cell parameters have to satisfy specific symmetry constraints, not because she&amp;rsquo;s seen a million similar structures, but because the constraints follow from a small set of facts she can verify against. A senior database engineer knows the soft-delete convention because she wrote it. A composer knows the chord progression doesn&amp;rsquo;t resolve because the leading tone wasn&amp;rsquo;t raised. That knowledge is symbolic, propositional, traceable to evidence the human can produce on demand. It isn&amp;rsquo;t a probability distribution.&lt;/p&gt;
&lt;p&gt;That is the gap an SME closes. Not &amp;ldquo;any reviewer with a checklist&amp;rdquo;; a generalist reviewer can&amp;rsquo;t tell when the model has silently corrupted the symmetry constraints, the soft-delete predicate, or the leading-tone rule. The corruption looks plausible because the model&amp;rsquo;s job is producing plausible output. Catching it requires someone who holds the actual constraints in their head and can check the model&amp;rsquo;s output against them. The cheaper the SME, the more corruption ships.&lt;/p&gt;
&lt;p&gt;The labor-market reading of this is already visible. &lt;a class="link" href="https://www.ibm.com/think/news/entry-level-roles-get-reset-ai" target="_blank" rel="noopener"
 &gt;IBM announced in February 2026 it would triple US entry-level hiring&lt;/a&gt;, explicitly because the AI era hollowed out the rote tasks that used to fill junior roles and left the load-bearing work (judgment, customer interaction, oversight of automated systems) needing humans who grow into it. The pipeline argument is unforgiving: cut juniors to capture the AI-productivity dividend, save short-term, and starve the senior layer the next decade of work depends on. The companies treating today&amp;rsquo;s juniors as a long bet on the experts they&amp;rsquo;ll become are reading the architecture honestly. The ones cutting them to bank the LLM savings are paying down the pipeline their competitors are building.&lt;/p&gt;
&lt;p&gt;The supply side is tightening on both ends. The senior tier is retiring out (the engineers who built the soft-delete conventions, the schema histories, the production-incident memory) and that institutional knowledge isn&amp;rsquo;t transferring into a probability distribution any model can sample from. On the formation side, &lt;a class="link" href="https://www.anthropic.com/research/AI-assistance-coding-skills" target="_blank" rel="noopener"
 &gt;Anthropic&amp;rsquo;s own research shows engineers using AI assistance score 50% on comprehension quizzes about the code they shipped, against 67% for engineers writing the same code unaided&lt;/a&gt; - a 17-point gap. The skill-formation loop that turns juniors into SMEs over a decade (write, struggle, debug, internalize) gets shortcut by tooling that produces working code without the struggle. Companies that don&amp;rsquo;t actively design against both effects get the worst of three pressures: SMEs retiring, juniors not deepening, and an architecture that has no internal substitute for either.&lt;/p&gt;
&lt;p&gt;The unintuitive recommendation that follows: don&amp;rsquo;t fire the humans you have. The SME labor market will tighten faster than LLM tooling can replace what SMEs do. Supply is shrinking on both ends, the architecture has no substitute, and today&amp;rsquo;s senior engineer is cheap relative to their replacement cost in three to five years. Companies banking the LLM productivity dividend by cutting senior staff are trading short-term margin for a much steeper rehiring bill against a constrained future market. The math will look obvious in retrospect. It doesn&amp;rsquo;t look obvious now because the LLM line item lands on the income statement before the SME-shortage bill arrives.&lt;/p&gt;
&lt;p&gt;This is why &amp;ldquo;best-in-class&amp;rdquo; is load-bearing in the title. A junior with a checklist runs the same architecture-level pattern-matching the model does. Recognizes things that look right, doesn&amp;rsquo;t catch silent semantic drift. A top-of-class SME has the constraint set internalized to the point that the wrong answer feels wrong, even when the surface looks correct. That feeling is the safeguard the architecture cannot provide.&lt;/p&gt;
&lt;h2 id="the-system"&gt;The system
&lt;/h2&gt;&lt;p&gt;Don&amp;rsquo;t delegate end-to-end. Decompose work into chunks small enough that an SME can verify each one in minutes. Checkpoint between chunks. Route each checkpoint to the SME whose domain it&amp;rsquo;s in. Treat every chunk as 25%-floor untrusted by default. Don&amp;rsquo;t trust agentic chains to self-verify (the verifier reads from the same training distribution as the generator). Don&amp;rsquo;t trust LLM-judge eval as a release gate (&lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/" &gt;Part 2 of the testing series&lt;/a&gt; covered why; the architectural reason is in the mechanism above). The system is decomposition plus checkpoints plus SMEs, not a better model and not a better prompt.&lt;/p&gt;
&lt;p&gt;The cost is real. SMEs are expensive, the workflow is slower, and the temptation to skip checkpoints when the early ones look fine is constant. The cost of the alternative (silent 25%-floor corruption layered through a long workflow, surfaced six months later when the data has propagated past the recovery window) is much higher and structurally harder to detect. The math is the math the testing series already laid out: catching corruption pre-deployment is a fraction of the cost of finding it after.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Drafts you&amp;rsquo;ll discard.&lt;/strong&gt; Brainstorming, throwaway code, content the human will rewrite anyway. The model is generating a starting point, not delegated output.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The user is the SME.&lt;/strong&gt; A senior database engineer using AI to draft SQL she&amp;rsquo;ll review line-by-line is using the model as autocomplete, not as delegation. The 25% is irrelevant because she&amp;rsquo;s the verification layer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Low-stakes, recoverable work.&lt;/strong&gt; A typo in a personal email isn&amp;rsquo;t a 25% corruption event you need to system-design around.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bounded, well-trodden problems.&lt;/strong&gt; Generating boilerplate in a popular language with a well-documented framework is the dense-distribution sweet spot. The rate is much lower because the prior is sharp.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Proof-of-concept and rapid-feedback work.&lt;/strong&gt; &amp;ldquo;Does this idea work at all&amp;rdquo; needed in minutes. The 25% floor is the right trade because the output is a directional signal, not production code; the cost of being wrong is &amp;ldquo;we tried, didn&amp;rsquo;t pan out.&amp;rdquo;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The article is about the rest - production work where corruption is invisible, expensive to fix, and the team is treating the model as a co-author instead of a guess machine.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Calling the model &amp;ldquo;intelligence&amp;rdquo; is the framing that gets engineers in trouble. Intelligence implies a knowing entity that holds facts, checks them against evidence, and tells you when it doesn&amp;rsquo;t know. The architecture has none of those properties. It has a learned distribution and a sampling procedure. The output is a guess every time, and the guess is well-calibrated only where the training data was dense and consistent - precisely not where your specific codebase, your specific schema, or your specific domain conventions live.&lt;/p&gt;
&lt;p&gt;The 25% floor is what that guarantees, in numbers. Versions don&amp;rsquo;t move it. Tools don&amp;rsquo;t move it. Bigger context doesn&amp;rsquo;t drive it to zero. The only thing that closes the gap between the architecture and the work is a human who knows the domain, checking the output against constraints the architecture can&amp;rsquo;t represent.&lt;/p&gt;
&lt;p&gt;Treat the model as a probability machine and the engineering decisions get easier. Decompose. Checkpoint. Put the best SME you have on each domain. Build the testing layer the way &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;the testing series&lt;/a&gt; describes. Stop expecting the next model to fix it.&lt;/p&gt;</description></item><item><title>How Teams Actually Finish What They Start, Part III: A Working Responder Rotation</title><link>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-iii-a-working-responder-rotation/</link><pubDate>Tue, 17 Mar 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-iii-a-working-responder-rotation/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post How Teams Actually Finish What They Start, Part III: A Working Responder Rotation" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;For teams whose week is operational by nature (SRE, DevOps, platform, database and storage reliability, anyone whose sprint work coexists with a steady stream of alerts and partner-team asks), a weekly responder rotation breaks silos only when the operational rules force the responder to actually do the work, not route it. Five rules carry the load: a fixed resort order (runbooks → docs → LLM → SME), SMEs as advisors rather than handoff targets, tiered routing for alerts and asks so the responder isn&amp;rsquo;t drowning, improvement tickets that shrink the rotation&amp;rsquo;s load over time, and tech implementation as the only valid mechanism for easing the role.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A team has a responder rotation. The responder&amp;rsquo;s name is in the channel topic every Monday. Six months in, the database alert that pages at 2am still goes to Sarah because she wrote the schema in 2024 and nobody else has dug into it. The Kafka partition imbalance at 3pm still goes to Marcus. The Redis eviction issue still goes to whoever has been on the team longest. The responder forwarded all three to the original owners within two minutes of the page. The rotation existed. The silos held. The responder name on the calendar was a routing layer, not a learning one.&lt;/p&gt;
&lt;p&gt;That is the failure mode the rest of this post is about. The rotation is necessary but not sufficient. What separates a working rotation from a name on a calendar is a small set of operational rules that force the responder to actually own the work, not just route it.&lt;/p&gt;
&lt;p&gt;The reflex is to write down a clearer rule: the responder handles everything, no exceptions, never escalate. That fails on first contact with a real production page. The 2am Kafka issue is genuinely faster to resolve if Marcus picks up. The customer is on the line. The deadline is tomorrow. Saying &amp;ldquo;no, the responder must learn&amp;rdquo; costs the company money this week and won&amp;rsquo;t carry next week either, because the next 2am page also has a real-world reason it should go to the specialist. &amp;ldquo;No escape&amp;rdquo; is not the rule. The rule that holds is a different shape.&lt;/p&gt;
&lt;h2 id="the-five-rules"&gt;The five rules
&lt;/h2&gt;&lt;p&gt;Each rule sits below the prompt the team gives itself, in a layer the team has to defend actively. None is novel on its own. The combination is what makes the rotation produce the silo-breaking it claims.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Resort order: runbooks, then docs, then internal LLM, then SME.&lt;/strong&gt; Before the responder asks a human, they work through the documented self-serve options in order. Runbooks for known incidents, docs for system understanding, an internal LLM or RAG tool for synthesis across both, and only after those run out, the SME. The point is not to ban the SME. It is to make sure the responder has tried the cheaper rungs first, so that when the SME does get pulled in, the conversation starts from &amp;ldquo;I read the runbook section on this and tried X, here is what I&amp;rsquo;m seeing&amp;rdquo; instead of &amp;ldquo;what is this and what do I do.&amp;rdquo;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;SMEs advise, they don&amp;rsquo;t take handoff.&lt;/strong&gt; When the responder consults the SME, the conversation produces a path forward, not a transfer. The SME explains the issue, suggests the next steps, and goes back to their declared work. The responder owns the ticket through resolution and writes the resolution into the runbook. This is the rule that turns &amp;ldquo;ask Marcus&amp;rdquo; into knowledge transfer instead of work transfer.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Alert and ask routing tiered by urgency and source.&lt;/strong&gt; The responder watches a high-signal channel actively for prod alerts and urgent asks, skims a separate channel for non-prod, and works a Jira queue between fires for non-urgent automated signals (failed nightly backup, config drift, flag mismatch). Asks from other engineers, especially storage-team work like Kafka or Redis, go to a live conversation channel rather than a ticket queue; tickets get filed downstream when the conversation produces work worth tracking, they are not the entry point. The detailed channel structure, severity policy, and alert-tuning discipline are their own subject for a future installment in this series.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Improvement tickets generate themselves.&lt;/strong&gt; Every recurring incident produces a ticket. A noisy alert that fired three times this quarter gets a tuning ticket. A runbook gap the responder hit gets a doc-update ticket. An LLM that gave a confident wrong answer gets a source-update ticket. The rule works because the role concentrates pain on one person for five days: the responder absorbs what is normally scattered across the team, and the person paged at 2am is the same person who will write the runbook on Wednesday. If the same fire happens twice in a quarter and no improvement ticket exists, the rotation is wallpapering toil instead of reducing it. The improvement queue is also the team&amp;rsquo;s most honest signal that the rotation is working: if the queue is shrinking and the runbooks are growing, the responder is producing the cross-training the rotation promised.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Reduce responder load only through tech, never through policy carve-outs.&lt;/strong&gt; As the rotation matures and the team wants to make the responder&amp;rsquo;s week easier, the only valid mechanism is technical implementation: new automation, better runbooks, alert tuning, self-service tools for partner teams who keep asking the same questions. Carving out categories back to the SME, lowering the bar for what the responder is expected to handle, or routing painful asks somewhere off-stage all shift toil rather than removing it. Tech implementation takes the toil out of the system entirely. Every responder week that produces a real engineering ticket reduces what the next rotation has to do. Policy carve-outs do the opposite, quietly.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The SME who keeps picking up is the failure mode&lt;/strong&gt;
 &lt;div&gt;Rule 2 fails more often than any of the other four. The first time the responder pings the SME, the SME thinks &amp;ldquo;I&amp;rsquo;ll just fix this one.&amp;rdquo; The second time, it is a habit. The fix is on the SME, not the responder: when consulted, the right response is &amp;ldquo;this belongs in the runbook&amp;rdquo; or &amp;ldquo;this should be automated,&amp;rdquo; never &amp;ldquo;let me handle it.&amp;rdquo; Every ask that reaches the SME is evidence of a gap the team should close.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;What the five rules buy for the rest of the team is a clean focus week. The non-responder ICs are not in the partner-team channel triaging asks, not fielding DMs about Kafka topics or Redis schema, not on the other end of the 2am page. They are doing the work they declared on Monday, with the morning declaration and 3pm sync from &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-ii-a-two-stage-standup/" &gt;Part II&lt;/a&gt; structuring their day, and they are finishing what they started. A morning declaration is a goal that four hours of unscheduled interruption will eventually destroy. The rotation is what protects the declaration long enough for the IC to actually finish it.&lt;/p&gt;
&lt;p&gt;The cost of all five is real. Each requires discipline that is easier to skip than to keep. The SME who always picks up will keep picking up unless the team explicitly stops the handoff pattern. The improvement-ticket discipline only works if there is a half-hour each rotation set aside to file them, and rotations under heavy load lose that half-hour first. The tiered routing requires actively maintaining alert filters and channel topology that drift fast. The tech-implementation rule asks the team to file real engineering work after each rotation, which competes with sprint commitments and slips when sprints get tight. None of this is one-time setup. The rules are an active practice the team defends the same way it defends the 3pm sync slot from Part II.&lt;/p&gt;
&lt;h2 id="handoff-at-the-week-boundary"&gt;Handoff at the week boundary
&lt;/h2&gt;&lt;p&gt;The responder&amp;rsquo;s week ends Friday afternoon. Three categories of things sit in the queue.&lt;/p&gt;
&lt;p&gt;Open incidents and paused investigations get explicitly handed off in a written note: what is the state, what is the next action, what was already tried, who has been pulled in. The note is short. Half a page is plenty. Bullet form is fine. The rule is not that everything is exhaustively documented; it is that nothing is silently dropped.&lt;/p&gt;
&lt;p&gt;Closed work gets closed, with whatever runbook update or follow-up ticket the resolution produced. Improvement work the responder identified but didn&amp;rsquo;t get to becomes a backlog ticket, scheduled into someone&amp;rsquo;s planned-work queue rather than left to the next responder to either pick up or ignore.&lt;/p&gt;
&lt;p&gt;The next responder picks up Monday morning with full context on what is actually inbound. No ramp-up day spent figuring out what the previous week was working on. No ticket that quietly got dropped at the rotation boundary because nobody owned it across the weekend.&lt;/p&gt;
&lt;h2 id="what-the-responder-does-not-handle"&gt;What the responder does not handle
&lt;/h2&gt;&lt;p&gt;A working rotation is honest about specialization. Some categories of work genuinely require the specialist, and naming them upfront prevents the format from feeling like a fiction.&lt;/p&gt;
&lt;p&gt;Security incidents. Corner-case data-recovery operations. Load-bearing decisions that require historical context the rotation can&amp;rsquo;t reasonably build (the schema choice from 2022 that has shaped every query since). The responder still owns the ticket and stays in the loop, but the actual work happens with the specialist driving and the responder learning. Over a quarter, the responder may move into the specialist column for some of these. Some they won&amp;rsquo;t, and that&amp;rsquo;s fine.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Carve-outs need a budget&lt;/strong&gt;
 &lt;div&gt;Three named carve-outs is honest about specialization. Thirty is theater wearing a costume. Keep the list short and explicit so it cannot expand quietly over a quarter into &amp;ldquo;the rotation only handles the easy stuff.&amp;rdquo;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The structure earns less than its cost when interrupt volume is too low. If the team gets pinged twice a day and most of those are easily handled, the rotation is a structure without a job. Volume is the test, not team size or specialization. A three-person team with heavy operational load still benefits from concentrating interruptions on one person while the other two ship sprint work; a ten-person team with light load doesn&amp;rsquo;t. A team of four MySQL DBAs benefits more from rotation, not less, because everyone can handle everything; uniform specialization makes the rotation easier, not harder. The format earns its cost when interrupt volume is high enough that focused weeks are otherwise impossible.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;A working responder rotation has visible evidence: improvement tickets are filed every rotation, the rotation&amp;rsquo;s interrupt volume is trending down quarter over quarter, the runbook count and quality is going up, and at handoff Friday the next responder receives a written note rather than a tribal-knowledge briefing. None of that is rocket science. All of it requires the team to defend the rules every week against the easier path of letting the SME pick up.&lt;/p&gt;
&lt;p&gt;The teams that abandon the rotation usually didn&amp;rsquo;t abandon it because the rotation was wrong. They kept the calendar entry and dropped the rules. The SMEs kept picking up, the improvement tickets stopped getting filed, and the rotation became a name in a channel topic that nobody was treating as load-bearing.&lt;/p&gt;</description></item><item><title>Designing Partitioning You Don't Have to Babysit</title><link>https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/</link><pubDate>Fri, 06 Mar 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Designing Partitioning You Don't Have to Babysit" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Partition by the primary key, not by &lt;code&gt;created_at&lt;/code&gt;, and let a background service manage boundaries based on observed growth. Queries keep using the keys they already have, partition pruning works automatically, and the partition column never leaks into application code. The same &amp;ldquo;service watches and adjusts&amp;rdquo; pattern applies to hash and list partitioning with different operations.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The orders dashboard started loading slowly the week after the partitioning deploy, and the team&amp;rsquo;s first instinct is to blame the new index strategy. The actual culprit shows up in &lt;code&gt;EXPLAIN&lt;/code&gt;: thirty-six lines of &lt;code&gt;Partitions: orders_p2025_01, orders_p2025_02, ...&lt;/code&gt; on a query that&amp;rsquo;s just &lt;code&gt;SELECT * FROM orders WHERE id = 12345&lt;/code&gt;. The plan reads every partition because the WHERE clause doesn&amp;rsquo;t include &lt;code&gt;created_at&lt;/code&gt;, and &lt;code&gt;created_at&lt;/code&gt; is the partition key. The lookup that used to be one index probe is now thirty-six.&lt;/p&gt;
&lt;p&gt;The proposed fix is the one that always gets proposed: add &lt;code&gt;created_at &amp;gt;= '2024-11-01'&lt;/code&gt; to the dashboard query. It works. The plan drops to one partition. Then the audit page does the same thing, then the admin tool, then the migration script. Three months later there&amp;rsquo;s an internal lint rule that flags any &lt;code&gt;SELECT FROM orders&lt;/code&gt; without a date filter, and code reviews include &amp;ldquo;did you add the partition filter?&amp;rdquo; as a standard check. The partition key has stopped being a storage decision and become a contract every query has to honor. Forgetting still produces no error. Just slowness.&lt;/p&gt;
&lt;h2 id="the-partition-key-problem"&gt;The partition key problem
&lt;/h2&gt;&lt;p&gt;Both PostgreSQL and MySQL require the partition key to be part of any primary key or unique constraint on the table. That rule exists for correctness: if the primary key didn&amp;rsquo;t include the partition key, the database couldn&amp;rsquo;t enforce uniqueness without scanning every partition.&lt;/p&gt;
&lt;p&gt;The consequence is that if you want to partition by &lt;code&gt;created_at&lt;/code&gt;, you can&amp;rsquo;t just have &lt;code&gt;PRIMARY KEY (id)&lt;/code&gt; anymore. You need &lt;code&gt;PRIMARY KEY (id, created_at)&lt;/code&gt;. The date column is now part of the primary key whether your application needed it to be or not.&lt;/p&gt;
&lt;p&gt;The more subtle cost is that &lt;code&gt;id&lt;/code&gt; is no longer unique in the eyes of the database. Uniqueness is enforced on the tuple &lt;code&gt;(id, created_at)&lt;/code&gt;: the database will cheerfully accept two rows with the same &lt;code&gt;id&lt;/code&gt; as long as they have different timestamps. The application probably still treats &lt;code&gt;id&lt;/code&gt; as unique, but nothing in the schema guarantees it. And you can&amp;rsquo;t recover the guarantee with a separate &lt;code&gt;UNIQUE (id)&lt;/code&gt; constraint: both MySQL and PostgreSQL require every unique constraint on a partitioned table to include the partition key columns. The uniqueness property has effectively been traded away.&lt;/p&gt;
&lt;p&gt;This isn&amp;rsquo;t purely cosmetic; it changes the query plans the optimizer is willing to generate:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;With &lt;code&gt;PRIMARY KEY (id)&lt;/code&gt;, &lt;code&gt;WHERE id = 1&lt;/code&gt; is a constant-time lookup. MySQL&amp;rsquo;s EXPLAIN shows this as the &lt;code&gt;const&lt;/code&gt; access type; the optimizer knows exactly one row matches and the executor stops after finding it. Joins on &lt;code&gt;id&lt;/code&gt; are &lt;code&gt;eq_ref&lt;/code&gt;, the fastest join access type.&lt;/li&gt;
&lt;li&gt;With &lt;code&gt;PRIMARY KEY (id, created_at)&lt;/code&gt;, the same query becomes a &lt;code&gt;ref&lt;/code&gt; lookup: a prefix scan on the leftmost index column that could, as far as the database is concerned, return multiple rows. Joins that used to be &lt;code&gt;eq_ref&lt;/code&gt; become &lt;code&gt;ref&lt;/code&gt;. Cardinality estimates fall back to index statistics instead of the guaranteed &amp;ldquo;one row&amp;rdquo; assumption, which can push the optimizer toward worse plans further up the query tree.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To get the old &lt;code&gt;const&lt;/code&gt; plan back, every lookup has to spell out the full primary key:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Was a const lookup, now a ref lookup (one of potentially many rows)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Back to const, but only if the caller knows the created_at
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-04-01 12:34:56&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;That&amp;rsquo;s the same leakage as partition pruning, from a different angle: the partition key has forced its way into queries that had nothing to do with dates, first to get pruning and now to get single-row access.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Before partitioning
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DATETIME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- After partitioning by month
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DATETIME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- created_at forced into the PK
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;RANGE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TO_DAYS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p202601&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TO_DAYS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-02-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p202602&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TO_DAYS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-03-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;At this point everything still works. The table accepts inserts, queries return correct results, and the partition boundaries exist. The problem shows up the first time someone runs a query that doesn&amp;rsquo;t include &lt;code&gt;created_at&lt;/code&gt; in the WHERE clause.&lt;/p&gt;
&lt;h2 id="partition-pruning-only-works-if-you-ask-for-it"&gt;Partition pruning only works if you ask for it
&lt;/h2&gt;&lt;p&gt;Partition pruning is the optimization that makes partitioning worth doing. When a query&amp;rsquo;s WHERE clause restricts the partition key, the database can skip partitions that can&amp;rsquo;t possibly match. A query for last week&amp;rsquo;s orders only reads the one or two partitions that contain last week&amp;rsquo;s data.&lt;/p&gt;
&lt;p&gt;That optimization depends on the partition key appearing in the WHERE clause. A query that filters on anything else doesn&amp;rsquo;t get pruned; it scans every partition.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- This query scans every partition. There are 36 of them.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;12345&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- This one prunes to a single partition
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;12345&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-03-01&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-04-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The first query is the kind of lookup that happens constantly: fetch an order by its primary key. On a non-partitioned table, it&amp;rsquo;s a single index seek. On a partitioned table where the pruning key isn&amp;rsquo;t in the WHERE clause, it&amp;rsquo;s a separate index probe against every partition: 36 index lookups instead of one. Still fast in absolute terms, but much worse than the non-partitioned version, which is the opposite of why partitioning was introduced.&lt;/p&gt;
&lt;p&gt;The &amp;ldquo;fix&amp;rdquo; teams usually land on is to add the partition key to every query that touches the table. That&amp;rsquo;s a leaky abstraction. A storage decision is now a contract with every caller: new code has to remember the partition filter, old code has to be audited, the ORM has to be configured around it.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;No error, just slowness&lt;/strong&gt;
 &lt;div&gt;A query that should prune but doesn&amp;rsquo;t still returns correct results. The plan just scans every partition. No exception, no warning, no flag in the application logs, only an &lt;code&gt;EXPLAIN&lt;/code&gt; that nobody reads until a dashboard times out. Most teams discover the failure by reviewing slow-query logs after a partition deploy, not from anything the database surfaces during query execution.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="static-partition-boundaries-dont-age-well"&gt;Static partition boundaries don&amp;rsquo;t age well
&lt;/h2&gt;&lt;p&gt;The other thing that tends to go wrong is hardcoding partition boundaries at table creation time. The initial layout reflects whatever the team&amp;rsquo;s growth projection looked like at that moment. Six months later the traffic pattern has changed, some partitions are 10x larger than others, and the &lt;code&gt;p_future&lt;/code&gt; catch-all partition is holding half the table.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Defined at creation: looks reasonable
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2026_q1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2026_q2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Six months later: growth accelerated, p_future is now the entire active workload
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAXVALUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- 800M rows and growing
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Manually splitting and rebalancing partitions is operational work nobody wants to own. It requires scheduling maintenance windows, running &lt;code&gt;ALTER TABLE ... REORGANIZE PARTITION&lt;/code&gt; against tables that might be hundreds of gigabytes, coordinating with application teams, and not making a mistake. It tends not to happen until there&amp;rsquo;s a performance incident, and at that point the fix is expensive.&lt;/p&gt;
&lt;h2 id="the-shape-of-the-better-approach"&gt;The shape of the better approach
&lt;/h2&gt;&lt;p&gt;The primary key already exists. For tables using &lt;code&gt;BIGINT AUTO_INCREMENT&lt;/code&gt;, it&amp;rsquo;s monotonically increasing: newer rows have larger IDs. That&amp;rsquo;s the property range partitioning needs. The primary key is the partition key.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DATETIME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;RANGE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p0001&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p0002&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p0003&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAXVALUE&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Every query that filters by &lt;code&gt;id&lt;/code&gt; (which is most of them) gets partition pruning for free, with no changes to application code. Range queries by ID prune across a small number of partitions. Point lookups prune to exactly one. The primary key is already in every WHERE clause that matters, because it&amp;rsquo;s the primary key.&lt;/p&gt;
&lt;p&gt;The trade-off is that partition boundaries aren&amp;rsquo;t directly defined by time anymore, which looks like it breaks time-based retention. In practice this is less of a trade-off than it looks; the point of partitioning often isn&amp;rsquo;t retention but keeping index sizes manageable, making maintenance operations cheap, and bounding the blast radius of a bad query. When retention is a goal, boundaries can still be chosen to align with time. They just get picked at DDL time by the partitioner service, rather than baked into the schema. See &lt;a class="link" href="#time-aligned-boundaries-without-a-date-in-the-key" &gt;Time-aligned boundaries without a date in the key&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="automating-range-partition-management"&gt;Automating range partition management
&lt;/h2&gt;&lt;p&gt;Everything up to this point assumes range partitioning: partitions defined by continuous boundaries on an ordered value (an ID range, a date range). The operational work is mechanical: watch the active partition fill up, split the &lt;code&gt;MAXVALUE&lt;/code&gt; catch-all into a new bounded partition before that happens, and drop partitions that have fallen past the retention threshold. A small service running on a schedule is enough to keep the layout healthy. The hard part isn&amp;rsquo;t the logic, it&amp;rsquo;s doing it safely: running DDL against a large table without locking out writes, handling partial failures, and recovering cleanly if the service crashes mid-operation.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Split the catch-all partition into a new bounded partition + new catch-all
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- This is the operation the service runs periodically
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;REORGANIZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p0037&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3700000000&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAXVALUE&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;REORGANIZE PARTITION&lt;/code&gt; on an empty catch-all partition is fast; there&amp;rsquo;s nothing to move. If you split the catch-all before any rows land above the split point, the operation is metadata-only. The service&amp;rsquo;s job is to stay ahead of the write workload: split the catch-all when it&amp;rsquo;s still small or empty, not when it&amp;rsquo;s already holding hundreds of millions of rows.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;What makes the service tricky in production&lt;/strong&gt;
 &lt;div&gt;The logic is a couple of DDL statements. The hard parts are everything around them: not locking out writes during the &lt;code&gt;REORGANIZE&lt;/code&gt;, surviving a service crash mid-DDL (idempotency on retry), handling concurrent migration tooling that&amp;rsquo;s also taking &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; on the table, and having a clear runbook for &amp;ldquo;the service has stalled and the catch-all is now 200M rows, what do we do.&amp;rdquo; Production-grade partitioners usually spend more code on the operations bracket than on the DDL itself.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There&amp;rsquo;s no single right target; it depends on what&amp;rsquo;s driving the partitioning in the first place. If the goal is keeping the OLTP working set small via retention, the boundary spacing is a business decision: how long does the data need to stay queryable in the hot store, one year, seven years, somewhere in between. If the goal is performance, sizing each partition so its indexes fit comfortably in memory is a reasonable rule of thumb, provided there&amp;rsquo;s no significant key skew concentrating reads or writes on a single partition. The service can be configured against either target and adjust boundary spacing based on observed growth.&lt;/p&gt;
&lt;h3 id="time-aligned-boundaries-without-a-date-in-the-key"&gt;Time-aligned boundaries without a date in the key
&lt;/h3&gt;&lt;p&gt;Partitioning by &lt;code&gt;id&lt;/code&gt; doesn&amp;rsquo;t mean giving up time-based boundaries; it just means choosing them after the fact. The service can run a single query against the live table to find the ID boundary for any point in time:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Where was the ID pointer at the start of March?
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-03-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- -&amp;gt; 3700842139
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;That value becomes the upper bound for the next bounded partition. The catch-all stays above it, and future partitions get cut at time-aligned ID boundaries:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Partition is still defined by ID range, but chosen to align with a month boundary
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;REORGANIZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2026_03&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3700842140&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_future&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LESS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MAXVALUE&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The resulting partition &lt;code&gt;p2026_03&lt;/code&gt; contains roughly all orders from March 2026, but &lt;code&gt;created_at&lt;/code&gt; never appears in the primary key, never needs to be in any WHERE clause to get pruning, and never leaks into application code. The date column is used once, at boundary-creation time, by the service running the DDL. Queries continue to filter by &lt;code&gt;id&lt;/code&gt; and get pruning for free.&lt;/p&gt;
&lt;p&gt;Retention works the same way. To drop data older than twelve months, the service runs &lt;code&gt;SELECT MAX(id) FROM orders WHERE created_at &amp;lt; NOW() - INTERVAL 12 MONTH&lt;/code&gt;, identifies every partition with an upper bound below that ID, and drops them. The &lt;code&gt;MAXVALUE&lt;/code&gt; catch-all is what makes this pattern work; there&amp;rsquo;s always a place for new rows to land while the service is deciding where to cut next.&lt;/p&gt;
&lt;h3 id="what-the-service-looks-like"&gt;What the service looks like
&lt;/h3&gt;&lt;p&gt;The service itself is small. It runs on a schedule (hourly for high-throughput tables, daily for slower-moving ones) and on each tick it does a handful of things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inventory.&lt;/strong&gt; Read the current partition layout from the catalog: partition names, upper bounds, and approximate row counts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sizing check.&lt;/strong&gt; Look at the active partition (the bounded one just below the catch-all). If it&amp;rsquo;s filled past a configured threshold of the target size, it&amp;rsquo;s time to cut the next boundary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Boundary selection.&lt;/strong&gt; Pick where to cut. For time-aligned partitions, query the live table for the ID that was current at the next month boundary; that ID becomes the upper bound of the new partition.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Split.&lt;/strong&gt; Reorganize the catch-all into a new bounded partition plus a fresh catch-all above it. As long as the catch-all is still empty when the split runs, this is metadata-only.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retention pruning.&lt;/strong&gt; Translate the retention window (e.g. twelve months) into an ID via the same &lt;code&gt;created_at&lt;/code&gt;-to-&lt;code&gt;id&lt;/code&gt; lookup, then drop any partition whose upper bound sits below that ID.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concurrency guard.&lt;/strong&gt; A single advisory lock or leader election so two instances don&amp;rsquo;t run DDL against the same table simultaneously.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Metrics and alerting.&lt;/strong&gt; Per-partition size and row count, time-since-last-tick, and a clear alert if the active partition starts filling faster than the service is splitting ahead of it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Run it as a cron job, a Kubernetes CronJob, or a tiny always-on worker; the operational footprint is intentionally small. The bulk of the production-readiness work goes into the concurrency guard, naming conventions, and handling of split failures from lock contention or concurrent DDL. None of that changes what the service does on each tick: a few catalog reads and one DDL statement.&lt;/p&gt;
&lt;h2 id="existing-tools-and-how-this-pattern-differs"&gt;Existing tools and how this pattern differs
&lt;/h2&gt;&lt;p&gt;The automation itself isn&amp;rsquo;t new; several tools already manage partition boundaries on a schedule. What differs across approaches is which column the partitioning is done on, and how much of the schema contract that choice locks in.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a class="link" href="https://github.com/pgpartman/pg_partman" target="_blank" rel="noopener"
 &gt;pg_partman&lt;/a&gt;&lt;/strong&gt; is the widely used partition manager in the PostgreSQL ecosystem. It pre-creates future partitions on a schedule, drops old ones against a retention window, and can migrate non-partitioned tables into partitioned ones in place. Its defaults (and most tutorials written on top of it) assume time-based range partitioning on a &lt;code&gt;timestamp&lt;/code&gt; column. That&amp;rsquo;s the pattern earlier sections argue against: the date column ends up in the primary key and leaks into every query that expects pruning.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a class="link" href="https://www.timescale.com/" target="_blank" rel="noopener"
 &gt;TimescaleDB&lt;/a&gt;&lt;/strong&gt; goes further. Its &amp;ldquo;hypertables&amp;rdquo; are automatically time-partitioned PostgreSQL tables, with chunk creation, retention, and compression all managed by the extension. It&amp;rsquo;s the right tool for workloads where every query is genuinely time-scoped: observability, IoT telemetry, append-only event streams. It&amp;rsquo;s a worse fit for OLTP tables where some queries are time-scoped and others aren&amp;rsquo;t, because the time column is mandatory and every non-time query pays the same partition-key-in-the-WHERE-clause tax as manual time partitioning.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a class="link" href="https://vitess.io/" target="_blank" rel="noopener"
 &gt;Vitess&lt;/a&gt;&lt;/strong&gt; includes partition management as part of its broader MySQL sharding solution. Its partitioning conventions are flexible, but most production uses land on the same time-based defaults.&lt;/p&gt;
&lt;p&gt;The common thread across all three: the automation layer assumes the partition key is picked in advance (usually a time column) and manages boundaries on top of that assumption.&lt;/p&gt;
&lt;p&gt;The approach in this post keeps the automation pattern (small service, pre-split the catch-all, drop behind retention) but changes the key choice. The partition key is the primary key, and time alignment is derived at DDL time via the &lt;code&gt;SELECT MAX(id) WHERE created_at &amp;lt; X&lt;/code&gt; lookup. The schema-level contract stays &lt;code&gt;PRIMARY KEY (id)&lt;/code&gt;; time-based retention still works, computed once per boundary instead of baked into every query.&lt;/p&gt;
&lt;p&gt;The trade-off is owning the service. pg_partman is a well-tested extension; a DIY partitioner is real operational surface area: advisory locks, failure recovery, metrics, alerts. The useful question is whether &lt;code&gt;created_at&lt;/code&gt; is already a natural filter in every query that matters. If every query is time-scoped by design (observability, telemetry, audit logs, anything time-series) pg_partman or TimescaleDB against a time column is the right answer. The partition key isn&amp;rsquo;t leaking because it was already there.&lt;/p&gt;
&lt;p&gt;If the workload is mixed (some queries filter by date, most don&amp;rsquo;t) then adding &lt;code&gt;created_at&lt;/code&gt; to the PK forces a choice: retrofit every non-time query with a date filter, or eat full partition scans on point lookups. Either option is the overhead, whether it&amp;rsquo;s already visible as slow queries or just spreading through the codebase as &lt;code&gt;AND created_at &amp;gt;= ?&lt;/code&gt; clauses added &amp;ldquo;for partitioning reasons&amp;rdquo; on queries that have nothing to do with dates. At that point, owning a small DDL service is cheaper than propagating a partition key through every caller forever.&lt;/p&gt;
&lt;h2 id="automating-hash-and-list-partitioning"&gt;Automating hash and list partitioning
&lt;/h2&gt;&lt;p&gt;The same &amp;ldquo;service watches and adjusts&amp;rdquo; idea transfers to other partitioning strategies, but the operations change.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hash partitioning&lt;/strong&gt; distributes rows across a fixed number of partitions via a hash function. With good cardinality, every partition grows at roughly the same rate; there&amp;rsquo;s nothing to split based on growth. What there is to monitor is skew: a low-cardinality column or a hot key produces one partition that grows faster than the others, which is the failure mode partitioning was supposed to prevent.&lt;/p&gt;
&lt;p&gt;Automation here isn&amp;rsquo;t about adjusting boundaries. Changing the hash partition count rebuilds the entire table, which isn&amp;rsquo;t something a background service should trigger. The useful work is detection: track per-partition size and growth, surface skew early, run &lt;code&gt;OPTIMIZE&lt;/code&gt; or &lt;code&gt;VACUUM FULL&lt;/code&gt; on partitions as they bloat. The service flags problems; a human decides whether to reshape the table. The consequence is that hash partition count is a decision to get right the first time. Over-provisioning (64 partitions when 16 would do today) is cheap insurance against a later full rebuild.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;List partitioning&lt;/strong&gt; maps enumerated values to specific partitions: one partition per region, per significant tenant, etc., with the long tail in a &lt;code&gt;DEFAULT&lt;/code&gt; catch-all. The automation problem is partition promotion: when a value in the catch-all grows large enough to deserve its own partition.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Starting state: named partitions for known-large tenants, DEFAULT for the rest
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tenant_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;JSON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tenant_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LIST&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tenant_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_tenant_42&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_tenant_73&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;73&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_default&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- The service notices tenant_id = 108 is now 15% of p_default and growing quickly.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- It promotes that tenant into its own partition.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;REORGANIZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_default&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_tenant_108&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;108&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PARTITION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p_default&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Promotion is more expensive than splitting an empty range catch-all (the rows for that tenant have to physically move out of &lt;code&gt;DEFAULT&lt;/code&gt; into the new partition) but it can be batched and scheduled during low-traffic windows. Dormant values can be merged back into &lt;code&gt;DEFAULT&lt;/code&gt; in the reverse direction to keep the partition count bounded.&lt;/p&gt;
&lt;h2 id="what-actually-belongs-in-the-partition-key"&gt;What actually belongs in the partition key
&lt;/h2&gt;&lt;p&gt;The question worth asking before adopting any partitioning scheme: what column is already in every query that matters? In most OLTP systems the answer is the primary key. It sits in every lookup, every join, every foreign-key fetch, so partitioning by it gets pruning for free (provided the key itself is sequential; a &lt;a class="link" href="https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/" &gt;random UUID key&lt;/a&gt; scatters inserts across every partition&amp;rsquo;s B-tree). The other answers are real but narrower. &lt;code&gt;tenant_id&lt;/code&gt; works in a multi-tenant system if every query is tenant-scoped; a date column works if the workload is time-series and every query already filters by date. When those conditions don&amp;rsquo;t hold, the partition key leaks into application code the first time someone writes a query without it.&lt;/p&gt;
&lt;p&gt;The failure mode is partitioning by a column that isn&amp;rsquo;t already in every query, then retrofitting the query layer to add it. That&amp;rsquo;s the path that ends with &lt;code&gt;AND created_at &amp;gt;= ?&lt;/code&gt; stapled onto queries that have nothing to do with dates, just to avoid a 36-partition scan.&lt;/p&gt;</description></item><item><title>How Teams Actually Finish What They Start, Part II: A Two-Stage Standup</title><link>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-ii-a-two-stage-standup/</link><pubDate>Sat, 28 Feb 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-ii-a-two-stage-standup/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post How Teams Actually Finish What They Start, Part II: A Two-Stage Standup" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Teams ship more when each IC declares one focused goal in writing every morning and the team holds a brief sync at roughly 3pm to surface what isn&amp;rsquo;t going to plan and offer help on it. The morning declaration creates focus and commitment. The mid-day sync catches problems while there is still a work day left to fix them, with help that&amp;rsquo;s actionable now rather than tomorrow.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It is 3pm on a Tuesday. The team meets for fifteen minutes. The first engineer reads back this morning&amp;rsquo;s declaration: green CI on the orders-export flake by 1pm. What actually happened: CI is green, but the snapshot endpoint is slow enough that the test takes eight minutes, which probably isn&amp;rsquo;t tolerable. Two minutes of conversation. Someone else hit a similar slow-endpoint problem last quarter and links the PR. A third engineer suggests a smaller fix that gets the test under three minutes. The first engineer goes back to their desk with a concrete next step and three hours to finish.&lt;/p&gt;
&lt;p&gt;A 9am standup could not have produced that conversation. At 9am the engineer didn&amp;rsquo;t know the snapshot endpoint was slow; they were committing to green CI. By the time they hit the slow-endpoint problem at 12:30, the morning meeting was four hours behind them, and the teammate with the fix had context-switched to something else. By 5pm, the conversation that could have unblocked the engineer is happening with no work day left to act on it. 3pm is the sweet spot, and the morning declaration is what the 3pm session is anchored to.&lt;/p&gt;
&lt;p&gt;The reflex is to fix the morning meeting instead. Run it tighter. Ask better questions. Replace it with Geekbot or an async post in Slack. Each produces a marginal improvement without changing what the format can do, because the morning is the wrong moment for solving problems. At 9am, today&amp;rsquo;s blockers haven&amp;rsquo;t surfaced yet. The conversations that could resolve them are happening eight hours before the conversations are useful.&lt;/p&gt;
&lt;h2 id="two-artifacts-one-cadence"&gt;Two artifacts, one cadence
&lt;/h2&gt;&lt;p&gt;The morning declaration goes into the team channel before the IC starts work, typically by 10:00 local time. The post answers three questions: what I&amp;rsquo;m working on today, what outcome I&amp;rsquo;m aiming for, what could block me. Two to four sentences. A single focused goal, not a list of three. A statement of intent that the IC, the lead, and the rest of the team can all read.&lt;/p&gt;
&lt;p&gt;A real example:&lt;/p&gt;

 &lt;blockquote&gt;
 &lt;p&gt;Working on the orders-export flake (#4127). Aim: green CI by 1pm. Blocker if it turns out to be the upstream snapshot endpoint, in which case I&amp;rsquo;ll switch to the dashboard cleanup ticket.&lt;/p&gt;

 &lt;/blockquote&gt;
&lt;p&gt;Compare to &amp;ldquo;today I&amp;rsquo;ll keep working on bug #4127, no blockers.&amp;rdquo; The first names a target and a failure path. The second is filler. The act of writing the first one forces the IC to commit to something concrete and to audit whether it fits in a day. The second is something an IC can recite half-asleep.&lt;/p&gt;
&lt;p&gt;The mid-day sync meets around 3pm, fifteen to thirty minutes. Each IC&amp;rsquo;s contribution starts with status: what I declared this morning, what actually happened so far, where I am right now. That part is unavoidable and useful. The rest of the team needs the read. The differentiator is the second beat: &lt;em&gt;what isn&amp;rsquo;t going to plan, what could help.&lt;/em&gt; Each contribution is anchored to the morning post, which means the team works through real, named issues in real time once the status piece is on the table.&lt;/p&gt;
&lt;p&gt;3pm is the load-bearing detail. A meeting at 5pm reports problems that already cost the team a day. A meeting at 11am hasn&amp;rsquo;t seen most of today&amp;rsquo;s blockers yet. 3pm is when today&amp;rsquo;s reality is mostly visible and today&amp;rsquo;s work day still has runway. A blocker named at 3pm is one a teammate can suggest a fix for at 3:05 and the IC can act on at 3:10. The same blocker named at 5pm is tomorrow&amp;rsquo;s problem.&lt;/p&gt;
&lt;p&gt;The two artifacts are paired. The morning declaration is what the 3pm sync is anchored to. Without the morning, the 3pm meeting is a synchronous standup with all of standup&amp;rsquo;s problems. Without the 3pm sync, the morning is a pile of writing the team never discusses, and the productivity benefit evaporates the same way classic standup&amp;rsquo;s information does.&lt;/p&gt;
&lt;h2 id="why-this-raises-output"&gt;Why this raises output
&lt;/h2&gt;&lt;p&gt;Several mechanisms compound.&lt;/p&gt;
&lt;p&gt;One focused goal per IC, declared in writing, beats a list of three. Teams that try to ship four things a day per IC finish fewer than teams that pick one, and Sophie Leroy&amp;rsquo;s 2009 paper on &amp;ldquo;attention residue&amp;rdquo; (&lt;em&gt;Organizational Behavior and Human Decision Processes&lt;/em&gt;, vol. 109) names the mechanism: cognitive load from an unfinished task A persists into task B, even when nothing in the environment is reminding the worker of A. Declaring one thing in the morning forces the IC to name the priority before the noise starts. The declaration is also a forcing function for honest scoping: an engineer writing &amp;ldquo;today I&amp;rsquo;ll finish the export refactor and start the migration&amp;rdquo; notices, in the act of writing, that two days of work won&amp;rsquo;t fit in one. Speaking has no such friction. A standup at 9am hears &amp;ldquo;I&amp;rsquo;ll work on the export and start the migration&amp;rdquo; and nobody, including the engineer, has audited the claim.&lt;/p&gt;
&lt;p&gt;Writing is binding, and the binding holds because the writing sticks. The commitment-and-consistency principle in social psychology (Cialdini&amp;rsquo;s &lt;em&gt;Influence&lt;/em&gt;, 1984, building on Deutsch and Gerard&amp;rsquo;s 1955 work on normative social influence) is the canonical statement: written commitments produce more consistent follow-through than spoken or merely-considered ones. A goal stated in writing, in a public channel, with a name attached, is a stronger commitment than the same goal mumbled aloud at 9:02. By 10:00, most of what was said at 9:00 is gone, not only from the listeners but from the speaker, who at 4pm cannot reliably recall what they committed to. The morning post is still readable at 4pm. Anyone who joined late, anyone in a different time zone, anyone in a partner team that needs to know what your team is touching today, can read the channel.&lt;/p&gt;
&lt;p&gt;The live 3pm sync produces saves the rest of the format cannot. Someone&amp;rsquo;s blocker is someone else&amp;rsquo;s two-minute fix; the live, bounded conversation surfaces the fix while the IC still has runway to apply it. Async help in Slack threads doesn&amp;rsquo;t carry the same load: nobody is required to read at any particular time, and a fix offered at 4:45pm with the IC heads-down is functionally a fix offered tomorrow. The sync works because everyone is present, the conversation is short, and the help is actionable now.&lt;/p&gt;
&lt;p&gt;The sync also builds a different kind of team feeling than ad-hoc help does. Going through real issues together in a session everyone planned to attend produces hints, half-remembered prior fixes, and &amp;ldquo;oh, I had this last week&amp;rdquo; moments that don&amp;rsquo;t carry the social cost of random interruption. A teammate pinged at 2:34pm pays a context-switch cost the asker doesn&amp;rsquo;t see; Gloria Mark&amp;rsquo;s research at UC Irvine on interrupted work has consistently measured refocus times around twenty to twenty-five minutes after a single interruption. That cost disappears when the conversation is the format. Over a quarter, ICs hear each other think out loud and the team starts to know each other as collaborators rather than as Slack avatars.&lt;/p&gt;
&lt;p&gt;Achievement compounds morale. Declaring something and getting it done is its own reinforcement. Teresa Amabile and Steven Kramer&amp;rsquo;s analysis of nearly 12,000 daily diary entries from 238 knowledge workers (&lt;em&gt;The Progress Principle&lt;/em&gt;, Harvard Business Review Press, 2011) found that perceiving daily progress on meaningful work was the single biggest driver of inner work life and motivation, larger than recognition or compensation. A team where ICs make daily declarations and meet most of them ends each week with a visible record of completed commitments. That isn&amp;rsquo;t a soft benefit. Over a quarter, it&amp;rsquo;s the difference between a team that perceives itself as producing and one that doesn&amp;rsquo;t, and the perception drives the next quarter&amp;rsquo;s output. Teams that don&amp;rsquo;t see their own progress slow down regardless of the underlying work; teams that do speed up.&lt;/p&gt;
&lt;p&gt;Inclusivity falls out of the format. Written-first formats produce more balanced contribution than live round-robins. Quiet team members get equal weight when their declaration is in the channel, and the 3pm session anchors back to what they wrote rather than rewarding whoever talks first. Over a year, this is the difference between knowing what your introverts are doing and not.&lt;/p&gt;
&lt;h2 id="where-this-fits-among-existing-patterns"&gt;Where this fits among existing patterns
&lt;/h2&gt;&lt;p&gt;Most components are not new.&lt;/p&gt;
&lt;p&gt;Async written standups are widely practiced. &lt;a class="link" href="https://geekbot.com/" target="_blank" rel="noopener"
 &gt;Geekbot&lt;/a&gt;, &lt;a class="link" href="https://standuply.com/" target="_blank" rel="noopener"
 &gt;Standuply&lt;/a&gt;, &lt;a class="link" href="https://www.range.co/" target="_blank" rel="noopener"
 &gt;Range&lt;/a&gt;, and &lt;a class="link" href="https://www.polly.ai/" target="_blank" rel="noopener"
 &gt;Polly&lt;/a&gt; are tools built specifically for the morning-write half. &lt;a class="link" href="https://basecamp.com/features/checkins" target="_blank" rel="noopener"
 &gt;Basecamp&amp;rsquo;s Check-ins&lt;/a&gt; does the same thing. GitLab&amp;rsquo;s handbook documents an async-first variant publicly, as do Doist (Twist), Automattic, and parts of Basecamp&amp;rsquo;s own engineering. Anyone who has worked at a remote-first org in the last five years has probably written one of these.&lt;/p&gt;
&lt;p&gt;What is less common is the deliberate pairing with a same-day live sync, and the timing of that sync at 3pm rather than at end-of-day. Most teams that move to async written standups skip the live half entirely. Most teams that keep a live standup don&amp;rsquo;t bother with the written morning. End-of-day retros exist in some agile shops but tend to surface problems too late to act on them today. The 3pm window is the productivity unlock, and it isn&amp;rsquo;t formalized in any of the named tools.&lt;/p&gt;
&lt;p&gt;The other less-common piece is using the written trail as a coaching primitive. Some tools surface trends, but most teams treat written standups as status updates rather than as longitudinal evidence about how an IC scopes their work. The same artifact that makes the morning bind makes it readable as a coaching signal across days and weeks.&lt;/p&gt;
&lt;p&gt;The article isn&amp;rsquo;t claiming async standups are new. The combination (one-goal morning declaration + 3pm team sync + multi-day longitudinal use) is the angle worth picking apart.&lt;/p&gt;
&lt;h2 id="how-team-leads-use-the-trail"&gt;How team leads use the trail
&lt;/h2&gt;&lt;p&gt;A week of declarations, read together, is a different artifact from any single one. A lead reading Monday-through-Friday for one IC sees the rhythm of declarations, what&amp;rsquo;s being achieved, what&amp;rsquo;s drifting, where the IC chooses to spend focus.&lt;/p&gt;
&lt;p&gt;Three patterns:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Weekly review.&lt;/strong&gt; Skim the week&amp;rsquo;s declarations on Friday or Monday. Look for ICs whose intent and outcome diverged repeatedly. Look for blockers that recur. Look for scope that grew without being renegotiated.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;1:1 prep.&lt;/strong&gt; Walk into the 1:1 with the IC&amp;rsquo;s last two weeks of declarations open. The conversation has a concrete anchor instead of &amp;ldquo;how&amp;rsquo;s everything going.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Drift detection.&lt;/strong&gt; When an IC&amp;rsquo;s declarations stop matching outcomes, when blockers recur, when commitments shrink without explanation, the trail surfaces it before the next sprint review does.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The discipline cuts both ways. A lead who reads declarations as ammunition turns the artifact into a control mechanism, and the team adapts by writing declarations that are safely vague.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The trail is not evidence&lt;/strong&gt;
 &lt;div&gt;The fastest way to kill this format is to use it as a productivity-tracking tool. A lead who cites past declarations as evidence against an IC, who treats missed commitments as a record to hold, who reads the trail to judge instead of to help, breaks it within a quarter. The team adapts: declarations get written defensively, blockers go unmentioned because admitting one is now on the record, and the real coordination work quietly moves into DMs and 1:1 channels where nothing is being filed. What&amp;rsquo;s left in the public channel is theater. The longitudinal coaching value disappears and the productivity gain goes with it. The format depends on honest declarations and the team feeling that the trail exists to help, not to judge. It amplifies whatever culture is already there. It does not fix a broken one.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="failure-modes"&gt;Failure modes
&lt;/h2&gt;&lt;p&gt;The structure has its own anti-patterns.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Declarations become theater.&lt;/strong&gt; &amp;ldquo;My goal: fix bugs&amp;rdquo; produces nothing useful at 3pm because there&amp;rsquo;s nothing concrete to talk through. The fix is to push the format toward concrete outcomes (a ticket number, a measurable end-state) and to model good declarations from the lead&amp;rsquo;s own posts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The 3pm sync collapses to status alone.&lt;/strong&gt; Some status is built into the format and that&amp;rsquo;s fine. The failure mode is when status is the whole meeting. When the lead asks &amp;ldquo;what&amp;rsquo;s your update&amp;rdquo; and nobody jumps in with a fix, a question, or &amp;ldquo;I had this last week,&amp;rdquo; the meeting has reverted to a synchronous standup with extra writing overhead. The discipline is the second beat: surfacing what isn&amp;rsquo;t working and inviting help on it before the next person reports.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Over-commitment in writing.&lt;/strong&gt; Engineers declare more than fits in a day because written commitments feel public. Two weeks of &amp;ldquo;declared three things, finished one&amp;rdquo; is a coaching signal, not a discipline issue. The format is asking for honest scoping; the lead&amp;rsquo;s job is to model it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Declarations nobody reads.&lt;/strong&gt; If the morning post goes into a channel nobody scrolls, the persistence benefit evaporates and the 3pm session has no anchor. The fix isn&amp;rsquo;t more pings. It&amp;rsquo;s making the channel a routine read for the lead, the partner teams, and the IC&amp;rsquo;s peers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The 3pm slot gets eroded by other meetings.&lt;/strong&gt; Mid-afternoon is prime calendar real estate, and over a quarter the slot can be eaten by partner-team syncs, reviews, and one-offs. Defend it. Moving the sync to 4:30 to accommodate another meeting kills the productivity property the 3pm timing was buying.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="when-classic-standup-is-still-the-right-tool"&gt;When classic standup is still the right tool
&lt;/h2&gt;&lt;p&gt;This isn&amp;rsquo;t a one-size-fits-all replacement.&lt;/p&gt;
&lt;p&gt;Tight single-time-zone teams get less from the async morning. A team in one office, all in the same five-hour window, can run a synchronous standup at 9:00 and the persistence benefit is small because everyone is already in the same room. The 3pm sync still pays back; the morning declaration is the part that becomes optional.&lt;/p&gt;
&lt;p&gt;Very small teams (three or four people) face overhead high relative to size. A daily fifteen-minute conversation accomplishes most of what the two-stage format does, and the multi-day coaching trail matters less when the lead can ask any of three people directly.&lt;/p&gt;
&lt;p&gt;Pair-programming and mob-programming workflows complicate the morning declaration. The artifact becomes the pair&amp;rsquo;s intent, not the individual&amp;rsquo;s. The 3pm sync still works; the longitudinal trail is less useful because the artifact you&amp;rsquo;re reading is the pair, not the IC.&lt;/p&gt;
&lt;p&gt;Crisis modes are the clearest exception. Incident response, deploy days, anything where the team is already on the same shared context for hours. Use a war-room channel and resume the regular cadence after.&lt;/p&gt;
&lt;h2 id="trade-offs"&gt;Trade-offs
&lt;/h2&gt;&lt;p&gt;This isn&amp;rsquo;t free.&lt;/p&gt;
&lt;p&gt;ICs do more writing every day. Five sentences before 10am may not sound like much, but compounded across a year and a team of ten it&amp;rsquo;s real overhead. The format is paying for that with output, morale, and a coaching trail. If none of those matter in the team&amp;rsquo;s context, the cost isn&amp;rsquo;t worth it.&lt;/p&gt;
&lt;p&gt;The 3pm slot is expensive calendar real estate. Carving fifteen to thirty minutes out of the most productive part of the work day is a real tax, paid back in problems solved while still solvable. A team that can&amp;rsquo;t defend the slot will see the productivity benefit decay over a quarter as the meeting slides later or gets cancelled.&lt;/p&gt;
&lt;p&gt;The format depends on psychological safety. A team where missed commitments become punishment material, where blockers are punished as weakness, will produce performative declarations regardless of the format. The structure amplifies whatever the team&amp;rsquo;s actual culture is.&lt;/p&gt;
&lt;p&gt;The longitudinal trail can be misused. Already named in the failure modes; the most expensive failure because it kills the productivity benefit fastest. The same artifact that makes the format work as coaching makes it dangerous as compliance theater.&lt;/p&gt;
&lt;p&gt;The tooling fit is partial. Geekbot, Standuply, Range, Polly, and Basecamp Check-ins each support parts of the structure. None map perfectly to &amp;ldquo;morning declaration + 3pm live sync + longitudinal trail.&amp;rdquo; Most teams running this end up with a Slack channel for the morning, a recurring 3pm calendar event, and the lead&amp;rsquo;s own notes for the trail. The format assumes the team was already &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-i-designing-the-team-as-a-process/" &gt;designed as a process&lt;/a&gt; (Part I), and &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-iii-a-working-responder-rotation/" &gt;Part III&lt;/a&gt; covers the responder rotation that keeps the 3pm sync from turning into interrupt triage. The tooling is a wrapper around the discipline, not a substitute for it.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The test for whether this format fits a team is concrete. Does the lead read the morning declarations, and does the 3pm meeting actually run as a working sync? If both are true, the productivity gain is real. If either drifts (the channel goes unread, or the meeting becomes a status round) the format collapses to a more expensive version of the standup it was supposed to replace.&lt;/p&gt;
&lt;p&gt;Teams that try this and abandon it usually abandoned it because they kept the format and dropped the discipline. The format is cheap. The discipline is the part that ships.&lt;/p&gt;</description></item><item><title>Testing Your Database, Part 2: What to Test, and How</title><link>https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/</link><pubDate>Tue, 17 Feb 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Testing Your Database, Part 2: What to Test, and How" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;What most teams call &amp;ldquo;database tests&amp;rdquo; are application tests with a database underneath. They cover whether the code reads and writes correctly, not whether the database does what its catalog claims. Real database testing covers five distinct categories, each requiring a different tool, and each invisible to the others.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The CI suite has 600 tests. Every one is green. Judged on what they actually exercise: 480 are unit tests using a stub database for fixtures, 80 are application integration tests using a real Postgres container with seeded fixtures, 20 are migration tests that run &lt;code&gt;db:migrate&lt;/code&gt; against the empty test database, 20 are end-to-end tests that hit the API and observe response shape. Coverage looks comprehensive. None of these tests catches: an &lt;code&gt;ALTER TABLE&lt;/code&gt; that locks the table for 40 minutes against production volume, a &lt;code&gt;CHECK&lt;/code&gt; constraint that&amp;rsquo;s syntactically valid and semantically wrong, an &lt;code&gt;ON CONFLICT (email)&lt;/code&gt; that depends on a UNIQUE constraint nobody declared, a JOIN that multiplies rows through a missing bridge UNIQUE, a query that returns the right shape with the wrong number, a generated column whose definition drifts from its dependencies after a migration. The suite isn&amp;rsquo;t bad. The failures live in categories the suite doesn&amp;rsquo;t cover.&lt;/p&gt;
&lt;p&gt;The obvious response is &amp;ldquo;use Testcontainers.&amp;rdquo; Testcontainers is a real tool, addresses a real gap (the test container is the production engine, not SQLite-as-Postgres), and most teams should adopt it. It still only addresses one of the categories below. A team that adopts Testcontainers and stops there has moved from &amp;ldquo;no database tests&amp;rdquo; to &amp;ldquo;application tests with a real database engine&amp;rdquo;; better, and still missing the four other categories. The same applies to every other &amp;ldquo;the one thing we should do&amp;rdquo; answer: each tool below addresses a class of failure the others can&amp;rsquo;t see, and an AI-introduced bug can land in any of them.&lt;/p&gt;
&lt;h2 id="five-categories-of-database-test"&gt;Five categories of database test
&lt;/h2&gt;&lt;h3 id="1-lint-ddl-safety-before-merge"&gt;1. Lint DDL safety before merge
&lt;/h3&gt;&lt;p&gt;The category most teams don&amp;rsquo;t have at all. The test runs against the migration source itself (not the database) and checks for patterns known to lock or rewrite tables in production: &lt;code&gt;ADD COLUMN ... NOT NULL&lt;/code&gt; without a default-then-backfill split (Postgres pre-11) or a non-constant default (Postgres 11+ stores it metadata-only), &lt;code&gt;ALTER COLUMN TYPE&lt;/code&gt; that triggers a table rewrite, &lt;code&gt;ADD FOREIGN KEY&lt;/code&gt; without &lt;code&gt;NOT VALID&lt;/code&gt;, &lt;code&gt;DROP COLUMN&lt;/code&gt; on a table other services still write, indexes created without &lt;code&gt;CONCURRENTLY&lt;/code&gt; (Postgres) or without &lt;code&gt;ALGORITHM=INPLACE, LOCK=NONE&lt;/code&gt; (MySQL).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tool.&lt;/strong&gt; &lt;a class="link" href="https://github.com/sbdchd/squawk" target="_blank" rel="noopener"
 &gt;Squawk&lt;/a&gt; for Postgres; lints SQL migrations for known-bad patterns. Configurable rule set, fast failure, runs as a CI step or pre-commit hook. &lt;a class="link" href="https://atlasgo.io/" target="_blank" rel="noopener"
 &gt;Atlas&lt;/a&gt; for cross-engine coverage (Postgres, MySQL, ClickHouse); its 2025 analyzer set covers destructive changes, data-dependent modifications like &lt;code&gt;ADD COLUMN NOT NULL&lt;/code&gt; without a default, nested transactions, and SQL-injection-prone migration code, with hooks designed to gate AI-authored migrations specifically. For MySQL, &lt;code&gt;pt-online-schema-change&lt;/code&gt; and &lt;code&gt;gh-ost&lt;/code&gt; defaults plus a custom lint script that flags raw &lt;code&gt;ALTER&lt;/code&gt; on tables over a configured row threshold.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it catches.&lt;/strong&gt; The locking-migration class from &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;Part 1&lt;/a&gt;: &lt;code&gt;ALTER TABLE users ADD COLUMN tier TINYINT NOT NULL DEFAULT 0&lt;/code&gt; against a 50M-row table. Squawk&amp;rsquo;s &lt;code&gt;adding-not-nullable-field&lt;/code&gt;, &lt;code&gt;disallowed-unique-constraint&lt;/code&gt;, and &lt;code&gt;require-concurrent-index-creation&lt;/code&gt; rules surface this pattern before the migration is applied anywhere.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it misses.&lt;/strong&gt; Anything that requires running the migration to detect. It&amp;rsquo;s a syntactic check. A migration that&amp;rsquo;s safe by lint but breaks an invariant the team relied on still passes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-assert-what-the-catalog-says"&gt;2. Assert what the catalog says
&lt;/h3&gt;&lt;p&gt;The catalog is full of declarations that are easy to write incorrectly and hard to read back. Did the FK actually cascade, or did it default to &lt;code&gt;NO ACTION&lt;/code&gt;? Does the partial index cover the predicate the query actually uses? Does the CHECK reject the values it claims to? After a migration applies, are the constraints, indexes, and triggers the team intended actually present, with the names, columns, and behavior they intended? Tests in this category run after migrations apply and assert against the resulting schema and the resulting behavior, not the application&amp;rsquo;s view of it.&lt;/p&gt;
&lt;p&gt;A note specifically on database-resident business logic. The companion post &lt;a class="link" href="https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/" &gt;Where Business Logic Lives&lt;/a&gt; argues to keep most of it in the application layer, where review density and tooling are higher. Triggers, stored procedures, functions, RLS policies, generated-column expressions, and multi-statement &lt;code&gt;CHECK&lt;/code&gt; constraints encoding state-machine rules are running code that doesn&amp;rsquo;t show up on a normal PR diff and doesn&amp;rsquo;t execute in local development the way application code does. If business logic is in the database (by accident, by legacy, or by deliberate choice) every one of those needs unit-test coverage the same way an application function would. For stored procedures and functions: assert every branch, every &lt;code&gt;EXCEPTION&lt;/code&gt; block, every side effect on the rows the procedure touches, every return value the caller depends on. For triggers: assert each firing condition (&lt;code&gt;BEFORE&lt;/code&gt; / &lt;code&gt;AFTER&lt;/code&gt; × &lt;code&gt;INSERT&lt;/code&gt; / &lt;code&gt;UPDATE&lt;/code&gt; / &lt;code&gt;DELETE&lt;/code&gt;), every &lt;code&gt;WHEN&lt;/code&gt; filter, the actual state change the action performs, and any interaction with other triggers on the same table. The same pgTAP / tSQLt harness covers all of it; the discipline is treating database code as code, not as configuration. A trigger that&amp;rsquo;s never been asserted against isn&amp;rsquo;t a guarantee. It&amp;rsquo;s a hope.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tool.&lt;/strong&gt; &lt;a class="link" href="https://pgtap.org/" target="_blank" rel="noopener"
 &gt;pgTAP&lt;/a&gt; for Postgres, &lt;a class="link" href="https://tsqlt.org/" target="_blank" rel="noopener"
 &gt;tSQLt&lt;/a&gt; for SQL Server, &lt;a class="link" href="https://www.utplsql.org/" target="_blank" rel="noopener"
 &gt;utPLSQL&lt;/a&gt; for Oracle. Schema-level assertions: &lt;code&gt;has_column('users', 'tier')&lt;/code&gt;, &lt;code&gt;col_type_is('users', 'tier', 'integer')&lt;/code&gt;, &lt;code&gt;has_index('users', 'users_email_idx')&lt;/code&gt;, &lt;code&gt;fk_ok('orders', 'user_id', 'users', 'id')&lt;/code&gt;. Behavior-level assertions: insert an illegal row and assert the CHECK rejects, insert a parent and child and delete the parent and assert the cascade fired, attempt a forbidden state transition and assert it&amp;rsquo;s rejected.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it catches.&lt;/strong&gt; The CHECK that lists valid values but doesn&amp;rsquo;t constrain transitions. The FK declared without &lt;code&gt;ON DELETE CASCADE&lt;/code&gt; despite the team thinking it was. The partial index whose &lt;code&gt;WHERE&lt;/code&gt; clause has drifted from the queries that use it. The UNIQUE constraint the upsert depends on but nobody declared.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it misses.&lt;/strong&gt; Anything outside the catalog: query result correctness, lock duration, performance regressions, runtime data invariants.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-assert-query-results-not-just-shapes"&gt;3. Assert query results, not just shapes
&lt;/h3&gt;&lt;p&gt;The hardest category and the most under-covered. The query is syntactically valid, the result set is the right shape, the EXPLAIN is clean, and the number is wrong by 30%. The test that catches this asserts the result against a known dataset: given a fixture with 1,000 users where 200 are soft-deleted, the active-users query returns 800; given five orders with stacked discounts, the revenue query returns the discounted total, not the row-multiplied total.&lt;/p&gt;
&lt;p&gt;Example-based fixtures aren&amp;rsquo;t enough on their own. The AI-generated bugs in this category live in inputs the test author didn&amp;rsquo;t think to write. Take a paginated query the model emits as &lt;code&gt;ORDER BY created_at LIMIT 100 OFFSET ?&lt;/code&gt;. An example test inserts ten orders, paginates through them, gets all ten back, passes. The bug (that &lt;code&gt;created_at&lt;/code&gt; isn&amp;rsquo;t unique, so rows with identical timestamps swap positions between pages and rows get skipped or duplicated) never surfaces against ten hand-written rows. A property-based test that asserts &amp;ldquo;every row appears exactly once across all pages&amp;rdquo; finds the timestamp collision in seconds and the fix is a deterministic tie-breaker (&lt;code&gt;ORDER BY created_at, id&lt;/code&gt;). The same pattern applies to round-trip (insert and read back unchanged), conservation (sum of children equals parent total), and idempotency (running twice equals running once).&lt;/p&gt;
&lt;p&gt;Property and fixture tests assert that the result is correct against a known input. They don&amp;rsquo;t assert the query means what the human asked. The second tier addresses that gap: dual-track evaluation, where the query runs programmatically (count, aggregate, expected rows) and a separate LLM judge scores semantic alignment against the original natural-language intent, the schema, and the result set. Thomson Reuters&amp;rsquo; internal SQL agent shipped with 73% silent-failure rate on time-based analyses (predicates landed on the parent date column but not the joined ones); adding a &amp;ldquo;consistent time constraint across joined tables&amp;rdquo; validator plus dual-track judge eval drove it below 10%.&lt;/p&gt;
&lt;p&gt;The 10% is lab-clean and best-case. TR measured it against curated analytical queries with known ground truth on an instrumented internal data lake. The gap from there to a typical legacy schema (undeclared FKs, polysemic &lt;code&gt;TINYINT&lt;/code&gt; status columns, tribal-knowledge soft-deletes, four-format &lt;code&gt;VARCHAR&lt;/code&gt; dates, JSON-as-schema, the realities in &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;What AI Gets Wrong About Your Database&lt;/a&gt;) multiplies that rate, because the judge reads the same impoverished catalog the generator does. 10% is unshippable on its own: a daily financial query at 10% silent-failure lays down corrupted data every week, errors layer into next month&amp;rsquo;s inputs, and by the time a customer flags the discrepancy six months later the WAL retention is exhausted and the backups have rolled past. That&amp;rsquo;s a continuity event, not a bug. Treat LLM-judge eval as a floor-raiser for what reaches human review, never the release gate. The gate is property tests, fixture-based result assertions, and human review against representative data; the judge sits underneath all three.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tool.&lt;/strong&gt; &lt;a class="link" href="https://docs.getdbt.com/docs/build/data-tests" target="_blank" rel="noopener"
 &gt;dbt tests&lt;/a&gt; for analytical/transformation SQL: built-in &lt;code&gt;unique&lt;/code&gt;, &lt;code&gt;not_null&lt;/code&gt;, &lt;code&gt;accepted_values&lt;/code&gt;, &lt;code&gt;relationships&lt;/code&gt;, plus custom SQL tests. &lt;a class="link" href="https://github.com/sodadata/soda-core" target="_blank" rel="noopener"
 &gt;Soda Core&lt;/a&gt; for production data quality assertions. For application SQL, custom integration tests that load a representative fixture, run the query, and assert the count and one or two known aggregates. &lt;a class="link" href="https://hypothesis.readthedocs.io/" target="_blank" rel="noopener"
 &gt;Hypothesis&lt;/a&gt; (Python), &lt;a class="link" href="https://github.com/dubzzz/fast-check" target="_blank" rel="noopener"
 &gt;fast-check&lt;/a&gt; (TypeScript), or &lt;a class="link" href="https://propertesting.com/" target="_blank" rel="noopener"
 &gt;PropEr&lt;/a&gt; (Erlang) for property-based generators that exercise the input distribution the fixture doesn&amp;rsquo;t. &lt;a class="link" href="https://github.com/datafold/data-diff" target="_blank" rel="noopener"
 &gt;data-diff&lt;/a&gt; for regression: run the query against the same dataset before and after a change, fail if the result diff is larger than expected. For semantic verification of AI-generated SQL: LLM-judge templates from Arize, Evidently, Langfuse, or Monte Carlo, scoped to the referenced tables only; schema bloat poisons the judge the same way it poisons the generator. Differential testing (running the agent&amp;rsquo;s query and a hand-written reference against the same dataset and diffing) is the natural extension. No productized tool exists for it yet, and any team adopting AI-authored SQL at scale should be ready to roll their own harness.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it catches.&lt;/strong&gt; The opening incident from &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;Part 1&lt;/a&gt;: the soft-delete-naive &lt;code&gt;LEFT JOIN&lt;/code&gt; that over-reported revenue by 7%. The JOIN cardinality blowup through a bridge table without composite &lt;code&gt;UNIQUE&lt;/code&gt;. The polysemic-TINYINT predicate landing on the wrong meaning. The pagination that drops rows on timestamp ties. The temporal-misalignment failure from the Thomson Reuters case: predicates landing on the parent date column but not the joined ones. The aggregate that ran in 80ms and was off by $1.4M. Anything where the failure shape is &amp;ldquo;result is plausible but wrong.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it misses.&lt;/strong&gt; Anything that only manifests at production scale, under concurrency, or against data shapes the fixture and the property generators didn&amp;rsquo;t include. The LLM-judge tier specifically misses any failure mode invisible from the result set: a query that returns the right number for the wrong reason still passes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-run-the-migration-and-budget-what-it-costs"&gt;4. Run the migration and budget what it costs
&lt;/h3&gt;&lt;p&gt;The category that catches the locking migration from Part 1. The test applies the migration to a database the size of production (or a representative fraction), measures lock duration with &lt;code&gt;pg_locks&lt;/code&gt; or &lt;code&gt;information_schema.innodb_trx&lt;/code&gt;, runs concurrent reads and writes against the table to surface metadata-lock contention, and asserts against a budget. Same idea for queries: run EXPLAIN against a representative dataset, assert the planner uses the index the team meant, assert the cost is below a budget, assert the query plan didn&amp;rsquo;t change unexpectedly between the previous and current revisions.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tool.&lt;/strong&gt; &lt;a class="link" href="https://testcontainers.com/" target="_blank" rel="noopener"
 &gt;Testcontainers&lt;/a&gt; for spinning up a real database engine inside the test runner, seeded with an anonymized prod-shaped snapshot (&lt;a class="link" href="https://postgresql-anonymizer.readthedocs.io/" target="_blank" rel="noopener"
 &gt;pg_anonymizer&lt;/a&gt; or equivalent for the snapshot pipeline). A test harness that applies the migration with a stopwatch and a &lt;code&gt;pg_locks&lt;/code&gt; watcher running in a parallel session. EXPLAIN budgets via per-query assertions in CI; production query-plan regressions via &lt;code&gt;pg_stat_statements&lt;/code&gt; snapshots.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it catches.&lt;/strong&gt; The 40-minute migration. The query that&amp;rsquo;s fast on 10K rows and slow on 10M. The index the planner ignores. The migration that succeeds in isolation and deadlocks against concurrent writers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What it misses.&lt;/strong&gt; Catalog-level invariants the migration doesn&amp;rsquo;t change but the test should still verify; data invariants that drift over time independent of any migration.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-catch-data-drift-after-the-schema-is-correct"&gt;5. Catch data drift after the schema is correct
&lt;/h3&gt;&lt;p&gt;The category most useful for catching production drift, not pre-deployment bugs. Once a day, in CI or as a scheduled job, run a set of assertions against actual production data: every order has a user, every user with an active subscription has a payment method, the soft-delete column is consistent across related tables, the JSON keys in the column match the documented shape, the count of &lt;code&gt;users.deleted_at IS NOT NULL&lt;/code&gt; matches the count of soft-delete audit records. These assertions don&amp;rsquo;t run against fixtures; they run against the real data and surface inconsistencies the schema can&amp;rsquo;t enforce - the integrity rules that live in application code, not in the catalog.&lt;/p&gt;
&lt;p&gt;Soda Core, &lt;a class="link" href="https://greatexpectations.io/" target="_blank" rel="noopener"
 &gt;Great Expectations&lt;/a&gt;, and custom SQL assertions wrapped in a test runner that fails loudly and pages on a missed assertion are the standard toolchain. &lt;a class="link" href="https://schemathesis.readthedocs.io/" target="_blank" rel="noopener"
 &gt;Schemathesis&lt;/a&gt; is the cousin that handles property-based testing of API contracts hitting the database, useful for catching drift introduced through the API rather than through backfills. What this layer catches is what the schema cannot: soft-delete inconsistencies between related tables, orphaned rows the FK should have caught but didn&amp;rsquo;t (because the FK was declared after the orphans existed and was created &lt;code&gt;NOT VALID&lt;/code&gt;), JSON shape drift, business-logic invariants that live in application code and got bypassed by a backfill or a one-off script. What it can&amp;rsquo;t catch is pre-deployment bugs. By the time a data invariant fires, the bad data is already there; this category is the safety net under the others, not a replacement for them.&lt;/p&gt;
&lt;h2 id="the-minimum-useful-subset"&gt;The minimum useful subset
&lt;/h2&gt;&lt;p&gt;Five categories is more than most teams will adopt at once. The order to add them, ranked by leverage per hour invested:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;DDL safety lint&lt;/strong&gt; (Squawk or equivalent). One config file, zero runtime cost, catches the highest-impact failure mode: schema migrations that lock production. Adopt this week.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Schema invariants&lt;/strong&gt; (pgTAP for Postgres, tSQLt for SQL Server). One test file per migration, asserting the migration produced the schema the team intended and that constraints behave the way the team thinks. Catches the constraints that look right and aren&amp;rsquo;t.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lock and performance budgets&lt;/strong&gt; (Testcontainers + prod-shaped snapshot). The largest setup cost - the snapshot pipeline has to be built and maintained - and the largest payoff. Catches the failures that only manifest at production scale.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Query result regressions&lt;/strong&gt; (dbt tests or custom integration tests). High value for analytical workloads, lower for transactional. Pick the queries that drive business decisions and assert their results against fixtures; expand from there.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data invariants&lt;/strong&gt; (Soda or scheduled SQL). Useful once the pre-deployment categories are in place. Without them, you&amp;rsquo;re chasing drift the earlier categories should have prevented.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A team that has none of these and adopts the first three closes most of the AI-introduced surface from &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;Part 1&lt;/a&gt;. A team that has all five has built the verification layer that, pre-AI, lived in the heads of senior engineers - now written down, runnable on demand, and cheap to re-run on every change.&lt;/p&gt;
&lt;h2 id="the-recovery-layer"&gt;The recovery layer
&lt;/h2&gt;&lt;p&gt;The five categories test the database on the way in. They don&amp;rsquo;t test the path back when something AI-introduced makes it past every category and corrupts data anyway. Backups that have never been restored aren&amp;rsquo;t backups; they&amp;rsquo;re unverified hopes. Replication and failover that have never been broken on purpose aren&amp;rsquo;t HA; they&amp;rsquo;re configuration that hasn&amp;rsquo;t been disproved.&lt;/p&gt;
&lt;p&gt;The drills are mechanical: pull a random backup from the last seven days, restore to a fresh ephemeral instance, run a checksum query against a known table, destroy the instance. Daily. Alert on failure. Same idea for point-in-time recovery: pick a timestamp from yesterday, restore to it, verify. Same for failover: kill the primary on a schedule in staging, confirm promotion, restore. Each drill costs an hour or two to automate and catches the class of failure where backups silently stopped working three months ago and nobody noticed because nobody needed them yet.&lt;/p&gt;
&lt;p&gt;The framing shifts with agents in the loop. An agent that holds write permissions on production can cause damage at machine speed; recovery has to work at machine speed too. A four-hour restore that requires three engineers isn&amp;rsquo;t a recovery procedure. It&amp;rsquo;s a postmortem.&lt;/p&gt;
&lt;h2 id="the-performance-environment"&gt;The performance environment
&lt;/h2&gt;&lt;p&gt;Category 4 covers per-PR migration safety and per-query plan budgets, good for CI feedback loops, where a Testcontainers engine spins up, runs one operation, asserts a budget, and tears down. That&amp;rsquo;s the wrong shape for the failure modes that only emerge under sustained load: throughput collapse under realistic concurrency, p95/p99 latency creeping past SLO under traffic mix, replication lag under write pressure that staging never produces, connection pool saturation when a new query plan blows the average query duration, buffer cache thrash when an added index pushes hot data out of &lt;code&gt;shared_buffers&lt;/code&gt;, and the slow degradation that only shows up after the cache has warmed and the workload has run for hours.&lt;/p&gt;
&lt;p&gt;The environment those tests need is a shadow of production: same data volume, same replication topology, ideally same hardware shape, populated from an anonymized snapshot refreshed on a regular cadence. Traffic comes from replay rather than synthesis. Capture statement traces with &lt;code&gt;pg_stat_statements&lt;/code&gt; or query logs over a representative window, and replay them with &lt;a class="link" href="https://github.com/laurenz/pgreplay" target="_blank" rel="noopener"
 &gt;pg_replay&lt;/a&gt;, Percona Playback, or a custom harness against the shadow at production rate. Synthetic load generators (&lt;a class="link" href="https://k6.io/" target="_blank" rel="noopener"
 &gt;k6&lt;/a&gt;, &lt;a class="link" href="https://jmeter.apache.org/" target="_blank" rel="noopener"
 &gt;JMeter&lt;/a&gt;) work for application-level scenarios but miss the long-tail query distribution that production carries, which is exactly where AI-introduced regressions hide.&lt;/p&gt;
&lt;p&gt;The payoff is the failure class CI cannot reach: a migration passes every Testcontainers check, deploys to production, and degrades p99 latency 40% three hours later because the new index shifted the planner&amp;rsquo;s choice for a different query the CI run never executed. That regression is invisible in a five-second container and obvious in a four-hour replay.&lt;/p&gt;
&lt;p&gt;The cloud collapses most of the setup cost. &lt;a class="link" href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Managing.Clone.html" target="_blank" rel="noopener"
 &gt;Aurora&amp;rsquo;s fast database cloning&lt;/a&gt; is copy-on-write against the source. Ready in minutes regardless of database size, you only pay for the diff, and you tear it down when done. &lt;a class="link" href="https://neon.com/docs/introduction/branching" target="_blank" rel="noopener"
 &gt;Neon&amp;rsquo;s branches&lt;/a&gt; do the same for managed Postgres outside Aurora. Google Cloud SQL clones and Azure SQL database copy are slower but in the same family. Plain RDS without Aurora is slower still (snapshot + restore) but cheaper than building the pipeline yourself. The &amp;ldquo;we&amp;rsquo;d need to maintain a parallel copy of production&amp;rdquo; objection that used to kill this kind of testing infrastructure is a one-API-call problem in 2026 for anyone on managed cloud Postgres or MySQL: clone prod on demand, run the migration and the replay against the clone, throw it away. The blocker shifted from infrastructure to discipline. Are AI-authored migrations actually running this gate before merge, or is the clone capability sitting unused?&lt;/p&gt;
&lt;p&gt;A read-only replica in production is the degenerate version of this. It&amp;rsquo;s the cheapest shadow you&amp;rsquo;ll ever build, and the answer to &amp;ldquo;is the new query going to scan a billion rows&amp;rdquo; is to run it on the replica before merging. Many teams already have one; far fewer route AI-generated queries through it as a standing gate.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The minimum useful subset assumes a production-facing system with multiple writers, frequent migrations, and AI in the loop. Cases where less is enough:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A read-only analytical workload with no migrations.&lt;/strong&gt; Categories 1 and 2 don&amp;rsquo;t apply. Category 3 (result regressions) and category 5 (data invariants) carry the load.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A throwaway service with one writer and no enduring data.&lt;/strong&gt; None of this is necessary; the cost of a wrong query is recoverable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A team with zero AI in its data layer.&lt;/strong&gt; The case for the test categories is weaker - the implicit human review is intact. The categories still matter, but they aren&amp;rsquo;t load-bearing in the same way.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A schema small and stable enough to fit in one head.&lt;/strong&gt; Twenty tables, three engineers, one service writing every row. The reviewer who wrote the migration is the test, the same way they always were. Grow the team or the schema by an order of magnitude and the math flips.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For everything else, the cost of building the test layer is a fraction of the cost of one production incident. AI made the math obvious.&lt;/p&gt;</description></item><item><title>How Teams Actually Finish What They Start, Part I: Designing the Team as a Process</title><link>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-i-designing-the-team-as-a-process/</link><pubDate>Wed, 11 Feb 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-i-designing-the-team-as-a-process/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post How Teams Actually Finish What They Start, Part I: Designing the Team as a Process" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A team&amp;rsquo;s output and motivation come from designing the work as a process: each person in a role that uses them well, an owned outcome attached to it, a cadence chosen deliberately. Every team&amp;rsquo;s process is custom; the operating principle is universal. Break the work into chunks the team can consume, run them on a schedule the team can hold, and the team ships like a clock.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Six engineers, three quarters in. Weekly standup, retro every two weeks, sprint planning Monday, sprint review Friday, an architecture review the second Tuesday of the month, OKR tracking, the usual mix of Slack channels. The team ships, but the velocity chart has been flat for two quarters and three engineers are quietly looking. Retros produce theme complaints (too many meetings, scope creep) and no underlying diagnosis. From the outside the team looks well-managed; from inside it feels like rituals running on inertia. Nobody can answer &amp;ldquo;what is this team&amp;rsquo;s process actually for&amp;rdquo; without falling back on the names of meetings.&lt;/p&gt;
&lt;p&gt;The reflex is to cut meetings. Cancel one, the others stay; the calendar gets quieter, the velocity stays flat, and the same three engineers keep looking. The problem isn&amp;rsquo;t meeting volume. The team has no process design: no answer to what each person is at the team to produce, what role they fill, what output flows from them to whom. Cutting rituals doesn&amp;rsquo;t add design. It removes friction from a system that wasn&amp;rsquo;t producing anything in particular.&lt;/p&gt;
&lt;h2 id="process-beats-capacity"&gt;Process beats capacity
&lt;/h2&gt;&lt;p&gt;NYC port had less infrastructure than Boston or Charleston in 1817. By 1830 it was the dominant Atlantic port and stayed that way for the next century. The difference was one decision in 1818: Black Ball Line started running ships on a published monthly schedule from NYC to Liverpool, full hold or not. Boston ran ships when there was cargo. Charleston the same. Traders started routing through NYC because they could plan around the schedule. Volume followed predictability, predictability compounded into market position, and the gap kept widening for a century. The engineering equivalent is the same shape. A team that ships on schedule draws downstream commitments. Partner teams plan around it. Leadership trusts it with bigger scope. Customers stop hedging. A team that ships fast when convenient does not.&lt;/p&gt;
&lt;p&gt;Andy Grove&amp;rsquo;s &lt;em&gt;High Output Management&lt;/em&gt; opens with a breakfast service. Same people, same stove, same eggs. With role design (one cook on the line, one runner, one dishwasher) the kitchen produces roughly twice the output of the same people working as a generalist mob. Grove&amp;rsquo;s frame is that a manager&amp;rsquo;s output is the output of the organization under their influence, and the leverage is in process design rather than in the manager&amp;rsquo;s individual speed at any task. An engineering team is the same shape. A team where everyone does everything looks egalitarian and produces less than a team where each person owns a role that uses their strengths and feeds the next person&amp;rsquo;s input.&lt;/p&gt;
&lt;p&gt;NASA&amp;rsquo;s Apollo mission control ran the same shape under maximum stakes. Each flight controller owned a specific system: FIDO for trajectory, RETRO for the return burn, EECOM for electrical and life support. The Flight Director consolidated. Each role had a clear handoff to the people whose decisions depended on theirs. The same engineers working as generalists across every screen would have caught nothing in time. When Apollo 13&amp;rsquo;s CO2 scrubber failed, the room routed the problem to the right console in seconds. The role design was what made that speed possible.&lt;/p&gt;
&lt;p&gt;These run on the same mechanism: consumable chunks on a held schedule, each station fed by the one before it. The Toyota Production System named the principle decades later. Place each person where the work arrives. Arrange the layout so output flows to the next station without wasted motion. A line designed that way produces more than the same people working as a generalist mob, because the design strips out the waiting, the searching, and the reaching that eat individual capacity. Engineering teams that ship reliably run the same shape, with whatever chunks and whatever schedule the work can sustain.&lt;/p&gt;
&lt;h2 id="roles-as-the-unit-of-design"&gt;Roles as the unit of design
&lt;/h2&gt;&lt;p&gt;Each station on that line is a role. &lt;em&gt;Team Topologies&lt;/em&gt; frames a team as exposing an API: the interface other teams plan against. The same shape applies inside a team. A role is an interface. The rest of the team needs to know what outcome it produces, who is accountable, and the cadence it runs on. Take the code-review queue. Reviewing PRs is the activity, not the role. The engineer on this week&amp;rsquo;s rotation is accountable for the queue. The outcome is PRs reviewed within four hours, with reviewers learning from each other in the process. The cadence is weekly: the rotation rolls every Monday. A team with that interface explicit has a designed role. A team with just the activity has a queue that may or may not produce anything. Roles fit together by design: one role&amp;rsquo;s output is another&amp;rsquo;s input, and engineers cooperate at the boundaries instead of throwing work over a wall. Owning a scope means accountability for what comes out of it, not territory.&lt;/p&gt;
&lt;p&gt;A team&amp;rsquo;s process is the set of roles it runs and the way work passes between them. A team without designed roles still has roles. They emerged accidentally, drifted to whoever was loudest or most senior, and rarely get pruned. Most silos start there: a role belongs to one person not because the team chose them, but because they happened to be the one who picked it up.&lt;/p&gt;
&lt;p&gt;Three rules separate designed roles from drifted ones:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Custom to the team, not a template.&lt;/strong&gt; Spotify Squads, Atlassian Goalies, the latest FAANG framework: every successful process is the team&amp;rsquo;s own. Importing someone else&amp;rsquo;s wholesale gets the form without the function. Templates are inputs to design, not the design itself.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Each role owns an outcome, not a task list.&lt;/strong&gt; A role that lists what to do produces compliance. A role that names the outcome the IC owns produces ownership. The difference shows up over a quarter: owners go deep, propose improvements, push back on bad designs, and stay engaged. Task-fillers don&amp;rsquo;t. The team&amp;rsquo;s reputation across the org follows the depth: whatever the team owns gets serious treatment, and the team gets credit for it.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cadence justifies itself by output.&lt;/strong&gt; A weekly meeting that exists because &amp;ldquo;that is our cadence&amp;rdquo; is a role optimized for nothing in particular. Each recurring role should serve a specific output. An SRE-to-INFRA weekly runs weekly because cross-team dependency surprises happen on a weekly horizon, and the meeting is less evil than the alternative of implementing in silos and surprising each other with operational load. Roles without a justification should be ad-hoc, set up when a purpose appears and dissolved when it goes away.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="the-managers-role"&gt;The manager&amp;rsquo;s role
&lt;/h2&gt;&lt;p&gt;The manager designs the interface and picks the people to staff it. Which roles exist, what each one produces, the cadences, the handoffs - those are decisions, not emergent properties. The manager hires into the roles, understands what each engineer does well and badly, and places them where the role&amp;rsquo;s outcome and the engineer&amp;rsquo;s strengths meet. When two roles overlap or interfere, redrawing the boundary is the manager&amp;rsquo;s call.&lt;/p&gt;
&lt;p&gt;The manager also decides last. ICs propose. The manager arbitrates from the only seat in the room that sees all roles at once. A team that runs every decision past its manager has a manager doing the team&amp;rsquo;s work. The reverse failure is a team that never escalates anything, where the manager has quietly stopped owning the scope.&lt;/p&gt;
&lt;p&gt;Priorities are the other lever. Most engineers have a tendency to rewrite things they find ugly.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The rewrite cycle&lt;/strong&gt;
 &lt;div&gt;If it were up to engineers, no release would ever ship. The legacy gets rewritten, the rewrite ages into legacy, and the rewrite of the rewrite begins.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The manager carries the business context that engineers do not always see: what the company is trying to do this quarter, what each system costs to run, what the customer actually pays for. That context turns &amp;ldquo;rebuild this because it&amp;rsquo;s ugly&amp;rdquo; into &amp;ldquo;fix the slow part first because it doubles conversion.&amp;rdquo; Low-hanging fruit and process optimization beat rebuilding from scratch nearly every time.&lt;/p&gt;
&lt;p&gt;Take a talented IC. Do they ship more inside the process you built than they would alongside the same teammates with no designed roles at all? Grove&amp;rsquo;s frame from the breakfast service makes this the central test: a manager&amp;rsquo;s output is the output of the team under their influence. A process that fits the work makes a strong IC compound: their output flows into a role where someone else is waiting for it, and that person&amp;rsquo;s output flows somewhere in turn. Without designed roles, the same IC works hard and the team still drifts, because the work has nowhere to go between people. That delta, between what the IC ships with the process and what they ship without it, is the manager&amp;rsquo;s actual output.&lt;/p&gt;
&lt;p&gt;The delta has a second face that velocity charts miss. A role with a named outcome and a clear handoff lets the IC running it see who is waiting on their work and what gets built on top of it. That visibility is what makes the team feel like a team, and what makes engineers want to push the work forward instead of clearing tickets. A process that ships work but leaves engineers feeling interchangeable is missing the half of the manager&amp;rsquo;s output that the engineers themselves feel.&lt;/p&gt;
&lt;h2 id="write-the-interface-down"&gt;Write the interface down
&lt;/h2&gt;&lt;p&gt;That kind of visibility does not happen by default. The interface only exists for the rest of the team if it is written down. Every role gets a short entry: the owner, the outcome it produces, the cadence it runs on, the SLA it holds itself to, who pages who when something slips. &lt;em&gt;Team Topologies&lt;/em&gt; publishes a Team API template for the team-to-team version, and the same shape works scoped down to the role level. The doc lives somewhere everyone reads, whether a wiki page, a pinned Slack thread, or the README of a process repo. Without a written record the interface lives in one person&amp;rsquo;s head, and the team is one departure away from rediscovering whose role each thing was. The doc is also where the team negotiates changes: an outcome shifts, a cadence moves, an owner rotates, and the change is visible to everyone affected before it happens. The same doc carries into quarterly reviews. A role&amp;rsquo;s outcome is what its owner committed to producing, and the review can work from a shared reference instead of from whatever incidents are easiest to recall. Engineers know in advance what the bar is.&lt;/p&gt;
&lt;h2 id="parts-ii-and-iii-as-worked-examples"&gt;Parts II and III as worked examples
&lt;/h2&gt;&lt;p&gt;This series puts role design to work. &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-ii-a-two-stage-standup/" &gt;Part II&lt;/a&gt; covers the morning declaration and 3pm sync as a productivity cadence: two roles that turn morning intent into the day&amp;rsquo;s output. &lt;a class="link" href="https://explainanalyze.com/p/how-teams-actually-finish-what-they-start-part-iii-a-working-responder-rotation/" &gt;Part III&lt;/a&gt; covers the responder rotation as the role that protects the others, especially for SRE, DevOps, and platform teams whose work is otherwise pinged into noise.&lt;/p&gt;
&lt;p&gt;Both are worked examples of the same discipline. Name the role, name the outcome, design the cadence to fit, measure what comes out, and prune the roles that don&amp;rsquo;t justify themselves. None of them is a template to copy. The discipline transfers; the specifics depend on your team.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;Process design overhead exceeds benefit in four cases.&lt;/p&gt;
&lt;p&gt;Genuinely small teams (three or fewer) where the &amp;ldquo;process&amp;rdquo; is mostly synchronous conversation. Designing roles for three people is over-engineering when the three of them can talk in real time about anything that matters.&lt;/p&gt;
&lt;p&gt;Pre-PMF or product-discovery teams, where the activity boundaries themselves are unstable. When the team does not yet know what it should be producing, designing roles around outcomes locks in the wrong shape, and the cost of redesigning weekly outpaces the cost of running ad-hoc. Stay loose until the work has a recognizable rhythm, then design.&lt;/p&gt;
&lt;p&gt;Pure-research environments where output is uncertain by definition. Process design assumes a known output to optimize for; research breaks that assumption. The right structure for research is closer to &amp;ldquo;give people room to wander and meet to share findings.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Crisis modes. Incidents, deploy days, market events. The ad-hoc response is the right move, and process discipline is the wrong tool until the crisis is over. Resume role discipline after.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;A team designed as a process is one whose members can answer &amp;ldquo;what role do I fill, what outcome do I own, what flows in and out.&amp;rdquo; That answer is the difference between rituals running on inertia and rituals serving output. From the outside the rituals look the same; the team&amp;rsquo;s quarter does not.&lt;/p&gt;
&lt;p&gt;The teams that improve over a year tend to be the teams where someone designed the process: pruned the roles that did not justify themselves, gave each surviving role an owner, made the cadence honest. Teams that don&amp;rsquo;t improve usually didn&amp;rsquo;t have that work happening.&lt;/p&gt;</description></item><item><title>Testing Your Database, Part 1: Why AI Made It Mandatory</title><link>https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/</link><pubDate>Tue, 10 Feb 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Testing Your Database, Part 1: Why AI Made It Mandatory" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;AI removed the implicit human review that used to catch database bugs. The engineer writing the migration was the test, and that test was never written down or runnable in CI. Once an LLM writes any portion of your data layer, the test suite is the only line between hallucinated SQL and a production incident.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A senior engineer asks an assistant to write a query returning each user&amp;rsquo;s total order value. The codebase has used soft deletes for three years; &lt;code&gt;deleted_at&lt;/code&gt; columns are on most tables. The model produces:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;COALESCE&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The query compiles. It runs. It returns numbers. It&amp;rsquo;s wrong: there&amp;rsquo;s no &lt;code&gt;o.deleted_at IS NULL&lt;/code&gt; predicate, so soft-deleted orders inflate every total. The reviewer skims the diff, sees &lt;code&gt;LEFT JOIN&lt;/code&gt;, sees &lt;code&gt;COALESCE&lt;/code&gt;, sees &lt;code&gt;deleted_at IS NULL&lt;/code&gt; somewhere in the &lt;code&gt;WHERE&lt;/code&gt; clause, approves. The bug ships. A finance dashboard over-reports revenue by 7% for two months until a customer flags a discrepancy against their own records.&lt;/p&gt;
&lt;h2 id="the-new-shape-of-database-failure"&gt;The new shape of database failure
&lt;/h2&gt;&lt;p&gt;The bugs an LLM introduces don&amp;rsquo;t look like junior-developer bugs. Junior devs ship SQL that doesn&amp;rsquo;t compile, throws an obvious type error, or returns nothing at all: the kind of failure CI catches by running the query once. The model ships SQL that compiles, runs, and returns something, just not the right something. It pattern-matched on a million open-source codebases and missed the rule that lives only in yours: the soft-delete convention this team adopted three years ago, the multi-tenancy filter every query is supposed to carry, the polysemic &lt;code&gt;TINYINT&lt;/code&gt; whose &lt;code&gt;0&lt;/code&gt; means &amp;ldquo;unknown&amp;rdquo; in one column and &amp;ldquo;free tier&amp;rdquo; in another, the denormalized counter that has to be bumped in the same transaction as the row it counts.&lt;/p&gt;
&lt;p&gt;The obvious response is &amp;ldquo;review AI-generated code more carefully.&amp;rdquo; That doesn&amp;rsquo;t survive contact with how reviews actually happen. &lt;a class="link" href="https://www.anthropic.com/research/AI-assistance-coding-skills" target="_blank" rel="noopener"
 &gt;Engineers using AI assistance score measurably lower on comprehension quizzes about the code they shipped&lt;/a&gt;; they read the output less carefully than the code they would have written themselves, the syntax is right, the change is small, and the reviewer ratifies. Even if that effect didn&amp;rsquo;t exist, the reviewer who can spot the missing &lt;code&gt;o.deleted_at IS NULL&lt;/code&gt; is the same reviewer who would have written the predicate in the first place, which is exactly the value AI was supposed to provide. &amp;ldquo;Review more carefully&amp;rdquo; asks the team to do a check the AI was supposed to obviate.&lt;/p&gt;
&lt;p&gt;It also misses how broad the surface is. The same reasoning shape (plausible SQL that pattern-matches on training data and misses the local rule) produces migrations that lock production at scale, upserts that assume a &lt;code&gt;UNIQUE&lt;/code&gt; that was never declared, indexes the planner won&amp;rsquo;t use, and &lt;code&gt;CHECK&lt;/code&gt; constraints that allow the state transition the team wanted to forbid. The SQL is syntactically valid in every case; the EXPLAIN is clean; the failure only appears against real data, real concurrency, real volume, or the conventions that live in nobody&amp;rsquo;s head but the team&amp;rsquo;s.&lt;/p&gt;
&lt;h2 id="what-the-experienced-engineer-was-doing-that-ci-doesnt"&gt;What the experienced engineer was doing that CI doesn&amp;rsquo;t
&lt;/h2&gt;&lt;p&gt;Before the model wrote that &lt;code&gt;LEFT JOIN&lt;/code&gt;, an engineer who had been on the team for a year would have done several things in their head:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Recognized the soft-delete convention from the column naming pattern and added &lt;code&gt;o.deleted_at IS NULL&lt;/code&gt; to the join, because the team&amp;rsquo;s rule is &amp;ldquo;every query that isn&amp;rsquo;t an audit filters soft-deletes on every joined table.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;Considered whether the report should attribute orders to soft-deleted users at all (probably not for revenue; possibly yes for retention analysis) and asked the requester instead of guessing.&lt;/li&gt;
&lt;li&gt;Recognized &lt;code&gt;o.amount&lt;/code&gt; is nullable for refund rows and decided whether refunds count toward the total or not.&lt;/li&gt;
&lt;li&gt;Checked whether the &lt;code&gt;orders&lt;/code&gt; table has a &lt;code&gt;tenant_id&lt;/code&gt; column the multi-tenancy filter requires, and added the predicate the codebase&amp;rsquo;s row-level security depends on.&lt;/li&gt;
&lt;li&gt;Recalled that an earlier version of this exact report shipped six months ago with a JOIN through &lt;code&gt;order_items&lt;/code&gt;, doubled every total, and required a backfill, and chose the simpler aggregation deliberately.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of these checks is in CI. Each is the kind of context the &lt;a class="link" href="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/" &gt;first post in the AI series&lt;/a&gt; describes: information the schema doesn&amp;rsquo;t carry, that lives in the engineer&amp;rsquo;s head, that the model has no way to read. That post argues for putting as much of that context back into the catalog as possible: declared FKs, column comments, named constraints, conventions. The work raises the floor; it doesn&amp;rsquo;t change what&amp;rsquo;s true here. Even with a perfectly described catalog, no schema declaration says &amp;ldquo;this team&amp;rsquo;s rule is to filter soft-deletes on every joined table&amp;rdquo; or &amp;ldquo;the previous version of this query had a JOIN cardinality bug, don&amp;rsquo;t repeat it.&amp;rdquo; Some classes of risk only exist at runtime against real data, real conventions, and real history, and the test suite is the only place those conditions can be reproduced before production.&lt;/p&gt;
&lt;h2 id="confidence-is-anti-signal"&gt;Confidence is anti-signal
&lt;/h2&gt;&lt;p&gt;The dangerous dynamic isn&amp;rsquo;t that the model gets things wrong. It&amp;rsquo;s that it sounds most confident exactly where it&amp;rsquo;s most likely wrong. Ask for a basic &lt;code&gt;SELECT&lt;/code&gt; with a &lt;code&gt;JOIN&lt;/code&gt; and the output is right, no hedging. Ask for NULL semantics in an outer join, timezone arithmetic across a DST boundary, isolation-level behavior under contention, dialect-specific JSON path syntax, or a window-function frame clause, and the output reads with the same calm tone. The probability of correctness has dropped; the prose around it hasn&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;Human reviewers anchor on tone. There&amp;rsquo;s no visual signal in the diff that says &amp;ldquo;this part lives in a region where the training data is sparse and contradictory.&amp;rdquo; A query that drops rows because of an unintended tie in &lt;code&gt;ORDER BY created_at LIMIT 100 OFFSET 200&lt;/code&gt; reads exactly like a query that doesn&amp;rsquo;t. A &lt;code&gt;CHECK&lt;/code&gt; that lists valid values but doesn&amp;rsquo;t constrain transitions reads exactly like one that does. The reviewer&amp;rsquo;s internal calibration (&amp;ldquo;this part looked sketchy, I&amp;rsquo;ll dig&amp;rdquo;) is fed by uncertainty cues that the model doesn&amp;rsquo;t emit. &amp;ldquo;Review more carefully&amp;rdquo; cannot fix this, because the things worth scrutinizing don&amp;rsquo;t look worth scrutinizing.&lt;/p&gt;
&lt;h2 id="volume-changes-the-math"&gt;Volume changes the math
&lt;/h2&gt;&lt;p&gt;The bugs above existed before AI. What changed is the rate. A team that used to ship eight migrations a week now ships eighty, because the cost of writing one collapsed and the cost of reviewing one didn&amp;rsquo;t. The reviewer who used to give each migration ten minutes now gets one; the senior engineer who would have caught the soft-delete bug on her own change has eight more changes in queue waiting for the same scrutiny. The implicit human review didn&amp;rsquo;t disappear, it got rationed.&lt;/p&gt;
&lt;p&gt;The acute version of this is the wrong query that ships to production. The chronic version is schema drift, and it&amp;rsquo;s worse. Naming conventions decay because nobody enforces them on every PR. Redundant indexes accumulate because the model suggested one without checking what already exists. &lt;code&gt;NOT NULL&lt;/code&gt; constraints get dropped because the migration was failing and removing the constraint made it pass. Soft deletes get reinvented every quarter because each AI session starts fresh on the team&amp;rsquo;s conventions, and &amp;ldquo;fresh&amp;rdquo; plus &amp;ldquo;confident&amp;rdquo; plus &amp;ldquo;eighty PRs a week&amp;rdquo; is how a codebase ends up with three different ways to mark a row deleted, all in production.&lt;/p&gt;
&lt;p&gt;None of this is catastrophic in any given week. The compounding cost shows up eighteen months later, when query plans degrade, an ORM upgrade exposes the inconsistencies, or a new engineer can&amp;rsquo;t tell which of three &amp;ldquo;current&amp;rdquo; patterns to follow. The test suite isn&amp;rsquo;t only catching the acute incident; it&amp;rsquo;s the artifact that resists the drift, because every assertion the team writes is a convention written down where the next session can&amp;rsquo;t unlearn it.&lt;/p&gt;
&lt;p&gt;Murphy&amp;rsquo;s Law used to apply intermittently. With AI in the loop, it applies 100% of the time. Every weak corner of the test suite gets exercised on a weekly cadence, and what used to be a rare edge case becomes the load-bearing case.&lt;/p&gt;
&lt;h2 id="the-failure-mode-is-broader-than-wrong-queries"&gt;The failure mode is broader than wrong queries
&lt;/h2&gt;&lt;p&gt;The soft-delete bug is one shape. The same dynamic produces every other class of database failure AI introduces:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Migrations that lock production at scale.&lt;/strong&gt; Asked to add a &lt;code&gt;tier&lt;/code&gt; column to &lt;code&gt;users&lt;/code&gt;, the model produces &lt;code&gt;ALTER TABLE users ADD COLUMN tier TINYINT NOT NULL DEFAULT 0&lt;/code&gt;. CI&amp;rsquo;s empty-database migration test runs in 200ms and passes; in production, MySQL rewrites all 50 million rows under a metadata lock for 40 minutes during business hours. The DDL is syntactically valid; the failure is volumetric, and CI is structurally incapable of seeing it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;JOIN cardinality bugs that produce plausible numbers.&lt;/strong&gt; An AI-generated &lt;code&gt;LEFT JOIN&lt;/code&gt; with a predicate placed in the &lt;code&gt;WHERE&lt;/code&gt; rather than the &lt;code&gt;ON&lt;/code&gt; clause filters out the unmatched side; a JOIN through a bridge table without composite &lt;code&gt;UNIQUE&lt;/code&gt; multiplies aggregations. The result set has the right shape, the row count is plausible, the number is wrong. Catching it requires a test that asserts the result against a known dataset where the failure mode would change the count.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Upserts assuming undeclared constraints.&lt;/strong&gt; &lt;code&gt;ON CONFLICT (email) DO UPDATE&lt;/code&gt; is correct only if &lt;code&gt;email&lt;/code&gt; actually has a &lt;code&gt;UNIQUE&lt;/code&gt; constraint. Without it, PostgreSQL throws the moment the planner sees no usable arbiter index; in some MySQL configurations, the equivalent &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; silently inserts duplicates because there&amp;rsquo;s no key to conflict on. The model writes the upsert from the column name and the question, doesn&amp;rsquo;t check the catalog for the constraint, and the test database has no concurrent writers exercising the path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CHECK constraints that look right and aren&amp;rsquo;t.&lt;/strong&gt; Asked to &amp;ldquo;prevent transitioning from &lt;code&gt;cancelled&lt;/code&gt; to &lt;code&gt;active&lt;/code&gt;,&amp;rdquo; the model emits &lt;code&gt;CHECK (status IN ('pending','active','cancelled'))&lt;/code&gt;, which lists the valid values but doesn&amp;rsquo;t constrain transitions. The constraint is syntactically right, semantically wrong, and indistinguishable from a working constraint until an &lt;code&gt;UPDATE&lt;/code&gt; in production succeeds where it shouldn&amp;rsquo;t.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Indexes the planner will ignore.&lt;/strong&gt; Asked to speed up &lt;code&gt;WHERE LOWER(email) = ?&lt;/code&gt;, the model adds &lt;code&gt;CREATE INDEX ON users (email)&lt;/code&gt;. The planner can&amp;rsquo;t use it for the function call; the query stays slow; the EXPLAIN was never inspected because the index was the visible &amp;ldquo;fix.&amp;rdquo;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Every one of these is detectable. None of them is detected by the kind of test most teams run.&lt;/p&gt;
&lt;h2 id="what-test-the-database-actually-means-today"&gt;What &amp;ldquo;test the database&amp;rdquo; actually means today
&lt;/h2&gt;&lt;p&gt;For most teams, &amp;ldquo;we test the database&amp;rdquo; means one of two things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The application&amp;rsquo;s unit tests use a real database (often SQLite or an empty Postgres) for fixtures, and they pass.&lt;/li&gt;
&lt;li&gt;CI runs &lt;code&gt;db:migrate&lt;/code&gt; against a fresh empty database before the test suite, and it doesn&amp;rsquo;t error.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Neither is testing the database. The first tests the application&amp;rsquo;s happy path with a database underneath. The second tests migration syntax. Both leave the entire surface above untested. The class of failure AI introduces - semantically valid SQL that misbehaves under realistic conditions - passes both checks every time.&lt;/p&gt;
&lt;p&gt;What&amp;rsquo;s missing is a layer of tests that asserts against the database&amp;rsquo;s actual behavior on representative data: the migration finishes within a duration budget; the constraint rejects the values it claims to; the query, run against a known fixture, returns the expected count and the expected aggregate; the index in the EXPLAIN is actually used; the schema invariants the team thinks they have are present and behave the way the team thinks they do. These categories of test exist. Tools for each have existed for years. Most teams have never written them. Pre-AI, the teams that didn&amp;rsquo;t write them got away with it because the engineer writing each migration and each query was applying the checks in their head: slowly, with friction, sometimes wrong, but applying them. Post-AI, that engineer is increasingly not in the loop, and the only thing left is what&amp;rsquo;s actually written down.&lt;/p&gt;
&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/" &gt;Part 2&lt;/a&gt; covers what to test in each category and the tools that exist for each.&lt;/p&gt;
&lt;h2 id="when-this-doesnt-apply"&gt;When this doesn&amp;rsquo;t apply
&lt;/h2&gt;&lt;p&gt;The argument is conditional: if AI is writing any portion of your data layer, you need this. Cases where the conditional doesn&amp;rsquo;t hold:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;AI isn&amp;rsquo;t writing your migrations or queries.&lt;/strong&gt; The team uses AI for application-level boilerplate; SQL and schema changes are still hand-written. The implicit human review is intact for the data layer, and the case for tests is the same as it was before.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The database is small and single-writer.&lt;/strong&gt; A 200-row admin table maintained by one service. Lock duration on &lt;code&gt;ALTER&lt;/code&gt; is microseconds, JOIN cardinality is unambiguous, the surface AI can hurt is small enough to manage by reading every diff.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The work is read-only and a domain expert validates each result.&lt;/strong&gt; An analyst uses AI to draft queries and reviews each result against expectations. The AI is generating drafts, not shipping queries. The domain expert is the test, the same way the senior engineer used to be.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The data is throwaway.&lt;/strong&gt; Dev environments, ephemeral analytics, throwaway scripts. The cost of being wrong is low and the failures are reversible.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For everything else (production-facing systems, multi-writer schemas, data the business depends on) the conditional holds.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Automation moves verification work; it doesn&amp;rsquo;t eliminate it. Pre-AI, &amp;ldquo;we don&amp;rsquo;t really test the database&amp;rdquo; worked for most teams because the engineer writing each migration and each query was the test, applying dozens of unwritten checks per change. The check was slow, expensive, and unreliable, but it existed. Post-AI, the engineer is increasingly not in the loop, and the team&amp;rsquo;s database verification is whatever the test suite explicitly asserts. The useful choice isn&amp;rsquo;t whether to verify; it&amp;rsquo;s whether to verify in CI or in production.&lt;/p&gt;
&lt;p&gt;The picture worsens with agents in the loop. An agent that runs migrations, executes restores, or modifies schemas under its own permissions doesn&amp;rsquo;t have an implicit human review even at the moment of execution. A model that&amp;rsquo;s right 99.9% of the time, given a thousand operations a week, ships a serious incident every two weeks (and &amp;ldquo;right 99.9%&amp;rdquo; is generous). The test suite is what makes any of that safe; the cost of building it is a fraction of the cost of one production incident, and AI made the math explicit.&lt;/p&gt;
&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/" &gt;Part 2&lt;/a&gt; covers what each layer has to assert and the frameworks (Squawk, pgTAP, Testcontainers, lock-duration probes, result-regression diffs) that already exist for each category.&lt;/p&gt;</description></item><item><title>What AI Gets Wrong About Your Database</title><link>https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/</link><pubDate>Tue, 03 Feb 2026 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post What AI Gets Wrong About Your Database" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A current model writing SQL handles joins, duplicate rows and date columns well, and gets wrong what the schema never states: what a value means. In a measured test here, an agent with access to the data worked that meaning out by inference, at about six times the time and cost of a column comment that simply stated it.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The working assumption in most teams by now is that a capable model, shown the schema, writes the query a careful analyst would. It mostly does. Asked for Q1 2026 revenue per enterprise customer on a three-table PostgreSQL 18 schema, Opus 5.5 avoided a duplicate-row trap in the tags table without being told about it, chose the payment date over the cart date, and wrote the same query in five runs out of five. All five overstated revenue by 10%: $1,762,496 against $1,601,792. All five also said why, in a comment above the SQL: &amp;ldquo;The status codes are undocumented, so status is not used.&amp;rdquo; Status 3 meant refunded. The model had read everything the database said about itself, and the database never said that.&lt;/p&gt;
&lt;h2 id="the-same-question-against-three-versions-of-one-schema"&gt;The same question against three versions of one schema
&lt;/h2&gt;&lt;p&gt;The fixture was built for this test, so its gaps are planted rather than found, and it is small: 2,000 customers, 60,000 orders, and a &lt;code&gt;customer_tags&lt;/code&gt; table in which one customer in five carries the tag &lt;code&gt;enterprise&lt;/code&gt;. It has three gaps that real schemas tend to have. &lt;code&gt;orders.status&lt;/code&gt; is a &lt;code&gt;smallint&lt;/code&gt; with three values and no documentation, where 1 is awaiting payment, 2 is paid and 3 is refunded. &lt;code&gt;orders&lt;/code&gt; has two timestamps, &lt;code&gt;created_at&lt;/code&gt; for when the cart was opened and &lt;code&gt;paid_at&lt;/code&gt; for when the money arrived. And a legacy import tagged 24 of the 400 enterprise customers twice, which nothing prevented because &lt;code&gt;customer_tags&lt;/code&gt; had no unique key.&lt;/p&gt;
&lt;p&gt;The model got the question three ways, five times each. The first two runs put the output of &lt;code&gt;pg_dump --schema-only&lt;/code&gt; in the system prompt and gave the model no tools. In one copy of the database that dump had names, types and primary keys only. In the other, the same data had a primary key on &lt;code&gt;customer_tags&lt;/code&gt; (after removing the duplicates), foreign keys, a &lt;code&gt;CHECK&lt;/code&gt; on &lt;code&gt;status&lt;/code&gt;, and five column comments, one of them &lt;code&gt;'1 = awaiting payment (paid_at is NULL), 2 = paid, 3 = refunded (paid_at is kept). Revenue counts status 2 only.'&lt;/code&gt; The third condition had the bare dump plus a shell tool that ran read-only queries as a role with &lt;code&gt;default_transaction_read_only&lt;/code&gt; on, which is roughly what a database MCP server gives an agent. Every run used Opus 5.5 through Claude Code in print mode, and every answer was graded by running its SQL and comparing all 400 per-customer totals with the correct ones.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Condition (5 runs each)&lt;/th&gt;
 &lt;th&gt;Correct&lt;/th&gt;
 &lt;th&gt;Total returned&lt;/th&gt;
 &lt;th&gt;Median time&lt;/th&gt;
 &lt;th&gt;Median cost&lt;/th&gt;
 &lt;th&gt;Turns&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Catalog only: names, types, primary keys&lt;/td&gt;
 &lt;td&gt;0 of 5&lt;/td&gt;
 &lt;td&gt;$1,762,495.70 (+10.0%)&lt;/td&gt;
 &lt;td&gt;10.8 s&lt;/td&gt;
 &lt;td&gt;$0.025&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Catalog + read-only access to the data&lt;/td&gt;
 &lt;td&gt;5 of 5&lt;/td&gt;
 &lt;td&gt;$1,601,791.94&lt;/td&gt;
 &lt;td&gt;49.3 s&lt;/td&gt;
 &lt;td&gt;$0.111&lt;/td&gt;
 &lt;td&gt;7–11&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Documented catalog: keys, CHECK, comments&lt;/td&gt;
 &lt;td&gt;5 of 5&lt;/td&gt;
 &lt;td&gt;$1,601,791.94&lt;/td&gt;
 &lt;td&gt;8.5 s&lt;/td&gt;
 &lt;td&gt;$0.017&lt;/td&gt;
 &lt;td&gt;1&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img alt="Dot chart of the total each condition returned, five identical runs each. Catalog only: $1,762,496, which is right only if status 3 is paid on invoice. Catalog plus data access: $1,601,792. Documented catalog: $1,601,792, which is right because status 3 is a refund." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/three-catalogs.svg"&gt;&lt;/p&gt;
&lt;p&gt;The catalog-only runs did better work than the 0 in that table suggests. All five guarded the tags join, four with &lt;code&gt;EXISTS&lt;/code&gt; and one with &lt;code&gt;DISTINCT&lt;/code&gt;, and every one gave the missing key as the reason: &amp;ldquo;customer_tags has no unique key, so a join could double-count.&amp;rdquo; So the model read the missing constraint as a warning. A plain join would have added $91,887 for the 24 doubled customers. All five used &lt;code&gt;paid_at&lt;/code&gt; and stated that choice as an assumption too. The one decision they could not make was the one the schema gave them nothing to make it with, and they left status out and said so.&lt;/p&gt;
&lt;p&gt;There is a detail in that wrong total worth sitting with. $1,762,495.70 is exactly the right answer if status 3 means &amp;ldquo;paid on invoice&amp;rdquo; instead of &amp;ldquo;refunded&amp;rdquo;. The data looks the same under both readings, since both have a &lt;code&gt;paid_at&lt;/code&gt; and both are a minority of rows, so the bare-catalog model and the agent below were each right under one reading of the same column. Only the comment decided which reading was true.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Note&lt;/strong&gt;
 &lt;div&gt;This is one model, one fixture and five runs per condition, so it measures where the meaning lived in this schema, not an accuracy rate for the model. A different question, a different model or a schema with fifty tables would move the numbers. The direction is the part that carries over, because it rests on what was and was not written in the catalog rather than on how clever the model was.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="letting-the-agent-read-the-data"&gt;Letting the agent read the data
&lt;/h2&gt;&lt;p&gt;The 2026 answer to a model that lacks context is to let it look. At Google Cloud Next in April, Google &lt;a class="link" href="https://cloud.google.com/blog/products/databases/whats-new-for-google-cloud-databases-at-next26" target="_blank" rel="noopener"
 &gt;announced managed remote MCP servers&lt;/a&gt; for AlloyDB, Cloud SQL, Spanner, Bigtable and Firestore. Databricks &lt;a class="link" href="https://www.databricks.com/blog/how-agentic-software-development-will-change-databases" target="_blank" rel="noopener"
 &gt;wrote in March&lt;/a&gt; that agents on Lakebase create roughly four times as many databases as human users do. An agent with a connection can profile a column before it filters on it, which is the check an experienced analyst runs by habit.&lt;/p&gt;
&lt;p&gt;And in the test it worked. The agent got all five runs right, and its reasoning was sound: status 1 never had a &lt;code&gt;paid_at&lt;/code&gt;, so it looked unpaid; status 2 was about 80% of orders; status 3 had a payment date but was a small share, so it &amp;ldquo;looks like refunds&amp;rdquo;. It also found the doubled tags, noticed that the extra copies all carried the same timestamp (2025-03-14 02:00) and called that a bulk load. Every run said the meaning was inferred, and most said what to change if the guess was wrong, one of them in so many words: &amp;ldquo;If status 3 turns out not to mean refunded, change the filter to &lt;code&gt;status IN (2, 3)&lt;/code&gt;.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;That sentence is the limit. The data supported &amp;ldquo;refund&amp;rdquo; because refunds happen to be rare and keep their payment date, and an invoicing status would look identical. Had status 3 meant paid on invoice, the same reasoning would have produced the same query and come in 9.1% short. The agent was honest about the guess, which moves the problem to the person reading the answer: to judge the caveat, they need to already know what status 3 means, and someone who knows that did not need to ask.&lt;/p&gt;
&lt;p&gt;&lt;img alt="Two bar charts, median of five runs. Seconds to answer: catalog only 11 s, catalog plus data access 49 s, documented catalog 8.5 s. API cost per answer: $0.025, $0.111 and $0.017." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/what-ai-gets-wrong-about-your-database/time-and-cost.svg"&gt;&lt;/p&gt;
&lt;p&gt;Inference also costs something on every question. The agent took 7 to 11 turns and a median of 49 seconds and $0.111 per answer, against 8.5 seconds and $0.017 for the documented catalog, which answered in one turn because it had nothing to work out. The comment is written once, and the inference is paid for again with every question anyone asks.&lt;/p&gt;
&lt;p&gt;Better models are the other half of the obvious fix, and the benchmark numbers look like they deliver it. The &lt;a class="link" href="https://arxiv.org/abs/2411.07763" target="_blank" rel="noopener"
 &gt;Spider 2.0 paper&lt;/a&gt;, built on enterprise databases that often have over 1,000 columns, reported that an o1-preview agent solved 21.3% of its tasks. By November 2026 the &lt;a class="link" href="https://spider2-sql.github.io/" target="_blank" rel="noopener"
 &gt;Spider 2.0-Snow leaderboard&lt;/a&gt; tops out at 96.70. In January, though, &lt;a class="link" href="https://arxiv.org/abs/2601.08778" target="_blank" rel="noopener"
 &gt;Jin, Choi, Zhu and Kang&lt;/a&gt; checked the reference answers themselves and found errors in 62.8% of Spider 2.0-Snow tasks and 52.8% of BIRD Mini-Dev. Re-scoring 16 agents on a corrected BIRD subset moved them by -7% to +31% and reshuffled the ranking by up to nine places. A leaderboard measures agreement with an answer key, and no one has an answer key for your schema.&lt;/p&gt;
&lt;h2 id="where-the-meaning-has-to-be-written-down"&gt;Where the meaning has to be written down
&lt;/h2&gt;&lt;p&gt;The test splits the gaps into two kinds. Some a model can discover, given time and a connection: duplicates exist or they don&amp;rsquo;t, a column is NULL in some rows or it isn&amp;rsquo;t. Others are facts about the business that the data is merely consistent with, and those are the ones only a declaration can carry. The table sorts the common gaps that way and points at the post that covers each one.&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Gap&lt;/th&gt;
 &lt;th&gt;What reading the data tells an agent&lt;/th&gt;
 &lt;th&gt;What only a declaration says&lt;/th&gt;
 &lt;th&gt;Covered in&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Relationships not declared (&lt;code&gt;creator_id&lt;/code&gt;, &lt;code&gt;placed_by&lt;/code&gt;)&lt;/td&gt;
 &lt;td&gt;Value ranges that overlap with some table&amp;rsquo;s ids&lt;/td&gt;
 &lt;td&gt;Which table the column refers to: a foreign key&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;Primary and foreign keys&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Bare &lt;code&gt;id&lt;/code&gt; columns on every table&lt;/td&gt;
 &lt;td&gt;Nothing; &lt;code&gt;a.id = b.id&lt;/code&gt; joins any pair and returns rows&lt;/td&gt;
 &lt;td&gt;The naming that makes the join obvious&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/" &gt;Generic &lt;code&gt;id&lt;/code&gt; primary keys&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;One column pointing at several tables&lt;/td&gt;
 &lt;td&gt;A type column next to an id column&lt;/td&gt;
 &lt;td&gt;That the join depends on the type, and how&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/polymorphic-references-are-not-foreign-keys/" &gt;Polymorphic references&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;JSON and TEXT payloads&lt;/td&gt;
 &lt;td&gt;The keys in whichever rows it samples&lt;/td&gt;
 &lt;td&gt;The other key names older rows still use&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/text-and-json-columns-where-the-schema-goes-to-hide/" &gt;TEXT and JSON columns&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;References into another database&lt;/td&gt;
 &lt;td&gt;Nothing, from inside one connection&lt;/td&gt;
 &lt;td&gt;That the other side exists&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/cross-database-joins-the-coupling-you-cant-see-until-you-split/" &gt;Cross-database joins&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Coded values (&lt;code&gt;status&lt;/code&gt;, &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;flag1&lt;/code&gt;)&lt;/td&gt;
 &lt;td&gt;How often each value occurs, and which other columns are empty with it&lt;/td&gt;
 &lt;td&gt;What each value means: a comment or a &lt;code&gt;CHECK&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Comment your schema&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Test rows and sentinel values&lt;/td&gt;
 &lt;td&gt;Outliers, if it looks for them&lt;/td&gt;
 &lt;td&gt;That &lt;code&gt;DO_NOT_USE@test.com&lt;/code&gt; is not a customer&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/reading-the-schema-is-not-reading-the-data/" &gt;Schema is not data&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Duplicates in a bridge table&lt;/td&gt;
 &lt;td&gt;That duplicates exist, if it counts&lt;/td&gt;
 &lt;td&gt;That they must not: a unique key&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/" &gt;Uniqueness and selectivity&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Business definitions (&amp;ldquo;active customer&amp;rdquo;)&lt;/td&gt;
 &lt;td&gt;Nothing&lt;/td&gt;
 &lt;td&gt;A view, a generated column or a &lt;code&gt;CHECK&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/" &gt;Where business logic lives&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Collation and charset differences&lt;/td&gt;
 &lt;td&gt;Joins that return fewer rows than expected&lt;/td&gt;
 &lt;td&gt;One collation per database&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/collation-drift-the-silent-index-killer/" &gt;Collation drift&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Naming that changed by era (&lt;code&gt;userId&lt;/code&gt;, &lt;code&gt;user_id&lt;/code&gt;)&lt;/td&gt;
 &lt;td&gt;Both spellings in use&lt;/td&gt;
 &lt;td&gt;Which one is current&lt;/td&gt;
 &lt;td&gt;&lt;a class="link" href="https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/" &gt;Schema conventions&lt;/a&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The middle column is what the 2026 tooling added, and it is real. Before agents had connections, everything in that column was out of reach too. It is also slow, paid per question, and a guess wherever the right column says something the data only hints at. When a team&amp;rsquo;s code defines the model in an ORM, the right column often exists, but in a model class the database never sees, which is the argument of &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;ORMs are a coupling&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Checking the result is the part none of this replaces. Application code has a compiler and a test suite that reject a broken change before anyone reads it. SQL has a parser, which accepts a wrong predicate as happily as a right one, and most teams review queries by reading them, which is exactly the check a fluent wrong query passes. &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-1-why-ai-made-it-mandatory/" &gt;Testing your database&lt;/a&gt; and &lt;a class="link" href="https://explainanalyze.com/p/testing-your-database-part-2-what-to-test-and-how/" &gt;its second part&lt;/a&gt; cover what an actual test of a query looks like. A richer catalog gives a test more to fail on.&lt;/p&gt;
&lt;h2 id="what-the-industry-built-in-2026-and-what-it-costs"&gt;What the industry built in 2026, and what it costs
&lt;/h2&gt;&lt;p&gt;Vendors reached the same conclusion and built a layer for it. Google&amp;rsquo;s &lt;a class="link" href="https://cloud.google.com/blog/products/databases/introducing-querydata-for-near-100-percent-accurate-data-agents" target="_blank" rel="noopener"
 &gt;QueryData announcement&lt;/a&gt; in April explains the accuracy gap with &amp;ldquo;Values can be ambiguous&amp;rdquo;, using a return-status column whose values are 1, 2 and 3, which is close to this fixture, and fixes it with a &amp;ldquo;schema ontology&amp;rdquo; of &amp;ldquo;descriptions of columns, tables and values&amp;rdquo;. Snowflake made &lt;a class="link" href="https://www.snowflake.com/en/blog/semantic-view-autopilot/" target="_blank" rel="noopener"
 &gt;Semantic View Autopilot&lt;/a&gt; generally available in February to generate semantic views from query history. Databricks&amp;rsquo; &lt;a class="link" href="https://docs.databricks.com/aws/en/ai-bi/release-notes/2026" target="_blank" rel="noopener"
 &gt;release notes&lt;/a&gt; say Genie Code now &amp;ldquo;prefers governed metric views over ad-hoc SQL datasets&amp;rdquo;. And the Open Semantic Interchange spec, meant to let those layers move between tools, &lt;a class="link" href="https://www.snowflake.com/en/blog/open-semantic-interchanges-specs-finalized/" target="_blank" rel="noopener"
 &gt;shipped a first version in January&lt;/a&gt; and has since become Apache Ossie (incubating). Atlan&amp;rsquo;s &lt;a class="link" href="https://atlan.com/know/ai-agent/semantic-layer/what-is-open-semantic-interchange/" target="_blank" rel="noopener"
 &gt;summary&lt;/a&gt; puts it plainly: &amp;ldquo;Most third-party tools do not import OSI directly today.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;A semantic layer can hold things a column comment can&amp;rsquo;t: a metric defined across six tables, synonyms, example questions and the query each one should produce. Its cost is that it is a second copy of the schema&amp;rsquo;s meaning, kept somewhere the schema&amp;rsquo;s migrations don&amp;rsquo;t touch, and read by whichever vendor&amp;rsquo;s agent it was built for. A comment goes the other way. It lives in &lt;code&gt;pg_description&lt;/code&gt; or &lt;code&gt;information_schema.COLUMNS&lt;/code&gt;, changes in the same migration as the column, and every tool that reads the catalog sees it, &lt;code&gt;psql&lt;/code&gt;&amp;rsquo;s &lt;code&gt;\d+&lt;/code&gt; included. The only published number for the in-database version is Tiger Data&amp;rsquo;s &lt;a class="link" href="https://www.tigerdata.com/blog/the-database-new-user-llms-need-a-different-database" target="_blank" rel="noopener"
 &gt;internal test of its semantic catalog&lt;/a&gt;, which reported &amp;ldquo;up to 27%&amp;rdquo; better SQL generation and noted that results varied a lot by schema. For definitions that span tables the semantic layer is the better home. For what a single column means, the column itself is.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Warning&lt;/strong&gt;
 &lt;div&gt;Giving an agent the data means giving it a connection, and the read-only switch in the tool is not the boundary. Datadog &lt;a class="link" href="https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/" target="_blank" rel="noopener"
 &gt;showed in 2025&lt;/a&gt; that &lt;code&gt;COMMIT; DROP SCHEMA public CASCADE;&lt;/code&gt; escaped the read-only transaction in the original reference PostgreSQL MCP server. In 2026 the same class of bug was assigned CVEs in &lt;a class="link" href="https://www.tenable.com/cve/CVE-2026-48774" target="_blank" rel="noopener"
 &gt;ProxySQL&amp;rsquo;s read-only tool&lt;/a&gt;, in &lt;a class="link" href="https://www.tenable.com/cve/CVE-2026-61789" target="_blank" rel="noopener"
 &gt;DBHub&lt;/a&gt; and in &lt;a class="link" href="https://aws.amazon.com/security/security-bulletins/2026-101-aws/" target="_blank" rel="noopener"
 &gt;AWS&amp;rsquo;s PostgreSQL MCP server&lt;/a&gt;. An agent that reads data can also be told what to do by it: in &lt;a class="link" href="https://generalanalysis.com/blog/supabase-mcp-blog" target="_blank" rel="noopener"
 &gt;General Analysis&amp;rsquo;s Supabase demonstration&lt;/a&gt; a support ticket instructed the agent to copy a token table into the ticket, and &amp;ldquo;No permissions were violated.&amp;rdquo; The boundary that holds is a database role that cannot write and can only see what the agent needs. Agents with more than that have already &lt;a class="link" href="https://aishippingblog.com/p/how-i-dropped-our-production-database" target="_blank" rel="noopener"
 &gt;deleted a production RDS database and its snapshots&lt;/a&gt; (March 2026) and &lt;a class="link" href="https://decrypt.co/365897/ai-agent-deletes-startup-database-9-seconds-founder-says" target="_blank" rel="noopener"
 &gt;a Railway volume with its backups&lt;/a&gt; (April 2026). No column comment helps with any of that.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="start-with-the-models-own-list-of-assumptions"&gt;Start with the model&amp;rsquo;s own list of assumptions
&lt;/h2&gt;&lt;p&gt;Every catalog-only answer in this test came with a comment block listing what the model had assumed, and the list was the same each time: the status codes are undocumented, Q1 means &lt;code&gt;paid_at&lt;/code&gt; in UTC, tags might repeat. Each of those lines is a missing &lt;code&gt;COMMENT ON&lt;/code&gt; or a missing constraint, written down by the reader who needed it. Asking a model the ten questions your team asks most often, against the catalog alone, gives you that list for your own schema in an afternoon. The fix is three statements in this case, and in most schemas it is about that size per column:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1 = awaiting payment (paid_at is NULL), 2 = paid, 3 = refunded (paid_at is kept). Revenue counts status 2 only.&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CONSTRAINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders_status_check&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_tags&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tag&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- after removing the doubled rows
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;With those in place, the agent&amp;rsquo;s 49 seconds of detective work became an 8.5-second answer in one turn.&lt;/p&gt;</description></item><item><title>Where Your Cloud Bill Actually Leaks: An Audit Nobody Runs</title><link>https://explainanalyze.com/p/where-your-cloud-bill-actually-leaks-an-audit-nobody-runs/</link><pubDate>Thu, 13 Nov 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/where-your-cloud-bill-actually-leaks-an-audit-nobody-runs/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Where Your Cloud Bill Actually Leaks: An Audit Nobody Runs" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Cloud bills creep up because nobody owns bringing them down. The largest leaks are S3 versioning without a lifecycle policy, backup retention set when the database was a fraction of its current size, cross-AZ traffic on chatty services, lower environments running 24/7 at production sizes, and old workloads on instance generations the cloud now surcharges. An annual one-day audit by one engineer typically recovers a five-figure monthly sum and the savings stop being mysterious.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The S3 bill on a team&amp;rsquo;s data-lake bucket went from $1,400 a month to $9,800 over six months without anyone deploying anything new. The bucket had versioning enabled in 2022, no lifecycle policy, and a daily ETL job overwriting the same 40,000 objects every morning. Six months of overwrites left each object with roughly 180 versions in cold storage, and the storage charge was for all of them. Two hours on a one-page lifecycle policy reclaimed about $8,000 a month. The cost had been compounding for three and a half years; nobody had looked at the line item that broke it down.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;Buy a FinOps tool&amp;rdquo; is the reflexive answer, and it&amp;rsquo;s half right. Cost tools surface the bill but don&amp;rsquo;t fix it. They tell you the storage line is up 40%; they don&amp;rsquo;t tell you which 40,000 objects are versioned 180 times, which dev environment has been running 24/7 since the previous CTO, or which AZ your chatty cache shares with. The savings live in walking the items.&lt;/p&gt;
&lt;h2 id="audit-storage-and-lifecycle-first"&gt;Audit storage and lifecycle first
&lt;/h2&gt;&lt;p&gt;Object storage with versioning enabled and no lifecycle policy is the most common large leak in any AWS account. S3 versioning charges for every version of every object indefinitely; a bucket with daily writes to the same keys can carry hundreds of versions per object after a year. The audit takes one query against the &lt;code&gt;s3:ListObjectVersions&lt;/code&gt; API or one tab in S3 Storage Lens. For buckets holding derived data (build artifacts, ETL outputs, logs with authoritative copies elsewhere), disable versioning entirely; that&amp;rsquo;s cheaper than running a lifecycle policy against it. For buckets that genuinely need versioning, a lifecycle rule expiring non-current versions after 30, 60, or 90 days reclaims most of the cost. Incomplete multipart uploads are the related sweep: failed uploads sit on the bucket forever unless a separate lifecycle rule clears them.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Check before you disable versioning&lt;/strong&gt;
 &lt;div&gt;Versioning is sometimes the only mechanism preventing data loss from an application bug, a misconfigured deletion policy, or a compliance retention requirement. A bucket that looks like &amp;ldquo;derived data&amp;rdquo; today might be the audit log a regulator asks about next year. Check the application&amp;rsquo;s recovery model and any compliance scope before turning it off.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Backup retention runs second. Most managed databases ship with a default of 7 days, and most teams later bumped it to 30 or 90 days &amp;ldquo;for safety&amp;rdquo; without revisiting whether the database was actually a fraction of its current size at the time. Snapshot storage above the database&amp;rsquo;s allocated size is billed separately at object-storage rates. A database that grew from 200 GB to 4 TB while retention stayed at 90 days has roughly 360 TB of snapshots on the line item, much of it for backups nobody has restored from. Cross-region snapshot replication, on by default in some compliance configurations, doubles that number. The conversation worth having is which databases need 90 days of point-in-time recovery and which only need 7. The answer is almost never &amp;ldquo;all of them&amp;rdquo;.&lt;/p&gt;
&lt;p&gt;Temporary and scratch storage is the third item. Buckets named &lt;code&gt;tmp-&lt;/code&gt;, &lt;code&gt;scratch-&lt;/code&gt;, &lt;code&gt;data-export-*&lt;/code&gt;, and &lt;code&gt;migration-2023-*&lt;/code&gt; get created for one-off jobs and never deleted. EFS file systems mounted for migration work that finished two years ago. Test datasets uploaded for vendor pitches nobody pursued. Logs shipped to a debugging bucket during last summer&amp;rsquo;s incident. The discipline is a tag-based lifecycle policy: every temporary resource carries an &lt;code&gt;expires=YYYY-MM-DD&lt;/code&gt; tag at creation, and a scheduled job deletes anything past its expiry. Same principle for ephemeral compute and infra: TTLs at creation, not retroactive sweeps.&lt;/p&gt;
&lt;p&gt;Database tiering is the fourth storage item, and the cost shows up twice: in steady-state storage charges, and again every time someone touches the cluster. On a 30 TiB RDS cluster left alone as &amp;ldquo;the archive&amp;rdquo;, a routine &lt;code&gt;ALTER TABLE&lt;/code&gt; to change one column&amp;rsquo;s datatype kicked off a full table rewrite that ran for a month and cost about $5,000 in IO before completing. The cluster had no active alerts, no recent change requests, and no one watching the bill - the charge accrued the full month before anyone noticed. Hot OLTP storage is the most expensive byte the cloud sells, and tables carrying years of archival rows the application reads less than monthly pay that premium plus a surprise tax on every schema migration. Partitioning by date and moving old partitions to S3, to a slower instance class, or to a column-store warehouse is a one-week project on a known shape. The migration looks unglamorous on a roadmap and gets perpetually deferred until the storage line, or an unexpected five-figure &lt;code&gt;ALTER&lt;/code&gt;, crosses a threshold finance flags.&lt;/p&gt;
&lt;p&gt;The unifying discipline across all four items is preventive: every storage resource needs an explicit retention policy and ownership tags at creation time, enforced in provisioning code rather than by human attention.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The audit recovers; the wrapped module prevents&lt;/strong&gt;
 &lt;div&gt;A Terraform module that creates an S3 bucket should require &lt;code&gt;lifecycle_rule&lt;/code&gt;, &lt;code&gt;owner&lt;/code&gt;, and &lt;code&gt;expires&lt;/code&gt; (or an explicit &lt;code&gt;retention_class&lt;/code&gt;) as inputs and refuse to plan if they&amp;rsquo;re missing. The same wrapper-module pattern applies to RDS, dev environments, scratch buckets, and one-off compute. Tags applied retroactively only cover what someone remembered to update; tags enforced at the module cover everything provisioned from that point forward, including the infra a future engineer spins up without thinking about cost.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="pin-chatty-pairs-and-right-size-capacity"&gt;Pin chatty pairs and right-size capacity
&lt;/h2&gt;&lt;p&gt;Cross-AZ traffic is the silent compute leak. AWS charges roughly $0.01 per GB for data crossing AZs in both directions; on a chatty service that fans out to a cache and a database in different AZs, the round-trip charges add up to more than the instance cost itself within a few months. The fix is placement. Pin the chatty pair to the same AZ when the consistency model allows it. Batch the calls when it doesn&amp;rsquo;t. Move the cache layer to a per-AZ deployment so each application instance hits its local replica. The audit is one query against VPC flow logs or a glance at the Cost Explorer &amp;ldquo;Data Transfer&amp;rdquo; breakdown filtered by AZ.&lt;/p&gt;
&lt;p&gt;Right-sizing is the next item. Instances provisioned for a load test in 2023 that ran at 12% CPU for two years are still on the bill at the size they were provisioned for. AWS Compute Optimizer and the equivalent recommenders in GCP and Azure are accurate enough to act on for the obvious cases without further investigation. The non-obvious cases (memory-bound workloads, spiky workloads, workloads with seasonal peaks, services with strict latency budgets) need a human pass with a week of metrics in front of them. Either way the data is already in the cloud; nothing has to be instrumented.&lt;/p&gt;
&lt;p&gt;HA is the third. Multi-AZ on a Postgres primary roughly doubles the instance cost. On services where a five-minute outage is genuinely tolerable (internal tools, batch jobs, dev databases, services with a clear retry path on the caller) the second instance is paying for an SLA the business doesn&amp;rsquo;t actually need. The conversation worth having is which services have an RPO and RTO that justifies the standby. Most don&amp;rsquo;t. The original architecture review made the call on every service the same way (HA on, by default) and never revisited it as the service catalog grew.&lt;/p&gt;
&lt;h2 id="tune-queries-on-the-hot-paths"&gt;Tune queries on the hot paths
&lt;/h2&gt;&lt;p&gt;Most items above remove waste in the infra layer. Query tuning and application-side optimization make the existing infra do more work per dollar, and on most systems they&amp;rsquo;re the largest single cost lever in this article. A single N+1 query in a hot path can put 10x more load on the database than necessary, sized as a more expensive RDS, a higher tier in every downstream cache, and more cross-AZ traffic. The infra audit cuts the bill by trimming what isn&amp;rsquo;t needed. Query tuning cuts it by reducing what&amp;rsquo;s actually being done.&lt;/p&gt;
&lt;p&gt;Pick any production codebase older than eighteen months. At least one of the patterns covered elsewhere on this blog is in it, and almost always more than one: &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;N+1 ORM iteration&lt;/a&gt; on a hot route, &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;non-SARGable predicates&lt;/a&gt; that defeat any index, indexes built without &lt;a class="link" href="https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/" &gt;understanding selectivity&lt;/a&gt;, &lt;code&gt;OFFSET&lt;/code&gt; pagination past page 50, retry loops without backoff that triple request rate during the exact conditions that caused the original timeout, aggregations recomputed every request that could be cached for thirty seconds, and &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/" &gt;long-held row locks&lt;/a&gt; blocking unrelated work. Each one shows up at the cost layer as more vCPU, more IO, more cache pressure, and more cross-AZ traffic than the workload actually requires.&lt;/p&gt;
&lt;p&gt;Query tuning is more expensive work than the infra audit: reading the slow-query log, profiling hot paths, and refactoring application code that touches the database. The payback shape is better, though. An infra audit recovers a fixed amount once. A query optimization saves on every future request, scaling with traffic growth.&lt;/p&gt;
&lt;h2 id="sweep-sprawl-and-version-surcharges"&gt;Sweep sprawl and version surcharges
&lt;/h2&gt;&lt;p&gt;Lower environments default to running 24/7 at sizes someone picked when production was a quarter of its current size. The cheapest move is scheduled shutdown nights and weekends, where the workload isn&amp;rsquo;t worldwide and the engineers using it aren&amp;rsquo;t online at 3am. A 16-hour weekday shutdown plus full weekends recovers two-thirds of the monthly hours. AWS Instance Scheduler, GCP&amp;rsquo;s recommender, and a 30-line Lambda all do the job. Lower environments don&amp;rsquo;t need HA, don&amp;rsquo;t need the same retention, and don&amp;rsquo;t need the same instance class.&lt;/p&gt;
&lt;p&gt;Per-engineer dev environments and PR-preview deployments are a related leak. Preview environments that spin up on every pull request and don&amp;rsquo;t tear down on close. Forgotten branches with attached infra. Personal sandboxes from engineers who left the company two years ago. Same TTL-at-creation discipline as the temp storage section above.&lt;/p&gt;
&lt;p&gt;The cloud charges a surcharge on deprecated product versions in two places. EC2 instance generations are the visible one. AWS retired a long list of older EC2 generations and quietly raised the per-hour price on the ones still launchable; eventually they refuse to launch at all. Workloads still running on m4, c4, t2, or r3 generations are paying the surcharge today. Migrating to a current generation is usually a stop-start with a different instance type and a brief test window. The audit is &lt;code&gt;aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceType'&lt;/code&gt; and a join against the published deprecated-generation list. Same pattern in GCP for retired n1 machines, same in Azure for older v2 series.&lt;/p&gt;
&lt;p&gt;The same surcharge runs on managed databases and the rest of the managed-storage catalog, less visibly. AWS RDS Extended Support charges per-vCPU-per-hour for Postgres, MySQL, and Aurora major versions past community end-of-life, stepping up each year until the version is forcibly upgraded. Postgres 11 hit that surcharge in early 2024; MySQL 5.7 followed. ElastiCache, OpenSearch managed, and DocumentDB have equivalent timelines. Azure SQL and Cloud SQL apply similar fees on out-of-support versions. EBS gp2 volumes carry a quieter version of the dynamic: gp3 is usually cheaper at the same IOPS budget even though gp2 isn&amp;rsquo;t formally deprecated. The audit is &lt;code&gt;aws rds describe-db-instances&lt;/code&gt; joined against the engine&amp;rsquo;s published support timeline. The major upgrade was going to happen eventually; the surcharge puts a deadline on it.&lt;/p&gt;
&lt;p&gt;Unused infra is the easiest sweep and the smallest line item per resource. EBS volumes left detached after the instance was terminated, billed monthly for storage that nothing reads. Elastic IPs not associated with any instance, billed hourly for the privilege of holding them. NAT gateways carrying near-zero traffic at the same hourly base rate as one carrying terabytes. Load balancers with zero healthy targets. RDS snapshots from databases deleted years ago. CloudWatch log groups with no retention policy that have been growing since 2019. The audit script is twenty lines per resource type. The savings are small per item and large in aggregate, and the cleanup is the safest of any item in this article. Nothing in production depends on a detached volume by definition.&lt;/p&gt;
&lt;p&gt;Shared infra is the last item and the hardest call. Centralized logging, metrics, CI runners, internal developer platforms, and shared lower-environment clusters all start as obvious wins because the per-team cost is low and the operational burden is borne by a platform team. Years later the per-team cost has crossed the threshold where running it locally to the team that owns the workload would be cheaper, but the original decision is rarely revisited. The conversation worth having is per-team cost vs. operational complexity, not absolute cost. Centralization wins on operations and loses on per-team economics at scale, and the right answer for a 50-engineer org is rarely the right answer for a 500-engineer one.&lt;/p&gt;
&lt;h2 id="when-this-discipline-isnt-worth-running"&gt;When this discipline isn&amp;rsquo;t worth running
&lt;/h2&gt;&lt;p&gt;Three conditions make the cost sweep overkill. Very small accounts where the total monthly bill is under a few thousand dollars don&amp;rsquo;t repay the engineering time it takes to walk the list. Workloads in a hard regulatory regime where retention, HA, and cross-region replication are externally mandated have less room to cut than the article suggests; the audit still surfaces the line items, but the action set is smaller. And teams in a steep growth phase where the cost of the engineer&amp;rsquo;s time on cost work is more expensive than the savings should defer the sweep until the growth stabilizes. The discipline pays back at sustained scale, in established workloads, with engineering time available to allocate.&lt;/p&gt;
&lt;h2 id="make-it-an-annual-habit"&gt;Make it an annual habit
&lt;/h2&gt;&lt;p&gt;The exercise is re-running old decisions against current numbers, in the order where the gap is biggest. The S3 lifecycle that was reasonable when the bucket held 40,000 objects, the backup retention that was reasonable when the database was 200 GB, the m4 instance that was a fine choice in 2021. None of those decisions were wrong when they were made; the numbers underneath them changed by an order of magnitude and nobody re-ran the math. The audit takes longer the first time because nothing is documented. By year three it&amp;rsquo;s a quarterly quick-pass, and the line item nobody used to read is the one finance forwards as good news.&lt;/p&gt;</description></item><item><title>TEXT and JSON Columns: Where the Schema Goes to Hide</title><link>https://explainanalyze.com/p/text-and-json-columns-where-the-schema-goes-to-hide/</link><pubDate>Thu, 25 Sep 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/text-and-json-columns-where-the-schema-goes-to-hide/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post TEXT and JSON Columns: Where the Schema Goes to Hide" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A &lt;code&gt;TEXT&lt;/code&gt; or &lt;code&gt;JSON&lt;/code&gt; column moves the schema out of the database catalog and into application code; the data inside has a shape, but the DDL won&amp;rsquo;t tell you what it is. Promote the fields that actually get queried into real columns, and treat the rest as genuinely opaque.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;An AI assistant is asked to &amp;ldquo;find customers who upgraded to enterprise in the last quarter.&amp;rdquo; It reads the catalog, finds &lt;code&gt;api_logs(id, endpoint VARCHAR, payload LONGTEXT, created_at DATETIME)&lt;/code&gt;, and generates the reasonable query:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;JSON_EXTRACT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;$.action&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;api_logs&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;JSON_EXTRACT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;$.action&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;upgrade&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;JSON_EXTRACT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;$.plan&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;enterprise&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INTERVAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;90&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DAY&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Runs clean. Returns zero rows. The actual key was renamed from &lt;code&gt;action&lt;/code&gt; to &lt;code&gt;event.type&lt;/code&gt; two years ago when the team adopted a shared event schema; new rows match &lt;code&gt;$.event.type&lt;/code&gt;, old rows still match &lt;code&gt;$.action&lt;/code&gt;, and no one migrated the historical data because it wasn&amp;rsquo;t queryable anyway. Neither column nor catalog said any of this. The query is syntactically perfect, semantically correct for the key it guessed, and wrong because the key doesn&amp;rsquo;t exist in most of the rows.&lt;/p&gt;
&lt;p&gt;The obvious fix is &amp;ldquo;switch to JSONB, validate with a JSON schema, add a GIN index.&amp;rdquo; Each one helps at the margin and none of them close the gap. JSONB tells you the blob is valid JSON, not what keys are in it. CHECK constraints with &lt;code&gt;JSON_SCHEMA_VALID&lt;/code&gt; or &lt;code&gt;jsonb_matches_schema&lt;/code&gt; work prospectively, but the six years of rows already in the table were written against five format generations and no validator reaches back in time. A GIN index accelerates key lookups but only if you know which keys to look up. The problem isn&amp;rsquo;t the storage format. The schema emigrated to application code, and changing the column type doesn&amp;rsquo;t bring it back.&lt;/p&gt;
&lt;h2 id="what-leaves-the-catalog-when-the-column-becomes-a-blob"&gt;What leaves the catalog when the column becomes a blob
&lt;/h2&gt;&lt;p&gt;DDL is the contract between the database and everything that reads it. A typed column says &amp;ldquo;this value is an integer between 0 and 2³¹−1, and here&amp;rsquo;s the index I&amp;rsquo;ve built over it.&amp;rdquo; A &lt;code&gt;TEXT&lt;/code&gt; or &lt;code&gt;JSON&lt;/code&gt; column says &amp;ldquo;this value is a string the application decided on, and the application can tell you what that means.&amp;rdquo; The second contract is thinner in ways that compound.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Readers can&amp;rsquo;t discover the shape from the schema.&lt;/strong&gt; &lt;code&gt;information_schema.COLUMNS&lt;/code&gt; for a JSON column returns &lt;code&gt;COLUMN_TYPE = 'json'&lt;/code&gt; and nothing else. Every tool that reads catalog metadata (MCP servers, ERD generators, typed-client code generators, AI assistants, new engineers running &lt;code&gt;\d+&lt;/code&gt;) sees a blob. The shape lives in the serializer class, the protobuf definition, the TypeScript interface, or nowhere. Whichever of those the reader happens to find is the shape they&amp;rsquo;ll assume. See &lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Comment Your Schema&lt;/a&gt; for the lowest-effort way to leave a trail, but comments can describe the shape; they can&amp;rsquo;t make the catalog enforce it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Generational drift is silent.&lt;/strong&gt; Year one the payload is &lt;code&gt;{action, user}&lt;/code&gt;. A migration adds nested metadata: &lt;code&gt;{action, user, metadata: {source}}&lt;/code&gt;. A rewrite flattens and renames: &lt;code&gt;{event: {type, user_id}, source}&lt;/code&gt;. A new service standardizes with a version field: &lt;code&gt;{version: 3, event: {...}}&lt;/code&gt;. All four versions are sitting in the same column with nothing to distinguish them at read time except the keys they happen to have. A JSON_EXTRACT path written against today&amp;rsquo;s producer hits the newest generation and silently misses the older ones. The failure mode is the legacy-schema one: the schema&amp;rsquo;s history is compressed into the data, and the data can&amp;rsquo;t decompress itself.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Writes are untyped.&lt;/strong&gt; Without CHECK constraints or a JSON-schema validator, the writer is the only guardrail. A service deployed last Tuesday that emits &lt;code&gt;amount&lt;/code&gt; as the string &lt;code&gt;&amp;quot;9900&amp;quot;&lt;/code&gt; instead of the integer &lt;code&gt;9900&lt;/code&gt; silently poisons the column. Downstream queries comparing &lt;code&gt;amount &amp;gt; 1000&lt;/code&gt; work on new rows and misbehave on the poisoned batch, because JSON-extract returns a string and the comparison is lexicographic. The same class of mismatch a typed column would reject on INSERT.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The planner is working blind.&lt;/strong&gt; Row-count estimates on &lt;code&gt;JSON_EXTRACT(payload, '$.event.type') = 'upgrade'&lt;/code&gt; have no histogram to consult; the planner falls back to a default selectivity estimate that&amp;rsquo;s usually wrong. Plans for queries filtered on JSON fields are routinely pessimistic or optimistic by an order of magnitude, and there&amp;rsquo;s no &lt;code&gt;ANALYZE&lt;/code&gt; to fix that because the statistics don&amp;rsquo;t exist for the interior of the blob.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Indexes are per-key, not per-column.&lt;/strong&gt; A functional index on &lt;code&gt;JSON_EXTRACT(payload, '$.event.type')&lt;/code&gt; accelerates one path. The next query filters on &lt;code&gt;$.source&lt;/code&gt; and scans the table. Generated columns are the cleaner version of this (&lt;code&gt;payload_event_type VARCHAR(50) GENERATED ALWAYS AS (JSON_EXTRACT(payload, '$.event.type')) STORED&lt;/code&gt;) but each one is a schema change with a backfill, and you have to know in advance which keys matter. GIN indexes on JSONB cover arbitrary keys but are large, slow to update, and still don&amp;rsquo;t tell the reader what keys exist.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Untyped writes &amp;#43; untyped reads = silent schema drift&lt;/strong&gt;
 &lt;div&gt;A TEXT or JSON column accepts anything the writer emits and returns exactly that on read. Two services writing to the same column with slightly different shapes don&amp;rsquo;t conflict at the database level; they produce a column whose contents depend on which service wrote the row. The divergence is invisible until a query tries to read uniformly across both.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="plausible-paths-empty-results"&gt;Plausible paths, empty results
&lt;/h2&gt;&lt;p&gt;Schema-reading LLMs generate JSON_EXTRACT paths the same way they generate column names in a typed schema, by pattern-matching the column name and the question. Asked about &amp;ldquo;upgrade actions,&amp;rdquo; the model guesses &lt;code&gt;$.action = 'upgrade'&lt;/code&gt; because the English-to-JSON-path mapping is obvious. It has no way to know that the key was renamed, that three generations coexist, or that the canonical name is now buried under two layers of nesting. The catalog gives it a column type of &lt;code&gt;json&lt;/code&gt; and nothing else, and the model&amp;rsquo;s best guess is reasonable and wrong.&lt;/p&gt;
&lt;p&gt;The failure pattern is familiar from other schema-hiding designs. &lt;a class="link" href="https://explainanalyze.com/p/polymorphic-references-are-not-foreign-keys/" &gt;Polymorphic references&lt;/a&gt; hide which table a foreign-key-shaped column points at; &lt;a class="link" href="https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/" &gt;bare &lt;code&gt;id&lt;/code&gt; primary keys&lt;/a&gt; hide which identifier is being compared; TEXT/JSON columns hide what&amp;rsquo;s in the column at all. All three are cases where the LLM generates a plausible query against a schema that isn&amp;rsquo;t telling it enough, and the query returns plausibly-shaped but semantically empty results.&lt;/p&gt;
&lt;h2 id="the-fix-and-where-it-stops-being-free"&gt;The fix, and where it stops being free
&lt;/h2&gt;&lt;p&gt;The lever is being honest about what&amp;rsquo;s inside and picking the right storage per field.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Promote fields that get queried.&lt;/strong&gt; If the application filters on &lt;code&gt;event.type&lt;/code&gt; more than occasionally, that&amp;rsquo;s a real column. Generated columns are the low-friction middle path: derive a typed, indexable column from the JSON, keep the raw payload as the audit trail.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;api_logs&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;VARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GENERATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ALWAYS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;JSON_UNQUOTE&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;JSON_EXTRACT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;$.event.type&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;STORED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_event_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event_type&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The trade-off: every promoted field is a migration, and generated columns don&amp;rsquo;t retroactively rewrite rows written with a different shape; you still need the &lt;code&gt;COALESCE(JSON_EXTRACT(payload, '$.event.type'), JSON_EXTRACT(payload, '$.action'))&lt;/code&gt; cleanup for the old generations, and you&amp;rsquo;re doing that exactly once as part of the promotion rather than in every query.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Enforce new writes with a JSON schema.&lt;/strong&gt; PostgreSQL&amp;rsquo;s &lt;code&gt;pg_jsonschema&lt;/code&gt; and MySQL 8.0&amp;rsquo;s &lt;code&gt;JSON_SCHEMA_VALID&lt;/code&gt; let a CHECK constraint reject writes that don&amp;rsquo;t match a named schema. Doesn&amp;rsquo;t fix existing rows; does stop the next silent format change from landing. If the team doesn&amp;rsquo;t already have a shared event schema, a CHECK constraint is the forcing function that produces one.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Version the payload explicitly.&lt;/strong&gt; &lt;code&gt;{&amp;quot;version&amp;quot;: 3, &amp;quot;payload&amp;quot;: {...}}&lt;/code&gt; at the top lets every reader dispatch on version instead of inferring it from which keys happen to be present. Doesn&amp;rsquo;t help rows written before versioning started, but bounds the drift going forward and turns &amp;ldquo;which generation is this row?&amp;rdquo; from archaeology into a lookup.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Document what stays inside.&lt;/strong&gt; Comments on the column (&amp;ldquo;see github.com/org/events for the schema; versions 1–3 coexist in rows older than 2024-Q2&amp;rdquo;) won&amp;rsquo;t replace types, but they give the reader a place to look. &lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Comments on the schema&lt;/a&gt; are cheap, in-place, and propagate through every tool that reads the catalog; for genuinely-opaque columns this is the best available signal.&lt;/p&gt;
&lt;h2 id="when-json-is-actually-the-right-answer"&gt;When JSON is actually the right answer
&lt;/h2&gt;&lt;p&gt;The pattern earns its keep in specific shapes where the alternative (typed columns) is worse.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Truly variable shape per row.&lt;/strong&gt; User-supplied settings blobs, custom-field configurations, extension points where the keys are genuinely per-tenant or per-user. Modeling each variant as a column produces a wide table full of NULLs; see &lt;a class="link" href="https://explainanalyze.com/p/god-tables-150-columns-and-the-quiet-cost-of-just-add-a-column/" &gt;God Tables&lt;/a&gt; for the cost of that direction. The column is honest about being schemaless because the data is schemaless.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Audit payloads nobody queries.&lt;/strong&gt; Raw API request/response bodies retained for compliance, debug traces, incident forensics. Written once, read by humans one row at a time, never aggregated. The lack of a queryable schema is fine because no query needs one. A sensible default here is to keep the payload compressed and add a small set of typed columns (&lt;code&gt;endpoint&lt;/code&gt;, &lt;code&gt;status_code&lt;/code&gt;, &lt;code&gt;user_id&lt;/code&gt;, &lt;code&gt;created_at&lt;/code&gt;) for the predicates the operational queries actually use.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Short-lived staging.&lt;/strong&gt; Job queues, idempotency cache payloads, outbox entries, where the producer and consumer are deployed together, the payload is read once, and the row is deleted on completion. Drift can&amp;rsquo;t accumulate in rows that don&amp;rsquo;t stay around.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Document stores on purpose.&lt;/strong&gt; PostgreSQL JSONB with a stable schema, validated on write, with functional indexes on the paths that matter. This is a real design; it&amp;rsquo;s not the unspoken default that most TEXT columns represent. If the team is reaching for JSONB and treating it as a document store, it should look like one (with validation, indexes, and documentation) not like a TEXT column that happens to parse.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;A TEXT or JSON column is a specific architectural choice: move part of the schema out of the catalog, in exchange for cheaper writes and looser contracts between producer and consumer. When the trade is deliberate (genuinely variable data, write-once audit, short-lived buffer) it&amp;rsquo;s the correct shape. When it&amp;rsquo;s the path of least resistance because typed columns would require a migration, the cost is deferred to every future reader who has to reconstruct the format from commit history.&lt;/p&gt;
&lt;p&gt;Databases are good at enforcing the contracts they know about. The column types are how they know. Every field that matters to a query deserves to be in the part of the schema the database can see; everything else is honestly opaque and should look it. The default drift (&amp;ldquo;stick it in the payload, we&amp;rsquo;ll parse it later&amp;rdquo;) produces columns whose contents nobody fully knows, including the team that wrote them.&lt;/p&gt;</description></item><item><title>Reading the Schema Is Not Reading the Data</title><link>https://explainanalyze.com/p/reading-the-schema-is-not-reading-the-data/</link><pubDate>Mon, 08 Sep 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/reading-the-schema-is-not-reading-the-data/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Reading the Schema Is Not Reading the Data" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A schema describes the shape the database enforces; the data inside follows a second set of conventions (soft-delete coverage, sentinel values, encoding quirks, format drift) that live nowhere the catalog can show. Queries written from the DDL alone run clean and return results that look right and mean something different. Treat the data as a second source that has to be read, sampled, and documented alongside the types.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;An engineer (or an AI) writes a query to find pending orders:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INTERVAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DAY&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;orders.status&lt;/code&gt; is &lt;code&gt;TINYINT NOT NULL&lt;/code&gt;. The query runs. Forty thousand rows come back. Most of them shipped days ago. The mistake lives in the column&amp;rsquo;s other life: &lt;code&gt;status&lt;/code&gt; on this table is a boolean &lt;code&gt;is_processed&lt;/code&gt; flag where &lt;code&gt;1&lt;/code&gt; means &amp;ldquo;has been through the fulfillment pipeline.&amp;rdquo; The order lifecycle state (pending, processing, shipped, delivered, cancelled) is in &lt;code&gt;orders.state&lt;/code&gt;, also &lt;code&gt;TINYINT NOT NULL&lt;/code&gt;, also no comments, and whoever read the schema first picked the column whose name they recognized. The DDL was no help; both columns have the same type, the same nullability, and the same look in &lt;code&gt;information_schema&lt;/code&gt;. The data was telling the real story, and the data wasn&amp;rsquo;t read.&lt;/p&gt;
&lt;p&gt;The obvious fix is &amp;ldquo;add comments, use ENUM, lint for ambiguous names.&amp;rdquo; Each of those helps on new columns and the next migration. None of them touch the existing data, which is where the ambiguity actually lives: forty thousand rows of &lt;code&gt;status = 1&lt;/code&gt; that mean one thing on this table and a different thing on its sibling, ten million VARCHAR dates written by five generations of code in three formats, and a &lt;code&gt;users&lt;/code&gt; table where rows with &lt;code&gt;email = 'DO_NOT_USE@test.com'&lt;/code&gt; have been on the leaderboard for two years. Fixing forward keeps the problem from growing. Reading the data is how you find out what&amp;rsquo;s already there.&lt;/p&gt;
&lt;h2 id="four-ways-the-data-disagrees-with-the-schema"&gt;Four ways the data disagrees with the schema
&lt;/h2&gt;&lt;p&gt;These are not the exotic cases. They show up in nearly every mature production database, and each one is a place where a schema-only read produces a plausible, wrong query.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;TINYINT(1)&lt;/code&gt; is polysemic.&lt;/strong&gt; It stores a boolean flag (&lt;code&gt;is_active&lt;/code&gt;, &lt;code&gt;has_seen_onboarding&lt;/code&gt;, &lt;code&gt;email_verified&lt;/code&gt;), a small enum (lifecycle states, tier levels, priority), a bit-packed byte (eight flags in a single column), or a count that never exceeds 127. All four uses produce identical entries in &lt;code&gt;information_schema&lt;/code&gt;. Naming conventions (&lt;code&gt;is_*&lt;/code&gt;, &lt;code&gt;has_*&lt;/code&gt;, &lt;code&gt;can_*&lt;/code&gt; for booleans; &lt;code&gt;_type&lt;/code&gt;, &lt;code&gt;_status&lt;/code&gt;, &lt;code&gt;_level&lt;/code&gt; for enums) are the informal signal, and like every informal signal, they&amp;rsquo;re applied inconsistently and broken in legacy tables. See &lt;a class="link" href="https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/" &gt;Schema Conventions and Why They Matter&lt;/a&gt; for the prescriptive side; this is the descriptive reality.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Soft-delete coverage is partial.&lt;/strong&gt; Some tables have &lt;code&gt;deleted_at TIMESTAMP NULL&lt;/code&gt;. Some have &lt;code&gt;is_deleted TINYINT(1) DEFAULT 0&lt;/code&gt;. Most have neither, because the original author decided the table didn&amp;rsquo;t need soft deletes and nobody revisited. A query that correctly filters &lt;code&gt;WHERE deleted_at IS NULL&lt;/code&gt; on &lt;code&gt;customers&lt;/code&gt; returns the right answer; the same pattern applied to &lt;code&gt;addresses&lt;/code&gt; either errors out (column doesn&amp;rsquo;t exist) or silently matches everything (column exists but is always NULL because the application never writes to it). There&amp;rsquo;s no global rule to encode and no way to know from the catalog which tables fall in which bucket. You have to read the data, or read the application code that writes to it (which is usually worse).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;VARCHAR dates in multiple formats.&lt;/strong&gt; A column called &lt;code&gt;signup_date VARCHAR(10)&lt;/code&gt; is a tell. The first generation of rows has &lt;code&gt;YYYY-MM-DD&lt;/code&gt;. A rewrite that switched import vendors introduced &lt;code&gt;MM/DD/YYYY&lt;/code&gt;. An international expansion produced &lt;code&gt;DD/MM/YYYY&lt;/code&gt; for rows that came in through a specific endpoint and &lt;code&gt;DD-Mon-YYYY&lt;/code&gt; for one partner&amp;rsquo;s CSV imports. All four formats live in the same column. &lt;code&gt;WHERE signup_date &amp;gt;= '2025-01-01'&lt;/code&gt; matches the first generation correctly, matches the third generation backwards (&amp;ldquo;2025-01-01&amp;rdquo; sorts before &amp;ldquo;15/03/2024&amp;rdquo;), and misses the fourth entirely because the sort order doesn&amp;rsquo;t touch &lt;code&gt;Mon&lt;/code&gt; strings. The query returned rows, so the reviewer moved on.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sentinel values and test data.&lt;/strong&gt; Row with &lt;code&gt;user_id = 0&lt;/code&gt; means &amp;ldquo;anonymous.&amp;rdquo; Row with &lt;code&gt;email = 'DO_NOT_USE@test.com'&lt;/code&gt; is a test account that&amp;rsquo;s been in production for three years because nobody wanted to take responsibility for deleting it. Row with &lt;code&gt;created_at = '1970-01-01 00:00:00'&lt;/code&gt; is a backfill where the original timestamp was unknown and epoch zero got written as a placeholder. Every one of these is an intentional violation of the apparent meaning of the column, and every schema-level read treats them as ordinary data. Copilot ranked &lt;code&gt;DO_NOT_USE&lt;/code&gt; as the top customer with $99,999 in revenue because the row had the highest total; the test record had been sitting there for years, visible to anyone who queried the table but invisible to anyone who only read the DDL.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Input-convention drift.&lt;/strong&gt; &lt;code&gt;VARCHAR(255)&lt;/code&gt; accepts &amp;ldquo;Acme Corp,&amp;rdquo; &amp;ldquo;ACME CORPORATION,&amp;rdquo; &amp;ldquo;Acme Corp.,&amp;rdquo; &amp;ldquo;acme corp,&amp;rdquo; and &amp;ldquo;ACME CORP&amp;rdquo; (two spaces, somebody&amp;rsquo;s trailing whitespace bug). All five are the same company in different rows. The unique constraint, if it exists, didn&amp;rsquo;t catch any of them because they&amp;rsquo;re not byte-identical. Any query that groups or joins on the text field silently double-counts - not by a small amount, by however much the convention drift is worth. Encoding quirks compound: &lt;code&gt;café&lt;/code&gt; in NFC and NFD look identical in the terminal and hash differently; case-folding depends on collation; trailing whitespace varies by source system.&lt;/p&gt;
&lt;h2 id="why-the-catalog-cant-tell-you-this"&gt;Why the catalog can&amp;rsquo;t tell you this
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;information_schema&lt;/code&gt; describes the contract the database enforces on writes. That contract is narrow: types, nullability, defaults, constraints, foreign keys. It doesn&amp;rsquo;t describe what got written before the constraint was added (almost all of it), what gets written by code paths that bypass the ORM (a surprising fraction of it), or what the application decided to write into a column that the database happily accepts because the type matches.&lt;/p&gt;
&lt;p&gt;Type compatibility is a floor, not a ceiling. &lt;code&gt;TINYINT NOT NULL&lt;/code&gt; excludes strings, NULLs, and integers outside &lt;code&gt;[-128, 127]&lt;/code&gt;. It doesn&amp;rsquo;t exclude &lt;code&gt;1&lt;/code&gt; meaning five different things in five different tables, because that&amp;rsquo;s not a type constraint - it&amp;rsquo;s a semantic one, and the database has no vocabulary for semantics. The same logic applies to NULL handling: the catalog tells you a column is nullable; it doesn&amp;rsquo;t tell you whether NULL means &amp;ldquo;unset,&amp;rdquo; &amp;ldquo;not applicable,&amp;rdquo; &amp;ldquo;still in progress,&amp;rdquo; or &amp;ldquo;data lost during the 2019 migration.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;LLMs inherit this limitation directly. A model generating SQL from the catalog sees column names and types, not data distributions. It has no way to tell that &lt;code&gt;status&lt;/code&gt; is polysemic across tables, that &lt;code&gt;deleted_at&lt;/code&gt; exists on four of the six relevant tables, or that &lt;code&gt;signup_date&lt;/code&gt; has three format generations. The LLM&amp;rsquo;s best guess is the one a new engineer would make: the schema looks uniform, so the data probably is. Neither is wrong in general; both are wrong often enough in mature databases to produce plausibly-shaped and semantically-hollow query results. Legacy schemas are one source of data drift, and there are others.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Runs clean, returns plausible, means something else&lt;/strong&gt;
 &lt;div&gt;Schema-only queries fail in the quietest way a query can fail. The SQL is syntactically correct. The types match. Rows come back. Some fraction of those rows mean what the author intended, and some fraction mean something else, and there&amp;rsquo;s no signal at the database level telling you which is which. Reviewers who only look at the query text can&amp;rsquo;t catch it. The data is where the check has to happen.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-fix-is-a-habit-not-a-migration"&gt;The fix is a habit, not a migration
&lt;/h2&gt;&lt;p&gt;You can&amp;rsquo;t retroactively enforce a schema on ten years of writes. You can change what the next reader (human or model) has available before they generate the next query.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Profile before you query.&lt;/strong&gt; Before writing a predicate against an unfamiliar column, run a one-liner: &lt;code&gt;SELECT col, COUNT(*) FROM t GROUP BY col ORDER BY COUNT(*) DESC LIMIT 20&lt;/code&gt;. For low-cardinality columns (status, type, flags) this reveals the actual value distribution in thirty seconds and catches the flag-versus-enum mistake before the query ships. For higher-cardinality columns, sample: &lt;code&gt;SELECT col FROM t ORDER BY RAND() LIMIT 50&lt;/code&gt;. The time cost is minutes; the catch rate is substantial.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Comment the columns the DDL can&amp;rsquo;t describe.&lt;/strong&gt; A one-line comment on &lt;code&gt;orders.status&lt;/code&gt; (&lt;code&gt;'Pending=1, Processing=2, Shipped=3, Delivered=4, Cancelled=5'&lt;/code&gt;) and on &lt;code&gt;orders.state&lt;/code&gt; (&lt;code&gt;'Boolean: 1 if order has been through fulfillment'&lt;/code&gt;) is the difference between a reader who gets it right and one who guesses. &lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Comment Your Schema&lt;/a&gt; covers the mechanics in full; for the flag/enum disambiguation specifically, this is the highest-leverage fix per character of effort anywhere in schema maintenance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CHECK constraints for new values.&lt;/strong&gt; &lt;code&gt;CHECK (status IN (1,2,3,4,5))&lt;/code&gt; is the forcing function for the next writer. It won&amp;rsquo;t clean up existing rows, and it won&amp;rsquo;t stop a future engineer from reaching for &lt;code&gt;6&lt;/code&gt;, but it will fail loudly when they try, instead of silently accepting a value the readers of the table don&amp;rsquo;t know about. On nullable columns, &lt;code&gt;CHECK (deleted_at IS NULL OR deleted_at &amp;gt; created_at)&lt;/code&gt; catches the backfill-sentinel case.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Migrate VARCHAR dates when you can afford it.&lt;/strong&gt; The migration is real work: parse each row, fail loudly on unparseable formats, pick a canonical representation, backfill. Leaving VARCHAR in place guarantees the next query is written against whichever format the author happened to sample. The right-sized fix in the meantime: a comment on the column listing the known formats, and a view that exposes a parsed &lt;code&gt;DATE&lt;/code&gt; for the queries that can tolerate loss on the unparseable rows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Treat data profiling as part of review.&lt;/strong&gt; When a PR adds a new query, the reviewer&amp;rsquo;s first question is &amp;ldquo;does this predicate match the data?&amp;rdquo;, which requires actually looking at the data, not just the query. For AI-assisted development this is even more load-bearing: the model generated the query from the catalog, so the human review is the only layer that can compare the query&amp;rsquo;s predicates to the column&amp;rsquo;s actual contents.&lt;/p&gt;
&lt;h2 id="when-schema-only-reading-is-fine"&gt;When schema-only reading is fine
&lt;/h2&gt;&lt;p&gt;Not every database carries this baggage. Three cases where the schema really is the data&amp;rsquo;s description:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schemas designed from scratch with strict conventions.&lt;/strong&gt; New services, greenfield tables, codebases where every column has a comment, every enum is an ENUM type, and every date column is &lt;code&gt;DATE&lt;/code&gt; or &lt;code&gt;TIMESTAMPTZ&lt;/code&gt;. The drift hasn&amp;rsquo;t had time to accumulate, and the conventions are enforced by linters on migrations. The failure modes described above can still show up; they show up as bugs that get caught, not as the steady-state of the table.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Small, single-team databases.&lt;/strong&gt; Twenty tables, three engineers, all the data flowing through one service. Everyone who writes to the table knows what the conventions are; the data drift is small because there are only three writers. The cost of the habit described above exceeds the cost of the drift it catches. Grow the team or the table count by a factor of ten and the math flips.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analytical warehouses that expect exploration.&lt;/strong&gt; In a BigQuery, Snowflake, or ClickHouse dataset built for analytics, everyone who queries the data profiles it as a matter of course: sample the column, check the distribution, look for nulls. The profiling habit is already the workflow; the schema is treated as a hint rather than a contract. This is the part of the data stack where reading the data is assumed, and the failure mode is correspondingly rare.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;A production database has two artifacts worth reading: the DDL the engine enforces, and the data the engine happens to hold. The first is legible, indexed, and comes with tooling; the second is tribal knowledge, distributed across rows written by years of code, and invisible to every tool that stops at the catalog. Everyone from new engineers to LLMs reads the first artifact and assumes it describes the second, which is true in schemas fresh enough to have no drift and false in every schema old enough to have generated any.&lt;/p&gt;
&lt;p&gt;Rigor on new tables pays off, but the larger lever is routine comparison between what the schema says and what the data does: sampling before querying, commenting columns whose meaning isn&amp;rsquo;t self-evident, treating data profiling as part of review rather than a debugging step. None of it scales to &amp;ldquo;we documented the whole schema in one sprint.&amp;rdquo; It scales one column at a time, on the columns that are about to be queried, until the fraction of the schema that lies to its readers is small enough to stop costing incidents.&lt;/p&gt;</description></item><item><title>Random UUIDs as Primary Keys: The B-Tree Penalty</title><link>https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/</link><pubDate>Fri, 22 Aug 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Random UUIDs as Primary Keys: The B-Tree Penalty" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;UUIDv4 primary keys are globally unique and coordination-free, and the cost is paid every time you write a row: random B-tree positions, page splits, secondary indexes bloated with 16- or 36-byte key copies, and a working set that stops fitting in the buffer pool once the table is large enough. UUIDv7 fixes the insert-locality problem (time-ordered, sortable) without changing storage size; the full fix is picking v7, storing as &lt;code&gt;BINARY(16)&lt;/code&gt; or native &lt;code&gt;uuid&lt;/code&gt;, and keeping UUIDs at the API boundary rather than internal to every join.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A table configured like this on day one looks unremarkable:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;CHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;36&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- UUIDv4, generated by the application
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Inserts are fast, reads are fast, the ORM is happy. At 100,000 rows, it&amp;rsquo;s still fine. At 10 million, the nightly ingest job gets noticeably slower. At 200 million, inserts take 50 ms each instead of 2 ms, the buffer pool is constantly churning, and the secondary indexes are three to four times the size they&amp;rsquo;d be with a &lt;code&gt;BIGINT&lt;/code&gt; primary key. Nothing about the schema changed. The table just got large enough for a design decision to start charging rent.&lt;/p&gt;
&lt;p&gt;The obvious fix is &amp;ldquo;use BIGINT auto-increment.&amp;rdquo; That&amp;rsquo;s the right answer in a lot of cases and the wrong one in others; it reintroduces coordination requirements, leaks row counts through URL-exposed IDs, and doesn&amp;rsquo;t work for schemas that need to be generated offline or across shards. UUIDs exist because those constraints are real. The sharper question is: what exactly is UUIDv4 costing you at scale, and which of those costs have cheaper alternatives?&lt;/p&gt;
&lt;h2 id="what-random-keys-do-to-a-b-tree"&gt;What random keys do to a B-tree
&lt;/h2&gt;&lt;p&gt;B-tree indexes are sorted structures. When the primary key is an auto-incrementing integer, every new row goes to the end. The rightmost leaf page is the only one that gets written to, and the rest of the index stays in cache undisturbed. Inserts are sequential and cheap.&lt;/p&gt;
&lt;p&gt;UUIDv4 is random by design. Every new row lands at a random position in the B-tree. Instead of appending to one page, the engine has to:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Find the right page somewhere in the middle of the tree.&lt;/li&gt;
&lt;li&gt;Load it into the buffer pool if it isn&amp;rsquo;t already (on a large table, it usually isn&amp;rsquo;t).&lt;/li&gt;
&lt;li&gt;Split it if it&amp;rsquo;s full.&lt;/li&gt;
&lt;li&gt;Write both halves back.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;On a table with hundreds of millions of rows, the index doesn&amp;rsquo;t fit in memory, so most inserts trigger a random disk read before they can do anything else. The write amplification is real and measurable: factor of 5 to 10× versus sequential inserts isn&amp;rsquo;t unusual.&lt;/p&gt;
&lt;p&gt;The damage doesn&amp;rsquo;t stop at the primary-key index. In InnoDB (MySQL), every secondary index includes a copy of the primary key at its leaves. A 36-byte &lt;code&gt;CHAR(36)&lt;/code&gt; UUID embedded in every secondary index entry means larger indexes, more pages, more I/O compared to an 8-byte &lt;code&gt;BIGINT&lt;/code&gt;. Secondary indexes on a UUID-keyed table are routinely 3–4× the size of the same indexes on a &lt;code&gt;BIGINT&lt;/code&gt;-keyed table. Every lookup through a secondary index reads more pages to cover the same rows.&lt;/p&gt;
&lt;p&gt;PostgreSQL handles storage differently. Its heap means the primary key is just another index, so the physical table isn&amp;rsquo;t ordered by it. The primary-key index still suffers the same random-insertion pathology, and the write amplification from random page loads still applies.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Page splits compound over time.&lt;/strong&gt; When a new UUID lands in a full page, InnoDB splits the page in two, each roughly half full. Over millions of inserts, the index develops internal fragmentation: pages allocated but only partially used. The index is physically larger than it needs to be, and scans read more pages for the same row count. &lt;code&gt;OPTIMIZE TABLE&lt;/code&gt; (MySQL) or &lt;code&gt;REINDEX&lt;/code&gt; (PostgreSQL) can repack the index, but on a busy table it&amp;rsquo;s a maintenance window you have to schedule.&lt;/p&gt;
&lt;h2 id="uuidv7-the-insert-locality-fix"&gt;UUIDv7: the insert-locality fix
&lt;/h2&gt;&lt;p&gt;UUIDv7 is the version most new code should reach for when UUIDs are the right answer. It encodes a Unix millisecond timestamp into the high 48 bits, with random bits filling the rest. Two practical consequences:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Sortable.&lt;/strong&gt; Sequential generation means new IDs land at the end of the B-tree, not scattered across it. Insert locality is close to a &lt;code&gt;BIGINT&lt;/code&gt;&amp;rsquo;s. The pathological page-split behaviour of v4 goes away.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Time-parseable.&lt;/strong&gt; The creation time is embedded in the ID, recoverable from the primary key alone: useful for log correlation, rough time-range filtering, and debugging without reaching for &lt;code&gt;created_at&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- UUIDv7: time-ordered, so inserts are roughly sequential
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL 18 ships a built-in uuidv7() function
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UUID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;uuidv7&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Recover creation time from the ID - no created_at column needed
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;uuid_extract_timestamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;uuid_extract_timestamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;date&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_date&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- v7 sorts chronologically, newest first
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;uuid_extract_timestamp()&lt;/code&gt; has existed in PostgreSQL since 17 but only returned a value for UUIDv1. PG 18 extended it to support v7 alongside the new &lt;code&gt;uuidv7()&lt;/code&gt; generator. One caveat: calling it in a &lt;code&gt;WHERE&lt;/code&gt; clause (&lt;code&gt;WHERE uuid_extract_timestamp(id) &amp;gt;= '2026-04-01'&lt;/code&gt;) is non-SARGable and forces a scan; see &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;Non-SARGable Predicates&lt;/a&gt;. For indexed time-range filtering, keep a &lt;code&gt;created_at&lt;/code&gt; column as the query target, or compare against a boundary UUID generated at the target timestamp.&lt;/p&gt;
&lt;p&gt;MySQL 8 doesn&amp;rsquo;t ship a v7 generator or a timestamp extractor, so application-side generation is the norm there - libraries exist in every major language, and most modern ORMs default to v7 if you ask for UUIDs. Extraction is manual: for &lt;code&gt;BINARY(16)&lt;/code&gt; storage (the recommended form), the first 6 bytes hold the millisecond timestamp.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL: manually parse v7&amp;#39;s timestamp prefix (BINARY(16) storage)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;FROM_UNIXTIME&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CONV&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;HEX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SUBSTRING&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;DATE&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FROM_UNIXTIME&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CONV&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;HEX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SUBSTRING&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_date&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- v7 sorts chronologically
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;For &lt;code&gt;CHAR(36)&lt;/code&gt; storage, the extraction strips hyphens first: &lt;code&gt;CONCAT(SUBSTRING(id, 1, 8), SUBSTRING(id, 10, 4))&lt;/code&gt; gives the 12 hex characters of the timestamp prefix. If your v1 UUIDs were stored with &lt;code&gt;UUID_TO_BIN(id, 1)&lt;/code&gt; (the swap flag that reorders bytes for v1 index locality), the byte layout differs and the substring offsets change. Most v7-generating libraries skip the swap because v7 is already time-ordered without it - check what yours does before trusting the extraction.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What v7 doesn&amp;rsquo;t change.&lt;/strong&gt; It&amp;rsquo;s still 16 bytes on disk, and still 36 if you stored it as &lt;code&gt;CHAR(36)&lt;/code&gt;. The insert-locality win doesn&amp;rsquo;t come with a storage discount, so the overhead versus a &lt;code&gt;BIGINT&lt;/code&gt; is the same as v4. The readable creation timestamp is usually a feature and occasionally a problem: in systems where row-creation time is sensitive (order IDs revealing traffic patterns to competitors, user IDs exposing signup timing), it&amp;rsquo;s the one property v4 had that v7 gives up.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;CHAR(36) is the silent tax&lt;/strong&gt;
 &lt;div&gt;The worst-case UUID storage, &lt;code&gt;CHAR(36)&lt;/code&gt;, is what most ORM-generated schemas default to, because it&amp;rsquo;s the portable representation. &lt;code&gt;BINARY(16)&lt;/code&gt; in MySQL or the native &lt;code&gt;uuid&lt;/code&gt; type in PostgreSQL cuts storage by more than half and keeps comparisons on fixed-width integers instead of strings. Pick the narrow form on day one; retrofitting it later is a full-table rewrite that touches every secondary index.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="uuid-to-integer-mapping-keep-uuids-at-the-edge"&gt;UUID-to-integer mapping: keep UUIDs at the edge
&lt;/h2&gt;&lt;p&gt;The other workable fix is structural: expose UUIDs externally, use integers internally. A single lookup table maps the external UUID to an internal &lt;code&gt;BIGINT&lt;/code&gt;, and every other table in the database uses the &lt;code&gt;BIGINT&lt;/code&gt; as its foreign key. The UUID lookup happens once (at the API boundary) and everything downstream is fast, compact, 8-byte integer joins.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;external_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BINARY&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- the UUID the outside world sees
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Every other table references the BIGINT, not the UUID
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- API request comes in with a UUID; one indexed lookup to resolve it
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;external_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UUID_TO_BIN&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;a1b2c3d4-...&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- From here on, everything uses the BIGINT
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The UUID column has a unique index, so the lookup is a single index seek, sub-millisecond regardless of table size. The rest of the schema gets 8-byte keys everywhere: smaller indexes, faster joins, no page splits, no secondary-index bloat. The external-facing API still uses UUIDs, so you don&amp;rsquo;t leak sequence information or row counts.&lt;/p&gt;
&lt;p&gt;The trade-off is an extra layer of indirection. Every inbound request resolves the UUID before anything else; in practice this is negligible (one indexed lookup), but it means the schema has two identity systems to maintain. For long-lived OLTP applications where every join on every table pays the UUID cost, this structure is often worth the extra lookup.&lt;/p&gt;
&lt;h2 id="when-random-uuids-are-actually-fine"&gt;When random UUIDs are actually fine
&lt;/h2&gt;&lt;p&gt;Not every schema needs to bend. Three cases where UUIDv4 as a primary key is a defensible choice:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Small tables that stay small.&lt;/strong&gt; A configuration table, a lookup table, a feature-flag table. At 50,000 rows the page-split pathology doesn&amp;rsquo;t show up, secondary indexes are tiny, and the convenience of client-generated IDs outweighs any cost.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Write rates low enough that random I/O doesn&amp;rsquo;t matter.&lt;/strong&gt; An admin tool recording 50 events per minute doesn&amp;rsquo;t care about write amplification. The index fits in cache, every page is warm, page splits happen rarely enough that fragmentation stays manageable. &amp;ldquo;Doesn&amp;rsquo;t survive scale&amp;rdquo; is only a problem at scale.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Information-leak concerns that outweigh performance.&lt;/strong&gt; If hiding creation-order is a hard requirement (competitive, privacy, or security), v7&amp;rsquo;s embedded timestamp is a non-starter and v4 is the only UUID version that meets the requirement. Pay the write-amplification cost and use the UUID-to-integer mapping to contain the damage.&lt;/p&gt;
&lt;h2 id="why-v4-keeps-showing-up-as-the-default"&gt;Why v4 keeps showing up as the default
&lt;/h2&gt;&lt;p&gt;Schema-reading assistants and scaffolding tools reinforce UUIDv4 as the default answer, and the reason is mostly inertial. Training corpora are heavy on examples where &lt;code&gt;uuid4()&lt;/code&gt; is the canonical &amp;ldquo;globally unique ID&amp;rdquo; call; &lt;code&gt;CREATE TABLE ... id UUID DEFAULT gen_random_uuid()&lt;/code&gt; appears in orders of magnitude more tutorials than the v7 equivalent. Asked for a new table schema, a model produces the v4 version because that&amp;rsquo;s what the surrounding code it learned from produced. B-tree locality and write amplification don&amp;rsquo;t show up in the DDL (they&amp;rsquo;re runtime properties of the key distribution) so the catalog gives no signal that v4 and v7 behave differently at 100M rows. Both look identical in &lt;code&gt;information_schema&lt;/code&gt;: &lt;code&gt;uuid&lt;/code&gt; or &lt;code&gt;char(36)&lt;/code&gt;, primary key, not null.&lt;/p&gt;
&lt;p&gt;The fix is the same discipline this post already makes the case for, with one amplified beat: document the choice where a schema reader can find it. A comment on the PK column (&lt;code&gt;'UUIDv7: time-ordered; required for insert locality'&lt;/code&gt; or &lt;code&gt;'UUIDv4: randomized; chosen to hide creation order'&lt;/code&gt;) turns a silent convention into a machine-readable decision. The next reader (teammate or model) sees why the column is what it is and why the alternative was rejected. Without the comment, the next table scaffolded by an assistant inherits whichever version the training data sampled, and the schema drifts toward whichever default produces the most plausible-looking DDL.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;UUIDv4 is a tool that solved a coordination problem (distributed ID generation without central authority) and accidentally became the default for everything, including the cases where coordination wasn&amp;rsquo;t a problem and the cost of random writes is non-trivial. &amp;ldquo;Pick a UUID for your PK&amp;rdquo; is a decision most schemas make without ever being explicit about what they&amp;rsquo;re trading.&lt;/p&gt;
&lt;p&gt;The decision matrix is short. Do you need globally unique, coordination-free IDs? If no, use &lt;code&gt;BIGINT&lt;/code&gt;. If yes, use UUIDv7 and store it as &lt;code&gt;BINARY(16)&lt;/code&gt; or native &lt;code&gt;uuid&lt;/code&gt;, never &lt;code&gt;CHAR(36)&lt;/code&gt;. If v7&amp;rsquo;s embedded timestamp is a problem, use v4 but keep it at the API boundary and use integers inside the schema. Each of those decisions costs almost nothing on day one and saves a lot of rework at 100 million rows.&lt;/p&gt;</description></item><item><title>God Tables: 150 Columns and the Quiet Cost of 'Just Add a Column'</title><link>https://explainanalyze.com/p/god-tables-150-columns-and-the-quiet-cost-of-just-add-a-column/</link><pubDate>Tue, 05 Aug 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/god-tables-150-columns-and-the-quiet-cost-of-just-add-a-column/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post God Tables: 150 Columns and the Quiet Cost of 'Just Add a Column'" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A wide table looks cheap because every column was added for a real reason; the expensive part is that rows grow, every write amplifies, and every secondary index inherits the bloat. The fix is splitting by access pattern (columns read together stay together, rarely-touched columns move out), not aggressive normalization that trades one wide table for six-way joins on every read.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The schema started clean four years ago: &lt;code&gt;users(id, email, password_hash, created_at)&lt;/code&gt;, four columns. Today the table is renamed &lt;code&gt;customers&lt;/code&gt; and has 184 columns. Billing address. Shipping address. Three additional shipping addresses numbered 2 through 4. &lt;code&gt;preferences_json&lt;/code&gt; for user settings. Twelve feature-flag &lt;code&gt;TINYINT&lt;/code&gt;s. Three Stripe identifiers from three processor migrations. &lt;code&gt;last_login_at&lt;/code&gt;, &lt;code&gt;last_seen_at&lt;/code&gt;, &lt;code&gt;last_purchase_at&lt;/code&gt;, &lt;code&gt;last_notification_sent_at&lt;/code&gt;. Forty more columns whose meaning lives in Confluence, if anywhere. No single &lt;code&gt;ALTER TABLE ADD COLUMN&lt;/code&gt; was unreasonable at the time. The accumulated result is an average row size of 6KB, an UPDATE to &lt;code&gt;last_login_at&lt;/code&gt; that rewrites every byte of it, and a buffer pool holding four customer rows per page instead of forty.&lt;/p&gt;
&lt;p&gt;The obvious fix is to normalize it: split into &lt;code&gt;customer_profile&lt;/code&gt;, &lt;code&gt;customer_billing&lt;/code&gt;, &lt;code&gt;customer_addresses&lt;/code&gt;, &lt;code&gt;customer_preferences&lt;/code&gt;, &lt;code&gt;customer_feature_flags&lt;/code&gt;, &lt;code&gt;customer_audit&lt;/code&gt;. That&amp;rsquo;s the textbook answer and it&amp;rsquo;s the one that breaks the moment you look at the dominant read. The list view on the admin page needs name, email, status, last login, Stripe status, and total spent. Now it&amp;rsquo;s a six-way join on every page load. The fix that looked clean in the migration doc makes the most-frequent query more expensive, not less. The read cost moves to the place it&amp;rsquo;s paid most often, and somebody (usually a few months later) proposes a materialized view to &amp;ldquo;just flatten it back out,&amp;rdquo; which is the god table returning through a different door.&lt;/p&gt;
&lt;h2 id="how-a-row-store-actually-reads-a-row"&gt;How a row-store actually reads a row
&lt;/h2&gt;&lt;p&gt;Before the cost math makes sense: OLTP engines like InnoDB and PostgreSQL&amp;rsquo;s heap store complete rows laid out contiguously on fixed-size pages - typically 16KB in InnoDB, 8KB in PostgreSQL. A page holds as many rows as fit. When a query needs one column of one row, the engine doesn&amp;rsquo;t read that column alone; it locates the row&amp;rsquo;s page via an index lookup or scan, loads the whole page into the buffer pool, and reads the requested column out of the in-memory row image.&lt;/p&gt;
&lt;p&gt;The one exception is the index-only scan: if every column the query projects and filters on is already present inside an index, the base table doesn&amp;rsquo;t have to be touched and only the index pages are loaded. See &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;Covering Index Traps&lt;/a&gt; for how quickly this optimization disappears, usually the moment a SELECT list grows by one column. Every other read path goes through the row, which means the row&amp;rsquo;s width sets the floor on how much data the engine moves per lookup. Reading &lt;code&gt;email&lt;/code&gt; from a 184-column customer row loads 6KB into memory to return 50 bytes; reading the same column from an 800-byte row loads 800 bytes. The buffer pool is a fixed size and every byte of unused column data in it is displacing something another query needs.&lt;/p&gt;
&lt;p&gt;Column stores (ClickHouse, BigQuery, Parquet-backed warehouses) invert this entirely. Data is laid out by column, so reading one column reads only that column&amp;rsquo;s storage. The wide-table cost math doesn&amp;rsquo;t apply there, which is why this anti-pattern is specifically a row-store OLTP problem and why denormalized fact tables in analytical warehouses are fine at 300 columns.&lt;/p&gt;
&lt;h2 id="what-150-columns-actually-costs"&gt;What 150 columns actually costs
&lt;/h2&gt;&lt;p&gt;The individual cost of one column is negligible. The system-level cost shows up in several places at once, and none of them are visible in a diff that adds one more.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Row size and write amplification.&lt;/strong&gt; InnoDB stores full rows on disk pages, and an UPDATE rewrites the entire row even if only one column changed. On a 184-column table averaging 6KB per row, updating &lt;code&gt;last_login_at&lt;/code&gt; on every sign-in rewrites 6KB, not 8 bytes. PostgreSQL doesn&amp;rsquo;t rewrite in place (MVCC creates a new tuple for every UPDATE and marks the old one dead) but the new tuple is 6KB too, and &lt;code&gt;VACUUM&lt;/code&gt; has that much more to reclaim. Either engine, the write cost per logical change scales with row width.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Buffer pool density.&lt;/strong&gt; The page-per-read mechanism above means buffer-pool efficiency scales inversely with row width. At 6KB per row, an InnoDB 16KB page holds two rows; at 400 bytes per row it holds forty. A database with 10GB of buffer pool has the effective working set of a much smaller instance once rows get wide. Queries that used to run hot start touching disk for no reason other than that the rows they cared about no longer fit in memory alongside the rows other queries cared about.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Secondary indexes inherit the width problem.&lt;/strong&gt; Every secondary index in InnoDB carries a copy of the primary key at its leaves; every index entry is a key-columns + PK-copy record. A wide table tends to accumulate indexes: you index email, Stripe ID, last-login, phone, region, account-manager-ID, each for a different query path. Six secondary indexes on a 184-column table isn&amp;rsquo;t unusual, and each of them is physically larger than it would be on a narrow table, because the PK copy and fill-factor choices interact with row density. &lt;a class="link" href="https://explainanalyze.com/p/one-column-added-to-a-select-1020-page-reads-became-166667/" &gt;Covering indexes&lt;/a&gt; are also harder to arrange: the list view wants eight columns projected, and indexing eight columns of a 184-column table to cover one query is an expensive trade.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lock and transaction width.&lt;/strong&gt; Every UPDATE acquires a row-level lock. Transactions that touch a wide row hold that lock for the duration of the transaction, and because the row spans many concerns (billing, preferences, audit timestamps) transactions from unrelated code paths contend on the same row. A background job updating &lt;code&gt;last_seen_at&lt;/code&gt; now serializes against a billing job updating &lt;code&gt;stripe_customer_id&lt;/code&gt; on the same customer, because both paths lock the same row. In the split-by-concern shape, they&amp;rsquo;d contend on different rows of different tables.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schema migrations get more expensive.&lt;/strong&gt; &lt;code&gt;ALTER TABLE ADD COLUMN&lt;/code&gt; on a 184-column table is slower, holds metadata locks longer, and has a larger blast radius if it fails. MySQL&amp;rsquo;s online DDL is usually fine for NULL-default additions; PostgreSQL is generally fast for the same case. Any migration that needs to rewrite rows (changing a column type, adding NOT NULL with a backfill) scales with row size, and a 6KB row rewrite on 200 million rows is a different operation than an 800-byte row rewrite on the same count.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Every column is a commitment&lt;/strong&gt;
 &lt;div&gt;The cost of adding a column is small and immediate. The cost of having 150 columns is systemic and deferred: buffer-pool density, index size, write amplification, lock contention, migration cost. None of the deferred costs are visible in the PR that adds one more column, which is why they accumulate uncorrected until the table is painful.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="why-llms-make-this-worse"&gt;Why LLMs make this worse
&lt;/h2&gt;&lt;p&gt;Schema drift in the wide-table direction is what language models reinforce by default. A model generating &lt;code&gt;ALTER TABLE&lt;/code&gt; for a feature request reads the current schema and proposes the smallest change that makes the feature work, which is almost always adding columns to the table that already holds the related data. Proposing a split requires understanding the access pattern, the transaction boundaries, and the write frequency of the new columns versus the existing ones. None of that is in the &lt;code&gt;CREATE TABLE&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The loop reinforces itself: the wider the table gets, the more natural it is for the next change to widen it further. &amp;ldquo;Where do loyalty tier and tier expiry go?&amp;rdquo; The model sees &lt;code&gt;customers&lt;/code&gt; has every other user-attached concept in it and adds two columns. The alternative (&lt;code&gt;CREATE TABLE customer_loyalty (customer_id PK FK, tier, expires_at)&lt;/code&gt;) requires the model to argue for a split, and splits are rare in the training data compared to additions because splits are rare in real codebases for the same reason: they&amp;rsquo;re harder to ship than additions. The model is correctly pattern-matching on what humans actually do, which is exactly the problem.&lt;/p&gt;
&lt;p&gt;ORMs compound this. One model equals one table is the default shape in ActiveRecord, Django ORM, Prisma, SQLAlchemy, and Ecto. Refactoring a &lt;code&gt;Customer&lt;/code&gt; model into three co-owned tables is a change that touches every query, every serializer, every test. The ORM makes &amp;ldquo;add a column to the existing model&amp;rdquo; a five-line change and &amp;ldquo;split the model&amp;rdquo; a project. Engineers pick the cheap option every time, and the wide table ratchets.&lt;/p&gt;
&lt;h2 id="split-by-access-pattern-not-by-concept"&gt;Split by access pattern, not by concept
&lt;/h2&gt;&lt;p&gt;&amp;ldquo;Normalize it&amp;rdquo; isn&amp;rsquo;t the fix because normalization is a property of data shape, not query cost. The fix is to look at what columns are actually read and written together, and keep those co-located; the rest moves out.&lt;/p&gt;
&lt;p&gt;A workable decomposition for the &lt;code&gt;customers&lt;/code&gt; example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Core hot table.&lt;/strong&gt; The columns read on nearly every query: &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;status&lt;/code&gt;, &lt;code&gt;tier&lt;/code&gt;, &lt;code&gt;stripe_customer_id&lt;/code&gt;, &lt;code&gt;created_at&lt;/code&gt;. Maybe twenty columns. This is what the list view, the auth path, and most API responses need.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;1:1 cold tables.&lt;/strong&gt; Concerns that are read rarely or in specific flows: &lt;code&gt;customer_audit&lt;/code&gt; for login/seen/purchase timestamps, &lt;code&gt;customer_preferences&lt;/code&gt; for user settings, &lt;code&gt;customer_feature_flags&lt;/code&gt; for the twelve TINYINT flags. Each is a separate table with &lt;code&gt;customer_id&lt;/code&gt; as PK and FK, joined only when the flow actually needs it. Writes to &lt;code&gt;last_login_at&lt;/code&gt; stop rewriting the billing row.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;1:N tables for repeating groups.&lt;/strong&gt; Addresses, payment methods, anything that was modeled as &lt;code&gt;shipping_address_2&lt;/code&gt;, &lt;code&gt;shipping_address_3&lt;/code&gt;, &lt;code&gt;shipping_address_4&lt;/code&gt; is an &lt;code&gt;addresses&lt;/code&gt; table with a FK and a type. This collapses polymorphic-ish schema decisions that shouldn&amp;rsquo;t have been made at the column level in the first place; see &lt;a class="link" href="https://explainanalyze.com/p/polymorphic-references-are-not-foreign-keys/" &gt;Polymorphic References&lt;/a&gt; for the related pattern where doing this without a FK goes wrong.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The trade-off is that some queries now join two or three tables instead of reading one. On the hot path this is fine; the joins are on PK-equals-FK, the join tables are small, and the read is usually cheaper than scanning a fat row. The cold path is where it matters: the audit screen now joins &lt;code&gt;customers&lt;/code&gt; to &lt;code&gt;customer_audit&lt;/code&gt;, which costs one indexed lookup and nobody notices. The place to be careful is the query that reads from three of the split tables on every request. If that&amp;rsquo;s dominant, one of those tables probably belongs merged back in.&lt;/p&gt;
&lt;h2 id="when-a-wide-table-is-actually-fine"&gt;When a wide table is actually fine
&lt;/h2&gt;&lt;p&gt;Not every 100-column table is a god table. Three cases where width is defensible:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analytical and reporting tables on columnar storage.&lt;/strong&gt; As noted above, warehouses like ClickHouse, BigQuery, and Redshift invert the cost calculus. Reading one column doesn&amp;rsquo;t load the rest, and the normalization pressure flips: denormalize aggressively because joins are expensive and per-column reads are cheap. This anti-pattern is specifically a row-store OLTP problem.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Small tables that stay small.&lt;/strong&gt; A &lt;code&gt;tenants&lt;/code&gt; table with 80 columns and 500 rows fits entirely in the buffer pool. The write amplification is paid a few thousand times a day, not a few million. The secondary-index cost is negligible because the indexes are small. Width matters when row count is large enough for the per-row cost to dominate; on small tables it doesn&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Every query reads every column.&lt;/strong&gt; Uncommon but real. If the dominant read is &amp;ldquo;fetch the full customer record for display&amp;rdquo; and the split would produce a join that runs on every request anyway, the split doesn&amp;rsquo;t help. The test is whether the queries you actually run touch disjoint column sets. If they do, the split has a real win; if they don&amp;rsquo;t, it&amp;rsquo;s architecture for its own sake.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Relational databases aren&amp;rsquo;t built for developer convenience. They&amp;rsquo;re built for storage efficiency and retrieval speed: narrow rows, well-placed indexes, joins on indexed keys, query plans that read only what they need. Normalization isn&amp;rsquo;t an academic ideal; it&amp;rsquo;s the shape that lines up with how the engine actually pays its bills. Every cost mechanism in this post (buffer-pool density, write amplification, index bloat, row-lock width) is the engine reporting the same thing in different dialects: the shape you&amp;rsquo;re asking it to hold isn&amp;rsquo;t the shape it was optimized for.&lt;/p&gt;
&lt;p&gt;God tables are the limit of a sequence of rational local decisions where the global cost is invisible at each step. The column count of a mature production table is usually a decent proxy for how long the team has been making the cheap choice, which is most teams most of the time, and that is not by itself a failure. The failure is that the cost goes uncounted. A 6KB row is a write-amplification multiplier on every UPDATE, a buffer-pool multiplier on every read, and an index-size multiplier on every secondary index. None of those costs are on the PR that adds a column; all of them are on the dashboard that shows p99 drifting up quarter after quarter.&lt;/p&gt;
&lt;p&gt;The lever is to count the cost at the system level when the table hits a certain width (pick a threshold: sixty columns, a hundred, whatever fits) and make the next column addition a conversation about whether this concern belongs here, not a line in a migration. The answer is often still yes, but it shouldn&amp;rsquo;t be the default answer.&lt;/p&gt;</description></item><item><title>Non-SARGable Predicates: How a Function in WHERE Kills Your Index</title><link>https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/</link><pubDate>Sat, 14 Jun 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Non-SARGable Predicates: How a Function in WHERE Kills Your Index" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A predicate is SARGable (Search ARGument able) if the database can use an index to evaluate it. Wrapping a column in a function makes the predicate non-SARGable: the engine has to compute the function on every row before it can filter, which means a full table scan no matter what indexes exist. The fix isn&amp;rsquo;t always to rewrite the predicate (sometimes the column&amp;rsquo;s type or collation is wrong and the code is masking it) but every non-SARGable predicate on a hot path is a performance bug waiting for the table to grow.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Here are two queries that return the exact same rows:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Version A
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;YEAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2025&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Version B
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2025-01-01&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2026-01-01&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;On a 10,000-row &lt;code&gt;events&lt;/code&gt; table, both run in under a millisecond and nobody notices the difference. On a 200-million-row &lt;code&gt;events&lt;/code&gt; table with an index on &lt;code&gt;created_at&lt;/code&gt;, version A does a sequential scan and takes 45 seconds; version B does an index range scan and takes 12 milliseconds. Neither query is wrong. They don&amp;rsquo;t even disagree about the answer. One just does the same work in a way the planner can&amp;rsquo;t optimize.&lt;/p&gt;
&lt;p&gt;The obvious fix is &amp;ldquo;rewrite every function-wrapped predicate as a range.&amp;rdquo; That works for the date-extraction case and a few others. For &lt;code&gt;WHERE LOWER(email) = 'alice@example.com'&lt;/code&gt;, the rewrite needs to know whether the column&amp;rsquo;s collation is case-insensitive, and if it isn&amp;rsquo;t, there&amp;rsquo;s no direct equivalent, only a functional index or a schema change. The fix depends on why the function is there, and &amp;ldquo;why&amp;rdquo; usually points back at something in the schema that&amp;rsquo;s pretending to be something it isn&amp;rsquo;t.&lt;/p&gt;
&lt;h2 id="what-sargable-means-in-practice"&gt;What SARGable means in practice
&lt;/h2&gt;&lt;p&gt;An index on &lt;code&gt;created_at&lt;/code&gt; is a sorted structure: the engine can jump to any date range in O(log n) time by walking the B-tree. For the planner to use that index on a predicate, the predicate has to be expressible as &amp;ldquo;the column is in this range&amp;rdquo;: a direct comparison between the column and a constant or parameter.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;created_at &amp;gt;= '2025-01-01'&lt;/code&gt; meets that contract. The planner translates it to &amp;ldquo;walk the index to the first entry ≥ 2025-01-01, read forward from there.&amp;rdquo; That&amp;rsquo;s a range scan.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;YEAR(created_at) = 2025&lt;/code&gt; doesn&amp;rsquo;t meet the contract. The value being compared isn&amp;rsquo;t &lt;code&gt;created_at&lt;/code&gt;; it&amp;rsquo;s the output of &lt;code&gt;YEAR()&lt;/code&gt; applied to &lt;code&gt;created_at&lt;/code&gt;. The index on &lt;code&gt;created_at&lt;/code&gt; doesn&amp;rsquo;t know the output of &lt;code&gt;YEAR()&lt;/code&gt; for any row without computing it. So the planner falls back to evaluating the function on every row (a sequential scan) and only then filtering.&lt;/p&gt;
&lt;p&gt;Common forms of the same mistake:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Non-SARGable: function on column → full scan
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LOWER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;alice@example.com&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;DATE&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2025-01-15&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CAST&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;CONCAT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;first_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39; &amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;last_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Alice Smith&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- SARGable equivalents
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;alice@example.com&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- if collation is case-insensitive
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2025-01-15&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2025-01-16&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- fix the type at the schema level
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;first_name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Alice&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;last_name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Smith&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Three of the four non-SARGable forms have clean rewrites. The first one (&lt;code&gt;LOWER(email)&lt;/code&gt;) depends on collation, which is where a lot of real-world cases live.&lt;/p&gt;
&lt;h2 id="the-collation-case"&gt;The collation case
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;WHERE LOWER(email) = 'alice@example.com'&lt;/code&gt; is almost always a tell that the &lt;code&gt;email&lt;/code&gt; column has a case-sensitive collation and the application is hiding it at query time. Two real fixes, one cosmetic fix:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fix the column.&lt;/strong&gt; If the data should be matched case-insensitively, give the column a case-insensitive collation. In PostgreSQL that&amp;rsquo;s &lt;code&gt;CITEXT&lt;/code&gt; or a &lt;code&gt;COLLATE &amp;quot;und-x-icu&amp;quot;&lt;/code&gt; with the ICU provider; in MySQL it&amp;rsquo;s a &lt;code&gt;_ci&lt;/code&gt; collation (which is usually the default anyway). Once the column&amp;rsquo;s collation handles the case folding, &lt;code&gt;WHERE email = 'alice@example.com'&lt;/code&gt; is SARGable and fast. This is the right fix when case-insensitivity is a property of the data.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Add a functional (expression) index.&lt;/strong&gt; If you can&amp;rsquo;t change the column&amp;rsquo;s collation (there&amp;rsquo;s a case-sensitive comparison elsewhere in the schema that depends on the current behavior) index the expression itself:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL: functional index
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_users_email_lower&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;LOWER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Now WHERE LOWER(email) = &amp;#39;...&amp;#39; uses the index
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL 8.0+: expression index (requires the same constant-folding fix)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_email_lower&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="k"&gt;LOWER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)));&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;This works, with caveats. The index&amp;rsquo;s storage and write cost is real. The predicate has to match the indexed expression exactly: &lt;code&gt;LOWER(email)&lt;/code&gt; is indexed, but &lt;code&gt;UPPER(email)&lt;/code&gt; isn&amp;rsquo;t, and the planner won&amp;rsquo;t translate between them. Every non-SARGable expression you want fast needs its own index.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Cosmetic fix: case-fold at write time.&lt;/strong&gt; Store the email as already-lowercased. &lt;code&gt;WHERE email = 'alice@example.com'&lt;/code&gt; is now SARGable directly, no expression index needed. This usually requires application changes (whoever&amp;rsquo;s writing has to remember to case-fold) which is why the functional index is more popular even though it&amp;rsquo;s heavier. &lt;a class="link" href="https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/" &gt;Where business logic lives&lt;/a&gt; covers the general shape of this decision; case-folding at the database with a generated column (&lt;code&gt;GENERATED ALWAYS AS (LOWER(email)) STORED&lt;/code&gt;) is often the cleanest answer when the application can&amp;rsquo;t be trusted to normalize consistently.&lt;/p&gt;
&lt;h2 id="implicit-type-conversions-are-the-subtler-version"&gt;Implicit type conversions are the subtler version
&lt;/h2&gt;&lt;p&gt;The function isn&amp;rsquo;t always in the query. Sometimes the planner is adding one:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- account_id is VARCHAR, literal is numeric
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;account_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;12345&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL will silently cast every &lt;code&gt;account_id&lt;/code&gt; value to a number for comparison: a per-row function call that kills index usage just as effectively as an explicit &lt;code&gt;CAST()&lt;/code&gt;. PostgreSQL is stricter and usually errors, but can still do implicit conversions between compatible types that undermine indexes.&lt;/p&gt;
&lt;p&gt;The fix is matching types in both directions: the column type should be what the column is (a numeric ID should be &lt;code&gt;BIGINT&lt;/code&gt;, not &lt;code&gt;VARCHAR&lt;/code&gt;), and the query should write the literal in the column&amp;rsquo;s type (&lt;code&gt;WHERE account_id = '12345'&lt;/code&gt; if the column is genuinely a string). Either fix works; matching the column type to the data&amp;rsquo;s real shape is usually the durable answer.&lt;/p&gt;
&lt;p&gt;This is also where &lt;a class="link" href="https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/" &gt;mixed PK strategies&lt;/a&gt; show up. Joining a BIGINT &lt;code&gt;id&lt;/code&gt; to a UUID &lt;code&gt;id&lt;/code&gt; doesn&amp;rsquo;t just return wrong results; on MySQL it coerces one side to a string, which is the same implicit-function problem dressed up as a join.&lt;/p&gt;
&lt;h2 id="when-non-sargable-is-acceptable"&gt;When non-SARGable is acceptable
&lt;/h2&gt;&lt;p&gt;Not every non-SARGable predicate is a bug. Three cases where it&amp;rsquo;s fine:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Small tables.&lt;/strong&gt; A 5,000-row lookup table with a function-wrapped predicate scans in microseconds. The planner isn&amp;rsquo;t going to use an index on that size anyway. &lt;code&gt;WHERE UPPER(code) = 'NY'&lt;/code&gt; on a 50-row &lt;code&gt;states&lt;/code&gt; table is not worth worrying about.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;One-off analytical queries.&lt;/strong&gt; A one-time data extract that scans a large table is going to scan it regardless. If the query will never run again, the function call isn&amp;rsquo;t the bottleneck (the table size is) and adding a functional index to optimize one query isn&amp;rsquo;t worth the write cost on every future insert.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When the function genuinely can&amp;rsquo;t be avoided.&lt;/strong&gt; Some predicates legitimately need to compute. &lt;code&gt;WHERE haversine_distance(lat, lng, user_lat, user_lng) &amp;lt; 10&lt;/code&gt; on a geospatial query can&amp;rsquo;t be rewritten as a simple range; you need a spatial index (PostGIS, MySQL spatial extensions) to make it SARGable in the geometric sense. The fix is a different kind of index, not a rewrite.&lt;/p&gt;
&lt;h2 id="why-natural-language-to-sql-tilts-non-sargable"&gt;Why natural-language-to-SQL tilts non-SARGable
&lt;/h2&gt;&lt;p&gt;Schema-reading assistants and text-to-SQL models produce this class of bug more often than hand-written queries do. A user asks &amp;ldquo;events in 2025&amp;rdquo;; the closest English-to-SQL mapping is &lt;code&gt;WHERE YEAR(created_at) = 2025&lt;/code&gt;, and that&amp;rsquo;s what the model writes. The correct form (a half-open range) requires knowing the calendar boundary of the year and producing two comparison operators, which is a less-direct translation of the question. &lt;code&gt;WHERE LOWER(email) = 'alice@example.com'&lt;/code&gt; is the natural translation of &amp;ldquo;find the user with this email, case-insensitive,&amp;rdquo; even when the column&amp;rsquo;s collation already handles case and the function wrap defeats the index it would otherwise use.&lt;/p&gt;
&lt;p&gt;The catalog-level fix is the same one the bigger-picture section below points at: model the column so the natural query is already SARGable. Pick a case-insensitive collation on &lt;code&gt;email&lt;/code&gt;, store prices as &lt;code&gt;NUMERIC&lt;/code&gt; so no cast is needed, partition or index date columns so the range-literal form performs. When the schema matches the shape of the question, the model&amp;rsquo;s default translation works. When it doesn&amp;rsquo;t, the model produces a query that runs clean and scans the table, and no plan inspection is built into the generation loop to catch it.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Non-SARGable predicates are easy to write, and they come from somewhere: almost always a schema decision that&amp;rsquo;s being papered over at query time. &lt;code&gt;LOWER(email)&lt;/code&gt; hides a collation mismatch. &lt;code&gt;CAST(price AS INT)&lt;/code&gt; hides a type that should have been &lt;code&gt;NUMERIC&lt;/code&gt; from the start. &lt;code&gt;DATE(created_at)&lt;/code&gt; hides the fact that the query is answering a date-range question but written in a way that reads more naturally as an equality. Every one of these is a query-level workaround for a schema-level issue, and every one of them costs an index when the table grows large enough to care.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; is the diagnostic. If the plan shows a sequential scan on a predicate that should hit an index, the predicate is almost certainly non-SARGable; look at what&amp;rsquo;s wrapping the column. Fix the schema if you can, add a functional index if you can&amp;rsquo;t, and treat non-SARGable predicates on hot paths as latent performance bugs, not style issues.&lt;/p&gt;</description></item><item><title>The Bare `id` Primary Key: When Every Table Joins to Every Other Table</title><link>https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/</link><pubDate>Tue, 27 May 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post The Bare `id` Primary Key: When Every Table Joins to Every Other Table" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A bare &lt;code&gt;id&lt;/code&gt; primary key on every table makes &lt;code&gt;a.id = b.id&lt;/code&gt; valid SQL between any two tables, which means neither a human reviewing the query nor an LLM generating one can tell which of those equalities are meaningful. Name primary keys after the table they identify, and the schema describes its own relationships.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Here&amp;rsquo;s a query an AI assistant generated against a real production schema:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;actions&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;alice@example.com&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Syntactically clean. Ran without error. Returned zero rows, which the assistant reported back as &amp;ldquo;this user has no actions.&amp;rdquo; The real answer: &lt;code&gt;users.id&lt;/code&gt; is a &lt;code&gt;BIGINT&lt;/code&gt; and &lt;code&gt;actions.id&lt;/code&gt; is a &lt;code&gt;CHAR(36)&lt;/code&gt; UUID. MySQL coerced the integer to a string, compared it to a UUID, and found no match. The join wasn&amp;rsquo;t wrong, exactly. It was meaningless, and the database had no way to say so.&lt;/p&gt;
&lt;p&gt;The experienced reader&amp;rsquo;s first fix is &amp;ldquo;just use UUIDs everywhere&amp;rdquo; or &amp;ldquo;enforce the type at join time.&amp;rdquo; Neither works. The footgun isn&amp;rsquo;t the type mismatch; it&amp;rsquo;s the column name. When every table&amp;rsquo;s primary key is named &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;a.id = b.id&lt;/code&gt; is a valid expression between any two tables in the schema, and nothing in the column names tells you whether that expression means anything. Fix the types and you close one failure mode; the identically-typed, semantically-unrelated &lt;code&gt;users.id = 42 = orders.id&lt;/code&gt; case still ships.&lt;/p&gt;
&lt;h2 id="what-nobody-can-see"&gt;What nobody can see
&lt;/h2&gt;&lt;p&gt;The &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt; convention is older than most of us, and the case for it is usually framed as clarity or style. The sharper framing is that bare &lt;code&gt;id&lt;/code&gt; hides the information that matters most at the point of the join (which table&amp;rsquo;s identity is being compared, and whether comparing them makes sense) from every reader of the query.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The query&amp;rsquo;s reviewer.&lt;/strong&gt; &lt;code&gt;ON u.id = a.id&lt;/code&gt; gives no hint of what&amp;rsquo;s being matched. A human reviewer has to carry the table-to-alias mapping (&lt;code&gt;u&lt;/code&gt; is &lt;code&gt;users&lt;/code&gt;, &lt;code&gt;a&lt;/code&gt; is &lt;code&gt;actions&lt;/code&gt;) and the table-to-type mapping (&lt;code&gt;users.id&lt;/code&gt; is BIGINT, &lt;code&gt;actions.id&lt;/code&gt; is UUID) in working memory, then cross-check them against the join condition. None of those steps are hard, but reviewers skip them because the column names look symmetric. Two &lt;code&gt;.id&lt;/code&gt; references read as &amp;ldquo;joining on primary keys,&amp;rdquo; which is the kind of join nobody flags.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The LLM reading the schema.&lt;/strong&gt; An assistant generating SQL from the catalog sees &lt;code&gt;users(id BIGINT, ...)&lt;/code&gt; and &lt;code&gt;actions(id CHAR(36), ...)&lt;/code&gt; as two tables with primary keys named &lt;code&gt;id&lt;/code&gt;. Absent a full column-type check on every candidate join (and most schema-reading prompts don&amp;rsquo;t do this), the natural-looking join between &amp;ldquo;a user and their actions&amp;rdquo; is &lt;code&gt;u.id = a.id&lt;/code&gt;, which is exactly wrong. The schema presented the column as joinable; the LLM took it at face value. The same mistake a tired human makes, but at scale and without fatigue to blame.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The static analyzer.&lt;/strong&gt; Linters and schema-aware query builders operate on names first and types second. A rule that warns on suspicious cross-table joins has no signal to fire on when both sides are &lt;code&gt;.id&lt;/code&gt;; the column names match, so the join is &amp;ldquo;legitimate&amp;rdquo; by shape. The same rule on &lt;code&gt;users.user_id = actions.action_id&lt;/code&gt; would flag it immediately, because the names would be obviously non-corresponding.&lt;/p&gt;
&lt;p&gt;None of these readers are missing a step they should have taken. They&amp;rsquo;re all doing the reasonable thing, and the reasonable thing produces wrong queries because the schema is telling them &lt;code&gt;id&lt;/code&gt; is &lt;code&gt;id&lt;/code&gt; in both tables.&lt;/p&gt;
&lt;h2 id="three-failure-modes-ranked-by-how-loudly-they-fail"&gt;Three failure modes, ranked by how loudly they fail
&lt;/h2&gt;&lt;p&gt;Three distinct outcomes hide behind &lt;code&gt;a.id = b.id&lt;/code&gt;, and they don&amp;rsquo;t fail equally:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;PostgreSQL, mixed types.&lt;/strong&gt; The comparison errors out with &lt;code&gt;operator does not exist: bigint = uuid&lt;/code&gt;. Loud, caught in development, fixed before merge. The best failure mode.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MySQL, mixed types.&lt;/strong&gt; Silent coercion to string, zero rows returned. The opening example. Bad, because &amp;ldquo;no results&amp;rdquo; looks like valid data to every downstream consumer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Either engine, same type but semantically unrelated.&lt;/strong&gt; &lt;code&gt;BIGINT users.id = 42&lt;/code&gt; matched against &lt;code&gt;BIGINT orders.id = 42&lt;/code&gt; returns the rows where the integers happen to collide. The query runs, the result set isn&amp;rsquo;t empty, and the rows look plausible because they&amp;rsquo;re real rows from real tables. The worst failure mode, because nothing about the output signals that the join was nonsense.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The first two are loud enough to catch in review. The third is the one that ships. The third is the default once more than one table in the schema uses a plain &lt;code&gt;BIGINT&lt;/code&gt; &lt;code&gt;id&lt;/code&gt;, which is almost every relational schema in existence.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Zero rows looks like no data&lt;/strong&gt;
 &lt;div&gt;A join that silently returns zero rows because of a type coercion is indistinguishable from a join that legitimately has no matches. Code generators, dashboards, and AI assistants all interpret empty results as &amp;ldquo;the relationship exists but has no rows,&amp;rdquo; not &amp;ldquo;the query is nonsense.&amp;rdquo; The failure hides inside success.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="mixed-pk-types-make-the-naming-problem-sharper"&gt;Mixed PK types make the naming problem sharper
&lt;/h2&gt;&lt;p&gt;Production schemas rarely stay on one PK strategy for long. The original tables are usually &lt;code&gt;BIGINT AUTO_INCREMENT&lt;/code&gt; because the framework defaulted to it; a newer service switches to UUIDs to let clients generate IDs offline or to distribute across shards; join tables pick up composite keys because &lt;code&gt;(user_id, role_id)&lt;/code&gt; is the natural identity. Nothing in the schema announces which tables fall into which bucket; &lt;code&gt;SHOW CREATE TABLE&lt;/code&gt; or &lt;code&gt;\d&lt;/code&gt; is the only source of truth, and even that requires reading every table to know what joins are legal.&lt;/p&gt;
&lt;p&gt;Mixed types are where the naming footgun turns from theoretical to frequent. When every PK was a BIGINT, the &amp;ldquo;same type but semantically unrelated&amp;rdquo; case was the main risk and reviewers caught most of it. Once the schema has BIGINT and UUID sitting next to each other (all named &lt;code&gt;id&lt;/code&gt;) the mismatched-type cases pile on top, and &amp;ldquo;no data found&amp;rdquo; becomes a regular report from any tool generating queries from the schema.&lt;/p&gt;
&lt;p&gt;The sizing question (when to pick BIGINT versus UUID versus UUIDv7 versus composite, and what each costs at the index level) is covered separately in &lt;a class="link" href="https://explainanalyze.com/p/random-uuids-as-primary-keys-the-b-tree-penalty/" &gt;Random UUIDs as Primary Keys&lt;/a&gt;. The two problems interact but have independent fixes: pick your PK types deliberately, and name them so the schema describes its own relationships. Neither fix substitutes for the other.&lt;/p&gt;
&lt;h2 id="naming-is-the-lever-that-actually-helps"&gt;Naming is the lever that actually helps
&lt;/h2&gt;&lt;p&gt;Naming is what makes a schema describe its own relationships without requiring the reader (human or otherwise) to open every &lt;code&gt;CREATE TABLE&lt;/code&gt;. Two conventions, consistently applied, close most of the gap:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Name the primary key after the table.&lt;/strong&gt; &lt;code&gt;users.user_id&lt;/code&gt;, &lt;code&gt;orders.order_id&lt;/code&gt;, &lt;code&gt;actions.action_id&lt;/code&gt;. The equality &lt;code&gt;users.user_id = orders.order_id&lt;/code&gt; reads as obvious nonsense, because the column names are no longer identical. Reviewers see it, LLMs don&amp;rsquo;t produce it, linters can flag it. The cost is a small amount of redundancy in queries (&lt;code&gt;users.user_id&lt;/code&gt; instead of &lt;code&gt;users.id&lt;/code&gt;), which is almost always a fair trade. This lines up with the broader guidance in &lt;a class="link" href="https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/" &gt;Schema Conventions and Why They Matter&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Foreign keys mirror the target PK.&lt;/strong&gt; &lt;code&gt;orders.user_id&lt;/code&gt; clearly references &lt;code&gt;users.user_id&lt;/code&gt;. &lt;code&gt;actions.user_id&lt;/code&gt; clearly references &lt;code&gt;users.user_id&lt;/code&gt;. This is already common practice; the only change is that the target&amp;rsquo;s PK name matches, closing the loop. &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;Foreign Keys Are Not Optional&lt;/a&gt; covers why the FK itself matters; naming is what makes the FK legible without the &lt;code&gt;REFERENCES&lt;/code&gt; clause in hand.&lt;/p&gt;
&lt;p&gt;The bare &lt;code&gt;id&lt;/code&gt; convention is defensible when the PK column only ever shows up in queries alongside its table name (&lt;code&gt;users.id&lt;/code&gt;) and never as a bare &lt;code&gt;id&lt;/code&gt; in a SELECT list or join condition. That discipline is hard to enforce across a team over years, and every framework&amp;rsquo;s default query builder produces &lt;code&gt;SELECT id FROM users&lt;/code&gt; without thinking about it. The naming fix makes the discipline unnecessary.&lt;/p&gt;
&lt;h2 id="when-bare-id-is-actually-fine"&gt;When bare &lt;code&gt;id&lt;/code&gt; is actually fine
&lt;/h2&gt;&lt;p&gt;Not every schema needs to bend. A small application, a service with a handful of tables, or a database where every query is reviewed by one team has plenty of context to keep the &lt;code&gt;a.id = b.id&lt;/code&gt; landmine out of reach. The cost of the convention scales with the number of tables, the number of engineers, and the number of non-human query generators; in the small case it rarely shows up.&lt;/p&gt;
&lt;p&gt;What changes once any of those numbers grow: nobody remembers which tables are BIGINT versus UUID, the assistant pattern of generating queries from schema is routine, and the review process that caught &lt;code&gt;a.id = b.id&lt;/code&gt; in a 20-table schema can&amp;rsquo;t read every join in a 400-table one. At that size the convention pays rent, and renaming PKs is a migration that gets slower every quarter.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;A schema&amp;rsquo;s job is to hold data correctly and describe its own shape well enough that the tools reading it can reason about relationships without reading every line. The bare &lt;code&gt;id&lt;/code&gt; PK is a small departure from that (one column name shared across tables) but it&amp;rsquo;s the departure that most consistently produces silent-wrong-answer queries, because SQL has no way to distinguish &amp;ldquo;same name, same meaning&amp;rdquo; from &amp;ldquo;same name, different meaning.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Name the primary key after the table it identifies, so the schema tells its own story when someone (human or otherwise) joins two of them together. It costs almost nothing on day one and leaves the schema legible at 400 tables.&lt;/p&gt;</description></item><item><title>Polymorphic References Are Not Foreign Keys</title><link>https://explainanalyze.com/p/polymorphic-references-are-not-foreign-keys/</link><pubDate>Sat, 10 May 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/polymorphic-references-are-not-foreign-keys/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Polymorphic References Are Not Foreign Keys" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A polymorphic reference is &lt;code&gt;resource_id&lt;/code&gt; plus &lt;code&gt;resource_type&lt;/code&gt; where the type string chooses which table the ID points to. ORMs make it a one-liner; the database enforces nothing. Reads need conditional joins, orphans accumulate silently, and for most uses (comments, notifications, attachments) per-target tables or mutually-exclusive FKs are the better trade.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="what-the-pattern-looks-like"&gt;What the pattern looks like
&lt;/h2&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resource_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resource_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;VARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- resource_type = &amp;#39;order&amp;#39; → resource_id references orders.id
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- resource_type = &amp;#39;invoice&amp;#39; → resource_id references invoices.id
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- resource_type = &amp;#39;ticket&amp;#39; → resource_id references support_tickets.id
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The tell is &lt;code&gt;resource_id BIGINT NOT NULL&lt;/code&gt; with no &lt;code&gt;REFERENCES&lt;/code&gt; clause; it can&amp;rsquo;t have one, because there are multiple targets. What the application treats as a foreign key is, at the database level, a plain integer with a sibling tag string.&lt;/p&gt;
&lt;h2 id="what-the-database-cant-do"&gt;What the database can&amp;rsquo;t do
&lt;/h2&gt;&lt;p&gt;The cost shows up as absence: every mechanism the database offers for reasoning about relationships is disabled, because the column&amp;rsquo;s meaning depends on data in another column.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;No foreign key.&lt;/strong&gt; A &lt;code&gt;REFERENCES&lt;/code&gt; clause names exactly one target. Orphaned &lt;code&gt;resource_id&lt;/code&gt; values are a write-time non-event and a read-time mystery. (&lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;Foreign Keys Are Not Optional&lt;/a&gt; covers the general cost; polymorphic is the case where skipping isn&amp;rsquo;t a choice.)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No cascade.&lt;/strong&gt; Delete an order and nothing cleans up the notifications pointing at it. The application has to know every table that might hold a polymorphic reference to &lt;code&gt;orders&lt;/code&gt; and clean each one. New tables added later don&amp;rsquo;t get noticed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No planner metadata.&lt;/strong&gt; Foreign keys feed join ordering and row estimates, especially in PostgreSQL. The planner sees &lt;code&gt;resource_id&lt;/code&gt; as a &lt;code&gt;BIGINT&lt;/code&gt; with a histogram and no known target.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No schema-level description.&lt;/strong&gt; Anything that reads the catalog (ERD tools, query generators, AI assistants, typed-client generators) sees no link between &lt;code&gt;notifications.resource_id&lt;/code&gt; and the tables it points at. The mapping lives in model files and string literals. (&lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Comment Your Schema&lt;/a&gt; helps here but can&amp;rsquo;t fully restore the information.)&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Orphans accumulate silently&lt;/strong&gt;
 &lt;div&gt;A polymorphic column with no FK and no cascade develops orphans over time. Reads paper over them with &lt;code&gt;LEFT JOIN ... WHERE target.id IS NOT NULL&lt;/code&gt;, so the broken rows disappear from the UI but stay in the table. In schemas a few years old, the orphan rate is rarely zero, and nobody designed for it.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="reads-pay-for-the-write-side-convenience"&gt;Reads pay for the write-side convenience
&lt;/h2&gt;&lt;p&gt;The absent FK is the schema problem. The read-path shape is where the cost becomes daily. A query that needs any column from the referenced row can&amp;rsquo;t write a single join; the target depends on a per-row value, and SQL&amp;rsquo;s join syntax takes a static target.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Conditional LEFT JOIN per target
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;COALESCE&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order_number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;invoice_number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ticket_code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ref&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;order&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;invoices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;invoice&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;support_tickets&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;ticket&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resource_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Every new target type adds a join clause here and in every other read-path query that displays a related field. The alternative (a &lt;code&gt;UNION ALL&lt;/code&gt; per target) is narrower per branch but scales linearly with target count and pushes pagination up to the union level. Most ORMs&amp;rsquo; default resolution is one query per &lt;code&gt;(resource_type, resource_id)&lt;/code&gt; group, which is the N+1 pattern that makes polymorphic feeds slow once the target set widens.&lt;/p&gt;
&lt;p&gt;&amp;ldquo;One column can point at many tables&amp;rdquo; on the write side turns into &amp;ldquo;every read query enumerates every possible table&amp;rdquo; on the read side. The symmetry people expect isn&amp;rsquo;t there.&lt;/p&gt;
&lt;h2 id="why-the-pattern-spreads"&gt;Why the pattern spreads
&lt;/h2&gt;&lt;p&gt;It&amp;rsquo;s the path of least resistance that framework ergonomics encourage. Rails&amp;rsquo; &lt;code&gt;polymorphic: true&lt;/code&gt;, Django&amp;rsquo;s &lt;code&gt;GenericForeignKey&lt;/code&gt;, and Laravel&amp;rsquo;s &lt;code&gt;morphTo&lt;/code&gt; make one-liner what would otherwise be multiple &lt;code&gt;belongs_to&lt;/code&gt; associations and a migration. &amp;ldquo;Comments on orders&amp;rdquo; and &amp;ldquo;comments on invoices&amp;rdquo; look like duplication, so a single &lt;code&gt;comments&lt;/code&gt; table with &lt;code&gt;commentable_id&lt;/code&gt; / &lt;code&gt;commentable_type&lt;/code&gt; feels cleaner. An open-ended &amp;ldquo;add comments to anything&amp;rdquo; product ask reads as an argument against committing to a target list.&lt;/p&gt;
&lt;p&gt;Each of those framings overweights the write-side cost (another table or another FK column) and underweights the integrity loss (no enforcement, no cascades, schema no longer describes itself). &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/" &gt;ORMs Are a Coupling&lt;/a&gt; covers the broader trade. Polymorphic is the canonical case where the ORM&amp;rsquo;s preferred shape is actively incompatible with what the database wants to enforce.&lt;/p&gt;
&lt;h2 id="what-the-schema-reading-assistant-sees"&gt;What the schema-reading assistant sees
&lt;/h2&gt;&lt;p&gt;A tool reading the catalog (Copilot on a schema dump, an MCP-backed agent, a RAG pipeline indexing DDL) sees &lt;code&gt;notifications.resource_id BIGINT NOT NULL&lt;/code&gt; with no &lt;code&gt;REFERENCES&lt;/code&gt; clause and no way to tell the column is anything other than an integer. Asked for &amp;ldquo;notifications about orders,&amp;rdquo; the assistant&amp;rsquo;s best guess is &lt;code&gt;notifications.resource_id = orders.id&lt;/code&gt;: a join that runs clean, returns every notification whose &lt;code&gt;resource_id&lt;/code&gt; happens to collide with an order ID (which includes invoice notifications, ticket notifications, and anything else pointing at an integer that also appears in &lt;code&gt;orders&lt;/code&gt;), and surfaces plausible-looking but semantically nonsense rows. The &lt;code&gt;resource_type&lt;/code&gt; filter that would make the join correct is the piece the schema doesn&amp;rsquo;t advertise.&lt;/p&gt;
&lt;p&gt;This is the structural version of the problem covered in &lt;a class="link" href="https://explainanalyze.com/p/the-bare-id-primary-key-when-every-table-joins-to-every-other-table/" &gt;the bare &lt;code&gt;id&lt;/code&gt; primary key&lt;/a&gt;: schema that can&amp;rsquo;t describe its own relationships forces every reader to guess, and schema-reading models guess confidently. Pulling the polymorphic column apart (per-target tables, mutually-exclusive FKs, supertype) restores the signal in the catalog. The assistant stops hallucinating the join; any RAG system indexing the schema picks up real &lt;code&gt;REFERENCES&lt;/code&gt; metadata; the next engineer reading the table doesn&amp;rsquo;t need to grep the ORM models to find out which target types exist. The integrity win and the catalog-legibility win come in the same migration.&lt;/p&gt;
&lt;h2 id="alternatives"&gt;Alternatives
&lt;/h2&gt;&lt;p&gt;Each alternative gives back some of the database&amp;rsquo;s relational machinery at different levels of verbosity.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Per-target tables.&lt;/strong&gt; Split along the target dimension: &lt;code&gt;order_notifications&lt;/code&gt;, &lt;code&gt;invoice_notifications&lt;/code&gt;, &lt;code&gt;ticket_notifications&lt;/code&gt;, each with a real FK. Real cascades, real planner metadata, self-describing schema. Cost: duplicated column sets and an explicit &lt;code&gt;UNION ALL&lt;/code&gt; for cross-target reads. That union already exists implicitly in the polymorphic shape, just moved from the read query into typed branches.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Mutually-exclusive nullable FKs with &lt;code&gt;CHECK&lt;/code&gt;.&lt;/strong&gt; One table, one FK column per target, a constraint enforcing exactly one is non-null:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;invoice_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;invoices&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ticket_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;support_tickets&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CONSTRAINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;exactly_one_target&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;invoice_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ticket_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;)::&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Real FKs per target, real cascades, row&amp;rsquo;s meaning unambiguous. Scales reasonably up to a handful of targets and stops scaling cleanly somewhere around ten.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Supertype table.&lt;/strong&gt; A shared parent table carries a common ID; each target type&amp;rsquo;s table references the parent. The polymorphic column then points at the parent, which is a single real FK. Cleanest structural answer and the one with the highest adoption cost; retrofitting this onto an existing schema is substantial migration work.&lt;/p&gt;
&lt;h2 id="when-polymorphic-is-actually-the-right-call"&gt;When polymorphic is actually the right call
&lt;/h2&gt;&lt;p&gt;The trade-offs stack up unfavorably for most common uses, but not all. The pattern earns its keep when the relationship is genuinely best-effort: audit events, activity logs, &amp;ldquo;recently viewed&amp;rdquo; lists, undo history, where a lost reference is a recoverable annoyance rather than a correctness incident. The FK was never going to be load-bearing, and the polymorphic shape matches the actual semantics: &amp;ldquo;reference anything, and if it&amp;rsquo;s gone, show a tombstone.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;Outside that zone the default bias should run the other way. A comment system with three possible parents is not a case for polymorphism; it&amp;rsquo;s a case for three comment tables or mutually-exclusive FK columns, with the ORM abstracting the read-side stitching.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Polymorphic references are a specific case of a broader pattern: designs that move information out of the schema and into the application, in exchange for ergonomics in the model layer. The schema drifts from &amp;ldquo;self-describing relational structure&amp;rdquo; toward &amp;ldquo;indexed key-value store the application interprets.&amp;rdquo; That&amp;rsquo;s a legitimate position (DynamoDB and friends live there on purpose) but a relational database running on polymorphic associations is paying for a relational engine and choosing not to use most of what it offers.&lt;/p&gt;
&lt;p&gt;The pattern isn&amp;rsquo;t wrong. It&amp;rsquo;s an aggressive trade, priced on day one by the convenience of &lt;code&gt;polymorphic: true&lt;/code&gt; and on day three hundred by the silent orphan count, the conditional joins, and &lt;code&gt;resource_id BIGINT&lt;/code&gt; telling no one what the table is related to. Reach for it on purpose. Keep the option of pulling it back onto typed FK columns open, because the migrations away are slower the longer the schema has been pretending the reference isn&amp;rsquo;t there.&lt;/p&gt;</description></item><item><title>ORMs Are a Coupling, Not an Abstraction</title><link>https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/</link><pubDate>Wed, 23 Apr 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post ORMs Are a Coupling, Not an Abstraction" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;An ORM is a coupling between schema shape and code shape, not an abstraction over it. The coupling pays off in year one and compounds against you in year five. For long-lived OLTP systems, a thinner layer over raw SQL (sqlc, jOOQ, typed query builders) ages better.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There&amp;rsquo;s a period early in a project where an ORM feels like pure upside. You define a model, the framework generates a migration, and &lt;code&gt;User.where(email: …)&lt;/code&gt; returns typed objects. No SQL to write, no mapping layer to maintain, no integration boilerplate. Five years later the same project has four migration directories, a model class with thirty custom methods overriding the ORM defaults, team memory of which relations are lazy-loaded and which aren&amp;rsquo;t, and a quarterly discussion about whether it&amp;rsquo;s time to upgrade Rails 4 to Rails 7 or skip straight to something else entirely.&lt;/p&gt;
&lt;p&gt;Somewhere between those two points, the ORM stopped being an abstraction and became a coupling: a bidirectional contract between schema and code that both sides have to honor for every change. The contract shapes more than how changes propagate. It also shapes the schema itself, because an ORM&amp;rsquo;s default output is a database structured like the class graph rather than one designed for the workload. Short-lived prototypes and simple CRUD apps still benefit from ORMs. The defensible use cases are narrower than the industry&amp;rsquo;s default deployment pattern suggests, and the coupling is durable and consistently underestimated at the point a team decides to adopt one.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;SQL outlives its wrappers&lt;/strong&gt;
 &lt;div&gt;SQL is arguably the most widely-deployed, longest-lived programming language in the industry. Every major database speaks it, every backend engineer eventually learns it, the DDL and DML haven&amp;rsquo;t meaningfully changed in decades. The ORMs wrapping it are the opposite: framework-specific, tied to a particular version of a particular stack, with conventions that differ across ecosystems and shift across major releases. The default across most engineering orgs is to go out of their way to adopt the less portable, less stable of the two and hide the more durable one behind it. A team joining a new project expects to relearn the ORM. Nobody expects to relearn &lt;code&gt;SELECT&lt;/code&gt;.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The rest of this post offers one answer for why that&amp;rsquo;s the default: the coupling an ORM introduces hides its cost long enough that the trade looks very different in year one than it does in year five.&lt;/p&gt;
&lt;h2 id="what-the-orm-is-actually-doing"&gt;What the ORM is actually doing
&lt;/h2&gt;&lt;p&gt;The word &amp;ldquo;ORM&amp;rdquo; suggests abstraction, &amp;ldquo;object-relational mapping&amp;rdquo; as if the mapping is the hidden plumbing. The practical reality is the opposite: the mapping is the product. An ORM takes your schema shape and projects it onto code shape. Columns become fields. Tables become classes. Foreign keys become methods. Indexes are invisible until you care about them. Constraints are whatever the ORM&amp;rsquo;s DSL exposes and nothing more.&lt;/p&gt;
&lt;p&gt;That projection is useful. It lets application code avoid SQL, most of the time. It also means the code and schema are now two views of the same data model, and those views are expected to stay in sync by you, by your migration framework, by your tests, and by every developer who touches either side.&lt;/p&gt;
&lt;p&gt;Stay in sync, in practice, means every schema change is also a code change and every migration is a coordinated edit across multiple files. That coupling is the defining characteristic of the tool.&lt;/p&gt;
&lt;h2 id="source-of-truth-pick-one-know-which"&gt;Source of truth: pick one, know which
&lt;/h2&gt;&lt;p&gt;Every ORM ecosystem has a default answer to &amp;ldquo;where does the schema canonically live&amp;rdquo;, and most teams never think about it.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Model-first.&lt;/strong&gt; Rails and Django generate migrations from changes to model classes. The model is the source of truth; the schema follows. Running &lt;code&gt;rails db:schema:dump&lt;/code&gt; produces a &lt;code&gt;schema.rb&lt;/code&gt; that describes the current state, and the migration files are the history of how it got there.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Schema-first.&lt;/strong&gt; &lt;a class="link" href="https://sqlc.dev/" target="_blank" rel="noopener"
 &gt;sqlc&lt;/a&gt; and &lt;a class="link" href="https://www.jooq.org/" target="_blank" rel="noopener"
 &gt;jOOQ&lt;/a&gt; read SQL DDL files and generate typed client code. The schema is the source of truth; the code follows.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hybrid / unclear.&lt;/strong&gt; Hibernate can do either, depending on configuration. SQLAlchemy lets you declare models in Python and generate migrations via Alembic, or point Alembic at an existing schema and generate models. Teams that don&amp;rsquo;t decide end up doing both.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The hybrid case is where the real damage happens. Over years, a team that migrates from model-first to schema-first (or vice versa) without a clean cutover ends up with a schema that neither the models nor the migration history correctly describes. Rows backfilled by a DBA with direct SQL don&amp;rsquo;t show up in the ORM&amp;rsquo;s understanding of the world. Columns added by a production hotfix get rediscovered six months later when someone regenerates models from the database.&lt;/p&gt;
&lt;p&gt;The fix is to decide, document, and enforce whichever one you pick, the way you would any other convention.&lt;/p&gt;
&lt;h2 id="migrations-stop-being-db-work"&gt;Migrations stop being &amp;ldquo;DB work&amp;rdquo;
&lt;/h2&gt;&lt;p&gt;In a raw-SQL codebase, a schema migration is a single file: &lt;code&gt;CREATE TABLE&lt;/code&gt;, &lt;code&gt;ALTER TABLE&lt;/code&gt;, &lt;code&gt;DROP COLUMN&lt;/code&gt;. The migration is the change.&lt;/p&gt;
&lt;p&gt;In an ORM codebase, a single logical schema change is typically:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A migration file (&lt;code&gt;add_email_to_users.rb&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;The model class (&lt;code&gt;User#email&lt;/code&gt; getter, validation, &lt;code&gt;serialize&lt;/code&gt; calls).&lt;/li&gt;
&lt;li&gt;The serializer (&lt;code&gt;UserSerializer#email&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;The API contract (OpenAPI spec, GraphQL schema, whatever the team uses).&lt;/li&gt;
&lt;li&gt;Fixtures and factories (FactoryBot, factory_boy, test data).&lt;/li&gt;
&lt;li&gt;Query helpers that need to know the new column.&lt;/li&gt;
&lt;li&gt;Type stubs or generated types (TypeScript declarations, Python stubs).&lt;/li&gt;
&lt;li&gt;Admin UI config, sometimes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What should be a single metadata-level change is now a coordinated edit across five to eight files, and missing any one of them produces a subtly broken application. The ORM didn&amp;rsquo;t create the complexity; it distributed it. The schema change is still one change. It just has to be propagated to every place the code has a mirror of the schema.&lt;/p&gt;
&lt;p&gt;At small scale this is fine. The friction compounds once the team is big enough that the people writing the migration aren&amp;rsquo;t the same people owning the serializers and the API consumers. A schema change now requires coordinating across teams, each with their own view of the data model, each needing their files updated. The schema itself didn&amp;rsquo;t get harder to change. The ORM layer around it did.&lt;/p&gt;
&lt;h2 id="hidden-queries"&gt;Hidden queries
&lt;/h2&gt;&lt;p&gt;The ORM generates SQL you didn&amp;rsquo;t write. That&amp;rsquo;s the value proposition. It&amp;rsquo;s also a persistent failure mode.&lt;/p&gt;
&lt;p&gt;Lazy loading is the classic. &lt;code&gt;user.orders&lt;/code&gt; triggers a query, &lt;code&gt;user.orders.first.line_items&lt;/code&gt; triggers another, and a loop over 100 users runs at least 101 queries, none of them visible in the code. Eager loading exists (&lt;code&gt;.includes(:orders)&lt;/code&gt;) but only if someone remembers to write it. The default is lazy. Defaults win. Magic methods hide their multiplicity: &lt;code&gt;where(status: :active).first_or_create(email: …)&lt;/code&gt; is three or four queries depending on the code path, and the code says nothing about it. Generated sorts do the same for indexes, since &lt;code&gt;User.order(:created_at).limit(10)&lt;/code&gt; on a table without an index on &lt;code&gt;created_at&lt;/code&gt; is a full table scan the reviewer never saw.&lt;/p&gt;
&lt;p&gt;All of this is the ORM doing exactly what it said it would. The cost is that the SQL the database actually runs isn&amp;rsquo;t in version control, isn&amp;rsquo;t code-reviewed, and isn&amp;rsquo;t profiled until it shows up in slow-query logs. Every ORM codebase accumulates query shapes nobody intentionally wrote.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The queries you don&amp;#39;t see&lt;/strong&gt;
 &lt;div&gt;The SQL emitted by an ORM is invisible until something breaks. Code review covers the method call; the database sees three joins and a subquery. Teams relying heavily on ORMs end up needing separate tooling (query logs, APM, &lt;code&gt;pg_stat_statements&lt;/code&gt;, &lt;code&gt;EXPLAIN&lt;/code&gt; on every slow path) just to know what&amp;rsquo;s actually running.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="two-query-languages-neither-complete"&gt;Two query languages, neither complete
&lt;/h2&gt;&lt;p&gt;Past the CRUD ceiling, every ORM codebase ends up with raw SQL living alongside ORM calls. Window functions, recursive CTEs, PostgreSQL &lt;code&gt;DISTINCT ON&lt;/code&gt;, &lt;code&gt;LATERAL&lt;/code&gt; joins, MySQL &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; with complex update clauses, exclusion constraints, full-text search, spatial queries: the list of things awkward or impossible to express through the ORM grows over the life of the project.&lt;/p&gt;
&lt;p&gt;The result is a codebase with two query languages coexisting. Reviewers have to know both. Type safety is uneven; ORM calls produce typed objects, raw SQL produces hashes or arrays that need manual mapping. The two styles drift. The ORM-side queries follow the ORM&amp;rsquo;s conventions; the raw-SQL queries follow whatever the author happened to write that day.&lt;/p&gt;
&lt;p&gt;Past a certain complexity threshold the ORM stops reducing the SQL surface area and starts adding a layer on top of it. The SQL didn&amp;rsquo;t go away. It got pushed into the half of the codebase that&amp;rsquo;s harder to trace.&lt;/p&gt;
&lt;h2 id="bidirectional-coupling"&gt;Bidirectional coupling
&lt;/h2&gt;&lt;p&gt;The part that surprises teams is how hard it is to leave.&lt;/p&gt;
&lt;p&gt;Migrating a database schema (renaming a column, changing a type, splitting a table) is mechanical. It&amp;rsquo;s a migration file and a deploy window. The mechanics are well-understood and the blast radius is bounded.&lt;/p&gt;
&lt;p&gt;Migrating off an ORM is not mechanical, because the conventions have bled everywhere. Controller and API code returns JSON whose shape matches model attributes, with &lt;code&gt;as_json&lt;/code&gt;, &lt;code&gt;serializable_hash&lt;/code&gt;, and callbacks defining what the outside world sees. The test suite&amp;rsquo;s fixtures, factories, and in-memory SQLite databases depend on the ORM being there. Third-party integrations (export formats, webhooks, analytics pipelines) were built against the ORM&amp;rsquo;s JSON representation of the data, and admin UIs like Rails Admin, Django Admin, and Laravel Nova are hard-wired to its conventions. Every scope, association, and callback in the codebase is ORM-native. Every engineer who&amp;rsquo;s been there more than a year thinks in its abstractions.&lt;/p&gt;
&lt;p&gt;The database is the innocent party here; it&amp;rsquo;s the surrounding code that grew up expecting the ORM to be there, and replacing the ORM means replacing or rewriting every one of those layers. A schema migration is a weekend project; an ORM migration is a yearlong initiative. The coupling is bidirectional, but the two directions don&amp;rsquo;t cost the same to undo, and teams that adopt an ORM for velocity rarely account for the exit cost.&lt;/p&gt;
&lt;h2 id="database-side-logic-doesnt-round-trip"&gt;Database-side logic doesn&amp;rsquo;t round-trip
&lt;/h2&gt;&lt;p&gt;Most ORMs have a tunnel-vision view of the schema: they see what they created. They don&amp;rsquo;t see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;CHECK&lt;/code&gt; constraints.&lt;/strong&gt; The ORM has no concept of them. A constraint like &lt;code&gt;CHECK (amount &amp;gt;= 0)&lt;/code&gt; is invisible to the model; the ORM&amp;rsquo;s validations become the only gatekeeper the application knows about.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Triggers.&lt;/strong&gt; A trigger that mutates a row after insert produces data the ORM didn&amp;rsquo;t know would be there. Reading back the row often requires an explicit reload.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Generated columns.&lt;/strong&gt; MySQL&amp;rsquo;s &lt;code&gt;GENERATED ALWAYS AS (…) STORED&lt;/code&gt; and PostgreSQL&amp;rsquo;s equivalent produce values the ORM treats as regular columns, but they can&amp;rsquo;t be written to, and the ORM&amp;rsquo;s default behavior is to try.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Partial and expression indexes.&lt;/strong&gt; The ORM sees the column, not the index. A query that should hit a partial index on &lt;code&gt;WHERE deleted_at IS NULL&lt;/code&gt; gets generated without that predicate and misses the index.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Exclusion constraints.&lt;/strong&gt; PostgreSQL &lt;code&gt;EXCLUDE USING gist (…)&lt;/code&gt;. Completely outside the ORM&amp;rsquo;s worldview.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The ORM&amp;rsquo;s view of the schema is a subset of the real schema. Queries written against that subset can violate invariants the database enforces. The application code thinks the write succeeded; the &lt;code&gt;INSERT&lt;/code&gt; comes back with a constraint violation; the code has no idea why. Teams paper over this with application-level validation that duplicates the database&amp;rsquo;s, and then the two drift, which is its own class of production incident.&lt;/p&gt;
&lt;h2 id="relational-modeling-isnt-object-modeling"&gt;Relational modeling isn&amp;rsquo;t object modeling
&lt;/h2&gt;&lt;p&gt;The coupling goes one direction that&amp;rsquo;s easy to see: schema changes require code changes. It also goes the other direction, which is harder to see. The ORM&amp;rsquo;s object model is what shapes the schema in the first place. For simple data, a &lt;code&gt;User&lt;/code&gt; with an email and a password hash, that&amp;rsquo;s fine. For non-trivial domains, the shape inherited from object modeling produces schemas that look like class hierarchies and perform like poorly-designed databases.&lt;/p&gt;
&lt;p&gt;This mismatch has a name: the object-relational impedance mismatch. Its practical consequence is that ORM-driven schemas get shaped by class hierarchies rather than by the relationships and access patterns the workload actually has.&lt;/p&gt;
&lt;p&gt;Normalization doesn&amp;rsquo;t look like inheritance. A properly normalized schema is structured by the shape of the relationships between entities, not by a class graph. Consider a scheduling application with three kinds of entries: appointments, days off, and product launches. All of them are events. They have a start time, an owner, a status. Each has different additional fields.&lt;/p&gt;
&lt;p&gt;The relational answer is a supertype/subtype pattern (sometimes called class table inheritance): a base &lt;code&gt;events&lt;/code&gt; table with the shared fields, and specialized tables for each subtype, each with &lt;code&gt;event_id&lt;/code&gt; as a primary key that&amp;rsquo;s also a foreign key back to &lt;code&gt;events&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;starts_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ends_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;appointment&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;day_off&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;launch&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;appointments&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DELETE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CASCADE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;location&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;days_off&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DELETE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CASCADE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;paid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BOOLEAN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;launches&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;event_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DELETE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CASCADE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;product_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;audience&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Each subtype has its own columns, indexes, and constraints. Each can evolve independently. A new field on &lt;code&gt;appointments&lt;/code&gt; doesn&amp;rsquo;t touch &lt;code&gt;events&lt;/code&gt;, &lt;code&gt;days_off&lt;/code&gt;, or &lt;code&gt;launches&lt;/code&gt;. Dropping the &lt;code&gt;launches&lt;/code&gt; feature drops one table and a CHECK-constraint value. Queries that only care about one subtype hit a narrow, well-indexed table instead of scanning across fifty columns of mostly-null data.&lt;/p&gt;
&lt;p&gt;The ORM-driven shape tends to produce something different. Rails&amp;rsquo; single-table inheritance (STI) collapses everything into one wide table with a &lt;code&gt;type&lt;/code&gt; column and every possible subtype field nullable. Django&amp;rsquo;s multi-table inheritance is closer to the relational answer but introduces implicit joins the developer didn&amp;rsquo;t ask for. Hibernate offers all three strategies (&lt;code&gt;SINGLE_TABLE&lt;/code&gt;, &lt;code&gt;JOINED&lt;/code&gt;, &lt;code&gt;TABLE_PER_CLASS&lt;/code&gt;) but most teams pick &lt;code&gt;SINGLE_TABLE&lt;/code&gt; because it&amp;rsquo;s the default and the fastest for small-scale CRUD.&lt;/p&gt;
&lt;p&gt;STI-style tables start showing their cost around the 10-million-row mark. Every query now scans a table with dozens of nullable columns. Indexes have to include the &lt;code&gt;type&lt;/code&gt; column to be useful. Adding a field to one subtype means adding a nullable column visible to every other subtype. The schema looks like a class hierarchy and performs like one table doing the job of four.&lt;/p&gt;
&lt;p&gt;Complex relationships don&amp;rsquo;t fit class graphs. Many-to-many bridges with their own columns, polymorphic references (one column that points to different tables depending on a sibling column&amp;rsquo;s value), temporal tables, recursive self-references; once the data model has these, the object graph starts fraying. The ORM&amp;rsquo;s answer is usually a custom association that looks natural in code and generates SQL nobody would write by hand.&lt;/p&gt;
&lt;p&gt;Normalization decisions are driven by access patterns, not classes. A well-designed schema decides what to normalize and what to denormalize based on read/write ratios, query patterns, and storage trade-offs. The ORM-first approach tends to normalize by class structure, which is mostly correlated with good access-pattern normalization at small scale and mostly uncorrelated with it at scale.&lt;/p&gt;
&lt;p&gt;The coupling here runs deeper than code-to-schema. The class graph shapes the schema itself, and that form of the coupling dictates how the database performs under real traffic.&lt;/p&gt;
&lt;h2 id="when-scale-exposes-the-modeling"&gt;When scale exposes the modeling
&lt;/h2&gt;&lt;p&gt;The class-shaped schema is cheap at small scale. Its cost is hidden until the workload grows, and because the schema shape is coupled to the class graph the application assumes, fixing it takes an application restructure rather than a schema migration. The ORM&amp;rsquo;s opinions about data modeling are fine at 1,000 rows. Tolerable at 1 million. Breaking at 10 million. At 100 million, the patterns that were quietly suboptimal become the production incidents of the quarter.&lt;/p&gt;
&lt;p&gt;Wide STI tables that scanned fine at 100k rows become the reason a query times out at 100M, because the planner can&amp;rsquo;t pick an efficient path through dozens of mostly-null columns with mixed cardinalities. Lazy-loaded associations that cost 200ms at small scale turn into 60-second requests fanning out to a thousand queries. &lt;code&gt;find_or_create_by&lt;/code&gt; races that never mattered when two users hit the same endpoint start causing daily deadlocks on hot rows. Unindexed ORM-generated sorts that worked at 10k rows become sequential scans over hundreds of gigabytes, and connection-pool exhaustion from ORMs that hold connections across application logic becomes a top-of-funnel incident when traffic grows.&lt;/p&gt;
&lt;p&gt;At this point, teams reach for tools that weren&amp;rsquo;t supposed to be in the solution space for an OLTP application. Materialized views are the common one. They&amp;rsquo;re legitimately useful for analytical workloads, wrong for write-heavy OLTP because they have to be refreshed, and refresh windows during traffic either stall the primary or serve stale reads. Read replicas with application-level routing get bolted on not because the read workload demands it, but because the primary is buckling under queries that would have been cheap on a better-designed schema. Caching layers get introduced to paper over query shapes the ORM insists on generating. Each of these has legitimate uses. None of them is a fix for a schema that wasn&amp;rsquo;t designed for the access pattern it&amp;rsquo;s getting.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Materialized views aren&amp;#39;t an OLTP tool&lt;/strong&gt;
 &lt;div&gt;A materialized view is a precomputed query result stored as a table. In an OLTP system with heavy writes, the refresh cost either stalls the primary during the refresh or leaves the view stale. Neither is acceptable for a live application. Materialized views are an analytical-workload tool; reaching for them to fix an OLTP performance problem is a sign the underlying schema shape is wrong.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The pattern: ORM-driven schemas work until they don&amp;rsquo;t, and when they don&amp;rsquo;t, the options are rewrite the schema (hard, because the ORM&amp;rsquo;s conventions are everywhere) or add infrastructure that papers over the problem (expensive, and eventually stops working too). The schema that was designed to be ergonomic for the ORM at 1,000 rows is now the binding constraint on what the application can do at 100M.&lt;/p&gt;
&lt;h2 id="the-thinner-alternatives"&gt;The thinner alternatives
&lt;/h2&gt;&lt;p&gt;There&amp;rsquo;s a spectrum between &amp;ldquo;hand-roll every query with &lt;code&gt;database/sql&lt;/code&gt;&amp;rdquo; and &amp;ldquo;full ORM with identity map, lazy loading, and 200-line models.&amp;rdquo; Several tools occupy the middle ground by treating SQL as the source of truth and generating typed code from it, without the mapping layer.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a class="link" href="https://sqlc.dev/" target="_blank" rel="noopener"
 &gt;sqlc&lt;/a&gt;.&lt;/strong&gt; Go, Kotlin, Python, TypeScript. You write SQL queries in &lt;code&gt;.sql&lt;/code&gt; files; sqlc generates type-safe client code. The schema is canonical, the queries are code-reviewed SQL, and there&amp;rsquo;s no runtime layer to reason about. Migrations stay plain DDL.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a class="link" href="https://www.jooq.org/" target="_blank" rel="noopener"
 &gt;jOOQ&lt;/a&gt;.&lt;/strong&gt; JVM. Reads your schema and produces a fluent, type-safe DSL for building queries. Feels like SQL, reads like SQL, with compile-time type checking. Schema-first, no model mapping.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a class="link" href="https://kysely.dev/" target="_blank" rel="noopener"
 &gt;Kysely&lt;/a&gt;.&lt;/strong&gt; TypeScript. Typed query builder with no ORM layer. You describe the schema in types; Kysely ensures queries match. The full SQL surface area is reachable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a class="link" href="https://orm.drizzle.team/" target="_blank" rel="noopener"
 &gt;Drizzle&lt;/a&gt;.&lt;/strong&gt; TypeScript. Despite the name, closer to a typed query builder than a classical ORM. Schema declared in code, queries written in a SQL-like DSL, no identity map.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Plain &lt;code&gt;database/sql&lt;/code&gt; or &lt;code&gt;pgx&lt;/code&gt; with a small query helper.&lt;/strong&gt; Go in particular has a tradition of &amp;ldquo;raw SQL plus a thin wrapper.&amp;rdquo; More boilerplate, minimal coupling.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The common thread across these tools: schema is the source of truth, queries are code-reviewed first-class artifacts, and there&amp;rsquo;s no mapping layer pretending the database doesn&amp;rsquo;t exist. The payoff is predictability; the SQL you see is the SQL that runs. The cost is some of the magic: no &lt;code&gt;User.find(1).orders.where(total: 100..).first_or_create&lt;/code&gt; one-liners.&lt;/p&gt;
&lt;p&gt;For long-lived OLTP systems with non-trivial query shapes, that predictability is worth more than the magic. For short-lived CRUD apps, it isn&amp;rsquo;t.&lt;/p&gt;
&lt;h2 id="when-orms-still-earn-their-place"&gt;When ORMs still earn their place
&lt;/h2&gt;&lt;p&gt;ORMs have a place. It&amp;rsquo;s narrower than the industry&amp;rsquo;s default deployment suggests. The workloads where the velocity payoff consistently outweighs the coupling cost share two properties: bounded scope and bounded lifespan.&lt;/p&gt;
&lt;p&gt;Short-lived prototypes and experiments qualify. If the project will be rewritten, replaced, or discarded within a year, model-first iteration is genuinely faster while the schema is fluid, and the coupling cost never gets time to compound. CRUD-heavy internal tools and admin UIs qualify too: the query shapes are uniform and simple, the workload won&amp;rsquo;t scale past the ORM&amp;rsquo;s comfort zone, and the system doesn&amp;rsquo;t outlive the product it supports. There the ORM&amp;rsquo;s constraints function as a style guide rather than a limit on what the application can do.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s the list, and the justifications teams actually use (&amp;ldquo;the team knows Rails&amp;rdquo;, &amp;ldquo;the query shapes are simple, for now&amp;rdquo;, &amp;ldquo;we&amp;rsquo;re small&amp;rdquo;) aren&amp;rsquo;t on it. Those framings start as short-lived exceptions and end up as the default, and once the project outlives its original scope the coupling cost compounds silently until it&amp;rsquo;s too expensive to remove.&lt;/p&gt;
&lt;p&gt;Picking an ORM for a prototype is fine. The failure mode is keeping it ten years later, after the prototype has become the company&amp;rsquo;s main production system, after the workload has grown past its original shape, and after migrating off costs more than a rewrite of the application. Most of the ORM codebases engineers end up cursing started as one of the two cases above and were never reconsidered when they outgrew them.&lt;/p&gt;
&lt;h2 id="trade-offs"&gt;Trade-offs
&lt;/h2&gt;&lt;p&gt;Everything in this post has a counter-argument, and the counter-arguments are real. ORMs save real time on simple queries; &lt;code&gt;User.find(1)&lt;/code&gt; is shorter than &lt;code&gt;SELECT * FROM users WHERE id = 1&lt;/code&gt;, and across a codebase it adds up. Type safety in the application layer is a genuine benefit where the ecosystem delivers it (Django&amp;rsquo;s model fields, SQLAlchemy&amp;rsquo;s typed columns, and Hibernate&amp;rsquo;s entity types do; Rails and ActiveRecord don&amp;rsquo;t give compile-time types), and raw SQL&amp;rsquo;s answer, schema-first code generation, works but requires tooling. Some teams legitimately want their data model to have methods, validations, and behavior co-located with the data. An ORM gives that for free; a query builder doesn&amp;rsquo;t. A team that knows Rails deeply will out-ship a team learning sqlc for the same project, so the right answer depends on the team, not the abstract merits. And the middle ground has costs of its own: typed query builders require maintained type definitions, schema-first code generation adds a build step, and &amp;ldquo;no ORM&amp;rdquo; means a different abstraction, maintained by you.&lt;/p&gt;
&lt;p&gt;The choice is a trade between two failure modes: the ORM&amp;rsquo;s coupling cost against the query-builder&amp;rsquo;s boilerplate and maintenance cost. For short-lived systems, the ORM wins. For long-lived systems, the thinner layer wins. The catch is that most systems surviving their first year are long-lived, and most teams underestimate how long their system will live. If the project is still running three years from now, you&amp;rsquo;re probably in the second category whether or not you planned to be.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;For short-lived projects (the prototype, the internal CRUD tool, the bounded experiment) the trade is worth it. The coupling cost is deferred, and by the time it would catch up the project has served its purpose or been replaced.&lt;/p&gt;
&lt;p&gt;For projects that live long enough and grow complex enough (which is almost any project that survives its first year) the coupling becomes the dominant cost. Every major framework upgrade is a migration of its own. Every scale inflection requires working around the ORM&amp;rsquo;s opinions. Every query past the CRUD ceiling is raw SQL anyway. The better default for an application the team expects to still be running in three years is schema-first: keep the DDL canonical, keep queries as first-class code-reviewed artifacts, use a thin typed layer (sqlc, jOOQ, Kysely, Drizzle) to bridge to the application, and leave the ORM in the toolbox for cases that genuinely match its narrow strengths.&lt;/p&gt;
&lt;p&gt;If you&amp;rsquo;re starting a project expected to live more than a year, default to schema-first. Inside an existing ORM codebase where the signals are showing up (raw-SQL ratio creeping up, migrations that require cross-team coordination, queries the ORM can&amp;rsquo;t express, &lt;a class="link" href="https://explainanalyze.com/p/non-sargable-predicates-how-a-function-in-where-kills-your-index/" &gt;predicates it wraps in a function&lt;/a&gt; so the index goes unused, performance paths that bypass it anyway) the useful question is where to draw the schema-first boundary for new work. Usually at new subsystems, not legacy code. Grandfather what&amp;rsquo;s there, pick up sqlc or jOOQ or Kysely for new code, and let the boundary move over years.&lt;/p&gt;</description></item><item><title>Schema Conventions Don't Survive Without Automation</title><link>https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/</link><pubDate>Sun, 06 Apr 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Schema Conventions Don't Survive Without Automation" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Schema conventions only survive when automation enforces them. A rule a linter, ORM, migration runner, or IaC module checks will hold for years; a rule the team merely agreed to won&amp;rsquo;t outlast the people who agreed. Pick the conventions your automation needs and skip the purely subjective ones, because they&amp;rsquo;ll drift regardless of how strongly anyone feels.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A new engineer adds a table to the analytics schema and runs into a build break: the CI lint rule complains about a missing soft-delete column. She checks ten other analytics tables. Eight have &lt;code&gt;deleted_at&lt;/code&gt;. Two have &lt;code&gt;is_deleted&lt;/code&gt;. One ignores soft-delete because its rows are immutable. She asks in #data-eng which convention applies and gets back &amp;ldquo;depends on the table, ask the original author.&amp;rdquo; Two of the original authors have left. She adds &lt;code&gt;deleted_at TIMESTAMP NULL&lt;/code&gt; to match the majority, ships the PR, and the dashboard that aggregates across all eleven tables starts double-counting the rows where &lt;code&gt;is_deleted = 1&lt;/code&gt; overlaps with the new &lt;code&gt;deleted_at IS NULL&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The convention the lint rule was meant to enforce never actually existed. The &lt;code&gt;deleted_at&lt;/code&gt; pattern landed in 2017; &lt;code&gt;is_deleted&lt;/code&gt; in 2019 from an engineer who preferred the explicit boolean; the no-soft-delete table in 2021 from a third engineer who argued (correctly, for that table) that soft delete didn&amp;rsquo;t fit the use case. Each decision was right in isolation. None of them got written down anywhere a tool could read. The lint rule enforces the column name. It cannot tell that the column name is meaningless when three patterns coexist for the same operation.&lt;/p&gt;
&lt;p&gt;The corollary is the thesis of this post. Conventions only survive when a tool is enforcing them, and they only matter when the tool checks what they actually mean, not just what they&amp;rsquo;re called. Pick the ones a linter, ORM, or migration runner can check fully (column name, behavior, and consistency against the surrounding schema), enforce them in CI, and skip the ones the tool can only validate by name. Those drift the same way the team&amp;rsquo;s memory does.&lt;/p&gt;
&lt;h2 id="what-conventions-means-here"&gt;What &amp;ldquo;conventions&amp;rdquo; means here
&lt;/h2&gt;&lt;p&gt;Conventions in this post means the decisions that apply across every table, not the design of any particular table:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Naming.&lt;/strong&gt; &lt;code&gt;snake_case&lt;/code&gt;, &lt;code&gt;camelCase&lt;/code&gt;, or &lt;code&gt;ALLCAPS&lt;/code&gt; for tables and columns.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Table names.&lt;/strong&gt; Singular (&lt;code&gt;user&lt;/code&gt;) or plural (&lt;code&gt;users&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Primary keys.&lt;/strong&gt; Bare &lt;code&gt;id&lt;/code&gt; or &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt;. BIGINT, UUID, or composite.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Foreign keys.&lt;/strong&gt; &lt;code&gt;user_id&lt;/code&gt; referencing &lt;code&gt;users.id&lt;/code&gt;, or ad-hoc names like &lt;code&gt;owner&lt;/code&gt; and &lt;code&gt;creator&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mandatory columns.&lt;/strong&gt; &lt;code&gt;created_at&lt;/code&gt;, &lt;code&gt;updated_at&lt;/code&gt;, &lt;code&gt;deleted_at&lt;/code&gt;, &lt;code&gt;created_by&lt;/code&gt;. Which tables need them and which don&amp;rsquo;t.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Status and enum patterns.&lt;/strong&gt; INT with documented values, CHECK constraint, or native ENUM. Zero-indexed or one-indexed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Boolean naming.&lt;/strong&gt; &lt;code&gt;is_active&lt;/code&gt;, &lt;code&gt;has_completed&lt;/code&gt;, &lt;code&gt;can_edit&lt;/code&gt;, or bare &lt;code&gt;active&lt;/code&gt; / &lt;code&gt;completed&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Timestamp types.&lt;/strong&gt; &lt;code&gt;TIMESTAMP&lt;/code&gt;, &lt;code&gt;DATETIME&lt;/code&gt;, &lt;code&gt;TIMESTAMPTZ&lt;/code&gt;. Timezone-aware or naive.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Character sets and collations.&lt;/strong&gt; &lt;code&gt;utf8mb4&lt;/code&gt; vs &lt;code&gt;latin1&lt;/code&gt;; &lt;code&gt;en_US.UTF-8&lt;/code&gt; vs &lt;code&gt;C&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of these have one right answer. All of them have consequences that multiply across the lifetime of the schema.&lt;/p&gt;
&lt;h2 id="humans-benefit-but-not-durably"&gt;Humans benefit, but not durably
&lt;/h2&gt;&lt;p&gt;Consistent schemas are easier for humans. Onboarding is faster, review is mechanical, queries are predictable. These benefits are real. They&amp;rsquo;re also entirely dependent on something other than memory holding the convention in place.&lt;/p&gt;
&lt;p&gt;A new engineer spends less time building a mental model when PKs, FKs, and timestamps are named the same way everywhere. True, and the convention enabling it exists only as long as someone is actively keeping it enforced.&lt;/p&gt;
&lt;p&gt;A migration adding &lt;code&gt;CustomerReference INT&lt;/code&gt; in a codebase where everything else is &lt;code&gt;customer_id BIGINT&lt;/code&gt; gets flagged when conventions are consistent. True, and whether it actually gets flagged depends on whether the reviewer remembers the rule or a linter is enforcing it.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;JOIN users ON orders.user_id = users.id&lt;/code&gt; works without a lookup when the convention is &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt;. True, and the query is right only because every prior migration followed the rule, which is only the case if something kept them on track.&lt;/p&gt;
&lt;p&gt;The pattern: every human benefit is downstream of enforcement. A rule that exists only because the current team agreed to it lasts exactly as long as that team does. People change jobs, preferences evolve, new hires bring their own instincts. Within a few quarters of turnover, a human-only convention is gone, and so is the benefit.&lt;/p&gt;
&lt;p&gt;The reasons worth picking a convention are the reasons a machine can enforce it.&lt;/p&gt;
&lt;h2 id="why-it-matters-for-automation"&gt;Why it matters for automation
&lt;/h2&gt;&lt;p&gt;Automation is the only thing that holds a convention over time. A linter fails the build when &lt;code&gt;snake_case&lt;/code&gt; becomes &lt;code&gt;camelCase&lt;/code&gt; and keeps failing until someone addresses it; a team agreement doesn&amp;rsquo;t. The tools below are both the enforcement mechanisms and, by that logic, the only reasons a convention is worth picking in the first place. If none of them apply to your stack, the convention probably isn&amp;rsquo;t worth the debate.&lt;/p&gt;
&lt;p&gt;Every tool that touches the schema reads conventions implicitly. When conventions are consistent, the tool works without configuration. When they&amp;rsquo;re not, someone has to tell the tool how to handle each exception. Usually in a config file nobody maintains.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ORMs rely on naming rules.&lt;/strong&gt; ActiveRecord assumes a table named &lt;code&gt;users&lt;/code&gt; has a primary key &lt;code&gt;id&lt;/code&gt; and that a &lt;code&gt;user_id&lt;/code&gt; column is the foreign key. Deviate and you write explicit mappings. Every non-standard table adds a line of configuration; every &lt;code&gt;belongs_to :author, foreign_key: :creator_ref&lt;/code&gt; is convention drift showing up as code. Other ORMs are more explicit but still benefit from predictable column names: autogeneration works, inference works, magic methods work.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Code generators produce better output.&lt;/strong&gt; &lt;a class="link" href="https://sqlc.dev/" target="_blank" rel="noopener"
 &gt;sqlc&lt;/a&gt;, Prisma, jOOQ, and similar tools read schema metadata and emit type-safe client code. Consistent naming means the generated output looks like hand-written code. Inconsistent naming produces &lt;code&gt;getCustomerReferenceByUserId()&lt;/code&gt; sitting next to &lt;code&gt;getOrderByUserId()&lt;/code&gt;, same concept, different shape, every caller has to remember the difference.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Migration tools depend on mandatory columns.&lt;/strong&gt; Frameworks that manage &lt;code&gt;created_at&lt;/code&gt; / &lt;code&gt;updated_at&lt;/code&gt; automatically assume every table has them. Tables that omit these columns silently break the assumption: inserts work, updates work, but the &amp;ldquo;last modified&amp;rdquo; display in an admin UI shows &lt;code&gt;null&lt;/code&gt; for some tables and not others.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Deployment pipelines assume a consistent migration shape.&lt;/strong&gt; Migration runners that execute schema changes as part of CI/CD (Flyway, Liquibase, Alembic, Atlas, skeema) rely on migration files following a predictable naming and ordering convention, up/down scripts that mirror each other, and tables that don&amp;rsquo;t need per-case special-handling. Zero-downtime patterns like expand-and-contract assume &lt;code&gt;updated_at&lt;/code&gt; exists for cache invalidation, that new columns are nullable or have defaults so old and new application versions can both write the table, and that soft-delete markers are consistent so rolling deploys across mixed versions don&amp;rsquo;t resurrect rows one version thought were gone. Every convention that drifts turns a deploy playbook into a per-table checklist, and the checklists are what get skipped under time pressure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schema diffing and drift detection depend on consistent shape.&lt;/strong&gt; Tools like &lt;a class="link" href="https://atlasgo.io/" target="_blank" rel="noopener"
 &gt;Atlas&lt;/a&gt; and &lt;a class="link" href="https://www.skeema.io/" target="_blank" rel="noopener"
 &gt;skeema&lt;/a&gt; compare the desired schema (in version control) to the actual state of each environment and generate the migration to reconcile them. They work well when naming, types, and mandatory columns are uniform, and produce noisy diffs, false positives, and hand-maintained exception lists when they aren&amp;rsquo;t. Environment parity between dev, staging, and prod degrades the same way: the drift the team never notices becomes the one that breaks a deploy at the worst time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schema linters only work if there&amp;rsquo;s a rule to check.&lt;/strong&gt; &lt;a class="link" href="https://sqlfluff.com/" target="_blank" rel="noopener"
 &gt;SQLFluff&lt;/a&gt;, &lt;a class="link" href="https://github.com/quarylabs/sqruff" target="_blank" rel="noopener"
 &gt;sqruff&lt;/a&gt;, and similar tools can enforce naming conventions, require certain columns on new tables, reject forbidden types, and flag style issues. But the lint rule has to match the team&amp;rsquo;s convention. No convention, no rule. No rule, no enforcement.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Documentation generators&lt;/strong&gt; like &lt;a class="link" href="https://github.com/k1LoW/tbls" target="_blank" rel="noopener"
 &gt;tbls&lt;/a&gt; and &lt;a class="link" href="https://schemaspy.org/" target="_blank" rel="noopener"
 &gt;SchemaSpy&lt;/a&gt; produce browsable schema docs straight from the catalog. Consistent conventions make the generated output navigable. Inconsistent ones make it look like a dump.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schema-reading LLMs and RAG pipelines&lt;/strong&gt; have joined the same list. Copilot, MCP-backed agents, text-to-SQL tools, and retrieval-augmented coding systems pull column names and types from &lt;code&gt;information_schema&lt;/code&gt; and pattern-match them against natural-language questions. When one table uses &lt;code&gt;createdAt&lt;/code&gt;, another uses &lt;code&gt;created_date&lt;/code&gt;, and a third uses &lt;code&gt;date_created&lt;/code&gt;, the model either generalizes from the most-frequent variant and gets the other two wrong, or hedges and produces verbose conditional SQL. Uniform naming lets the model carry an assumption across tables without re-checking the catalog for every column; the accuracy gains from clean conventions stack on top of the 27% lift studies attribute to column comments alone. Conventions that were about making humans and codegen tools agree turn out to matter just as much for the machine-reading layer.&lt;/p&gt;
&lt;p&gt;The common thread: tools treat conventions as a contract. When the contract holds, tools work. When it doesn&amp;rsquo;t, tools either break or force the team to maintain exceptions forever.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The contract is implicit&lt;/strong&gt;
 &lt;div&gt;Nobody writes down that &lt;code&gt;created_at&lt;/code&gt; must be a &lt;code&gt;TIMESTAMPTZ&lt;/code&gt; or that FKs must be named &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt;; the tooling silently starts expecting it. The moment a table violates the expectation, every tool built on it starts producing surprises. Conventions are a contract whether or not anyone acknowledges them, and the tools are the ones keeping score.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="the-menu-pick-what-automation-expects"&gt;The menu: pick what automation expects
&lt;/h2&gt;&lt;p&gt;Each decision below matters only if something in your stack cares about it. The notes below lean on what tools typically expect. Pick the option that matches your automation. If nothing in your stack cares either way, skip the decision; it won&amp;rsquo;t survive the next round of team change regardless of which side &amp;ldquo;won&amp;rdquo; the debate.&lt;/p&gt;
&lt;h3 id="naming-snake-vs-camel"&gt;Naming: snake vs camel
&lt;/h3&gt;&lt;p&gt;&lt;code&gt;snake_case&lt;/code&gt; is the idiomatic choice for PostgreSQL and MySQL. Unquoted identifiers in PostgreSQL are case-folded to lowercase, so &lt;code&gt;created_at&lt;/code&gt; and &lt;code&gt;createdAt&lt;/code&gt; both become &lt;code&gt;createdat&lt;/code&gt; unless one is quoted, which means mixed-case names force every query to quote the column. &lt;code&gt;camelCase&lt;/code&gt; works if the team is disciplined about quoting, but most teams aren&amp;rsquo;t. Pick &lt;code&gt;snake_case&lt;/code&gt; unless there&amp;rsquo;s a specific reason not to.&lt;/p&gt;
&lt;h3 id="table-names-singular-or-plural"&gt;Table names: singular or plural
&lt;/h3&gt;&lt;p&gt;Both work. Rails and Django default to plural (&lt;code&gt;users&lt;/code&gt;). &lt;code&gt;CREATE TABLE user&lt;/code&gt; will actually fail in PostgreSQL because &lt;code&gt;user&lt;/code&gt; is a reserved word, which is an argument for plural. Singular reads cleaner in joins (&lt;code&gt;user.id&lt;/code&gt; feels like &amp;ldquo;the user&amp;rsquo;s id&amp;rdquo;). This is the smallest decision on the list in terms of consequences. The real requirement is that whatever you pick, you use it everywhere.&lt;/p&gt;
&lt;h3 id="primary-keys-id-vs-table_id"&gt;Primary keys: &lt;code&gt;id&lt;/code&gt; vs &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt;
&lt;/h3&gt;&lt;p&gt;Bare &lt;code&gt;id&lt;/code&gt; is shorter and matches the default of most ORMs. It also creates a subtle hazard: &lt;code&gt;table_a.id = table_b.id&lt;/code&gt; is syntactically valid SQL that silently returns wrong results. &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt; (so &lt;code&gt;user_id&lt;/code&gt; on the &lt;code&gt;users&lt;/code&gt; table) makes cross-table joins impossible to write accidentally, because the identifier tells you which table the ID belongs to.&lt;/p&gt;
&lt;p&gt;The trade-off is that ORM defaults expect &lt;code&gt;id&lt;/code&gt;, so using &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt; means configuring every model. For teams that rely heavily on an ORM&amp;rsquo;s conventions, staying with &lt;code&gt;id&lt;/code&gt; is pragmatic. For teams with more ad-hoc SQL, &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt; pays off.&lt;/p&gt;
&lt;h3 id="foreign-key-naming"&gt;Foreign key naming
&lt;/h3&gt;&lt;p&gt;&lt;code&gt;user_id&lt;/code&gt; referencing &lt;code&gt;users.id&lt;/code&gt; is the convention most tools expect. Ad-hoc names like &lt;code&gt;owner&lt;/code&gt;, &lt;code&gt;creator&lt;/code&gt;, &lt;code&gt;assigned_to&lt;/code&gt;, &lt;code&gt;ref_id&lt;/code&gt; are sometimes necessary (multiple FKs to the same table need different names) but should be explicit about what they reference, either in the column name (&lt;code&gt;owner_user_id&lt;/code&gt;) or in a schema comment. A column named &lt;code&gt;owner&lt;/code&gt; with no comment and no FK is a question nobody can answer from the schema alone.&lt;/p&gt;
&lt;h3 id="mandatory-columns"&gt;Mandatory columns
&lt;/h3&gt;&lt;p&gt;Decide which columns every table must have. Common choices:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()&lt;/code&gt;. Row creation time.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()&lt;/code&gt;. Last modification, driven by a trigger or application logic.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;created_by&lt;/code&gt; / &lt;code&gt;updated_by&lt;/code&gt;. Audit fields, if the team needs them.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;deleted_at TIMESTAMPTZ&lt;/code&gt;. Soft-delete marker.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Partial adoption is worse than none&lt;/strong&gt;
 &lt;div&gt;If 80% of tables have &lt;code&gt;deleted_at&lt;/code&gt; and 20% don&amp;rsquo;t, every query has to remember which tables to filter and which not to. The queries that forget silently return soft-deleted rows from some tables and not others. Pick a rule (&amp;ldquo;every table has &lt;code&gt;created_at&lt;/code&gt;, &lt;code&gt;updated_at&lt;/code&gt;; soft-delete tables have &lt;code&gt;deleted_at&lt;/code&gt;&amp;rdquo;) and apply it uniformly.&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id="status-and-enum-patterns"&gt;Status and enum patterns
&lt;/h3&gt;&lt;p&gt;Three common strategies, each with trade-offs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;INT with documented values.&lt;/strong&gt; &lt;code&gt;status TINYINT NOT NULL COMMENT '1=active, 2=paused, 3=cancelled'&lt;/code&gt;. Compact, fast, relies on comments for semantics. Works across engines.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CHECK constraint.&lt;/strong&gt; &lt;code&gt;status VARCHAR(20) CHECK (status IN ('active', 'paused', 'cancelled'))&lt;/code&gt;. Self-documenting in the DDL, slightly larger storage, human-readable in query results.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Native ENUM.&lt;/strong&gt; PostgreSQL has first-class ENUM types, MySQL has &lt;code&gt;ENUM(...)&lt;/code&gt;. Compact and typed, but changing the set requires a schema migration; in PostgreSQL, removing a value is genuinely hard.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Any of these is fine. Mixing them (one table uses INT, another uses CHECK, a third uses ENUM) is what creates the problem. Every query that aggregates across tables has to handle three value formats.&lt;/p&gt;
&lt;h3 id="boolean-prefixes"&gt;Boolean prefixes
&lt;/h3&gt;&lt;p&gt;&lt;code&gt;is_active&lt;/code&gt;, &lt;code&gt;has_completed&lt;/code&gt;, &lt;code&gt;can_edit&lt;/code&gt; make filter expressions self-documenting: &lt;code&gt;WHERE is_active AND NOT is_deleted&lt;/code&gt;. Bare names like &lt;code&gt;active&lt;/code&gt; or &lt;code&gt;completed&lt;/code&gt; create ambiguity in review. Is this column a flag or a timestamp? Adjective or verb? Prefixing eliminates the ambiguity at no runtime cost.&lt;/p&gt;
&lt;h3 id="timestamp-types"&gt;Timestamp types
&lt;/h3&gt;&lt;p&gt;The choice matters more than the name. &lt;code&gt;TIMESTAMP&lt;/code&gt; in MySQL auto-converts between UTC and the session timezone, which is usually not what you want. &lt;code&gt;DATETIME&lt;/code&gt; stores the literal value with no timezone awareness. PostgreSQL&amp;rsquo;s &lt;code&gt;TIMESTAMPTZ&lt;/code&gt; stores UTC with automatic conversion on input and output, the most forgiving option for most applications.&lt;/p&gt;
&lt;p&gt;Mixing types across related tables is where silent timezone bugs come from. A &lt;code&gt;created_at TIMESTAMPTZ&lt;/code&gt; on one table joined to a &lt;code&gt;DATETIME&lt;/code&gt; on another will either implicit-cast or mismatch, depending on engine and version. Pick one per engine and apply it everywhere.&lt;/p&gt;
&lt;h3 id="character-sets-and-collations"&gt;Character sets and collations
&lt;/h3&gt;&lt;p&gt;&lt;code&gt;utf8mb4&lt;/code&gt; in MySQL, &lt;code&gt;UTF-8&lt;/code&gt; in PostgreSQL. Anything else in 2026 is a legacy holdover. The subtle hazard: mixing charsets across columns causes joins between text columns to fail silently or return wrong results. PostgreSQL is stricter about this; MySQL is more permissive and more dangerous because of it.&lt;/p&gt;
&lt;h2 id="conventions-beyond-the-schema"&gt;Conventions beyond the schema
&lt;/h2&gt;&lt;p&gt;Schema conventions usually stop at the DDL, but the automation layer around the database depends on naming decisions that live outside it: secrets, endpoints, users, roles, hostnames, backup files, environment variables. Those names show up in Terraform modules, Vault paths, Kubernetes resources, IAM policies, service-discovery records, monitoring dashboards, and every deploy pipeline. When they&amp;rsquo;re consistent, the infrastructure is self-describing and IaC modules stay generic. When they aren&amp;rsquo;t, every piece of automation grows a special case.&lt;/p&gt;
&lt;p&gt;Common places this shows up:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Secret names.&lt;/strong&gt; &lt;code&gt;prod/db/orders/primary/password&lt;/code&gt; vs &lt;code&gt;prod-orders-db-pw&lt;/code&gt; vs &lt;code&gt;orders_prod_password&lt;/code&gt;. A clear prefix/suffix pattern lets secret rotation scripts, IAM scopes (&lt;code&gt;arn:aws:secretsmanager:*:*:secret:prod/db/*&lt;/code&gt;), and environment-promotion automation use wildcards instead of hardcoded lists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hostnames and endpoints.&lt;/strong&gt; &lt;code&gt;db-orders-rw.internal&lt;/code&gt; and &lt;code&gt;db-orders-ro.internal&lt;/code&gt; for reader/writer splits, &lt;code&gt;db-orders-primary-0.us-east-1&lt;/code&gt; for cluster node addressing. Consistent patterns mean DR runbooks, connection pools, and failover scripts can resolve endpoints by transforming a base name rather than reading from config.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database users and roles.&lt;/strong&gt; &lt;code&gt;app_orders_rw&lt;/code&gt;, &lt;code&gt;app_orders_ro&lt;/code&gt;, &lt;code&gt;migration_bot&lt;/code&gt;, &lt;code&gt;readonly_analytics&lt;/code&gt;. The role name should say what it can do. Teams without a convention end up with &lt;code&gt;svc_user_42&lt;/code&gt;, &lt;code&gt;rails&lt;/code&gt;, &lt;code&gt;monitoring&lt;/code&gt;, and nobody can audit privileges without a spreadsheet.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database names.&lt;/strong&gt; &lt;code&gt;orders_prod&lt;/code&gt; vs &lt;code&gt;prod_orders&lt;/code&gt; vs &lt;code&gt;orders-production&lt;/code&gt;. Consistent environment placement (always suffix or always prefix) means wildcard grants, backup pattern matching, and cross-environment queries stay simple.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Environment variables.&lt;/strong&gt; &lt;code&gt;DB_ORDERS_HOST&lt;/code&gt;, &lt;code&gt;DB_ORDERS_USER&lt;/code&gt;, &lt;code&gt;DB_ORDERS_PASSWORD_SECRET&lt;/code&gt;. A per-service naming convention lets config loaders and IaC modules generate the full variable set from a single identifier.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Backup and snapshot names.&lt;/strong&gt; &lt;code&gt;orders-prod-20260420-0000&lt;/code&gt; vs &lt;code&gt;backup_orders_20260420&lt;/code&gt;. Retention jobs, restore runbooks, and compliance audits all read these names by pattern.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These aren&amp;rsquo;t schema conventions in the strict sense; they&amp;rsquo;re operational conventions that happen to be tied to the schema. They follow the same rules: pick a pattern, apply it everywhere, document it where the infrastructure code lives, and enforce it in the IaC linter (&lt;code&gt;tflint&lt;/code&gt;, &lt;code&gt;checkov&lt;/code&gt;) or the Kubernetes admission controller so new resources can&amp;rsquo;t be named off-pattern.&lt;/p&gt;
&lt;p&gt;The failure mode is the same as inside the schema. A team with three secret-naming patterns needs a custom script per resource. A team with three hostname patterns runs DR runbooks twice as long as they should be. Operational conventions have the same compounding cost as schema conventions, in a different layer; the tooling to enforce them is different (IaC linters instead of SQLFluff), but the discipline is identical.&lt;/p&gt;
&lt;h2 id="enforcement-conventions-without-enforcement-decay"&gt;Enforcement: conventions without enforcement decay
&lt;/h2&gt;&lt;p&gt;Written conventions that nobody enforces last until the next person who didn&amp;rsquo;t read the doc. The only conventions that hold over years are the ones CI checks.&lt;/p&gt;
&lt;h3 id="schema-linters"&gt;Schema linters
&lt;/h3&gt;&lt;p&gt;&lt;a class="link" href="https://sqlfluff.com/" target="_blank" rel="noopener"
 &gt;SQLFluff&lt;/a&gt; is the most popular for PostgreSQL and MySQL. It runs on migration files in CI and can enforce:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Naming rules (&lt;code&gt;snake_case&lt;/code&gt; only, specific prefixes/suffixes).&lt;/li&gt;
&lt;li&gt;Required columns on &lt;code&gt;CREATE TABLE&lt;/code&gt; (every table must have &lt;code&gt;created_at&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Forbidden types (reject &lt;code&gt;TIMESTAMP&lt;/code&gt; in favor of &lt;code&gt;TIMESTAMPTZ&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Style (trailing commas, keyword casing, indentation).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The alternative is a custom linter, a script that parses migration files and checks them against a ruleset. More work to build but more flexible if the rules are unusual. Teams with strong opinions often end up here.&lt;/p&gt;
&lt;h3 id="ci-checks-on-the-schema-itself"&gt;CI checks on the schema itself
&lt;/h3&gt;&lt;p&gt;Beyond linting migration files, a CI job can introspect the database after migrations are applied and assert properties of the final schema:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Every table in the application schema has created_at
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;columns&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;public&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;HAVING&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COUNT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;FILTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;column_name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;created_at&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;If the result is non-empty, fail the build. This catches the migration that adds a new table without the mandatory columns, the case a file-level linter can miss if the &lt;code&gt;CREATE TABLE&lt;/code&gt; was split across migrations.&lt;/p&gt;
&lt;p&gt;Other useful assertions:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- No table uses TIMESTAMP without timezone
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;column_name&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;columns&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;data_type&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;timestamp without time zone&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;table_schema&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;public&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Every FK column has an index
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- (expensive to query but worth running on schedule)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Introspection-based checks run against the shape of the schema after migrations are applied; they catch drift the file-level linter can&amp;rsquo;t see.&lt;/p&gt;
&lt;h3 id="pre-commit-hooks"&gt;Pre-commit hooks
&lt;/h3&gt;&lt;p&gt;Developer-machine enforcement: running &lt;code&gt;sqlfluff&lt;/code&gt; on staged migration files before commit. Faster feedback than CI, but only works if every developer has the hook installed. Treat pre-commit hooks as a developer experience improvement, not as the real gate. CI is the gate.&lt;/p&gt;
&lt;h3 id="codeowners-on-migration-directories"&gt;CODEOWNERS on migration directories
&lt;/h3&gt;&lt;p&gt;Putting a small group of owners on &lt;code&gt;migrations/&lt;/code&gt; forces review by someone who understands the conventions. This is a human check, not a mechanical one, but it catches things the linter can&amp;rsquo;t (&amp;ldquo;this new table has all the right columns but the design is wrong&amp;rdquo;). The owner doesn&amp;rsquo;t have to be one person; a rotating review responsibility works.&lt;/p&gt;
&lt;h3 id="review-templates"&gt;Review templates
&lt;/h3&gt;&lt;p&gt;A PR template that includes a checklist for schema changes (&amp;ldquo;does this follow the naming convention? does it include mandatory columns? are the types consistent with existing tables?&amp;rdquo;) nudges the author to check before review. The cost is zero; the benefit is that most issues get caught before they reach a reviewer.&lt;/p&gt;
&lt;h3 id="scope-strict-for-new-lenient-for-legacy"&gt;Scope: strict for new, lenient for legacy
&lt;/h3&gt;&lt;p&gt;The enforcement question that derails most teams: do existing tables have to meet the convention? Trying to retrofit decades of legacy is an impossible project; requiring only new tables to meet the convention is achievable. The practical pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;New tables.&lt;/strong&gt; Linter is strict. No exceptions without a documented reason.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Existing tables.&lt;/strong&gt; Grandfathered. Linter skips them or only checks newly-added columns.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Legacy migrations.&lt;/strong&gt; An explicit backlog, prioritized by frequency of use and onboarding pain.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This splits the problem into &amp;ldquo;hold the line on new work&amp;rdquo; and &amp;ldquo;improve legacy opportunistically.&amp;rdquo; Both are manageable. Trying to do both at once isn&amp;rsquo;t.&lt;/p&gt;
&lt;h2 id="the-hardest-part-changing-conventions-without-creating-a-new-one"&gt;The hardest part: changing conventions without creating a new one
&lt;/h2&gt;&lt;p&gt;Conventions decay not because they were bad, but because they changed faster than the team could propagate the change. The result isn&amp;rsquo;t &amp;ldquo;the new convention&amp;rdquo;. It&amp;rsquo;s a schema with three coexisting conventions, none of which applies everywhere.&lt;/p&gt;
&lt;p&gt;The discipline is straightforward, even if it&amp;rsquo;s not always followed.&lt;/p&gt;
&lt;h3 id="write-the-convention-down"&gt;Write the convention down
&lt;/h3&gt;&lt;p&gt;Before enforcement, before any migration, there has to be a single authoritative document: a &lt;code&gt;SCHEMA-CONVENTIONS.md&lt;/code&gt; in the repo, or a runbook, or an RFC. Not a Slack thread, not tribal knowledge. Something a new engineer can read and apply.&lt;/p&gt;
&lt;p&gt;The doc is short by design: a page or two, not a book. It answers &amp;ldquo;what naming convention do we use?&amp;rdquo; and &amp;ldquo;what columns does every table need?&amp;rdquo; and &amp;ldquo;which timestamp type?&amp;rdquo;. It doesn&amp;rsquo;t try to teach relational design. Short docs get read; long ones don&amp;rsquo;t.&lt;/p&gt;
&lt;h3 id="use-a-lightweight-rfc-process-for-changes"&gt;Use a lightweight RFC process for changes
&lt;/h3&gt;&lt;p&gt;When someone wants to change a convention (switch from &lt;code&gt;id&lt;/code&gt; to &lt;code&gt;&amp;lt;table&amp;gt;_id&lt;/code&gt;, add &lt;code&gt;updated_by&lt;/code&gt; as a mandatory column, move from INT to UUID primary keys) it goes through a written proposal:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What&amp;rsquo;s changing and why.&lt;/li&gt;
&lt;li&gt;Impact on existing tables (migrate all, grandfather, or cutover by date).&lt;/li&gt;
&lt;li&gt;Impact on tools, ORMs, dashboards, and downstream consumers.&lt;/li&gt;
&lt;li&gt;Who decides (single decision-maker or review board).&lt;/li&gt;
&lt;li&gt;Explicit cutover date if changing for new work only.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The RFC doesn&amp;rsquo;t have to be heavyweight. A paragraph in a shared doc, reviewed by two or three people, approved by a named owner. The value isn&amp;rsquo;t the document. It&amp;rsquo;s the forcing function that prevents conventions from changing by PR comment.&lt;/p&gt;
&lt;h3 id="decide-migrate-grandfather-or-both"&gt;Decide: migrate, grandfather, or both
&lt;/h3&gt;&lt;p&gt;Three options, each with a different risk profile:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Migrate everything.&lt;/strong&gt; Rename columns across the schema, update every query, every ORM model, every dashboard. This is the clean option and almost never the practical one. Retroactive renaming breaks downstream consumers the team may not even know exist: analytics jobs, exports, integration partners, cached query plans.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Grandfather legacy, enforce on new.&lt;/strong&gt; Old tables stay as-is; new tables follow the new rule. The schema ends up with two conventions coexisting, but it&amp;rsquo;s predictable: &amp;ldquo;tables before this date use X, tables after use Y.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cutover with a migration window.&lt;/strong&gt; Pick a date, migrate the highest-traffic or highest-visibility tables before the date, grandfather the rest, close out the long tail opportunistically.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The grandfather option is the most common in practice because it respects the reality that the schema is a shared resource nobody fully owns. Write the decision down (&amp;ldquo;before 2025-Q3, tables used camelCase; after, snake_case&amp;rdquo;) so future engineers know the split exists and isn&amp;rsquo;t a bug.&lt;/p&gt;
&lt;h3 id="the-two-generation-rule"&gt;The two-generation rule
&lt;/h3&gt;&lt;div class="note-box"&gt;
 &lt;strong&gt;Two is the limit&lt;/strong&gt;
 &lt;div&gt;One convention is best. Two coexisting conventions is survivable - new engineers can be told &amp;ldquo;look at the table&amp;rsquo;s creation date.&amp;rdquo; Three or more is where schemas become unreviewable. Any proposal to change a convention needs to answer: &amp;ldquo;are we ending up with two generations, or a third?&amp;rdquo; A third generation is a forcing function to finish migrating the first one first, not to introduce a new one.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This is a heuristic, not a hard rule, but it&amp;rsquo;s a useful test. When a proposed change would create a third convention without a plan to eliminate one of the existing two, the change probably isn&amp;rsquo;t worth it.&lt;/p&gt;
&lt;h2 id="when-to-accept-legacy-drift"&gt;When to accept legacy drift
&lt;/h2&gt;&lt;p&gt;Not every legacy convention is worth fixing. The calculation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;How often does the old convention cause bugs?&lt;/strong&gt; Column names nobody can remember, types that force implicit casts, missing mandatory columns that break tooling. Real costs, worth migrating.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How often is the table touched?&lt;/strong&gt; A table used by ten queries a day is different from one used by ten thousand. Migration risk scales with usage.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What breaks downstream?&lt;/strong&gt; ORM models, dashboards, exports, cached plans, monitoring. Every consumer of the table name or column name has to update. If the count is unknown, it&amp;rsquo;s higher than you think.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is there a cheap alternative?&lt;/strong&gt; A &lt;code&gt;VIEW&lt;/code&gt; that exposes the table under the new convention, while the underlying table keeps its legacy name, can bridge the gap without a full migration.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The honest answer is often &amp;ldquo;leave it alone and document why.&amp;rdquo; A comment in the schema, or a note in the conventions doc, is cheaper than a migration and accomplishes the main goal: making the inconsistency visible and intentional.&lt;/p&gt;
&lt;h2 id="trade-offs"&gt;Trade-offs
&lt;/h2&gt;&lt;p&gt;Conventions have a cost. A rule that doesn&amp;rsquo;t serve automation is noise. It takes space in the conventions doc, invites bikeshedding in review, and adds nothing to the schema&amp;rsquo;s consistency over time, because there&amp;rsquo;s nothing to keep it from decaying the moment the people who cared move on. The heuristic: if no tool fails when the rule is violated, the rule doesn&amp;rsquo;t need to exist.&lt;/p&gt;
&lt;p&gt;Over-specifying is the second failure mode. A team with thirty linter rules will find a way around them or ignore them. Rules that block common, legitimate cases get bypassed with &lt;code&gt;-- noqa&lt;/code&gt; comments until the linter stops being a gate.&lt;/p&gt;
&lt;p&gt;The lightweight approach:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A small set of rules, each one tied to a specific tool that cares (naming, mandatory columns, forbidden types).&lt;/li&gt;
&lt;li&gt;A larger set of advisory warnings, not blockers.&lt;/li&gt;
&lt;li&gt;A clear escape hatch for exceptions, with the exception documented.&lt;/li&gt;
&lt;li&gt;Periodic review. Rules that fire too often are wrong; rules that never fire are noise.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Strict conventions are a feature up to the point where the enforcement matches the rule count. Beyond that, they become a tax on every change. The right level is the smallest set automation will actually enforce without constant arguments.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;The useful question is what your automation needs, and whether a machine can enforce it. If yes, pick the convention your automation needs and wire it into CI. If no, skip the decision; debating aesthetics in the absence of enforcement produces nothing that will still be true a year from now. People change, teams turn over, preferences drift. A convention enforced by a linter doesn&amp;rsquo;t care who wrote the migration; a convention enforced by &amp;ldquo;we agreed last quarter&amp;rdquo; does.&lt;/p&gt;
&lt;p&gt;The schemas that age well are the ones where the only surviving conventions are ones a linter, ORM, migration runner, or IaC module is actively enforcing. &lt;a class="link" href="https://explainanalyze.com/p/comment-your-schema/" &gt;Column comments&lt;/a&gt; are the one exception worth making, and only because a missing comment is itself lintable. Everything else (bikeshed questions about singular vs. plural, religious debates about column ordering) drifts the moment the people who cared stop working there. That&amp;rsquo;s the predictable result of anchoring a rule to something as ephemeral as a team&amp;rsquo;s current preference.&lt;/p&gt;</description></item><item><title>Where Business Logic Lives - Database vs. Application</title><link>https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/</link><pubDate>Wed, 19 Mar 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/where-business-logic-lives-database-vs.-application/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Where Business Logic Lives - Database vs. Application" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Keep the database narrow: &lt;code&gt;NOT NULL&lt;/code&gt;, &lt;code&gt;UNIQUE&lt;/code&gt;, &lt;code&gt;FK&lt;/code&gt; within a service, simple &lt;code&gt;CHECK&lt;/code&gt; for per-row invariants, generated columns for stable derived values. Put everything else (orchestration, computation, rules that change weekly, anything crossing services) in an application-layer library every writer uses. &amp;ldquo;Dumb database&amp;rdquo; is half right: dumb across service boundaries, narrowly smart within one.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;code&gt;amount &amp;gt;= 0&lt;/code&gt; lives in three places. A &lt;code&gt;CHECK&lt;/code&gt; on the column, a Pydantic validator in the API model, a guard in the order-creation service. Added in different quarters by different teams. Out of sync since GDPR forced a change to the validator that nobody propagated to the constraint. The migration tightening the &lt;code&gt;CHECK&lt;/code&gt; to match fails on 4,000 rows the application thought were fine.&lt;/p&gt;
&lt;p&gt;This is the default state of any rule about valid data, eventually. It lives in more than one place. The places drift. The reflex answer, &amp;ldquo;both layers for safety,&amp;rdquo; is what produced the drift in the first place; &amp;ldquo;application-only because we have microservices&amp;rdquo; is the same answer applied to a different fashion cycle. Neither is a decision, both are defaults. The useful question is what each layer can enforce, what it costs, and how often the rule will change. Four axes do the work: scope, cadence, cost, and write-path count.&lt;/p&gt;
&lt;h2 id="the-short-history-of-the-dumb-database-position"&gt;The short history of the &amp;ldquo;dumb database&amp;rdquo; position
&lt;/h2&gt;&lt;p&gt;The microservices canon and the cloud databases built to support it have already answered one half of this question.&lt;/p&gt;
&lt;p&gt;Chris Richardson&amp;rsquo;s &lt;a class="link" href="https://microservices.io/patterns/data/database-per-service.html" target="_blank" rel="noopener"
 &gt;database-per-service pattern&lt;/a&gt; rules out cross-service foreign keys as a design choice: each service owns its schema and no one else touches it. &lt;a class="link" href="https://martinfowler.com/articles/microservices.html" target="_blank" rel="noopener"
 &gt;Fowler and Lewis&amp;rsquo;s &amp;ldquo;Microservices&amp;rdquo;&lt;/a&gt; article coined &amp;ldquo;smart endpoints and dumb pipes&amp;rdquo; and &amp;ldquo;decentralized data management&amp;rdquo;. Neither the middleware nor a shared database holds cross-service logic. Fowler calls the alternative, integration through a shared database, &lt;a class="link" href="https://martinfowler.com/bliki/IntegrationDatabase.html" target="_blank" rel="noopener"
 &gt;the canonical encapsulation breach&lt;/a&gt;. Vaughn Vernon&amp;rsquo;s DDD work puts the consistency boundary at the &lt;a class="link" href="https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf" target="_blank" rel="noopener"
 &gt;aggregate&lt;/a&gt;, enforced in process, not in the DBMS.&lt;/p&gt;
&lt;p&gt;The storage layer follows suit. Google Spanner &lt;a class="link" href="https://cloud.google.com/spanner/docs/reference/standard-sql/stored-procedures" target="_blank" rel="noopener"
 &gt;does not support user-defined stored procedures or triggers&lt;/a&gt;; its docs explicitly say that on migration, &amp;ldquo;business logic implemented by database-level stored procedures and triggers must be moved into the application.&amp;rdquo; DynamoDB has no &lt;code&gt;CHECK&lt;/code&gt;, no foreign keys, no triggers; &lt;a class="link" href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Constraints.html" target="_blank" rel="noopener"
 &gt;integrity is a per-item conditional write&lt;/a&gt;. Cassandra, Bigtable, and &lt;a class="link" href="https://www.uber.com/us/en/blog/schemaless-part-one-mysql-datastore/" target="_blank" rel="noopener"
 &gt;Uber&amp;rsquo;s Schemaless&lt;/a&gt; are the same story. Facebook&amp;rsquo;s &lt;a class="link" href="https://engineering.fb.com/2013/06/25/core-infra/tao-the-power-of-the-graph/" target="_blank" rel="noopener"
 &gt;TAO&lt;/a&gt; keeps the social graph&amp;rsquo;s integrity inside TAO itself; the underlying MySQL shards don&amp;rsquo;t enforce it. Shopify, even inside a Rails monolith, &lt;a class="link" href="https://shopify.engineering/shopify-made-patterns-in-our-rails-apps" target="_blank" rel="noopener"
 &gt;doesn&amp;rsquo;t enforce relationships at the database layer&lt;/a&gt;; foreign keys are maintained only in the model code, a choice driven by their sharding and cell architecture.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s the position the last fifteen years of large-scale engineering has converged on, and it&amp;rsquo;s right in the scope it applies to. Across service boundaries, the database physically can&amp;rsquo;t enforce most cross-cutting rules, the dominant cloud storage engines won&amp;rsquo;t host procs or triggers, and the pattern literature has codified the split.&lt;/p&gt;
&lt;p&gt;The mistake is generalizing from this to &amp;ldquo;the database should be dumb, period.&amp;rdquo; That collapses two different debates into one slogan.&lt;/p&gt;
&lt;h2 id="where-the-position-is-strong-and-where-it-isnt"&gt;Where the position is strong and where it isn&amp;rsquo;t
&lt;/h2&gt;&lt;p&gt;The near-unanimous consensus is about cross-service integrity: FK between services, triggers as integration glue, stored procs as the coordination layer. There the answer is genuinely settled. Application-layer, usually in a shared library, sometimes in an orchestration service.&lt;/p&gt;
&lt;p&gt;The within-service question is different. Inside a single service&amp;rsquo;s private schema, with one team owning the reads and writes, the database still sees every write path the service produces: the normal request path, backfill scripts, admin tools, the occasional DBA command at 2am, the new code path the team added last sprint. Richardson, Fowler, and Vernon don&amp;rsquo;t argue against &lt;code&gt;NOT NULL&lt;/code&gt;, &lt;code&gt;CHECK&lt;/code&gt;, or &lt;code&gt;UNIQUE&lt;/code&gt; inside that boundary. Shopify&amp;rsquo;s position is an outlier driven by sharding operations, not ideology. Yugabyte goes further and &lt;a class="link" href="https://www.yugabyte.com/blog/are-stored-procedures-and-triggers-anti-patterns-in-the-cloud-native-world/" target="_blank" rel="noopener"
 &gt;defends stored procedures and triggers inside a service boundary&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So the real framing: the &amp;ldquo;dumb database&amp;rdquo; position is unanimous across service boundaries and contested within them. The rest of this post is about where the line actually sits within a service. The honest answer is still &amp;ldquo;mostly keep the database lean, but not empty,&amp;rdquo; for reasons that have more to do with deployment cadence and scaling economics than with purity.&lt;/p&gt;
&lt;h2 id="the-four-axes-that-actually-decide-the-split"&gt;The four axes that actually decide the split
&lt;/h2&gt;&lt;p&gt;The rule-by-rule question is a balance across four properties of the system, not a preference between layers.&lt;/p&gt;
&lt;h3 id="1-scope-does-this-rule-cross-service-boundaries"&gt;1. Scope: does this rule cross service boundaries?
&lt;/h3&gt;&lt;p&gt;If the rule spans services, the database can&amp;rsquo;t enforce it. A foreign key into another service&amp;rsquo;s database doesn&amp;rsquo;t exist. A trigger that writes to tables owned by another team isn&amp;rsquo;t compatible with any sane microservices pattern. Cross-service correctness lives in application code, typically in a library that every writing service depends on, or in event-driven compensation (sagas, outbox patterns, eventual-consistency protocols).&lt;/p&gt;
&lt;p&gt;The only databases that let you enforce cross-service rules are ones the pattern literature treats as an anti-pattern on purpose: shared databases with multiple writers.&lt;/p&gt;
&lt;h3 id="2-cadence-how-often-does-this-rule-change"&gt;2. Cadence: how often does this rule change?
&lt;/h3&gt;&lt;p&gt;Application code deploys in minutes. Schema migrations deploy on a migration window, with expand-and-contract dances, &lt;code&gt;NOT VALID&lt;/code&gt; + &lt;code&gt;VALIDATE&lt;/code&gt; phases, and careful ordering across rolling deploys. A rule that lives in the database inherits the database&amp;rsquo;s deployment cadence.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s fine for rules that change annually or never: &amp;ldquo;email column is not null&amp;rdquo;, &amp;ldquo;amount is non-negative&amp;rdquo;, &amp;ldquo;status is one of four values for the life of the product&amp;rdquo;. It&amp;rsquo;s painful for rules that change with product experiments: pricing logic, promotion codes, fraud thresholds, discount stacking rules, feature gates. The friction of modifying a &lt;code&gt;CHECK&lt;/code&gt; constraint or a stored procedure for a rule that&amp;rsquo;s going to change again next quarter adds up to &amp;ldquo;this probably shouldn&amp;rsquo;t have been in the database in the first place.&amp;rdquo;&lt;/p&gt;
&lt;h3 id="3-cost-where-can-this-rule-run-cheapest"&gt;3. Cost: where can this rule run cheapest?
&lt;/h3&gt;&lt;p&gt;The application tier scales horizontally. The primary database, for most OLTP workloads, scales vertically until sharding, and sharding is a project, not a tuning knob. Every CPU cycle spent inside the database is a cycle not spent on I/O, lock management, query planning, or serving other requests. A busy primary at 80% CPU doesn&amp;rsquo;t have slack for an additional stored procedure body to run on every write.&lt;/p&gt;
&lt;p&gt;For a simple &lt;code&gt;CHECK (amount &amp;gt;= 0)&lt;/code&gt;, the cost is measured in nanoseconds per write. Irrelevant. For a trigger that recomputes an aggregate on every insert, the cost is a hot row plus whatever the aggregation costs, charged to the most scarce compute tier in the system. For a stored procedure that loops over rows, the cost is full procedure-body CPU on the primary for every call.&lt;/p&gt;
&lt;p&gt;Application code, by contrast, has near-free horizontal scale. Adding a pod is cheap. Adding database CPU is vertical-scaling dollars until you&amp;rsquo;ve run out of instance sizes, then it&amp;rsquo;s a sharding project.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The database is a vertical-scaling tier&lt;/strong&gt;
 &lt;div&gt;Moving computation into the database moves it toward the scaling ceiling. Declarative constraints (&lt;code&gt;CHECK&lt;/code&gt;, &lt;code&gt;FK&lt;/code&gt;, &lt;code&gt;UNIQUE&lt;/code&gt;) are cheap enough to be irrelevant. Triggers that do nontrivial work, procedures that run loops, and anything that touches multiple rows per call eat CPU on the one tier that&amp;rsquo;s hardest to scale. The &amp;ldquo;app can do this magnitudes faster&amp;rdquo; intuition is right when &amp;ldquo;faster&amp;rdquo; is measured in throughput under load, not because a single call is faster, but because the application tier absorbs more of them without a scaling event.&lt;/div&gt;
&lt;/div&gt;

&lt;h3 id="4-write-path-count-how-many-things-write-to-this-schema"&gt;4. Write-path count: how many things write to this schema?
&lt;/h3&gt;&lt;p&gt;One service, one codebase, one team, one ORM writing to a schema the team fully owns: application-layer enforcement works. A shared library is the single choke point; every write goes through it.&lt;/p&gt;
&lt;p&gt;More than one writer (multiple services, admin tools in a different language, backfill scripts maintained by a different team, DBA incident-response SQL) and the library has gaps. Every writer that isn&amp;rsquo;t the library bypasses the validation. The database is the only layer that catches them all, and the cost of catching them is a small set of declarative constraints.&lt;/p&gt;
&lt;p&gt;Two writers isn&amp;rsquo;t a lot. Most systems that survive a few years accumulate more: data-migration jobs for a table split, an admin dashboard written in a different stack than the service, a reporting ETL that occasionally writes aggregates back, a partner integration that writes through a shared DB user.&lt;/p&gt;
&lt;h2 id="the-balance-that-holds-in-practice"&gt;The balance that holds in practice
&lt;/h2&gt;&lt;p&gt;The four axes point at a consistent split. Keep the database narrow and declarative. Put everything else in application code, ideally in a library every writer depends on.&lt;/p&gt;
&lt;p&gt;The narrow set the database earns its keep on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;NOT NULL&lt;/code&gt;, &lt;code&gt;UNIQUE&lt;/code&gt;, &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;&lt;code&gt;FOREIGN KEY&lt;/code&gt;&lt;/a&gt; within a service&amp;rsquo;s private schema.&lt;/li&gt;
&lt;li&gt;Simple &lt;code&gt;CHECK&lt;/code&gt; constraints for per-row invariants: ranges, regex on identifiers, enum membership.&lt;/li&gt;
&lt;li&gt;Generated columns for derived values that are deterministic, stable, and cheap to compute.&lt;/li&gt;
&lt;li&gt;Indexes the application needs for performance (not business logic, but a reminder they belong in the schema, not in code).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These are declarative, near-zero CPU cost per write, cover every write path, and change rarely enough that the schema&amp;rsquo;s deployment cadence isn&amp;rsquo;t a problem. Foreign keys in particular are the canonical within-service example. &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;A post on their own&lt;/a&gt; goes deeper on why application-layer referential integrity consistently loses to database-enforced FKs over time, and that argument is this whole post&amp;rsquo;s framework applied to one specific constraint.&lt;/p&gt;
&lt;p&gt;What stays in application code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Orchestration across multiple statements, services, or external calls.&lt;/li&gt;
&lt;li&gt;Rules that depend on request context, caller identity, time-of-day, or anything outside the row.&lt;/li&gt;
&lt;li&gt;Rules that change with product experiments.&lt;/li&gt;
&lt;li&gt;Rules that span services.&lt;/li&gt;
&lt;li&gt;Computation that would cost measurable database CPU per call.&lt;/li&gt;
&lt;li&gt;Derived values that involve complex business logic or are likely to change.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If there&amp;rsquo;s one writer, a shared library is the single source of truth. If there are multiple writers (or there will be, which is most systems after a year), the library is still valuable but needs a narrow safety net in the database for the invariants that would corrupt data if they slipped.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;The library as the primary, the schema as the safety net&lt;/strong&gt;
 &lt;div&gt;The pattern that works in practice: a validation library (or a rich domain model) owns the full rule set, including validation messages, business logic, cross-field checks, everything the UI and API need. The schema carries only the declarative subset the database can enforce cheaply: &lt;code&gt;NOT NULL&lt;/code&gt;, &lt;code&gt;CHECK&lt;/code&gt;, &lt;code&gt;UNIQUE&lt;/code&gt;, &lt;code&gt;FK&lt;/code&gt;. When the library&amp;rsquo;s rules diverge from the schema&amp;rsquo;s, the database rejects the write. The schema is the safety net, not the primary enforcement path. Violations surface as 500s that flag drift, not silent corruption.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="check-constraints-the-cheap-defensible-middle-ground"&gt;CHECK constraints, the cheap, defensible middle ground
&lt;/h2&gt;&lt;p&gt;Declarative &lt;code&gt;CHECK&lt;/code&gt; constraints are the strongest example of database-side logic that justifies itself on every axis.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;amount_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currency&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;CHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;currency&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;~&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;^[A-Z]{3}$&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;paid&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;shipped&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;refunded&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;placed_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shipped_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shipped_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;OR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shipped_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;placed_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Scope is within the service&amp;rsquo;s schema, applicable. Cadence is annual or never; adding a new status value is a planned migration, not a product-experiment iteration. Cost is near zero, since the planner evaluates the expression once per write and for the operators shown it&amp;rsquo;s nanoseconds. Write-path count covers every path, including the backfill job someone writes next year in a different language.&lt;/p&gt;
&lt;p&gt;The trade-off is real but small. Error messages from a constraint violation are less friendly than a hand-crafted validation message, and adding a &lt;code&gt;CHECK&lt;/code&gt; to a large existing table is a migration project (MySQL rewrites the table; PostgreSQL needs &lt;code&gt;NOT VALID&lt;/code&gt; then &lt;code&gt;VALIDATE CONSTRAINT&lt;/code&gt; to avoid long locks). Both are known problems with known workarounds.&lt;/p&gt;
&lt;p&gt;The common pattern that holds up: application library owns the error message and UX, the database owns the enforcement. The library&amp;rsquo;s check is a fast-path for better errors; the constraint is the gate.&lt;/p&gt;
&lt;h2 id="generated-columns-the-most-underused-declarative-tool"&gt;Generated columns, the most underused declarative tool
&lt;/h2&gt;&lt;p&gt;Generated columns produce a derived value from other columns in the same row. MySQL since 5.7, PostgreSQL since 12. Indexable. Can&amp;rsquo;t be written to. Consistency guaranteed by the engine.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;line_items&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;unit_price_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;unit_price_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GENERATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ALWAYS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;unit_price_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;STORED&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email_normalized&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GENERATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ALWAYS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;LOWER&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;STORED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email_normalized&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;On the four axes: scope is within-service, cadence is stable (the formula is an identity, not a business rule), cost is negligible (pure arithmetic or string operations), write-path count covers everything because every writer gets the same result automatically. Generated columns are the cleanest way to handle derived values that would otherwise be maintained by discipline.&lt;/p&gt;
&lt;p&gt;The cost: the derivation has to be stable. Changing &lt;code&gt;email_normalized = LOWER(email)&lt;/code&gt; to add Unicode normalization is a migration. If the formula is an active business rule, it&amp;rsquo;s the wrong tool.&lt;/p&gt;
&lt;h2 id="triggers-for-schema-migrations-only"&gt;Triggers, for schema migrations only
&lt;/h2&gt;&lt;p&gt;Triggers run procedural code on insert, update, or delete. That&amp;rsquo;s exactly what makes them wrong for implementation logic. A trigger mutates rows the caller didn&amp;rsquo;t ask to change, fires cascades the caller didn&amp;rsquo;t initiate, and makes &amp;ldquo;this update touches one column&amp;rdquo; a lie. The caller&amp;rsquo;s application logs say one thing; the database does something else. When a bug surfaces, the stack trace goes to application code that never ran the hidden logic.&lt;/p&gt;
&lt;p&gt;The usual defenses (&lt;code&gt;updated_at&lt;/code&gt; maintenance, audit logging, soft-delete cascades, counter caches) are all better handled in application code.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;updated_at&lt;/code&gt; belongs in the ORM&amp;rsquo;s model callback, the shared write library, or a middleware that sets it on every persist. Every writer already goes through that path, and adding a timestamp is one line. If backfill scripts or admin tools bypass the library, the fix is to make them use the library, not to paper over the gap with a trigger.&lt;/p&gt;
&lt;p&gt;Audit logs need application context: the user ID, the request ID, the reason, the session, the tenant. A trigger can&amp;rsquo;t see any of that without awkward session-variable tricks that break across connection pools. Write the audit row in application code, next to the logic that knows why the change is happening.&lt;/p&gt;
&lt;p&gt;Soft-delete cascades are business rules. Which child rows get deleted when a parent is soft-deleted, in what order, with what side effects, is a product decision, not a storage concern. Orchestrate it in the application.&lt;/p&gt;
&lt;p&gt;Counter caches via trigger create a hot row where every concurrent write serializes on the same parent lock. Application-side counters, background rollups, or a separate events-with-aggregation pipeline all scale better and leave the hot path free.&lt;/p&gt;
&lt;p&gt;The general principle: application logic should be visible in application code. A trigger that modifies data the application wrote is a hidden side effect, and hidden side effects are an anti-pattern for the same reason global variables are. They make the reachable state of the system larger than the code the reader is looking at.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;The debugging cost is the real cost&lt;/strong&gt;
 &lt;div&gt;When an on-call engineer is looking at a production incident, they read the application code that ran. A trigger that fired three levels down, in a language they may not read fluently, mutating rows nobody expected, is the single biggest source of &amp;ldquo;the code says X, the database did Y&amp;rdquo; incidents. That&amp;rsquo;s not a tooling problem. It&amp;rsquo;s a design choice that can be avoided by not writing triggers as implementation.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This gap widens when an ORM sits between the application and the database. ORMs model what they created (columns and relations) and don&amp;rsquo;t reflect triggers, &lt;code&gt;CHECK&lt;/code&gt; constraints, or generated columns in the model class. A trigger that mutates a row after insert produces data the ORM didn&amp;rsquo;t know would be there, and the in-memory object diverges from the persisted row until someone thinks to reload. &lt;a class="link" href="https://explainanalyze.com/p/orms-are-a-coupling-not-an-abstraction/#database-side-logic-doesnt-round-trip" &gt;The ORM coupling post&lt;/a&gt; covers this failure mode in more depth; triggers are one of the specific shortfalls that show up as &amp;ldquo;the model says one thing, the database did another.&amp;rdquo;&lt;/p&gt;
&lt;h3 id="the-legitimate-case-schema-migrations"&gt;The legitimate case: schema migrations
&lt;/h3&gt;&lt;p&gt;The one place triggers earn their keep is time-bounded, explicit migration work. During an expand-and-contract schema change (renaming a column, splitting a table, changing a type), a trigger can dual-write between the old and new shape so that mixed old-application and new-application traffic both see consistent data. The trigger exists for the duration of the migration window and is dropped once the backfill is complete and all writers are on the new shape.&lt;/p&gt;
&lt;p&gt;This is trigger-as-scaffolding. A temporary mechanism that bridges a specific transition, with a clear removal criterion. It doesn&amp;rsquo;t hide business logic; it handles transitional compatibility between two versions of a schema while the application rolls forward.&lt;/p&gt;
&lt;p&gt;The most common real-world instance of this pattern in MySQL is &lt;a class="link" href="https://docs.percona.com/percona-toolkit/pt-online-schema-change.html" target="_blank" rel="noopener"
 &gt;Percona&amp;rsquo;s &lt;code&gt;pt-online-schema-change&lt;/code&gt;&lt;/a&gt;: it creates a shadow table with the target schema, installs &lt;code&gt;INSERT&lt;/code&gt;/&lt;code&gt;UPDATE&lt;/code&gt;/&lt;code&gt;DELETE&lt;/code&gt; triggers on the original to replicate writes into the shadow while data is copied in chunks, then atomically renames and drops the triggers. The triggers exist for the migration&amp;rsquo;s duration and nothing longer. In PostgreSQL, &lt;a class="link" href="https://github.com/xataio/pgroll" target="_blank" rel="noopener"
 &gt;&lt;code&gt;pgroll&lt;/code&gt;&lt;/a&gt; does the same kind of dual-write-via-trigger for zero-downtime schema changes. Both treat triggers exactly as this section argues they should be treated: time-bounded scaffolding with an explicit tear-down step.&lt;/p&gt;
&lt;p&gt;Worth noting the counter-example. &lt;a class="link" href="https://github.com/github/gh-ost" target="_blank" rel="noopener"
 &gt;GitHub&amp;rsquo;s &lt;code&gt;gh-ost&lt;/code&gt;&lt;/a&gt; performs the same migrations without triggers, reading the binlog instead. Their stated reason is that triggers add synchronous load to the primary during the migration and share its locking fate. That argument is about migration tooling trade-offs, not a defense of triggers in application logic. The conclusion in both camps is the same: triggers outside of migration scaffolding don&amp;rsquo;t earn their keep.&lt;/p&gt;
&lt;p&gt;Everything outside that narrow case (cross-cutting concerns, derived values, audit logs, product rules) belongs in application code where it&amp;rsquo;s visible, testable, and traceable from the same stack trace as the logic that caused the write.&lt;/p&gt;
&lt;h3 id="how-companies-end-up-with-triggers-anyway"&gt;How companies end up with triggers anyway
&lt;/h3&gt;&lt;p&gt;A large share of production databases carrying heavy trigger logic didn&amp;rsquo;t get there by choice. They got there by losing track of the write boundary. The pattern is predictable. A database starts as one service&amp;rsquo;s store. A second team needs the same data and connects directly because it&amp;rsquo;s easier than building an API. A data-warehouse ETL starts writing back aggregates. An analytics job needs a &amp;ldquo;last seen&amp;rdquo; column updated. A partner integration gets a read-write user &amp;ldquo;just for this quarter.&amp;rdquo; Five years later the database has a dozen clients, some inside the company, some not, some on systems nobody actively maintains, and nobody has a full list.&lt;/p&gt;
&lt;p&gt;At that point, asking every writer to go through a shared library stops being possible. The library is only the single source of truth if every writer imports it, and &amp;ldquo;every writer&amp;rdquo; now includes a Java batch job, a Go analytics worker, a legacy PHP admin tool, a vendor ETL, and a spreadsheet someone&amp;rsquo;s been running for years. The company doesn&amp;rsquo;t know where all the calls are coming from, so moving rules into an API layer isn&amp;rsquo;t an option. There&amp;rsquo;s no API layer every caller can be forced through.&lt;/p&gt;
&lt;p&gt;The database, meanwhile, sees every writer. That&amp;rsquo;s how a team ends up with a trigger enforcing a rule that should have been in application code. The trigger is the only remaining place. It&amp;rsquo;s a symptom of losing the boundary, not a design choice made on its merits.&lt;/p&gt;
&lt;p&gt;The real lesson is that the boundary is the thing worth defending. Once multiple unknown clients are writing to a schema, every future rule either becomes a trigger by necessity or goes un-enforced. Greenfield systems should treat &amp;ldquo;who is allowed to write to this schema&amp;rdquo; as a first-class architectural decision, with one service in front of it and everyone else going through that service. Migrations out of the trap exist (service extraction, proxying direct-DB clients through a write API, introducing a write-time event bus) but they&amp;rsquo;re multi-quarter projects, and the trigger layer usually stays in place throughout because it&amp;rsquo;s doing the job nothing else is available to do.&lt;/p&gt;
&lt;h2 id="stored-procedures-the-vertical-scaling-trap"&gt;Stored procedures, the vertical-scaling trap
&lt;/h2&gt;&lt;p&gt;Stored procedures move application logic into the database process. They&amp;rsquo;re the tool most directly opposed to the &amp;ldquo;database as storage&amp;rdquo; position, and the one with the clearest scaling argument against them. On the four axes, stored procedures fail most of them for general business logic.&lt;/p&gt;
&lt;p&gt;Scope is within one database. Across services, impossible (which is part of why Spanner and DynamoDB don&amp;rsquo;t support them). Cadence is schema-migration speed; a product rule that needs a hotfix takes a migration. Cost is the procedure body running on the primary&amp;rsquo;s CPU, competing with every query for the same scarce resource, when the application tier could run the same logic on a pod that scales horizontally. Write-path count is the one axis where procedures are strongest: if the procedure is the only way to perform the operation, every write path is covered.&lt;/p&gt;
&lt;p&gt;The narrow case for stored procedures is the intersection of those trade-offs. Operations that must be atomic, must cover every write path, and would be prohibitively expensive to run row-by-row over the network. Bulk data operations that are genuinely row-by-row expensive. Security boundaries where the application is explicitly not trusted with direct table access. Legacy systems where procedures are the system of record.&lt;/p&gt;
&lt;p&gt;Outside those cases, stored procedures trade a scaling-ceiling problem and a deployment-cadence problem for centralization that a shared application library provides at lower cost. The argument that &amp;ldquo;a stored procedure prevents the application from drifting&amp;rdquo; is real, and the same argument applies to a validation library without the scaling or deployment penalty.&lt;/p&gt;
&lt;h2 id="views-the-quietly-useful-option"&gt;Views, the quietly useful option
&lt;/h2&gt;&lt;p&gt;Views don&amp;rsquo;t enforce writes but they do shape reads, and shaping reads affects correctness in practice. A view that filters soft-deleted rows means every consumer sees the same definition of &amp;ldquo;active&amp;rdquo;. Updatable views can also be a migration-compatibility tool.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VIEW&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;active_orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Scope is within-service. Cadence is fine either way; view bodies change as often as the underlying queries. Cost is the planner expanding views at query time, and complex views can hide expensive plans from the caller. Write-path count is read-time only, so views don&amp;rsquo;t help with integrity.&lt;/p&gt;
&lt;p&gt;Views are underused for their cheap benefits (canonical join shapes, soft-delete filtering, migration shims) and overused when they become a layer of logic the calling code can&amp;rsquo;t see. Materialized views are a separate topic; they add refresh-cadence questions the live-query tools don&amp;rsquo;t.&lt;/p&gt;
&lt;h2 id="derived-columns-and-counter-caches-implicit-logic"&gt;Derived columns and counter caches, implicit logic
&lt;/h2&gt;&lt;p&gt;Comment counts, follower counts, status summaries, running totals. Every one of these encodes business logic; the question is which mechanism maintains it.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;posts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;author_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;REFERENCES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;comment_count&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;last_comment_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPTZ&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Through the four-axis lens, four mechanisms:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Application code maintains it.&lt;/strong&gt; Cadence is fast. Cost is zero on the DB, per-write work on the app tier. Write-path count fails if any writer skips the library. Scope is fine within the service.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Materialized view or batch job.&lt;/strong&gt; Cadence is decoupled from the write. Cost is the refresh window. Write-path count covers everything, but the value is stale between refreshes. Scope is within-service.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Read-time aggregation.&lt;/strong&gt; Cadence is irrelevant. Cost is per-read and can be expensive on feed-style queries. Write-path count is always correct. Scope is within-service.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Separate counter service with async events.&lt;/strong&gt; Cadence is fast. Cost is extra infrastructure and delivery semantics to reason about. Write-path count covers everything if every writer publishes the event. Scope is any.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A trigger is conspicuously absent from that list on purpose. Counter-cache triggers are the canonical example of hidden logic causing a contention problem the application team can&amp;rsquo;t see: every concurrent comment insert serializes on the parent post&amp;rsquo;s row lock, and the debugging path goes straight through PL/pgSQL the service engineers didn&amp;rsquo;t write. The four-axis analysis points instead at the library-maintained counter when there&amp;rsquo;s one writer, the background rollup when reads are hot, and a separate counter service at scale or across boundaries.&lt;/p&gt;
&lt;h2 id="the-library-pattern-done-seriously"&gt;The library pattern, done seriously
&lt;/h2&gt;&lt;p&gt;The natural consequence of &amp;ldquo;narrow database, logic in application&amp;rdquo; is that the application layer&amp;rsquo;s logic has to be reusable. A validation that only lives in one service&amp;rsquo;s Rails app isn&amp;rsquo;t a library, it&amp;rsquo;s service code. A library every writer imports is the actual mechanism.&lt;/p&gt;
&lt;p&gt;Four shapes show up in practice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Monolith, one language.&lt;/strong&gt; A package inside the codebase, imported by every write path. Works well. Admin tools and background jobs depend on the same package as the web request path. Backfill scripts should depend on it too; in practice this is where discipline breaks down.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Microservices, one language.&lt;/strong&gt; A shared library published as a package. Every service depends on the same version, or accepts that a rollout takes a deploy cycle across services. Version skew is the operational tax.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Polyglot services.&lt;/strong&gt; A shared library doesn&amp;rsquo;t exist. Validation gets reimplemented per service, or pushed into a validation service that every caller hits over RPC. The RPC option is real and works; it turns &amp;ldquo;shared library&amp;rdquo; into &amp;ldquo;shared service&amp;rdquo; with the same logical role.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Schema-first code generation.&lt;/strong&gt; Tools like &lt;a class="link" href="https://sqlc.dev/" target="_blank" rel="noopener"
 &gt;sqlc&lt;/a&gt; and &lt;a class="link" href="https://www.jooq.org/" target="_blank" rel="noopener"
 &gt;jOOQ&lt;/a&gt; generate typed client code from the schema, which gives a narrow kind of library reuse (type safety and query shapes) without attempting to encode business logic. For logic itself, schemas aren&amp;rsquo;t enough; the library is separate.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The discipline that makes this work: the library is the only write path, and if it isn&amp;rsquo;t, the database&amp;rsquo;s declarative constraints are the backup. The two pieces reinforce each other. The library holds the full rule set, fast and rich and horizontal-scale. The schema holds the small subset the database can enforce cheaply and that every writer, library or not, has to pass through.&lt;/p&gt;
&lt;h2 id="the-duplication-trap"&gt;The duplication trap
&lt;/h2&gt;&lt;p&gt;The most common failure mode isn&amp;rsquo;t picking the wrong layer. It&amp;rsquo;s picking both without deciding which is authoritative.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Application validator: &lt;code&gt;email&lt;/code&gt; must match regex A.&lt;/li&gt;
&lt;li&gt;Database &lt;code&gt;CHECK&lt;/code&gt;: &lt;code&gt;email&lt;/code&gt; must match regex B.&lt;/li&gt;
&lt;li&gt;Over the years, one gets updated (for GDPR, for internationalization); the other doesn&amp;rsquo;t.&lt;/li&gt;
&lt;li&gt;Legacy rows exist that pass the old version but not the new one.&lt;/li&gt;
&lt;li&gt;A migration that tries to tighten the &lt;code&gt;CHECK&lt;/code&gt; fails on legacy rows the application thought were fine.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The pattern repeats with status enums, numeric ranges, referential rules, and soft-delete semantics. Two versions of the truth stay in sync as long as someone is actively keeping them in sync, and then they don&amp;rsquo;t.&lt;/p&gt;
&lt;p&gt;The useful framing: pick one layer as authoritative and name the other as a UX mirror or a safety net. The authoritative layer is the one that runs when the other doesn&amp;rsquo;t, which, for correctness invariants where write paths multiply, still points at the database for the narrow declarative subset.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- authoritative: the declarative CHECK
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CHECK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;active&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;closed&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# mirror in the library: better errors, fast-fail before the round trip&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;validate_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;pending&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;active&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;&amp;#34;closed&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="n"&gt;ValidationError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;Status must be pending, active, or closed.&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;If the library and the schema disagree, the schema wins and the write fails. The failure is loud, traceable, and tells you the drift exists, instead of the silent corruption you get when neither layer enforces a rule.&lt;/p&gt;
&lt;h2 id="rules-the-assistant-can-see"&gt;Rules the assistant can see
&lt;/h2&gt;&lt;p&gt;The choice of where to put a rule is, among other things, a choice about which readers can see it. An AI assistant writing SQL or application code against the schema reads the catalog (column types, constraints, FKs, CHECK definitions) and whatever source files the prompt happens to include. Declarative rules show up in &lt;code&gt;information_schema&lt;/code&gt; and &lt;code&gt;pg_constraint&lt;/code&gt;. The assistant can reason about them without being pointed at additional files. A &lt;code&gt;CHECK (status IN ('pending', 'active', 'closed'))&lt;/code&gt; is visible to any schema-reading tool on day one.&lt;/p&gt;
&lt;p&gt;Rules living in triggers, stored procedures, ORM callbacks, or a shared Python validation library don&amp;rsquo;t surface when the same tool reads the catalog. The write path enforces them at runtime; the schema doesn&amp;rsquo;t describe them. A model generating an INSERT statement against a table whose uniqueness is enforced only by a before-insert trigger will produce a query that looks correct and violates an invariant the catalog never mentioned. This doesn&amp;rsquo;t change the conclusion that most logic belongs in the application, but it does tip the math, at the margin, toward the narrow set of correctness invariants where declarative constraints pay double: they enforce on every write path, and they&amp;rsquo;re the only form of the rule a schema-reading assistant sees for free.&lt;/p&gt;
&lt;h2 id="trade-offs"&gt;Trade-offs
&lt;/h2&gt;&lt;p&gt;Every position in this post has counter-arguments, and they&amp;rsquo;re real.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Declarative database constraints lock you into SQL semantics.&lt;/strong&gt; A &lt;code&gt;CHECK&lt;/code&gt; constraint doesn&amp;rsquo;t survive a migration to DynamoDB or Spanner without rework. Teams building for a future migration accept less database-side logic in exchange for portability. The trade is real; the frequency of actual cross-engine migrations is lower than the frequency of discussions about them.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Schema changes are slow enough that even &amp;ldquo;simple&amp;rdquo; constraints are friction.&lt;/strong&gt; Adding a &lt;code&gt;CHECK&lt;/code&gt; to a 500M-row table is a migration project. For teams shipping schema changes weekly, every constraint is a cost, and sometimes the cheaper answer is to accept looser database-side invariants and stricter application-side ones.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application-side validation is easier to test, version, and roll back.&lt;/strong&gt; A library&amp;rsquo;s tests run in milliseconds; a constraint&amp;rsquo;s tests need a real database. Teams with weak integration-testing infrastructure end up under-testing database-side rules.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Horizontal-scaling arithmetic isn&amp;rsquo;t universal.&lt;/strong&gt; For services running on a single database at moderate load, the &amp;ldquo;vertical scaling ceiling&amp;rdquo; argument is an abstraction. The primary has plenty of headroom and the scaling argument is theoretical. The argument matters more as traffic grows.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shopify&amp;rsquo;s position is internally consistent.&lt;/strong&gt; No database-level foreign keys, all integrity in models, sharded storage. It works because every write path goes through Rails and because the operational investment in model-layer integrity is serious. A smaller team without that investment can&amp;rsquo;t safely adopt the same pattern; the constraints in the database are what a smaller team can afford.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stored procedures aren&amp;rsquo;t universally bad.&lt;/strong&gt; The Yugabyte post is right that in a single-service OLTP context, procedures can centralize logic effectively. The scaling argument is real but not always the binding constraint. Teams with deep SQL skills and disciplined version-control-for-procedures can extract more value than the &amp;ldquo;avoid them&amp;rdquo; position suggests.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The balance described above is what holds across the most common cases. Specific cases have specific answers. The failure mode is rarely picking the wrong point on the axis. It&amp;rsquo;s not picking at all.&lt;/p&gt;
&lt;h2 id="a-rule-by-rule-framework"&gt;A rule-by-rule framework
&lt;/h2&gt;&lt;p&gt;Instead of a blanket policy, a set of questions that point at the right layer per rule.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Does the rule cross service boundaries?&lt;/strong&gt; If yes, application library or orchestration service. The database can&amp;rsquo;t help.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Would violation corrupt data?&lt;/strong&gt; If yes, the database should enforce it as a declarative constraint, because every write path has to be covered.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the rule a derived value with a stable formula?&lt;/strong&gt; Generated column. Cheap, covers every writer, zero sync code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the rule a derived value with a changing formula or external inputs?&lt;/strong&gt; Application library.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Does the rule depend on anything outside the row (request context, external services, feature flags)?&lt;/strong&gt; Application library.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Does the rule change more often than quarterly?&lt;/strong&gt; Application library.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the rule a cross-cutting concern every write path needs (timestamps, audit logs)?&lt;/strong&gt; Application library that every writer imports, not a trigger. The trigger hides the logic; the library makes it visible to the reader of the code that caused the write.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Does the rule involve non-trivial computation or touch multiple rows per call?&lt;/strong&gt; Application library. Database CPU is the scarce tier.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is there more than one write path?&lt;/strong&gt; The library alone isn&amp;rsquo;t enough; declarative constraints in the schema are the backup.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The questions don&amp;rsquo;t eliminate judgment (several rules will land on edges) but they make the trade-offs visible and keep decisions from being driven by which layer the author was working in when the rule came up.&lt;/p&gt;
&lt;h2 id="the-bigger-picture"&gt;The bigger picture
&lt;/h2&gt;&lt;p&gt;Across services, the database is storage and logic lives in services and shared libraries. That&amp;rsquo;s the direction Spanner, DynamoDB, Cassandra, and the pattern literature all point, and the cross-service question is genuinely settled. Within a service it&amp;rsquo;s softer. The database can enforce things the application can&amp;rsquo;t, a narrow set of declarative constraints costs almost nothing, and the schema is the only layer that sees every writer the library&amp;rsquo;s author didn&amp;rsquo;t plan for. Keep the database lean. Put the full rule set in a library the application owns. Let the schema carry the small subset that catches the writes the library missed (which is more writes than anyone planning the system thought there would be).&lt;/p&gt;</description></item><item><title>Database Deadlocks, Part 2: Diagnosis, Retries, and Prevention</title><link>https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/</link><pubDate>Sun, 02 Mar 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Database Deadlocks, Part 2: Diagnosis, Retries, and Prevention" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;&lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/" target="_blank" rel="noopener"
 &gt;Part 1&lt;/a&gt; covered the patterns. This post is the operational half: reading the deadlock log to identify which pattern fired, designing retries that fail loudly instead of hiding the real bug, isolating hot rows before they become incidents, and the prevention primitives (&lt;code&gt;NOWAIT&lt;/code&gt;, &lt;code&gt;SKIP LOCKED&lt;/code&gt;, isolation-level changes, &lt;code&gt;lock_timeout&lt;/code&gt;) that remove entire categories from the workload.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A nightly inventory sync deadlocks every Tuesday at 02:14. The job runs &lt;code&gt;INSERT INTO inventory ... ON CONFLICT (sku) DO UPDATE&lt;/code&gt; across eighteen partner warehouses in parallel, and the deadlock counter spikes from 3 per hour to 400 per hour for the duration of the run. The on-call response over the last three incidents has been the same: bump the retry limit from 5 to 10. The deadlocks still happen, they just take longer to surface as user-facing errors. After the third week, someone reads the &lt;code&gt;LATEST DETECTED DEADLOCK&lt;/code&gt; output and finds &lt;code&gt;lock_mode X locks rec but not gap&lt;/code&gt; on the primary key. The workers aren&amp;rsquo;t sorting the upsert batches. One worker processes &lt;code&gt;(1, 2, 3)&lt;/code&gt; while another processes &lt;code&gt;(3, 2, 1)&lt;/code&gt;, and they deadlock on the middle row.&lt;/p&gt;
&lt;p&gt;The fix is one line in application code: &lt;code&gt;rows.sort(key=lambda r: r.sku)&lt;/code&gt; before each batch. The deadlock counter drops back to baseline immediately. The retry limit goes back to 5. The three weeks of bumping retry settings were chasing the symptom; the actual fix lived in the access path, not the retry layer. The log told the story the first time it was generated.&lt;/p&gt;
&lt;p&gt;This post is the operational half of the deadlocks series. &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/" &gt;Part 1&lt;/a&gt; covered the patterns. What follows is the sequence: read the log to identify which pattern fired, design retries that don&amp;rsquo;t hide the bug, then reach for the prevention primitives that remove categories from the workload entirely.&lt;/p&gt;
&lt;h2 id="read-the-mysql-deadlock-log"&gt;Read the MySQL deadlock log
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt; dumps the most recent deadlock in the &lt;code&gt;LATEST DETECTED DEADLOCK&lt;/code&gt; section. The catch: only the most recent. On a busy system, deadlocks overwrite each other faster than someone can log in and copy the output. Before anything else, turn on &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_print_all_deadlocks" target="_blank" rel="noopener"
 &gt;&lt;code&gt;innodb_print_all_deadlocks&lt;/code&gt;&lt;/a&gt;&lt;code&gt; = ON&lt;/code&gt; in every production deployment. It writes every deadlock to the error log instead of a single overwriting slot. The volume is negligible, the diagnostic value is high, and there is no downside.&lt;/p&gt;
&lt;p&gt;A representative entry looks like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;span class="lnt"&gt;14
&lt;/span&gt;&lt;span class="lnt"&gt;15
&lt;/span&gt;&lt;span class="lnt"&gt;16
&lt;/span&gt;&lt;span class="lnt"&gt;17
&lt;/span&gt;&lt;span class="lnt"&gt;18
&lt;/span&gt;&lt;span class="lnt"&gt;19
&lt;/span&gt;&lt;span class="lnt"&gt;20
&lt;/span&gt;&lt;span class="lnt"&gt;21
&lt;/span&gt;&lt;span class="lnt"&gt;22
&lt;/span&gt;&lt;span class="lnt"&gt;23
&lt;/span&gt;&lt;span class="lnt"&gt;24
&lt;/span&gt;&lt;span class="lnt"&gt;25
&lt;/span&gt;&lt;span class="lnt"&gt;26
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-mysql" data-lang="mysql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TRANSACTION&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;TRANSACTION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4823941&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ACTIVE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sec&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;starting&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;read&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;mysql&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kp"&gt;tables&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;use&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;locked&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LOCK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WAIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;struct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;heap&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1136&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;MySQL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;thread&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;892&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;OS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;thread&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;handle&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="n"&gt;x7f&lt;/span&gt;&lt;span class="p"&gt;...,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;18293&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;shipped&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1001&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WAITING&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;THIS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LOCK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;BE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;GRANTED&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;RECORD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LOCKS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;space&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;48&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;no&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;112&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;144&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;of&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;shop&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4823941&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lock_mode&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rec&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;but&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;not&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;gap&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;waiting&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TRANSACTION&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;TRANSACTION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4823942&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ACTIVE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sec&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;starting&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;read&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;paid&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1002&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HOLDS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;THE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LOCK&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;S&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;RECORD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LOCKS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;space&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;48&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;no&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;112&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;144&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;of&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;shop&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4823942&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lock_mode&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rec&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;but&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;not&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;gap&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WAITING&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;THIS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LOCK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;BE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;GRANTED&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;RECORD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LOCKS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;space&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;48&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;no&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;112&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;144&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;index&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;of&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;table&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;shop&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;`&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4823942&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lock_mode&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rec&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;but&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;not&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;gap&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;waiting&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="o"&gt;***&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ROLL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;BACK&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;TRANSACTION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The parts that matter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;lock_mode&lt;/code&gt; vs. &lt;code&gt;lock_type&lt;/code&gt;.&lt;/strong&gt; &lt;code&gt;X&lt;/code&gt; is exclusive, &lt;code&gt;S&lt;/code&gt; is shared. &lt;code&gt;locks rec but not gap&lt;/code&gt; is a pure record lock; &lt;code&gt;locks gap before rec&lt;/code&gt; is a gap lock; the unadorned &lt;code&gt;X&lt;/code&gt; under &lt;code&gt;REPEATABLE READ&lt;/code&gt; is usually next-key (record + gap). Matching &lt;code&gt;lock_mode S locks rec but not gap&lt;/code&gt; against &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#unique-index-deadlocks-are-a-category-of-their-own" &gt;Part 1&amp;rsquo;s unique-index section&lt;/a&gt; tells you immediately that this is a duplicate-key-on-insert deadlock.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;index&lt;/code&gt; name.&lt;/strong&gt; &lt;code&gt;index PRIMARY&lt;/code&gt; vs. &lt;code&gt;index idx_customer&lt;/code&gt; reveals whether the cycle formed on the clustered index or a secondary one. Two transactions approaching the same rows from different indexes is the &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#index-scans-lock-more-rows-than-queries-return" &gt;&amp;ldquo;secondary index locks on InnoDB&amp;rdquo; pattern from Part 1&lt;/a&gt;; the fix is usually consolidating access paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The query text.&lt;/strong&gt; This is the last statement the transaction executed before the deadlock, not necessarily the one that caused it. A transaction holding locks from three earlier statements can deadlock on the fourth, and the log only shows the fourth. Cross-reference with the application&amp;rsquo;s structured logs to reconstruct the full transaction.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;trx id&lt;/code&gt;&lt;/strong&gt; is monotonically increasing and stable for the life of the transaction. Searching the general log or slow-query log for that &lt;code&gt;trx id&lt;/code&gt; reconstructs the full statement sequence, but only if general-query logging is on for the window in question, which it usually isn&amp;rsquo;t.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;performance_schema.data_locks&lt;/code&gt; and &lt;code&gt;data_lock_waits&lt;/code&gt; give a real-time view of current locks and waits. Useful for catching a deadlock-adjacent pathology (long wait chains, hot rows) before the cycle forms:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lock_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lock_mode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;object_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;REQUESTING_ENGINE_TRANSACTION_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;waiting_trx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BLOCKING_ENGINE_TRANSACTION_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocking_trx&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data_lock_waits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data_locks&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;BLOCKING_ENGINE_LOCK_ID&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ENGINE_LOCK_ID&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OBJECT_SCHEMA&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;shop&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;h2 id="read-the-postgresql-deadlock-log"&gt;Read the PostgreSQL deadlock log
&lt;/h2&gt;&lt;p&gt;PostgreSQL&amp;rsquo;s diagnostic story is narrower by design. Deadlocks are logged automatically when the cycle is detected. &lt;code&gt;log_lock_waits = on&lt;/code&gt; logs any wait exceeding &lt;code&gt;deadlock_timeout&lt;/code&gt; (default 1s), which catches the wait-chain escalation before the detector fires. There&amp;rsquo;s no equivalent to &lt;code&gt;SHOW ENGINE INNODB STATUS&lt;/code&gt;; everything lives in &lt;code&gt;postgresql.log&lt;/code&gt; or the extensions you&amp;rsquo;ve installed.&lt;/p&gt;
&lt;p&gt;A representative deadlock entry:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-zed" data-lang="zed"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;ERROR&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deadlock&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;detected&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;DETAIL&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14234&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;waits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ShareLock&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;on&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;89234&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocked&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;by&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14235&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14235&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;waits&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ShareLock&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;on&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;89233&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocked&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;by&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14234&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14234&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;2&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Process&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;14235&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;50&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;HINT&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;See&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;server&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;details&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;CONTEXT&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;updating&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="err"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="err"&gt;18&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;in&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kn"&gt;relation&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;&amp;#34;&lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="err"&gt;&amp;#34;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The &lt;code&gt;ShareLock on transaction X&lt;/code&gt; wording is PostgreSQL-specific. One transaction is waiting to see the commit status of another (a row-lock wait manifests as waiting on the holder&amp;rsquo;s transaction ID). The tuple identifier &lt;code&gt;(0,18)&lt;/code&gt; points to the exact physical row (page 0, tuple 18 in the heap), which is useful for reproducing the scenario but changes as rows are updated (MVCC creates new versions at new &lt;code&gt;(page, tuple)&lt;/code&gt; locations).&lt;/p&gt;
&lt;p&gt;For real-time inspection, &lt;code&gt;pg_locks&lt;/code&gt; joined against &lt;code&gt;pg_stat_activity&lt;/code&gt; shows live lock state:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;usename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;wait_event_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;wait_event&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;mode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;locktype&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;relation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_blocking_pids&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;blocked_by&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;80&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stat_activity&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LEFT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;JOIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_locks&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;granted&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;idle&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;pg_blocking_pids(pid)&lt;/code&gt; returns the array of PIDs blocking a given transaction. Walking it recursively reconstructs the live wait-for graph: the same data the deadlock detector uses, just before a cycle forms. For hot systems, &lt;code&gt;pg_stat_statements&lt;/code&gt; combined with &lt;code&gt;pg_stat_activity&lt;/code&gt; snapshots at regular intervals builds a picture of which statements accumulate the most wait time, which is almost always the right first place to look.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Row locks are invisible in pg_locks&lt;/strong&gt;
 &lt;div&gt;&lt;p&gt;PostgreSQL&amp;rsquo;s row-level locks (the result of &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, FK checks, and plain &lt;code&gt;UPDATE&lt;/code&gt;/&lt;code&gt;DELETE&lt;/code&gt;) are stored on the tuple itself, in the &lt;code&gt;xmax&lt;/code&gt; system column, not in the shared lock table. They don&amp;rsquo;t show up in &lt;code&gt;pg_locks&lt;/code&gt;. The only way to see them is through the &lt;code&gt;pgrowlocks&lt;/code&gt; extension, which scans the heap directly:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;EXTENSION&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pgrowlocks&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pgrowlocks&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;accounts&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;This is the single biggest difference between PG and InnoDB lock introspection, and the reason PG operators often feel blind to row-level contention until a cycle actually forms.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="handle-serializable-serialization-failures-separately"&gt;Handle SERIALIZABLE serialization failures separately
&lt;/h2&gt;&lt;p&gt;Under &lt;code&gt;SERIALIZABLE&lt;/code&gt; isolation, PostgreSQL uses Serializable Snapshot Isolation (SSI), an optimistic mechanism based on SIREAD predicate locks that track read-write dependencies between transactions. SSI cannot deadlock by design; it never blocks on lock acquisition. What it does is abort one transaction with a serialization failure when it detects a dangerous read-write dependency cycle that would violate serializability.&lt;/p&gt;
&lt;p&gt;The two failure codes look similar but have fundamentally different semantics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;40001 serialization_failure&lt;/code&gt;.&lt;/strong&gt; SSI detected a dependency cycle and aborted the transaction before it could commit a non-serializable result. The transaction did nothing wrong; the combination of its operations with a concurrent transaction would have produced an inconsistency. Retrying is always safe and usually succeeds (the concurrent transaction will have committed or aborted, so the second attempt doesn&amp;rsquo;t see the same conflict).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;40P01 deadlock_detected&lt;/code&gt;.&lt;/strong&gt; A cycle in the wait-for graph was broken by killing a victim. Retrying may or may not succeed depending on what caused the cycle. If the cycle was deterministic (two code paths with inconsistent ordering), it will keep recurring.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The practical consequence for retry architecture: an application running under &lt;code&gt;SERIALIZABLE&lt;/code&gt; must handle 40001. It&amp;rsquo;s not a deadlock, it&amp;rsquo;s the normal failure mode of SSI, and retries are the only recovery path. An application running under &lt;code&gt;READ COMMITTED&lt;/code&gt; never sees 40001. An application that handles 40001 identically to 40P01 is correct but coarse. The right granularity is: always retry 40001 (the workload&amp;rsquo;s own correctness guarantee assumes this); retry 40P01 with caution and escalate on repeat.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;retry_on_conflict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_attempts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_attempts&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;psycopg&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;SerializationFailure&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="c1"&gt;# 40001: always retry. SSI guarantees make this safe.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;psycopg&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DeadlockDetected&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="c1"&gt;# 40P01: retry with caution; log for root-cause analysis.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;log_deadlock_for_analysis&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;...&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;backoff&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="n"&gt;TransactionRetryExhausted&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;h2 id="architect-retries-that-surface-bugs-not-bury-them"&gt;Architect retries that surface bugs, not bury them
&lt;/h2&gt;&lt;p&gt;Every database driver documentation says &amp;ldquo;deadlocks happen, retry the transaction.&amp;rdquo; That&amp;rsquo;s true. It&amp;rsquo;s also incomplete. The dangers are subtle enough that a naive retry loop becomes part of the problem:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Retries without backoff make the cycle worse.&lt;/strong&gt; The condition that caused the deadlock (contention on a hot key set) is still in effect when the retry runs. A tight retry loop turns one deadlock into a thundering herd: all victims retry simultaneously, all hit the same contention, all deadlock again. Use exponential backoff with full jitter, capped at a few hundred milliseconds.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Retries mask lock-ordering bugs.&lt;/strong&gt; If an application deadlocks 10x/minute but retries successfully, the operator sees no failures, but the underlying transactions are doing up to 20x the work (original + retry). The deadlock rate itself is a metric worth tracking, not just the post-retry error rate. When the rate grows, the fix is diagnosing the pattern, not tuning the retry limit.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Retries aren&amp;rsquo;t always safe.&lt;/strong&gt; A transaction that sent an external notification, wrote to a message queue, or called a non-idempotent HTTP endpoint before the deadlock can&amp;rsquo;t be blindly retried; the external side effect already happened. Retries belong on database-only transactions, or on transactions where the external calls are idempotent and tolerant of duplicate execution. The boundary is architectural, not a library setting.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Retries need a budget.&lt;/strong&gt; If a transaction can&amp;rsquo;t complete after ~3 attempts, the problem is no longer transient contention. It&amp;rsquo;s either a systemic hot spot or a bug that retries will never resolve. Escalate (alert, fail the request, enqueue for manual review), don&amp;rsquo;t loop forever.&lt;/p&gt;
&lt;p&gt;The retry pattern that works in production:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;do_work&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;return&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;DeadlockError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;SerializationFailure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;metrics&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;db.retry&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tags&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;error&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;uniform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.1&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="n"&gt;RetryBudgetExhausted&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Three attempts, exponential backoff up to ~400ms, metrics emitted on every retry, hard failure past the budget. The metric matters as much as the retry - without it, the team never learns which transactions are retrying frequently and why.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Idempotency is a transaction-shape property&lt;/strong&gt;
 &lt;div&gt;A transaction is safe to retry iff re-running it produces the same observable state. That includes downstream side effects. A transaction that writes to a table AND sends a webhook is not safe to retry even if both operations are internally correct: the second attempt sends a duplicate webhook. The fix is the outbox pattern: write the webhook-send intent to a table in the same transaction, then have a separate worker process the outbox with its own idempotency guarantees. This is a non-negotiable part of building deadlock-retry-safe systems at scale.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="sort-writes-to-lock-in-one-direction"&gt;Sort writes to lock in one direction
&lt;/h2&gt;&lt;p&gt;&lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#the-canonical-lock-ordering-deadlock" &gt;Part 1&amp;rsquo;s lock-ordering deadlock&lt;/a&gt; (two transactions updating the same set of rows in opposite orders) is the single most common production pattern and the one with the highest-leverage fix. If every code path that writes to a set of tables acquires locks in the same order, the wait-for graph literally cannot form a cycle on those rows. The engine still takes the locks, still holds them for the duration of the transaction, but the second transaction waits cleanly for the first instead of grabbing a lock the first will need.&lt;/p&gt;
&lt;p&gt;The rule is: sort the rows by a stable key (usually the primary key) in application code, before any SQL is issued. Lock acquisition order in both engines is determined by the order the engine processes rows, which for most write patterns is the order the application submitted them. Sort once up front, and N workers all doing the same thing can&amp;rsquo;t cycle because they all approach the row set from the same end.&lt;/p&gt;
&lt;p&gt;The three batch shapes that matter in practice, and where the ordering actually happens:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Loop of per-row UPDATEs.&lt;/strong&gt; The classic batch worker:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Sort in the application; the iteration order IS the lock acquisition order.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;UPDATE accounts SET balance = balance + &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt; WHERE id = &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Each UPDATE locks its target row at execution time; the loop order determines acquisition order. No SQL-level &lt;code&gt;ORDER BY&lt;/code&gt; involved; the fix lives in the &lt;code&gt;.sort()&lt;/code&gt; call.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Bulk UPSERT.&lt;/strong&gt; &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; (MySQL) or &lt;code&gt;INSERT ... ON CONFLICT&lt;/code&gt; (PostgreSQL):&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Sort rows by the unique key BEFORE building the batch.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;execute_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;INSERT INTO accounts (id, balance) VALUES &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt; &amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;ON CONFLICT (id) DO UPDATE SET balance = accounts.balance + EXCLUDED.balance&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The engine processes the VALUES list in order and acquires locks as it goes. Two concurrent batches sorted by the same key approach the key space from the same end; without the sort, one batch might process &lt;code&gt;(1, 2, 3)&lt;/code&gt; while another processes &lt;code&gt;(3, 2, 1)&lt;/code&gt; and they deadlock on the middle row. This is the exact shape of the bulk-UPSERT deadlocks called out in &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#unique-index-deadlocks-are-a-category-of-their-own" &gt;Part 1&amp;rsquo;s unique-index section&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Small multi-row transactions.&lt;/strong&gt; The canonical bank transfer:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Always update the lower id first, regardless of transfer direction.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;For 2–3 rows with per-row different values, the application computes &lt;code&gt;sorted((X, Y))&lt;/code&gt; and issues UPDATEs in that order. Same principle as the batch case, just smaller.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Where &lt;code&gt;SELECT ... FOR UPDATE ORDER BY&lt;/code&gt; actually earns its keep.&lt;/strong&gt; Most batches don&amp;rsquo;t need it; they control lock order through the submission order. The one shape where it&amp;rsquo;s the right answer is a single UPDATE statement over a derived table where the engine decides scan order and you can&amp;rsquo;t control it from outside:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Here, sorting the VALUES list in application code doesn&amp;rsquo;t reliably control lock order; the planner picks the scan. A &lt;code&gt;SELECT id FROM accounts WHERE id IN (...) ORDER BY id FOR UPDATE&lt;/code&gt; up front pre-acquires locks in deterministic order before the UPDATE runs. Or refactor into shape 1 or 2.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;ORDER BY controls result order, not scan order&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;ORDER BY&lt;/code&gt; on a &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; controls the result ordering, but lock acquisition happens during the scan. With a primary-key or unique-index predicate (&lt;code&gt;WHERE id IN (...)&lt;/code&gt; on a PK), the planner does ordered index lookups and locks land in ORDER BY order in practice. For non-indexed predicates or range scans on non-unique columns, the planner may scan in a different order and sort results afterward; locks get acquired in scan order. Verify with &lt;code&gt;EXPLAIN&lt;/code&gt; before relying on this pattern against non-PK predicates. Also: MySQL&amp;rsquo;s &lt;code&gt;UPDATE ... ORDER BY&lt;/code&gt; syntax applies one SET clause to all matching rows; it doesn&amp;rsquo;t help when rows need different values.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This sounds trivial. It almost never is in practice; the ordering has to hold across every code path that writes to the same tables: the main request handler, backfill scripts, admin scripts, scheduled jobs, ORM bulk-save methods, and whatever migration scripts run during releases. One path that writes in a different order is enough to reopen the cycle. The durable fix is encoding the order in the access layer so individual query sites can&amp;rsquo;t diverge from it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A repository function that always sorts by PK before writing.&lt;/li&gt;
&lt;li&gt;A stored procedure or database function that owns the multi-row write.&lt;/li&gt;
&lt;li&gt;A service method with the ordering baked in, and a lint rule or review check forbidding direct table writes from elsewhere.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Two places this invariant breaks without anyone noticing:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ORM bulk-save methods.&lt;/strong&gt; ORMs hide whether they process in input order or reorder internally. Django&amp;rsquo;s &lt;code&gt;Model.objects.bulk_update&lt;/code&gt;, SQLAlchemy&amp;rsquo;s &lt;code&gt;bulk_update_mappings&lt;/code&gt;, ActiveRecord&amp;rsquo;s &lt;code&gt;upsert_all&lt;/code&gt;, Hibernate&amp;rsquo;s batch inserts; some process in input order, some sort by PK internally, some chunk before doing either. If you can&amp;rsquo;t tell from docs, test it: two concurrent bulk-saves with opposing-ordered input lists will either deadlock (proving input order matters) or not (proving the ORM sorts internally). Either way, sorting the input collection before handing it to the ORM is cheap insurance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Batches sourced from a &lt;code&gt;SELECT&lt;/code&gt; in the same transaction.&lt;/strong&gt; A common pattern: &amp;ldquo;grab N pending rows, process them.&amp;rdquo; If the feeder SELECT doesn&amp;rsquo;t have an &lt;code&gt;ORDER BY&lt;/code&gt;, rows come back in scan order, non-deterministic across workers, which reopens the cycle. The fix is an explicit &lt;code&gt;ORDER BY&lt;/code&gt; on the feeder query, not in the subsequent loop:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Bad: scan order feeds the loop.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;SELECT id, delta FROM pending WHERE status = &amp;#39;ready&amp;#39; LIMIT 100&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# Whatever the scan produced; varies across workers.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="o"&gt;...&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Good: deterministic order, same across every worker.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;SELECT id, delta FROM pending WHERE status = &amp;#39;ready&amp;#39; ORDER BY id LIMIT 100&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="o"&gt;...&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The lint-rule angle matters more than it sounds. Deadlock-ordering violations are almost impossible to catch in code review - two PRs that each look correct in isolation can introduce inconsistent ordering when combined. The check that actually works is structural: no direct writes to tables X, Y from anywhere except the repository. Once that invariant is enforced, the ordering invariant follows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Multi-table transactions need the same rule applied to table order.&lt;/strong&gt; A transaction that updates &lt;code&gt;users&lt;/code&gt; then &lt;code&gt;orders&lt;/code&gt; in one code path, and &lt;code&gt;orders&lt;/code&gt; then &lt;code&gt;users&lt;/code&gt; in another, can deadlock through the FK chain even with per-table row ordering. The rule generalizes: sort rows within a table, and sort tables within a transaction, by a stable convention the whole codebase agrees on (alphabetical is fine; just pick one).&lt;/p&gt;
&lt;h2 id="weigh-the-isolation-level-trade-offs"&gt;Weigh the isolation-level trade-offs
&lt;/h2&gt;&lt;p&gt;The isolation level a workload runs under determines which deadlock categories even apply. Most MySQL deadlock incidents stem from &lt;code&gt;REPEATABLE READ&lt;/code&gt;&amp;rsquo;s gap locks, a category that doesn&amp;rsquo;t exist on PostgreSQL or on MySQL at &lt;code&gt;READ COMMITTED&lt;/code&gt;. Changing the isolation level is the single highest-leverage tuning lever, and also the one with the most potential to quietly break application correctness.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dropping MySQL from &lt;code&gt;REPEATABLE READ&lt;/code&gt; to &lt;code&gt;READ COMMITTED&lt;/code&gt;.&lt;/strong&gt; Under &lt;code&gt;READ COMMITTED&lt;/code&gt;, InnoDB still takes row locks but skips most gap locks (they exist only for unique-key and FK enforcement on inserts). Most OLTP workloads don&amp;rsquo;t need &lt;code&gt;REPEATABLE READ&lt;/code&gt;&amp;rsquo;s range-consistency guarantee. Most application code was designed around &lt;code&gt;READ COMMITTED&lt;/code&gt; semantics anyway, because that&amp;rsquo;s what PostgreSQL and SQL Server default to. Teams migrating to &lt;code&gt;READ COMMITTED&lt;/code&gt; typically see deadlock rates drop by an order of magnitude with no functional change.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Avoiding range locks on write paths.&lt;/strong&gt; Independent of isolation level, replacing &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; scans over ranges with point lookups by primary key removes the gap-lock surface entirely on the statements that do it. If a write path doesn&amp;rsquo;t need to lock &amp;ldquo;all orders for customer 5,&amp;rdquo; locking just the specific row it&amp;rsquo;s about to update is both faster and safer.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;FK shared locks are shorter-lived under &lt;code&gt;READ COMMITTED&lt;/code&gt;.&lt;/strong&gt; The &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#foreign-keys-take-shared-locks-you-didnt-ask-for" &gt;foreign-key shared-lock pattern from Part 1&lt;/a&gt; (high-write child tables concentrating shared locks on hot parent rows) has a narrower window under &lt;code&gt;READ COMMITTED&lt;/code&gt; simply because the lock lifespan is tied to the statement rather than the transaction. The cycle potential is still there, but the wait window is smaller.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Isolation change is a behavior change, not a tuning knob&lt;/strong&gt;
 &lt;div&gt;&lt;code&gt;READ COMMITTED&lt;/code&gt; eliminates most gap locks but also changes the visibility semantics of long-running transactions. Any code that relied on re-reading a row and getting the same result (transfer logic, inventory deductions, financial calculations) has to be re-examined. The safe migration is application-by-application, not database-wide. Run it in staging under production-like load and watch for subtle correctness regressions: &amp;ldquo;phantom&amp;rdquo; rows appearing inside a transaction that used to see a stable snapshot, inventory counts that shift mid-transaction, calculations that no longer match because an underlying row changed between reads.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Session-scoped change as a migration path.&lt;/strong&gt; Both engines let you set isolation level per session or per transaction (&lt;code&gt;SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED&lt;/code&gt; in MySQL, &lt;code&gt;SET TRANSACTION ISOLATION LEVEL READ COMMITTED&lt;/code&gt; per transaction in PostgreSQL). The usual migration pattern is to start with the most contended code paths, move them to session-scoped &lt;code&gt;READ COMMITTED&lt;/code&gt;, monitor for regressions, then expand the scope. A global flip from &lt;code&gt;REPEATABLE READ&lt;/code&gt; to &lt;code&gt;READ COMMITTED&lt;/code&gt; on a large, stable MySQL deployment is rarely the right first step.&lt;/p&gt;
&lt;h2 id="isolate-hot-rows-off-the-contention-path"&gt;Isolate hot rows off the contention path
&lt;/h2&gt;&lt;p&gt;When the top N deadlocks on a production system concentrate on a small set of rows (a counter, a config row, an &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; source of truth), retries don&amp;rsquo;t converge. Every retry hits the same row, takes the same lock, cycles with the same peers. The fix is removing the row from the hot path, not tuning the retry layer.&lt;/p&gt;
&lt;p&gt;Three patterns that work:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Counter tables with sharding&lt;/strong&gt;, for extreme write-hot counters only. Reach for this only when the counter is taking thousands of writes per second against a single row and the simpler options below aren&amp;rsquo;t viable. For anything less, the queue pattern below or an external store (Redis atomic &lt;code&gt;INCR&lt;/code&gt;, a time-series DB) is almost always the better answer: less complexity, no schema overhead, no sum-across-rows read cost. Sharded counters are the specialized escalation, not the default.&lt;/p&gt;
&lt;p&gt;When it does fit the workload: N physical shards per logical counter, keyed on a compact integer &lt;code&gt;(counter_id, shard_id)&lt;/code&gt; composite. Application code picks the shard. Keeping the random choice out of SQL makes it portable across engines and testable independently:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_shards&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- FK to a counters metadata table if you need names
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shard_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;SMALLINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- 0..N-1, fixed per-counter
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counter_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shard_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Seed the shards once per counter (e.g., when the counter is created):
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_shards&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counter_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shard_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;14&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;span class="lnt"&gt;12
&lt;/span&gt;&lt;span class="lnt"&gt;13
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-python" data-lang="python"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Increment: application picks the shard. Portable, cheap, no SQL-side RAND().&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;shard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;randrange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;UPDATE counter_shards SET value = value + 1 &amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;WHERE counter_id = &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt; AND shard_id = &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;shard&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;# Read: sum across shards.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="s2"&gt;&amp;#34;SELECT COALESCE(SUM(value), 0) FROM counter_shards WHERE counter_id = &lt;/span&gt;&lt;span class="si"&gt;%s&lt;/span&gt;&lt;span class="s2"&gt;&amp;#34;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,),&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;16 shards turn one hot row into 16 warm rows. The contention surface scales with shard count. The read cost is one &lt;code&gt;SUM&lt;/code&gt; across N rows instead of a single-row &lt;code&gt;SELECT&lt;/code&gt;, usually acceptable for counter use cases; if not, cache the aggregate.&lt;/p&gt;
&lt;p&gt;A common refinement is deriving the shard deterministically from the connection or worker ID (e.g., &lt;code&gt;connection_id % 16&lt;/code&gt;) so each worker consistently hits the same shard. That improves InnoDB buffer-pool locality and reduces cross-shard interference, at the cost of slightly less even distribution if worker counts aren&amp;rsquo;t balanced.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Advisory locks for app-level serialization.&lt;/strong&gt; Both MySQL and PostgreSQL support advisory locks: named locks that exist outside the table model and don&amp;rsquo;t take row locks. For operations that need to be serialized at the application level (leader election, rate limiting, config migration), advisory locks are dramatically cheaper than row locks and can&amp;rsquo;t participate in a table-lock cycle:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL: advisory lock keyed by a bigint.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_advisory_xact_lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hashtext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;refresh_cache:customer_42&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Lock released at transaction end. Only one worker per key runs at a time.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL equivalent:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;GET_LOCK&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;refresh_cache:customer_42&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Returns 1 if acquired, 0 on timeout. Must explicitly RELEASE_LOCK.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The caveats: advisory locks are application-layer discipline; they don&amp;rsquo;t enforce anything the database checks. Use them where the application chooses to serialize, not where correctness requires it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Queue patterns instead of direct updates.&lt;/strong&gt; For counter-like workloads, write intents to an append-only table and aggregate periodically:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_events&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counter_key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- No contention: every insert creates a new row.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Periodic aggregation job:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_totals&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counter_key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SUM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;delta&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_events&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;processed&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FALSE&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;GROUP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_key&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;CONFLICT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;counter_key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;counter_totals&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;EXCLUDED&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Trades real-time accuracy for throughput. The right trade-off for page-view counters, metric accumulation, any workload where eventual consistency is acceptable.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hot parent rows behind FK chains.&lt;/strong&gt; &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#foreign-keys-take-shared-locks-you-didnt-ask-for" &gt;Part 1&lt;/a&gt; described how a high-write child table concentrates shared locks on a hot parent row, and how any exclusive-lock request on that parent (a name update, a soft-delete, a trigger-driven counter update) becomes a contention point. Two levers that work:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Move high-frequency parent-row updates to a side table.&lt;/strong&gt; The &lt;code&gt;last_activity_at&lt;/code&gt; timestamp, the cached counter, the &lt;code&gt;updated_at&lt;/code&gt; that a trigger bumps on every child insert; none of these need to live on the parent table. Moving them to &lt;code&gt;customer_activity(customer_id, last_seen_at)&lt;/code&gt; or &lt;code&gt;customer_counters(customer_id, order_count)&lt;/code&gt; eliminates the exclusive-lock contention entirely. The parent row stops changing on hot paths, the shared locks from FK checks coexist fine, and the cycle potential disappears.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Narrow the FK scope where integrity can tolerate it.&lt;/strong&gt; Not every child table needs an enforced FK to every parent. Logs, events, and audit tables are often the biggest offenders, and often have the least need for strict integrity (an orphaned log row is rarely a correctness problem). Dropping the FK removes the shared-lock dependency entirely. This trades integrity for throughput, a decision that belongs with the team owning the data, not a default.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Under &lt;code&gt;READ COMMITTED&lt;/code&gt;, both levers matter less because the FK shared locks release at statement end rather than transaction end. A workload that runs on &lt;code&gt;REPEATABLE READ&lt;/code&gt; and can&amp;rsquo;t change isolation level (because of application semantics) gets the most benefit from these two fixes.&lt;/p&gt;
&lt;h2 id="shorten-long-running-transactions"&gt;Shorten long-running transactions
&lt;/h2&gt;&lt;p&gt;The longer a transaction holds locks, the wider the window for a cycle. Two patterns recur in production:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Application-layer long transactions.&lt;/strong&gt; A transaction that opens at request start, makes several queries, calls an external API, then commits. The external call is where the transaction actually spends its time: seconds of open transaction holding row locks the whole time. Every concurrent transaction that touches those rows waits. Deadlock probability scales with transaction duration. The fix is the inverse of the outbox pattern: do the external call outside the transaction, passing in any needed IDs.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Idle-in-transaction sessions.&lt;/strong&gt; A session that runs &lt;code&gt;BEGIN&lt;/code&gt;, some writes, then stalls; idle but not committed. In PostgreSQL, this blocks vacuum on touched tables, bloats MVCC, and holds locks indefinitely. &lt;code&gt;pg_stat_activity&lt;/code&gt; shows &lt;code&gt;state = 'idle in transaction'&lt;/code&gt;. MySQL&amp;rsquo;s equivalent is a thread with an open transaction and no current query.&lt;/p&gt;
&lt;p&gt;PostgreSQL has a first-class timeout for this; MySQL does not:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL: kill idle-in-transaction sessions after 5 minutes.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- (Units required; bare integer would be interpreted as milliseconds.)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idle_in_transaction_session_timeout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;5min&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL has no direct equivalent. &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_wait_timeout" target="_blank" rel="noopener"
 &gt;&lt;code&gt;wait_timeout&lt;/code&gt;&lt;/a&gt; and &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_interactive_timeout" target="_blank" rel="noopener"
 &gt;&lt;code&gt;interactive_timeout&lt;/code&gt;&lt;/a&gt; govern idle connections, not sessions idle inside an open transaction. A connection that did &lt;code&gt;BEGIN&lt;/code&gt; then stopped sending queries will hold its locks until the connection drops or the client commits. The production workaround is either a watchdog script (e.g., Percona&amp;rsquo;s &lt;code&gt;pt-kill&lt;/code&gt;) that polls &lt;code&gt;information_schema.innodb_trx&lt;/code&gt; and terminates transactions exceeding a duration threshold, or a connection pool with per-connection transaction lifetimes. Connection pools that acquire a connection, start a transaction, then return the connection to the pool without committing (rare but real) will produce sessions that live indefinitely otherwise.&lt;/p&gt;
&lt;p&gt;Finding long-running transactions:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;usename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;duration&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stat_activity&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;INTERVAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;30 seconds&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;duration&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_started&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_mysql_thread_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_rows_locked&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_query&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;innodb_trx&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TIMESTAMPDIFF&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SECOND&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;trx_started&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOW&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Alerting on any transaction exceeding 30s in an OLTP workload catches most of the long-transaction-induced deadlocks before they produce incidents.&lt;/p&gt;
&lt;h2 id="audit-triggers-and-cascades-for-hidden-locks"&gt;Audit triggers and cascades for hidden locks
&lt;/h2&gt;&lt;p&gt;A trigger that updates a second table on every write to the first adds an edge to the wait-for graph that isn&amp;rsquo;t visible in the original query. &lt;code&gt;ON DELETE CASCADE&lt;/code&gt; foreign keys behave similarly - one delete can take locks on every child row in the cascade, and if the cascade order differs between two concurrent deletes, they can deadlock through tables neither statement directly referenced.&lt;/p&gt;
&lt;p&gt;This is the origin of the &amp;ldquo;why is my &lt;code&gt;DELETE FROM users&lt;/code&gt; deadlocking against an &lt;code&gt;INSERT INTO events&lt;/code&gt;?&amp;rdquo; question. The &lt;code&gt;DELETE&lt;/code&gt; triggered a cascade to &lt;code&gt;user_preferences&lt;/code&gt;, which had a trigger that updated a counter in &lt;code&gt;tenants&lt;/code&gt;, which was locked by the &lt;code&gt;INSERT&lt;/code&gt;. Four tables in the cycle, two in the application&amp;rsquo;s explicit query, zero mention of the other two in any log entry until someone reads the DDL.&lt;/p&gt;
&lt;p&gt;The operational pattern: when a deadlock log mentions a table the application&amp;rsquo;s code doesn&amp;rsquo;t explicitly reference, check (1) FK cascades on the tables that are in the query, (2) triggers on those tables, (3) generated columns that fire on update. All three are non-obvious lock sources, all three are fixable, but only after they&amp;rsquo;re identified.&lt;/p&gt;
&lt;h2 id="set-innodb_autoinc_lock_mode-deliberately"&gt;Set &lt;code&gt;innodb_autoinc_lock_mode&lt;/code&gt; deliberately
&lt;/h2&gt;&lt;p&gt;MySQL InnoDB&amp;rsquo;s &lt;code&gt;AUTO_INCREMENT&lt;/code&gt; column has its own lock, historically a source of contention and occasional deadlock. The &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_autoinc_lock_mode" target="_blank" rel="noopener"
 &gt;&lt;code&gt;innodb_autoinc_lock_mode&lt;/code&gt;&lt;/a&gt; parameter controls the behavior:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mode 0 (traditional).&lt;/strong&gt; Table-level AUTO-INC lock held for the duration of the statement. Serialized across inserts. Safe for statement-based replication, terrible for concurrency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mode 1 (consecutive).&lt;/strong&gt; A lighter lock for simple inserts (single-row or known-row-count), and the traditional table lock for bulk inserts (&lt;code&gt;INSERT ... SELECT&lt;/code&gt;). Was the default in 5.7.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mode 2 (interleaved).&lt;/strong&gt; No AUTO-INC table lock; IDs are assigned per-row as needed, possibly interleaved across concurrent statements. Default in MySQL 8.0. Fastest, and correct for row-based replication (which is also the 8.0 default).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The mode-2 default in 8.0 eliminated a substantial source of historical deadlocks and contention. Bulk inserts that used to serialize on the AUTO-INC lock now proceed in parallel. If you&amp;rsquo;re migrating from 5.7 to 8.0, this is a free win. If you&amp;rsquo;re still on &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_binlog_format" target="_blank" rel="noopener"
 &gt;&lt;code&gt;binlog_format&lt;/code&gt;&lt;/a&gt;&lt;code&gt; = STATEMENT&lt;/code&gt; (uncommon but not unheard of in legacy deployments), you cannot safely run mode 2; the replica may generate different IDs than the source, corrupting the data. Switch to &lt;code&gt;binlog_format = ROW&lt;/code&gt; first, then adopt mode 2.&lt;/p&gt;
&lt;h2 id="guard-ddl-migrations-with-lock_timeout"&gt;Guard DDL migrations with &lt;code&gt;lock_timeout&lt;/code&gt;
&lt;/h2&gt;&lt;p&gt;Online schema change isn&amp;rsquo;t deadlock-prone in the classical sense, but it interacts with deadlocks in a specific operational way: DDL takes heavy locks that queue behind ongoing DML, and while the DDL waits, every subsequent query on that table queues behind the DDL. In PostgreSQL, a DDL taking &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; that waits for an existing long-running &lt;code&gt;SELECT&lt;/code&gt; will cause every new &lt;code&gt;SELECT&lt;/code&gt; to wait behind the DDL. The system grinds to a halt, and application logs fill with timeout errors that look like deadlocks but aren&amp;rsquo;t. It&amp;rsquo;s a queue, not a cycle.&lt;/p&gt;
&lt;p&gt;The standard prevention idiom for PostgreSQL migrations:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;lock_timeout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;2s&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;TEXT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;If the &lt;code&gt;ALTER&lt;/code&gt; can&amp;rsquo;t acquire its lock in 2 seconds, it fails instead of queueing. The migration tool catches the error and retries with backoff. This prevents the queue-behind-DDL outage entirely - the cost is that some migrations need multiple attempts to land, which is almost always the right trade-off.&lt;/p&gt;
&lt;p&gt;MySQL&amp;rsquo;s equivalent tooling is &lt;code&gt;pt-online-schema-change&lt;/code&gt; (Percona) and &lt;code&gt;gh-ost&lt;/code&gt; (GitHub). Both create a copy of the table, stream writes to both via trigger or binlog, and swap at the end. They run concurrent DML against the original and the copy, so they inflate deadlock rates during the migration window: not because the tool is buggy, but because there are now more transactions touching the same rows. The operational practice: run migrations at low-traffic windows, watch the deadlock counter during the run (not just replica lag), and have a rollback path ready.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;DDL inside transactions is engine-dependent&lt;/strong&gt;
 &lt;div&gt;PostgreSQL supports transactional DDL: &lt;code&gt;BEGIN; ALTER TABLE ...; COMMIT;&lt;/code&gt; is atomic. MySQL does not; every DDL statement implicitly commits the current transaction. A migration script that assumes it can roll back mid-migration works on PostgreSQL and silently half-applies on MySQL. Know which engine you&amp;rsquo;re writing migrations for.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="reach-for-nowait-and-skip-locked"&gt;Reach for &lt;code&gt;NOWAIT&lt;/code&gt; and &lt;code&gt;SKIP LOCKED&lt;/code&gt;
&lt;/h2&gt;&lt;p&gt;Both engines support two SQL-level concurrency primitives that remove the need for application-layer deadlock handling in specific patterns:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;SELECT ... FOR UPDATE NOWAIT&lt;/code&gt;.&lt;/strong&gt; If the row is locked by another transaction, fail immediately with an error instead of waiting. Useful for user-facing paths where &amp;ldquo;I can&amp;rsquo;t get this resource right now&amp;rdquo; is a better UX than &amp;ldquo;wait 500ms and maybe deadlock anyway.&amp;rdquo; Also useful for detecting lock contention synthetically in tests.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;SELECT ... FOR UPDATE SKIP LOCKED&lt;/code&gt;.&lt;/strong&gt; If rows are locked by another transaction, skip them and return only rows the current transaction can lock. Transforms a contended queue-processor pattern into a lock-free one: N workers each grab a different set of rows, zero contention, zero deadlocks.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Queue processor: deadlock-free, contention-free.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;jobs&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ORDER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;BY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;priority&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;LIMIT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FOR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SKIP&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LOCKED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Fast-fail acquisition: don&amp;#39;t wait, fail now.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;leader_election&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resource_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;cache-refresh&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FOR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NOWAIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;SKIP LOCKED&lt;/code&gt; arrived in PostgreSQL 9.5 and MySQL 8.0. Before those versions, queue-processor patterns required either advisory locks or application-level coordination (Redis, Zookeeper). Post-&lt;code&gt;SKIP LOCKED&lt;/code&gt;, they can live entirely in the database with a single primitive. For any workload where workers pull from a shared queue, this is the pattern - not retry loops on &lt;code&gt;FOR UPDATE&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="monitor-the-metrics-that-catch-regressions"&gt;Monitor the metrics that catch regressions
&lt;/h2&gt;&lt;p&gt;The single most useful metric is deadlock rate over time. Not error rate, not retry rate; the raw count of deadlocks per minute or per thousand transactions. A workload with 0.1 deadlocks per thousand transactions is healthy; 10 per thousand is a paging threshold; 100 per thousand means retries aren&amp;rsquo;t converging and something is structurally wrong.&lt;/p&gt;
&lt;p&gt;For MySQL: there&amp;rsquo;s no &lt;code&gt;Innodb_deadlocks&lt;/code&gt; status variable. The correct source is &lt;code&gt;performance_schema.events_errors_summary_global_by_error&lt;/code&gt;, which is enabled by default:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Cumulative deadlock count (compare over time windows).
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SUM_ERROR_RAISED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deadlock_count&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;performance_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;events_errors_summary_global_by_error&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ERROR_NAME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;ER_LOCK_DEADLOCK&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Lock-wait activity (useful for adjacent contention, NOT a deadlock counter):
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SHOW&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GLOBAL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;STATUS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;LIKE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Innodb_row_lock_waits&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Plus the error log, searchable for &amp;#34;LATEST DETECTED DEADLOCK&amp;#34;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- once innodb_print_all_deadlocks=ON.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;code&gt;Innodb_row_lock_waits&lt;/code&gt; is commonly misread as a deadlock counter - &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.0/en/server-status-variables.html#statvar_Innodb_row_lock_waits" target="_blank" rel="noopener"
 &gt;the manual&lt;/a&gt; defines it as &amp;ldquo;the number of times operations on InnoDB tables had to wait for a row lock,&amp;rdquo; which is contention in general. Pair it with the &lt;code&gt;events_errors_summary&lt;/code&gt; query, not in place of it.&lt;/p&gt;
&lt;p&gt;For PostgreSQL:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- pg_stat_database exposes per-database deadlock counter.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deadlocks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_commit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;xact_rollback&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stat_database&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;datname&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_database&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Scrape both into Prometheus (mysqld_exporter and postgres_exporter both expose these), compute the rate, alert on sustained rises. Pair the deadlock rate with a &lt;em&gt;retry rate&lt;/em&gt; from the application layer - a spike in one without the other means either the retry logic is broken or the workload shape changed. A spike in both means a real regression.&lt;/p&gt;
&lt;p&gt;Beyond the rate itself, the top-K pairs of statements involved in deadlocks (extracted from &lt;code&gt;innodb_print_all_deadlocks&lt;/code&gt; logs or PG&amp;rsquo;s deadlock log entries) identify exactly which code paths are fighting. This list rarely changes - the same two or three patterns account for most deadlocks in any given system. Fix those and the rate drops by an order of magnitude.&lt;/p&gt;
&lt;h2 id="the-mental-model-for-part-2"&gt;The mental model for Part 2
&lt;/h2&gt;&lt;p&gt;Part 1&amp;rsquo;s patterns answer why deadlocks happen. Part 2&amp;rsquo;s operations answer what to do about them, and the useful reframe is that the answer is almost never &amp;ldquo;tune the retry logic.&amp;rdquo; Retries are the recovery mechanism that keeps the application running while the actual fix lands. The actual fix is almost always one of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Identify the pattern from the log. This is step zero; skipping it means you&amp;rsquo;re tuning blind.&lt;/li&gt;
&lt;li&gt;Enforce consistent lock ordering at the access-layer level. Highest-leverage fix for the lock-ordering pattern; deterministically eliminates the cycle rather than shrinking its window.&lt;/li&gt;
&lt;li&gt;Change the code path to use &lt;code&gt;SKIP LOCKED&lt;/code&gt; / &lt;code&gt;NOWAIT&lt;/code&gt; where the pattern matches (queue processors, resource acquisition).&lt;/li&gt;
&lt;li&gt;Isolate hot rows (counter tables, shards, advisory locks, queue patterns; move high-frequency parent-row updates to side tables).&lt;/li&gt;
&lt;li&gt;Shorten transactions. Move external calls out, enforce idle-transaction timeouts.&lt;/li&gt;
&lt;li&gt;Drop isolation level where the workload allows it; session-scoped first, global only after regression testing. Eliminates the gap-lock category on MySQL.&lt;/li&gt;
&lt;li&gt;Remove cascades/triggers from the hot path when they&amp;rsquo;re the hidden lock source.&lt;/li&gt;
&lt;li&gt;Handle &lt;code&gt;SERIALIZABLE&lt;/code&gt;&amp;rsquo;s 40001 as a normal event if you&amp;rsquo;re on &lt;code&gt;SERIALIZABLE&lt;/code&gt;, and don&amp;rsquo;t confuse it with 40P01.&lt;/li&gt;
&lt;li&gt;Plan DDL windows with &lt;code&gt;lock_timeout&lt;/code&gt; and watch the deadlock counter through the migration.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Retries let the application survive while the fix is in flight. Monitoring tells you which fix to prioritize. Each of the above removes a category from the workload entirely. The goal is a system where the few remaining deadlocks are rare enough that the retry layer handles them invisibly and the team&amp;rsquo;s attention can go elsewhere. Not zero (that&amp;rsquo;s a theoretical fiction at realistic concurrency), but managed.&lt;/p&gt;</description></item><item><title>Database Deadlocks, Part 1: The Patterns</title><link>https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/</link><pubDate>Thu, 13 Feb 2025 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Database Deadlocks, Part 1: The Patterns" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;A deadlock is two or more transactions (groups of statements the database runs as one unit) each waiting for a lock that another one holds, so that none can finish until the database cancels one. This post covers what a lock is and how long it lasts, how ordinary waiting turns into a loop, how MySQL and PostgreSQL notice the loop and choose which transaction to cancel, and the shapes deadlocks take in real workloads, including the ones where the locked row is one the query never mentions. &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/" target="_blank" rel="noopener"
 &gt;Part 2&lt;/a&gt; covers reading the deadlock log, retries and prevention.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Here is what the database saw, in outline. If two transactions, like the two payments, could change the same row at the same moment, whichever wrote last would erase the other&amp;rsquo;s change. So before a transaction changes a row, the database gives it a lock on that row, held until the transaction ends, and anyone else who wants to change the row waits. Usually the wait is short, because the first transaction finishes and the next one goes. But for the two payments it never ends. Payment 1 has changed account 1 and wants account 2, payment 2 has changed account 2 and wants account 1, and each is waiting for the other to finish, which neither can do without the row the other holds. That is a deadlock. Waiting longer cannot end it, so the database looks for exactly this loop and, when it finds one, cancels one transaction, undoing its changes and releasing its locks so the other can finish. The error is the notice that it did. Its advice, to restart the transaction, is also the fallback the &lt;a class="link" href="https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-DEADLOCKS" target="_blank" rel="noopener"
 &gt;PostgreSQL manual&lt;/a&gt; offers. It works often enough to hide the cause: neither payment was wrong, the loop came from the order they touched the rows in, and that order is still in the code the next time two payments cross.&lt;/p&gt;
&lt;h2 id="a-quick-reminder-about-transactions"&gt;A quick reminder about transactions
&lt;/h2&gt;&lt;p&gt;A payment is two changes, and the application needs both or neither, even through a crash or another payment squeezing in between. Guaranteeing that by hand is hard, so the database does it: a transaction is a group of statements it treats as one unit. &lt;code&gt;BEGIN&lt;/code&gt; opens one, &lt;code&gt;COMMIT&lt;/code&gt; keeps every change and &lt;code&gt;ROLLBACK&lt;/code&gt; undoes every change; a statement sent without &lt;code&gt;BEGIN&lt;/code&gt; is a transaction of its own. PostgreSQL and InnoDB, MySQL&amp;rsquo;s default storage engine, make four guarantees for every transaction, known together as ACID:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Guarantee&lt;/th&gt;
 &lt;th&gt;What it promises&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Atomic&lt;/td&gt;
 &lt;td&gt;all of the transaction&amp;rsquo;s changes happen, or none of them do&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Consistent&lt;/td&gt;
 &lt;td&gt;every rule the schema declares (keys, constraints) holds when the transaction ends&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Isolated&lt;/td&gt;
 &lt;td&gt;a transaction is not disturbed by other transactions running at the same moment&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Durable&lt;/td&gt;
 &lt;td&gt;once committed, the changes survive a crash&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Deadlocks come from the third row, and there are a lot of transactions to keep apart: every program talking to the database holds a connection, which both engines call a session, PostgreSQL allows 100 by default and MySQL 151, and busy systems run thousands. Isolation has two tools. One is MVCC, multi-version concurrency control, which keeps a changed row&amp;rsquo;s old version around so that a plain read gets a consistent answer without waiting for anyone (the MVCC posts for &lt;a href="https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/"&gt;PostgreSQL&lt;/a&gt; and MySQL cover it). The other is locks, which MVCC does not replace, because two transactions that both want to change the same row still have to take turns. The first row comes in at the end: cancelling a transaction is a rollback, and atomicity guarantees that all of its changes are undone, not some.&lt;/p&gt;
&lt;h2 id="a-lock-lasts-until-the-transaction-ends"&gt;A lock lasts until the transaction ends
&lt;/h2&gt;&lt;p&gt;A lock is a note the database keeps that a transaction is using a row, and what makes deadlocks possible is how long the note stays: from the statement that touches the row until &lt;code&gt;COMMIT&lt;/code&gt; or &lt;code&gt;ROLLBACK&lt;/code&gt;, however many statements later. It has to. If payment 1 let go of account 1 after its first &lt;code&gt;UPDATE&lt;/code&gt;, payment 2 could change the row, and a rollback of payment 1 would then wipe out payment 2&amp;rsquo;s change as well.&lt;/p&gt;
&lt;p&gt;Locks come in two strengths. An exclusive lock is for changing a row. A shared lock is for reading a row while making sure nobody changes it until you are done. Any number of transactions can share a row; an exclusive lock keeps out everyone else:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Lock another transaction already holds&lt;/th&gt;
 &lt;th&gt;Asking for a shared lock&lt;/th&gt;
 &lt;th&gt;Asking for an exclusive lock&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;none&lt;/td&gt;
 &lt;td&gt;granted&lt;/td&gt;
 &lt;td&gt;granted&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;shared&lt;/td&gt;
 &lt;td&gt;granted&lt;/td&gt;
 &lt;td&gt;waits&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;exclusive&lt;/td&gt;
 &lt;td&gt;waits&lt;/td&gt;
 &lt;td&gt;waits&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;code&gt;UPDATE&lt;/code&gt;, &lt;code&gt;DELETE&lt;/code&gt; and &lt;code&gt;INSERT&lt;/code&gt; take exclusive locks on the rows they change, &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; takes one without changing anything, and &lt;code&gt;SELECT ... FOR SHARE&lt;/code&gt; takes a shared one. A plain &lt;code&gt;SELECT&lt;/code&gt; takes no row lock at either engine&amp;rsquo;s default settings, because MVCC answers it from row versions (stricter settings change that; the isolation levels post covers them, and this post sticks to the defaults). The engine also takes some locks on its own, for checks the query never spelled out, and those are behind the hardest deadlocks to read.&lt;/p&gt;
&lt;p&gt;The table already contains a deadlock. Two transactions that each hold a shared lock on a row, and then each ask for an exclusive one, wait for each other&amp;rsquo;s shared lock forever. The isolation levels post ran into it on MySQL 8.4.13, whose strictest setting, SERIALIZABLE, makes a plain read take a shared lock. Two deposits that read the same balance and then updated it deadlocked, and in a 20-second run of 16 sessions moving money between 100 accounts, 906 transfers were rolled back as deadlocks (median of three runs).&lt;/p&gt;
&lt;p&gt;Waiting on its own is not a deadlock, and a picture tells them apart. Draw a dot for each transaction and an arrow from each waiting transaction to the one it waits for; this is the wait-for graph, and it is what the database inspects. If C waits for B and B waits for A, the chain ends at A, which is still running, and drains when A commits. A deadlock is when the arrows come back around to where they started, a cycle, and nobody in it can move.&lt;/p&gt;
&lt;p&gt;&lt;a id="the-canonical-lock-ordering-deadlock"&gt;&lt;/a&gt;The two payments make the smallest cycle there is, and it is the example the &lt;a class="link" href="https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-DEADLOCKS" target="_blank" rel="noopener"
 &gt;PostgreSQL manual&lt;/a&gt; uses to explain deadlocks:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Payment 1
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Payment 2, at the same time
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Payment 1 updates account 1 and holds its lock. Payment 2 updates account 2 and holds that one. Payment 1 moves on to account 2 and has to wait for payment 2; payment 2 moves on to account 1 and has to wait for payment 1. Now the arrows point both ways:&lt;/p&gt;
&lt;p&gt;&lt;img alt="Payment 1 has updated account 1 and holds its lock, payment 2 has updated account 2 and holds its lock, and each waits for the row the other holds, which in the wait-for graph is a cycle from payment 1 to payment 2 and back; the database breaks it by cancelling one payment." loading="lazy" sizes="(max-width: 767px) calc(100vw - 30px), (max-width: 1023px) 700px, (max-width: 1279px) 950px, 1232px" src="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/lock-cycle.svg"&gt;&lt;/p&gt;
&lt;p&gt;Neither transaction is wrong, and that is the part worth holding on to. Each takes its locks in an order that makes sense on its own; the cycle exists only in how the two orders combine, which no test of one code path will ever show. It needs transactions that hold locks while asking for more, two of them each wanting what the other holds, and no way to take both locks in one step. Remove any of those and it cannot form. The usual one to remove is the second, by making every code path touch rows in the same order (the lower account id first), so the second payment waits behind the first instead of grabbing a row the first one needs. The PostgreSQL manual calls a consistent order &amp;ldquo;the best defense&amp;rdquo;, and &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/#sort-writes-to-lock-in-one-direction" &gt;Part 2&lt;/a&gt; covers making it hold across a whole codebase.&lt;/p&gt;
&lt;h2 id="how-mysql-and-postgresql-break-the-loop"&gt;How MySQL and PostgreSQL break the loop
&lt;/h2&gt;&lt;p&gt;Left alone, a cycle lasts forever. The PostgreSQL manual puts it flatly: &amp;ldquo;So long as no deadlock situation is detected, a transaction seeking either a table-level or row-level lock will wait indefinitely for conflicting locks to be released.&amp;rdquo; So both engines run a deadlock detector, which walks the wait-for graph looking for a cycle, picks one transaction in it as the victim, rolls it back and returns an error to its application. The rest carry on as if nothing had happened.&lt;/p&gt;
&lt;p&gt;The engines differ in when they look and in whom they pick:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;&lt;/th&gt;
 &lt;th&gt;MySQL (InnoDB)&lt;/th&gt;
 &lt;th&gt;PostgreSQL&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;When the check runs&lt;/td&gt;
 &lt;td&gt;on by default, controlled by &lt;code&gt;innodb_deadlock_detect&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;after a transaction has waited &lt;code&gt;deadlock_timeout&lt;/code&gt;, 1 second by default&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Who gets cancelled&lt;/td&gt;
 &lt;td&gt;the smaller transaction, by rows inserted, updated or deleted&lt;/td&gt;
 &lt;td&gt;&amp;ldquo;difficult to predict and should not be relied upon&amp;rdquo;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Error the victim gets&lt;/td&gt;
 &lt;td&gt;1213, SQLSTATE 40001: &lt;code&gt;Deadlock found when trying to get lock; try restarting transaction&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;SQLSTATE 40P01: &lt;code&gt;deadlock detected&lt;/code&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;With the detector off&lt;/td&gt;
 &lt;td&gt;&lt;code&gt;innodb_deadlock_detect = OFF&lt;/code&gt;: the waiters give up after &lt;code&gt;innodb_lock_wait_timeout&lt;/code&gt;, 50 seconds by default&lt;/td&gt;
 &lt;td&gt;no off switch; a higher &lt;code&gt;deadlock_timeout&lt;/code&gt; only delays the check&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;PostgreSQL&amp;rsquo;s delay is deliberate: its &lt;a class="link" href="https://www.postgresql.org/docs/18/runtime-config-locks.html" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt; calls the check &amp;ldquo;relatively expensive&amp;rdquo; and bets that most lock waits end on their own, so a deadlock there is noticed only once one of its transactions has waited that long. InnoDB &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlock-detection.html" target="_blank" rel="noopener"
 &gt;has a quirk&lt;/a&gt; of its own: when more than 200 transactions are queued in one wait-for chain, it treats the chain as a deadlock and rolls back the transaction doing the checking, cycle or no cycle.&lt;/p&gt;
&lt;p&gt;The victim did nothing wrong, so running it again is safe as far as the database is concerned, and the retry usually succeeds because the other transaction has finished by then. Whether it is safe for the application (an email already sent, a payment provider already called) is a question &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/" &gt;Part 2&lt;/a&gt; takes up.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Deadlock vs. lock wait timeout&lt;/strong&gt;
 &lt;div&gt;A deadlock is a cycle. A lock wait timeout is a long chain: A waits for B, B is busy with something legitimate that takes too long, and a timer runs out. No cycle, no victim selection. The two errors look alike in application logs but have different causes and different fixes. &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-parameters.html#sysvar_innodb_lock_wait_timeout" target="_blank" rel="noopener"
 &gt;&lt;code&gt;innodb_lock_wait_timeout&lt;/code&gt;&lt;/a&gt; (MySQL) and &lt;a class="link" href="https://www.postgresql.org/docs/18/runtime-config-client.html#GUC-LOCK-TIMEOUT" target="_blank" rel="noopener"
 &gt;&lt;code&gt;lock_timeout&lt;/code&gt;&lt;/a&gt; (PostgreSQL, off by default) govern the second; the deadlock detector works independently of both.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="locks-the-query-never-asked-for"&gt;Locks the query never asked for
&lt;/h2&gt;&lt;p&gt;In the payment example every lock is written in the SQL. The deadlocks that take longest to understand involve a lock nobody wrote, taken by the engine to keep some other promise, often on a row or index entry the statement never names. Four come up again and again, three of them at their worst at MySQL&amp;rsquo;s default settings.&lt;/p&gt;
&lt;h3 id="a-search-that-finds-nothing-still-locks"&gt;A search that finds nothing still locks
&lt;/h3&gt;&lt;p&gt;The default isolation level, the setting for how much a transaction is shielded from others, is READ COMMITTED in PostgreSQL and REPEATABLE READ in MySQL. At REPEATABLE READ, a locking search in InnoDB also locks the gaps between the index entries it passes, so that nobody can insert a row into a range the transaction has searched and the same search cannot turn up a new row later. The manual calls the combination a next-key lock, &amp;ldquo;a record lock on the index record and a gap lock on the gap before the index record.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;A gap lock has a slightly absurd property. Its only job is to keep inserts out, so the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locking.html#innodb-gap-locks" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; lets everyone hold one at once: &amp;ldquo;Gap locks can co-exist.&amp;rdquo; That turns a very common piece of code, check that a row does not exist and then insert it, into a deadlock. Two requests create the first order for customer 7 at the same moment, both running this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL at its default REPEATABLE READ; orders has an index on customer_id
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- and no rows yet for customer 7
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FOR&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- finds nothing, locks the gap
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;amount_cents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Both searches find nothing and both lock the same gap, which they may do together. Then each inserts into it, and an insert has to wait for any gap lock another transaction holds on that spot. Each waits for the other&amp;rsquo;s: a cycle over a row neither transaction has written. Run as two sessions on MySQL 8.4.13, half a second apart, the first insert went through once the second session had been rolled back with &lt;code&gt;Deadlock found when trying to get lock&lt;/code&gt;, and customer 7 ended with one order.&lt;/p&gt;
&lt;p&gt;PostgreSQL has no gap locks at any isolation level, so this shape cannot deadlock there. It cannot protect anything either: on PostgreSQL 18.6 both sessions&amp;rsquo; searches found nothing, both inserts went through, and customer 7 ended with two first orders. The &lt;a href="https://explainanalyze.com/p/postgresql-mvcc-explained-dead-tuples-vacuum-and-idle-transactions/"&gt;PostgreSQL MVCC post&lt;/a&gt; measured the difference: an insert into a range another transaction had locked with &lt;code&gt;FOR UPDATE&lt;/code&gt; went through in 2.6 ms on PostgreSQL 18.6, while MySQL 8.4.13 at its defaults made it wait the full 2 seconds the other transaction stayed open. At READ COMMITTED, MySQL keeps gap locking only for foreign-key and duplicate-key checks (&lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt;), and in the MySQL MVCC post the same insert then took 6.7 ms. That removes the deadlock and the protection with it: run the same way at READ COMMITTED, both MySQL sessions inserted and customer 7 got two orders, as on PostgreSQL. Only a unique index stops that on either engine. Switching levels changes what the application sees in other ways too, which &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/#weigh-the-isolation-level-trade-offs" &gt;Part 2&lt;/a&gt; weighs.&lt;/p&gt;
&lt;h3 id="unique-index-deadlocks-are-a-category-of-their-own"&gt;A failed insert still takes a lock
&lt;/h3&gt;&lt;p&gt;A unique index promises that no two rows share a value, and InnoDB keeps that promise with a lock even when the insert fails: an &lt;code&gt;INSERT&lt;/code&gt; that hits a duplicate puts a shared lock on the existing index entry before raising the error. The &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locks-set.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; shows where that goes wrong with three sessions inserting the same primary key. Session 1 inserts first and holds an exclusive lock on the new row. Sessions 2 and 3 find the duplicate and queue for a shared lock. Then session 1 rolls back, sessions 2 and 3 are granted their shared locks together, and both now need an exclusive lock to insert the row, which each one&amp;rsquo;s shared lock denies the other. &amp;ldquo;At this point, sessions 2 and 3 deadlock.&amp;rdquo; It is the shared-then-exclusive deadlock from the lock table, set off by a check the application never asked for.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; takes an exclusive lock on a duplicate instead, since it is about to change the row, so two of them hitting the same existing row simply queue; batches of them reaching the same keys in different orders still cycle like the payments. PostgreSQL has no shared lock to upgrade: a second insert of a key another transaction has just inserted waits for that transaction to finish, then fails or goes ahead, and its &lt;code&gt;INSERT ... ON CONFLICT&lt;/code&gt; deadlocks come from batches in different key orders (&lt;a class="link" href="https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/#unique-indexes-also-concentrate-deadlock-pressure" &gt;more on unique indexes under concurrent writes&lt;/a&gt;).&lt;/p&gt;
&lt;h3 id="foreign-keys-take-shared-locks-you-didnt-ask-for"&gt;Foreign keys lock the parent row
&lt;/h3&gt;&lt;p&gt;A foreign key promises that a child row points at a parent that exists, &lt;code&gt;orders.customer_id&lt;/code&gt; at a real &lt;code&gt;customers.id&lt;/code&gt;, so both engines lock the parent row while a child row is written, to keep the parent from being deleted underneath it. MySQL takes a shared lock: any statement that has to check the constraint &amp;ldquo;sets shared record-level locks on the records that it looks at to check the constraint&amp;rdquo; (&lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locks-set.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;That shared lock is what makes a counter cache deadlock. Say each order also bumps &lt;code&gt;customers.order_count&lt;/code&gt;, through application code or a trigger, and two orders for customer 42 arrive at once:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Both orders for customer 42 run this at the same time (MySQL)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;amount_cents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- shared lock on customer 42
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_count&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;order_count&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- needs an exclusive lock on it
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;Each insert takes a shared lock on customer 42 through the foreign key, and both are granted, since shared locks coexist. Then each update needs an exclusive lock and waits for the other&amp;rsquo;s shared lock. On MySQL 8.4.13 the second session got the deadlock error and the first finished, leaving &lt;code&gt;order_count&lt;/code&gt; at 1 and one order. The deadlock names &lt;code&gt;customers&lt;/code&gt;, a table neither &lt;code&gt;INSERT&lt;/code&gt; mentions, which is why this shape so often reaches someone as &amp;ldquo;why is my &lt;code&gt;UPDATE customers&lt;/code&gt; deadlocking against an &lt;code&gt;INSERT INTO orders&lt;/code&gt;?&amp;rdquo;&lt;/p&gt;
&lt;p&gt;PostgreSQL takes a weaker lock, &lt;code&gt;FOR KEY SHARE&lt;/code&gt;, added in version 9.3, which &amp;ldquo;blocks other transactions from performing &lt;code&gt;DELETE&lt;/code&gt; or any &lt;code&gt;UPDATE&lt;/code&gt; that changes the key values, but not other &lt;code&gt;UPDATE&lt;/code&gt;&amp;rdquo; (&lt;a class="link" href="https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-ROWS" target="_blank" rel="noopener"
 &gt;documentation&lt;/a&gt;). So on PostgreSQL the counter updates do not conflict with the foreign-key locks, and the second waits for the first like any two updates of one row: a queue, not a cycle. On PostgreSQL 18.6 the second update finished 0.54 seconds after the first, once the first transaction had committed, and &lt;code&gt;order_count&lt;/code&gt; ended at 2. Deleting the customer or changing its id would still conflict. On either engine a hot parent row lines up every write that touches it; &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/#isolate-hot-rows-off-the-contention-path" &gt;Part 2&lt;/a&gt; covers moving such updates off the parent.&lt;/p&gt;
&lt;h3 id="index-scans-lock-more-rows-than-queries-return"&gt;An UPDATE locks what it reads
&lt;/h3&gt;&lt;p&gt;At REPEATABLE READ, InnoDB locks every index entry a locking statement examines, not only the rows it ends up changing. An &lt;code&gt;UPDATE orders SET priority = 'high' WHERE status = 'pending'&lt;/code&gt; with no index on &lt;code&gt;status&lt;/code&gt; has to read the whole table to find the pending rows, and the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locks-set.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; spells out the result: &amp;ldquo;every row of the table becomes locked, which in turn blocks all inserts by other users to the table.&amp;rdquo; Those locks last until the transaction ends, so every transaction touching any row of the table now has someone to wait for, and a slow query has become a deadlock-prone one too. At READ COMMITTED, InnoDB releases the locks on rows that did not match once it has checked the &lt;code&gt;WHERE&lt;/code&gt; clause (&lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt;), and PostgreSQL only ever locks the rows an &lt;code&gt;UPDATE&lt;/code&gt; changes. An index on &lt;code&gt;status&lt;/code&gt; helps at every setting, because the search then examines only the matching entries.&lt;/p&gt;
&lt;div class="note-box"&gt;
 &lt;strong&gt;Two indexes, one row&lt;/strong&gt;
 &lt;div&gt;When InnoDB finds rows through a secondary index, it locks the entries in that index and then the row itself in the clustered index, the primary key index that holds the table&amp;rsquo;s rows (the &lt;a href="https://explainanalyze.com/p/clustered-vs-non-clustered-index-the-table-is-the-index-in-mysql/"&gt;clustered index post&lt;/a&gt; explains that layout). Two transactions that reach the same rows through different indexes, one by &lt;code&gt;status&lt;/code&gt; and one by &lt;code&gt;customer_id&lt;/code&gt;, take those locks in different orders and can deadlock on the primary key, even though their &lt;code&gt;WHERE&lt;/code&gt; clauses share no columns.&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id="when-the-same-work-runs-many-times-at-once"&gt;When the same work runs many times at once
&lt;/h2&gt;&lt;p&gt;Every shape so far needs two transactions that happen to collide. Running the same work many times in parallel makes collisions routine. The common case is a pool of identical workers pulling jobs from one table (&lt;code&gt;jobs&lt;/code&gt;, &lt;code&gt;outbox&lt;/code&gt;, &lt;code&gt;email_queue&lt;/code&gt;), each locking a batch with &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;. Without an &lt;code&gt;ORDER BY&lt;/code&gt;, two workers can lock overlapping rows in different orders: the payment deadlock, spread across copies of code that no review will fault, since every copy is identical. Locking rows in a fixed order removes the cycle, and &lt;code&gt;SKIP LOCKED&lt;/code&gt;, which makes a worker pass over rows someone else has locked instead of waiting for them, removes the waiting altogether (&lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/#reach-for-nowait-and-skip-locked" &gt;Part 2&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Replicas can deadlock on transactions that never overlapped on the primary. A MySQL 8.4 replica applies changes with four worker threads by default (&lt;code&gt;replica_parallel_workers&lt;/code&gt;), so transactions that committed one after another on the source can run side by side on the replica, and the &lt;a class="link" href="https://dev.mysql.com/doc/refman/8.4/en/replication-options-replica.html#sysvar_replica_transaction_retries" target="_blank" rel="noopener"
 &gt;manual&lt;/a&gt; plans for it: a worker that fails &amp;ldquo;because of an InnoDB deadlock&amp;rdquo; retries up to &lt;code&gt;replica_transaction_retries&lt;/code&gt; times, 10 by default, before replication stops with an error. PostgreSQL 18 made parallel apply the default for logical replication, with a &lt;a class="link" href="https://www.postgresql.org/docs/18/sql-createsubscription.html" target="_blank" rel="noopener"
 &gt;documented&lt;/a&gt; &amp;ldquo;risk of deadlock when the schemas of the publisher and subscriber differ, although such cases are rare,&amp;rdquo; also retried automatically. Either way the deadlocks show up on the replica with nothing matching them on the source.&lt;/p&gt;
&lt;h2 id="which-shape-is-firing"&gt;Which shape is firing
&lt;/h2&gt;&lt;p&gt;Every shape in this post, with the lock behind it and where it can happen at each engine&amp;rsquo;s settings:&lt;/p&gt;
&lt;table&gt;
 &lt;thead&gt;
 &lt;tr&gt;
 &lt;th&gt;Shape&lt;/th&gt;
 &lt;th&gt;The lock behind it&lt;/th&gt;
 &lt;th&gt;MySQL, REPEATABLE READ (default)&lt;/th&gt;
 &lt;th&gt;MySQL, READ COMMITTED&lt;/th&gt;
 &lt;th&gt;PostgreSQL, READ COMMITTED (default)&lt;/th&gt;
 &lt;th&gt;Evidence&lt;/th&gt;
 &lt;/tr&gt;
 &lt;/thead&gt;
 &lt;tbody&gt;
 &lt;tr&gt;
 &lt;td&gt;Two transactions, opposite order&lt;/td&gt;
 &lt;td&gt;the row locks the statements take&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;documented (PostgreSQL manual&amp;rsquo;s example)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Shared lock, then update&lt;/td&gt;
 &lt;td&gt;shared locks from &lt;code&gt;FOR SHARE&lt;/code&gt;, or from plain reads at MySQL&amp;rsquo;s SERIALIZABLE&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock with &lt;code&gt;FOR SHARE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;measured on MySQL 8.4.13 at SERIALIZABLE: 906 in 20 s, 16 sessions, median of 3 runs&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Check, then insert&lt;/td&gt;
 &lt;td&gt;gap locks from a search that found nothing&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;no gap lock, and no protection against a second insert&lt;/td&gt;
 &lt;td&gt;no gap locks, no deadlock, and no protection either&lt;/td&gt;
 &lt;td&gt;measured on MySQL 8.4.13 and PostgreSQL 18.6 (MySQL READ COMMITTED included)&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Duplicate insert&lt;/td&gt;
 &lt;td&gt;shared lock left by the duplicate-key error&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;waits for the first inserter instead&lt;/td&gt;
 &lt;td&gt;documented (MySQL manual&amp;rsquo;s three-session example); READ COMMITTED and PostgreSQL reasoned&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Child insert, then parent update&lt;/td&gt;
 &lt;td&gt;foreign-key lock on the parent row&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;queues; the key-share lock does not block the update&lt;/td&gt;
 &lt;td&gt;measured on MySQL 8.4.13 (REPEATABLE READ) and PostgreSQL 18.6; MySQL READ COMMITTED from the manual&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Unindexed &lt;code&gt;UPDATE&lt;/code&gt;&lt;/td&gt;
 &lt;td&gt;locks on every row it reads&lt;/td&gt;
 &lt;td&gt;every scanned row locked&lt;/td&gt;
 &lt;td&gt;non-matching rows released&lt;/td&gt;
 &lt;td&gt;only changed rows locked&lt;/td&gt;
 &lt;td&gt;documented&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Worker pool&lt;/td&gt;
 &lt;td&gt;the opposite-order shape, in identical workers&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;can deadlock&lt;/td&gt;
 &lt;td&gt;reasoned&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
 &lt;td&gt;Parallel replica apply&lt;/td&gt;
 &lt;td&gt;replica worker threads&lt;/td&gt;
 &lt;td&gt;retried up to 10 times&lt;/td&gt;
 &lt;td&gt;retried up to 10 times&lt;/td&gt;
 &lt;td&gt;logical replication in PostgreSQL 18: rare, retried&lt;/td&gt;
 &lt;td&gt;documented&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The error the application gets is the same for every row of that table, which is why restarting the transaction treats the symptom of each and the cause of none. The useful first question, when one turns up, is whether the locks in the cycle are ones the SQL asked for. If the deadlock log names a table or an index that the statements never mention, it is one of the middle rows, and reordering the code rarely helps; the fix is in the schema or the isolation level. Reading that log is where &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/" &gt;Part 2&lt;/a&gt; starts.&lt;/p&gt;</description></item><item><title>Uniqueness and Selectivity: The Two Numbers That Drive Query Plans</title><link>https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/</link><pubDate>Mon, 23 Dec 2024 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/uniqueness-and-selectivity-the-two-numbers-that-drive-query-plans/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Uniqueness and Selectivity: The Two Numbers That Drive Query Plans" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Uniqueness governs correctness, selectivity governs performance. The interesting parts of both live in the edge cases: partial unique indexes and their UPSERT targeting quirks, the way partitioning weakens every uniqueness guarantee, correlated columns that defeat planner assumptions, stale statistics that turn a 5ms query into a 5-minute one. Declaring the constraints the planner can see and keeping its statistics fresh buys more than any amount of query rewriting.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Everyone who works with relational databases knows &lt;code&gt;UNIQUE&lt;/code&gt;. What they often don&amp;rsquo;t know is how it behaves under partitioning, how &lt;code&gt;ON CONFLICT&lt;/code&gt; targets it (and doesn&amp;rsquo;t), and what the planner actually does with it beyond rejecting duplicates. Selectivity is in the same category. The definition is trivial, but the behavior that matters lives in composite column ordering, stale statistics, and the correlated-columns problem that breaks the planner&amp;rsquo;s core assumption.&lt;/p&gt;
&lt;p&gt;This is the territory where &amp;ldquo;the query is correct&amp;rdquo; and &amp;ldquo;the query is fast&amp;rdquo; stop being the same question, and both depend on what the database can actually prove about the data. The constraints are the contract between the schema and the planner. Everything else is inference.&lt;/p&gt;
&lt;h2 id="partial-and-filtered-unique-indexes"&gt;Partial and filtered unique indexes
&lt;/h2&gt;&lt;p&gt;PostgreSQL supports partial unique indexes: uniqueness enforced only over rows matching a predicate. This is the right tool for the common real-world case &amp;ldquo;email must be unique among active users&amp;rdquo;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- PostgreSQL: email unique only among non-soft-deleted rows.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INDEX&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users_active_email_uniq&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;A plain &lt;code&gt;UNIQUE (email)&lt;/code&gt; forces a choice: either allow re-registration (and lose referential integrity by reusing emails across deleted and active rows) or block it (and frustrate users whose accounts were long ago soft-deleted). The partial index lets both coexist.&lt;/p&gt;
&lt;p&gt;MySQL doesn&amp;rsquo;t support partial unique indexes directly. The workaround exploits MySQL&amp;rsquo;s treatment of NULL as distinct under &lt;code&gt;UNIQUE&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL idiom: generated column that&amp;#39;s NULL for deleted users.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email_active&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;VARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;255&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;GENERATED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ALWAYS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;CASE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHEN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;THEN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;END&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VIRTUAL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ADD&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UNIQUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users_active_email_uniq&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email_active&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The constraint effectively fires only for rows where &lt;code&gt;email_active&lt;/code&gt; is non-NULL: exactly partial-index semantics, just expressed through a generated column. Awkward to write, but portable-ish and the ORMs catch on eventually.&lt;/p&gt;
&lt;h2 id="partitioned-tables-force-uniqueness-compromises"&gt;Partitioned tables force uniqueness compromises
&lt;/h2&gt;&lt;p&gt;Partitioned tables in both PostgreSQL and MySQL require the partition key to be part of every unique constraint - including the primary key. The rule exists for correctness: without the partition key in the constraint, the database would have to scan every partition on every insert to enforce uniqueness, defeating the point of partitioning.&lt;/p&gt;
&lt;p&gt;The practical consequence is that &lt;code&gt;PRIMARY KEY (id)&lt;/code&gt; isn&amp;rsquo;t allowed on a table partitioned by &lt;code&gt;created_at&lt;/code&gt;. It has to become &lt;code&gt;PRIMARY KEY (id, created_at)&lt;/code&gt;. The same applies to every other unique constraint: &lt;code&gt;UNIQUE (email)&lt;/code&gt; on a users table partitioned by region becomes &lt;code&gt;UNIQUE (email, region)&lt;/code&gt;, which quietly weakens the guarantee. The schema now allows the same email to exist in multiple regions, whether or not the application ever intended that.&lt;/p&gt;
&lt;p&gt;This is one of the sharper trade-offs in partitioning decisions. A uniqueness guarantee the schema used to provide gets weaker, and point lookups that used to be single-row &lt;code&gt;const&lt;/code&gt; accesses become &lt;code&gt;ref&lt;/code&gt; lookups because the full primary key isn&amp;rsquo;t spelled out in every query. &lt;a class="link" href="https://explainanalyze.com/p/designing-partitioning-you-dont-have-to-babysit/#what-actually-belongs-in-the-partition-key" &gt;How Partitioning Turns &lt;code&gt;WHERE id = 12345&lt;/code&gt; Into a 36-Partition Scan&lt;/a&gt; covers the full picture, including why partitioning by the primary key itself (when the PK is monotonically increasing) sidesteps the trade-off entirely.&lt;/p&gt;
&lt;h2 id="upsert-targeting-is-more-specific-than-it-looks"&gt;UPSERT targeting is more specific than it looks
&lt;/h2&gt;&lt;p&gt;&lt;code&gt;INSERT ... ON CONFLICT&lt;/code&gt; (PostgreSQL) and &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; (MySQL) bind to specific unique constraints, not to &amp;ldquo;any uniqueness that happens to apply.&amp;rdquo; The difference between the two engines is where most of the subtle bugs live.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;PostgreSQL is explicit.&lt;/strong&gt; &lt;code&gt;ON CONFLICT (email)&lt;/code&gt; requires a unique constraint or unique index exactly matching &lt;code&gt;email&lt;/code&gt;. If none exists, the statement errors out. If a partial unique index exists instead of a plain one, &lt;code&gt;ON CONFLICT (email)&lt;/code&gt; does not match it; you need the full predicate:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Must match the partial index&amp;#39;s predicate to target it.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;INTO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;VALUES&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;alice@example.com&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Alice&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;CONFLICT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;deleted_at&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;DO&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;UPDATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;EXCLUDED&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;If the partial index changes (predicate tightened, column added), every &lt;code&gt;ON CONFLICT&lt;/code&gt; targeting it has to change too. This is explicit coupling, but it&amp;rsquo;s coupling.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MySQL is implicit and more dangerous.&lt;/strong&gt; &lt;code&gt;ON DUPLICATE KEY UPDATE&lt;/code&gt; fires on conflict with any unique key on the table, not just the one the query author had in mind. If the table has &lt;code&gt;UNIQUE (email)&lt;/code&gt; and &lt;code&gt;UNIQUE (external_id)&lt;/code&gt;, an insert that conflicts on either key triggers the update. For rows where the inserted &lt;code&gt;email&lt;/code&gt; matches one existing row and the &lt;code&gt;external_id&lt;/code&gt; matches a different one, the behavior depends on which index is checked first and is undefined as far as the language is concerned.&lt;/p&gt;
&lt;p&gt;The practical implication: adding a new unique key to a table can silently change the semantics of every existing &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; against that table. There&amp;rsquo;s no error, no warning, just different behavior on the next conflict that falls into the new key&amp;rsquo;s path. On large schemas with dozens of unique keys, this is the UPSERT equivalent of action at a distance.&lt;/p&gt;
&lt;p&gt;The mitigation on MySQL is to prefer &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; only when there&amp;rsquo;s a single obvious unique key, and to reach for &lt;code&gt;REPLACE&lt;/code&gt; or explicit &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; + conditional &lt;code&gt;UPDATE&lt;/code&gt;/&lt;code&gt;INSERT&lt;/code&gt; flows when the semantics need to be explicit.&lt;/p&gt;
&lt;h2 id="unique-indexes-also-concentrate-deadlock-pressure"&gt;Unique indexes also concentrate deadlock pressure
&lt;/h2&gt;&lt;p&gt;Two deadlock patterns are specific to unique indexes and show up almost nowhere else:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Duplicate-key inserts take locks even when they fail.&lt;/strong&gt; When InnoDB detects a duplicate on insert, it doesn&amp;rsquo;t just raise the error; it first acquires a shared next-key lock on the conflicting row. Under &lt;code&gt;REPEATABLE READ&lt;/code&gt; (the default), that lock covers the gap too. Two concurrent transactions inserting near the same unique key can deadlock on those shared locks before either sees the duplicate-key error. The most common production signature: a batch-upsert worker hitting the same hot row ranges from multiple threads.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;ON DUPLICATE KEY UPDATE&lt;/code&gt; batches deadlock when key ordering differs.&lt;/strong&gt; Each row in a batch insert acquires its lock when the row is processed, not when the batch starts. Two batches touching overlapping keys &lt;code&gt;(A, B)&lt;/code&gt; vs &lt;code&gt;(B, A)&lt;/code&gt; take locks in opposite order and cycle. The fix is either sorting rows by unique key before the batch (so lock acquisition order is consistent across workers) or switching to &lt;code&gt;INSERT ... ON CONFLICT DO NOTHING&lt;/code&gt; plus a separate targeted &lt;code&gt;UPDATE&lt;/code&gt; pass.&lt;/p&gt;
&lt;p&gt;Neither of these shows up the same way with non-unique indexes; the uniqueness check itself is what forces the extra locking. It&amp;rsquo;s the cost of making the database enforce the guarantee, and it scales badly once the hot-key set is small and write concurrency is high. (&lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-1-the-patterns/#unique-index-deadlocks-are-a-category-of-their-own" &gt;Database Deadlocks, Part 1&lt;/a&gt; covers the broader patterns; &lt;a class="link" href="https://explainanalyze.com/p/database-deadlocks-part-2-diagnosis-retries-and-prevention/#reach-for-nowait-and-skip-locked" &gt;Part 2&lt;/a&gt; covers reading the log, retries, and prevention.)&lt;/p&gt;
&lt;h2 id="composite-index-column-ordering"&gt;Composite index column ordering
&lt;/h2&gt;&lt;p&gt;The order of columns in a composite index is a selectivity decision that determines whether the index helps the query it was built for. The usual rules compress to three:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Equality filters before range filters.&lt;/strong&gt; An index on &lt;code&gt;(customer_id, created_at)&lt;/code&gt; is efficient for &lt;code&gt;WHERE customer_id = 42 AND created_at &amp;gt; '2026-01-01'&lt;/code&gt;. Reversed (&lt;code&gt;(created_at, customer_id)&lt;/code&gt;), the index has to scan a wide range of &lt;code&gt;created_at&lt;/code&gt; values and filter &lt;code&gt;customer_id&lt;/code&gt; as a secondary step, which is usually worse than a sequential scan.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;More selective column first for equality-only predicates.&lt;/strong&gt; For filters of the form &lt;code&gt;WHERE a = ? AND b = ?&lt;/code&gt;, the column with more distinct values goes first so the first lookup narrows more aggressively.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Match the query&amp;rsquo;s access pattern.&lt;/strong&gt; An index on &lt;code&gt;(a, b, c)&lt;/code&gt; serves queries filtering by &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;(a, b)&lt;/code&gt;, or &lt;code&gt;(a, b, c)&lt;/code&gt;. It does not serve queries filtering by &lt;code&gt;b&lt;/code&gt; alone, &lt;code&gt;c&lt;/code&gt; alone, or &lt;code&gt;(b, c)&lt;/code&gt;. The leading column is load-bearing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These interact with covering index considerations, sort order requirements, and the planner&amp;rsquo;s ability to combine multiple indexes via bitmap scans. But the starting point is: think about how the index will be read, not what columns are available to throw at it.&lt;/p&gt;
&lt;h3 id="mysql-clustered-indexes-flip-the-rule"&gt;MySQL clustered indexes flip the rule
&lt;/h3&gt;&lt;p&gt;The above applies cleanly to secondary indexes. The MySQL InnoDB primary key is a different animal: a clustered index, meaning the PK&amp;rsquo;s leaf pages are the table. The ordering of PK columns decides physical row order on disk, and that often matters more than selectivity.&lt;/p&gt;
&lt;p&gt;The canonical example is &lt;code&gt;PRIMARY KEY (tenant_id, id)&lt;/code&gt; on a multi-tenant table. &lt;code&gt;tenant_id&lt;/code&gt; has maybe 10K distinct values (low selectivity); &lt;code&gt;id&lt;/code&gt; is near-unique. By &amp;ldquo;most selective first,&amp;rdquo; the answer would be &lt;code&gt;(id, tenant_id)&lt;/code&gt;, and it would be wrong:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Physical clustering.&lt;/strong&gt; All rows for one tenant sit contiguously in the B-tree. Tenant-scoped range scans read a narrow slice of pages sequentially, and the buffer pool caches a single tenant&amp;rsquo;s hot data together. &lt;code&gt;(id, tenant_id)&lt;/code&gt; scatters that same tenant&amp;rsquo;s rows across the whole table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Secondary index lookups cost less.&lt;/strong&gt; InnoDB secondary indexes store the PK, not a row pointer. A query that uses a secondary index and then needs a full row does a PK lookup per match. With &lt;code&gt;(tenant_id, id)&lt;/code&gt;, those lookups for one tenant cluster together. With &lt;code&gt;(id, tenant_id)&lt;/code&gt;, each is random I/O across the table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insert locality.&lt;/strong&gt; If &lt;code&gt;id&lt;/code&gt; is monotonically increasing within a tenant, inserts land on recent pages per tenant, avoiding page splits scattered across the index.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The rule for an InnoDB PK is: put the column that represents the dominant access pattern first, even if it&amp;rsquo;s less selective. Selectivity cuts rows; clustering cuts I/O. On a large clustered index, I/O usually dominates.&lt;/p&gt;
&lt;p&gt;This is also why &lt;code&gt;PRIMARY KEY (id)&lt;/code&gt; plus &lt;code&gt;INDEX (tenant_id)&lt;/code&gt; on a multi-tenant table is often slower than &lt;code&gt;PRIMARY KEY (tenant_id, id)&lt;/code&gt;; the secondary index forces a PK-lookup hop on every read that the clustered choice avoids entirely.&lt;/p&gt;
&lt;p&gt;PostgreSQL&amp;rsquo;s primary key is a separate B-tree unique index, not clustered (a &lt;code&gt;CLUSTER&lt;/code&gt; command exists but isn&amp;rsquo;t maintained as rows are inserted), so the ordering logic there stays closer to the secondary-index rules.&lt;/p&gt;
&lt;h2 id="the-planner-doesnt-read-the-data---it-reads-statistics"&gt;The planner doesn&amp;rsquo;t read the data - it reads statistics
&lt;/h2&gt;&lt;p&gt;The planner&amp;rsquo;s entire decision-making process rests on statistics that summarize the data, not the data itself. PostgreSQL&amp;rsquo;s per-column statistics live in &lt;code&gt;pg_stats&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;span class="lnt"&gt;9
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;attname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n_distinct&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- estimated distinct values (negative means fraction)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;null_frac&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- fraction of rows that are NULL
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;most_common_vals&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- top values by frequency
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;most_common_freqs&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- corresponding frequencies
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;histogram_bounds&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;-- distribution of non-common values
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pg_stats&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tablename&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;orders&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;attname&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;customer_id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;MySQL exposes similar information through &lt;code&gt;information_schema.STATISTICS&lt;/code&gt; and &lt;code&gt;INNODB_TABLESTATS&lt;/code&gt;, though less granularly than PostgreSQL&amp;rsquo;s statistics. MySQL lacks per-column histograms on most versions (8.0+ has optional histograms, off by default).&lt;/p&gt;
&lt;p&gt;These statistics are gathered by explicit &lt;code&gt;ANALYZE&lt;/code&gt; in PostgreSQL and maintained automatically by InnoDB in MySQL. They go stale between runs. A table that was analyzed at 10M rows and is now 200M rows has planner statistics that no longer reflect reality. Join reorderings based on those estimates are decisions made on outdated data.&lt;/p&gt;
&lt;p&gt;The usual symptom is a query that was fast yesterday and slow today, with no schema or query change. The planner&amp;rsquo;s row estimate for some step has drifted far enough from reality that the plan shape flipped: nested loop where it should have been hash join, or a sequential scan where an index seek would have won. &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; with its estimated-vs-actual row counts is the fastest way to confirm this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;EXPLAIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Index Scan using orders_customer_id_idx
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- (cost=0.43..1234.56 rows=1000 width=128)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- (actual time=0.123..45.678 rows=180000 loops=1)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The &lt;code&gt;rows=1000&lt;/code&gt; is the estimate. The &lt;code&gt;actual rows=180000&lt;/code&gt; is reality. A ratio of 100x+ between them is the signal. The fix is statistical (refresh stats, increase the statistics target for that column, add extended statistics for correlated columns) and not a query rewrite.&lt;/p&gt;
&lt;h2 id="cardinality-estimation-errors-and-their-shape"&gt;Cardinality estimation errors and their shape
&lt;/h2&gt;&lt;p&gt;The single most common cause of bad query plans in production is a bad row-count estimate on an intermediate step. Two flavors, each with distinctive symptoms:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Underestimates.&lt;/strong&gt; The planner thinks a step will return 10 rows, actually returns 10 million. The plan picks a nested loop (good for a small outer side), which now runs 10 million iterations. A query that should have been a 50ms hash join takes 50 minutes. The telltale sign in &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; is &lt;code&gt;loops=10000000&lt;/code&gt; on an inner node that was costed for a handful.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Overestimates.&lt;/strong&gt; The planner thinks 10 million rows, actually 10. The plan allocates a hash table sized for millions, spills to disk under memory pressure, and runs a 5ms lookup in 5 seconds. Less common but more insidious, because the query didn&amp;rsquo;t &amp;ldquo;fail&amp;rdquo; in any obvious way; it just used more memory and I/O than it needed.&lt;/p&gt;
&lt;p&gt;Both are failures of the statistics, not the query. Both are especially hard to diagnose because the query text is identical in the fast and slow cases; only the planner&amp;rsquo;s belief about the data changed. When the ratio between estimated and actual is large and consistent, the problem is upstream of the query.&lt;/p&gt;
&lt;h2 id="correlated-columns-break-the-independence-assumption"&gt;Correlated columns break the independence assumption
&lt;/h2&gt;&lt;p&gt;The planner estimates the selectivity of a compound predicate &lt;code&gt;WHERE a = x AND b = y&lt;/code&gt; by multiplying the individual selectivities, assuming the columns are statistically independent. When they&amp;rsquo;re not, the estimate can be off by orders of magnitude.&lt;/p&gt;
&lt;p&gt;The canonical example is &lt;code&gt;(country, state)&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;EXPLAIN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;addresses&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;US&amp;#39;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;CA&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Estimate: (0.25) * (0.02) * N = 0.5% of rows
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Reality: ~2% of rows - state = &amp;#39;CA&amp;#39; implies country = &amp;#39;US&amp;#39;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The planner assumed the two filters cut the rowcount independently. In reality, &lt;code&gt;state = 'CA'&lt;/code&gt; already determines &lt;code&gt;country = 'US'&lt;/code&gt; (there are no California rows with a different country) so the compound filter isn&amp;rsquo;t as selective as the multiplication suggests.&lt;/p&gt;
&lt;p&gt;PostgreSQL 10+ supports extended statistics to fix this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;STATISTICS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country_state_corr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dependencies&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ndistinct&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;country&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;state&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;addresses&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ANALYZE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;addresses&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;The &lt;code&gt;dependencies&lt;/code&gt; statistic captures functional dependencies (one column determines another); &lt;code&gt;ndistinct&lt;/code&gt; captures the distinct combinations of the column set. Both are used during planning to correct the independence-assumption multiplication.&lt;/p&gt;
&lt;p&gt;MySQL has no equivalent. Correlated-column estimation errors there are harder to fix at the planner level; the workaround is usually to restructure the query (force a specific join order, introduce an intermediate CTE, or add a covering index that captures the correlated access pattern directly).&lt;/p&gt;
&lt;h2 id="unique-as-a-planner-signal-not-just-a-guardrail"&gt;UNIQUE as a planner signal, not just a guardrail
&lt;/h2&gt;&lt;p&gt;A &lt;code&gt;UNIQUE&lt;/code&gt; constraint is also a proof the planner can use. Knowing a column is unique lets the optimizer reason about the shape of joins and aggregates in ways it can&amp;rsquo;t when uniqueness is only implicit:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Deduplication elimination.&lt;/strong&gt; &lt;code&gt;SELECT DISTINCT u.id FROM users u JOIN orders o ON o.user_id = u.id&lt;/code&gt; can skip the &lt;code&gt;DISTINCT&lt;/code&gt; step entirely if the planner knows &lt;code&gt;users.id&lt;/code&gt; is unique. The join already produces at most one row per &lt;code&gt;u.id&lt;/code&gt; per matching order, and the &lt;code&gt;DISTINCT&lt;/code&gt; becomes a no-op. Without the declared uniqueness, the planner has to run the dedup pass.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Join elimination.&lt;/strong&gt; When joining A to B on a unique column of B, and selecting only columns from A, the planner can drop the join entirely in some cases (it proved the join doesn&amp;rsquo;t change the output). This is a real optimization on star-schema queries.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reorderable joins.&lt;/strong&gt; Unique constraints make certain join orderings provably equivalent, giving the optimizer more plan shapes to choose from. The more plans it can try, the more likely it finds a good one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Index-only scan eligibility.&lt;/strong&gt; Unique indexes are natural targets for index-only scans, which skip the heap/table access when every column the query needs is already in the index.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Schemas that leave uniqueness implicit (enforced in application code, promised in a wiki) can still produce correct results, but the planner can&amp;rsquo;t trust assumptions it can&amp;rsquo;t see. The constraint is what turns uniqueness from a property of the data into a property of the schema that the planner reads as a fact.&lt;/p&gt;
&lt;h2 id="what-unique-tells-a-schema-reading-model"&gt;What UNIQUE tells a schema-reading model
&lt;/h2&gt;&lt;p&gt;The planner isn&amp;rsquo;t the only consumer of declared uniqueness. Schema-reading assistants (Copilot, MCP-backed agents, text-to-SQL tools) read &lt;code&gt;information_schema.TABLE_CONSTRAINTS&lt;/code&gt; and &lt;code&gt;pg_constraint&lt;/code&gt; the same way they read column types. A declared &lt;code&gt;UNIQUE&lt;/code&gt; is the only signal in the catalog that says &amp;ldquo;at most one row per X.&amp;rdquo; Without it, the model has no way to prove 1:1 semantics and either hedges with a defensive &lt;code&gt;LIMIT 1&lt;/code&gt; it can&amp;rsquo;t justify or writes &lt;code&gt;GROUP BY&lt;/code&gt; / &lt;code&gt;DISTINCT&lt;/code&gt; passes that shouldn&amp;rsquo;t be necessary. &lt;code&gt;ON CONFLICT&lt;/code&gt; and &lt;code&gt;ON DUPLICATE KEY UPDATE&lt;/code&gt; targeting is especially fragile: the model picks the column name that matches the prompt (&amp;ldquo;upsert by email&amp;rdquo;) and the query either fails at runtime because no unique constraint exists on that column, or silently targets a different constraint than intended.&lt;/p&gt;
&lt;p&gt;Selectivity is the part the model has even less access to. Planner statistics (&lt;code&gt;pg_stats.n_distinct&lt;/code&gt;, MySQL&amp;rsquo;s &lt;code&gt;information_schema.STATISTICS&lt;/code&gt; cardinality estimates) aren&amp;rsquo;t part of the prompt for most schema-aware tools, and the model has no way to query them mid-generation. Asked &amp;ldquo;how do I speed this query up?&amp;rdquo; the assistant&amp;rsquo;s default answer is &amp;ldquo;add an index,&amp;rdquo; regardless of whether the indexed column has two distinct values or two million. The same schema discipline that keeps the planner honest (declared unique constraints on every at-most-one relationship, composite primary keys on bridge tables, column-level comments that describe the value shape) is what gives catalog-reading models enough context to produce queries that don&amp;rsquo;t require a second human pass.&lt;/p&gt;
&lt;h2 id="diagnosing-the-usual-suspects"&gt;Diagnosing the usual suspects
&lt;/h2&gt;&lt;p&gt;Three patterns cover most of the uniqueness/selectivity-shaped bugs in production:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&amp;ldquo;This query got slow and nothing changed.&amp;rdquo;&lt;/strong&gt; Run &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt;. Compare estimated to actual row counts on each node. A large ratio (10x+) means the planner has stale statistics, missing extended statistics on correlated columns, or both. Refresh stats with &lt;code&gt;ANALYZE&lt;/code&gt;; add extended statistics if a compound predicate is the source.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&amp;ldquo;I built an index and the planner ignores it.&amp;rdquo;&lt;/strong&gt; Check the column&amp;rsquo;s selectivity directly: distinct values over total. Below ~5%, a sequential scan is usually the right choice and the planner isn&amp;rsquo;t wrong. If selectivity is high, check for functions in the &lt;code&gt;WHERE&lt;/code&gt; clause (non-SARGable predicates), implicit type casts (an indexed &lt;code&gt;BIGINT&lt;/code&gt; column filtered with a &lt;code&gt;VARCHAR&lt;/code&gt; literal can fall off the index), or stale statistics underreporting the column&amp;rsquo;s uniqueness.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&amp;ldquo;My UPSERT corrupts data under load.&amp;rdquo;&lt;/strong&gt; Check which unique key it&amp;rsquo;s targeting. In MySQL, &lt;code&gt;ON DUPLICATE KEY UPDATE&lt;/code&gt; fires on conflict with any unique key, including ones added after the query was written. In PostgreSQL, partial unique indexes require the predicate in &lt;code&gt;ON CONFLICT&lt;/code&gt;; mismatches silently fall through to insert rather than update.&lt;/p&gt;
&lt;h2 id="the-mental-model"&gt;The mental model
&lt;/h2&gt;&lt;p&gt;Uniqueness and selectivity collapse to two questions that both the planner and the engineer need answered for every table and query:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;How many rows per key?&lt;/strong&gt; Uniqueness. Determines whether joins multiply, whether UPSERTs target the right constraint, and whether aggregations can be trusted.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How many distinct values relative to total?&lt;/strong&gt; Selectivity. Determines whether indexes help, which join order the planner picks, and how badly a compound filter will miss.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Both answers are visible to the planner if the constraints are declared and the statistics are current. Both become guesswork when they&amp;rsquo;re not. The habit that pays off isn&amp;rsquo;t heroic query tuning. It&amp;rsquo;s keeping the database&amp;rsquo;s model of the data honest: declare the unique constraints that exist (including composite ones on bridge tables), refresh statistics on busy tables, add extended statistics where correlation has burned you before, and read &lt;code&gt;EXPLAIN ANALYZE&lt;/code&gt; for the ratio between estimated and actual rows every time a query slows down.&lt;/p&gt;</description></item><item><title>Comment Your Schema</title><link>https://explainanalyze.com/p/comment-your-schema/</link><pubDate>Mon, 18 Nov 2024 00:00:00 +0000</pubDate><guid>https://explainanalyze.com/p/comment-your-schema/</guid><description>&lt;img src="https://explainanalyze.com/" alt="Featured image of post Comment Your Schema" /&gt;&lt;div class="tldr-box"&gt;
 &lt;strong&gt;TL;DR&lt;/strong&gt;
 &lt;div&gt;Every major database engine lets you attach comments to tables and columns: descriptions that live in the schema itself and show up in every tool that reads it. They cost nothing to add, require no downtime, and make every schema dump, ER diagram, and monitoring tool more useful. Almost nobody uses them.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;A new engineer is debugging a customer support ticket: &amp;ldquo;order #4421 shows up as &amp;lsquo;Failed&amp;rsquo; in the admin tool but the customer received it.&amp;rdquo; She opens the &lt;code&gt;orders&lt;/code&gt; table in DataGrip and finds &lt;code&gt;status TINYINT NOT NULL&lt;/code&gt;. The admin tool displays &amp;ldquo;Failed&amp;rdquo; when status = 2. The fulfillment service ships when status = 3. The reporting view treats status = 1 as &amp;ldquo;active.&amp;rdquo; None of the three definitions are in the schema, and nobody on the team remembers the original mapping; the engineer who designed the table left eight months ago.&lt;/p&gt;
&lt;p&gt;Resolving the ticket takes ninety minutes: grep three service codebases, find three different mappings, reconcile them against the actual row&amp;rsquo;s status = 2, draft the customer email. Every part of that work happens because the integer values aren&amp;rsquo;t grounded anywhere the database knows about, and the code&amp;rsquo;s three guesses disagree. The mechanism that would have grounded them in the catalog has existed in every major database engine since the 1990s. The team has just never written it down.&lt;/p&gt;
&lt;h2 id="what-schema-comments-are"&gt;What schema comments are
&lt;/h2&gt;&lt;p&gt;Schema comments are metadata strings attached directly to database objects: tables, columns, indexes, views. They&amp;rsquo;re stored in the database catalog and exposed through standard metadata queries.&lt;/p&gt;
&lt;p&gt;In PostgreSQL:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Customer purchase orders. One row per checkout.&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end_date&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;NULL means order is still in progress&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;In MySQL:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt; 1
&lt;/span&gt;&lt;span class="lnt"&gt; 2
&lt;/span&gt;&lt;span class="lnt"&gt; 3
&lt;/span&gt;&lt;span class="lnt"&gt; 4
&lt;/span&gt;&lt;span class="lnt"&gt; 5
&lt;/span&gt;&lt;span class="lnt"&gt; 6
&lt;/span&gt;&lt;span class="lnt"&gt; 7
&lt;/span&gt;&lt;span class="lnt"&gt; 8
&lt;/span&gt;&lt;span class="lnt"&gt; 9
&lt;/span&gt;&lt;span class="lnt"&gt;10
&lt;/span&gt;&lt;span class="lnt"&gt;11
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MODIFY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TINYINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Or at table creation:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AUTO_INCREMENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;References users.id&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TINYINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;total_cents&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;BIGINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Order total in cents, not dollars&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end_date&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;DATE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;DEFAULT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;NULL = order still in progress&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;Customer purchase orders. One row per checkout.&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;SQL Server uses extended properties, Oracle uses &lt;code&gt;COMMENT ON&lt;/code&gt;. The syntax varies. The concept is universal.&lt;/p&gt;
&lt;h2 id="where-comments-show-up"&gt;Where comments show up
&lt;/h2&gt;&lt;p&gt;This is the part that makes comments more useful than a wiki page or a README. Because they live in the catalog, they propagate automatically to every tool that reads schema metadata.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Schema dumps.&lt;/strong&gt; &lt;code&gt;pg_dump&lt;/code&gt; and &lt;code&gt;mysqldump&lt;/code&gt; include comments in the output. Anyone restoring a backup or reviewing a migration gets the context without looking elsewhere.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ER diagram tools.&lt;/strong&gt; DBeaver, DataGrip, pgAdmin, MySQL Workbench all render column comments in schema viewers and diagrams. Hover over a column and the description is right there.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;information_schema and catalog queries.&lt;/strong&gt; Any script, tool, or automation that queries metadata picks up comments for free.&lt;/p&gt;
&lt;p&gt;In PostgreSQL:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;span class="lnt"&gt;5
&lt;/span&gt;&lt;span class="lnt"&gt;6
&lt;/span&gt;&lt;span class="lnt"&gt;7
&lt;/span&gt;&lt;span class="lnt"&gt;8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Get a table comment
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;obj_description&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;orders&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;pg_class&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Get a column comment
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;col_description&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;orders&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- Or just use psql
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;In MySQL:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;span class="lnt"&gt;4
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;COLUMN_COMMENT&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;information_schema&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;COLUMNS&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;WHERE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TABLE_SCHEMA&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;your_database&amp;#39;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;AND&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE_NAME&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;orders&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;&lt;strong&gt;ORM introspection.&lt;/strong&gt; Many ORMs and code generators that reverse-engineer models from databases will pull comments into generated code as docstrings or annotations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Monitoring and alerting tools.&lt;/strong&gt; When an alert fires about a table or column, the comment provides immediate context without requiring someone to look up external documentation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CI pipelines and schema validation.&lt;/strong&gt; Linting tools can check whether new tables and columns have comments, the same way code linters check for function docstrings.&lt;/p&gt;
&lt;p&gt;The point is that comments flow through the entire toolchain. You write them once, in one place, and every tool that reads the schema benefits, without configuration, without plugins, without maintaining anything separately.&lt;/p&gt;
&lt;h2 id="what-goes-wrong-without-them"&gt;What goes wrong without them
&lt;/h2&gt;&lt;p&gt;The absence of comments creates a category of problems that compounds over time. Onboarding takes longer than it should: every new engineer who encounters &lt;code&gt;status TINYINT&lt;/code&gt; has to ask someone or investigate. Multiply that by every ambiguous column in every table across every service, and it stops being a one-time cost. It&amp;rsquo;s paid every time someone new touches the schema.&lt;/p&gt;
&lt;p&gt;Debugging becomes archaeology. When something breaks at 2am and you&amp;rsquo;re looking at a table with columns named &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;flag&lt;/code&gt;, &lt;code&gt;ref_id&lt;/code&gt;, and &lt;code&gt;config&lt;/code&gt;, all with no comments, you&amp;rsquo;re not debugging. You&amp;rsquo;re reverse-engineering institutional knowledge that should have been written down.&lt;/p&gt;
&lt;p&gt;Schema reviews lose context too. A migration that adds &lt;code&gt;is_processed TINYINT(1) DEFAULT 0&lt;/code&gt; looks fine syntactically; processed by what, when, and is it idempotent? A comment turns the review from &amp;ldquo;does this look right?&amp;rdquo; into &amp;ldquo;does this match what we agreed on?&amp;rdquo;&lt;/p&gt;
&lt;p&gt;External documentation drifts the moment someone adds a column or changes a status code without updating the doc. Comments live in the schema itself. They move with &lt;code&gt;ALTER TABLE&lt;/code&gt;. They show up in every dump. They can&amp;rsquo;t be in a different repo than the data they describe.&lt;/p&gt;
&lt;h2 id="what-to-comment"&gt;What to comment
&lt;/h2&gt;&lt;p&gt;Not everything needs a comment. A column called &lt;code&gt;created_at TIMESTAMP NOT NULL&lt;/code&gt; is self-documenting. Focus on the columns where the schema doesn&amp;rsquo;t tell the whole story:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Status and type columns.&lt;/strong&gt; What do the values mean? &lt;code&gt;1=active, 2=suspended, 3=closed&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Nullable columns where NULL has meaning.&lt;/strong&gt; Does NULL mean &amp;ldquo;not set,&amp;rdquo; &amp;ldquo;not applicable,&amp;rdquo; or &amp;ldquo;ongoing&amp;rdquo;?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ID columns that reference other tables without foreign keys.&lt;/strong&gt; &lt;code&gt;owner_id BIGINT COMMENT 'References users.id'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Columns with non-obvious units.&lt;/strong&gt; &lt;code&gt;total_cents&lt;/code&gt; vs &lt;code&gt;total&lt;/code&gt; (dollars? cents? units?), &lt;code&gt;duration&lt;/code&gt; (seconds? milliseconds? minutes?).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Columns with business logic encoded in values.&lt;/strong&gt; &lt;code&gt;plan_type TINYINT COMMENT '1=free, 2=starter, 3=pro, 4=enterprise'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tables themselves.&lt;/strong&gt; What does this table represent? One row per what?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A good table comment answers: &amp;ldquo;What is one row in this table?&amp;rdquo; A good column comment answers: &amp;ldquo;What does this value mean when I see it in a query result?&amp;rdquo;&lt;/p&gt;
&lt;h2 id="adding-comments-to-an-existing-schema"&gt;Adding comments to an existing schema
&lt;/h2&gt;&lt;p&gt;This is the part that makes the cost-benefit ratio hard to argue against.&lt;/p&gt;
&lt;p&gt;In PostgreSQL, &lt;code&gt;COMMENT ON&lt;/code&gt; is a catalog-only operation. It takes no locks on the table. It doesn&amp;rsquo;t rewrite data. It doesn&amp;rsquo;t block reads or writes. On a table with 500 million rows, it completes in milliseconds.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- This is instant. No lock. No downtime. No risk.
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;IS&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;p&gt;In MySQL, &lt;code&gt;ALTER TABLE ... MODIFY COLUMN&lt;/code&gt; with a comment is a metadata-only change in most cases with InnoDB online DDL, but behavior depends on the version and what else is in the &lt;code&gt;MODIFY&lt;/code&gt;. For comment-only changes on MySQL 8.0+, the &lt;code&gt;ALGORITHM=INSTANT&lt;/code&gt; path applies. On older versions or when combined with type changes, it may trigger a table rebuild.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;div class="chroma"&gt;
&lt;table class="lntable"&gt;&lt;tr&gt;&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code&gt;&lt;span class="lnt"&gt;1
&lt;/span&gt;&lt;span class="lnt"&gt;2
&lt;/span&gt;&lt;span class="lnt"&gt;3
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;
&lt;td class="lntd"&gt;
&lt;pre tabindex="0" class="chroma"&gt;&lt;code class="language-sql" data-lang="sql"&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="c1"&gt;-- MySQL 8.0+: instant for comment-only changes
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;TABLE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;MODIFY&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COLUMN&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;TINYINT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NOT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="line"&gt;&lt;span class="cl"&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;COMMENT&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;div class="note-box"&gt;
 &lt;strong&gt;Zero-downtime operation&lt;/strong&gt;
 &lt;div&gt;In PostgreSQL, &lt;code&gt;COMMENT ON&lt;/code&gt; is a catalog-only update: no table lock, no rewrite, completes in milliseconds even on tables with hundreds of millions of rows. In MySQL 8.0+, comment-only changes go through the &lt;code&gt;ALGORITHM=INSTANT&lt;/code&gt; path. This is about as safe as database changes get.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The risk profile is as close to zero as database changes get. There&amp;rsquo;s no reason not to do this incrementally; comment a few columns every time you touch a table. Over time, the schema becomes self-documenting.&lt;/p&gt;
&lt;h2 id="generating-documentation-from-comments"&gt;Generating documentation from comments
&lt;/h2&gt;&lt;p&gt;Because comments live in the catalog, tools can extract them and produce browsable documentation automatically. A few worth knowing:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a class="link" href="https://schemaspy.org/" target="_blank" rel="noopener"
 &gt;SchemaSpy&lt;/a&gt;.&lt;/strong&gt; Java-based, generates interactive HTML with ER diagrams. Reads table and column comments from the catalog. Run it against your database and you get a full documentation site with relationships, comments, and diagrams; no manual authoring.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a class="link" href="https://github.com/k1LoW/tbls" target="_blank" rel="noopener"
 &gt;tbls&lt;/a&gt;.&lt;/strong&gt; A single Go binary, CI-friendly. Outputs Markdown, PlantUML, or SVG. Reads comments directly from the schema. Designed to run in pipelines: generate docs on every migration, commit them to the repo, and they stay in sync.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DataGrip / DBeaver.&lt;/strong&gt; Not doc generators per se, but both render column comments inline in their schema browsers. For teams already using these, comments become immediately visible without any extra tooling.&lt;/p&gt;
&lt;p&gt;The pattern is the same across all of them: comments in the schema become descriptions in the output. No separate documentation source to maintain. The schema is the source.&lt;/p&gt;
&lt;p&gt;For teams that want generated docs as part of CI, &lt;code&gt;tbls&lt;/code&gt; is the lowest-friction option: add it to your pipeline, point it at the database, and commit the Markdown output. Every migration that adds or changes a comment updates the docs automatically.&lt;/p&gt;
&lt;h2 id="the-rag-surface-most-teams-forget"&gt;The RAG surface most teams forget
&lt;/h2&gt;&lt;p&gt;Schema-reading assistants (Copilot, MCP-backed agents, text-to-SQL tools, retrieval-augmented coding models) start with the same catalog every human does: &lt;code&gt;information_schema&lt;/code&gt;, &lt;code&gt;pg_description&lt;/code&gt;, &lt;code&gt;\d+&lt;/code&gt;. If the catalog contains only column names and types, that&amp;rsquo;s the context the model gets. A column named &lt;code&gt;status TINYINT&lt;/code&gt; is ambiguous to the model for the same reason it&amp;rsquo;s ambiguous to a new engineer, except the model won&amp;rsquo;t ping the on-call channel; it will generate a plausible query and hand it back. Published studies on text-to-SQL accuracy have put the lift from adding column-level semantic descriptions as high as ~27%, not because models are bad at reading schemas, but because most schemas don&amp;rsquo;t tell them enough to read.&lt;/p&gt;
&lt;p&gt;Comments are the one catalog field that can carry business meaning. Every other metadata row is mechanical: type, nullability, length, constraint name. A comment on &lt;code&gt;orders.status&lt;/code&gt; (&lt;code&gt;'1=pending, 2=processing, 3=shipped, 4=delivered, 5=cancelled'&lt;/code&gt;) turns a blind guess into a grounded answer for any tool that reads the catalog, human or otherwise. It&amp;rsquo;s the cheapest RAG context a team can ship: no vector store, no separate doc pipeline, no sync problem; the description travels with the column it describes. If the team is rolling out database-aware AI assistants and hasn&amp;rsquo;t commented the ambiguous columns first, the assistants are working from less context than a new hire would get on day one.&lt;/p&gt;
&lt;h2 id="making-it-stick"&gt;Making it stick
&lt;/h2&gt;&lt;p&gt;The challenge isn&amp;rsquo;t the mechanism, it&amp;rsquo;s the habit. Comments rot just like any other documentation if they&amp;rsquo;re not maintained. A few things help:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Comment at creation time.&lt;/strong&gt; If the comment is part of the &lt;code&gt;CREATE TABLE&lt;/code&gt; or migration, it happens naturally. Retrofitting is always harder than including it from the start.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Add it to your migration template.&lt;/strong&gt; If your team uses a migration tool, add comment fields to the template. Make the absence visible rather than the default.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lint for it.&lt;/strong&gt; A simple CI check can flag tables or columns without comments. It doesn&amp;rsquo;t have to block merges - even a warning changes behavior over time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Treat comments as part of the schema, not as documentation.&lt;/strong&gt; When a column&amp;rsquo;s semantics change, the comment changes in the same migration. Same PR, same review.&lt;/p&gt;
&lt;h2 id="the-trade-offs"&gt;The trade-offs
&lt;/h2&gt;&lt;p&gt;Comments aren&amp;rsquo;t a substitute for all documentation. They&amp;rsquo;re good at describing what a column or table is, not how a multi-table workflow operates. System-level documentation (data flow diagrams, service interaction maps, runbooks) still belongs somewhere else.&lt;/p&gt;
&lt;div class="warning-box"&gt;
 &lt;strong&gt;Watch out&lt;/strong&gt;
 &lt;div&gt;Stale comments are worse than no comments; they actively mislead. A column that says &lt;code&gt;'1=active, 2=inactive'&lt;/code&gt; when the code now also uses &lt;code&gt;3=suspended&lt;/code&gt; will send someone down the wrong path. Treat comment updates as part of the migration, not a follow-up task.&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There&amp;rsquo;s also a maintenance cost. Stale comments are worse than no comments because they actively mislead. A column that says &lt;code&gt;'1=active, 2=inactive'&lt;/code&gt; when the code was updated to also use &lt;code&gt;3=suspended&lt;/code&gt; will send someone down the wrong path. The mitigation is treating comments as schema, not as a nice-to-have; they change when the schema changes, and a check in CI is what keeps that true after the people who cared have moved on (see &lt;a class="link" href="https://explainanalyze.com/p/schema-conventions-dont-survive-without-automation/" &gt;Schema Conventions Don&amp;rsquo;t Survive Without Automation&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;For teams with hundreds of tables and thousands of columns, retrofitting comments is a slow process. It&amp;rsquo;s not a weekend project. It&amp;rsquo;s an incremental habit that pays off over months.&lt;/p&gt;
&lt;h2 id="where-to-start"&gt;Where to start
&lt;/h2&gt;&lt;p&gt;Start with the columns that make people ask questions. The status column where 0/1/2 means something nobody can quote from memory. The nullable date that means &amp;ldquo;ongoing&amp;rdquo; in one place and &amp;ldquo;missing&amp;rdquo; in another. The &lt;a class="link" href="https://explainanalyze.com/p/primary-and-foreign-keys-explained-one-missing-index-50-ms-per-delete/" &gt;foreign key with no foreign key&lt;/a&gt;. Those are the columns where a one-line &lt;code&gt;COMMENT ON&lt;/code&gt; recovers more institutional knowledge per character than any other change a schema can absorb.&lt;/p&gt;</description></item></channel></rss>