Branching
By the end of this page you will be able to fork a ScramDB database instantly, connect to the fork like any other database, and use that fork for testing, debugging, CI, and agent sandboxes.
Branching is ScramDB's "give me a working copy of the database right now" feature. It runs entirely in SQL, against a live, running server, and it is instant because it does not copy data: a branch is a copy-on-write fork that shares storage with its parent at the moment it is created.
The two forms
CLONE: fork the current state
CREATE DATABASE staging_test CLONE scramdb;
Instant, present-state, copy-on-write fork of scramdb into a new database called staging_test. It needs zero extra configuration, and works out of the box on a single node and on a cluster (see Branching on a cluster).
PostgreSQL-familiar spellings work identically, they are accepted synonyms rewritten to the same operation:
CREATE DATABASE staging_test2 TEMPLATE scramdb;
CREATE DATABASE staging_test3 TEMPLATE = scramdb; -- the = form is equivalent
FROM ... AT TIMESTAMP: fork a past state
CREATE DATABASE audit_before_incident FROM scramdb AT TIMESTAMP '2026-08-02T09:30:00Z';
Forks scramdb as it existed at the given timestamp, rather than as it exists right now. This requires [storage.wal.backup].destination to be configured and a base backup to already exist there, plus WAL history back to your target timestamp, either in the local WAL directory or the WAL archive. See Backups to set that up if you have not already; if the config key is missing, the statement fails loud naming it directly, it does not fail silently or produce an empty database.
The time is read the same way at every place that takes one: CREATE DATABASE ... AT TIMESTAMP, scram.branch_at, RESET DATABASE ... AT TIMESTAMP, REFRESH DATABASE ... AT TIMESTAMP and the at argument of scram.reset_branch and scram.refresh_branch. It is read as PostgreSQL reads a timestamptz literal, in these spellings:
- RFC 3339,
'2026-08-02T09:30:00Z', with a fraction for microsecond precision ('2026-08-02T09:30:00.123456Z') or an offset ('2026-08-02T11:30:00+02:00'); - a date and a time with a space or a
Tbetween them, the seconds and their fraction optional:'2026-08-02 09:30','2026-08-02 09:30:00.650340'; - a date alone, which is midnight:
'2026-08-02'; - after the seconds, a zone of
Z,+HH,+HH:MMor+HHMM, with-for a zone west of UTC:'2026-08-02 11:30:00+02'.
A time with no zone is UTC. A text that no timestamp reads ('not a time') is refused with 22007, and a text with the shape of a timestamp whose month, day, hour, minute or second does not exist ('2026-13-45T00:00:00Z', '2026-02-30'), or a time before 1970 ('1969-12-31 23:59:59'), with 22008, by every one of those places alike.
Making a branch, at a past time or of the present state, asks the same two things of the role, by the statement and by scram.branch_at alike: the CREATEDB attribute (a superuser has it) and ownership of the source database (a member of the owning role counts). A role without CREATEDB is refused with 42501, permission denied to create database, and a role that does not own the source with 42501, permission denied to copy database "name". A refused statement makes nothing.
There is also a function-call form, equivalent to the SQL syntax above:
SELECT scram.branch_at('scramdb', 'audit_before_incident', '2026-08-02T09:30:00Z');
A bare CREATE DATABASE child FROM parent; with no AT TIMESTAMP clause is not valid syntax, it is a hard parse error. FROM is only ever followed by AT TIMESTAMP '<literal>'.
What copy-on-write means here
At the moment of the fork, the child database shares its parent's underlying storage: nothing is physically copied, which is why the fork completes instantly regardless of how large the parent database is. From that point on, the two databases are fully independent. A write to the parent after the fork never appears in the child, and a write to the child never appears in the parent; each side only consumes new storage for the data it actually changes. You get an isolated, full-sized working copy at the storage cost of the changes you make to it, not the size of the whole database.
What a branch holds
A CLONE takes everything the parent database holds, in every schema:
- every table, with its rows, indexes, constraints, defaults, partitions, triggers and row-level policies;
- every view and materialized view, a materialized view with the rows it held;
- every sequence, at the parent's position: the branch's first value is the parent's next one, and a
serialcolumn draws from the branch's own sequence; - every function and procedure, user-defined type (enum, composite and domain), event trigger and schema, an empty schema included, with their owners;
- the grants on tables, views, sequences, schemas and routines, the default privileges, and the comments on tables, columns, indexes, views, materialized views, sequences, functions, types and schemas.
A clone builds no index, for a table kept on one node and for a table spread over several shard groups of a cluster alike. On a cluster each node pins its parts of the parent's indexes when it applies the clone's hold, which is before the position the cluster cuts at, so every node's branch reads the same rows. A branch reads its parent's indexes as they were at the cut and keeps its own changes beside them, so creating one costs time that does not grow with the size of the indexes, and a vector index is not loaded again. Every index kind answers the same way on the branch as on the parent, and row-level policies apply to a read through an index exactly as they do to a scan. When the branch has changed a large share of a table, or on VACUUM of the branch's table, its changes are folded into indexes of its own and it stops reading the parent's. The parent compacts as it always does while branches read it, VACUUM, VACUUM FULL and the background merge included, and a branch reads the same rows before, during and after. Until a branch folds, the parent keeps the storage the branch still reads, which scramdb_branch_hold_retained_bytes reports.
The rows are taken at one commit position. Every transaction acknowledged before the CLONE statement began is in the branch, with no CHECKPOINT needed first, and none that commits after it is. While the clone lists the parent's tables, CREATE TABLE, DROP TABLE, ALTER TABLE and renames on the same instance wait, so the branch never holds a table under two names, under none, or listed with no storage behind it; scramdb_branch_clone_gate_waits_total counts the statements that waited. A sequence is taken at the parent's value when the clone reaches it, the same as or later than the position of the rows, never earlier, so a value the parent handed out is not handed out again on the branch.
A CLONE is all or nothing. If a step fails, the statement answers an error that names it, and the new database, its tables and everything else it took are removed, so the same statement can be run again; scramdb_branch_clone_rollbacks_total counts the clones undone. A stop of the server in the middle of a CLONE leaves no half-made database: the next start removes what the clone had made, so the name is free again.
A CLONE takes each table's segments as they stand, the one the parent is still writing included, so the parent starts no new segment for it; a table that buffered more rows than one segment holds starts one, and scramdb_branch_clone_rotation_fallbacks_total counts it. A table of the branch has no file of its own until its first write: the clone writes one small record for the whole database, scramdb_branch_tables_inherited_total counts the tables made live that way and scramdb_branch_files_born_total the files first writes made.
A CLONE reserves the memory it needs from the execution budget before it starts. When other statements or clones hold it, the clone waits for its turn, for as long as its statement_timeout allows and never refused for memory (scramdb_branch_clone_admission_parked_total), and only when memory stays short past the wait is it refused with SQLSTATE 53200 and nothing left behind (scramdb_branch_clone_admission_refused_total). Run it again, or raise execution_memory_bytes in [storage].
A table the parent has set aside after a restart (see A table refuses every statement after a restart) does not fail the clone: the branch carries it as quarantined, it refuses every access in the branch the same way, scram_quarantined_tables lists it under the branch's name, and scramdb_quarantined_tables_cloned_total counts it. Dropping and recreating it in the branch, or in the parent, does not touch the other side.
A data file the branch shares with its parent is removed only when the last table that lists it lets go, so dropping, truncating or compacting the parent never takes a file a branch still reads.
After the fork the two databases share nothing that changes: a sequence advances on one side only, and a view, function, type, trigger, policy, grant or comment made, changed or dropped on one side never shows on the other. A function replaced on the parent while a transaction runs in the branch leaves that transaction's function unchanged.
CREATE FUNCTION branch_price(amount NUMERIC) RETURNS NUMERIC
RETURN amount * 2;
CREATE DATABASE price_branch CLONE scramdb;
CREATE OR REPLACE FUNCTION branch_price(amount NUMERIC) RETURNS NUMERIC
RETURN amount * 3;
SELECT branch_price(10) AS on_scramdb;
The last statement answers 30. A connection to price_branch calls branch_price(10) and still answers 20, and a DROP FUNCTION there leaves scramdb's function in place. A function is stored in the database that created it, so the same name can hold a different body in every database.
A branch at a past time (FROM ... AT TIMESTAMP) is rebuilt from the catalog and the tables of that time, and what it carries depends on where it is made. On a single node it carries, as they were at that time:
- every table, with its rows, columns, defaults, identity columns, indexes and constraints, in every schema;
- every view and materialized view;
- every sequence, at the position it had then;
- the comments on tables, columns, constraints, indexes, views, materialized views and sequences.
It carries none of the parent's functions, procedures, types, event triggers or grants: those are what a CLONE takes that a branch at a past time does not. On a cluster the branch carries the tables of that time with their rows, indexes and constraints, and not the parent's views or the sequences made apart from a table.
A table of that time with a column of an enum, composite or domain type is rebuilt with the type as the parent has it now, so a type renamed or moved to another schema, before or after the time, is found by its name now. A type dropped after the time, or a schema renamed after it, is not found, and the branch statement then fails.
A built-in type a superuser renamed or moved (ALTER TYPE uuid RENAME TO tag, ALTER TYPE tag SET SCHEMA s), once or several times, is found the same way, and each statement of the log is read by the type it named when it ran: after the built-in uuid is renamed, a user type may be given the name uuid, and a later ALTER TYPE uuid RENAME TO mood renames that user type, not the built-in one, in the branch as in the parent.
Branching on a cluster
Both forms work on a cluster, issued through any node, and the branch opens on every node.
A CLONE forks the parent at one commit position that every shard group of the parent shares: every commit at or below it is in the branch and none after it, so a transaction that wrote several groups is in the branch on all of them or on none. Each group keeps the row versions the fork needs until its replicas have forked the branch, and the metadata group decides the clone once. A CLONE needs a quorum of each shard group, never every member; a node that was down takes the fork from the group's log when it returns. A clone that cannot give every shard group its fork is dropped again on every node, and the statement says why.
A table renamed, swapped with another or made again while a clone runs, or after it, changes nothing the branch holds. The clone forks each table by its identity and not by the name the statement read: a rename between the statement's read of the parent's tables and its cut does not refuse it, a table is forked once, and a row that reaches a shard group after the fork goes to the branch's table of the same identity, not to the table that took its name since. If a fork cannot finish on a node, repair what stops it or drop the branch.
A branch at a past time (FROM ... AT TIMESTAMP or scram.branch_at) reads the cluster's WAL archive instead of a base backup: turn on [storage.wal.archive] on every node, pointed at one shared destination, as a cluster restore needs. The time resolves to one commit position every group shares, exactly as a cluster restore's --target-time does; the parent's tables as they were then become the branch's; and each shard group's archived history up to that position is replayed into the branch's own groups, so every replica holds the branch's rows. A table that lives on one node only is brought to that time from that node's own base backup and WAL, as on a single node.
The functions, types, triggers and the other catalog objects a branch carries are forked on every node the same way, and a CREATE, REPLACE or DROP on one database is applied on every node to that database only. The scramdb_cluster_branch_* metrics on Observability count the branches made, the tables forked and the rows read from the archive.
Connecting to a branch
A branch is a real, independently-connectable database, reachable by name over the normal PostgreSQL wire protocol, exactly like any other database on the instance. It is not a special mode of the parent's connection, and it does not require a restart, tables created by the branch are visible immediately.
psql "host=127.0.0.1 port=5432 user=scramdb dbname=staging_test"
Any PostgreSQL-compatible driver works the same way, point its dbname (or equivalent connection parameter) at the branch's name.
Cleaning up a branch
DROP DATABASE staging_test;
This works even if the branch has tables and data in it, DROP DATABASE tears down every table in the branch first, releasing storage the branch changed while leaving data still shared with the parent untouched. DROP DATABASE IF EXISTS staging_test; is also available if you are not sure the branch still exists. The drop also takes the branch's views, sequences, comments and grants, so a database made later under the same name starts empty, and it removes a branch a failed clone or a crash left half made, with or without IF EXISTS.
The files a dropped database or table no longer needs are removed in the same step and leave the disk ledger's books with them, which scram_disk shows (see Observability). A file a clone still reads stays until the last table that lists it lets go.
The default database of an instance can never be dropped; ScramDB refuses that outright.
A branch can also expire on its own. Give it an expiry when you make it, or later, and the server drops it once the time passes:
CREATE ROLE ci; -- the role the branches below belong to
CREATE DATABASE staging_test CLONE scramdb WITH (owner = ci, expire_after = '1 day');
ALTER DATABASE staging_test SET (expire_after = '2 hours'); -- or NULL to keep it
SELECT * FROM scram.branch('scramdb', 'staging_ci', owner => 'ci', expire_after => '1 day');
SELECT * FROM scram.expire_branch('staging_ci', '2 hours');
SELECT * FROM scram.drop_branch('staging_ci', force => true); -- ends its sessions first, as DROP DATABASE ... WITH (FORCE)
SELECT * FROM scram_branches; -- the branches you own or may connect to, with their expiry
scram_branches also shows each branch's bytes_owned (written by the branch itself) and bytes_shared (still read from its parent), counted in whole pages and not counting rows still in a write buffer, and last_merge_at and last_refresh_at (commit positions, NULL when none is recorded on this node).
Setting or clearing an expiry (ALTER DATABASE ... SET (expire_after = ...) or scram.expire_branch) is the branch owner's: any other role is refused with 42501, must be owner of database name. scram.branch_info('name') needs CONNECT on the branch (42501, permission denied for database name), and scram.branches() lists the branches of the open database that you own or may connect to, by the rule scram_branches follows. scram.branch_info answers the branch's last merge and last refresh (last_refresh_id, last_refresh_position) to a session of any database, the branch's own, its parent's or one above it, and not to the branch's own session alone.
To make a branch the new parent, swap the names: ALTER DATABASE app SWAP WITH staging_test (or scram.swap_branch('app', 'staging_test')). app then holds the branch's data and staging_test the old parent's. Each database's owner, grants and comments move with its data. A merge made after a swap carries everything the merged database holds, the rows it held before the swap included.
- The caller must own both databases and hold
CREATEDB. - No session may be connected to either (
55006). - The default database cannot be swapped (
0A000).
Resetting or refreshing to a point in time:
-
RESET DATABASE b TO pnames the parent to start again from (42809when it is notb's parent). -
RESET DATABASE b AT TIMESTAMP '...'starts again from the parent as it was then, and needs what a branch at a past time needs. -
REFRESH DATABASE b FROM p AT TIMESTAMP '...'(orscram.refresh_branch('b', at => '...')) brings in the parent's changes up to the last commit at or before that time. -
The time is read in the spellings listed above; a text no timestamp reads is refused with
22007, and one with a field that does not exist with22008. -
A time before the branch's last merge or refresh, or in the future, is refused (
22023). A time older than both the node's log and its WAL archive is refused (55000), naming the earliest time they reach. -
The
scram.*branch functions also take named arguments:scram.reset_branch('b', at => '2026-10-30 12:00'). -
An expired branch is dropped as
DROP DATABASE ... WITH (FORCE)would drop it, its sessions ended first. On a cluster one node drops it for the whole cluster. -
scram.rename_branch('old', 'new')renames a branch. It is refused (55006) while sessions are connected to it. -
Dropping a parent leaves its branches standing as databases of their own, shown as
orphanedinscram_branches. A merge, refresh or reset of one answers that its parent was dropped (55000). Dropping a database that another was cloned from, directly or further up, leaves the clone's reads whole: every row it inherited reads as before, by key and by scan. -
A merge with
drop_branch = on, andscram.promote_branch(branch, true), are refused with55006while a session is connected to the branch after a five second wait, and the refusal comes before anything is merged. A session that connects while the merge runs is ended when the branch is dropped. -
While a merge, refresh or reset runs on a database,
DROP DATABASEis refused (55006, naming the operation).DROP DATABASE ... WITH (FORCE)waits for it instead, within the statement'slock_timeoutorstatement_timeout(55P03or57014when it runs out).
A branch merges into the database it was cut from or into any database above that, such as the database a snapshot was cut from; a refresh or a reset takes the parent alone. A database between the two that merged into its parent or refreshed from it after the next one was cut stops the merge (55000, naming it and the merge to make first). A database that is not above the branch answers 42809. The conditions in full are on Branching for agents.
To merge a branch back into its parent, see Branching for agents.
Worked workflows
1. Testing against real data
Clone production, try something risky against the clone, throw it away.
CREATE DATABASE migration_test CLONE scramdb;
psql "host=127.0.0.1 port=5432 user=scramdb dbname=migration_test" \
-c "ALTER TABLE orders ADD COLUMN priority integer DEFAULT 0;" \
-c "UPDATE orders SET priority = 1 WHERE status = 'urgent';"
Verify the migration did what you expected against real data volumes and real data shapes:
psql "host=127.0.0.1 port=5432 user=scramdb dbname=migration_test" \
-c "SELECT priority, count(*) FROM orders GROUP BY priority;"
DROP DATABASE migration_test;
Production was never touched, and you tested against the actual data, not a synthetic fixture.
2. Debugging production data
Branch as of just before an incident, then compare it against the current state to see exactly what changed.
CREATE DATABASE audit_before_incident FROM scramdb AT TIMESTAMP '2026-08-02T09:30:00Z';
psql "host=127.0.0.1 port=5432 user=scramdb dbname=audit_before_incident" \
-c "SELECT id, status FROM orders WHERE id = 101;"
psql "host=127.0.0.1 port=5432 user=scramdb dbname=scramdb" \
-c "SELECT id, status FROM orders WHERE id = 101;"
Comparing the two outputs shows you exactly what the row looked like right before the incident versus now, without touching production and without a separate restore-to-a-new-server round trip.
DROP DATABASE audit_before_incident;
3. CI
Give every test run its own isolated copy of a known-good fixture database, with no per-run data setup cost.
RUN_ID=$(date +%s)
psql "host=127.0.0.1 port=5432 user=scramdb dbname=scramdb" \
-c "CREATE DATABASE ci_run_${RUN_ID} CLONE template_db;"
# run your test suite against dbname=ci_run_${RUN_ID}
psql "host=127.0.0.1 port=5432 user=scramdb dbname=scramdb" \
-c "DROP DATABASE ci_run_${RUN_ID};"
Every run starts from the exact same fixture state, instantly, and cleans up after itself. No shared mutable test database, no fixture-loading step slowing down the pipeline.
4. Agent sandboxes
Give each autonomous job or agent its own branch to read and write freely, fully isolated from production and from every other agent's branch.
CREATE DATABASE agent_task_4471 CLONE scramdb;
The agent connects to agent_task_4471 and can run arbitrary reads and writes, including ones you would never let it run against production, since nothing it does there can reach the parent database or any other agent's branch.
DROP DATABASE agent_task_4471;
Known constraints
- A branch at a past time on a cluster needs the cluster's archive. Without
[storage.wal.archive]on every node, pointed at one shared destination, the archive does not reach the time and the statement says so. See Branching on a cluster. - Not inside an explicit transaction block.
CREATE DATABASE(either form) is refused if you run it insideBEGIN ... COMMIT. Run it as its own statement. - The default database can never be cloned away or dropped. Every instance's default database is protected from
DROP DATABASE, regardless of how many branches exist. FROM ... AT TIMESTAMPneeds its prerequisites in place. See is your instance configured for this? for the checklist: a configured backup destination, a base backup taken to it, and WAL history reaching back to your target timestamp.
Next
- Backups: set up the backup location that
FROM ... AT TIMESTAMPdepends on. - Point-in-time recovery: the same backup-plus-WAL machinery, used to rebuild a whole fresh instance instead of forking a database.