<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tempest on Medium]]></title>
        <description><![CDATA[Stories by Tempest on Medium]]></description>
        <link>https://medium.com/@tempest_61922?source=rss-c2798f05e179------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gIDF0y6muzmdHjjyeBI_EQ.png</url>
            <title>Stories by Tempest on Medium</title>
            <link>https://medium.com/@tempest_61922?source=rss-c2798f05e179------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:34:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tempest_61922/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PostgreSQL Logical Replication and Schema Changes]]></title>
            <link>https://medium.com/@tempest_61922/postgresql-logical-replication-and-schema-changes-d646ca44ea35?source=rss-c2798f05e179------2</link>
            <guid isPermaLink="false">https://medium.com/p/d646ca44ea35</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[logical-replication]]></category>
            <dc:creator><![CDATA[Tempest]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 01:29:34 GMT</pubDate>
            <atom:updated>2025-12-03T02:49:04.458Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Key Insight:</strong> PostgreSQL logical replication does transmit schema information via Relation messages, but only when data is modified, not when DDL executes. This timing makes it problematic for read replicas but perfectly suited for caching systems.</p><p>The common wisdom is PostgreSQL logical replication doesn’t support schema changes. I thought so too, until building <a href="https://www.pgcache.com/">PgCache</a> forced me to understand the replication protocol in detail.</p><p>The reality is schema changes <em>are</em> transmitted in the stream, just not in a way that keeps read replicas synchronized. This distinction is crucial.</p><h3>What the Documentation Says</h3><p>The PostgreSQL documentation states plainly: “The database schema and DDL commands are not replicated.” This is technically accurate — ALTER TABLE, CREATE INDEX, and other DDL commands never appear in the logical replication stream.</p><p>But the statement is incomplete. It tells you what <em>isn’t</em> sent without clarifying what <em>is</em>.</p><p>If you stop at the headline claim, you’ll conclude that any system built on logical replication must handle schema changes entirely out of band. That’s true for DDL commands themselves. It’s not true for schema metadata.</p><h3><strong>What Appears in the Stream</strong></h3><p>What <em>does</em> appear in the stream are Relation messages. These are protocol messages that describe a table’s structure, including its name, columns, and column types. Most critically these messages arrive when data changes, not when the DDL runs.</p><p>The <a href="https://www.postgresql.org/docs/current/logical-replication-restrictions.html">documentation</a> describes this behavior:</p><blockquote>Before the first DML message for a given relation OID, a Relation message will be sent, describing the schema of that relation. Subsequently, a new Relation message will be sent if the relation’s definition has changed since the last Relation message was sent for it.</blockquote><p>If a table’s data never changes, no Relation message is ever sent for it.</p><figure><img alt="The Timing Problem — Schema changes only propagate when data is modified" src="https://cdn-images-1.medium.com/max/1024/1*MMIqROA7TYbjXWMDsDpDiw.png" /></figure><h3>The Timing Problem for Read Replicas</h3><p>Schema changes only propagate to subscribers when data is modified. Here’s what actually happens:</p><pre>1. Developer executes: <strong>ALTER TABLE users ADD COLUMN email VARCHAR(255)</strong><br>2. The DDL runs on the origin database<br>3. No message appears in the replication stream<br>4. Eventually, an <strong>INSERT</strong>, <strong>UPDATE</strong>, or <strong>DELETE</strong> is performed on the <strong>users</strong> table<br>5. PostgreSQL generates a Relation message with the updated schema<br>6. The Relation message is sent before the DML operation<br>7. Subscribers finally learn about the schema change</pre><p>If data in that table is never modified, the schema change will never arrive.</p><p><strong>For read replicas, this creates serious coordination challenges.</strong> Schema changes must be manually applied to each replica, and the timing is critical. Apply changes too early, and the replication stream might send data that doesn’t match the replica’s schema, breaking replication. Apply changes too late, and application queries will fail when they reference columns that don’t exist on the replica yet.</p><h3>Why Caches Can Tolerate This Timing</h3><p>Caches operate fundamentally differently than read replicas. A read replica must be authoritative, every query is expected to succeed with the data and schema the replica has. A cache is opportunistic, it can miss, fall back to the origin, and refresh its understanding. This distinction transforms a serious limitation into an inconvenience.</p><figure><img alt="Two different consumers, two different outcomes" src="https://cdn-images-1.medium.com/max/1024/1*lI19usVA13Gl65N7-qq6Ow.png" /></figure><h3>How PgCache Implements This Approach</h3><p>The insight that caches can afford to miss led to the approach used in <a href="https://www.pgcache.com/">PgCache</a>. Rather than needing to maintain a perfectly synchronized schema like a read replica, the schema is treated as metadata that can be refreshed on demand.</p><p>When a query arrives, PgCache tries to process it from cache. If successful, it returns cached data. If there’s any error, including schema-related errors, it automatically fails over to the origin database. The query succeeds, and the result gets cached with the new schema.</p><p>PgCache learns about schema in two ways:</p><ol><li><strong>For new tables:</strong> Proactively queries PostgreSQL to retrieve the initial schema.</li><li><strong>For known tables:</strong> Watches for Relation messages in the replication stream and compares them with the cached schema. When a change is detected, the entire table is invalidated and repopulated on demand.</li></ol><h3>Beyond Caching</h3><p>The same principle applies to any system that tolerates temporary inconsistency: ETL pipelines that can reprocess when schemas change, analytics systems that refresh on mismatch, audit logs that don’t need real-time schema accuracy. If your system has a fallback mechanism, delayed schema metadata becomes a design constraint rather than a blocker.</p><p>For those building on logical replication, the <a href="https://www.postgresql.org/docs/current/protocol-logical-replication.html">Logical Streaming Replication Protocol</a> documentation describes all message types in detail.</p><p>I’m building <a href="https://www.pgcache.com/">PgCache</a> in public and documenting what I learn along the way. If you’re interested in following the progress or have experience with database caching and logical replication, I’d love to hear from you. You can find me on <a href="https://bsky.app/profile/tempest98.bsky.social">Bluesky</a>, where I share updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d646ca44ea35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL query optimizations]]></title>
            <link>https://medium.com/@tempest_61922/postgresql-query-transforms-8ccba47943e3?source=rss-c2798f05e179------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ccba47943e3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Tempest]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 23:40:33 GMT</pubDate>
            <atom:updated>2025-10-23T23:51:20.466Z</atom:updated>
            <content:encoded><![CDATA[<p>I came across this <a href="https://blog.jooq.org/10-cool-sql-optimisations-that-do-not-depend-on-the-cost-model/">article</a> a while ago that looks at a number of query optimizations databases can make to optimize queries before executing them.</p><p>The author, <a href="https://blog.jooq.org/author/lukaseder/">lukaseder</a>, looked at 10 sql optimizations and analyzed 5 different databases to see which ones supported the optimizations.</p><p>I’m working on a transparent proxy caching for PostgreSQL, and have been thinking about sql transformations quite a bit. I was curious to know if PostgreSQL made any changes since the article came out in 2017. <a href="https://blog.jooq.org/author/lukaseder/">lukaseder</a> tested version 9.6 of PG, I tested version 18.0.</p><p>Of the 10 optimizations, PG 9.6 fully supported 4 of them, 3 remain unsupported in 18.0, and 3 optimizations differ in version 18.0 from version 9.6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*BQEdmEx-9LmTq36wtSBe4Q.png" /><figcaption>Changed and unchanged optimizations</figcaption></figure><p>In this article we’re going to take a look at the three optimizations where some support was added since 9.6.</p><p>Before proceeding, consider taking a look at the <a href="https://blog.jooq.org/10-cool-sql-optimisations-that-do-not-depend-on-the-cost-model/">original article</a> to learn more about all the transformations from the chart above.</p><h3>Removing “Silly” Predicates</h3><p>This came from wondering about what happens with a query like:</p><pre>SELECT * FROM film WHERE release_year = release_year; </pre><p>I’m not really sure how you end up writing a query like that in practice. Maybe if you are programmatically building queries, ending up with silly predicates becomes more likely. In any case, what do we expect to happen?</p><p>For columns that are NOT NULL, the where clause will always be true. If the column is nullable, then the clause is only true for the rows that are not null, since in SQL’s three valued logic NULL is not equal to NULL.</p><p>The NOT NULL case is equivalent to:</p><pre>SELECT * FROM film;</pre><p>The nullable case is equivalent to:</p><pre>SELECT * FROM film WHERE release_year IS NOT NULL;</pre><p>Here are the plans that PostgreSQL creates:</p><p>NOT NULL column:</p><pre>explain SELECT * FROM film WHERE film_id = film_id;<br><br>                        QUERY PLAN<br>----------------------------------------------------------<br> Seq Scan on film  (cost=0.00..65.00 rows=1000 width=390)</pre><p>nullable column:</p><pre>explain SELECT * FROM film WHERE release_year = release_year;<br><br>                        QUERY PLAN<br>----------------------------------------------------------<br> Seq Scan on film  (cost=0.00..65.00 rows=1000 width=390)<br>   Filter: ((release_year)::integer IS NOT NULL)</pre><p>We can see the execution plans make the expected transformations.</p><p>I also wondered if the optimization was always made or if more complicated clauses would prevent the change. After a couple of experiments, it quickly became clear the transformation is not always made.</p><p>Using a query with an AND clause with a NOT NULL column, the optimization is applied:</p><pre>explain SELECT * FROM film WHERE film_id = film_id AND rating = &#39;PG&#39;;<br><br>                                   QUERY PLAN<br>--------------------------------------------------------------------------------<br> Bitmap Heap Scan on film  (cost=5.65..63.08 rows=194 width=390)<br>   Recheck Cond: (rating = &#39;PG&#39;::mpaa_rating)<br>   -&gt;  Bitmap Index Scan on idx_film_rating  (cost=0.00..5.61 rows=194 width=0)<br>         Index Cond: (rating = &#39;PG&#39;::mpaa_rating)</pre><p>However, using an OR clause does not apply the transformation:</p><pre>explain SELECT * FROM film WHERE film_id = film_id OR rating = &#39;PG&#39;;<br><br>                           QUERY PLAN<br>-----------------------------------------------------------------<br> Seq Scan on film  (cost=0.00..70.00 rows=198 width=390)<br>   Filter: ((film_id = film_id) OR (rating = &#39;PG&#39;::mpaa_rating))</pre><p>Which is unfortunate, since PostgreSQL will optimize away a trivial OR clause:</p><pre>explain SELECT * FROM film WHERE true OR rating = &#39;PG&#39;;<br><br>                        QUERY PLAN<br>----------------------------------------------------------<br> Seq Scan on film  (cost=0.00..65.00 rows=1000 width=390)</pre><h3>Provably Empty Sets</h3><p>This optimization is to remove a derived table in a join when that table has to be empty. Two cases are used, one is using an IS NULL predicate on a column that is marked NOT NULL and the other case is doing an intersection where the intersection result has to be empty.</p><p>This can be a particularly valuable transformation, as can be seen in the query plans below. In the first case the query is turned into a constant. Without the transformation, a significant amount of work may need to be done.</p><p>The original article tested both inner joins and semi-joins, We’ll just look at the cases using an inner join since the results for the semi-joins are the same.</p><p>When creating a table that has to be empty by using an IS NULL clause on a NOT NULL column, PostgreSQL will optimize it away:</p><pre>explain SELECT *<br>FROM actor a<br>JOIN (<br>  SELECT *<br>  FROM film_actor<br>  WHERE film_id IS NULL<br>) fa ON a.actor_id = fa.actor_id;<br><br>QUERY PLAN<br>-------------------------------------------<br> Result  (cost=0.00..0.00 rows=0 width=25)<br>   One-Time Filter: false</pre><p>When creating an empty table using an INTERSECTION clause, the query is not optimized:</p><pre>explain SELECT *<br>FROM actor a<br>JOIN (<br>  SELECT actor_id, film_id<br>  FROM film_actor<br>  INTERSECT<br>  SELECT NULL, NULL<br>) fa ON a.actor_id = fa.actor_id;<br><br>                                   QUERY PLAN<br>--------------------------------------------------------------------------------<br> Hash Join  (cost=111.99..116.75 rows=1 width=33)<br>   Hash Cond: (a.actor_id = (NULL::integer))<br>   -&gt;  Seq Scan on actor a  (cost=0.00..4.00 rows=200 width=25)<br>   -&gt;  Hash  (cost=111.98..111.98 rows=1 width=8)<br>         -&gt;  HashSetOp Intersect  (cost=111.98..111.98 rows=1 width=8)<br>               -&gt;  Result  (cost=0.00..0.01 rows=1 width=8)<br>               -&gt;  Seq Scan on film_actor  (cost=0.00..84.64 rows=5464 width=8)</pre><h3>Unneeded Self JOIN</h3><p>This is another situation the probably arises when programmatically building queries, in this case joining a table to itself using its primary key. The join effectively creates a new alias for the same table and set of rows.</p><p>Without the optimization, the query planner and execution will perform a join operation which can end up being fairly expensive. With the optimization, the join operation is completely eliminated.</p><p>This query:</p><pre>SELECT a1.first_name, a2.last_name<br>FROM actor a1<br>JOIN actor a2 ON a1.actor_id = a2.actor_id;</pre><p>is equivalent to this:</p><pre>SELECT first_name, last_name<br>FROM actor;</pre><p>And we can see that the PostgreSQL planner turns the query into a simple scan without any join operations:</p><pre>                        QUERY PLAN<br>-----------------------------------------------------------<br> Seq Scan on actor a2  (cost=0.00..4.00 rows=200 width=13)</pre><p>When I started testing the optimizations, I was expecting (or hoping) that there would have been more improvements made to PostgreSQL. While I was writing this article, PostgreSQL 18 was released and added the Unneeded Self JOIN optimization, so it is nice to see the continual evoltion of PostgreSQL.</p><p>When the original article was written it sparked discussion on the PostgreSQL development mailing list. The <a href="https://www.postgresql.org/message-id/CAMjNa7cC4X9YR-vAJS-jSYCajhRDvJQnN7m2sLH1wLh-_Z2bsw@mail.gmail.com">discussion thread</a> is an informative look on how the PostgreSQL community approaches these types of optimizations.</p><p>The discussion revolved around weighing the value of making the optimizations to the query planner versus the cost of doing so. The cost of the planning is particularly important since PostgreSQL doesn’t cache plans by default, instead the client has to opt in to caching by using prepared statements. Without caching, the additional cost of query planning will be paid on every query, and that affects the balance of which optimizations are worth implementing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccba47943e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>