A year after it went out, Instant database clones is still one of the biggest sources of traffic to boringSQL. The whole post rests on file_copy_method = clone, the PostgreSQL 18 setting that lets CREATE DATABASE ... STRATEGY = FILE_COPY reflink a 6 GB database in 212 milliseconds instead of copying it byte by byte. It also comes with a limitation, and most of the replies were about it:
ERROR: source database "myapp" is being accessed by other users
DETAIL: There is 1 other session using the database.
One idle pool connection is enough to trip it. That's fine for a template nobody touches, and it rules out the database you most likely want a copy of, the live one your application is connected to. So I went to see how hard the check would be to remove.
It made no sense to me at first: idle sessions don't write anything, and CountOtherDBBackends() runs before the strategy is even looked at, so WAL_LOG gets the same refusal. The change to test it is small. createdb() in dbcommands.c raises an error on any hit from that call, so I turned the ereport(ERROR) into a warning, ran make install, and cloned with sessions open.
Every clone succeeded with data intact, which proved less than it looked like. The guard only uses sessions as a proxy. What it's really there for is a write landing while the copy runs.
What a write during the copy breaks
Every row in PostgreSQL carries xmin and xmax transaction IDs. Whether a query can see a tuple depends on whether those transactions committed, and that status doesn't live inside the database's own directory. It lives cluster-wide in pg_xact:
$PGDATA/
base/16384 -- FILE_COPY copies this
pg_xact/ -- but not this. Shared by the whole cluster.
pg_wal/ -- or this.
Here is the failure. A session inserts a row and doesn't commit yet. The tuple sits on the heap page with xmin 4711, pg_xact says 4711 is in progress. FILE_COPY copies the page, tuple included. The clone doesn't show the row, so far so good. Then the source commits. pg_xact is the same file for both databases, so now the clone shows the row too. Nobody wrote it to the clone.
Files copy one by one
Even with reflinks, copydir still walks the directory and clones files one by one. There's no syscall that snapshots 400 files at once, so the heap can land on one side of a write and its index on the other, leaving index entries that point at heap tuples that aren't there. Crash recovery normally repairs that kind of skew from WAL, but a same-cluster clone has no redo point to start from: its heap and index files come from different instants on the same timeline, and nothing in WAL makes them agree again. Heap/index skew and torn pages stay in the clone. Checksums, on by default in PG18, catch a torn page on read; heap/index skew reads clean.
What FILE_COPY requires is zero writers. PostgreSQL has no cheap way to forbid writes to one database for 200 milliseconds, so it enforces zero connected sessions instead (prepared two-phase transactions are counted separately in the same errdetail, since those aren't sessions). DROP DATABASE gained WITH (FORCE) in PG13 to kick sessions out, while CREATE DATABASE still has no equivalent.
So the patched build isn't a fix. FILE_COPY makes a correct copy only of a database that isn't moving, and that's what I'll mean by a clone for the rest of this post. Two ways forward are left: make the source stand still on purpose, or copy something that carries its own pg_xact and WAL.
Cloning a source that stands still
For tests this part is easy. A template database nobody connects to passes the guard. If you need fast isolated test databases (or reproducible runs for coding agents), try this first, before any ZFS automation. Reflinks work on XFS, Btrfs, APFS and ZFS with block cloning. No root needed.
The scripts and SQL behind every setup in this post sit in pg-branch-recipes. The file-level recipes I ran on a 2 vCPU / 2 GB Hetzner VM with Ubuntu 24.04, ZFS 2.2.2, and packaged PostgreSQL 18.5, using a file-backed ZFS pool, loop-mounted XFS, and a streaming replica; the per-PR wrapper is newer and has only run in containers so far. Treat ratios as the signal rather than the absolute timings.
Every Postgres cluster ships with template1, and CREATE DATABASE myapp implicitly clones it. Point that same command at a template loaded with your schema and masked data, and flip one setting in postgresql.conf:
file_copy_method = cloneCREATE DATABASE app_template;
-- load schema and masked data, then freeze
\c app_template
VACUUM FREEZE ANALYZE;
\c postgres
ALTER DATABASE app_template IS_TEMPLATE true;
ALTER DATABASE app_template ALLOW_CONNECTIONS false;
ALLOW_CONNECTIONS false blocks new logins (FATAL: database "app_template" is not currently accepting connections), just like template0, while still letting CREATE DATABASE ... TEMPLATE app_template STRATEGY = FILE_COPY copy it. Existing sessions stay attached until you terminate them, so ALLOW_CONNECTIONS false only stops new ones from arriving.
On XFS, cloning a 200 MB template dropped from 0.716 s (+180 MB written) with the default WAL_LOG to 0.267 s (+5 MB) with FILE_COPY and file_copy_method = clone. In pytest, each test function gets a real, isolated database in a short pytest fixture (level1-template/fixture.py in pg-branch-recipes):
import psycopg, pytest
from uuid import uuid4
ADMIN_DSN = "postgresql://postgres@localhost/postgres"
@pytest.fixture(scope="function")
def db():
name = f"test_{uuid4().hex[:8]}"
with psycopg.connect(ADMIN_DSN, autocommit=True) as admin:
admin.execute(
f'CREATE DATABASE "{name}" TEMPLATE app_template STRATEGY=FILE_COPY'
)
try:
with psycopg.connect(f"postgresql://postgres@localhost/{name}") as conn:
yield conn
finally:
admin.execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')
try/finally plus WITH (FORCE) keeps a failing test or leaked connection from wedging cleanup and piling up leftover databases.
Watch out for ZFS 2.2.x on Ubuntu 24.04. OpenZFS turned block cloning off by default in 2.2.1, after corruption reports against 2.2.0, and 2.3.0 turned it back on. When /sys/module/zfs/parameters/zfs_bclone_enabled is 0, FILE_COPY falls back to copying bytes. On my test VM, flipping that flag moved a 1.7 GB template from 3.33 s (+468 MiB) to 0.56 s (0 extra space, confirmed via zpool get bclonesaved tank). compat/check-filesystem.sh /var/lib/postgresql/18/main prints what your host supports.
The nightly refresh (level1-template/refresh-template.sh) is where masking and freezing belong. Dump from production (pg_dump -Fd -j4), restore into a staging database, run your anonymization SQL, and run VACUUM FREEZE ANALYZE before swapping it in as app_template. Freezing sets tuple hint bits up front. Without it, the first reader in every test clone dirties pages just to set hint bits, breaking copy-on-write sharing across parallel tests. If nightly is too stale, make the template a logical replication subscriber and run ALTER SUBSCRIPTION tmpl_sub DISABLE; while cloning.
FILE_COPY starts each of its two copy passes with a cluster-wide checkpoint, both CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT, the first with CHECKPOINT_FLUSH_ALL. Every DROP DATABASE adds another. That's harmless on a CI instance and disruptive on a busy cluster with large shared_buffers.
Branching a source that keeps writing
None of this gets you what the patch was after in the first place, the live database, copied while the app keeps writing to it. A template refreshed overnight is up to a day old by the time a test touches it, which is fine for unit tests and not much use when you want to try a migration against the data it'll actually meet, or hand each pull request its own copy. If the source won't sit still, the copy has to bring its own pg_xact and pg_wal, and something has to sort out files grabbed at slightly different moments. Postgres already has that part, it's crash recovery. Snapshot the whole data directory, start a second Postgres on it, and the first boot does the rest. I'll call that a branch, mostly because that's what Neon and friends call it.
On the test VM, the first boot of a ZFS branch logged this:
LOG: database system was not properly shut down; automatic recovery in progress
LOG: redo starts at 0/9D000028
LOG: redo done at 0/9D000080
LOG: database system is ready to accept connections
As far as Postgres knows, the server just lost power. Transactions that were in flight have no commit record in the branch's pg_wal, so their pg_xact bits never get set, nobody in the new cluster is running those xids, and every reader treats them as aborted. So transaction 4711 from earlier stays invisible in the branch, whatever the source does later. The branch has its own pg_xact now.
Replay also fixes up heap and index files. That matters mostly for copies that aren't atomic, like a paused replica reflinked file by file, or a filesystem snapshot taken under load. With full_page_writes on (the default), the first change to a page after a checkpoint logs the whole page, so a page captured half-written just gets overwritten during replay. A ZFS snapshot doesn't need any of that to be consistent, it simply goes through the same startup.
Compared to a clone, you pay with a whole second Postgres process per branch instead of one 200 ms statement. In return the source never has to stop.
ZFS snapshots
ZFS snapshots a dataset's blocks atomically, and clones them instantaneously as writable copy-on-write branches:
zfs snapshot -r tank/pgdata@before-migration-42
zfs clone -o mountpoint=/tank/pgdata-branch tank/pgdata@before-migration-42 tank/pgdata-branch
rm -f /tank/pgdata-branch/postmaster.pid
sudo -u postgres /usr/lib/postgresql/18/bin/pg_ctl start \
-D /tank/pgdata-branch -o "-p 5433 -c archive_mode=off" -w
On a 1.94 GB cluster, a fresh branch took 414 KiB of pool space. Deleting two million rows on the branch grew it to 892 MB.
zfs snapshot -r is atomic across child datasets, but zfs clone takes one dataset only, there's no -r. Simplest is to keep pg_wal inside $PGDATA on the same dataset. Tablespaces are worse. pg_tblspc/ holds symlinks with absolute paths, so a branch follows them straight into the source's live tablespace and writes there. The recipe assumes no tablespaces. If you have them, each one needs its own clone from the same -r snapshot, and the symlinks rewritten to point at those clones before the branch starts.
You don't need a spare block device or dedicated storage box to run this in CI. A sparse file (truncate -s 20G /zfs.img and zpool create -f tank /zfs.img with recordsize=8K) works on a plain Linux VM or a GitHub-hosted ubuntu-latest runner, whose HWE kernel ships the ZFS 2.3 module while userland stays on 2.2 (level2-zfs/setup-pool.sh and level2-zfs/ci-branch.yaml).
Postgres in Docker on ZFS
If you run Postgres in containers rather than from /usr/lib/postgresql, keep ZFS on the host and mount each cloned dataset into a container (IMAGE=postgres:18 ./level2-zfs/branch-create.sh automates this with a port you pass in; the per-PR wrapper below asks Docker for a free one):
zfs clone tank/pgdata@nightly tank/pgdata-pr-42
rm -f /tank/pgdata-pr-42/postmaster.pid
docker run -d --name pgdata-pr-42 -p 127.0.0.1:5433:5432 \
-e PGDATA=/pgdata -v /tank/pgdata-pr-42:/pgdata \
postgres:18 -c archive_mode=off -c listen_addresses='*'
# wait until `docker exec pgdata-pr-42 pg_isready -q -h 127.0.0.1` succeeds, then:
docker exec -i -u postgres pgdata-pr-42 psql -v ON_ERROR_STOP=1 < level2-zfs/sanitize.sql
Pass -e PGDATA=/pgdata explicitly because the postgres:18 image moved its default data path from /var/lib/postgresql/data to /var/lib/postgresql/18/docker. Seed the baseline with the same Docker image too: Debian- and Ubuntu-packaged clusters store postgresql.conf and pg_hba.conf in /etc/postgresql outside $PGDATA, so a snapshot of /var/lib/postgresql/18/main will not boot inside a container.
Bind the published port to 127.0.0.1 until sanitize.sql finishes, since Docker's port publishing bypasses ufw and a fresh branch still carries production's pg_hba.conf. -c listen_addresses='*' overrides whatever the source's config says. A cluster initialized by the official image already listens on *, but one from a plain initdb defaults to localhost, so the published port forwards to nothing, and a production config naming the host's own IP can't bind inside the container at all, so the branch never starts.
Paused replica plus reflink (XFS / APFS)
Without ZFS, you can pause replay on a streaming replica, reflink its data directory file by file, and promote the copy onto its own timeline (level2-reflink-replica/):
# PG19+ can optionally wait until replay reaches a primary LSN
# (untested here; my VM ran PG 18.5, syntax from PG 19 docs):
# psql -h replica -c "WAIT FOR LSN '$PRIMARY_LSN' WITH (TIMEOUT '60s');"
psql -h replica -c "SELECT pg_wal_replay_pause();"
until [ "$(psql -h replica -Atc 'SELECT pg_get_wal_replay_pause_state()')" = paused ]; do
sleep 0.2
done
psql -h replica -c "CHECKPOINT;"
cp -a --reflink=always /mnt/xfs/replica /mnt/xfs/branch # macOS/APFS: cp -ac
psql -h replica -c "SELECT pg_wal_replay_resume();"
rm -f /mnt/xfs/branch/postmaster.pid
sudo -u postgres sed -i 's/^primary_conninfo/#primary_conninfo/' \
/mnt/xfs/branch/postgresql.auto.conf
sudo -u postgres pg_ctl start -D /mnt/xfs/branch -o "-p 5436 -c archive_mode=off" -w
sudo -u postgres pg_ctl promote -D /mnt/xfs/branch -w
pg_wal_replay_pause() halts replay, not the walreceiver, and restartpoints can still flush buffers, so the copy isn't atomic. Crash recovery and full_page_writes are what make it safe. Use cp -a (not -r, which drops postgres ownership), --reflink=always (not auto, which copies bytes without saying so), and pg_ctl promote instead of deleting standby.signal. Keeping standby.signal and promoting switches the branch onto a new timeline (00000002... instead of 00000001...), preventing WAL filename collisions with the primary. Because pg_wal/ already holds segments streamed while paused, if you need the branch to stop at an exact LSN, set recovery_target_lsn, recovery_target_action = 'promote', and recovery_target_timeline = 'current' before starting.
Copying a 1,025 MB data directory this way cost 1 MB of extra disk.
A branch per pull request
Each recipe above makes one branch by hand, with someone watching. A branch per pull request runs the same steps unattended, on runners that die halfway, for developers who shouldn't be reading production rows. In pg-branch-recipes that's level2-zfs/pr-lifecycle/ plus the shared helpers: 351 lines of bash, YAML, and SQL wrapped around a single zfs clone.
What a branch inherits from its source
Every branch starts from a copy of the source's configuration, and some of that configuration points back at production. archive_command is the one that bit me: my first ZFS branch started without -c archive_mode=off, and before I killed it the branch had archived two WAL segments into the source's archive. The names caused it. A branch begins on the same timeline as its source, so it numbers segments identically, and an archive_command like aws s3 cp %p s3://wal-archive/%f keys the destination on that name. Source and branch both offered up 00000001000000000000009D, second upload overwrote the first with no error on either side. In production that destroys point-in-time recovery across the window.
postmaster.pid is the other file-level trap. The branch inherits the source's pid, so Postgres refuses to start until you delete it.
For the rest, boot with -c archive_mode=off, and take away the outbound hooks before anything connects (level2-zfs/sanitize.sql):
ALTER SYSTEM SET archive_mode = off;
ALTER SYSTEM SET synchronous_standby_names = '';
-- a dotted name: no-op unless pg_cron is preloaded
ALTER SYSTEM RESET cron.database_name;
-- local slots are left over from the source's standby or consumer
SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots;
SELECT pg_reload_conf();
If the baseline is a logical subscriber, disable its subscriptions too: a subscription only advances production's slot while it is the one attached, and names differ per source, so that line stays out of the shared file (ALTER SUBSCRIPTION branch_sub DISABLE;).
pg_cron and a subscription's apply worker start with the server, before any of this runs, so a branch you don't trust yet is better booted with -c max_logical_replication_workers=0 and -c shared_preload_libraries='' and sanitized afterwards.
Crash recovery also truncates every UNLOGGED table, because its contents were never written to WAL. If production keeps caches, queues, or session state in unlogged tables, every branch comes up with those tables silently empty.
Masking every branch
sanitize.sql cuts the branch off from production's infrastructure, and it leaves production's data alone. A branch of the live cluster carries every email address and every payment token the source has. The template got masked once a night, in one place. A branch would need masking every time it's created, and masking on a copy-on-write branch works against the copy-on-write: an UPDATE over a whole users table writes a new version of every row, so the branch stops sharing those blocks and grows by the size of everything you masked.
The way out is to branch from a masked baseline instead, a replica or nightly snapshot you anonymize once and snapshot afterwards, which is what pgdata@nightly in the Docker example stands for. That baseline is only as fresh as its last masking run, so "a branch of production as of now" quietly turns back into "a branch of last night". Keeping a masked baseline close to live is a pipeline of its own (logical replication into a masking step, or zfs send -i of a masked replica to every runner), and none of it is in the repo.
Creating and destroying them
The create script is where the mess collects. Ports have to be handed out under a lock, and the lock alone isn't enough:
# the state file is the reservation: a port is taken from the moment
# it is written, not from the moment the branch starts listening
exec 9>"$STATE_DIR/port.lock"
flock 9
for p in $(seq 5433 5533); do
case " $(reserved_ports | tr '\n' ' ') " in
*" $p "*) continue ;;
esac
if port_free "$p"; then
PORT="$p"
break
fi
done
exec 9>&-
Two things broke in an earlier version. The cleanup trap called pg_ctl directly, as root, which pg_ctl refuses, and under set -e a failure inside an EXIT handler abandons the rest of it, so zfs destroy never ran and cleanup silently did nothing. And pg_ctl -w prints waiting for server to start.... done to stdout: the workflow captured the script's stdout as the connection string, so $GITHUB_OUTPUT got three lines of chatter along with it. Now stdout carries the port number and the rest goes to stderr.
The rest of the script guards against failures that are easy to predict once runners start dying:
- The state file is written before the clone, and the trap tears the branch down afterwards, so a failure can't leave a dataset the script no longer knows about. Without it, the next run dies on "dataset already exists", destroy finds no state and has nothing to do, and the PR stays stuck until someone runs
zfs destroyby hand. - Readiness is bounded at a minute, and the lock is released before the server starts, so one branch that never comes up fails on its own instead of stalling every other PR behind it.
pg_hba.confis first match wins, so a rule appended below an existingrejectdoes nothing. The script prepends it withsed -i "1i …".- A runner that dies never reaches its
if: always()step, sosweep-branches.shruns nightly, asksgh pr viewabout every state file, and destroys branches whose PR is closed or merged. Whenghitself fails, it skips that branch instead of guessing.
Two branches created concurrently got ports 5433 and 5434, and deleting two million rows on one left the other and the source alone (pr42=2000000 pr43=4000000 source=4000000).
What you're paying a vendor for
For CI on hardware I work with, I stop at the clone: frozen masked app_template, short pytest fixture, no root scripts, no container per test. The branch recipes are short. The previous section, plus a masking pipeline I haven't written, is what a vanilla-Postgres branching vendor sells, and the markup mostly pays for someone else keeping it working.
Postgres.ai's DbLab Engine wraps local ZFS or LVM snapshots in an API, a retention manager, and a UI. It's Apache-2.0 self-hosted, with a managed tier, and it can seed its pool from a logical dump of RDS or Cloud SQL. If you want branches on your own hardware and don't want to own the lifecycle scripts, it saves you writing them. Networked block platforms push the same idea across nodes.
ClickHouse's Managed Postgres is the networked version. Xatastor exports ZFS zvols over NVMe/TCP, so unmodified Postgres boots on thin copy-on-write volumes. For now the product still branches through PITR, with copy-on-write branching announced but not shipped.
Where Neon branches instead
Neon rebuilt the storage engine itself. Compute nodes are patched PostgreSQL whose pages arrive from a pageserver over GetPage@LSN, fed by Paxos-based safekeepers that make WAL durable across a quorum. Both pg_xact and pg_multixact live in that same versioned store alongside relation pages:
pub enum SlruKind { Clog, MultiXactMembers, MultiXactOffsets }
Only pg_xact (Clog) and pg_multixact sit in that versioned keyspace, not auxiliary SLRUs like pg_subtrans, and SLRU pages mostly skip GetPage@LSN: by default (lazy_slru_download = false) they ship inside the startup basebackup, and the lazy path fetches whole segments separately. Compute keeps an ephemeral local directory too, for basebackup contents, unlogged and temporary tables, and a cache in front of the pageserver.
Because pg_xact is versioned by LSN, Neon can branch at 14:32 last Tuesday, as long as that's inside the project's history retention window, by moving a timeline pointer, with no data copied. ZFS and reflinks only branch now, or at a snapshot you happened to take. Without access to the filesystem (RDS, Cloud SQL), a template clone keeps working but loses its reflink, and filesystem branching is gone. Managed PITR gives you a past point but pays for it by provisioning an instance and waiting, which is fine for debugging an incident and too slow for a test loop.
The DIY equivalent is plain PITR: restore a base backup from before the target, point restore_command at the WAL archive, and set a target (I reconstructed this from the PostgreSQL docs rather than running it on the Hetzner box):
# auto.conf, not postgresql.conf: if production ever ran ALTER SYSTEM,
# postgresql.auto.conf came along in the backup and wins
cat >> /var/lib/pg/branch/postgresql.auto.conf <<EOF
restore_command = 'aws s3 cp s3://wal-archive/%f %p'
recovery_target_lsn = '0/5A000028'
recovery_target_action = 'promote'
recovery_target_timeline = 'current'
archive_mode = off
EOF
touch /var/lib/pg/branch/recovery.signal # without it, recovery_target_* is ignored
Slow, because it replays WAL all the way from the base backup. But if you run PITR backups already, you have this.
None of these give you git merge for rows. Branches fork and don't merge; you replay schema migrations forward, and reconciling divergent data is still on you.