<?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 Mohammad Suhail on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Suhail on Medium]]></description>
        <link>https://medium.com/@mohammadsuhail3257?source=rss-2ae91ea33156------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rQeVzK-wyVU-IEbX</url>
            <title>Stories by Mohammad Suhail on Medium</title>
            <link>https://medium.com/@mohammadsuhail3257?source=rss-2ae91ea33156------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:22:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammadsuhail3257/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[Zero-Downtime PostgreSQL Upgrade: RDS Blue/Green from version 13 to version 18]]></title>
            <link>https://medium.com/@mohammadsuhail3257/zero-downtime-postgresql-upgrade-rds-blue-green-from-version-13-to-version-18-d75e02091189?source=rss-2ae91ea33156------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75e02091189</guid>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[aws-rds]]></category>
            <dc:creator><![CDATA[Mohammad Suhail]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 10:48:46 GMT</pubDate>
            <atom:updated>2026-06-17T10:48:46.500Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL has been the most popular open source database since 2020 and matured over decades. Many organization have already started migrating their databases to PostgreSQL because of the <a href="https://www.cloudraft.io/postgresql-consulting">open source</a> nature, flexibility and the customization that we can do in PostgreSQL with extensions.</p><p>For one of our customers, we had several production PostgreSQL instances running on version 13, spread across multiple AWS regions. Each was a few hundred GBs in size along with read replicas. As you might know that AWS RDS standard support for PostgreSQL 13 ended in February 2026 and AWS charges additional fees for extended support. From March 2026, every Postgres v13 instance will incur a surcharge of 6x on the standard pricing. To get bug fixes and security patches you are forced to pay premium or upgrade to a newer version. Also, there is a risk that after sometime, the older versions will not be supported at all.</p><p>This is where we decided to upgrade to Postgres v18. Like every other business, we wanted to have a minimum downtime and minimum code changes. To achieve this, we explored and identified that AWS RDS blue/green deployment is the best way to do it. In this blog post, we will share our experience of upgrading and learnings.</p><h3>Why Postgres v18, and Why Now</h3><p>PostgreSQL v18 is a major release in the recent years and for good reasons. It has a lot of improvements and new features that we wanted to take advantage of. To take advantage, we skipped four versions and upgraded to v18.</p><p>Here are some of the key features that we are excited about:</p><h3>Async I/O</h3><p>Native asynchronous I/O delivers 2–3X throughput on sequential scans, bitmap heap scans, and VACUUM. No application changes needed.</p><h3>Better observability</h3><p>pg_stat_io breaks cache hits and reads latency down per backend. pg_stat_statements query identifiers now survive restarts.</p><h3>Planner and index improvements</h3><p>B-tree skip scans make composite indexes useful for queries that don’t filter on the leading column. Better join ordering. Better partition pruning.</p><h3>Runway</h3><p>Postgres v18 is supported until February 2031.</p><h3>Why we used AWS RDS Blue/Green deployment strategy?</h3><p>Major-version upgrades on RDS used to mean two bad options. Run pg_upgrade in place, accept a real maintenance window, and pray nothing goes wrong because rollback is painful. Or do a dump-and-restore, and accept hours of downtime. Neither works for a 24/7 system with users in three timezones.</p><p>Blue/Green changes the problem entirely. AWS spins up a copy of your database on the new version (Green) while the original (Blue) keeps serving traffic. PostgreSQL logical replication keeps them in sync. When you’re ready, AWS swaps the DNS endpoints in under a minute, and your app reconnects to the upgraded database. The connection string never changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4h3lgPET-woAk7Vm" /></figure><p>Blue Green Workflow</p><h3>Planning the upgrade</h3><p>The most important thing to do to get confidence in our process is to rehearse it. So we worked on well written runbook and tested it in our non-production clusters until we refined it to the point where we were confident it would work in production.</p><h3>The upgrade process</h3><ul><li>Take a manual snapshot of production</li><li>Restore it as an isolated RDS instance in the same account and VPC</li><li>Attach a custom parameter group with the right logical replication settings</li><li>Create a Blue/Green deployment targeting Postgres v18</li><li>Wait for sync, run smoke tests against the Green endpoint, and switch over</li><li>once confident and ready drop the old instance</li></ul><p>How to Rollback? Blue/Green has automatic rollback if the switchover fails its own health checks; AWS just keeps you on Blue. But once the switchover succeeds and your application has written even a single row to the new database, going back means losing those writes. That’s a real decision with real data-loss implications. The rehearsal is when you decide what would actually trigger one. You don’t want to be making that call for the first time during an incident.</p><h3>Learnings</h3><ol><li>Configuration Issues: Parameter group settings that don’t meet Blue/Green prerequisites. Tune these to match the workload, and remember some of them require a reboot:</li></ol><ul><li>max_wal_senders</li><li>max_replication_slots</li><li>max_logical_replication_workers</li><li>max_worker_processes</li><li>rds.logical_replication</li><li>rds.blue_green_replication_type</li></ul><ol><li>Schema Issues: Two specific things will fail Blue/Green creation with errors:</li></ol><ul><li>Tables without primary keys: Logical replication uses the primary key to identify rows. Without one, updates and deletes won’t replicate, and the whole stream can stall. If adding a real PK needs a design review you don’t have time for, REPLICA IDENTITY FULL is a reasonable workaround. It tells PostgreSQL to send the entire old row instead of just the key. WAL volume goes up a bit but upgrade will work.</li><li>Extensions Incompatibility: A version of an extension that works on Postgres v13 may not even exist on Postgres v18. RDS upgrades the binary during Blue/Green but leaves your extensions where they were. If an extension version exists on Postgres v13 but not Postgres v18, deployment creation fails with an unhelpful error. Audit installed extensions, update anything that’s behind, then update them again on Green after the switchover.</li></ul><ol><li>Logical replication wasn’t enabled: Blue/Green needs it on the source, but stock RDS parameter groups don’t have it.</li></ol><p>Fix: Custom parameter group, set the logical replication and worker process parameters, reboot. Do this well before the change window as these settings need a restart.</p><p>2. DDL executions during the sync broke replication</p><p>Logical replication doesn’t carry schema changes. Someone added a column to a table on Blue while Green was syncing, and the next write to that table broke the replication stream. There’s no clean recovery — we had to tear down the Blue/Green and start over. It cost us more than an hour of re-provisioning.</p><p>Fix: Hard-freeze all schema changes from the moment Blue/Green is created until switchover finishes. Tell every team with write access. Same rule for long-running transactions, since they hold back replication and can fail the switchover itself.</p><p>3. Smoke testing Green before switching</p><p>The Green instance has its own endpoint while Blue is still alive. Use it. We checked the version, confirmed replication lag was zero, ran our top queries from pg_stat_statements against Green and compared plans against Blue, verified extensions, and spot-checked row counts on the largest tables. If anything fails here, you abort and Blue keeps serving. That&#39;s the whole point of the design, and it&#39;s worth actually exercising.</p><h3>The Switchover</h3><p>Once you click Switch Over, AWS handles the rest. It briefly write-blocks Blue so Green can catch up to the final LSN. It verifies they’re in sync. It swaps DNS endpoints, flips Green to read-write, and puts Blue into read-only as a safety net. If any health check or timeout fails along the way, AWS rolls everything back automatically and leaves you on Blue.</p><p>The best part is what doesn’t happen: your application’s connection string doesn’t change. AWS reuses the original endpoint name, so existing connections drop, the connection pool reconnects, and the next query lands on the upgraded database. We redeployed the app during the window to force all connections to reset cleanly, but it wasn’t strictly necessary. The whole switchover finished in under a minute. Users didn’t notice.</p><h3>What we improved with the upgrade</h3><p>A major-version upgrade is a rare moment when you have permission to change almost everything. We treated it as more than a version bump and rolled in every hygiene fix we’d been putting off.</p><ul><li>Postgres v18 features: Native asynchronous I/O is the headline change — 2–3x faster on sequential scans, bitmap heap scans, and VACUUM. We also picked up B-tree skip scans, the richer pg_stat_io view for per-backend cache and latency analysis, planner statistics that survive pg_upgrade, native UUIDv7, and OAuth 2.0 authentication.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*raJIBqVMJOAB796K" /></figure><p>Async I/O</p><p>PostgreSQL 18’s async I/O is the biggest raw-performance change in years. Worker-based I/O lets backends queue multiple reads in parallel instead of blocking on each one.</p><ul><li>A fresh parameter group: We didn’t carry the Postgres v13 group forward. Started from default.postgres18 and only set the values we actually needed: async I/O on, effective_io_concurrency raised, work_mem increased, checkpoint and autovacuum behaviour tuned. Everything that was a workaround for an old-version quirk got dropped.</li><li>Extensions brought current: Every extension in every database got ALTER EXTENSION... UPDATE after the switchover. RDS won&#39;t do this for you, and stale versions just accumulate quietly until something breaks.</li><li>Monitoring turned on: Performance Insights and Enhanced Monitoring went on as part of the Green configuration. Both are cheap. Neither needs a restart if you enable them upfront. You’ll need both for the tuning work that comes next.</li><li>Graviton instance class: Moved from Intel-based db.m5 to Graviton3-based db.m7g. AWS&#39;s own RDS benchmarks show about 30% better throughput, 27% better price-performance over the previous generation, and 50% more memory bandwidth. PostgreSQL is memory-bandwidth-bound on hot queries, so this actually matters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PXweMX7B05ZoDxH" /></figure><p>Graviton Performance</p><p>AWS’s own RDS benchmarking for PostgreSQL. Graviton3 (m7g) is the first RDS instance family with DDR5 memory, giving 50% more memory bandwidth — meaningful for memory-bandwidth-bound workloads like PostgreSQL.</p><ul><li>gp3 storage with tuned IOPS and throughput: gp3 separates capacity from performance — you size storage for what you need to store and set IOPS and throughput independently. Much better fit for a database than gp2’s coupled model. You don’t need Blue/Green to do this, but doing it in the same window meant we only had to validate performance once.</li></ul><h3>Post-Switchover Performance Tuning</h3><p>The switchover itself is anticlimactic. Database is up, app reconnects, users don’t notice. There’s a temptation to close the ticket and move on, Don’t. The first few days/week on the new version are when you have the richest performance data you’ll ever have.</p><p>Postgres v18’s pg_stat_io, pg_stat_statements, and pg_stat_user_tables together surface common opportunities:</p><ul><li>Async I/O isn’t always on: On some instances RDS defaults io_method to sync, which silently disables Postgres v18&#39;s biggest feature. Check every instance after switchover. Flipping it to the worker is the highest-ROI change you&#39;ll make.</li><li>One query usually dominates database time: Sort pg_stat_statements by total execution time and you&#39;ll almost always find one or two queries eating most of the budget. The fix often isn&#39;t in the database - it&#39;s a polling loop or an unfiltered join in the application that needs to be redesigned. Hand the evidence back to the app team.</li><li>Cache hit ratios below 97% point at a missing index: The pg_stat_io breaks cache behaviour down per table, so you can spot the one table thrashing the buffer pool. The fix is usually a partial index that matches the actual query pattern.</li><li>Unused indexes are pure cost: They take disk, buffer cache, and slow down every write. Find them with pg_stat_user_indexes WHERE idx_scan = 0. Wait a few weeks to be sure, confirm with the app team, then drop them with DROP INDEX CONCURRENTLY.</li><li>Bloated tables and stale autovacuum settings: Blue/Green resets statistics — every table starts with Last Analyzed = today and zero dead tuples. Default autovacuum thresholds only kick in at 10% dead, which on a large table is a lot of bloat. Run manual VACUUM ANALYZE on the biggest tables, then tune per-table autovacuum settings to trigger earlier.</li><li>Checkpoint and work_mem tuning: Long checkpoint write times mean max_wal_size and checkpoint_completion_target need raising. Lots of temp file generation in pg_stat_statements means work_mem is too small. Both are parameter group changes that apply without a restart.</li></ul><h3>Final Thoughts</h3><p>With any upgrade, there is always a risk of failure or a miss, so keep a few things in mind:</p><ul><li>Rehearse on a real restored snapshot to find production surprises in an environment you can throw away.</li><li>Freeze schema changes during the sync window. DDL during sync breaks replication with no clean recovery.</li><li>Budget DBA time for two weeks after switchover to use the new telemetry to fix tuning opportunities.</li></ul><p>PostgreSQL releases a major version annually. Skipping these updates creates “technical debt” as missed versions pile on deprecated parameters and orphaned extensions. Old versions just become more expensive to maintain.</p><p>If you are looking for help with migration, please <a href="https://www.cloudraft.io/contact-us">book a meeting</a> with us to discuss your needs.</p><p><a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.cloudraft.io%2Fblog%2Fzero-downtime-postgres-upgrade&amp;text=I%20just%20read%20an%20article%20about%20Zero-Downtime%20PostgreSQL%20Upgrade%3A%20RDS%20Blue%2FGreen%20from%20version%2013%20to%20version%2018%20by%20%40cloudraftio.%0A%0A"><strong>Tweet this article</strong></a><strong> </strong><a href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.cloudraft.io%2Fblog%2Fzero-downtime-postgres-upgrade"><strong>Share on LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75e02091189" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero downtime CloudNativePG (CNPG) and PostgreSQL upgrade on Kubernetes]]></title>
            <link>https://medium.com/@mohammadsuhail3257/zero-downtime-cloudnativepg-cnpg-and-postgresql-upgrade-on-kubernetes-1253c755c1a1?source=rss-2ae91ea33156------2</link>
            <guid isPermaLink="false">https://medium.com/p/1253c755c1a1</guid>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[database-upgrade]]></category>
            <category><![CDATA[cnpg]]></category>
            <dc:creator><![CDATA[Mohammad Suhail]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 10:39:33 GMT</pubDate>
            <atom:updated>2026-06-17T10:43:54.333Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL major upgrades in Kubernetes involve much more than changing the database version. We often hear stories that running databases on Kubernetes is hard. One can argue on this topic and whether we should run it or not, Chris has <a href="https://www.cloudraft.io/blog/why-would-you-run-postgresql-on-kubernetes">penned down his thoughts</a> earlier. In short, we do recommend stable projects like CloudNativePG to create PostgreSQL clusters on Kubernetes. The project has evolved a lot in the last few years. Due to its recent acceptance as a CNCF Sandbox project, it has got more traction and support from various companies including us.</p><p>If you have not heard about CloudNativePG (CNPG) so far, here is a short introduction. It is an open-source operator designed to manage PostgreSQL workloads on Kubernetes cluster. It fosters cloud-neutrality through seamless deployment in private, public, hybrid, and multi-cloud environments via its distributed topology feature. We have seen many customers migrating off from cloud managed services like AWS RDS to save cost or to make multi-cloud possible. The self-hosted architecture allows you to be cloud agnostic and at the same time gives you freedom to build a custom PostgreSQL for you from hundreds of extensions available. For example, if you are looking to run TimescaleDB on PostgreSQL, today you can’t do it on AWS RDS, however this is possible on CNPG running on EKS. Talking about reliability, we have seen <a href="https://www.cloudraft.io/cloudnativepg-commercial-support-for-enterprises">our customers run 100s of databases</a> using CNPG just like AWS RDS.</p><p>This article talks about a very important aspect of CloudNativePG management that is upgrades. Often upgrading a database is hard because of variability over time. No two systems are the same. Here we are showing methods on how to do database upgrade reliability with minimal down time.</p><h3>Why upgrade to latest CNPG Operator and PostgreSQL version</h3><p>Before going further, we would like to highlight that CNPG is relatively a young project unlike PostgreSQL in the CNCF ecosystem and it is evolving rapidly. In past few versions, there were many operations bugs that caused issues. CNPG developers are working hard to make it bug free and hence we also recommend testing the new version thoroughly. If you need help, don’t hesitate to <a href="https://www.cloudraft.io/contact-us">engage us</a>.</p><p>Upgrading to CloudNativePG 1.29 provides significant infrastructure improvements, specifically by enabling in-place instance manager updates that eliminate rolling restarts and connection drops during maintenance, alongside a more robust, native backup configuration.</p><p>PostgreSQL 18 introduces a native async_io subsystem, which speeds up sequential scans and data-heavy queries by fetching data from disk concurrently instead of waiting on blocking system calls. The update also enhances logical replication stability, optimizes GIN indexes, and accelerates JSONB querying for improved performance.</p><h3>Understanding the CloudNativePG upgrade approaches</h3><p>CloudNativePG supports multiple approaches for PostgreSQL major version upgrades, each with different trade-offs around downtime, complexity, and rollback safety. To understand the operational impact in real environments, we tested both supported upgrade paths: traditional in-place pg_upgrade and logical replication-based migration. The goal was to compare how each method behaves during backups, failovers, replication sync, and production-style cutovers.</p><p>We tested both supported upgrade approaches.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmJWaH%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmJWaH%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmJWaH%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="875" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1b78f9b49c111e9006ff2dcfbdeef5b/href">https://medium.com/media/f1b78f9b49c111e9006ff2dcfbdeef5b/href</a></iframe><p>For production systems with strict uptime requirements, logical replication-based migration is the perfect solution.</p><h3>How to upgrade the CNPG Operator and Database</h3><p>To showcase, we have created a scenario from one of our environments. We wanted to understand CNPG behaviour before touching anything in production. This demo is created using a Kind cluster with a realistic-sized database and runs through every operation: install, backup, operator upgrade, major version upgrade, logical replication, monitoring, and a full disaster recovery cycle.</p><p>The test database had 32 million rows across 6 tables — customers, orders, order_items, products, inventory, and an audit_log, with JSONB columns, GIN indexes, and foreign keys. Big enough to expose real problems.</p><p>Here’s the high-level flow we have tested:</p><p>Install CNPG operator 1.25 with a PostgreSQL17 cluster (primary + standby) Deploy MinIO as S3-compatible backup storage Load test data, take a backup, validate it Upgrade the CNPG operator from 1.25 to 1.29 Create PostgreSQL cluster with version 18 Setup logical replication between PostgreSQL17 and PostgreSQL18 and monitor Setup CNPG monitoring Destroy everything and restore from backup (DR test)</p><h3>Architecture Overview of our setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hqJHaz2RYs-1V10t" /></figure><p>Architecture for the CNPG PostgreSQL upgrade demo environment.</p><h3>Installation and setting up a test cluster</h3><p>To showcase the upgrade (production like state), here we are installing the 1.25 version.</p><pre># install CNPG 1.25 operator in kind cluster<br><br>kubectl apply --server-side -f \<br>https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.25/releases/cnpg-1.25.0.yaml</pre><p>Now let’s create a small 2 node Postgres cluster (Primary + 1 standby, PostgreSQL 17)</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: Cluster<br>metadata:<br>  name: &lt;server-name&gt;           # &lt;server-name&gt; = say pg_lab<br>spec:<br>  instances: 2                  # 1.(Creates pods: pg-lab-1, pg-lab-2)<br>  imageName: ghcr.io/cloudnative-pg/postgresql:17.4<br>  storage:<br>    size: 1Gi<br>  postgresql:<br>    parameters:<br>      wal_level: &quot;logical&quot;      # 2. Used for replication<br>      ...</pre><p>Note that instances: 2 creates one primary and one standby in the SAME cluster, not two clusters. CNPG auto-creates three services per cluster:</p><ul><li>&lt;name&gt;-rw → always points to primary (use for writes)</li><li>&lt;name&gt;-ro → points to standbys (use for read scaling)</li><li>&lt;name&gt;-r → points to all instances</li></ul><p>To check who is primary/standby:</p><pre>kubectl get pods -l cnpg.io/cluster=&lt;server-name&gt; -L role<br>kubectl exec -it &lt;pod-name&gt; -- psql -U postgres -c &quot;SELECT pg_is_in_recovery();&quot;<br># f = primary, t = standby</pre><h3>Deploying MinIO for local S3 storage</h3><pre># Create namespace and authentication secret<br>kubectl create ns &lt;name-space&gt;<br>kubectl create secret generic minio-creds \<br>  --namespace &lt;name-space&gt; \<br>  --from-literal=MINIO_ROOT_USER=&lt;minio-user&gt; \<br>  --from-literal=MINIO_ROOT_PASSWORD=YOUR_PASSWORD</pre><pre># minio-setup.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: minio<br>  namespace: &lt;name-space&gt;<br>spec:<br>  replicas: 1<br>  template:<br>    spec:<br>      containers:<br>        - name: &lt;container-name&gt;<br>          image: quay.io/minio/minio:latest<br>          args: [&#39;server&#39;, &#39;/data&#39;, &#39;--console-address&#39;, &#39;:9001&#39;]<br>          envFrom: [{ secretRef: { name: minio-creds } }]<br>          # ... [ports, volumeMounts, and emptyDir volumes here] ...<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: minio<br>  namespace: &lt;name-space&gt;<br>spec:<br>  ports:<br>    - port: 9000<br>      name: api<br>  # ... [console port and selector info here] ...</pre><p>Provision your target backup bucket</p><pre>kubectl run minio-mc --namespace &lt;name-space&gt; --rm -it --restart=Never \<br>  --image=quay.io/minio/mc:latest --command -- \<br>  sh -c &quot;mc alias set local http://minio.minio-upgrade.svc.cluster.local:9000 &lt;minio-user&gt; &lt;password&gt; &amp;&amp; mc mb local/&lt;backup-folder&gt;&quot;</pre><h3>Load test data, take backup, and validate it</h3><p>Insert data in PostgreSQL17 (primarily via the ~rw service) and CloudNativePG. It instantly replicates it to the standby pods automatically. Take the backup and validate it.</p><pre># ecom-db-backup.yaml<br>apiVersion: postgresql.cnpg.io/v1<br>kind: Backup<br>metadata:<br>  name: &lt;backup-name&gt;<br>spec:<br>  cluster:<br>    name: &lt;server-name&gt;<br># List backup files in S3<br>kubectl run minio-mc --namespace &lt;name-space&gt; --rm -it --restart=Never \<br>  --image=quay.io/minio/mc:latest --command -- \<br>  sh -c &quot;mc alias set local http://minio.minio-upgrade.svc.cluster.local:9000 &lt;minio-user&gt; YOUR_PASSWORD &amp;&amp; mc ls --recursive local/&lt;backup-name&gt;/&lt;server-name&gt;/base/&quot;</pre><p>Always set the serverName explicitly in your configuration, as even a tiny mismatch completely breaks the restoration path in MinIO and triggers a no target backup found error.</p><h3>Upgrading CNPG operator from 1.25 to 1.29</h3><p>Upgrading the CNPG operator is not very complicated but do read the release notes of each release and also be aware of certain settings in your cluster specification about automatic in-place upgrade. Each cluster pod runs two containers, one is the bootstrap container that is upgraded during the CRD update. The other one is postgreSQL instance container (actual database application container).</p><p>During the operator upgrade, the new container detects older instance binaries running in existing database pods. By default this triggers a rolling restart of PostgreSQL instances that can cause an automatic switchover where a standby is promoted and the primary restarts resulting in a brief connection interruption.</p><p>Hence to reduce disruption, enable in-place instance manager updates before upgrading the operator.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: cnpg-controller-manager-config<br>  namespace: &lt;name-space&gt;<br>data:<br>  ENABLE_INSTANCE_MANAGER_INPLACE_UPDATES: &#39;true&#39;</pre><p>Run this in correct order:</p><ol><li>apply the configmap</li></ol><pre><br>kubectl apply -f cnpg-inplace-config.yaml</pre><p>2. restart the CURRENT operator so it loads the config</p><pre>kubectl rollout restart deployment cnpg-controller-manager -n cnpg-system<br>kubectl wait --namespace &lt;name-space&gt; \<br>  --for=condition=ready pod -l app.kubernetes.io/name=cloudnative-pg --timeout=120s</pre><p>3. verify the config is loaded (look for inplace in the logs)</p><pre>kubectl logs -n cnpg-system deploy/cnpg-controller-manager | grep -i inplace</pre><p>4. NOW upgrade the operator</p><pre>kubectl apply --server-side -f \<br>https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.29/releases/cnpg-1.29.0.yaml</pre><p>5. Verify:</p><pre>kubectl get deployment cnpg-controller-manager -n &lt;name-space&gt; \<br>  -o jsonpath=&#39;{.spec.template.spec.containers[0].image}&#39; &amp;&amp; echo<br>kubectl get cluster &lt;server-name&gt;<br>kubectl get pods -l cnpg.io/cluster=&lt;pod-name&gt; -L role</pre><h3>Create PostgreSQL cluster with version 18</h3><p>For near-zero downtime migration, we are setting up a parallel PostgreSQL cluster with the latest version. Next we will set up logical replication between source and target cluster.</p><p>Let’s create a PostgreSQL 18 cluster.</p><pre>apiVersion: postgresql.cnpg.io/v1<br>kind: Cluster<br>metadata:<br>  name: pg-lab<br>spec:<br>  instances: 2<br>  imageName: ghcr.io/cloudnative-pg/postgresql:18.3<br>  storage:<br>    #.... Storage configuration here ...</pre><p>Here you have two clusters running side by side. PostgreSQL17 (source) with all your data, PostgreSQL18 (target) empty. The source keeps serving traffic.</p><h3>Setup logical replication and monitor data sync</h3><p>First, check which pod is primary on the target:</p><pre>kubectl get pods -l cnpg.io/cluster=&lt;pod-name&gt; -L role</pre><p>Logical replication can replicate row data continuously but it does not copy DDL objects like tables/indexes, therefore the schema must be dumped from the source and restored on the target separately.</p><p>Dump schema from source and apply to target using pg_dump</p><pre>kubectl exec -i &lt;source-pod&gt; -- pg_dump -U postgres -s &gt; source_ddl.sql<br>kubectl exec -i &lt;target-pod&gt; -- psql -U postgres &lt; source_ddl.sql</pre><p>Create the publication on the source</p><pre>Kubectl exec -i &lt;source-pod&gt; -- psql -U postgre &quot;CREATE PUBLICATION &lt;pub_name&gt; FOR ALL TABLES;&quot;</pre><p>Create the subscription on the target</p><pre>kubectl exec -i &lt;target-pod&gt; -- psql -U postgre &quot;CREATE SUBSCRIPTION &lt;sub_name&gt; connection &#39;host=&lt;source-pod&gt; port=5432 dbname=postgres user=postgres password=&lt;password&gt;&#39; PUBLICATION &lt;pub_name&gt;;&quot;</pre><p>Monitor sync progress: (Sync states: r=ready , d=compying , i=initializing)</p><pre>kubectl exec -i &lt;target-pod&gt; –- psql -U postgres -c &quot;SELECT srrelid::regclass AS table_name, srsubstate AS state FROM pg_subscription_rel ORDER BY table_name;&quot;</pre><p>Wait until all tables shows ‘r’ syncing state</p><h3>Cutover to PostgreSQL 18 once all data is replicated</h3><p>verify zero lag:</p><pre>kubectl exec -i &lt;target-pod&gt; -- psql -U postgres -c &quot;<br>SELECT subname, received_lsn, latest_end_lsn, received_lsn = latest_end_lsn AS fully_synced FROM pg_stat_subscription;&quot;</pre><p>Should show fully_synced = t.</p><p>Test real-time replication: Insert some rows on source Database and immediately check the same on target database.</p><p>Do the actual cutover :</p><pre># disable subscription<br>kubectl exec -i &lt;target-pod&gt; -- psql -U postgres -c &quot;ALTER SUBSCRIPTION &lt;sub_name&gt; DISABLE;&quot;<br><br><br># detach from replication slot<br>kubectl exec -i &lt;target-pod&gt; -- psql -U postgres -c &quot;ALTER SUBSCRIPTION &lt;sub_name&gt; SET (slot_name = NONE);&quot;<br><br># drop subscription<br>kubectl exec -i &lt;target-pod&gt; -- psql -U postgres -c &quot;DROP SUBSCRIPTION &lt;sub_name&gt;;&quot;<br><br># drop publication on source<br>kubectl exec -i &lt;source-pod&gt; -- psql -U postgres -c &quot;DROP PUBLICATION &lt;pub_name&gt;;&quot;<br><br># clean up orphaned replication slot on source<br>kubectl exec -i &lt;source-pod&gt; -- psql -U postgres -c &quot;<br>SELECT slot_name, active FROM pg_replication_slots WHERE slot_name = &#39;&lt;sub_name&gt;&#39;;&quot;<br><br># if it exists:<br>kubectl exec -i &lt;source-pod&gt; -- psql -U postgres -c &quot;SELECT pg_drop_replication_slot(&#39;&lt;sub_name&gt;&#39;);&quot;</pre><h3>Things to keep in mind while replicating data through logical replication</h3><h4>1. If Sync crashes</h4><p>If the initial sync crashes the target pod (WAL space), CNPG fails over to the standby. The subscription survives but is broken.</p><p>Fix: reset source password, then on target:</p><pre>ALTER SUBSCRIPTION &lt;sub_name&gt; DISABLE;<br>ALTER SUBSCRIPTION &lt;sub_name&gt; SET (slot_name = NONE);<br>DROP SUBSCRIPTION &lt;sub_name&gt;;<br>TRUNCATE &lt;all-tables&gt; CASCADE;</pre><p>Then drop the orphaned slot on source:</p><pre> SELECT pg_drop_replication_slot(&#39;sub_from_source&#39;);</pre><p>And recreate the subscription.</p><h4>2. If CNPG resets password</h4><p>Because CloudNativePG manages database credentials internally, manual ALTER USER password changes may be overwritten during reconciliation or pod restarts, causing password authentication failed errors during replication. For production environments, use operator-managed replication users or certificate-based authentication instead of relying on manual password changes.</p><h3>Monitoring with Prometheus</h3><p>CNPG recommends Prometheus for monitoring and it exposes Prometheus metrics which can be consumed in the existing Prometheus setup. You can enable this during the installation (if doing using Helm) by configuring PodMonitor and verifying metrics are flowing.</p><p>This command connects to Prometheus and checks whether the CloudNativePG metrics collector is healthy and exposes metrics correctly.</p><pre>kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090:9090 &amp;<br>sleep 3<br>curl -s &quot;http://localhost:9090/api/v1/query?query=cnpg_collector_up&quot; | python3 -m json.tool</pre><p>Key metrics worth alerting on:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FSkGVU%2F3%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FSkGVU%2F3%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FSkGVU%2Fplain-s.png%3Fv%3D3&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="299" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1e4f4b6ed4bdb0c3d6b4c46664c8f67/href">https://medium.com/media/a1e4f4b6ed4bdb0c3d6b4c46664c8f67/href</a></iframe><p>Monitoring became especially useful during logical replication because lag visibility mattered during cutover.</p><h3>Disaster Recovery Test</h3><p>The final step was intentionally destructive. We deleted both PostgreSQL clusters completely. Then restored PostgreSQL 18 from MinIO backups. The restore succeeded and all row counts matched.</p><ul><li>Destroy the cluster</li></ul><pre>kubectl delete cluster &lt;target-cluster&gt;</pre><ul><li>Verify the backup survived in MinIO</li></ul><pre>kubectl run minio-mc –namespace &lt;name-space&gt; -rm -it –restart=Never –image=quay.io/minio/mc:latest –command –sh -c &quot;mc alias set local http://minio.minio.svc.cluster.local:9000 &lt;minio-user&gt; &lt;password&gt; &amp;&amp; mc ls –recursive local/&lt;backup-name&gt;/&lt;server-name&gt;/base&quot;</pre><ul><li>Check the data.tar and backup.info files are still in MinIO</li><li>Restore from backup</li></ul><h3>Things to keep in mind</h3><p>serverName must match the S3 prefix of the backup and imageName must match the PostgreSQL version 18 of the backup</p><pre>spec:<br>  imageName: ghcr.io/cloudnative-pg/postgresql:18.3<br>  bootstrap:<br>    recovery:<br>      source: &lt;backup&gt;<br>  externalClusters:<br>    - name: &lt;backup-name&gt;<br>      barmanObjectStore:<br>        serverName: pg-lab<br>        destinationPath: s3://&lt;backup-name&gt;/<br>        ...<br>  backup:<br>    barmanObjectStore:<br>      serverName: &lt;server-name&gt;<br>      destinationPath: s3://&lt;backup-name&gt;/<br>      ...</pre><p>This validated:</p><ul><li>base backup recovery</li><li>WAL restore</li><li>object storage integrity</li><li>CNPG recovery workflow</li></ul><p>Backups are meaningless until restores are tested. If you are looking for more details on the disaster recovery test, <a href="https://www.cloudraft.io/blog/postgresql-on-kubernetes">read our other article</a> where we have explained this in more detail.</p><h3>Learnings from this exercise</h3><p>This testing exercise changed how we think about PostgreSQL upgrades on Kubernetes. CNPG itself was stable and reliable — most of the challenges came from operational details like password management, restore assumptions, WAL sizing, failover behavior, and upgrade sequencing.</p><p>The biggest takeaway for us was that zero-downtime upgrades are absolutely possible, but only when every moving part is understood beforehand. Logical replication ultimately became the safer production approach because rollback stayed simple and the original cluster remained untouched until the final cutover.</p><p>If you’re planning PostgreSQL upgrades on Kubernetes, test the entire lifecycle — not just the happy path. That includes backups, restores, failovers, replication behavior, monitoring, and disaster recovery scenarios. Most real-world issues only appear when the full workflow is exercised end-to-end.</p><p><a href="https://www.cloudraft.io/contact-us">Book a session</a> if you want to discuss your PostgreSQL upgrade strategy on Kubernetes.</p><p><a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.cloudraft.io%2Fblog%2Fcnpg-upgrade-zero-downtime&amp;text=I%20just%20read%20an%20article%20about%20Zero%20downtime%20CloudNativePG%20(CNPG)%20and%20PostgreSQL%20upgrade%20on%20Kubernetes%20by%20%40cloudraftio.%0A%0A"><strong>Tweet this article</strong></a><strong> </strong><a href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.cloudraft.io%2Fblog%2Fcnpg-upgrade-zero-downtime"><strong>Share on LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1253c755c1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>