<?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 Vineet Naik on Medium]]></title>
        <description><![CDATA[Stories by Vineet Naik on Medium]]></description>
        <link>https://medium.com/@naikvin_34014?source=rss-8245797404f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5onxtqU7nhsGKO9Ijb_-lw.jpeg</url>
            <title>Stories by Vineet Naik on Medium</title>
            <link>https://medium.com/@naikvin_34014?source=rss-8245797404f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:25:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naikvin_34014/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[Updating PostgreSQL server config]]></title>
            <link>https://medium.com/helpshift-engineering/updating-postgresql-server-config-78dc43150be9?source=rss-8245797404f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/78dc43150be9</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Vineet Naik]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 04:43:14 GMT</pubDate>
            <atom:updated>2023-10-11T07:31:06.388Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are running a PostgreSQL (pg) server in production for a fair amount of time, chances are that you’d have had to change its configuration at least once by now. Overtime any database server needs regular tuning to make it operationally suitable to the evolving needs, particularly if it powers a successful/growing product.</p><p>In case of pg, the simplest way to update server configuration is to make changes in the config file, postgresql.conf and restart the server process. But depending on your setup, doing this without downtime could be non-trivial at best (if your setup is highly available) or impossible at worst (if there’s just one server running).</p><p>The good news is that in pg not all config parameter changes require a server restart. But how do we know whether or not the parameter we want to change requires a restart?</p><h4>The pg_settings view</h4><p>The builtin view pg_settings can give us this information. This view provides access to run-time config parameters of the server through SQL queries. If you are connected to the db using psql, try running select * from pg_settings limit 10; to quickly check the schema.</p><p>The column we’re interested in is context which can have a bunch of values. For example - a query such as,</p><pre>SELECT<br>    name,<br>    context<br>FROM<br>    pg_settings<br>WHERE<br>    name IN (&#39;min_wal_size&#39;, &#39;max_wal_size&#39;, &#39;wal_level&#39;);</pre><p>would return the result,</p><pre>     name     |  context<br>--------------+------------<br> max_wal_size | sighup<br> min_wal_size | sighup<br> wal_level    | postmaster<br>(3 rows)</pre><p>In the above output we can see 2 different values for context:</p><ol><li>sighup: This means changes to these settings can be made in postgresql.conf without restarting the server. We can simply send a SIGHUP signal to the postmaster process and it will re-read postgresql.conf and apply the changes.</li><li>postmaster: These settings can only be applied when the server starts, so any change requires restarting the server.</li></ol><p>Besides the above two, there are other types of contexts too. See docs — <a href="https://www.postgresql.org/docs/current/view-pg-settings.html">https://www.postgresql.org/docs/current/view-pg-settings.html</a>.</p><p>In the above case, max_wal_size and min_wal_size can be modified by reloading the config, whereas to modify wal_level we will need to restart the server.</p><h4>Sending SIGHUP using ‘pg_reload_conf’</h4><p>One easy way to send SIGHUP to the postmaster from within a running psql session is by calling the admin function pg_reload_conf</p><pre>postgres=# select pg_reload_conf();<br> pg_reload_conf<br>----------------<br> t<br>(1 row)</pre><p>Note that the use of this function is restricted to superusers only, for obvious reasons.</p><h4>Verifying that the new config is in effect</h4><p>After reloading, you might want to confirm that the updated config has taken effect. To do that, you may either run the SHOWcommand as follows,</p><pre>postgres=# show max_wal_size;<br> max_wal_size<br>--------------<br> 1536MB<br>(1 row)</pre><p>or query the same pg_settings view, which is more convenient for multiple config params.</p><pre>SELECT<br>    name,<br>    setting,<br>    unit<br>FROM<br>    pg_settings<br>WHERE<br>    name IN (&#39;min_wal_size&#39;, &#39;max_wal_size&#39;);</pre><h4>Making temporary config changes using ‘alter system’</h4><p>It’s even possible to update a “reloadable” config parameter by setting it directly from the psql session (again, restricted to superuser).</p><pre>postgres=# alter system set max_wal_size = 144;<br>ALTER SYSTEM<br>postgres=# select pg_reload_conf();<br> pg_reload_conf<br>----------------<br> t<br>(1 row)<br>postgres=# SELECT name, setting, unit from pg_settings where name = &#39;max_wal_size&#39;;<br>     name     | setting | unit<br>--------------+---------+------<br> max_wal_size | 144     | 16MB<br>(1 row)</pre><p>This way, there’s no need to edit the config file thereby making it extremely useful for,</p><ol><li>changing the config as quickly as possible during an ongoing incident or,</li><li>trying out various config values while experimenting on a local/staging server.</li></ol><p>But in most other cases, it’s recommended to update the config file in order to avoid any confusion. A config change done using alter system instead of updating the config file is ephemeral, i.e. if the server restarts for whatever reason, the change would get unknowingly reverted.</p><p>Having a provision to update the config without changing the config file also means that the config file cannot be treated as the source of truth. So if you want to check the current value of a config parameter, the best way to do so is to just query the pg_settings view.</p><h4>Config parameters with implicit units</h4><p>In the previous example, notice that the max_wal_size value was set to 144. However, the entry in pg_settings view for this parameter shows 16MB in the “unit” column.</p><p>Config parameters that store memory or time values have implicit units. In such cases, the actual value is then obtained by multiplying the explicitly set value (144) with the unit (16MB). This can be confirmed using the SHOW command which implicitly does the calculation.</p><pre>postgres=# SELECT name, setting, unit from pg_settings where name = &#39;max_wal_size&#39;;<br>     name     | setting | unit<br>--------------+---------+------<br> max_wal_size | 144     | 16MB<br>(1 row)<br>postgres=# show max_wal_size;<br> max_wal_size<br>--------------<br> 2304MB<br>(1 row)</pre><p>The SHOW command correctly shows the value of max_wal_size as 144 * 16 = 2304MB .</p><p>So when inspecting any config parameter value from the pg_settings view, make sure to include the unit column as well to get the full picture.</p><h4>In summary</h4><p>If you find yourself in a situation that requires pg config changes, first find out whether any of the params require a restart of the postmaster. If all are “reloadable”, then the config change is fairly trivial. On the other hand, if any of the params have ‘postmaster’ as the context, then a server restart is required. Depending on the above and your setup, you will need to plan it accordingly (planned maintenance window, customer communication etc.)</p><p>alter system is quite handy for experimentation and quickly making changes to recover from production incidents (<em>provided you know what you’re doing</em>).</p><p>The server config file postgresql.conf shouldn’t be treated as a source of truth. Instead check the values by querying the pg_settings view. In any case, it’s always recommended to update the config file for permanent changes.</p><p>When inspecting config values, don’t forget to consider the implicit units.</p><p>These are just a few useful things about postgresql configuration. For more comprehensive info on the subject, the official documentation is your friend — <a href="https://www.postgresql.org/docs/current/runtime-config.html">https://www.postgresql.org/docs/current/runtime-config.html</a>.</p><p><em>Thanks to </em><a href="https://medium.com/u/93c26ced7936"><em>Narendra Pal</em></a><em> and Somya Maithani for reviewing the drafts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78dc43150be9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/updating-postgresql-server-config-78dc43150be9">Updating PostgreSQL server config</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-vacuum tuning in PostgreSQL]]></title>
            <link>https://medium.com/helpshift-engineering/auto-vacuum-tuning-in-postgresql-3408f8b62ad8?source=rss-8245797404f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3408f8b62ad8</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database-tuning]]></category>
            <category><![CDATA[autovacuum]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vineet Naik]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 04:42:07 GMT</pubDate>
            <atom:updated>2023-10-11T07:32:03.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1o0bi-OQQn5Fp8rlVf8QvQ.jpeg" /><figcaption>Pic credit: <a href="https://unsplash.com/photos/cpIgNaazQ6w">https://unsplash.com/photos/cpIgNaazQ6w</a></figcaption></figure><p>In May 2021, we were caught off guard by the infamous XID wraparound problem on one of our important PostgreSQL (pg) clusters. Many others have encountered this problem and have written about their experience dealing with it. After employing some <em>hacky</em> workarounds to restore service as quickly as possible, we knew we had to really understand the root cause if we wanted to continue using pg. So we started with the following questions:</p><ol><li>Why did it happen?</li><li>Can it happen again?</li><li>If yes, how to ensure that it doesn’t happen again.</li></ol><p>TL;DR of #1 was that the vacuum operation hadn’t run for a long time. More on this later.</p><p>The answer to #2 was obviously “yes”, thanks to <a href="https://en.wikipedia.org/wiki/Murphy%27s_law">Murphy’s law</a> —</p><blockquote>Anything that can go wrong will go wrong — Murphy’s law</blockquote><p>Finding the answer to #3 was the key. Something had to be done to prevent it from happening in the future.</p><p>Fast-forward to today, the vacuum operation has consistently run on the server for the past 2 years, and the cluster continues to operate smoothly. More importantly, we now have clear visibility into when the vacuum operation runs, or if it doesn’t run at all.</p><p>Writing about our remediation efforts to address the XID wraparound issue has been long overdue. This post will be long and in-depth. But I strongly believe that diving a bit deeper into the intricacies of vacuum is essential for appreciating the need for it, rather than merely complaining about it.</p><p>Here is a rough outline of what follows:</p><ol><li>Understanding the vacuum operation</li><li>Tuning auto-vacuum config to prevent (a) db bloat and, (b) XID wraparound</li><li>Monitoring and alerting</li><li>Tuning config to ensure vacuum runs effectively</li></ol><p>If you’re someone who’s looking for the answer to question #3 above, I hope this post will be useful. If you’re running a postgresql cluster for any serious use case, I’d highly recommend reading further. It’s better to be prepared, cause you never know when and how badly XID wraparound may hit you!</p><h3>Understanding vacuum</h3><p>In pg, “vacuuming” is a critical maintenance task that needs to be performed periodically. If databases are not vacuumed for long enough, it may result in table bloat and/or XID wraparound. The latter implies serious downtime (of hours, days or even weeks). In other words, vacuum is not something that we should try to avoid as it’s essential for healthy and smooth functioning of the db.</p><p>To understand vacuum, let’s begin with the very basic “tuple”. In pg, rows are immutable. A tuple is an internal representation of a row. As application developers, what we usually refer to as a “row” is actually a tuple that’s visible at a given time. There could be other tuples associated with the same row which represent older versions of it. These are invisible to new transactions but could still be visible to ongoing ones (<a href="https://www.postgresql.org/docs/current/mvcc.html">See more: MVCC</a>).</p><p>As the name suggests, the primary goal of vacuum is cleanup, but it does much more than that. Mainly, it performs the following four tasks:</p><ol><li><strong>Remove bloat</strong>: Db bloat means additional disk usage than required to store the data. In pg, when a row is deleted or updated, a new tuple is created, and the old one becomes “invisible” to new transactions. It doesn’t stop there though— pg also needs to change all the index entries to point to the new version of the row. This results in accumulation of index entries pointing to dead tuples. If there are many indexes on a table, it can lead to significantly large bloat — something referred to as “write amplification”. Vacuum does the important job of deleting the dead tuples and pruning the index pointers to them, thereby freeing up space which can be reused for storing future data.</li><li><strong>To protect against XID wraparound: </strong>pg operates with limited (32 bit or 4 byte) transaction IDs or XIDs. The XID gets associated with a row at the time of a write operation. If the cluster is running for a long time, there’s a risk of running out of XID values. When the limit is reached, new XID values will “wraparound” i.e. the XID space is circular with no endpoint. So, by the time the XID wraps around, all old XIDs associated with old rows need to be gone. Otherwise, XID of a new transaction can be less than the XID of an old transaction, causing data corruption. The vacuum process prevents this by updating the XID of old transactions (older than a configured threshold age) with a special value FrozenTransactionId that is handled by the XID comparison algorithm. This process is commonly referred to as “freezing” tuples.</li><li><strong>To update visibility map</strong>: Vacuum builds a visibility map for each table which has information about which tuples are visible to transactions and which are not. This speeds up index-scans as well as the vacuum process itself.</li><li><strong>To analyze tables and generate statistics</strong>: pg looks at samples of data and generates statistics that can are used by the query planner to serve queries efficiently. This operation doesn’t take much time and can even be done in stages of incremental sample sizes. Hence, pg also provides a way to run vacuum only to generate statistics, leaving out the other expensive operations.</li></ol><p>Detailed information about vacuum can be obtained here — <a href="https://www.postgresql.org/docs/9.6/routine-vacuuming.html">Routine Vacuuming</a></p><p>One question that arises is, why does vacuum try to do so many things? The answer is — because it involves scanning the heap, it tries to club various unrelated operations and performs them in a single scan.</p><h3>The autovacuum daemon</h3><p>Pg has a daemon process called autovacuum launcher that is in charge of starting worker process to perform the vacuum operation on all dbs.</p><p>While vacuum can be run manually on any db or even specific tables of a db at any given time, it’s best to let the autovacuum daemon do the job as it will ensure that vacuum will be performed on all the dbs that are eligible for vacuuming.</p><p>There are 2 main things that pg considers when deciding whether a db needs vacuuming</p><ol><li>No. of dead tuples increasing beyond a threshold</li><li>Max XID age of tuples in the db exceeding a limit</li></ol><p>However, there could be cases where autovacuum fails to run if it’s not tuned properly. Hence it’s important to tune the autovacuum config.</p><h3>Side effects of vacuum operation</h3><p>Normal vacuum process doesn’t acquire any exclusive locks[1] and can be run along with the cluster serving reads and writes. VACUUM FULL on the other hand is an aggressive version that acquires exclusive locks and is a blocking operation. It blocks any reads and writes until completion in order to return the freed up space back to the OS.</p><p>Having said that, some of the phases[2] of vacuum (both normal and full) result in a lot of disk I/O. Thus ongoing vacuum operation can interfere with the other active processes on the cluster.</p><p>In short, vacuuming isn’t free of costs and may lead to temporary performance degradation for the applications. Hence it needs to be run only when justified. Something to keep in mind when tuning the autovacuum config parameters:</p><ul><li>If it’s triggered too frequently, there will be unnecessary I/O</li><li>If it’s triggered very rarely, there’s a chance of db bloat and XID wraparound</li></ul><p>Another question is, how big is the table. For a large table (more no. of rows), vacuum will take more time which translates to poor application performance for a longer duration.</p><h3>Tuning vacuum to prevent DB bloat</h3><p>There are 2 config parameters which decide when autovacuum is triggered as a reaction to db bloat. One of them is a static component and the other is the dynamic component. The formula is,</p><pre>actual threshold =  autovacuum_vacuum_threshold <br>                  + autovacuum_vacuum_scale_factor * no. of rows</pre><p><strong>autovacuum_vacuum_threshold</strong> is the minimum number of updated or deleted tuples needed to trigger a VACUUM in any table. The default is 50 tuples.</p><p><strong>autovacuum_vacuum_scale_factor</strong> is a fraction of the table size (in terms of no. of rows) to decide whether vacuum should be triggered. Default is 0.2</p><p>Which means that,</p><ul><li>For a smaller table (less rows) the static threshold component is what will contribute more towards triggering vacuum</li><li>For larger tables (more rows) the dynamic component scale_factor is what will contribute more towards triggering vacuum</li></ul><p>Now let’s talk about our specific incident. As it turned out, one large table in our db was the reason why vacuum hadn’t run on for a long time. This particular table is like an append only log with a lot of insertions and no updates. Deletions happen at the time of archival (at a later date) or when the customer leaves us. The default scale factor of 0.2 was too large for us which caused the autovacuum trigger point to be pushed farther and farther with increase in no. of rows.</p><p>To arrive at the suitable value for the scale factor, we considered the following:</p><ol><li>Rate of dead tuples created per day</li><li>No. of rows in the large table of interest</li><li>Rate at which news rows are inserted in the table</li></ol><p>The rate of dead tuples (1) can be calculated using the n_dead_tup value from the pg_stat_user_tables view. Eg.</p><pre>-- For a specific table<br>select n_dead_tup from pg_stat_user_tables where relname = &#39;&lt;tablename&gt;&#39;;<br><br>-- Or for all tables <br>select sum(n_dead_tup) from pg_stat_user_tables;</pre><p>It’d be expensive to get the exact count of rows (2) for a large table, but we can get an estimate as follows,</p><pre>SELECT<br>    c.relname,<br>    c.reltuples::bigint AS estimate<br>FROM<br>    pg_class c<br>    JOIN pg_namespace n ON n.oid = c.relnamespace<br>WHERE<br>    c.relname = &#39;&lt;tablename&gt;&#39;<br>    AND n.nspname = &#39;public&#39;;</pre><p>Finally, to find out the rate of insertions (3), you can use application side metrics if any. In our case, the insertions were done by a kafka consumer and we already had charts for throughput of the consumer. So we just used those numbers.</p><p>The values in our case were as follows:</p><ol><li>Rate of creation of dead tuples ≈ 20m per day</li><li>No. of rows in the table ≈ 4.3b</li><li>Rate of insertions ≈ 10m on avg per day</li></ol><p>Now with the default scale factor of 0.2 and static threshold of 50, autovacuum will be triggered when (4.3b * 0.2) + 50 = 910mdead tuples are created. That’s a huge number. With this config, autovaccum would trigger after 45 days. But at a rate of 10m insertions per day, the no. of rows in the table will have increased by almost half a billion in those 45 days. You see the problem, right?</p><p>If we wanted to have autovacuum triggered daily, we’d need to reduce the scale factor to 0.005 (4.3b * 0.005 = 21m). But we decided to start with a conservative frequency of once a week and reduced it to 0.035 as per the following calculation:</p><pre>4.3b * 0.035 = 150.5m</pre><p>This is roughly equal to the no. of dead tuples accumulated in 7.5 days. Note that during these 7.5 days, there would be around 75m insertions but this number is not too large.</p><p>This worked quite well for us.</p><h3>Tuning autovacuum to avoid XID wraparound</h3><p>Db bloat is one thing but the real reason why you’d want prioritize tuning autovacuum is to avoid XID wraparound. You may be able to work your way around db bloat by adding more and more disk (throwing money at the problem). But if the age of the oldest XID (max age) exceeds 2 billion, then the db will go into read-only mode i.e. it will stop accepting writes. At this point the only way to recover from it is by running a standalone VACUUM FREEZE operation in single user mode i.e. with the database process shutdown. This can result in a downtime of hours, days or even weeks[3].</p><p>As a guard against reaching this point, pg will react with some warning signs.</p><p>A bit before XID wraparound, it will start writing warnings to the log file. But in absence of regular monitoring of logs, they will most certainly be missed. So this is not very useful.</p><p>A more effective warning, or rather a measure is the forced vacuum operation[4] that pg will trigger at a much earlier threshold of 200m (10% of 2b). It is special in the sense that,</p><ol><li>It gets run even if the autovacuum daemon is disabled and,</li><li>It cannot be cancelled permanently — If a vacuum of this kind is in progress, some statements such as alter table or index creation will get blocked because of shared locking. In that case, it’s perfectly ok to cancel the vacuum process and allow the other transaction to proceed. But as soon as that transaction is complete, a new vacuum process will start. While such vacuum is running, the cluster can continue to serve reads and writes.</li></ol><p>There’s nothing to worry about forced vacuum operation as long as it completes in reasonable time and doesn’t cause performance degradation. For smaller dbs this is not a problem at all. For larger dbs, it’s a rather important consideration.</p><p>For tuning the config to prevent XID wraparound, there are 3 params of interest:</p><p><strong>autovacuum_freeze_max_age:</strong></p><p>This is the max age (in no. of transactions) a table’s pg_class.relfrozenxid can attain before vacuum is forced in order to prevent XID wraparound.</p><p>Default is 200m which is ~10% of the possible 2³¹ values (wraparound). Now 10% may seem too less and one might be tempted to increase it. But that would just delay the inevitable forced vacuum process further (thereby also increasing the time it’d take to complete).</p><p>The right value can be found out based on your transaction burn rate i.e. how fast the XIDs will be used up. But we might just be able to get away with the default value itself if other things are configured correctly (as explained a bit later).</p><p><strong>vacuum_freeze_min_age</strong>:</p><p>The cutoff age (in transactions) that vacuum should use to decide whether to freeze row versions while scanning a table.</p><p>Default is 50m which means all XIDs that are older than 50m will be frozen and the youngest XID in the table will have an age of 50m. This is very very conservative number. Consider transaction advancement rate of 50m in 24 hours. Unless we have transactions or queries that run for 24 hours, do we really need that old XIDs to be present? Another way to think about it is — even after vacuum is run, we are only 50m transactions away from the next forced vacuum. From a practical standpoint, this value can be reduced by a lot (considering the default 200m autovacuum_max_freeze_age).</p><p>The right value can be decided based on two things — the rate of transactions and the duration of longest running query/transaction served by the cluster.</p><p>A vacuum freeze instead of plain vaccumimplicitly sets this value to 0 i.e. XID on all rows will be frozen.</p><p><strong>vacuum_freeze_table_age:</strong></p><p>If the table’s pg_class.relfrozenxid value reaches this threshold, then vacuum will aggressively scan the tuples i.e. it will visit every page that may contain unfrozen tuples, not just the ones that contain dead tuples. This is provided because normally, vacuum uses an optimization to avoid scanning all pages. The visibility_map tells which pages may contain dead tuples and vacuum can only scan those.</p><p>Default value is 150m. Recommended is 80% of autovacuum_freeze_max_age</p><p>Again, a vacuum freeze instead of plain vaccumimplicitly sets this value to 0 ie. XID on all rows will be frozen.</p><p>To calculate the suitable values for the above config params, we’d need to consider:</p><ol><li>Current max XID age, at least for the databases having large tables. It’d also be good to know this value as a percentage of autovacuum_freeze_max_age as well as as percentage of 2b (when XID wraparound would happen)</li><li>Transactions burn rate i.e. rate at which XIDs are getting “exhausted”</li></ol><p>For current max XID age (1), we can run a query as follows,</p><pre>WITH max_age AS ( <br>    SELECT 2000000000 as max_old_xid<br>        , setting AS autovacuum_freeze_max_age <br>        FROM pg_catalog.pg_settings <br>        WHERE name = &#39;autovacuum_freeze_max_age&#39; )<br>, per_database_stats AS ( <br>    SELECT datname<br>        , m.max_old_xid::int<br>        , m.autovacuum_freeze_max_age::int<br>        , age(d.datfrozenxid) AS oldest_current_xid <br>    FROM pg_catalog.pg_database d <br>    JOIN max_age m ON (true) <br>    WHERE d.datallowconn ) <br>SELECT max(oldest_current_xid) AS oldest_current_xid<br>    , max(ROUND(100*(oldest_current_xid/max_old_xid::float))) AS percent_towards_wraparound<br>    , max(ROUND(100*(oldest_current_xid/autovacuum_freeze_max_age::float))) AS percent_towards_emergency_autovac <br>FROM per_database_stats</pre><p>The above query will return 2 important values:</p><ol><li><strong>percent_towards_wraparound</strong>: If this is close to 100%, it means XID exhaustion will happen soon and if older XIDs are not frozen, the database would shutdown to prevent data corruption. We want to avoid this at all costs because then there would be no time to react.</li><li><strong>percent_towards_emergency_autovac</strong>: If this is close to 100% it means forced vacuum is around the corner. Ideally we’d want to avoid getting to this point, but things would still be in much better control than the first case.</li></ol><p>It also helps to find XID max age per database using the following query</p><pre>SELECT datname, age(datfrozenxid) FROM pg_database;</pre><p>For transaction burn rate (2), we can use the xact_commit and xact_rollback stats from pg_stat_database view.</p><pre>SELECT<br>    xact_commit,<br>    xact_rollback<br>FROM<br>    pg_stat_database<br>WHERE<br>    datname = &#39;&lt;tablename&gt;&#39;;</pre><p>We send these metrics to statsite and plot the nonNegativeDerivative over time windows of 1 hour (green bars) and 1 day (blue bars).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pitWVpuoF9pXR8-rrlq9tw.png" /></figure><p>Now let’s look at how we can tune the above 3 params based on the these metrics.</p><p><strong>autovacuum_freeze_max_age:</strong></p><p>Interestingly, if other values are tuned correctly then there’s no need to change this setting and we can let it be the default. That’s because if other params are tuned properly, then this limit will never be reached. And even if it’s reached, autovacuum will run without any performance degradation. So let’s assume this setting will be the default of 200m.</p><p><strong>vacuum_freeze_min_age:</strong></p><p>To tune this, we also need to consider the duration of longest running query (that we expect based on our specific use case), besides the transaction burn rate e.g. if it is 4 hours, then it’s ok to freeze tuples for transactions older than 4 hours. For a typical OLTP workload, 4 hours is more than sufficient. But let’s use this as a conservative estimate.</p><p>In our case, at the time of tuning the config params, the avg. daily transactions were around 11m which amounts to an hourly rate of 460k.</p><p>Let’s say we decide that 4 hour old transactions can be frozen, then vacuum_freeze_min_age can be set to, 4 * 460k = 1.84m</p><p>As you can see, it’s significantly lesser than the default which is 50m. This will have a major impact on how aggressively the tuples will get frozen.</p><p>Aside: The hourly rate calculated above also gives us an estimate of time between XID wraparounds (in the absence of vacuum), <br>2000000000 / 460000 hours = 181 days ≈ 6 months</p><p><strong>vacuum_freeze_table_age:</strong></p><p>We can set it to 80% of auto_vacuum_max_freeze_age i.e. 0.8 * 200m = 160m</p><h3>Monitoring and alerting</h3><p>Tuning database config is not a one time activity. You may need to regularly re-tune the config based on the changes in the use cases, traffic patterns etc. But how do we know when re-tuning is in order?</p><p>Having monitoring and alerting helps in this case. All of the metrics that we considered above can be plotted on the monitoring platform of your choice. Moreover, you can set threshold based alerts on some metrics e.g. we have alerts when percent_towards_wraparound exceeds 10% and percent_towards_emergency_autovac exceeds 120%. This will give us sufficient time to investigate any issues and take corrective actions.</p><p>We also plotted the various phases of vacuum operation by querying the pg_stat_progress_vacuum view and it has turned out to be tremendously helpful in understanding what the vacuum operation is currently doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiKI1KOxKlTZbiacwq64Ew.png" /></figure><h3>Making sure vacuum runs effectively</h3><p>There’s nothing to worry about vacuum operation as long as, it completes in reasonable time and doesn’t cause performance degradation while it’s in progress. Both these can be easily achieved if the database is small but for large databases we need to strike a balance between time taken v/s performance impact. This can be done by tuning the config params that control the resources available to the vacuum process.</p><p>More the resources, there will be increased I/O (more impact) but vacuum will take less time (shorter impact duration)</p><p>Lesser the resources, there will be less I/O (less impact) but vacuum will run for longer duration and in the worst case, it may not catch up with transaction burn rate or dead tuple creation rate. Then we have a problem.</p><p>The relevant config parameters that we can tune here,</p><p><strong>maintenance_work_mem</strong>: The default value of 64MB is too less. On typical production environments, we can easily increase it to at least 1GB. This will allocate more memory to vacuum process so that it completes faster.</p><p><strong>autovacuum_max_workers: </strong>maximum number of autovacuum processes (other than the autovacuum launcher) that may be running at any one time. The default value is 3. We can keep it the default or equal to the no. of large databases, whichever is smaller.</p><p><strong>autovacuum_vacuum_cost_delay: </strong>Specifies the cost delay value that will be used in automatic VACUUM operations. We can keep it unchanged.</p><p><strong>autovacuum_vacuum_cost_limit</strong>: Specifies the cost limit value that will be used in automatic VACUUM operations. We can keep it unchanged.</p><p>In conclusion,</p><ul><li>vacuum is an important operation for proper functioning of a postgres server. It’s not something to be avoided or delayed, rather it needs to be tuned as per the specific traffic pattern and workload to ensure effective vacuuming at regular intervals.</li><li>Further, tuning the (auto) vacuum config is not a one time exercise as it needs to be revisited as and when the nature of traffic and workload changes.</li><li>It’s worth investing in good monitoring and alerting sooner than later, as it greatly helps in tuning the config. If there’s one takeaway from this article, it should be this.</li></ul><p>If you made this far, thanks for reading and hope this post is useful to you (hopefully proactively rather than reactively :-))</p><p><em>Thanks to </em><a href="https://medium.com/u/93c26ced7936"><em>Narendra Pal</em></a><em> for reviewing the drafts.</em></p><h3>Footnotes</h3><p>[1]: This is true even for the forceful vacuum started to avoid XID wraparound at XID max age of 200m.</p><p>[2]: The vacuum process happens in multiple phases which are described in detail <a href="https://www.postgresql.org/docs/9.6/progress-reporting.html">here</a>.</p><p>[3]: During the aforementioned incident, the vacuum full operation in single user mode ran for ~2 weeks. As we didn’t have any monitoring in place yet, we were starting to lose hope. That it eventually did complete felt like a miracle!</p><p>[4]: One valid question is why the forced vacuum operation was not able to avoid XID wraparound in our case. Our guess is that forced vacuum did run but it was not able to catch up due to insufficient resources (due to poor configuration, we didn’t know any better at that time!)</p><h3>References</h3><ul><li><a href="https://blog.crunchydata.com/blog/managing-transaction-id-wraparound-in-postgresql">https://blog.crunchydata.com/blog/managing-transaction-id-wraparound-in-postgresql</a></li><li>Freezing your tuples off <a href="http://www.databasesoup.com/2012/09/freezing-your-tuples-off-part-1.html">Part 1</a> | <a href="http://www.databasesoup.com/2012/10/freezing-your-tuples-off-part-2.html">Part 2</a> | <a href="http://www.databasesoup.com/2012/12/freezing-your-tuples-off-part-3.html">Part 3</a></li><li><a href="https://onesignal.com/blog/lessons-learned-from-5-years-of-scaling-postgresql/">Lessons Learnt From 5 Years of Scaling PostgreSQL</a></li><li><a href="https://cloud.google.com/solutions/optimizing-monitoring-troubleshooting-vacuum-operations-postgresql.pdf">https://cloud.google.com/solutions/optimizing-monitoring-troubleshooting-vacuum-operations-postgresql.pdf</a></li><li><a href="https://www.davepacheco.net/blog/2019/visualizing-postgresql-vacuum-progress/">https://www.davepacheco.net/blog/2019/visualizing-postgresql-vacuum-progress/</a></li><li><a href="https://www.2ndquadrant.com/en/blog/its-the-end-of-the-world-as-we-know-it-and-postgres-is-fine/">https://www.2ndquadrant.com/en/blog/its-the-end-of-the-world-as-we-know-it-and-postgres-is-fine/</a></li><li><a href="https://blog.sentry.io/2015/07/23/transaction-id-wraparound-in-postgres">https://blog.sentry.io/2015/07/23/transaction-id-wraparound-in-postgres</a></li><li><a href="https://devcenter.heroku.com/articles/postgresql-concurrency">https://devcenter.heroku.com/articles/postgresql-concurrency</a></li><li><a href="https://www.postgresql.eu/events/pgconfeu2019/sessions/session/2748/slides/242/vacuum_future_pgconf_eu_2019.pdf">https://www.postgresql.eu/events/pgconfeu2019/sessions/session/2748/slides/242/vacuum_future_pgconf_eu_2019.pdf</a></li><li><a href="https://aws.amazon.com/blogs/database/implement-an-early-warning-system-for-transaction-id-wraparound-in-amazon-rds-for-postgresql/">https://aws.amazon.com/blogs/database/implement-an-early-warning-system-for-transaction-id-wraparound-in-amazon-rds-for-postgresql/</a></li><li><a href="https://www.keithf4.com/per-table-autovacuum-tuning/">https://www.keithf4.com/per-table-autovacuum-tuning/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3408f8b62ad8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/auto-vacuum-tuning-in-postgresql-3408f8b62ad8">Auto-vacuum tuning in PostgreSQL</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating PostgreSQL databases using AWS DMS]]></title>
            <link>https://medium.com/helpshift-engineering/migrating-postgresql-databases-using-aws-dms-e91cf26fa6e?source=rss-8245797404f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91cf26fa6e</guid>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-migration-service]]></category>
            <dc:creator><![CDATA[Vineet Naik]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 04:50:41 GMT</pubDate>
            <atom:updated>2021-11-20T04:50:41.993Z</atom:updated>
            <content:encoded><![CDATA[<p>by <a href="https://medium.com/@naikvin_34014">Vineet Naik</a> and <a href="https://medium.com/@shubham05.setia">Shubham Setia</a></p><h3>Overview</h3><p>As part of the data center migration project, we had a challenging task of migrating our existing PostgreSQL clusters from one AWS region to another. If we calculate the total amount of data we had to migrate it adds up to around 6TB.</p><p>In this blog post we’d like to share how we used AWS DMS for this task and the things we learnt along the way.</p><h3>Our setup</h3><p>Before getting into what is AWS DMS, let’s understand our PostgreSQL setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dr_ZsNY5hx2oBG_R" /></figure><p>This diagram shows our setup where the applications connect to pgpool nodes via HAProxy. We have added PG master and one standby as PGPool backends, where read-write requests are served by the master node and read-only requests are served by the standby node.</p><h3>Options for PG migration</h3><h4>pg_dump/pg_restore</h4><p>PostgreSQL comes with the pg_dump and pg_restore scripts which can be used to copy data between clusters in a clean way but it may involve significant downtime for large databases. Also, there are some restrictions if there are large objects in the db.</p><p>As we had a couple of very large databases which couldn’t afford a long write downtime, this approach was out of question for us.</p><h4>Bucardo</h4><p>It’s an asynchronous PostgreSQL replication system which allows multi-source and multi-target operations. But it has some limitations:</p><ul><li>Performance and maintenance overhead on source db.</li><li>No support for replicating schema changes (DDLs).</li><li>Consistency can be impacted if infra is not optimized correctly.</li></ul><h4>AWS Data Migration Service (DMS)</h4><p>Data migration service (DMS) is an AWS cloud service that makes it easy to migrate relational databases, data warehouses, NoSQL databases, and other types of data stores. It can be used to migrate data into the AWS Cloud or between combinations of cloud and on-premises setups.</p><p>After evaluating all the options we ended up choosing DMS.</p><h3>Using DMS</h3><p>At a basic level, DMS provides a server in the AWS cloud that runs replication software. You create source and target connections to tell where to extract data from and load to. Then you schedule a task that runs on this server to move your data. DMS creates the tables and associated primary keys if they don’t exist on the target. You may also create the target tables beforehand yourself, if you prefer. You can perform one-time migrations (full load), and/or replicate ongoing changes (CDC) to keep sources and targets in sync. It also provides HA/Resiliency with Multi-AZ replication instances.</p><p>The following diagram illustrates the replication process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*suPvVB-F63geewdz" /></figure><h4>Prerequisites for DMS</h4><p>There are a few prerequisites for using DMS, mainly:</p><ul><li>Either one of the source or target endpoints should be on AWS i.e. you can’t have source and target both outside AWS.</li><li>For PostgreSQL, the server version needs to be 9.4+ and pglogical extension needs to be installed on both source and target clusters.</li></ul><p>Refer <a href="https://docs.aws.amazon.com/dms/latest/sbs/chap-sqlserver2aurora.prerequisites.html">AWS documentation</a> for complete list of prerequisites.</p><h4>Checking for datatype compatibility</h4><p>There are certain limitations about which data/column types are supported. There are some pg data types which are not supported at all eg. tsvector whereas others that are supported partially eg. json . One good thing is that databases can be checked beforehand for compatibility so that there are no surprises during migration. For that, make sure you check the “Pre-migration assessment” option when starting the task. You can even create dummy endpoints and tasks just for this purpose — even a source db with just the schema loaded should be sufficient.</p><p>If you are using data types which are not supported, then those columns won’t get migrated. If that’s a deal breaker then you may need to evaluate other options for migration.</p><p>Partial support on the other hand means DMS can migrate these data types but only under certain conditions. If you use json data type in your db, you may come across this case when migrating from PG to PG. For homogeneous migration (i.e both source and target dbs are same), partially supported data types are mostly what DMS calls “Large Objects” (LOBs). The problem with such columns is that they can potentially contain unbounded data and hence DMS has no clue about how much memory to pre-allocate for them during migration.</p><p>This can be worked around by choosing “Limited LOB mode” when creating the task, which allows you to set a known limit which is applicable to all the LOBs in the db. If the data exceeds the specified size limit, then it gets truncated, so beware of using it with json types. We based this limit on the max size of the json columns that existed in our db using the following query:</p><p><strong>Warning</strong>! This query can be very expensive on a large db. To ensure it doesn’t impact normal db operations, we temporarily provisioned a hidden replica just for running it. It took ~27 hours!</p><pre>SELECT<br>    coalesce((octet_length(c1::text)) / (1024.0), 0) AS size<br>FROM<br>    t1<br>ORDER BY<br>    size DESC<br>LIMIT 1;</pre><h3>Logical replication plugin</h3><p>Before getting into which logical replication plugin to use, let’s look under the hood and understand logical decoding.</p><h4>Logical decoding</h4><p>The traditional mechanism in PostgreSQL for keeping standby/replica nodes in-sync with the primary is physical replication. It is implemented by streaming the write-ahead-log (WAL) records in binary format to the replica, which then get applied byte-by-byte i.e. in its entirety. This ensures that the replica has all the required changes for it to be promoted as the new primary in case the original one fails. This works great for synchronization and failover but it’s not so suitable for data migration. For one, selective replication is not possible i.e. there’s no way to replicate only a certain db on the cluster or a subset of tables in a db. Secondly, the PG installation on both the primary and standby nodes need to be exactly the same — same version, dbs, schemas etc.</p><p>These limitations have been worked around to an extent using various trigger based approaches such as Slony, Londiste, Bucardo.</p><p>In version 9.4, PostgreSQL introduced logical decoding which paved the way for logical replication. It is implemented by decoding the contents of the WAL into an application-specific format. Moreover, it supports selective replication. Logical replication is built on top of the same streaming architecture that physical replication uses and “output plugins” can be implemented to transform the WAL’s internal representation into the desired application-specific format.</p><p><a href="https://www.postgresql.org/docs/9.6/test-decoding.html">test_decoding</a> is a basic output plugin included in the postgresql-contrib package. Directly quoting from the docs — “It doesn’t do anything especially useful, but can serve as a starting point for developing your own output plugin”.</p><p><a href="https://github.com/2ndQuadrant/pglogical">pglogical</a> is an advanced output plugin implemented by 2ndquadrant as a postgresql extension following the publish/subscribe model.</p><p>DMS uses either test_decoding or pglogical depending on whether the pglogical plugin is available on the source. However it can also be explicitly specified by setting the extra connection attribute PluginName .</p><p>Aside: PostgreSQL 10+ comes with a builtin implementation of logical replication, but doesn’t look like AWS DMS uses it even for those versions of pg. All our pg instances were on version 9.6 so we didn’t need to go deeper into this.</p><h4>Which plugin to use?</h4><p>We started with pglogical as we had installed it on our source clusters. But one of our tasks failed in the CDC stage after running for a few days. As per AWS support, there’s a known issue with DMS and pglogical and we were advised to use test_decoding for the failed task.</p><p>Following that we chose test_decoding for rest of the dbs. Thus we ended up using pglogical for some tasks and test_decoding for others. Due to time constraints, we didn’t really go into depth of what exactly the known issue is.</p><p>Outside the context of DMS, pglogical is more feature rich than both test_decoding as well as the <a href="https://www.2ndquadrant.com/en/blog/pglogical-logical-replication-postgresql-10/">builtin logical decoding implementation in pg 10</a>. So it can be a good first choice.</p><h3>PG config changes for DMS</h3><p>If you don’t have pglogical installed already, you will need to install the extension on the source as well as target. This can be done using the OS’s package manager.</p><p>Once that is done, modify the postgresql.confparameters as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24632a71d0b5b01fdec94007d952e9b1/href">https://medium.com/media/24632a71d0b5b01fdec94007d952e9b1/href</a></iframe><p>Some of the config parameters above require a server restart, so you may need to schedule a planned maintenance / downtime.</p><p>Additionally, there are a few more points to note:</p><ol><li>If you are on Ubuntu and behind the latest minor version of postgresql then installing the latest version of pglogical may cause postgresql to be upgraded as well. Being a minor version upgrade, it’s not a problem from compatibility standpoint but it will cause the postgresql process to restart, which may be undesirable. apt-get will prompt you for confirmation about this, so make sure you say “no” to it. In that case you may want to perform this step during a planned maintenance window.</li><li>If you are running a highly available setup with one or more standby nodes then shared_preload_librarieswill have to be modified on the standby nodes as well. Also max_worker_processeshas a default value of 8. In case it’s being set to a higher value, then the value on standby nodes must be at least equal to the one on primary. So you will need to configure and restart the standby nodes first otherwise the standby will fail to join the primary node when it’s restarted.</li><li>AWS documentation recommends setting wal_sender_timeout to 0 on the source db to prevent the sending server from ending the replication connections that are inactive for longer than 60 seconds (default). This config change doesn’t require postmaster restart to take effect so you can do it just before starting the first DMS task on this source db. In case your pg instance is configured with a different value than default, take note of that value so that it can be reset after the DMS tasks using this source endpoint are completed.</li></ol><h3>Choosing the replication instance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*GgEpnjY-VySjSezd" /></figure><p>AWS DMS uses a replication instance to connect to your source data store, read the source data, and format the data for consumption by the target data store. It also loads the data into the target data store. Most of this processing happens in memory. However, large transactions might require some buffering on disk. Cached transactions and log files are also written to disk.</p><p>AWS DMS currently supports the T2/T3 (burstable performance instances), C4/C5 (CPU optimized), R4/R5 (Memory optimized) Amazon EC2 instance classes for replication instances.</p><p>As discussed earlier, DMS has 2 stages — (1) Full load and (2) CDC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*UsIQ1d6DJxvrsc8Q" /></figure><p>In the full load stage, DMS starts capturing changes for the tables it’s migrating from the source engine’s transaction log (cached changes). After full load is done, these cached changes are collected and applied on the target. Depending on the volume of cached changes, these changes can directly be applied from memory, where they are collected first, up to a set threshold. Or they can be applied from disk, where changes are written when they can’t be held in memory.</p><p>After cached changes are applied, by default AWS DMS starts a transactional apply process on the target instance (CDC).</p><p>In the entire process, DMS uses memory buffers in various places e.g. two stream buffers, one each for incoming and outgoing data as well as a memory buffer for a component named sorter which is responsible for maintaining the commit order. If any of these buffers experience memory pressure, the migration can have performance issues and potential failures.</p><p>So for heavy workloads, the extra memory provided by R5 instances is useful. R5 instances can also help with holding a large number of transactions in memory, thereby preventing memory-pressure issues during ongoing replications.</p><p>For more details about this, please refer to <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.Types.html">the AWS documentation</a>.</p><h3>Dropping/restoring indexes and constraints</h3><p>The full load stage of DMS is essentially a COPYoperation. During this stage, presence of indexes and constraints can affect the task performance negatively. When data is copied, additional cost is incurred in updating the indexes. Also, the full load task loads groups of tables at a time, so referential integrity constraints may get violated causing failures.</p><p>It’s far more efficient to create the indexes and constraints later on i.e. after full load completes and before CDC begins. Thanks to pg_restore’s —-sectionoption, this can be achieved rather easily.</p><ol><li>Before starting the DMS task, create the database on target and restore the schema using pg_restore with the flags --schema-onlyand--section=pre-data . This will import all table definitions but leave out the indexes and constraints.</li><li>When creating the DMS task make sure to select the DMS config as follows: (a) “Do nothing” option in the table preparation mode and (b) “Stop task after full load completes” option. This will give us time to restore the indexes and constraints before the CDC stage.</li><li>Run the task.</li><li>When the full load stage completes, the task will stop. At this point run the same pg_restore command again but this time with the flag. --section=post-data.It will now create the indexes and constraints.</li><li>Once the above command finishes, “resume” the DMS task.</li></ol><p>If you take this approach, don’t forget to account for the time required to restore the indexes and constraints while estimating the total migration time.</p><h3>Sequences need to be synced manually</h3><p>If your tables use auto-incremented primary keys implemented as sequences, then the sequences will not be advanced on target even though data is being copied from source. This is something DMS doesn’t support with any of the logical replication plugins.</p><p>This means once you cut over the writes to the target db, the first insert in such a table will result in a conflict for the primary key.</p><p>To work around this, add a step in your checklist just after stopping the DMS task to reset the sequence to the next value.</p><p>For eg. Let’s say there is a table t1 with column c1 that is auto-incremented using a sequence s1 , do the following just after stopping the DMS task:</p><ol><li>Find the max value of the column in target db and add 1 to it</li></ol><pre>select coalesce(max(c1), 0) + 1 from t1;</pre><p>2. Let’s say the above query returned 451 as the result. Reset the sequence on target db to that value</p><pre>alter sequence s1 restart with 451;</pre><h3>Monitoring the DMS tasks</h3><p>Monitoring of DMS tasks is very crucial in production, particularly for tasks that may run for a long period of time.</p><p>When a DMS task fails, the replication_slot created on the source db is not dropped (it just becomes “inactive”). This causes WAL logs to be retained on the source db, thereby increasing the disk usage. If the slot is not dropped within a reasonable time frame, there’s a risk of the source db running out of disk space. So make sure this is not missed. (More on how to drop slot later in the “Stopping the DMS task” section).</p><p>One way to monitor DMS tasks is by using <a href="https://aws.amazon.com/blogs/database/automating-database-migration-monitoring-with-aws-dms/">cloudwatch alarms</a>. But we felt it was an overkill. Instead, we implemented a python script that runs as a cron job. It reads a list of task ids from a file and checks the status of each task using the AWS APIs. If any of the tasks in the list is found to be in stopped or failed state, the on-call person gets paged.</p><h3>Stopping the DMS tasks</h3><p>If you stop the DMS task in the CDC stage, you still have an option to resume it as long as the replication_slot is present on the source. This means, for the time duration when the job is stopped, WALs will be retained on source and it’s disk usage will keep increasing rapidly. At this point, you need to take a decision whether to drop the slot or add more disk space.</p><p>To drop a slot, first find out the one which has been created for the particular task.</p><pre>SELECT<br>    *<br>FROM<br>    pg_replication_slots<br>WHERE<br>    slot_type = &#39;logical&#39;<br>    AND DATABASE = &#39;&lt;your-dbname&gt;&#39;<br>    AND active IS FALSE;</pre><p>This query should mostly return a single row but if that’s not the case, you can compare the restart_lsn column with the value displayed as part of the “CDC recovery checkpoint” on the DMS task page in AWS console.</p><p>Once you figure out the slot corresponding to the task, drop it as follows:</p><pre>SELECT pg_drop_replication_slot(&#39;&lt;&lt;slotname&gt;&gt;&#39;);</pre><h3>Final thoughts</h3><p>So these were some of the things we learnt from migrating large PostgreSQL databases using AWS DMS. We hope these points are useful to someone who plans to use DMS for migrating PostgreSQL databases.</p><p>After using DMS extensively, we are pretty impressed by it. While a lot of heavy lifting is done by the underlying logical decoding framework and plugins, DMS does provide a good hosted solution by managing the complexity. Other than moving large amounts of data between regions, we can definitely see ourselves using it in future, particularly for database upgrades.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91cf26fa6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/migrating-postgresql-databases-using-aws-dms-e91cf26fa6e">Migrating PostgreSQL databases using AWS DMS</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Private Python Package Index with Zero Hassle]]></title>
            <link>https://medium.com/helpshift-engineering/private-python-package-index-with-zero-hassle-6164e3831208?source=rss-8245797404f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6164e3831208</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vineet Naik]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 12:59:27 GMT</pubDate>
            <atom:updated>2018-10-26T13:18:21.756Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is about how we host our own private python package index with zero hassle, or in other words — in a simple, secure, cost-effective and maintenance-free manner.</p><p>We are also excited to announce that we have open sourced <a href="https://github.com/helpshift/pypiprivate">pypiprivate</a>, which is a utility for privately publishing python packages and an important component of our solution.</p><h3>Background</h3><p>Although Clojure is our primary programming language at Helpshift, Python has always been there in some capacity right from the beginning. We’ve been using Python for all kinds of use cases, from developer tooling to critical production operations such as release automation, monitoring, backups and disaster recovery. It’s also the preferred language of our data scientists and we’ve been using it extensively for building our Machine learning platform since past 2 years.</p><p>With increase in it’s adoption across the organization, we felt a need to enable easy code reuse in Python too, similar to how we have for Clojure. A typical way of reusing code is to group generic abstractions and common utilities into libraries. These libraries can then be included as dependencies in multiple projects. However, not all of our libraries are open source, thus <a href="https://pypi.org/">pypi.org</a> isn’t the right place to publish them. In short, we required a way to distribute private libraries securely, not just with developers but also with our automated build and deployment systems.</p><h3>Existing tools</h3><p>We started by evaluating existing tools that Python ecosystem had to offer, <a href="https://github.com/devpi/devpi">Devpi</a> and <a href="https://pypi.org/project/pypiserver/">pypiserver</a> being the most prominent ones. These tools provide a web application to serve the package index over HTTP and an interface (either web or CLI or both) for publishing packages to the repository, plus additional features such as index search for discoverability, multiple indexes, mirroring etc.</p><p>Sounds pretty straightforward right? Unfortunately, that’s hardly ever the case when it comes to running anything in production. To build a reliable system, it’s important to think about high availability, monitoring &amp; alerts, backups &amp; disaster recovery and so on. As a result, the final solution ends up becoming much more complex than originally intended. Moreover, tools such as devpi come with a lot of features that are rarely useful and mostly unnecessary.</p><p>Hence, setting up a multi-node production-ready system for hosting private packages felt like an overkill to us considering the infrastructure and maintenance costs.</p><h3>PEP-503: Simple Repository API</h3><p>Fortunately, the requirements for hosting a pypi-compatible repository and index are minimum and clearly specified in <a href="https://www.python.org/dev/peps/pep-0503/">PEP-503</a>. All you need to do is store the package artifacts in a certain directory structure, generate an index for the files and put both the repository (ie. package artifacts) and the index behind any web server that can serve static files.</p><p>As per the specification, the directory structure looks something like this,</p><pre>/simple<br>|-- foo<br>|   |-- foo-0.1.0-py2-none-any.whl<br>|   |-- foo-0.1.0-py3-none-any.whl<br>|   |-- foo-0.2.0-py2-none-any.whl<br>|   |-- foo-0.2.0-py3-none-any.whl<br>|   `-- index.html<br>|-- index.html<br>`-- bar<br>    |-- index.html<br>    |-- bar-0.3.1-py2-none-any.whl<br>    |-- bar-0.3.1-py3-none-any.whl<br>    `-- bar-0.3.1.tar.gz</pre><pre>2 directories, 16 files</pre><p>Once the directory structure is ready, you can setup a web server in front of it to serve the package files and index over HTTP(S).</p><p>Now, users can install private packages from this index by specifying --extra-index-url option with the pip install command as follows,</p><pre>$ pip install mypackage --extra-index-url=<a href="https://my.private.pypi.com/simple">https://my.pypi.com/simple</a></pre><h3>Securing access</h3><p>The above setup will give us a working package index. However, if you remember, we started with the goal of keeping the packages secure and private.</p><p>For that it helps to think about two types of users who will need different levels of access to the repository and index,</p><ol><li><strong>Publishers</strong>: Will publish packages to the repository when new versions are released. They will need read-write access to the repository. Ideally, your release automation system will be the publisher. Additionally, there could also be human release managers who are authorized to publish packages.</li><li><strong>Consumers</strong>: Will fetch and install packages for development or production use. These will be developers plus the build automation system. They will need read-only access to the package index served over HTTP.</li></ol><h3>Our setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Mp3a4QIW3SA6yMe8u4jOsQ.png" /><figcaption>Our setup using S3, nginx and a custom package publishing tool — pypiprivate</figcaption></figure><p>In our setup, we use the following components:</p><h4>Amazon S3</h4><p>Package artifacts and indexes are stored in an <a href="https://aws.amazon.com/s3/">S3</a> bucket which is protected by IAM credentials.</p><h4>Pypiprivate</h4><p>For copying files to S3 as per the required directory structure (or more precisely, an s3 key hierarchy) and generating the index, we built our own tool —<a href="https://github.com/helpshift/pypiprivate"> pypiprivate</a>, as there wasn’t an existing one that met our requirements. You can install pypiprivate from pypi.org and read it’s documentation on github.</p><p>At present, pypiprivate supports S3 and local file system as storage backends but it can be easily extended to support others such as Azure Blob Storage, Google Cloud Storage etc.</p><h4>Nginx</h4><p>We use <a href="https://nginx.org/">nginx</a> as the reverse proxy server sitting in front of the S3 bucket.</p><p>For secure access to S3, we’ve configured the <a href="https://github.com/anomalizer/ngx_aws_auth">AWS Auth Plugin</a> through which nginx authenticates with Amazon using read-only credentials. At the same time, HTTP Basic Authentication is configured to provide secure access to the index over HTTP(S). Our nginx conf looks something like this,</p><pre>server {</pre><pre>    server_name my.pypi.com;</pre><pre>    ...</pre><pre>    auth_basic &quot;Restricted&quot;;<br>    auth_basic_user_file /etc/nginx/.htpasswd;</pre><pre>    location /simple {<br>        # serve the index if request ends with a slash<br>        rewrite ^(.*)\/$ $1/index.html break;</pre><pre>        aws_access_key &quot;**************&quot;;<br>        aws_secret_key &quot;**************&quot;;<br>        s3_bucket mypypibucket;</pre><pre>        proxy_set_header Authorization $s3_auth_token;<br>        proxy_set_header x-amz-date $aws_date;<br>        proxy_pass <a href="https://mypypibucket.s3.amazonaws.com/">https://mypypibucket.s3.amazonaws.com</a>;<br>    }<br>}</pre><p>For installing from the private repository, HTTP basic auth credentials can be specified in the pip install command as follows,</p><pre>$ pip install mypackage --extra-index-url=https://&lt;username&gt;:&lt;password&gt;<a href="http://twitter.com/my">@my</a>.pypi.com/simple</pre><h3>What about the “zero hassle” part?</h3><p>As you can see, by not running an application server we’ve managed to side step a lot of complexity. If we’d have been running an application server such as devpi or pypyserver, then high availability and monitoring would have been our additional concerns.</p><p>Nginx cluster being already a part of our infra, HA and monitoring for that was already in place.</p><p>S3 as the storage is highly available, cheap and replicates data on multiple devices across availability zones by default. This spares us from worrying about backup and recovery.</p><h3>Conclusion</h3><p>We’ve been using this private package index for quite a few months. It’s a simple solution that covers our basic use case and is hassle-free for us to maintain. At the same time, there is definitely a trade-off in terms of missing all the cool features that sophisticated solutions such as devpi offer.</p><p>The purpose of this post was mainly to share the approach that has worked well for us. You may use it to host your own private package repository and index, adapting it the cloud provider and web server of your choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6164e3831208" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/private-python-package-index-with-zero-hassle-6164e3831208">Private Python Package Index with Zero Hassle</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>