<?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 Atharva Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Atharva Kulkarni on Medium]]></description>
        <link>https://medium.com/@atharvavk?source=rss-85f996318ea6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1qPLmqAUHnArI3_y.jpg</url>
            <title>Stories by Atharva Kulkarni on Medium</title>
            <link>https://medium.com/@atharvavk?source=rss-85f996318ea6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:21:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atharvavk/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[Inter-cloud PostgreSQL Migration at moderate scale]]></title>
            <link>https://medium.com/@atharvavk/inter-cloud-postgresql-migration-at-moderate-scale-89108f45ae06?source=rss-85f996318ea6------2</link>
            <guid isPermaLink="false">https://medium.com/p/89108f45ae06</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[pgbouncer]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Atharva Kulkarni]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 06:18:02 GMT</pubDate>
            <atom:updated>2026-10-31T06:18:02.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaE23RWN52HDeVV0WZa-1Q.png" /></figure><h3>Statement</h3><p>Frequently while migrating load from one cloud to another or while upgrading the DB, we cannot always use the native streaming replication provided by PostgreSQL. Also there exist some problems like traffic switching/dropping when we point the application from one database to another.</p><h3>Simple solutions which might not work</h3><h3>Import And Export</h3><p>Accept downtime, export the database, restore it and then start fresh fleet of application deployment. It will work for the non-critical workload.</p><p>Problems: Obvious downtime. Export is a bit heavy process, restore too. During export and restoration, writes will be lost.</p><h3>Logical replication with services like Database Migration Services or CDC like debezium (AWS or Google Cloud)</h3><p>Setup logical replication. When the target catches up with source, stop the writes, stop the DMS and then point the application databases to new workload.</p><p>Problems: The downtime is lesser but still there is. There is also a minimal overhead of setting up these services and also their availability is dependent on the cloud platform. When debezium is used, we also need to have a kafka cluster provisioned for it to work.</p><h3>Application level strategies</h3><p>Setup the logical replication first without the CDC. Have your application manually buffer the connections during the switch phase. Start buffering the new transactions when the flag is turned on. Let the running transactions be working as expected. Advantage: minimum downtime</p><p>Problems: Too much code change. The flag propagation delays might impact depending on the implementation.</p><h3>How can we make the switch phase independent of the code changes?</h3><h3>TLDR: PgBouncer</h3><p>Till now, we saw that the minimum impact to system was observed in the Application Level Strategies. But implementation might introduce errors and the code efforts will be useless after the successful migration. So what I propose is, application should be independent of the underlying database logic. A proxying layer should be managing the transactions and routing the traffic. <strong>PgBouncer</strong> does exactly what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7XQh1IbdMfWImFmsXGMXg.png" /></figure><p>We can setup the logical replication between two PostgreSQL servers, assuming that these servers have network reachability. Setup the PgBouncer proxy on the source server. Start the proxy in the transaction mode (important). The default session mode will not behave this way.</p><p>Whenever the lag reaches near-zero, PAUSE the proxy. Doing this, PgBouncer will start buffering the new transactions but it will let the existing transactions finish. Keep monitoring for the active transactions to drop to zero. When done, check the LSN lag (Log Sequence Number). Once it reaches zero, copy the sequences, the sequences do not get replicated.</p><h4>If we wish to have bi-directionality, setup the reverse logical replication from target to source during this period.</h4><p>(Use origin = &#39;none&#39; on these subscriptions — it applies only locally-originated changes and keeps the two directions from echoing each other&#39;s writes.)</p><p>Change the connection to target in PgBouncer and reload the config. Resume the connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVFOcNXIi0F8_NO8apKZyA.png" /></figure><h3>What impact will this make on your system?</h3><p>The PAUSE duration depends on the length of your transactions.</p><p>During the paused phase, new transactions will be blocked, your application will keep on waiting and it might block some of the threads. So application will face some load during this period.</p><p>Doing this in the lean time will be easier. Having the automated scripts to move the sequences and monitoring the LSN lag/Active transactions will reduce this time significantly.</p><p><strong>So 2 major parameters impacting the state of migration are:</strong></p><ol><li>Duration of transactions.</li><li>Rate of transactions. (Number of transactions running per second)</li></ol><p>If I had to say, first parameter is more impacting than the second one. If transactions finish quicker, PAUSE duration will be shorter and hence the wait new transactions will need to do.</p><h3>Verification</h3><p>To verify this, I wrote a simple golang app, connecting to the PgBouncer proxy. The application runs 10s transactions:</p><ol><li>Start the transaction.</li><li>Insert one row.</li><li>Wait for 10s.</li><li>Edit the inserted row.</li><li>Commit the transaction.</li></ol><p>So our transaction duration is ~10s.</p><p>While doing this, I PAUSE the proxy. Do the necessary monitoring and then RELOAD with appropriate target connections.</p><h3>Observability required on</h3><p><strong>Application layer</strong></p><ol><li>The pause duration.</li><li>Average increase in the transaction duration during the period.</li></ol><p><strong>Database layer</strong></p><ol><li>LSN lag</li></ol><pre>-- how far is the target behind the source, per replication slot<br>SELECT slot_name, active,<br>       pg_current_wal_lsn() - confirmed_flush_lsn AS lag_bytes,<br>       pg_size_pretty(pg_current_wal_lsn() - confirmed_flush_lsn) AS pretty_lag<br>FROM pg_replication_slots;</pre><p>2. Active transactions (drain is done when this hits zero)</p><pre>SELECT count(*) AS in_flight<br>FROM pg_stat_activity<br>WHERE state &lt;&gt; &#39;idle&#39;<br>  AND application_name NOT LIKE &#39;sub_names%&#39;<br>  AND pid &lt;&gt; pg_backend_pid();</pre><p>3. Subscription worker status</p><pre>SELECT subname, received_lsn, latest_end_lsn, latest_end_time<br>FROM pg_stat_subscription;</pre><p><strong>PgBouncer layer</strong></p><ol><li>Number of running/paused/buffered transactions.</li></ol><pre>-- cl_active  = clients currently inside a transaction (drain count)<br>-- cl_waiting = clients buffered while the proxy is paused<br>-- maxwait    = seconds the longest buffered client has waited<br>SHOW POOLS;</pre><p>Also handy: SHOW SERVERS (server conns to old primary should drop to 0 during drain), SHOW STATS (tx rate through the proxy), and SHOW DATABASES (which host the pool currently points at).</p><p>The admin console runs off the same pgbouncer port: psql -h 127.0.0.1 -p 6432 -d pgbouncer -U pgbadmin</p><h3>Observations from the runs</h3><p>Two runs, source on port 5432, target on 5433, load generator spawning 5 transactions/sec (300/min), each holding a transaction open for ~10s (worst case for drain).</p><p>Run 1 (80s, switchover at ~t+18s): 400 transactions spawned, <strong>0 failed</strong>, 90 committed on 5432 and 310 on 5433. The PAUSE window itself took ~10.1s — bounded by the oldest in-flight transaction (10s hold). Transaction start-to-insert latency stayed at p50 ~2ms during normal times; p95 spiked to ~6s and max to ~10s purely because of buffered transactions waiting during the pause. Nobody got rejected, nothing timed out — hooks are max_client_conn and query_wait_timeout on PgBouncer, both tuned above the drain window.</p><p>Run 2 (5 min, switchover at ~t+90s): 1500 transactions spawned, <strong>0 failed</strong>, 450 on 5432 and 1050 on 5433, row counts identical on both instances afterwards.</p><p>The full setup scripts, the switchover automation (drain → LSN check → sequence copy → RELOAD → RESUME) and the load generator live here: <a href="https://github.com/atharvavk/pg_migration">https://github.com/atharvavk/pg_migration</a></p><h3>Conclusion</h3><p>The pattern worked as expected: the application never knew a switchover happened — no failed transaction, no reconnect needed, the buffering latency during the drain window was the only visible cost. The proxy owning the switch is what keeps the application code clean, and the drain-catchup-verify order is what keeps the data clean.</p><p>Things to keep in mind before using it for real: schema/DDL parity must already exist on the target (logical replication moves data only), every identity column needs the sequence copy step, PgBouncer is now a single point of failure so run a redundant pair in production, and cross-region latency will stretch both the catch-up and the drain window — pick a lean time for it.</p><p>The repo is a lab-grade blueprint (trust auth, single proxy) — worth reading through before production use: <a href="https://github.com/atharvavk/pg_migration">https://github.com/atharvavk/pg_migration</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89108f45ae06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>