<?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 Nikolai Averin on Medium]]></title>
        <description><![CDATA[Stories by Nikolai Averin on Medium]]></description>
        <link>https://medium.com/@nikolai_averin?source=rss-eef5965a3241------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-NDwhFEQxb57EpyNer3y0A.png</url>
            <title>Stories by Nikolai Averin on Medium</title>
            <link>https://medium.com/@nikolai_averin?source=rss-eef5965a3241------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:53:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikolai_averin/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[SQL migrations in PostgreSQL, part 2]]></title>
            <link>https://medium.com/@nikolai_averin/sql-migrations-in-postgresql-part-2-3a14abd50873?source=rss-eef5965a3241------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a14abd50873</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-migration]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Nikolai Averin]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 15:55:11 GMT</pubDate>
            <atom:updated>2026-09-24T15:55:11.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*9WV8KkKlF5i5A3th.jpg" /></figure><p>In the <a href="https://medium.com/miro-engineering/sql-migrations-in-postgresql-part-1-bc38ec1cbe75">first part</a> we covered basic operations: adding columns, creating indexes and constraints, and so on.</p><p>This article focuses on two more complex migrations:</p><ul><li>updating a large table</li><li>splitting a table in two.</li></ul><h3>Contents</h3><ul><li><a href="#c6fe">Updating a large table</a></li><li><a href="#7f28">Approach 1: replacing the table</a></li><li><a href="#b748">Approach 2: using a temporary table</a></li><li><a href="#2d53">Approach 3: updating in batches</a></li><li><a href="#39fd">Splitting a table in two</a></li></ul><h3>Updating a large table</h3><p>Let’s suppose that we need to update the value of an attribute in a large table. The query may look like this:</p><pre>UPDATE my_table SET new_column = 42</pre><p>It&#39;s important to note that the notion of a <em>&quot;large table&quot;</em> is very subjective. In this context, what we mean is that the size of the table doesn&#39;t allow us to perform the migration head-on because of these two constraints:</p><ul><li>prolonged locking of other concurrent queries</li><li>bloat of the table and its indexes.</li></ul><p>In this article, we&#39;ll look at approaches that help reduce the impact of one or both of these issues. We’ll examine three approaches in total:</p><ul><li>replacing the table</li><li>using a temporary table</li><li>updating in batches.</li></ul><p>Before we get to the approaches themselves, let’s take a look at the root causes of the two problems. We will cover a bit of basic theory about how locks work in PostgreSQL, as well as the bloat effect on tables and indexes — feel free to <strong>skip ahead</strong> to <a href="#7f28">Approach 1</a> if you’d rather get straight to the practical part.</p><h4>Locks in PostgreSQL</h4><p>At the heart of the PostgreSQL engine is the <a href="https://www.postgresql.org/docs/current/mvcc-intro.html">MVCC</a> mechanism (Multi-Version Concurrency Control), which defines the rules for concurrent transactions.</p><p>As the name suggests, MVCC is based on data versioning: there are <strong><em>versions</em></strong> of data that are visible and accessible only to specific transactions, and not to others. Versioning is implemented through special <a href="https://www.postgresql.org/docs/current/ddl-system-columns.html">system columns</a> that exist in every table but are hidden by default: ctid, xmin, xmax, and others. You can view them by explicitly listing them in a SELECT query:</p><pre>postgres=# SELECT ctid, xmin, xmax, * FROM my_table;<br><br>    ctid    | xmin | xmax |   id    | new_column<br>------------+------+------+---------+------------<br> (0,1)      | 1401 | 1420 |  200061 | 2<br> (0,2)      | 1401 | 1420 |  250528 | 4<br> (0,3)      | 1405 | 0    |  407753 | 11</pre><ul><li>ctid is a pair of values (page + position on the page) representing the address of the current row version</li><li>xmin is the ID of the transaction that created the version</li><li>xmax is the ID of the transaction that deleted the version (empty for versions that haven’t been deleted).</li></ul><p>When transactions access a table, they see a snapshot of the data based on xmin and xmax. We won’t go into the filtering rules used to build that snapshot in this article. Instead, let’s walk through an example to see how these attributes are populated.</p><p>Suppose that the transaction with ID=435 inserts a row into an empty table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6t2LnkY227xh5c8Q.png" /></figure><ul><li>ctid = (0,1) — page 0, position 1 on the page. ctid points to itself (the address on the right of the table represents the actual location of the version)</li><li>xmax = 0 means that the version hasn’t been deleted.</li></ul><p>Then transaction 456 inserts a second row. Under the hood, everything works the same way as the previous command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rQP7I4lRBJ4srdKT.png" /></figure><p>Next comes an UPDATE. Transaction 459 updates one of the attributes of the second row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z-1bx0oNYwHcmHkk.png" /></figure><p>This results in three main changes:</p><ul><li>a new version is created and stored at address (0,3)</li><li>the ctid pointer of the previous version is set to this new address</li><li>the xmax of the previous version is set to the ID of the current transaction (459).</li></ul><p>Now the second row has two versions, one of which <em>may be</em> visible to other transactions. Which one is visible depends on the transaction start time, its status, and the isolation level.</p><p>It’s important to note that if we tried to see all versions using the SELECT we showed earlier, we’d only see the version with ctid=(0,3), because the result would already be filtered according to the visibility rules for our transaction. To see all versions, you can use the <a href="https://www.postgresql.org/docs/current/pageinspect.html">pageinspect</a> extension. Here’s an example query:</p><pre>SELECT t_xmin, t_xmax, t_ctid, t_data<br>FROM heap_page_items(get_raw_page(&#39;my_table&#39;,0));<br><br> t_xmin | t_xmax | t_ctid |       t_data<br>--------+--------+--------+--------------------<br>   1267 |   1268 | (0,2)  | \x0100000002000000<br>   1268 |      0 | (0,2)  | \x0200000002000000</pre><p>Let’s continue with our example. A new transaction with ID=501 tries to update the second row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jgmHqkGBJvMnUMWf.png" /></figure><p>PostgreSQL needs to determine which of the two versions is active and accessible to the current transaction. Version 1 at address (0,2) has xmax != 0, which means that it’s been deleted. However, to simply ignore that version and move on to version 2 (at address (0,3)), PostgreSQL needs to know the status of transaction 459 — has it already been committed (or rolled back)?</p><p>If transaction 459 is still active, transaction 501 will wait for it to finish. This is the moment when problems can start, if transaction 459 <strong>takes a long time</strong>.</p><p>By the way, if transaction 501 were only reading the data (SELECT), it wouldn’t have to wait for the result of transaction 459. If transaction 459 has been committed, version (0,3) is used. If it hasn’t been committed yet, or if it was rolled back, then version (0,2) is used.</p><p>When a query touches many rows, the locks gradually take over more and more of the table — potentially forcing more and more concurrent transactions to wait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rePNUZCZjPBfEXnT.gif" /></figure><h4>The bloat effect</h4><p>Table bloat is directly related to the MVCC mechanism. To understand the root causes, let’s take a look at how data is stored on disk. Table data is split into pages (8 KB each by default). A page contains both current and deleted versions (marked in green and gray respectively).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R6tdqW0ofEyfebRP.png" /></figure><p>Once a page fills up, a new page is allocated. The larger the table, the more pages it uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*6g1V-jz9UdrmdWBN.gif" /></figure><p>In our 4-page example, roughly half of the data consists of deleted versions that just take up space. When we’re talking about large tables, the volume of such “garbage” can be substantial.</p><p>Another important point is that a page is the smallest unit of disk access. If we need to read the version at address (3,5), page 3 is read in full and loaded into shared buffers (and shared buffers aren’t unlimited either). The fewer pages we need to read, the lower the load on the disk system and the higher database performance. So, to simplify, our goal is to minimize the number of gray cells.</p><h4>A few words about vacuum</h4><p>As you may know, PostgreSQL has a dedicated (auto)vacuum mechanism that’s responsible for reclaiming the space taken up by deleted versions so it can be reused. The problem is that under heavy database load and an insufficiently aggressive configuration, vacuum may not be able to keep up with the “cleaning” work and its efficiency drops.</p><p>Moreover, in the case of long-running transactions, vacuum can’t process deleted versions until the transaction has finished, and new modifications require <strong>new pages</strong> even though the existing pages would’ve had enough capacity if they were vacuumed fast enough.</p><p>After vacuum finishes, the picture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xSmkj_TCerKl0dTQ.png" /></figure><p>Empty “cells” for new versions have appeared in each page. However, we still have 4 pages instead of the 2 we could have, and as a result, we have both problems mentioned earlier — extra storage costs and extra data access costs.</p><p>That’s enough theory — let’s get to practice.</p><h4>Approach 1: replacing the table</h4><p>The idea is very simple: create a new table, copy the data over while applying the necessary changes, and then drop the original table.</p><p>This approach is suitable when:</p><ul><li>reads significantly outweigh writes (SELECT &gt;&gt; INSERT + UPDATE + DELETE)</li><li>some write operations can be lost or carried out with a substantial delay</li><li>there is enough free disk space.</li></ul><p>Additional free space is needed only during the migration, when both tables exist at the same time. Once the migration completes, the original table is dropped and the space is reclaimed. You can estimate the required size as:</p><pre>size(original_table) - bloat(original_table) + size(new_data)</pre><ul><li>to estimate bloat, you can use various SQL scripts, for example <a href="https://github.com/pgexperts/pgx_scripts/tree/master/bloat">these</a></li><li>new_data is an estimate of how much the table will grow as a result of the migration</li><li>it’s a good idea to add 30–50% on top, just in case.</li></ul><p>Now let’s get to it.</p><pre>BEGIN;<br>LOCK TABLE my_table IN SHARE MODE; (1)<br><br>CREATE TABLE new_my_table (id int, ...); (2)<br><br>INSERT INTO new_my_table SELECT ... FROM my_table; (3)<br><br>-- create constraints, indices, triggers (4)<br><br>DROP TABLE my_table; (5)<br><br>ALTER TABLE new_my_table RENAME TO my_table; (6)<br><br>COMMIT;<br>END;</pre><p>Step by step:</p><ol><li>Acquiring a lock in <a href="https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES">SHARE MODE</a> — this doesn’t block <em>reads</em>, but it blocks <em>all modifications</em>. The lock is needed so that the state of the table can’t change in concurrent transactions while the migration is running.</li><li>Creating the new table.</li><li>Copying the data into the new table. This is where we apply the modifications.</li><li>Creating constraints, indexes, and so on. We do this <em>after</em> the table has been populated, so as not to slow down the insert in the previous step.</li><li>Dropping the previous table. At this moment, queries can fail with an error (see details below).</li><li>Renaming the new table.</li><li>All that’s left is to commit the transaction, and the migration is complete.</li></ol><p>A few important points:</p><ul><li>Steps 2 and 3 are very <strong>flexible</strong>. You can apply many different modifications here — adding attributes, changing types, merging or splitting attributes, and so on. The main thing is that the application is ready for the new data model.</li><li>Depending on the PostgreSQL version, the behavior in steps 6 and 7 may <strong>differ</strong>. Before version 9.2, when the table is dropped, all queries that were waiting to acquire a lock (modifications, that is — SELECTs were not blocked) <strong>fail</strong> with an error. This is because recreating the table changes its <a href="https://www.postgresql.org/docs/current/datatype-oid.html">OID</a>, and the OID is what’s used when acquiring locks, not the table name directly. In version 9.2 the behavior changed — transactions “recompute” the OID and acquire a lock on the new table. To be more precise, they queue up to acquire it, since the new table will be in ACCESS EXCLUSIVE mode until the commit.</li><li>If the table has <strong>foreign keys</strong>, the migration gets much more complicated, because they cause locks on the referenced tables. If there are only a few keys/tables involved, this approach can still work. In step 1 you’ll also need to acquire locks on those tables. From that point on, they’ll be in read-only mode too. In theory, you could defer this step until the foreign keys are created in (4), but then you’d risk running into deadlocks. Locking all the relevant tables up front is the simplest and most reliable option.</li></ul><p>Summary of this approach:</p><ul><li>(+) the fastest of the approaches we cover in this article</li><li>(+) no table bloat</li><li>(–) requires free disk space</li><li>(–) writes are blocked during the migration</li><li>(–) the table OID changes (which can sometimes be critical).</li></ul><h4>Approach 2: using a temporary table</h4><p>If, for whatever reason, it is required to preserve the original table, you can adjust the previous approach a bit by copying the data twice instead of once. First we copy the data to a new table while applying the migration, and then we copy the data back into the now-empty original table.</p><p>Otherwise, the conditions are the same:</p><ul><li>reads significantly outweigh writes (SELECT &gt;&gt; INSERT + UPDATE + DELETE)</li><li>some write operations can be lost or carried out with a substantial delay</li><li>there is enough free disk space</li><li>the original table is preserved.</li></ul><pre>BEGIN;<br>LOCK TABLE my_table IN SHARE MODE; (1)<br><br>SET LOCAL temp_buffers = &#39;????MB&#39;; (2)<br><br>CREATE TEMP TABLE new_my_table ON COMMIT DROP AS SELECT ... FROM my_table; (3)<br><br>-- drop constraints, indexes, triggers (4)<br><br>TRUNCATE my_table; (5)<br><br>INSERT INTO my_table SELECT * FROM new_my_table; (6)<br><br>-- create constraints, indexes, triggers (7)<br><br>COMMIT;<br>END;</pre><p>The main differences from the first approach:</p><ul><li>Instead of a regular table, we create a temporary one (3). ON COMMIT DROP is used so that the table is dropped automatically when the transaction ends. By default, it would be dropped when the session ends.</li><li>To speed up working with the temporary table, it’s a good idea to increase the <a href="https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-TEMP-BUFFERS">temp_buffers</a> parameter beforehand, so as to keep as much data as possible in memory and avoid flushing it to disk.</li><li>In step 4, we prepare the original table to be cleared.</li><li>Then we clear the table (5). At this point, the lock that we previously acquired is escalated to the strictest one (ACCESS EXCLUSIVE), which means that new read queries will also be <strong>blocked</strong>.</li><li>In step 6, we move the data back into the original table. Here we can also change the data model, for example, by adding or removing an attribute.</li><li>If foreign keys are involved, the complications are the same as in the previous approach.</li></ul><p>Summary:</p><ul><li>(+) reasonably fast</li><li>(+) the original table is preserved</li><li>(+) no table bloat</li><li>(–) requires free disk space</li><li>(–) writes are blocked (for the entire duration of the migration)</li><li>(–) reads are blocked (for roughly half of the time, from the TRUNCATE onward).</li></ul><h4>Approach 3: updating in batches</h4><p>Both of the approaches above are good at solving the bloat problem, but they share a common drawback — write operations are blocked (and in the second approach, some reads are blocked too).</p><p>As you may recall from the beginning of the article, the reason for the prolonged lock in the head-on approach is that the migration runs in a <strong>single transaction</strong> that updates a <strong>large amount of data</strong>. So the idea behind the third approach suggests itself — split the migration into many small ones and run each of them in its own transaction.</p><p>This approach is suitable when:</p><ul><li>modifications make up a noticeable share of the load ( SELECT &gt; INSERT + UPDATE + DELETE)</li><li>you need to keep concurrent write operations running</li><li>there may be not much free disk space.</li></ul><p>Let’s get to it.</p><p>In our example, we’ll use batches of up to 10000 rows. The execution will look something like this:</p><pre>UPDATE my_table SET new_column = 42<br>WHERE id BETWEEN 1 AND 10000 AND new_column IS NULL;<br>COMMIT;<br><br>UPDATE my_table SET new_column = 42<br>WHERE id BETWEEN 10001 AND 20000 AND new_column IS NULL;<br>COMMIT;<br><br>...</pre><p>A couple of important notes:</p><ul><li>We don’t use OFFSET &lt;batch_num&gt;*10000 LIMIT 10000 in the query, because that is significantly less efficient — OFFSET would scan extra rows.</li><li>It follows from the above that, if there are gaps in id, the actual batch size <strong>can vary</strong> anywhere from 0 to 10000.</li></ul><p>This way we solve the prolonged-locking problem — no more than 10000 rows are locked at any one time. However, it doesn’t solve the bloat problem — if all these UPDATEs run one after another in quick succession, VACUUM still won’t keep up. The obvious solution is to trigger vacuum manually:</p><pre>UPDATE my_table SET new_column = 42<br>WHERE id BETWEEN 1 AND 10000 AND new_column IS NULL;<br>COMMIT;<br>VACUUM;<br><br>UPDATE my_table SET new_column = 42<br>WHERE id BETWEEN 10001 AND 20000 AND new_column IS NULL;<br>COMMIT;<br>VACUUM;<br><br>...</pre><p>The main drawback is that it will <strong>significantly slow down</strong> the migration. A reasonable compromise is to run vacuum every N updates — for example, every 5 or 10.</p><p>To avoid writing each UPDATE separately, the next possible step could be to write a procedure that does something like this:</p><pre>FOR i IN 1..batch_count LOOP<br>    id_from := ...<br>    id_to := ...<br><br>    UPDATE my_table SET new_column = 42<br>      WHERE id BETWEEN id_from AND id_to AND new_column IS NULL;<br><br>    COMMIT;<br><br>    VACUUM my_table; -- ERROR!<br>END LOOP;</pre><p>However, this code <strong>won’t work</strong>, because the VACUUM command can’t be called inside a transaction. To get around this limitation, you can use the <a href="https://github.com/vibhorkum/pg_background">pg_background</a> extension (it supports PostgreSQL 9.5+). It allows you to run a command in a separate process. The updated code looks like this:</p><pre>FOR i IN 1..batch_count LOOP<br>    id_from := ...<br>    id_to := ...<br><br>    UPDATE my_table SET new_column = 42<br>      WHERE id BETWEEN id_from AND id_to AND new_column IS NULL;<br><br>    COMMIT;<br><br>    pid := pg_background_launch(&#39;vacuum my_table&#39;);<br>    PERFORM * FROM pg_background_result(pid) as p (r text);<br>END LOOP;</pre><h4>Choosing the batch size</h4><p>The number of rows updated in a single iteration affects a few different things. The <strong>smaller</strong> the value,</p><ul><li>the slower the migration</li><li>the smaller the final amount of bloat</li><li>the lower the probability of <strong>deadlocks</strong>.</li></ul><p>The first two points are fairly self-explanatory; let’s take a closer look at the third one.</p><p>When we update the table all at once after acquiring a lock, no one else can modify the data — everyone waits for the migration to finish. With batched updates, a concurrent transaction may also try to acquire locks on some rows. If locks are acquired in different orders (for example, transaction 1 acquires id=1 and id=3, while transaction 2 acquires id=3 and id=1), we end up in the classic deadlock situation. PostgreSQL will pick one of the transactions and kill it. It’s worth noting that deadlocks can be much more complex — involving several tables and transactions.</p><p>To eliminate the possibility of deadlocks entirely, we’d need to guarantee that the order in which they’re acquired is always the same. In practice this is usually hard to achieve. For example, when running a query like UPDATE … WHERE id &lt; 100, the rows being updated can be locked in an <strong>arbitrary order</strong>. If PostgreSQL uses an index, the locks will <em>likely</em> be ordered according to the index. If it uses a <em>seqscan</em>, the order will depend on how the data is stored on disk.</p><p>To control the lock order, you can use the following pattern:</p><pre>UPDATE my_table SET … WHERE id IN (<br>    SELECT id FROM my_table WHERE &lt;condition&gt; ORDER BY id FOR UPDATE<br>);</pre><p>First we acquire locks based on the ordered result of the SELECT, and only then perform the update. It works great, but there’s a catch — every UPDATE would have to be written this way, <strong>both</strong> in the migration and in the “regular” application code, which obviously no one’s would like to do.</p><p>Fortunately, we can take a different route. SELECT FOR UPDATE supports the SKIP LOCKED option, which lets us acquire locks on “free” rows and skip the ones that are already locked (by the application, for example). Using it in the migration helps us avoid deadlocks. The downside is that we’ll have to run more UPDATE queries.</p><p>Let’s put everything together, tidy it up a bit, and add some debug output:</p><pre>DO $$<br>DECLARE<br>    batch_size constant int := 10000;<br>    vacuum_freq constant int := 10;<br>    id_max int;<br>    id_from int;<br>    id_to int := 0;<br>    i int := 1;<br>    updated_cnt_query int;<br>    updated_cnt_since_last_vacuum int := 0;<br>    pid int;<br>BEGIN<br>    SELECT max(id) into id_max FROM my_table;<br><br>    WHILE (id_to &lt; id_max) LOOP<br>        id_from := (i - 1) * batch_size;<br>        id_to := id_from + batch_size - 1;<br>        RAISE INFO &#39;processing id % - %&#39;, id_from, id_to;<br><br>        WHILE (SELECT EXISTS(SELECT 1 FROM my_table<br>                             WHERE id BETWEEN id_from AND id_to AND new_column IS NULL)) LOOP<br>            UPDATE my_table SET new_column = 42 WHERE id IN (<br>                SELECT id FROM my_table<br>                WHERE id BETWEEN id_from AND id_to AND new_column IS NULL<br>                FOR UPDATE SKIP LOCKED<br>            );<br><br>            GET DIAGNOSTICS updated_cnt_query = ROW_COUNT;<br>            COMMIT;<br><br>            IF (updated_cnt_query = 0) THEN<br>                RAISE INFO &#39;sleeping 1 sec&#39;;<br>                PERFORM pg_sleep(1);<br>            END IF;<br><br>            updated_cnt_since_last_vacuum := updated_cnt_since_last_vacuum + updated_cnt_query;<br>        END LOOP;<br><br>        IF (i % vacuum_freq = 0 AND updated_cnt_since_last_vacuum &gt; 0) THEN<br>            RAISE INFO &#39;running vacuum&#39;;<br>            pid := pg_background_launch(&#39;vacuum my_table&#39;);<br>            PERFORM * FROM pg_background_result(pid) as r (t text);<br>            updated_cnt_since_last_vacuum := 0;<br>        END IF;<br>        i := i + 1;<br>    END LOOP;<br>END $$;</pre><p>The key points:</p><ul><li>we update 10000 rows at a time</li><li>if nothing got updated because the rows were locked, we wait 1 second</li><li>we run vacuum every 10 batches, if there have been successful updates in between.</li></ul><p>Running it, we see the following:</p><pre>INFO:  processing id 0 - 9999<br>INFO:  processing id 10000 - 19999<br>INFO:  processing id 20000 - 29999<br>INFO:  processing id 30000 - 39999<br>INFO:  processing id 40000 - 49999<br>INFO:  processing id 50000 - 59999<br>INFO:  processing id 60000 - 69999<br>INFO:  processing id 70000 - 79999<br>INFO:  processing id 80000 - 89999<br>INFO:  processing id 90000 - 99999<br>INFO:  running vacuum<br>INFO:  processing id 100000 - 109999<br>INFO:  processing id 110000 - 119999</pre><p>If the migration runs into locked rows, the output will look something like this:</p><pre>INFO:  processing id 370000 - 379999<br>INFO:  processing id 380000 - 389999<br>INFO:  processing id 390000 - 399999<br>INFO:  running vacuum<br>INFO:  processing id 400000 - 409999<br>INFO:  processing id 410000 - 419999<br>INFO:  sleeping 1 sec<br>INFO:  sleeping 1 sec<br>INFO:  sleeping 1 sec<br>INFO:  processing id 420000 - 429999<br>INFO:  processing id 430000 - 439999</pre><p>After 3 seconds, the lock is released and the migration continues.</p><p>Summary of this approach:</p><ul><li>(+) minimal lock time</li><li>(+) modest table bloat</li><li>(+) foreign keys don’t complicate the migration</li><li>(–) slow</li><li>(–) requires installing the pg_background extension</li></ul><p>Overall, this is a fairly general-purpose solution that applies in many cases.</p><h3>Splitting a table in two</h3><p>This migration is unrelated to the previous one, and in general it’s needed much less often, but it does come up occasionally. For example, you might want to separate data from different domains into different tables. Or you might want to split frequently and rarely used data for performance reasons.</p><p>In any case, let’s suppose that we have a table that we want to “halve” into two, where one of the new tables will reference the other. We’ll call them the “head” and the “tail” respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*QORlscdYG6qDj972.gif" /></figure><p>The most important requirement is that the migration must be carried out <strong>without stopping</strong> the application.</p><p>The approach is based on an interesting feature of PostgreSQL —<em> updatable views</em>. To split the table, we’ll temporarily replace it with a view that supports all the operations we need (except for TRUNCATE) — SELECT, UPDATE, DELETE. The original table will become the “head” table, from which we’ll then “cut off the tail.” Visually, the process looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*OnGXmrRsC_wflBtv.gif" /></figure><p>Let’s get to it. The original table:</p><pre>CREATE TABLE big_table (id int primary key, a int, b int, c int);</pre><p>We create the “tail”:</p><pre>CREATE TABLE tail_table<br>(<br>   id int primary key,<br>   b  int,<br>   c  int,<br>   CONSTRAINT fk_tail_table FOREIGN KEY (id)<br>      REFERENCES big_table (id) ON DELETE CASCADE<br>)</pre><p><strong>Step 1</strong> — replace the original table with a view and a trigger. We open a transaction and run a few operations:</p><pre>BEGIN<br>ALTER TABLE big_table RENAME TO head_table;<br>CREATE VIEW big_table as SELECT * FROM head_table;<br><br>CREATE OR REPLACE FUNCTION big_table_trigger_func() RETURNS TRIGGER AS<br>$$<br>BEGIN<br>   IF TG_OP = &#39;INSERT&#39; THEN<br>       INSERT INTO head_table VALUES (NEW.*);<br>       INSERT INTO tail_table values (NEW.id, NEW.b, NEW.c);<br>       RETURN NEW;<br><br>   ELSEIF TG_OP = &#39;UPDATE&#39; THEN<br>       UPDATE head_table SET a=new.a, b=new.b, c=new.c WHERE id = new.id;<br>       INSERT INTO tail_table VALUES (NEW.id, NEW.b, NEW.c)<br>           ON CONFLICT (id) DO UPDATE SET b=new.b, c=new.c;<br>       RETURN NEW;<br><br>   ELSEIF TG_OP = &#39;DELETE&#39; THEN<br>       DELETE FROM head_table WHERE id = OLD.id;<br>       RETURN OLD;<br>   END IF;<br>END;<br>$$ LANGUAGE plpgsql;<br><br>CREATE TRIGGER big_table_trigger<br>INSTEAD OF INSERT OR UPDATE OR DELETE ON big_table<br>FOR EACH ROW EXECUTE PROCEDURE big_table_trigger_func();<br><br>END;</pre><p>The most interesting thing in this code is PostgreSQL’s ability to create triggers on views (introduced in PostgreSQL 9.1). The modification logic is fairly straightforward:</p><ul><li>on INSERT, we insert into both tables</li><li>on UPDATE, we update the “head” table and also try to insert into the “tail.” If the row already exists (it was inserted earlier), we update its value.</li><li>on DELETE, we delete from the “head” table — the “tail” is updated automatically thanks to the foreign key with cascade delete.</li></ul><p>The code above runs very quickly (provided that it doesn’t have to wait too long to acquire a lock on the original table), so the application won’t notice the swap.</p><p>From this moment on, all new data is split across the new tables. We still need to migrate the existing data. Let’s move on to <strong>step 2</strong>. We apply the approach from the previous migration:</p><pre>INSERT INTO tail_table(id, b, c) SELECT id, b, c FROM head_table<br>WHERE id BETWEEN 1 AND 10000 ON CONFLICT DO NOTHING;<br>COMMIT;<br><br>INSERT INTO tail_table(id, b, c) SELECT id, b, c FROM head_table<br>WHERE id BETWEEN 10001 AND 20000 ON CONFLICT DO NOTHING;<br>COMMIT;<br><br>...</pre><p>If a row already exists, we simply ignore it — ON CONFLICT DO NOTHING.</p><p>Just like in the previous approach, we can wrap this in a loop, like so:</p><pre>BEGIN<br>    FOR i IN 1..batch_count LOOP<br>        id_from := ...<br>        id_to := ...<br><br>        INSERT INTO tail_table(id, b, c)<br>        SELECT id, b, c FROM head_table<br>        WHERE id BETWEEN id_from AND id_to ON CONFLICT DO NOTHING;<br><br>        COMMIT;<br>    END LOOP;<br>END;</pre><p>Note that we don’t run vacuum, because INSERT doesn’t create bloat.</p><p>You may be tempted to write the code slightly differently, using a <em>cursor</em> — <strong>don’t do that:</strong></p><pre>-- DON&#39;T DO THIS!<br>BEGIN<br>    FOR r in SELECT * FROM head_table LOOP -- holdable cursor<br>        INSERT INTO tail_table(id, b, c) VALUES (r.id, r.b, r.c)<br>          ON CONFLICT DO NOTHING;<br><br>        i := i + 1;<br><br>        IF i % batch_size = 0 THEN<br>            COMMIT;<br>        END IF;<br>    END LOOP;<br>END;</pre><p>When this code runs, a cursor is opened that “looks at” the data snapshot created by PostgreSQL for the current transaction. As soon as we commit, that snapshot becomes outdated. To allow us to keep iterating over the cursor, PostgreSQL converts it into a so-called <strong>holdable cursor</strong>, which effectively means copying the data snapshot to disk. As you can imagine, for a large table this can take quite a while.</p><p><strong>Step 3</strong> — replacing the view’s query.</p><p>Once all the data is in the right tables, we replace the view’s query to prepare for dropping the unneeded columns from the “head” table:</p><pre>CREATE OR REPLACE VIEW big_table AS<br>  SELECT h.id, h.a, t.b, t.c FROM head_table h<br>  LEFT JOIN tail_table t ON h.id = t.id;</pre><p><strong>Step 4 </strong>— switch the application to working with head_table and tail_table.</p><p>After the previous step, the application can keep working with the view as before, or switch to working with the new tables — the data is in sync. We switch the code over to the target data model and stop using big_table.</p><p><strong>Step 5</strong>, the last one — cleanup. We drop the view and the columns that are no longer needed:</p><pre>DROP VIEW big_table;<br>DROP FUNCTION big_table_trigger_func();<br>ALTER TABLE head_table DROP COLUMN b, DROP COLUMN c;</pre><p>If there were any foreign keys referencing the b and c columns of the original table, you’ll need to recreate the equivalent constraints on the “tail” table before the cleanup. In the previous <a href="https://medium.com/miro-engineering/sql-migrations-in-postgresql-part-1-bc38ec1cbe75">article</a> we covered the best ways to do this.</p><p>That brings the migration to an end. And our article too. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a14abd50873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL migrations in PostgreSQL, part 1]]></title>
            <link>https://medium.com/miro-engineering/sql-migrations-in-postgresql-part-1-bc38ec1cbe75?source=rss-eef5965a3241------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc38ec1cbe75</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sql-migration]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Nikolai Averin]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 07:06:11 GMT</pubDate>
            <atom:updated>2026-09-27T13:45:30.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X_Ex9PokUDj3-Uv4" /></figure><p>How do you update an attribute value in all table rows? How do you add a primary or a unique key to a table? How do you split a table in two? How do you…</p><p>If you accept to factor in some downtime while you’re performing migrations, then the answers to these questions are easy. But what if you need to carry out migrations on the fly, without stopping the database, and without interfering with other people’s work?</p><p>In this article, we try to give practical answers to these and other questions related to schema and data migrations in PostgreSQL.</p><p>It’s a lot of information, so we’re splitting the article in two:</p><ul><li>Base migrations</li><li>Approaches to updating large tables</li></ul><p>At the end of the article, you can find a cheat sheet for the entire piece.</p><h3>Contents</h3><p><a href="#852e">Task definition</a><br><a href="#e3d1">Adding a column<br></a><a href="#5786">Adding a column with a default value<br></a><a href="#7281">Deleting a column<br></a><a href="#0baf">Creating an index<br></a><a href="#cc43">Creating an index for a partitioned table</a><br><a href="#2421">Creating a NOT NULL constraint<br></a><a href="#906a">Creating a foreign key<br></a><a href="#0927">Creating a unique constraint<br></a><a href="#40aa">Creating a primary key<br></a><a href="#d809">A quick cheat sheet with migrations</a></p><h3>Task definition</h3><p>Let’s suppose that we’re running an application that works with a database. In a minimal configuration, it may consist of two nodes: the application, and the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoffAPTjA3rue1HS" /></figure><p>In such a configuration, application updates often lead to downtime, which we can use also to update the database. Time is the crucial factor here: the migration should take as little time as possible to minimize service downtime.</p><p>As the application grows in size and complexity, it may become necessary to release without the downtime and to use multiple application servers. There can be as many servers as we want, and they run different versions of the code. In this case, it is essential to ensure backward compatibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wUrfCoKOqpvJT3nJ" /></figure><p>The application keeps growing, and a single database is no longer enough to store all the data. Now it’s time to scale the database as well by sharding it. It’s very difficult to apply migrations to multiple databases synchronously; at some point, they may have different data schemas. Therefore, we’ll work in a mixed environment, where application servers may have different code, and databases may have different data schemas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GFcn0KhrJB7Qhm0c" /></figure><p>This is the kind of configuration that we’re focusing on in this article. We’ll look at some of the most popular migrations that developers work on, from simple to more complex ones.</p><p>Basically, we want to perform SQL migrations with minimum impact on the application, i.e., we want to change the data or the data schema while the application keeps running, and without affecting users.</p><h3>Adding a column</h3><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>COLUMN</strong> new_column INTEGER -- fast and safe</pre><p>Probably, anyone who works with databases has written such a migration. As for PostgreSQL, this migration is cheap and safe. Even though the command acquires the highest-level lock (<a href="https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES">AccessExclusive</a>), it executes fast: it only adds the new column metadata, without overwriting the table. In most cases, the process doesn’t cause any noticeable ripples. However, trouble may be brewing if long transactions are running on the table while the migration is taking place. To understand the nature of the problem, let’s take a quick look at how locks work in PostgreSQL. This is important when reviewing most of the following migrations.</p><p>Let’s suppose that we have a large table, and that we want to perform a SELECT query on all the data it holds. Depending on the sizes of the database and the table, it can take from several seconds to some minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QgKVheMA5Ys_QJtl61WZmQ.gif" /></figure><p>When the transaction starts executing, the weakest <a href="https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES">AccessShare</a> lock is acquired to prevent changes to the table structure.</p><p>At the same time, another transaction starts executing; it tries to run an ALTER TABLE query on the same table. As we’ve seen, the ALTER TABLE command acquires an <a href="https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES">AccessExclusive</a> lock that is <a href="https://www.postgresql.org/docs/current/explicit-locking.html#TABLE-LOCK-COMPATIBILITY">incompatible</a> with any other locks. Therefore, this transaction is queued.</p><p>Queued queries are executed based on their order in the queue, regardless of them acquiring blocking or non-blocking locks. For instance, if a few SELECT queries start executing after the ALTER TABLE query, they will be queued even though they do not conflict with the currently running SELECT query. As a result, the ALTER TABLE query acts as a bottleneck for the application, until it is executed.</p><p>What can we do in this situation? We can limit the locking time with the <a href="https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-LOCK-TIMEOUT">SET lock_timeout</a> command: run it before the ALTER TABLE query. The LOCAL keyword applies the setting only to the current transaction. Without this keyword, the setting applies to the current session.</p><pre><strong>SET</strong> <strong>LOCAL</strong> lock_timeout <strong>TO</strong> &#39;100ms&#39;</pre><p>If the query SET lock_timeout refers to can’t acquire a lock within 100 milliseconds, it fails. Then we can either run it again, expecting it to execute correctly; or we can try to find out why it’s taking so long when it shouldn’t. What matters here is that we don’t negatively impact the application. Another option is using <a href="https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-STATEMENT-TIMEOUT">SET statement_timeout</a>, which sets the timeout for the whole query execution, including locking time.</p><p>Usually, it’s good practice to set a timeout for any command that acquires a strict lock.</p><h3>Adding a column with a default value</h3><pre>-- fast and safe since PostgreSQL 11 <br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>COLUMN</strong> new_column INTEGER <strong>DEFAULT</strong> 42</pre><p>Executing this command in PostgreSQL before version 11 overwrites all table rows. If it runs on a large table, it can take a long time. And since the command acquires a strict lock (<a href="https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES">AccessExclusive</a>), any other queries on the table are blocked.</p><p>Since PostgreSQL 11, this operation has become much cheaper. Now the default value is saved to the <a href="https://www.postgresql.org/docs/13/catalog-pg-attribute.html">pg_attribute</a> catalog. When a SELECT query executes, all empty values in the column are replaced on the fly with the value from the pg_attribute. Then, when rows in the table are overwritten due to any modifications, the default value is also written to those rows.</p><p>Moreover, since version 11 you can also create a new column, and mark it as NOT NULL right away:</p><pre>-- fast and safe since PostgreSQL 11<br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>COLUMN</strong> new_column INTEGER <strong>DEFAULT</strong> 42 <strong>NOT</strong> <strong>NULL</strong></pre><p>What if PostgreSQL is older than version 11?</p><p>You can split the migration in several steps. First, create a new column with no restrictions and no default values. This is both cheap and fast. In the same transaction, modify this column by adding a default value.</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>COLUMN</strong> new_column INTEGER; <br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ALTER</strong> <strong>COLUMN</strong> new_column <strong>SET</strong> <strong>DEFAULT</strong> 42;</pre><p>Splitting one command into two may look awkward at first. However, the point is that the mechanism to create a new column with a default value immediately affects all existing records in the table, while setting a value for an existing column (even if it has just been created, as in this case) affects only new records.</p><p>After running these commands, we only need to update the values that were already in the table. In a nutshell:</p><pre><strong>UPDATE</strong> my_table <strong>set</strong> new_column = 42 -- <em>not safe for a large table</em></pre><p>However, running UPDATE like this may backfire: updating a large table would lock the entire table for a long time. In the second part of this article (there will be a link later on), we’ll examine some strategies to update large tables in PostgreSQL; for now, let’s assume that we somehow updated the data, and now both old and new data have the required default value.</p><h3>Deleting a column</h3><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>DROP</strong> <strong>COLUMN</strong> new_column -- fast and safe</pre><p>The underlying logic here is the same as when adding a column: table data is not modified right away, we change only the metadata. When carrying out a deletion, the column is marked as deleted, and it’s not possible to run queries on it. This is why deleting a column in PostgreSQL doesn’t release disk space, unless you also run VACUUM FULL: old data remains stored in the table, but it becomes inaccessible. The space it takes frees up gradually, as data in table rows gets overwritten.</p><p>The migration in itself is quite simple, but sometimes mistakes can occur on the application side. To avoid that, carry out a few simple preliminary steps before deleting a column.</p><ul><li>Remove any constraints (NOT NULL, CHECK, …) applied to the column:<br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ALTER</strong> <strong>COLUMN</strong> new_column <strong>DROP</strong> <strong>NOT</strong> NULL</li><li>Then, ensure back-end compatibility. Make sure that the column isn’t being used anywhere. For example, in Hibernate you need to tag the field with the @Transient annotation. We use JOOQ, which features a special &lt;excludes&gt; tag to add fields to exceptions:<br>&lt;excludes&gt;my_table.new_column&lt;/excludes&gt;<br>You should also carefully inspect all SELECT * queries, as frameworks may map all columns to the structure in the code (and vice versa); you may again encounter the problem of referring to a column that doesn’t exist.</li></ul><p>After applying the changes to all application servers, it’s safe to delete the column.</p><h3>Creating an index</h3><pre><strong>CREATE</strong> <strong>INDEX</strong> my_table_index <strong>ON</strong> my_table (name) -- <em>not safe, it locks the table</em></pre><p>If you work with PostgreSQL, you probably know that this command locks the entire table. However, since version 8.2 the special keyword <a href="https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY">CONCURRENTLY</a> enables creating an index in non-blocking mode.</p><pre><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_index <strong>ON</strong> my_table (name) -- safe</pre><p>The execution is slower, but it doesn’t interfere with concurrent queries.</p><p>There’s a little twist to this command. It may fail; for example, when creating a unique index in a table containing duplicate values. The index is created, but it’s marked as invalid, and it’s not available for querying. You can check the status of the index with the following query:</p><pre><strong>SELECT</strong> pg_index.indisvalid     <br>  <strong>FROM</strong> pg_class, pg_index <br><strong>WHERE</strong> pg_index.indexrelid = pg_class.oid     <br>  <strong>AND</strong> pg_class.relname = &#39;my_table_index&#39;</pre><p>In such a case, delete the old index, fix the values in the table, and then rebuild the index.</p><pre><strong>DROP</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_index <br><strong>UPDATE</strong> my_table ... <br><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_index <strong>ON</strong> my_table (name)</pre><h4>REINDEX</h4><p>The <a href="https://www.postgresql.org/docs/current/sql-reindex.html">REINDEX</a> command deserves a special mention, since it’s designed exactly to recreate the index. In the versions before 12, it operates in blocking mode only, which makes it difficult to use. From PostgreSQL 12, the command supports the CONCURRENTLY keyword, which makes its usage more convenient.</p><pre><strong>REINDEX</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_index -- since PostgreSQL 12</pre><p>It’s important to point out that since REINDEX does the same thing as CREATE INDEX CONCURRENTLY + SWAP + DROP INDEX CONCURRENTLY, it may also end up failing and leaving behind invalid indexes.</p><ul><li>If an error occurs while creating a new index, _ccnew is appended to the index name. The recommended way to fix it is to delete the index and to run REINDEX again.</li><li>If _ccold is appended to the index name, it means that an error occurred while deleting the old index. In this case, delete this index, as the new index was built successfully.</li></ul><p>REINDEX CONCURRENTLY for tables, schemas, and such works slightly differently: invalid indexes are ignored to avoid generating even more of them.</p><p>You can learn more about the REINDEX mechanism in the <a href="https://www.postgresql.org/docs/12/sql-reindex.html#SQL-REINDEX-CONCURRENTLY">PostgreSQL official documentation</a>.</p><h3>Creating an index for a partitioned table</h3><p>Now let’s look at creating indexes for partitioned tables. There are two types of partitioning in PostgreSQL: table inheritance, and declarative partitioning, introduced in version 10. Let’s review both using a simple example.</p><p>Let’s suppose that we want to partition a table by date, where each partition contains the equivalent of one year of data.</p><p>When partitioning through inheritance, the schema looks like this:</p><p>Parent table:</p><pre><strong>CREATE</strong> <strong>TABLE</strong> my_table (<br>    ...<br>    reg_date   date <strong>not</strong> <strong>null</strong><br>)</pre><p>Partitions for the years 2020 and 2021:</p><pre><strong>CREATE</strong> <strong>TABLE</strong> my_table_y2020 (<br><strong>CHECK</strong> ( reg_date &gt;= DATE &#39;2020-01-01&#39; <strong>AND</strong> reg_date &lt; DATE &#39;2021-01-01&#39; ))<br><strong>INHERITS</strong> (my_table);<br><br><strong>CREATE</strong> <strong>TABLE</strong> my_table_y2021 (<br><strong>CHECK</strong> ( reg_date &gt;= DATE &#39;2021-01-01&#39; <strong>AND</strong> reg_date &lt; DATE &#39;2022-01-01&#39; ))<br><strong>INHERITS</strong> (my_table);</pre><p>Partition field indexes for each partition:</p><pre><strong>CREATE</strong> <strong>INDEX</strong> <strong>ON</strong> my_table_y2020 (reg_date);<br><strong>CREATE</strong> <strong>INDEX</strong> <strong>ON</strong> my_table_y2021 (reg_date);</pre><p>For now, let’s leave out creating a trigger/rule to insert data in the table.</p><p>The most important thing here is that each partition is basically an almost independent table, and it’s processed separately. Therefore, creating new indexes is the same as creating for regular tables:</p><pre><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_y2020_index <strong>ON</strong> my_table_y2020 (name); <br><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_y2021_index <strong>ON</strong> my_table_y2021 (name);</pre><p>Now let’s look at declarative partitioning:</p><pre><strong>CREATE</strong> <strong>TABLE</strong> my_table (...) <strong>PARTITION BY RANGE</strong> (reg_date); <br><strong>CREATE</strong> <strong>TABLE</strong> my_table_y2020 <strong>PARTITION</strong> <strong>OF</strong> my_table <strong>FOR</strong> <strong>VALUES</strong> <strong>FROM</strong> (&#39;2020-01-01&#39;) <strong>TO</strong> (&#39;2020-12-31&#39;); <br><strong>CREATE</strong> <strong>TABLE</strong> my_table_y2021 <strong>PARTITION</strong> <strong>OF</strong> my_table <strong>FOR</strong> <strong>VALUES</strong> <strong>FROM</strong> (&#39;2021-01-01&#39;) <strong>TO</strong> (&#39;2021-12-31&#39;);</pre><p>Index creation varies, based on the PostgreSQL version in use. In version 10, indexes are created individually, just like in the previous approach. Creating new indexes for existing tables works in the same way.</p><p>In version 11, declarative partitioning is improved, and tables are processed <strong>together.</strong> Creating an index on the parent table automatically results in creating indexes for all existing and <strong>new</strong> partitions that will be created in the future:</p><pre><em>-- since PG 11 it’s convenient for a new (empty) partitioned table<br></em><strong>CREATE</strong> <strong>INDEX</strong> <strong>ON</strong> my_table (reg_date)</pre><p>It’s convenient when creating a partitioned table, but it’s not viable when creating a new index for an existing table, because this command acquires a strict lock on the table while the indexes are being created.</p><pre><strong>CREATE</strong> <strong>INDEX</strong> <strong>ON</strong> my_table (name) -- it locks the table</pre><p>Unfortunately, CREATE INDEX does not support the CONCURRENTLY keyword for partitioned tables. To bypass this restriction, and to perform a migration without locks, you can do the following:</p><p>1. Create an index for the parent table with the ONLY option:<br><strong>CREATE</strong> <strong>INDEX</strong> my_table_index <strong>ON</strong> <strong>ONLY</strong> my_table (name)<br>This generates an empty invalid index <strong>without creating indexes for the partitions.</strong></p><p>2. Create indexes for each partition:<br><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_y2020_index <strong>ON</strong> my_table_y2020 (name);<br><strong>CREATE</strong> <strong>INDEX</strong> <strong>CONCURRENTLY</strong> my_table_y2021_index <strong>ON</strong> my_table_y2021 (name);</p><p>3. Attach partition indexes to the parent table index:<br><strong>ALTER</strong> <strong>INDEX</strong> my_table_index <strong>ATTACH PARTITION</strong> my_table_y2020_index;<br><strong>ALTER</strong> <strong>INDEX</strong> my_table_index <strong>ATTACH PARTITION</strong> my_table_y2021_index;<br>Once all indexes are attached, the index of the parent table automatically becomes valid.</p><h3>Constraints</h3><p>Now let’s go over constraints: NOT NULL, foreign, unique, and primary keys.</p><h3>Creating a NOT NULL constraint</h3><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ALTER</strong> <strong>COLUMN</strong> name <strong>SET</strong> <strong>NOT</strong> <strong>NULL</strong> -- it locks the table</pre><p>Creating a constraint this way causes the entire table to be examined: all rows are checked for the NOT NULL condition. If it’s a large table, it can take a long time. This query acquires a strict lock, which blocks all concurrent queries until the initial query has been completed.</p><p>What options do we have? PostgreSQL features another type of constraint: <a href="https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS">CHECK</a>. This constraint can help us. The constraint checks for any boolean conditions composed of columns of a row. In our case, the condition is trivial: CHECK (name IS NOT NULL). Most importantly, the CHECK constraint supports the NOT VALID option:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> chk_name_not_null      <br>  <strong>CHECK</strong> (name <strong>IS</strong> <strong>NOT</strong> <strong>NULL</strong>) <strong>NOT</strong> <strong>VALID</strong> -- safe since PostgreSQL 9.2</pre><p>This constraint applies only to newly added and to modified records — existing ones are not affected, so it doesn’t examine the whole table.</p><p>To ensure that existing records also meet the constraint, it is necessary to validate it (of course, after updating the data in the table):</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>VALIDATE</strong> <strong>CONSTRAINT</strong> chk_name_not_null</pre><p>This command iterates through table rows and checks that all records are not-null. But unlike the usual NOT NULL constraint, the lock that this command acquires is not very strict (ShareUpdateExclusive); it doesn’t block insert, update, and delete operations.</p><h3>Creating a foreign key</h3><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> fk_group      <br>  <strong>FOREIGN KEY</strong> (group_id) <strong>REFERENCES</strong> <strong>groups</strong>(id) -- locks both the tables</pre><p>When a foreign key is added, all the entries in the child table are scanned for a value from the parent table. If it’s a large table, the scan can take a long time, and both tables are locked while the operation is in progress.</p><p>Fortunately, foreign keys in PostgreSQL also support the NOT VALID option; therefore, we can use the same approach that we previously discussed with CHECK. Let’s create a non-valid foreign key:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> fk_group      <br>  <strong>FOREIGN KEY</strong> (group_id) <strong>REFERENCES</strong> <strong>groups</strong>(id) <strong>NOT</strong> <strong>VALID</strong></pre><p>Then, after updating the data, let’s perform validation:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>VALIDATE</strong> <strong>CONSTRAINT</strong> fk_group_id</pre><h3>Creating a unique constraint</h3><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> uk_my_table <strong>UNIQUE</strong> (id) -- it locks the table</pre><p>As with the previously discussed constraints, this command acquires a strict lock while it checks all rows in the table against the specified constraint — in this case, uniqueness.</p><p>The implementation of unique constraints in PostgreSQL is built on unique indexes. In other words, when a constraint is created, a corresponding unique index with the same name is also created to <strong>serve </strong>the constraint. You can find the corresponding index of the constraint with the following query:</p><pre><strong>SELECT</strong> conindid index_oid, conindid::regclass index_name<br>  <strong>FROM</strong> pg_constraint<br><strong>WHERE</strong> conname = &#39;uk_my_table_id&#39;</pre><p>Most of the time required to create a constraint is spent on the index, while its subsequent binding to the constraint is relatively fast. If you already have a unique index, you can bind it manually by adding a constraint with the USING INDEX keywords:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> uk_my_table_id <strong>UNIQUE<br>  USING</strong> <strong>INDEX</strong> uk_my_table_id -- fast since PostgreSQL 9.1</pre><p>The basic idea is simple: let’s create a unique index CONCURRENTLY, as we discussed earlier, and then use it to create a unique constraint.</p><p>At this point, <a href="https://stackoverflow.com/questions/23542794/postgres-unique-constraint-vs-index">you may wonder</a> why we should create a constraint at all, if the index does exactly what we want it to do — ensure that values are unique. If we exclude <a href="https://www.postgresql.org/docs/current/indexes-partial.html">partial</a> indexes from the comparison, then from some point of view the result is really almost identical. The only difference we could point out is that constraints can be <a href="https://www.postgresql.org/docs/current/sql-set-constraints.html">deferrable</a>, while indexes can’t. In the documentation about older versions of PostgreSQL (up to and including 9.4), there was a <a href="https://www.postgresql.org/docs/9.4/indexes-unique.html">footnote</a> stating that the preferred way to create a uniqueness constraint was to explicitly create an ALTER TABLE … ADD CONSTRAINT, while the use of indexes should be considered as an implementation detail. However, in more recent versions this footnote is no longer there.</p><h3>Creating a primary key</h3><p>Besides uniqueness, a primary key also imposes a NOT NULL constraint. If the column initially had this restriction, it’s not difficult to turn it into a primary key — just create a unique index CONCURRENTLY, and then create a primary key:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>CONSTRAINT</strong> uk_my_table_id <strong>PRIMARY KEY<br>  USING</strong> <strong>INDEX</strong> uk_my_table_id -- if id is NOT NULL</pre><p>The column must have an “honest” NOT NULL constraint. The CHECK workaround discussed earlier won’t work.</p><p>If the column doesn’t have the required constraint, and if we’re using PostgreSQL versions before 11, we can’t create a primary key without locking the table.</p><p>But if we’re on PostgreSQL 11 or later, we can solve the problem by creating a new column to replace the existing one. Let’s go through it step by step.</p><p>Create a new column that is not-null by default, and that has a default value:</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>ADD</strong> <strong>COLUMN</strong> new_id INTEGER <strong>NOT</strong> <strong>NULL</strong> <strong>DEFAULT</strong> -1 <br>-- safe since PostgreSQL 11</pre><p>Set up data synchronization of the old and the new columns with a trigger:</p><pre><strong>CREATE</strong> <strong>FUNCTION</strong> on_insert_or_update() <strong>RETURNS</strong> TRIGGER <strong>AS</strong><br>$$<br><strong>BEGIN</strong><br>    NEW.new_id = NEW.id;<br>    <strong>RETURN</strong> NEW;<br><strong>END</strong>;<br>$$ <strong>LANGUAGE</strong> plpgsql;<br><br><strong>CREATE</strong> <strong>TRIGGER</strong> trg <strong>BEFORE</strong> <strong>INSERT</strong> <strong>OR</strong> <strong>UPDATE</strong> <strong>ON</strong> my_table<br><strong>FOR</strong> <strong>EACH</strong> <strong>ROW</strong> <strong>EXECUTE</strong> <strong>PROCEDURE</strong> on_insert_or_update();</pre><p>Then, update the data of the rows that were not affected by the trigger:</p><pre>-- <em>don’t do that on a large table<br></em><strong>UPDATE</strong> my_table <strong>SET</strong> new_id = id <strong>WHERE</strong> new_id = -1</pre><p>The update query above is very straightforward, and it’s better not to use it on a large table because it keeps the table locked for a long time.</p><p>As mentioned earlier, in the second part of this article we’ll discuss approaches to update large tables. For now, let’s assume that the data is updated, and that all we need to do is to swap the columns.</p><pre><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>RENAME</strong> <strong>COLUMN</strong> id <strong>TO</strong> old_id; <br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>RENAME</strong> <strong>COLUMN</strong> new_id <strong>TO</strong> id; <br><strong>ALTER</strong> <strong>TABLE</strong> my_table <strong>RENAME</strong> <strong>COLUMN</strong> old_id <strong>TO</strong> new_id;</pre><p>DDL commands in PostgreSQL are transactional, which means that you can rename, add, and delete columns without a concurrent transaction knowing about it during its execution.</p><p>After swapping the columns, all we need to do is create an index and clean up: delete the trigger, the function, and the old column.</p><h3>A quick cheat sheet with migrations</h3><p>It’s advisable to invoke a lock timeout before any queries that acquire a strict lock (almost all ALTER TABLE … queries):</p><pre><strong>SET</strong> <strong>LOCAL</strong> lock_timeout <strong>TO</strong> &#39;100ms&#39;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c348f9c236186e1a13546bb529db16cc/href">https://medium.com/media/c348f9c236186e1a13546bb529db16cc/href</a></iframe><p>In the <a href="https://medium.com/@nikolai_averin/sql-migrations-in-postgresql-part-2-3a14abd50873">second article</a>, we’ll discuss approaches to update large tables. Enjoy easy migrations everyone!</p><h3>Join our team!</h3><p>Would you like to be an Engineer at Miro? Check out opportunities to join the <a href="https://miro.com/careers/">Engineering team</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc38ec1cbe75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/miro-engineering/sql-migrations-in-postgresql-part-1-bc38ec1cbe75">SQL migrations in PostgreSQL, part 1</a> was originally published in <a href="https://medium.com/miro-engineering">Miro Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Databases from a Developer’s Perspective]]></title>
            <link>https://medium.com/miro-engineering/handling-databases-from-a-developers-perspective-fc916ab3fe68?source=rss-eef5965a3241------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc916ab3fe68</guid>
            <category><![CDATA[flyway]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nikolai Averin]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 05:38:49 GMT</pubDate>
            <atom:updated>2021-05-11T04:06:28.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling databases from a developer’s perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HVwTXeE0s4ClEVp.jpeg" /></figure><p>When you develop a new feature using databases, the development cycle usually includes (but is not limited to) the following steps:</p><p>Writing an SQL migration → writing source code → testing → release → monitoring.</p><p>In this article, I want to share some practical tips on shortening the cycle time for each of these stages without any loss in quality — instead, we would like to improve it.</p><p>Since we are working with PostgreSQL and our server code is written in Java, the examples will be based on this stack. However, most of these ideas will apply regardless of the database or programming language you are using.</p><h3>SQL migration</h3><p>The first development stage after designing the feature is writing an SQL migration. The most basic advice is not to make any manual changes to the data schema, but always to make changes through scripts that are all stored in one place.</p><p>Developers write SQL migrations themselves at our company, so migrations are stored in a repository alongside the source code. For some organizations, the schema is managed by database administrators. In such a case, the migration registry is stored somewhere at their side. In both cases, this approach brings the following benefits:</p><ul><li>You can always easily create a new database from scratch or upgrade existing ones to the current version. This allows you to deploy new test environments and local development environments quickly.</li><li>All databases have the same schema, which means no surprises in maintenance.</li><li>You can see the full history of all changes (versioning).</li></ul><p>There are several available tools to automate this process, both commercial and free: <a href="https://flywaydb.org/">Flyway</a>, <a href="https://www.liquibase.org/">Liquibase</a>, <a href="https://sqitch.org/">Sqitch</a>, and others. We’re not going to compare and choose the best tool in this article because that is a big, separate topic, and many other articles have already been written about it.</p><p>We’re using Flyway, so here’s some information on it.</p><ul><li>There are two types of migration: <a href="https://flywaydb.org/documentation/migrations#sql-based-migrations">SQL-based</a> and<a href="https://flywaydb.org/documentation/migrations#java-based-migrations"> Java-based</a>.</li><li>SQL migrations are immutable. After the first execution, an SQL migration cannot be changed. Flyway calculates the checksum for a migration file’s content and checks it for every run. For Java migrations to be immutable, additional <a href="https://flywaydb.org/documentation/migrations#checksums-and-validation">manual handling</a> is required.</li><li>The history of all migrations is stored in the <a href="https://flywaydb.org/getstarted/how">flyway_schema_history</a> (formerly schema_version) table. You can find the date and duration of each migration and its type, file name, and checksum there.</li></ul><p>Under our internal arrangements, all changes to the data schema are made only through an SQL migration. Their immutability ensures that we can always obtain a current schema that is entirely identical to all environments.</p><p>Java migrations are only used for DML when you can’t write in plain SQL. A typical case is a migration to Postgres from another database (we are moving from Redis to Postgres, but that’s a story for another day). One more example is updating the data for a large table in several transactions to minimize the table lock time. It’s worth mentioning that since the 11th version of Postgres, this can be done with SQL procedures on plpgsql.</p><p>When Java code becomes obsolete, the migration can be removed because we don’t want to produce legacy code (the Java class for the migration remains, but it’s blank). We set this to happen no sooner than a month after performing the migration in production — we believe this is enough time for all test environments and local development environments to update. Since Java migrations are used only for DML, its removal does not affect the creation of new databases from scratch.</p><h4>An important note for those who use pg_bouncer</h4><p>During the migration, Flyway acquires a lock to prevent multiple migrations from co-executing. To simplify, it works like this:</p><ul><li>A lock is acquired.</li><li>A transactional migration is executed.</li><li>The lock is released.</li></ul><p>For Postgres, Flyway uses <a href="https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS">advisory locks</a> in session mode, which means that to work properly, the application server must be running on the same connection when it is released as it was when it was acquired. If you use pg_bouncer in <a href="https://www.pgbouncer.org/config.html#pool_mode">transactional mode</a> (which is most common) or in statement mode, it can return a new connection for each transaction, and Flyway will not be able to release the lock.</p><p>To solve this problem, we use a small dedicated connection pool on pg_bouncer in session mode, which is intended for migrations only. On the application side, there is also a separate pool containing one connection that closes on a timeout after the migration is complete in order not to hold resources.</p><h3>Writing source code</h3><p>The migration is in place, so now we can write the code.</p><p>There are three approaches for working with the database on the application side:</p><ul><li>using ORM (for Java, hibernate is the de facto standard)</li><li>using plain SQL + jdbcTemplate or the like</li><li>using DSL libraries</li></ul><p>Using ORM reduces your SQL skill requirements — a lot of things are generated automatically:</p><ul><li>The data schema can be created from an XML description or a Java entity available from the code.</li><li>Object relations are defined using a declarative description — ORM will make joins for you.</li><li>With Spring Data JPA, even tricky queries can be generated automatically by the <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details">repository method’s signature</a>.</li></ul><p>One more bonus is data caching out of the box (for hibernate, 3 levels of caching).</p><p>But it is important to note that ORM, like any other powerful tool, requires specific skills to use. Without proper customization, the code is still likely to work, but far from optimally.</p><p>The opposite option is to write SQL manually. This allows you to control the queries fully — your queries will be performed exactly as you wrote them, without any surprises. But that increases the amount of manual labor and the requirements for the developers’ qualifications.</p><h4>DSL libraries</h4><p>Somewhere between these two approaches is another one: using DSL libraries (<a href="https://www.jooq.org/">jOOQ</a>, <a href="http://www.querydsl.com/">Querydsl</a>, etc.). These are usually much more lightweight than ORM, but more convenient than completely manual work with a database. Their usage is not so widespread, so in this article, we will briefly consider this approach.</p><p>We’re going to discuss <a href="https://www.jooq.org/">jOOQ</a>, which offers</p><ul><li>database inspection and automatic generation of classes</li><li>fluent API for writing queries</li></ul><p>Since jOOQ is not an ORM, there is no auto-generation of queries or caching, but some of the manual approach problems are fully covered:</p><ul><li>classes for tables, views, functions, and other database objects are generated automatically;</li><li>queries are written in Java, which ensures type safety — if the query is syntactically incorrect or has a wrong type parameter, it will not compile — your IDE will immediately indicate an error. You won’t have to spend time launching the application to check if the query is correct. This speeds up the development process and reduces the error probability.</li></ul><p>Queries in code look like <a href="https://www.jooq.org/doc/3.13/manual/sql-building/sql-statements/select-statement/">this</a>:</p><pre>BookRecord book = dslContext.selectFrom(BOOK)<br>                       .where(BOOK.LANGUAGE.eq(“DE”))<br>                       .orderBy(BOOK.TITLE)<br>                       .fetchAny();</pre><p>You can also use plain SQL if you want to:</p><pre>Result&lt;Record&gt; records = dslContext.fetch(“SELECT * FROM BOOK WHERE LANGUAGE = ? ORDER BY TITLE LIMIT 1”, “DE”);</pre><p>Obviously, in this case, the query’s correctness and the results parsing are completely on you.</p><h4>jOOQ Record and POJO</h4><p>BookRecord, in the example above, is a wrapper for the row in the “book” table that implements the <a href="https://www.martinfowler.com/eaaCatalog/activeRecord.html">active record</a> pattern. Because this class is a part of the data access layer (moreover, its specific implementation), you might not want to pass it to other layers of the application but rather use your POJO. For an easy record ↔ POJO conversion, jOOQ offers several mechanisms: <a href="https://www.jooq.org/doc/3.13/manual/sql-execution/fetching/pojos/">automatic ones</a> and <a href="https://www.jooq.org/doc/3.13/manual/sql-execution/fetching/pojos-with-recordmapper-provider/">a manual</a> one. The documentation referenced above contains various examples for reading, but there are no examples for inserting new data or updating it. Let us fill in this gap:</p><pre>private static final RecordUnmapper&lt;Book, BookRecord&gt; unmapper =<br>  book -&gt; new BookRecord(book.getTitle(), …); <em>// some kind of logics</em></pre><pre>public void create(Book book) {<br>    context.insertInto(BOOK)<br>           .set(unmapper.unmap(book))<br>           .execute();<br>}</pre><p>As you can see, it’s simple enough.</p><p>This approach allows you to hide implementation details within a data access layer class and avoid leaks to other application layers.</p><p>Jooq can also generate <a href="https://www.jooq.org/doc/3.13/manual/sql-execution/daos/">DAO</a> classes with a set of basic methods to simplify data handling for this table and reduce the amount of manual code writing (very similar to Spring Data JPA):</p><pre>public interface DAO&lt;R extends TableRecord&lt;R&gt;, P, T&gt; {<br>    void insert(P object) throws DataAccessException;<br>    void update(P object) throws DataAccessException;<br>    void delete(P… objects) throws DataAccessException;<br>    void deleteById(T… ids) throws DataAccessException;<br>    boolean exists(P object) throws DataAccessException;<br>    …<br>}</pre><p>We don’t use auto-generation DAO classes at our company — we only generate wrappers for database objects and write the queries manually. Wrapper generation takes place every time a dedicated Maven module for the migrations is rebuilt. Further in this article, there will be more details on how we implemented the wrapper generation.</p><h3>Testing</h3><p>Testing is an essential part of the development process. Useful tests guarantee the quality of your code and save time in its further maintenance. The opposite is also true: wrong tests may create an illusion of high-quality code, conceal errors, and slow down the development process. That’s why it is not enough just to decide that you’re going to write tests — you need to do it right. However, the proper test concept is very vague, and everyone has their idea of what it means.</p><p>The same is true for the classification of tests. In this article, we suggest the following classification:</p><ul><li>unit-testing</li><li>integration testing</li><li>end-to-end testing</li></ul><p><strong>Unit testing</strong> implies checking the functionality of each module separately from others. Once again, there is no single opinion on the size of the module. Some believe it should be a single method; others that it should be a class. Separation means that all other modules will be replaced with mocks or stubs in testing. Follow <a href="https://martinfowler.com/articles/mocksArentStubs.html">this link</a> to read Martin Fowler’s article about the difference between the two. Unit tests are small and fast, but they can only guarantee that an individual unit’s logic is correct.</p><p><strong>Integration testing</strong>, unlike unit testing, allows checking how several modules interact with each other. Working with a database is an excellent example of a situation where integration testing makes sense because it’s challenging to properly mock a database so that every critical detail is taken into account. In most cases, integration tests for databases make a good compromise between execution speed and quality assurance compared to other types of testing. That’s why we will discuss this type of testing more thoroughly in this article.</p><p><strong>End-to-end testing</strong> is the most extensive type of testing. To carry it out, you need to set up an entire environment. It guarantees the highest level of confidence in the product quality, although it is the slowest and most expensive type of test.</p><h4>Integration testing</h4><p>When it comes to implementing integration testing for code that works with a database, most developers have to address the same questions: how to start the database, initialize its state, and how to do so as quickly as possible.</p><p>Some time ago, it was common to use <a href="http://www.h2database.com/">H2</a> in integration testing. H2 is an in-memory database written in Java that has modes that allow <a href="http://www.h2database.com/html/features.html#feature_list">compatibility</a> with most popular databases. It’s versatile and doesn’t require installing a database, making it a very convenient replacement for actual databases, especially in applications that don’t depend on a specific database and use only what is included in the SQL standard (which is not always the case).</p><p>The trouble begins when you start to use some tricky database features that are not supported in H2 or completely new ones from a fresh release. In general, since this is a “simulation” of a specific DBMS, it might not perfectly reflect the behavior of that DBMS.</p><p>Another option is to use <strong>embedded Postgres</strong>. This is the real Postgres shipped as an archive; it also does not require installation. You may work with it as you would with a regular Postgres version.</p><p>There are several implementations thereof. The most popular are the ones developed by <a href="https://github.com/yandex-qatools/postgresql-embedded">Yandex</a> and <a href="https://github.com/opentable/otj-pg-embedded">openTable</a>. We used the Yandex version. Its disadvantages are a rather slow start (the archive is unpacked every time, and the database launch takes 2–5 seconds depending on the computer’s capacity) and the delay behind the official release version. We also had an error that occurred sometimes after an attempt to stop it with code: the Postgres process would keep running in the OS until we killed it manually.</p><h4>Testcontainers</h4><p>The third option is to use docker. There is a <a href="https://www.testcontainers.org/">Testcontainers</a> library that provides an API for working with docker containers through your code for Java. This way, any dependency in your application with a docker image can be <a href="https://www.testcontainers.org/features/creating_container/">replaced</a> in tests with Testcontainers. Also, there are separate ready-to-use classes for many popular technologies that provide a more convenient API, depending on the image used:</p><ul><li><a href="https://www.testcontainers.org/modules/databases/">database containers</a> (Postgres, Oracle, Cassandra, MongoDB, etc.)</li><li>nginx</li><li>Kafka</li><li>etc.</li></ul><p>By the way, when the Tescontainers project became popular, Yandex developers officially announced that they were stopping the development of their embedded Postgres project and advised everyone to switch to Testcontainers.</p><p>What are the pros:</p><ul><li>Testcontainers is fast (starting empty Postgres takes less than a second).</li><li>The Postgres community releases <a href="https://hub.docker.com/_/postgres">official docker images</a> for each new version.</li><li>Testcontainers has a <a href="https://www.testcontainers.org/features/configuration/#customizing-ryuk-resource-reaper">dedicated process</a> that kills hanging containers after shutting JVM down unless you have killed them yourself.</li><li>with Testcontainers you can use a unified approach to test your application’s external dependencies, which makes things easier.</li></ul><p>An example of a <a href="https://github.com/testcontainers/testcontainers-java/blob/master/modules/postgresql/src/test/java/org/testcontainers/junit/postgresql/SimplePostgreSQLTest.java">test</a> with Postgres:</p><pre><a href="http://twitter.com/Test">@Test</a><br>public void testSimple() throws SQLException {<br>    try (PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;()) {<br>        postgres.start();<br>        ResultSet resultSet = performQuery(postgres, &quot;SELECT 1&quot;);<br>        int resultSetInt = resultSet.getInt(1);<br>        assertEquals(&quot;A basic SELECT query succeeds&quot;, 1, resultSetInt);<br>    }<br>}</pre><p>If there is no separate class for the image in Testcontainers, then creating a container looks like <a href="https://www.testcontainers.org/features/creating_container/#examples">this</a>:</p><pre>public static GenericContainer redis = new GenericContainer(“redis:3.0.2”).withExposedPorts(6379);</pre><p>Testcontainers has extra <a href="https://www.testcontainers.org/#prerequisites">support</a> for JUnit4, JUnit5, and Spock, making writing tests easier if you are using these frameworks.</p><h4>Speeding up tests with Testcontainers</h4><p>Switching from embedded Postgres to Testcontainers made our tests faster because the Postgres launch was taking less time. However, over time, the tests began to slow down again due to the increased SQL migrations that Flyway performs at startup. When the number of migrations exceeded one hundred, the execution time was about 7–8 seconds, which significantly slowed down the tests. Here’s how it worked:</p><ol><li>Before the next test class, a “clean” container with Postgres was launched.</li><li>Flyway performed the migrations.</li><li>Tests for this class were executed.</li><li>The container was stopped and removed.</li><li>All of this was repeated for the next test class.</li></ol><p>Obviously, over time, the second step took longer and longer.</p><p>While trying to solve this problem, we realized that it is enough to perform migrations only once before all tests, save the container’s state, and then use it for all tests. So we changed the algorithm:</p><ol><li>A “clean” container with Postgres launches before all tests.</li><li>Flyway performs the migrations.</li><li>The сontainer state is saved.</li><li>Before the next test class, a previously prepared container is launched.</li><li>Tests for this class are executed.</li><li>The container stops and is removed.</li><li>The algorithm repeats from step 4 for the next test class.</li></ol><p>Now the execution time of an individual test doesn’t depend on the number of migrations, and with the current number of migrations (200+), the new algorithm saves several minutes on each run of all tests.</p><h4>Here are some advanced tips on how to implement it.</h4><p>Docker has a built-in mechanism for creating a new image from a running container using the <a href="https://docs.docker.com/engine/reference/commandline/commit/">commit</a> command. This allows you to customize the images, for example, by changing some settings.</p><p>An important detail is that this command doesn’t save the data of the mounted partitions. But suppose you use the official Postgres docker image. In that case, the PGDATA directory in which the data is stored is located in such a separate partition so as not to lose data after restarting. So, when the commit is executed, the state of the database will not be saved.</p><p>The solution is to not use the partition for PGDATA but to keep the data in memory, which is quite normal for tests. There are two ways to achieve this: (1) use your dockerfile (it may look <a href="https://github.com/docker-library/postgres/blob/master/11/alpine/Dockerfile">like this</a>) without creating a directory, or (2) override the PGDATA variable when starting the official container (the former directory will still be made, but won’t be used). The second way seems much simpler:</p><pre>PostgreSQLContainer&lt;?&gt; container = ...<br>container.addEnv(&quot;PGDATA&quot;, &quot;/var/lib/postgresql/data-no-mounted&quot;);<br>container.start();</pre><p>It is recommended to make a <a href="https://www.postgresql.org/docs/current/sql-checkpoint.html">checkpoint</a> for Postgres before committing to copy the shared buffers’ changes to the “disk” (which matches the overridden PGDATA variable):</p><pre>container.execInContainer(“psql”, “-c”, “checkpoint”);</pre><p>This is how the commit is executed:</p><pre>CommitCmd cmd = container.getDockerClient().commitCmd(container.getContainerId())<br>                .withMessage(&quot;Container for integration tests. ...&quot;)<br>                .withRepository(imageName)<br>                .withTag(tag);<br>String imageId = cmd.exec();</pre><p>It should be noted that the approach of using prepared images can be implemented for many other images, which will also save time during integration tests.</p><h4>A few more words about optimizing build time</h4><p>As it has been mentioned earlier, when building the separate Maven module with migrations, among other things, Java wrappers are generated over the database objects. We use a self-written Maven plugin that runs before compiling the main code and performs three actions:</p><ol><li>It launches a “clean” docker container with Postgres.</li><li>It launches Flyway to perform SQL migrations for all databases, thereby checking their validity.</li><li>It launches Jooq to inspect the database schema and generate Java classes for tables, views, functions, and other schema objects.</li></ol><p>As you can see, the first two actions are identical to those performed when the tests start. To save time on creating the container and running migrations before tests, we have moved the container state’s saving state to the plugin. This means that the prepared images of all databases used in the code will appear in the local Docker images repository immediately after rebuilding the module.</p><p><strong>A more detailed code example</strong></p><p>An adapter for PostgreSQLContainer for use in the plugin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e6b05a8559c870f47c17e450075869a/href">https://medium.com/media/5e6b05a8559c870f47c17e450075869a/href</a></iframe><p>The plugin’s start goal implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d675bfa5a86e12a40149dd53306746e1/href">https://medium.com/media/d675bfa5a86e12a40149dd53306746e1/href</a></iframe><p>Thesave-stateand stop goals are implemented in a very similar way and therefore omitted here.</p><p>Using in pom.xml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c20c68b74a047492589b8cf331e2b0a2/href">https://medium.com/media/c20c68b74a047492589b8cf331e2b0a2/href</a></iframe><h3>Release</h3><p>The code has been written and tested, and now it’s time to release. In general, the complexity of a release depends on the following factors:</p><ul><li>the number of databases (one or more)</li><li>the database size</li><li>the number of application servers (one or more)</li><li>whether the release is seamless (whether application downtime is allowed)</li></ul><p>The first and third items above impose a backward compatibility requirement on the code since, in most cases, it is impossible to update all databases and all application servers simultaneously: there will always be a moment when the databases have different schemas, and the servers have different versions of the code.</p><p>The database size affects the migration time: the larger the database, the more likely you will have to perform a long migration.</p><p>Being seamless is partly a resulting factor: if a release is performed with a downtime, then the first three items are not so important and only affect the time when the app is unavailable.</p><p>Here’s what our service looks like:</p><ul><li>There are about 30 database clusters.</li><li>The size of a single database is 200–400 GB.</li><li>Several application servers (their number is auto-scaled during the day depending on the load; it can exceed 100 at peak times), and each server is connected to all databases.</li><li>Our releases are seamless.</li></ul><p>We do <a href="https://martinfowler.com/bliki/CanaryRelease.html">canary releases</a>: a new version of the application is first applied to a few servers (we call it a prerelease), and after a while, if no errors are found in the prerelease, this version is released to the rest of the servers. Thus, production servers can have different versions.</p><p>Each application server checks the DB version against the script versions from the source code (in terms of Flyway, this is called <a href="https://flywaydb.org/documentation/command/validate">validation</a>). If the versions differ, the server will not start, which guarantees compatibility between the code and the database. This also prevents a situation where, for example, a code is trying to access a database table that hasn’t been created yet because the migration is in a different version of the server.</p><p>But this certainly does not resolve the problem when, for example, a new version of an application has a migration that removes a column from a table that can still be used in the old version of the server. Currently, we only check such situations at the review stage (which is mandatory), but we need to implement a different stage with this check our CI/CD cycle.</p><p>Sometimes migrations can take a lot of time (for example, updating data in a large table); in this case, we use a combined migration technique to avoid slowing down the releases. This technique consists of two steps. First, we manually run the migration on a running server (via the administration panel, without Flyway, and, accordingly, without any record in the <a href="https://flywaydb.org/documentation/migrations#schema-history-table">schema history table</a>). Second, we do the same migration in the “regular” way at the server’s next version. The migrations of this kind must satisfy the following requirements:</p><ul><li>It must be written so that it does not block the application when it’s running for a long time (the main point here is not to acquire long-term locks at the database level). To do so, we have internal guidelines for developers on how to write migrations. In the future, we may also share them on Medium.</li><li>A “regular” run of the migration should realize that it has already been performed in manual mode; in this case, it should do nothing but add a new record in the schema history table. For SQL migrations, such a check is performed by executing an SQL query to see if anything has changed. There is another approach for Java migrations — we use some stored boolean flags that are set after a manual run.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1I5k8snI0J02QZL" /></figure><p>This approach solves two problems:</p><ul><li>The release is fast (though with some manual actions).</li><li>All environments (the local ones for developers and the test ones) are updated automatically without manual actions.</li></ul><h3>Monitoring</h3><p>The development cycle doesn’t end after the release. To understand whether the new features work (and how they do), you need to add many metrics. They can be divided into two groups.</p><p>The<strong> first group</strong> are the very domain-specific metrics: it’s useful for a mail server to know the number of messages sent, a news resource to see the number of unique users per day, etc.</p><p>The <strong>second group</strong>’s metrics are pretty much universal: they determine the technical state of the server, such as CPU consumption, memory allocation, network load, database status, and so on.</p><p>What exactly you need to monitor and how to do it is the topic of an impressive number of dedicated articles so that it won’t be discussed here. We would like only to remind you of the essential things (here comes Captain Obvious):</p><p><strong>Define the metrics in advance<br></strong>You need to define a list of basic metrics. And you should do this in advance, before the release — not after the first incident when you don’t understand what is happening to the system.</p><p><strong>Set up automatic alerts<br></strong>This will speed up your reactions and will save time on manual monitoring. Ideally, you should know about problems before users start to notice and point them out to you.</p><p><strong>Collect the metrics from all nodes<br></strong>You can never have too many metrics or logs. Having data from each node of your system (application server, database, connection pooler, load balancer, etc.) allows you to see the complete picture of its status, and if necessary, to quickly localize the problem.</p><p>A simple example: loading data from a web page is getting slower. There could be many reasons:</p><ul><li>The web server is overloaded and is taking a long time to respond to requests.</li><li>The SQL query now takes longer than usual to execute.</li><li>A longer queue appears at the connection pooler, and the application server can’t get a connection for a long time.</li><li>There are network problems.</li><li>Something else.</li></ul><p>Finding the cause of the problem without metrics won’t be easy.</p><h3>Instead of a conclusion</h3><p>I would like to say quite an obvious thing about the fact that there is no one-size-fits-all solution, and the choice of one approach over another depends on the requirements of the particular task — what works well for others may not be applicable to you. But the more different approaches you are aware of, the more thorough and efficient your decision-making will be. I hope you’ve learned something new from this article that will help you in the future. I would be happy to see comments on what approaches you use to improve your working processes with databases!</p><h3>Join our team!</h3><p>Would you like to be an Engineer, Team Lead or Engineering Manager at Miro? Check out opportunities to join the <a href="https://miro.com/careers/">Engineering team</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc916ab3fe68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/miro-engineering/handling-databases-from-a-developers-perspective-fc916ab3fe68">Handling Databases from a Developer’s Perspective</a> was originally published in <a href="https://medium.com/miro-engineering">Miro Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL: bloat, pg_repack, and deferred constraints]]></title>
            <link>https://medium.com/miro-engineering/postgresql-bloat-pg-repack-and-deferred-constraints-d0ecf33337ec?source=rss-eef5965a3241------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ecf33337ec</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[pgrepack]]></category>
            <category><![CDATA[bloat]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Nikolai Averin]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 10:48:24 GMT</pubDate>
            <atom:updated>2020-09-02T08:38:36.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Table/index bloating is a widely known effect and is not unique to PostgreSQL. There are built-in methods to deal with it like VACUUM FULL or CLUSTER, but they lock tables and therefore cannot always be used.</p><p>This article contains a bit of theory on how bloat occurs, how to deal with it, what are deferred constraints, and what problems they bring when using the pg_repack extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yYDfXmdHVvTUpBrj.jpeg" /></figure><h3>Why bloat occurs</h3><p>PostgreSQL uses a multiversion model (<a href="https://www.postgresql.org/docs/current/mvcc-intro.html">MVCC</a>). The essence of that model is that each table row can have multiple versions, but transactions can only see one of them and not necessarily the same one. This allows multiple transactions to work simultaneously with little or no impact on each other.</p><p>Of course, all these versions need to be stored somewhere. PostgreSQL uses a paging mechanism to manage the memory, and one page is the minimum amount of data that can be read from or written to disk. Let’s look at a small example to see how this works.</p><p>Suppose we have a table with some newly added records. The first page of that table’s file will contain the new data. These are “live” versions of the rows, which are available to other transactions after the commit (for simplicity, we will assume that the isolation level is Read Committed).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*_Qs3Oa6p8zSbEoNM" /></figure><p>Next, we will update one of the records, which will mark the previous version as obsolete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*0aDzBaQBkUzwwJ7h" /></figure><p>Step by step, by updating and deleting rows, we will get a page that is half-filled with garbage data. This data is invisible to any transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*dESJIQgXzJqzR-kj" /></figure><p>PostgreSQL has a <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">VACUUM</a> function that removes obsolete versions and frees up space for new data. But if it is not configured aggressively enough or is busy working with other tables, the garbage data will persist, and we will have to use additional pages for new data.</p><p>In our example, the table, at some point, will consist of four pages, but only half of that data will be live. As a result, if we try to access the table, we will read much more data than necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*PRbRBTvQr2V9fxCw" /></figure><p>Now, even if VACUUM does remove obsolete row versions, the situation will not improve dramatically. We will have free space in the pages (or even completely free pages) for new rows, but we will still be reading more data than we need to.</p><p>By the way, if the completely empty page (the second in our example) were at the end of the file, VACUUM would be able to remove it. But as it is right now, it is in the middle, so nothing can be done with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*g8SSwgUSk4YXPv37" /></figure><p>When the number of such empty or heavily fragmented pages becomes large, this is called bloat, and it begins to affect the performance.</p><p>Everything described above is the mechanics of how bloat occurs in tables. For indexes, the process is more or less the same.</p><h3>Do I have bloat?</h3><p>There are several ways to determine if you have bloat. The first way is to use PostgreSQL internal statistics, which contain approximate information about the total number of rows in tables, the number of live rows, and so on. You can find many variations of scripts for that on the Internet. As a basis, we used the <a href="https://github.com/pgexperts/pgx_scripts/tree/master/bloat">script</a> from PostgreSQL Experts that can estimate table bloat as well as TOAST bloat and B-tree index bloat. In our experience, its margin of error is about 10 to 20 percent.</p><p>We also used the <a href="https://postgres.ai/products/postgres-checkup/">postgres-checkup</a> tool, which, in addition to an approximate estimate of the bloat (the evaluation logic is similar), gives a lot of other valuable <a href="https://postgres.ai/docs/postgres-checkup/postgres-checkup-overview#reports">information</a> about the state of the database.</p><p>Another way is to use the <a href="https://www.postgresql.org/docs/current/pgstattuple.html">pgstattuple</a> extension, which allows you to look inside the pages and get both estimated and exact bloat values. But to get the exact values, you have to scan the entire table.</p><p>A little bloat, up to 20 percent, we consider acceptable. It can be thought of as an analog of Fill factor for <a href="https://www.postgresql.org/docs/current/sql-createtable.html#RELOPTION-FILLFACTOR">tables</a> and <a href="https://www.postgresql.org/docs/current/sql-createindex.html#INDEX-RELOPTION-FILLFACTOR">indexes</a>. At 50 percent and above, performance problems may start to occur.</p><h3>Dealing with bloat</h3><p>There are several built-in ways to deal with bloat in PostgreSQL, but all of them are far from universal solutions.</p><p><strong>Configure AUTOVACUUM to prevent bloat from happening,</strong> or more precisely, to keep it at an acceptable level. This might seem like obvious advice, but in reality, it is not always easy to achieve. Let’s say, for example, that your active development involves regular schema changes or that you are doing some sort of data migration. As a result, your load profile can change frequently, and it is usually different for different tables. That means that you always have to work a little ahead and adjust AUTOVACUUM to the changing profile of each table. Clearly, this is not easy to do.</p><p>Another common reason that AUTOVACUUM is unable to process tables in time is the presence of long transactions that prevent it from reclaiming the occupied storage because that storage is available to these transactions. The recommendation here is also obvious — get rid of hanging transactions and minimize the duration of active transactions. But if your workload is a mix of OLAP and OLTP, you can have many frequent updates and short queries, and long-running operations (like building a report) at the same time. In such a situation, it is worth thinking about distributing the load across multiple databases, which will allow for more fine-tuning of each of them.</p><p>As another example, even if the load profile is uniform, if the database is under heavy load, even the most aggressive AUTOVACUUM may not be enough, and bloat will occur. Scaling (vertical or horizontal) is the only solution.</p><p>What about the situation when AUTOVACUUM is configured but bloat continues to grow?</p><p>The <strong>VACUUM FULL</strong> command rebuilds the contents of tables and indexes, keeping only the actual data. For eliminating bloat, it works perfectly, but during the execution, it locks the table with an AccessExclusiveLock, which does not allow any queries against that table, even SELECT. If you can afford to temporarily stop your service or part of it for some time (from tens of minutes to several hours, depending on the size of the database and your hardware), then this is the best option. Unfortunately, we do not have enough time to run VACUUM FULL during a scheduled maintenance period, so this approach does not suit us.</p><p>The <strong>CLUSTER</strong> command, like VACUUM FULL, also rebuilds the contents of tables, but it allows you to specify an index based on which the data will be physically reordered on the disk (but it does not guarantee that index order for new rows). In certain situations, this is a good optimization for a number of queries — those that read multiple rows by index. The CLUSTER command has the same disadvantage as the VACUUM FULL command: it locks the table during its operation.</p><p>The <strong>REINDEX</strong> command is similar to the previous two, but it rebuilds a specific index or all indexes on a table. Its locks are slightly weaker: ShareLock on the table (prevents modification but allows SELECT) and AccessExclusiveLock on the index that is being rebuilt (blocks all queries that use that index). However, version 12 of PostgreSQL introduced the <a href="https://www.postgresql.org/docs/12/sql-reindex.html">CONCURRENTLY</a> option, which allows you to rebuild an index without blocking inserts, updates, and deletes.</p><p>With earlier versions of PostgreSQL, you can achieve similar results to REINDEX CONCURRENTLY with <a href="https://www.postgresql.org/docs/9.1/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY">CREATE INDEX CONCURRENTLY</a>. It allows you to create a new index without a strict lock (it uses a ShareUpdateExclusiveLock, which allows both reads and writes on the table), then replace the old index with the new one and delete the old one. This eliminates index bloat without interfering with your application. It is important to note that the index rebuild process causes an additional load on the file system.</p><p>Thus, there are ways to eliminate bloat on a running database for indexes, but not for tables. This is where the various external extensions come into play: <a href="https://github.com/reorg/pg_repack">pg_repack</a> (formerly pg_reorg), <a href="https://github.com/grayhemp/pgtoolkit">pgcompact</a>, <a href="https://github.com/dataegret/pgcompacttable">pgcompacttable</a>, and others. In this article, I will not compare them and will only talk about pg_repack, which, after some modification, we use in our product.</p><h3>How does pg_repack work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*utQ_D2zDSo1Y2kle" /></figure><p>Suppose that we have a typical table with indexes, constraints, and (unfortunately) bloat. The first thing pg_repack does is to create a log table to store all data changes that occur during the operation. A trigger will record all inserts, updates, and deletes. Then it creates a table that is structurally similar to the original table, but without indexes and constraints so as not to slow down the data insertion process.</p><p>Next, pg_repack moves the data from the old table to the new table, automatically filtering out all dead rows, and then it creates indexes for the new table. During the execution of all these operations, changes are accumulated in the log table.</p><p>The next step is to transfer these changes to the new table. The transfer is performed in several iterations, and when there are less than 20 records remaining in the log table, pg_repack acquires a strict lock, moves the rest of the data, and replaces the old table with the new one in the PostgreSQL system tables. This is the only and very short period of time when you cannot work with the table. After that, the old table and the log table are dropped to free disk space. And that is it, all done.</p><p>Everything looks great in theory, but what about in practice? We tested pg_repack both without and under load and also tested how well it works after being interrupted (Ctrl+C, to put it simply). All test results were great.</p><p>We moved on to the production environment, and this is where things went not the way we expected.</p><h3>First failure at the production server</h3><p>The first cluster gave us an error about a violation of a unique constraint:</p><pre>$ ./pg_repack -t tablename -o id<br>INFO: repacking table “tablename”<br>ERROR: query failed:<br>ERROR: duplicate key value violates unique constraint “index_16508” DETAIL: Key (id, index)=(100500, 42) already exists.</pre><p>This constraint had an autogenerated name index_16508 — it was created by pg_repack. By its attributes, we had identified our constraint that corresponded to it. The problem turned out to be that this is not an ordinary constraint, but a <a href="https://www.postgresql.org/docs/current/sql-set-constraints.html">deferred constraint</a>, i.e., it is enforced after an SQL query, which leads to unexpected consequences.</p><h3>Deferred constraints: Why you may need them and how they work</h3><p>A bit of theory on deferred constraints.</p><p>Consider a simple example. We have a table of cars with two columns: the name of the car and its order number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*ZUCdEteobWQObwdH" /><figcaption>cars</figcaption></figure><pre>create table cars <br>(<br>  name text constraint pk_cars primary key, <br>  ord integer not null constraint uk_cars unique<br>);</pre><p>Let’s say we need to swap the order number of the first two cars. A direct approach would be to set the first value to the second value, and vice versa:</p><pre>begin;<br>  update cars set ord = 2 where name = ‘audi’;<br>  update cars set ord = 1 where name = ‘bmw’;<br>commit;</pre><p>But if we try to run this code, we will expectedly get a constraint violation error because the order number must be unique:</p><pre>[23305] ERROR: duplicate key value violates unique constraint “uk_cars”<br>Detail: Key (ord)=(2) already exists.</pre><p>How to do this differently? Option one would be to use a temporary value that is guaranteed not to exist in the table, like -1. In programming, this is known as swapping the values of two variables using a third variable. The only drawback to this method is the need for an additional update.</p><p>The second option is to redesign the table and change the data type of the order number column from integer to floating-point. Then, if we update the value from 1 to, for example, 2.5, the first record will be placed between the second and the third records. This solution works, but there are two limitations. First, it will not work for you if the value is used somewhere in the user interface. Second, depending on the accuracy of the data type, you will have a limited number of possible updates before you will have to recalculate the values of all records.</p><p>Option number three is to make the constraint deferred so that it is enforced only on commit:</p><pre>create table cars<br>(<br>  name text constraint pk_cars primary key,<br>  ord integer not null constraint uk_cars unique <strong>deferrable initially deferred</strong><br>);</pre><p>Since the logic of our initial query ensures that all values are unique at the time of a commit, it will execute successfully.</p><p>The above example is, of course, very artificial, but it explains the idea. In our application, we use deferred constraints to implement the logic for resolving conflicts that happen when multiple users are working simultaneously with the same objects/widgets on a whiteboard. The use of deferred constraints allows us to make the application code a bit simpler.</p><p>In general, depending on the type of constraint, there are three levels of granularity of constraint enforcement in PostgreSQL: row, statement, and transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ys3Cf5XO6gr6cPI_XPFX9w.png" /><figcaption>Source: <a href="http://begriffs.com/posts/2017-08-27-deferrable-sql-constraints.html">begriffs</a></figcaption></figure><p>CHECK and NOT NULL are always enforced at the row level; for other constraints, as can be seen from the table, there are different options. You can read more about that <a href="http://begriffs.com/posts/2017-08-27-deferrable-sql-constraints.html">here</a>.</p><p>To summarize briefly, deferred constraints in a number of situations allow for more readable code and fewer queries. The downside of that, however, is the complication of the debugging process, since the moment an error occurs and the moment you find out about it will be separated in time. Another possible problem is that the planner cannot always build an optimal plan if a deferred constraint is involved in the query.</p><h3>Modifying pg_repack</h3><p>Now we know what deferred constraints are, but how are they related to our problem? Let’s recall the error we previously encountered:</p><pre>$ ./pg_repack -t tablename -o id<br>INFO: repacking table “tablename”<br>ERROR: query failed:<br>ERROR: duplicate key value violates unique constraint “index_16508”<br>DETAIL: Key (id, index)=(100500, 42) already exists.</pre><p>It occurs when the data is copied from the log table to the new table. It looks strange because the data from the log table is committed together with the data from the original table. If that data satisfies the constraints of the original table, how can it violate the same constraints in the new table?</p><p>As it turns out, the root of the problem lies in the previous step of pg_repack where it creates indexes but not constraints: The old table had a unique constraint, but the new table has a unique index instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jBLDkI07jgGcLhY_" /><figcaption>creation indexes for the new table</figcaption></figure><p>It is important to note here that if the constraint is not deferred, the unique index created instead of that constraint will be equivalent to it because, in PostgreSQL, unique constraints are implemented by creating a unique index. But in the case of a deferred constraint, the behavior is different because an index cannot be deferred and is always enforced at the time a query is executed.</p><p>Thus, the essence of the problem lies in the fact that the enforcement is deferred: In the original table, it occurs at the time of a commit, and in the new table, it occurs at the time a query is executed. Therefore, we need to make sure that the enforcements are the same in both cases: either always deferred or always immediate.</p><p>So, what ideas did we have?</p><h3>Create an index similar to deferred</h3><p>The first idea is to enforce both checks in immediate mode. This may cause some false positive constraint violations, but if there are only a few of them, it should not affect the user experience, since such conflicts are a regular thing for users. They happen, for example, when two users start modifying the same widget at the same time and the second user’s client is not able to receive in time the information that the widget is already locked by the first user. In such a situation, the server responds to the second user with an error, and the client rolls back the changes and locks the widget. Later, when the first user finishes modifying the widget, the second user will receive the information that the widget is no longer locked and they will be able to repeat their action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*kOs5gqE2_xH6_RVUJJMpdA.gif" /></figure><p>To ensure that the checks are always immediate, we created a new index that is similar to the original deferred constraint:</p><pre>CREATE UNIQUE INDEX CONCURRENTLY uk_tablename__immediate ON tablename (id, index);<br> — run pg_repack<br>DROP INDEX CONCURRENTLY uk_tablename__immediate;</pre><p>In the test environment, we received only a few expected errors. It’s a success! Then, we launched pg_repack in the production environment again and got five errors on the first cluster in an hour. This is an acceptable result. However, the number of errors on the second cluster already had a manifold increase and we had to stop pg_repack.</p><p>Why did it happen? The probability of an error depends on how many users work simultaneously with the same widgets. Apparently, at that time, the first cluster had a much smaller number of concurrent data changes than the others, so we just got “lucky.”</p><p>The idea did not work. At that moment, we saw two other solutions: rewrite our application code to stop using deferred constraints or modify pg_repack to add support for them. We chose the second one.</p><h3>Replacing the indexes in the new table with the deferred constraints from the original table</h3><p>The purpose of the modification was obvious: if the original table has a deferred constraint, a deferred constraint should be created in the new table, not an index.</p><p>To test our changes, we wrote a simple test:</p><ul><li>create a table with a deferred constraint and one record;</li><li>make a loop to insert new data that will conflict with the existing record;</li><li>make an UPDATE query to resolve the conflicts;</li><li>commit changes.</li></ul><pre>create table test_table<br>(<br>  id serial,<br>  val int,<br>  constraint uk_test_table__val unique (val) deferrable initially deferred<br>);</pre><pre>INSERT INTO test_table (val) VALUES (0);</pre><pre>FOR i IN 1..10000 LOOP<br>  BEGIN<br>    INSERT INTO test_table VALUES (0) RETURNING id INTO v_id;<br>    UPDATE test_table set val = i where id = v_id;<br>    COMMIT;<br>  END;<br>END LOOP;</pre><p>The original version of pg_repack always failed on the first INSERT; the modified one worked without errors. Excellent.</p><p>Moving to the production environment, we encountered the same error when the data was copied from the log table to the new table:</p><pre>$ ./pg_repack -t tablename -o id<br>INFO: repacking table “tablename”<br>ERROR: query failed:<br>ERROR: duplicate key value violates unique constraint “index_16508”<br>DETAIL: Key (id, index)=(100500, 42) already exists.</pre><p>Classic. The code that works in the test environment does not work in the production environment.</p><h3>APPLY_COUNT and the juncture of two chunks</h3><p>We started analyzing the code, literally line by line, and found an important part: data is copied from the log table to the new table in chunks, and the APPLY_COUNT constant defines the size of a chunk:</p><pre>for (;;)<br>{<br>  num = apply_log(connection, table, APPLY_COUNT);</pre><pre>  if (num &gt; MIN_TUPLES_BEFORE_SWITCH)<br>    continue; /* there might be still some tuples, repeat. */<br>  …<br>}</pre><p>The problem is that queries from the initial transaction that violate a constraint can become broken into two chunks, which will be committed separately. And this part is a complete matter of chance: if the queries from the first chunk do not violate any constraint, then everything is fine, but if they do, an error occurs.</p><p>APPLY_COUNT is set to 1,000 queries, which explains why our tests were successful — they did not cover the cases of chunking. We used two queries, one INSERT, and one DELETE, so exactly 500 query pairs were placed in a chunk and we did not encounter any problems. After we added a second UPDATE, our modification stopped working:</p><pre>FOR i IN 1..10000 LOOP<br>  BEGIN<br>    INSERT INTO test_table VALUES (1) RETURNING id INTO v_id;<br>    UPDATE test_table set val = i where id = v_id;<br>    UPDATE test_table set val = i where id = v_id; — one more update<br>    COMMIT;<br>  END;<br>END LOOP;</pre><p>So, our next task was to make sure that the data from the original table that was changed within the scope of one transaction was copied to the new table also within one transaction.</p><h3>Getting rid of chunking</h3><p>Again, we had two options. Option number one: get rid of chunking completely and copy all data as one transaction. One advantage of this option is its simplicity: the required code changes are minimal (by the way, this is exactly how the previous version of pg_repack, pg_reorg, was written). But there is a problem: we create a long transaction, and this, as was said before, increases the possibility of bloat.</p><p>Option number two is more complicated but probably more correct: create a column in the log table that will identify the transaction that added the data to the table. Then, when copying data, we can group it by that column and ensure that related changes are transferred together. A chunk will consist of several transactions (or one big one), and its size will vary depending on how many changes these transactions contain. It is important to note that since transaction data in the log table is accumulated in a random order, it will no longer be possible to read it sequentially. A sequential scan for every query that filters by txid is too expensive; we need an index, but even that will slow down this method due to the overhead of updating it. So, as always, you have to sacrifice something.</p><p>We decided to start with the first option, the simpler one. First, we needed to figure out whether a long transaction would be a real problem. Since the main data transfer from the original table to the new table also occurs in one long transaction, the question can be formulated as follows: How much will we extend this transaction? The duration of the first transaction depends mainly on the size of the table. The duration of the new transaction will depend on how many changes will accumulate in the table during the data transfer, i.e., on the database load. We did a pg_repack run during a minimum load period, and the number of changes was infinitely small compared to the size of the original table. We decided that we can neglect the duration of the new transaction (for comparison, it is one hour and two or three minutes on average).</p><p>The experiments were successful. The production run also went smoothly. To demonstrate, here is a chart of the size of one database after the run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_WOwk3anOcLyQCpI" /></figure><p>Since we were completely satisfied with this solution, we did not try to implement the second one but are considering discussing it with the extension developers. Our current revision, unfortunately, is not yet ready for publication as we have only solved the problem with deferred unique constraints, and a fully fledged patch requires adding support for other types as well. We hope we will be able to do that in the future.</p><p>You might be asking yourself: Why did they even bother modifying pg_repack instead of using any other similar tool? At some point, we were thinking about that, but the positive experience we had using it earlier (on tables without deferred constraints) motivated us to try to understand the problem and fix it. Besides, using other solutions would also require time for testing, so we decided that first, we would try to fix the problem with pg_repack, and if we were not able to do that in a reasonable time, then we would consider other tools.</p><h3>Conclusions</h3><p>What we can recommend based on our experience:</p><ol><li>Monitor your bloat. By using your monitoring data, you will be able to understand how well AUTOVACUUM is configured.</li><li>Configure AUTOVACUUM to keep bloat at an acceptable level.</li><li>If bloat still grows and you cannot beat it using built-in methods, do not be afraid to use external extensions. Just remember to properly test everything.</li><li>Do not be afraid to modify external solutions to your needs. Sometimes this can be more effective and even easier than changing your own code.</li></ol><p>PS: Big thanks to guys from <a href="http://postgres.ai/">postgres.ai</a> for helping with detecting the problem of bloat and finding possible solutions.</p><h3>Join our team!</h3><p>Would you like to be an Engineer, Team Lead or Engineering Manager at Miro? Check out opportunities to join the <a href="https://miro.com/careers/">Engineering team</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ecf33337ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/miro-engineering/postgresql-bloat-pg-repack-and-deferred-constraints-d0ecf33337ec">PostgreSQL: bloat, pg_repack, and deferred constraints</a> was originally published in <a href="https://medium.com/miro-engineering">Miro Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>