Moving live tenant databases to CloudNativePG with minutes of downtime
Florian Schauer, Senior Site Reliability Engineer
Until late September, every production tenant ran its own PostgreSQL: a single-replica StatefulSet on one Hetzner Cloud volume. Since 2 October, no production tenant does. Tenants now share one three-instance CloudNativePG cluster per environment. Each tenant gets its own databases, owned by its own roles, and a Job revokes CONNECT from PUBLIC on each of them and grants it back to the owning role, so one tenant’s role cannot connect to another tenant’s databases.
The old shape had run out of road. Hetzner allows 16 volumes per server, and every tenant database was one volume. Losing a node meant minutes of detaching and reattaching volumes, where, in a test on our development cluster, CloudNativePG promoted a standby 4 seconds after the primary went away. And the databases were mostly idle: more than nine in ten transactions wrote no rows at all. Measure that before you consolidate: it tells you whether one shared cluster can carry the load.
The hard part was moving live customers. A typical tenant moved on its own was down for about three minutes. Our largest tenant, 23 GB, was down for just under seven, where a dump and restore would, by our estimate, have stopped it for well over half an hour. Here is how, and what we would advise anyone doing the same.
The idea: copy while serving, stop only to switch
A dump and restore keeps the tenant down for the whole copy, so the downtime grows with the data. Logical replication moves almost all of that work out of the downtime. The old database publishes its tables, the new cluster subscribes, copies everything while the tenant keeps writing, and then applies every new change as it happens. Once it has caught up, we stop the application briefly, check that both sides match, and point it at the new database.
The core is two SQL statements, one on each side:
-- on the old database
CREATE PUBLICATION mig FOR ALL TABLES;
-- on the new cluster
CREATE SUBSCRIPTION mig
CONNECTION 'host=<old-database> dbname=files user=repl_mig password=…'
PUBLICATION mig;
Most of the work is in the gaps. Logical replication does not copy schema changes, sequences or large objects, and with a schema-only copy a materialized view arrives empty. A table with no primary key or other replica identity, once published, makes updates and deletes fail on the live source. Plan how to close each one before anything else.
The steps
Prepare the source. Our tenant databases were not set up to publish anything, and turning that on restarts Postgres: a short, separate outage of about a minute. Announce it as one. The same change caps how much WAL a stalled replication slot may hold back: without a cap, a stuck subscription fills the tenant’s disk and takes the tenant down; with one, only the migration fails. PostgreSQL enforces the cap at checkpoints, not continuously, so leave disk headroom above it and alert on every slot. The change also creates the tenant’s roles and databases on the new cluster ahead of time, and opens the network path from it to that one tenant’s database.
Before publishing, give every table without a primary key or other replica identity a setting that lets it replicate updates and deletes, or the tenant’s writes start failing the moment the publication exists. Let a preflight script refuse databases with large objects or materialized views rather than move half of one.
Copy, then index. Load the schema on the new cluster without the most expensive indexes, then subscribe. Maintaining them row by row during the copy is far slower than building them once afterwards, still while the tenant is live. Until the switch, backing out only means dropping the subscriptions, publications and slots; script it before you start.
Verify and switch. Now the downtime starts. A pull request scales the application to zero. A script then refuses to go on unless the application has no connections left to the old database, replication has caught up to the last byte, and every table matches on both sides. Only then does it copy sequence values across, end the replication and hand the schemas, tables, sequences, functions and types to the tenant’s roles. A second, pre-reviewed pull request points the application at the new cluster. Make each condition a hard stop that changes nothing, so a refusal only needs the scale-down reverted. The old volume stays as the way back, but going back loses whatever was written since the switch, so decide fast.
How we checked the copy
The check compares content, not just row counts. For every table, both sides compute a hash of the rows: every column is hashed in full except one bulky column type, which is hashed on a fixed sample of rows picked by primary key, so both sides sample the same rows. Row counts are always exact. Each row’s hash is added into a sum, so the result does not depend on row order and nothing has to be sorted. Both servers are told to print values the same way, so identical data produces identical bytes.
If a single table differs or a hash query fails, the cutover refuses: a check that did not run must never count as a match. We don’t distrust PostgreSQL’s replication; the check catches what our procedure could miss, like a table created after the schema was copied. It runs inside the downtime, so let its runtime decide how much you sample, never which tables you check.
What bit us
PostgreSQL’s replication limits are tiny by default. PostgreSQL caps how many replication workers run at once, and the default is four. One tenant has four databases, so its four subscriptions take every worker, and the workers that do the initial copy never start. Nothing errors. Our first rehearsal passed only because one copy grabbed a worker first. PostgreSQL 18 gives replication origins their own cap, defaulting to ten, which each subscription and each copy worker needs. Count the subscriptions you will run at once, add their copy workers, and raise both caps, plus the background worker pool they draw from, before the first one starts.
Before you restart a primary after a bulk move, let the archive catch up. A live move writes roughly the tenant’s size as WAL on the new cluster, faster than our backup sidecar can archive it. When CloudNativePG switches primaries, the old primary’s shutdown waits until every queued WAL file has been archived. Anything that restarts the primary with a full queue waits for it, and until the new primary is up, nothing on that cluster can write. We made archiving parallel and gave the sidecar real CPU, which took it from about 17 MB/s with parallelism alone to at least 50 MB/s. An alert watches the queue, and before any planned primary restart we check that it is empty.
A clean rebase can be the dangerous one. The switch pull request was reviewed before the downtime, then rebased onto main after the “scale to zero” change had merged. The first times that conflicted. Then it applied cleanly, which was the problem: git quietly kept the “zero replicas” line, so the switch would have moved the database and left the application stopped. Review caught it before merge. We now rebuild the switch commit from the reviewed file and diff it against main, instead of rebasing.
The batch
After single moves on 28 and 29 September, the rest moved together on 2 October. Three things are worth copying. Make the capacity changes first: they restart the primary, and after the copies that restart would wait for their WAL. Switch a small canary group before everyone else. And freeze application releases for the window: a schema change on the old side does not replicate. Every cutover passed its content check. The main group was down for about eleven minutes, seven of them after its switch merged, while ArgoCD rolled everything out and the applications started: in a batch, the rollout sets the downtime, not the database.
What we’d tell you before you start
- Rehearse from the shape you actually have. Our first rehearsal started from a tenant that already lived on CloudNativePG and missed both the role setup and the worker limit.
- Decide how each replication gap gets closed before the first publication.
- Do the worker arithmetic up front. Running short fails quietly, with only a warning in the new cluster’s log.
- Treat a live move’s WAL as a debt that comes due at the next primary restart.
- Let every gate refuse, including a check that did not run.
- Measure where the downtime goes. In one rehearsal the cutover itself took 10 seconds of a 4-minute outage. Most of the rest, reviewing a pull request and waiting for deployment, can move out of the window.
- Rebuild reviewed changes instead of rebasing them.
We build amaiko, an AI colleague for Microsoft Teams.