Upgrading PostgreSQL 18 to 19 With Seconds of Downtime: A Measured Blue/Green Design With Logical Replication

 

PostgreSQL 18 to 19 upgrade with seconds of downtime: 48 s copy, 2.27 s cutover

Every PostgreSQL team meets the same question once a year: how do we move to the next major version without taking the application down for long? pg_upgrade is fast but still needs the database stopped, and dump/restore needs hours on a big database. The third way is blue/green with logical replication: build the new version next to the old one, let it catch up while the application keeps running, and switch over in a short, controlled window.

PostgreSQL 19 is out, so I measured exactly that: PostgreSQL 18.1 → 19.0, 20 million rows, 16 clients writing the whole time, with every step of the cutover timed and the data validated before the switch. Everything here comes from one end-to-end run, and the full kit of scripts is at the end so you can repeat it.

TL;DR
  • Initial copy to PostgreSQL 19: 48 seconds for 20 M accounts plus a 5 M-row partitioned table, while the application kept writing. Throughput on the old server dropped from about 15,400 to 10,200 tps during the copy.
  • Steady replication: after a one-minute catch-up (peak lag 297 MB, 6.4 s), green stayed on average 0.7 MB and at most 0.36 s behind blue.
  • Cutover: 2.27 s from freezing writes on blue to opening green, including a full count-and-sum validation that matched on all five tables. The validation alone was 1.69 s.
  • What the application saw: about 2.4 seconds without writes, 16 in-flight transactions rolled back (one per client), and 0 committed transactions lost.
  • The traps (sequences, tables without a primary key, partitioned tables, roles, DDL) and how to handle each are in the checklist below.

The design

Blue is the current production database. Green is a new cluster on the new major version, with the same settings. Logical replication streams every committed change from blue to green, so green is a live, up-to-date copy. At cutover you stop writes on blue for a moment, let green apply the last changes, fix the things logical replication does not carry, check the data, and point the application at green. Blue is left frozen and untouched as the fallback.

Animation: blue/green PostgreSQL upgrade with logical replication, from initial copy to cutover


The test setup

Details
ServerRHEL 8.10, 16 vCPUs, 62 GB RAM, SSD. Both clusters on the same server, different ports, identical settings (8 GB shared_buffers, wal_level = logical).
BluePostgreSQL 18.1 (PGDG packages)
GreenPostgreSQL 19.0, built from source (the PGDG repositories on this RHEL 8 server did not list PostgreSQL 19 packages yet)
Data (synthetic)pgbench scale 200: 20 M accounts. Plus an orders table partitioned by day with 5 M rows and an identity key, like a real orders or events table.
Applicationpgbench, 16 clients, connecting as an app role: 90% TPC-B-like transactions, 10% inserts into orders. It writes the whole time, and reconnects every 0.2 s if its connection is cut.

Step 1: build green and copy the schema

Logical replication copies data, not schema, so the schema goes over first. Use the new version's pg_dump against the old server. Roles are global objects and are not in a database dump, so create them on green first. I create the application role with NOLOGIN on green, so nothing can write to it by mistake before the cutover.

psql -p 5429 -d appdb -c "CREATE ROLE app NOLOGIN;"
/usr/pgsql-19/bin/pg_dump -p 5428 -d appdb --schema-only \
    --no-publications --no-subscriptions > schema.sql
psql -p 5429 -d appdb -f schema.sql

Step 2: publish on blue, subscribe on green

-- on blue (PostgreSQL 18)
CREATE PUBLICATION bg_pub FOR ALL TABLES
  WITH (publish_via_partition_root = true);

-- on green (PostgreSQL 19)
CREATE SUBSCRIPTION bg_sub
  CONNECTION 'host=... port=5428 dbname=appdb user=...'
  PUBLICATION bg_pub;

-- wait until every table has finished its initial copy (state 'r' = ready)
SELECT count(*) FROM pg_subscription_rel WHERE srsubstate <> 'r';

publish_via_partition_root = true makes changes to the daily partitions of orders arrive as changes to the parent table. Without it, every partition is published separately and the partition layout on green must match blue exactly. With it, green can even be partitioned differently.

Step 3: the initial copy, under load

The subscription copied all tables in 48 seconds while the 16 clients kept writing. The copy is not free: blue's throughput dropped by about a third while it ran, then recovered.

Transactions per second during the PostgreSQL 18 to 19 blue/green upgrade, with cutover zoom

Phase (blue, PostgreSQL 18.1)Average tps
Before replication (30 s)15,414
During the initial copy (48 s)10,156 (−34%)
Catch-up (next 60 s)14,639
Steady replication (2 min)14,362 (−7%)

In production, start the initial copy in a quiet period. The roughly 7% lower throughput during steady replication is the price of decoding and sending WAL; my baseline was short (30 s), so treat it as an indication, not a precise number.

Step 4: catch-up and steady replication

While the tables were being copied, blue kept writing. Those changes queue up in the replication slot and green applies them after the copy. Lag peaked at 297 MB (6.4 s) just after the copy finished and was gone about a minute later. From then until the cutover, green was on average 0.7 MB and never more than 0.36 s behind.

Replication lag from PostgreSQL 18 to 19 under live load


-- on blue: how far behind is the subscriber? (bytes and time)
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), s.confirmed_flush_lsn) AS lag_bytes,
       r.write_lag, r.replay_lag
  FROM pg_replication_slots s
  LEFT JOIN pg_stat_replication r ON r.application_name = s.slot_name
 WHERE s.slot_name = 'bg_sub';

Step 5: the cutover, timed

This is the only part the application notices. The script does six things in a fixed order and logs a timestamp for each:

-- 1. freeze writes on blue: no new logins for the app, end its sessions
ALTER ROLE app NOLOGIN;
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'app';
SELECT pg_current_wal_lsn();                       -- remember this LSN

-- 2. wait until green has confirmed everything up to that LSN
SELECT confirmed_flush_lsn >= '<lsn from step 1>'::pg_lsn
  FROM pg_replication_slots WHERE slot_name = 'bg_sub';   -- repeat until true

-- 3. copy sequence positions (generated on blue, run on green)
SELECT format('SELECT setval(%L, %s, true);',
              quote_ident(schemaname) || '.' || quote_ident(sequencename), last_value)
  FROM pg_sequences WHERE last_value IS NOT NULL;

-- 4. validate: the same counts and sums on both sides (both are frozen now)
-- 5. on green: ALTER SUBSCRIPTION bg_sub DISABLE;
-- 6. on green: ALTER ROLE app LOGIN;  then point the application at green
Cutover stepMeasured
1. Freeze writes on blue (16 sessions ended)0.15 s
2. Wait until green has everything0.37 s
3. Copy 2 sequence positions0.02 s
4. Validate counts and sums, 5 tables, 28.6 M rows (MATCH)1.69 s
5–6. Disable the subscription, open green0.04 s
Total, freeze to switch2.27 s

The validation compared count(*) and the sum of a value column on every table, run on both sides at once:

orders           | 5,355,653 | 2680613474
pgbench_accounts |20,000,000 |   12153963
pgbench_branches |       200 |   12153963
pgbench_history  | 3,200,180 |   12153963
pgbench_tellers  |     2,000 |   12153963      -- identical on blue and green
The trade-off worth discussing with your team: validation was 1.69 of the 2.27 seconds. Without it, the freeze-to-switch window is about 0.6 s. On a bigger database a full count-and-sum takes longer, so many teams validate a sample (recent rows, key tables) inside the window and run the full comparison right after the switch, against the frozen blue.

What the application saw

The zoom in the throughput chart shows it second by second. Blue was committing until the freeze at 10:51:06.94; green was serving about 14,000 tps in the second that started at 10:51:09.38. So the application went about 2.4 seconds without writes: the 2.27 s cutover plus a fraction of a second to reconnect 16 clients. (pgbench reports once per second, so the gap between its last and first full reports is 4.0 s; the real window is the shorter one.)

  • 0 committed transactions lost: pgbench reported 0 failed transactions, and the validation matched every row.
  • 16 in-flight transactions were rolled back, one per client, when their sessions were ended. That is expected: your application needs retry logic for this, the same as for any failover.
  • Green then ran at about 15,800 tps. That is not a fair speed comparison with blue (freshly loaded tables, different run lengths), so I am not claiming PostgreSQL 19 is faster here.

The checklist: traps and how to handle them

TrapWhat happensWhat to do
SequencesLogical replication copies rows, not sequence positions. Green's sequences start at 1, and the first insert after the switch fails with a duplicate key.Copy every sequence's last_value with setval() during the cutover (step 3). In my run: orders_id_seq 5,355,653 and pgbench_history_hid_seq 3,200,181.
Tables without a primary keyOnce in a publication, UPDATE/DELETE on them fail on blue, because there is no replica identity.Add a primary key, or set REPLICA IDENTITY FULL (slow for big tables). pgbench's history table has no key; I gave it an identity column.
Partitioned tablesEach partition is published separately by default.publish_via_partition_root = true, as above.
DDLSchema changes are not replicated.Freeze schema changes from the schema copy until the cutover.
Roles and grantsRoles are global and not in the database dump.Create them on green first (pg_dumpall --roles-only), and keep the app role NOLOGIN there until the switch.
Optimizer statisticsFreshly copied tables have no statistics until autovacuum gets to them.Run ANALYZE on green before the cutover. (In this short test I relied on autovacuum.)
Large objectsNot replicated by logical replication.Check pg_largeobject; copy them separately if you use them.
In-flight transactionsRolled back when their sessions end at the freeze.Application retry logic; do the cutover in a quiet period.

Rollback

Until green takes its first write, rollback is trivial: blue is frozen and complete, so re-enable the app role on blue and point the application back. After green has taken writes, going back means bringing those writes to blue too. The clean way is to prepare it before opening green: a publication on green and a subscription on blue with copy_data = false, so blue keeps following green after the switch. I did not test that reverse path in this run; it is the next thing to add if you need a rollback window of hours rather than minutes.

What this test does and does not show

  • It shows the method works end to end on PostgreSQL 18.1 → 19.0 under continuous writes, with measured timings and validated data.
  • Both clusters were on one server, so the copy competed with the workload for the same CPUs and disks. On separate servers the copy is usually faster and the impact on blue smaller, but network speed then matters.
  • The data and workload are synthetic, and this was one run. Your numbers will depend on data size, write rate and hardware; the scripts below let you measure them.

The scripts

The kit creates its own two test clusters on separate ports (it never touches an existing instance), loads the data, runs the workload, sets up replication, monitors lag, performs the cutover and writes a summary. Run it as the postgres OS user; the test clusters accept local connections only, so no passwords are needed. run_all.sh runs everything in about 15 minutes.

00_env.sh: settings
#!/bin/bash
# 00_env.sh : settings shared by all scripts (edit here if your paths differ)
export BIN_OLD=${BIN_OLD:-/usr/pgsql-18/bin}         # blue  = current major version
export BIN_NEW=${BIN_NEW:-/usr/pgsql-19/bin}         # green = new major version
export BASE=${BASE:-/var/pgtest/bluegreen}        # both test clusters live here (needs ~15 GB free)
export PORT_OLD=5428
export PORT_NEW=5429
export DB=appdb
export SCALE=${SCALE:-200}                # pgbench scale: 200 = 20 million accounts (~3 GB)
export ORDERS=${ORDERS:-5000000}          # rows preloaded into the partitioned orders table
export CLIENTS=${CLIENTS:-16}
export LOAD_SECONDS=${LOAD_SECONDS:-3600} # upper limit; run_all.sh stops the load itself
export STEADY_SECONDS=${STEADY_SECONDS:-180}  # steady replication under load before cutover
export AFTER_SECONDS=${AFTER_SECONDS:-120}    # keep load running on green after cutover
export SHARED_BUFFERS=${SHARED_BUFFERS:-8GB}
export RESULTS=$BASE/results

psql_old() { "$BIN_NEW/psql" -X -q -h 127.0.0.1 -p "$PORT_OLD" -U postgres -v ON_ERROR_STOP=1 "$@"; }
psql_new() { "$BIN_NEW/psql" -X -q -h 127.0.0.1 -p "$PORT_NEW" -U postgres -v ON_ERROR_STOP=1 "$@"; }
ts()  { date +%H:%M:%S.%3N; }
now() { date +%s.%N; }
01_create_clusters.sh: two clusters, identical settings
#!/bin/bash
# 01_create_clusters.sh : create blue (PG old) and green (PG new) test clusters on separate ports
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
mkdir -p "$BASE" "$RESULTS"
for side in old new; do
  if [ "$side" = old ]; then BIN=$BIN_OLD; PORT=$PORT_OLD; else BIN=$BIN_NEW; PORT=$PORT_NEW; fi
  D=$BASE/$side
  if [ -d "$D" ]; then echo "ERROR: $D already exists - run ./99_cleanup.sh first"; exit 1; fi
  "$BIN/initdb" -D "$D" -E UTF8 --no-locale -U postgres --auth=trust >/dev/null
  cat >> "$D/postgresql.conf" <<CONF
# ---- blue/green test settings (identical on both sides) ----
port = $PORT
listen_addresses = '127.0.0.1'
unix_socket_directories = '$BASE'
max_connections = 200
shared_buffers = $SHARED_BUFFERS
effective_cache_size = 24GB
maintenance_work_mem = 1GB
wal_level = logical
max_wal_size = 16GB
checkpoint_timeout = 15min
max_wal_senders = 10
max_replication_slots = 10
max_logical_replication_workers = 8
max_sync_workers_per_subscription = 4
CONF
  "$BIN/pg_ctl" -D "$D" -l "$BASE/$side.log" -w start >/dev/null
done
psql_old -d postgres -c "CREATE DATABASE $DB;"
psql_new -d postgres -c "CREATE DATABASE $DB;"
echo "Blue : $(psql_old -d postgres -Atc 'select version()')"
echo "Green: $(psql_new -d postgres -Atc 'select version()')"
psql_old -d postgres -Atc "select version()" >  "$RESULTS/versions.txt"
psql_new -d postgres -Atc "select version()" >> "$RESULTS/versions.txt"
echo "OK: clusters running on ports $PORT_OLD (blue) and $PORT_NEW (green)"
02_load_blue.sh: synthetic data on blue
#!/bin/bash
# 02_load_blue.sh : build the "production" database on blue (synthetic data only)
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
t0=$(now)
"$BIN_OLD/pgbench" -i -s "$SCALE" -q -h 127.0.0.1 -p "$PORT_OLD" -U postgres "$DB"
psql_old -d "$DB" <<SQL
-- application role (no password: test cluster uses local trust auth)
CREATE ROLE app LOGIN;
-- pgbench_history has no primary key: give it one (identity = a sequence to carry over)
ALTER TABLE pgbench_history ADD COLUMN hid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY;
-- a daily-partitioned table with an identity key, like a real orders/events table
CREATE TABLE orders (
  id         bigint GENERATED ALWAYS AS IDENTITY,
  account_id int         NOT NULL,
  amount     int         NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
DO \$\$
DECLARE d date;
BEGIN
  FOR d IN SELECT generate_series(current_date - 3, current_date + 3, interval '1 day')::date LOOP
    EXECUTE format('CREATE TABLE orders_%s PARTITION OF orders FOR VALUES FROM (%L) TO (%L)',
                   to_char(d, 'YYYYMMDD'), d, d + 1);
  END LOOP;
END \$\$;
INSERT INTO orders (account_id, amount, created_at)
SELECT 1 + (random() * (100000 * $SCALE - 1))::int, 1 + (random() * 999)::int,
       now() - random() * interval '3 days'
  FROM generate_series(1, $ORDERS);
GRANT USAGE ON SCHEMA public TO app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app;
VACUUM ANALYZE;
SQL
psql_old -d "$DB" -c "SELECT relname, n_live_tup, pg_size_pretty(pg_total_relation_size(relid)) AS size
                        FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 12;"
printf 'load_seconds=%.0f\n' "$(echo "$(now) - $t0" | bc)" | tee "$RESULTS/load.txt"
orders.sql: pgbench script for the inserts
\set aid random(1, 100000 * :scale)
\set amt random(1, 1000)
INSERT INTO orders (account_id, amount) VALUES (:aid, :amt);
03_start_load.sh: the application (reconnects to whichever side is live)
#!/bin/bash
# 03_start_load.sh : the "application" - pgbench writing to whichever port is in target_port.
# When its connections are cut at cutover it reconnects every 0.2 s, so the gap in its
# per-second progress log is the downtime the application really saw.
set -uo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
echo "$PORT_OLD" > "$BASE/target_port"
end=$((SECONDS + LOAD_SECONDS))
while [ $SECONDS -lt $end ]; do
  port=$(cat "$BASE/target_port")
  "$BIN_NEW/pgbench" -h 127.0.0.1 -p "$port" -U app -c "$CLIENTS" -j 8 -T $((end - SECONDS)) \
      -P 1 --progress-timestamp -b tpcb-like@9 -f orders.sql@1 "$DB" \
      >> "$RESULTS/pgbench_$port.log" 2>&1
  sleep 0.2
done
echo "load finished" >> "$RESULTS/pgbench_$PORT_OLD.log"
04_setup_green.sh: schema, publication, subscription, initial copy
#!/bin/bash
# 04_setup_green.sh : schema to green, publication on blue, subscription on green,
# then wait for the initial copy (done while the live load is running)
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
log() { echo "$(ts) $*" | tee -a "$RESULTS/setup.log"; }
log "create app role on green (NOLOGIN until cutover, so nobody writes to green early)"
psql_new -d "$DB" -c "CREATE ROLE app NOLOGIN;"
log "copy schema blue -> green (pg_dump $("$BIN_NEW/pg_dump" --version | awk '{print $3}') --schema-only)"
"$BIN_NEW/pg_dump" -h 127.0.0.1 -p "$PORT_OLD" -U postgres -d "$DB" --schema-only \
    --no-publications --no-subscriptions > "$RESULTS/schema.sql"
psql_new -d "$DB" -f "$RESULTS/schema.sql" > /dev/null
log "publication on blue (publish_via_partition_root: partitions replicate as the parent table)"
psql_old -d "$DB" -c "CREATE PUBLICATION bg_pub FOR ALL TABLES WITH (publish_via_partition_root = true);"
t0=$(now)
log "subscription on green (initial copy starts)"
psql_new -d "$DB" -c "CREATE SUBSCRIPTION bg_sub
   CONNECTION 'host=127.0.0.1 port=$PORT_OLD dbname=$DB user=postgres'
   PUBLICATION bg_pub;"
while true; do
  pending=$(psql_new -d "$DB" -Atc "SELECT count(*) FROM pg_subscription_rel WHERE srsubstate <> 'r'")
  [ "$pending" = "0" ] && break
  sleep 2
done
secs=$(echo "$(now) - $t0" | bc)
log "initial copy finished: all tables in state 'r' (ready)"
printf 'initial_sync_seconds=%.1f\n' "$secs" | tee "$RESULTS/initial_sync.txt"
05_monitor_lag.sh: lag every second
#!/bin/bash
# 05_monitor_lag.sh : every second, replication lag of the subscription (bytes and time)
set -uo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
out=$RESULTS/lag.csv
echo "time,lag_bytes,write_lag,replay_lag" > "$out"
while [ ! -f "$BASE/stop_monitor" ]; do
  psql_old -d "$DB" -Atc "
    SELECT to_char(clock_timestamp(),'HH24:MI:SS'),
           pg_wal_lsn_diff(pg_current_wal_lsn(), s.confirmed_flush_lsn),
           coalesce(extract(epoch from r.write_lag)::numeric(10,3), 0),
           coalesce(extract(epoch from r.replay_lag)::numeric(10,3), 0)
      FROM pg_replication_slots s
      LEFT JOIN pg_stat_replication r ON r.application_name = s.slot_name
     WHERE s.slot_name = 'bg_sub'" 2>/dev/null | tr '|' ',' >> "$out"
  sleep 1
done
06_cutover.sh: the timed cutover
#!/bin/bash
# 06_cutover.sh : the switch. Every step is timestamped in results/cutover.log
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
L=$RESULTS/cutover.log
log() { echo "$(ts) $*" | tee -a "$L"; }
T0=$(now)
log "STEP 1 freeze writes on blue: app role NOLOGIN + end its sessions"
psql_old -d "$DB" -Atc "ALTER ROLE app NOLOGIN;
  SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename = 'app';" | tee -a "$L"
lsn=$(psql_old -d "$DB" -Atc "SELECT pg_current_wal_lsn()")
log "STEP 2 wait until green has confirmed everything up to blue LSN $lsn"
until [ "$(psql_old -d "$DB" -Atc "SELECT confirmed_flush_lsn >= '$lsn'::pg_lsn FROM pg_replication_slots WHERE slot_name = 'bg_sub'")" = "t" ]; do
  sleep 0.05
done
T2=$(now); log "       caught up"
log "STEP 3 copy sequence positions blue -> green (logical replication does not carry them)"
psql_old -d "$DB" -Atc "SELECT format('SELECT setval(%L, %s, true);',
                         quote_ident(schemaname) || '.' || quote_ident(sequencename), last_value)
                    FROM pg_sequences WHERE last_value IS NOT NULL" > "$RESULTS/seq_sync.sql"
psql_new -d "$DB" -f "$RESULTS/seq_sync.sql" > /dev/null
cat "$RESULTS/seq_sync.sql" | tee -a "$L"
T3=$(now)
log "STEP 4 validation while both sides are frozen (row counts and sums must match)"
Q="SELECT * FROM (
             SELECT 'pgbench_accounts' t, count(*), sum(abalance) FROM pgbench_accounts
   UNION ALL SELECT 'pgbench_branches', count(*), sum(bbalance) FROM pgbench_branches
   UNION ALL SELECT 'pgbench_tellers',  count(*), sum(tbalance) FROM pgbench_tellers
   UNION ALL SELECT 'pgbench_history',  count(*), sum(delta)    FROM pgbench_history
   UNION ALL SELECT 'orders',           count(*), sum(amount)   FROM orders) x ORDER BY 1"
psql_old -d "$DB" -Atc "$Q" > "$RESULTS/check_blue.txt" &
psql_new -d "$DB" -Atc "$Q" > "$RESULTS/check_green.txt" &
wait
if diff "$RESULTS/check_blue.txt" "$RESULTS/check_green.txt" > /dev/null; then
  log "       MATCH:"; sed 's/^/         /' "$RESULTS/check_green.txt" | tee -a "$L"
else
  log "       MISMATCH - NOT switching. blue vs green:"; diff "$RESULTS/check_blue.txt" "$RESULTS/check_green.txt" | tee -a "$L"
  exit 1
fi
T4=$(now)
log "STEP 5 detach green from blue (subscription disabled, kept for reference)"
psql_new -d "$DB" -c "ALTER SUBSCRIPTION bg_sub DISABLE;"
log "STEP 6 open green and point the application at it"
psql_new -d "$DB" -c "ALTER ROLE app LOGIN;"
echo "$PORT_NEW" > "$BASE/target_port"
T6=$(now)
log "SWITCHED"
{
  printf 'freeze_to_caught_up_s=%.3f\n' "$(echo "$T2 - $T0" | bc)"
  printf 'sequence_sync_s=%.3f\n'       "$(echo "$T3 - $T2" | bc)"
  printf 'validation_s=%.3f\n'          "$(echo "$T4 - $T3" | bc)"
  printf 'total_cutover_script_s=%.3f\n' "$(echo "$T6 - $T0" | bc)"
} | tee "$RESULTS/cutover_timing.txt"
07_summary.sh: results
#!/bin/bash
# 07_summary.sh : what the application saw (from pgbench progress) + all measurements
set -uo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
B=$RESULTS/pgbench_$PORT_OLD.log; G=$RESULTS/pgbench_$PORT_NEW.log
last_blue=$(grep '^progress:' "$B" | awk '$4 > 0 {t=$2} END {print t}')
first_green=$(grep '^progress:' "$G" 2>/dev/null | awk '$4 > 0 {print $2; exit}')
{
echo "===== versions ====="; cat "$RESULTS/versions.txt"
echo "===== data load ====="; cat "$RESULTS/load.txt"
echo "===== initial copy (under live load) ====="; cat "$RESULTS/initial_sync.txt"
echo "===== replication lag during steady load (bytes) ====="
awk -F, 'NR>1 && $2 != "" {n++; s+=$2; if ($2>m) m=$2} END {printf "samples=%d avg_bytes=%.0f max_bytes=%.0f\n", n, s/n, m}' "$RESULTS/lag.csv"
echo "===== blue workload before cutover (tps, per-second samples) ====="
grep '^progress:' "$B" | awk '$4 > 0 {n++; s+=$4} END {printf "avg_tps=%.0f over %d s\n", s/n, n}'
echo "===== green workload after cutover ====="
grep '^progress:' "$G" 2>/dev/null | awk '$4 > 0 {n++; s+=$4} END {if (n) printf "avg_tps=%.0f over %d s\n", s/n, n}'
echo "===== cutover steps ====="; cat "$RESULTS/cutover_timing.txt"
echo "===== DOWNTIME SEEN BY THE APPLICATION ====="
echo "last blue progress with tps>0  : $last_blue"
echo "first green progress with tps>0: $first_green"
if [ -n "$last_blue" ] && [ -n "$first_green" ]; then
  printf 'write_gap_seconds=%.1f  (pgbench reports once per second, so +/- 1 s)\n' "$(echo "$first_green - $last_blue" | bc)"
fi
echo "===== errors seen by the application ====="
grep -hcE 'ERROR|FATAL|aborted' "$B" "$G" 2>/dev/null | paste -sd' ' | sed 's/^/blue green: /'
echo "===== green sequences vs data (last_value must be >= max id) ====="
psql_new -d "$DB" -Atc "SELECT 'history', (SELECT last_value FROM pgbench_history_hid_seq), (SELECT max(hid) FROM pgbench_history)
                        UNION ALL SELECT 'orders', (SELECT last_value FROM orders_id_seq), (SELECT max(id) FROM orders)"
} | tee "$RESULTS/summary.txt"
run_all.sh: everything in order
#!/bin/bash
# run_all.sh : the whole experiment, start to finish (about 35-40 minutes). Run inside screen.
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
./01_create_clusters.sh
./02_load_blue.sh
rm -f "$BASE/stop_monitor"
stop_bg() { touch "$BASE/stop_monitor"; pkill -f 03_start_load.sh 2>/dev/null; pkill -f "pgbench -h 127.0.0.1" 2>/dev/null; true; }
trap stop_bg EXIT
./03_start_load.sh & LOAD_PID=$!
sleep 30                                  # let the workload settle on blue
./05_monitor_lag.sh & MON_PID=$!
./04_setup_green.sh                       # initial copy while the application keeps writing
echo "$(ts) steady replication under load for $STEADY_SECONDS s ..."
sleep "$STEADY_SECONDS"
./06_cutover.sh
echo "$(ts) application now on green; running $AFTER_SECONDS s more ..."
sleep "$AFTER_SECONDS"
stop_bg
wait "$MON_PID" 2>/dev/null || true
./07_summary.sh
echo "Results are in $RESULTS - archive them, then run ./99_cleanup.sh"
99_cleanup.sh: remove the test clusters
#!/bin/bash
# 99_cleanup.sh : stop and delete both test clusters (keeps results/ unless you pass --all)
set -uo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
"$BIN_OLD/pg_ctl" -D "$BASE/old" -m fast stop 2>/dev/null
"$BIN_NEW/pg_ctl" -D "$BASE/new" -m fast stop 2>/dev/null
rm -rf "$BASE/old" "$BASE/new" "$BASE/target_port" "$BASE/stop_monitor" "$BASE"/*.log
[ "${1:-}" = "--all" ] && rm -rf "$BASE"
echo "cleanup done ($(du -sh "$BASE" 2>/dev/null | cut -f1) left in $BASE)"

Summary

With logical replication, a major PostgreSQL upgrade does not have to mean a maintenance window. In this test, PostgreSQL 19 received a full copy of the database in 48 seconds while the application kept writing, stayed less than half a second behind, and took over after a 2.27-second cutover that included validating every table. The application went about 2.4 seconds without writes and lost no committed transactions. The work is in the preparation: sequences, primary keys, partitioned tables, roles, statistics, and a tested rollback plan.

If you have partitioned your big tables (see my earlier post, Zero-Downtime Partitioning of a 2-Billion-Row PostgreSQL Table), publish_via_partition_root is the setting that keeps this upgrade simple.

Tested by me on a dedicated RHEL 8.10 test server (16 vCPUs, 62 GB RAM): PostgreSQL 18.1 and PostgreSQL 19.0. All data is synthetic, and this is one run; results will vary with hardware, data and workload. Test in a non-production environment.

Tamilselvan Perumal is an Oracle ACE Associate and Senior DBA with 12+ years in banking databases, working on database performance and benchmarking. Connect on LinkedIn.