How Neon Branches a Postgres Database Without Copying It

17 min readpostgresql

Postgres has no BRANCH command. There is no CREATE DATABASE dev FROM main AS OF yesterday. Yet on Neon you click a button and get a writable copy of your database in about a second, and it doesn't matter whether the database is 1 GB or 1 TB.

I asked someone at Neon how that works. The short answer was: it happens below Postgres. Neon stores versioned pages built from the WAL. A branch is a new timeline that points at its parent at a specific LSN. It reads unchanged data from the parent, and its own writes go to its own timeline.

That answer is correct and I didn't fully understand it. So I did what I usually do. I read the code (Neon's pageserver is open source), then I built a small version myself to check I understood it.

The toy is about 400 lines of Go: github.com/Avik-creator/pgbranch. This post walks through it, shows the matching parts of the real Neon code, and covers the two bugs a randomized test found in my first version. Both bugs taught me the same rule, and it's the one that makes branching safe.

What Postgres already gives you#

Branching rests on three facts about plain Postgres.

Everything is pages. Tables and indexes are stored as 8 KB pages. Every read and write inside Postgres is "block N of relation R".

Every change is logged first. Before Postgres changes a page, it writes a WAL record that describes the change. The page itself is written to disk later, lazily.

Every WAL record has an LSN. The LSN (log sequence number) is the record's byte position in the WAL. It only grows, and Postgres prints it like 0/16B3748. Each page also remembers the LSN of the last change applied to it.

Put these together and you get the important part. After a crash, Postgres rebuilds the data files by replaying WAL. So the data files are a cache. The WAL is the real database. If you kept all of it, you could rebuild any page as it was at any LSN.

Plain Postgres throws old WAL away. Neon keeps it, organised by page. Once you can read any page at any LSN, branching is a small step.

Where Neon cuts Postgres apart#

Neon splits Postgres into three pieces:

code
Compute (Postgres + neon extension)
   │  WAL (pushed)                 ▲
   ▼                               │  GetPage(page, LSN) → 8 KB
Safekeepers ×3 (Paxos, 2 of 3)     │
   │  WAL                          │
   ▼                               │
Pageserver ────────────────────────┘
   │  immutable layer files
   ▼
S3
  • Compute is Postgres with its storage manager replaced by an extension. It has no data directory it relies on. When a page isn't in memory, it asks the pageserver for that page as of a given LSN. This request is called GetPage@LSN.
  • Safekeepers make the WAL durable. A commit counts once two of three have it on disk.
  • The pageserver reads the WAL from the safekeepers, sorts it by page, and answers GetPage@LSN.

Inside the pageserver, a page's history is stored under a key and an LSN. Each stored value is one of two things:

  • an image: the full page as it was at that LSN, or
  • a delta: one WAL record to apply on top of the previous version.

To answer GetPage(P, L), the pageserver finds the newest image of P at or before L. Then it replays P's deltas on top of it, up to L. The replay uses Postgres's own redo code, run in a sandboxed process called walredo.

That's the storage model. Now the toy.

The toy: pages and records#

A real page is 8 KB of bytes with line pointers. Mine is a list of strings, and a row's slot is its position in the list.

go
type Page []string
 
type Record struct {
	Op   Op     // OpInsert or OpUpdate
	Slot int    // OpUpdate only
	Row  string
}

Like a real WAL record, a Record changes exactly one page, and it only makes sense on top of the version before it. Applying one is my version of walredo:

go
func redo(p Page, r Record) Page {
	next := slices.Clone(p)
	switch r.Op {
	case OpInsert:
		next = append(next, r.Row)
	case OpUpdate:
		next[r.Slot] = r.Row
	}
	return next
}

The slices.Clone looks like a detail but it matters. The page passed in may be a stored image that other reads, and other branches, still use. If redo changed it in place, a write on one branch could change what another branch sees. Branches can share data only because nothing stored is ever changed. Neon's layer files are immutable for the same reason.

Then the store itself. A key names a page. A version is a value at an LSN.

go
type LSN uint64
type Key struct { Rel string; Block uint32 }   // printed as orders/0
 
type Value struct {
	Image  Page    // a full page, or
	Record *Record // one delta
}
 
type version struct { LSN LSN; Value Value }

Neon's key is 18 bytes built from the tablespace, database, relation, fork and block. Mine is orders/0. The model is the same.

A branch is two pointers#

Here is the timeline. In Neon's code, a branch is called a timeline (not to be confused with Postgres's own WAL timelines).

go
type Timeline struct {
	ID          string
	ancestor    *Timeline // nil for main
	ancestorLSN LSN       // the branch point
	children    []*Timeline
	lastLSN     LSN
	gcCutoff    LSN
	history     map[Key][]version // only versions written on THIS timeline
}

The comment on history is the whole idea. A timeline stores only what was written on it. Everything older comes from ancestor, as it was at ancestorLSN.

So creating a branch is mostly validation, then an empty map:

go
child := &Timeline{
	ID:          id,
	ancestor:    parent,
	ancestorLSN: at,
	lastLSN:     at, // the child's first record takes LSN at+1
	history:     map[Key][]version{},
}
parent.children = append(parent.children, child)

Neon does the same thing in branch_timeline_impl in pageserver/src/tenant.rs. It takes the GC lock, checks the LSN, and writes metadata. The comment there says it plainly:

rust
// Create the metadata file, noting the ancestor of the new timeline.
// There is initially no data in it, but all the read-calls know to look
// into the ancestor.

No pages are copied. That's why branching 1 TB takes as long as branching 1 GB.

Writing is just as small. A write appends a delta at the next LSN, on this timeline only. The parent is never touched:

go
t.lastLSN++
t.history[key] = append(t.history[key], version{LSN: t.lastLSN, Value: Value{Record: &rec}})

The read path#

All the interesting work happens on reads:

go
func (t *Timeline) reconstruct(key Key, lsn LSN) Page {
	var deltas []Record // newest first
	for tl := t; ; tl = tl.ancestor {
		hist := tl.history[key]
		// Everything before index i has LSN <= lsn.
		i, _ := slices.BinarySearchFunc(hist, lsn+1, func(v version, target LSN) int {
			return cmp.Compare(v.LSN, target)
		})
 
		for _, v := range slices.Backward(hist[:i]) {
			if v.Value.isImage() {
				return replay(v.Value.Image, deltas)
			}
			deltas = append(deltas, *v.Value.Record)
		}
 
		if tl.ancestor == nil {
			return replay(nil, deltas) // start from an empty page
		}
		lsn = min(lsn, tl.ancestorLSN)
	}
}

Step by step:

  1. Find this page's versions at or below the requested LSN. Anything newer is in the future for this read.
  2. Walk them newest to oldest and collect deltas until you reach an image. An image is a complete page, so you can stop, replay the deltas on top, and return.
  3. If this timeline runs out of versions first, the rest of the page's history is in the parent. Move to the parent, but lower the LSN to the branch point first.

That last line, lsn = min(lsn, tl.ancestorLSN), is what keeps branches apart. Say dev branched from main at LSN 3, and main has since written LSN 4, 5 and 6. When a read on dev moves to main, it reads main as of LSN 3, so main's later writes never appear on dev. The same loop also handles a branch of a branch of a branch, because each step up lowers the LSN again.

Neon has the same line. In get_vectored_reconstruct_data in pageserver/src/tenant/timeline.rs:

rust
// Each key range in the original query is at some point in the LSN space.
// When descending into the ancestor, lower all ranges in the LSN space
// such that new changes on the parent timeline are not visible.
query.lower(timeline.ancestor_lsn);

Neon's version reads many keys at once from LSM layer files, and mine reads one key from a sorted slice. The rule is the same.

Running it#

The demo writes three records on main, branches dev at LSN 3, then writes different things on each:

code
main  LSN 1  customers/0  insert "alice"
main  LSN 2  orders/0  insert "#1 alice 20.00"
main  LSN 3  orders/0  insert "#2 alice 35.00"

dev branched at LSN 3
page versions stored: main=3 dev=0 (branching copied nothing)

main  LSN 4  orders/0  insert "#3 alice 12.50"
dev   LSN 4  orders/0  update slot 0 = "#1 alice 20.00 REFUNDED"
dev   LSN 5  orders/0  insert "#99 test order"

Look at LSN 4. It exists on both branches and means something different on each. An LSN alone doesn't identify a version. A timeline plus an LSN does.

Every read in the demo prints where each part of the page came from. Here is orders/0 read on dev:

code
GetPage(orders/0, LSN 5) on dev
   dev    orders/0 at LSN <= 5: 2 delta(s), no image. Go to main at LSN 3.
   main   orders/0 at LSN <= 3: 2 delta(s), no image, no ancestor. Start from an empty page.
   slot 0: #1 alice 20.00 REFUNDED
   slot 1: #2 alice 35.00
   slot 2: #99 test order

That one page is built from two timelines. Slots 0 and 1 started on main, then dev's update and insert were replayed on top. main's order #3 isn't there, because dev read main as of LSN 3.

A page dev never wrote comes entirely from main:

code
GetPage(customers/0, LSN 5) on dev
   dev    customers/0 at LSN <= 5: 0 delta(s), no image. Go to main at LSN 3.
   main   customers/0 at LSN <= 3: 1 delta(s), no image, no ancestor. Start from an empty page.
   slot 0: alice

Branching from the past is the same operation with an older LSN. tenant.Branch("audit", main, 2) gives a branch that sees main as it was at LSN 2. This is how Neon does point-in-time restore: you don't restore a backup, you branch at an old LSN.

What a parent owes its children#

If you keep every version forever, storage grows without limit. So the pageserver runs garbage collection. Each timeline keeps a restore window of recent history (Neon calls the setting pitr_interval), and anything older can go.

Branches complicate this. Say dev branched from main at LSN 3, and main is now at LSN 8 with a window of two LSNs. main's own reads only need LSN 6 and later. But dev still falls through to main at LSN 3, and it will keep doing that for as long as it exists.

So GC must keep each page readable at every child's branch point, however old. Neon gathers these points into a list called retain_lsns:

rust
let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    .remove(&timeline.timeline_id)
    .unwrap_or_default();
...
target.retain_lsns = branchpoints;

My GC follows Neon's newer approach (RFC 043, bottom-most GC compaction). For each page, it writes one image at each point that must stay readable. Then it drops the deltas below the cutoff:

go
// The points to keep below the cutoff: each child's branch point,
// then the cutoff itself.
for _, key := range slices.SortedFunc(maps.Keys(t.history), compareKeys) {
	hist := t.history[key]
	var kept []version
	prev := LSN(0)
	for _, p := range points {
		if changedBetween(hist, prev, p) {
			kept = append(kept, version{LSN: p, Value: Value{Image: t.reconstruct(key, p, nil)}})
		}
		prev = p
	}
	for _, v := range hist {
		if v.LSN > cutoff {
			kept = append(kept, v)
		}
	}
	newHistory[key] = kept
}

The changedBetween check avoids storing duplicate images. If a page didn't change between two kept points, the earlier image already answers reads at the later one. If the page was never written on this timeline, nothing is stored, and reads keep falling through to the parent.

In the demo, main writes four more updates and then runs GC:

code
cutoff LSN 6, branch points kept [2 3]
main page versions: 8 before, 6 after (4 page images written)
dev still reads the same page:   true
audit still reads the same page: true

GetPage(customers/0, LSN 5) on dev
   dev    customers/0 at LSN <= 5: 0 delta(s), no image. Go to main at LSN 3.
   main   customers/0 at LSN <= 3: 0 delta(s), then an image at LSN 2. Done.

The read on dev now ends at an image that GC wrote. History below LSN 6 is gone for everyone else:

code
read main at LSN 5: main: LSN 5 is below the GC cutoff (6); that history is gone
branch main at LSN 1: invalid branch start lsn 1: less than GC cutoff 6

That second message borrows the wording of Neon's own error (invalid branch start lsn: less than latest GC cutoff). It's the reason you can only branch from a past point inside your restore window.

There's a cost here too. An old branch you forgot about keeps its parent's pages from months ago alive. The branch looks empty, but it still pins storage.

How I checked it#

The demo shows the toy works on one story. That doesn't prove much. So the main test compares the toy against a model that can't be wrong in the same way.

The model never garbage-collects and never shares anything. Each branch keeps its full list of records. To read a page, the model rebuilds it from scratch: the parent's page at the branch point, then this branch's own records.

go
func (m *model) read(key Key, lsn LSN) Page {
	var page Page
	if m.parent != nil {
		page = m.parent.read(key, min(lsn, m.branchLSN))
	}
	for _, l := range m.log {
		if l.key == key && l.lsn <= lsn {
			page = redo(page, l.rec)
		}
	}
	return page
}

The test runs 200 seeds. Each seed takes 300 random steps: 70% writes, 15% branches at a random allowed LSN, 15% GC runs with a random window. After every step, it reads every page at every readable LSN on every branch and compares the result with the model.

My first version failed it.

Bug 1: reading a branch before it existed#

code
step 13: t1 a/0 at LSN 1 = [], model says [s0]

The test read branch t1 at LSN 1, but t1 branched at a later LSN. A read below the branch point falls through to the parent at that old LSN. The parent had already run GC, and GC only protected the branch point itself, not the history before it. So the page came back empty.

Neon's compute never reads a branch before its start, so the fix is to refuse:

go
if t.ancestor != nil && lsn < t.ancestorLSN {
	return nil, fmt.Errorf("%s: LSN %d is before the branch point (%d); read %s instead", ...)
}

Bug 2: branching a branch before it existed#

With the first fix in, the test still failed. I added logging and ran the failing seed alone:

code
step 19: branch t1 from t0 at 3
step 21: GC t0 {Cutoff:12 RetainLSNs:[3] ...}
step 24: branch t2 from t1 at 3
step 25: branch t3 from t2 at 1
step 25: t3 b/0 at LSN 1 = [], model says [s0]

t2 starts at LSN 3, and the test branched t3 from t2 at LSN 1. That's not t2's history at all. It's t0's history from before any of these branches existed, and t0's GC had already dropped it. Nothing in the tree had promised to keep LSN 1.

The fix is the same kind of check, in Branch:

go
if parent.ancestor != nil && at < parent.ancestorLSN {
	return nil, fmt.Errorf("cannot branch %s at LSN %d: it starts at LSN %d; branch %s instead", ...)
}

After both fixes, all 200 seeds pass.

The rule both bugs teach#

A parent keeps exactly the branch points of its children. It does not keep the history around them.

That one rule explains several things that otherwise look like separate product limits:

  • You can't branch from a point outside the restore window, because that history is gone.
  • Old branches cost storage, because each one pins its branch point on the parent.
  • A branch only reaches back to the moment it was created. Before that, the history belongs to the parent.

When the person at Neon told me they "retain the state a branch needs, not raw WAL forever", this is what they meant. I didn't understand it until my test broke on it twice.

Why there's no merge#

Git merges text. It finds a common ancestor and applies both sides' changes line by line, and a person resolves what's left.

Database branches don't merge, and the reason is clear once you've seen the storage. Neon's history is physical: page images and WAL records, not row-level changes. Page 7 on a branch and page 7 on its parent can have tuples at different offsets. There's nothing meaningful to diff at that level. And even with a logical diff, merging data has no general right answer:

  • Both branches update the same row. Which value wins?
  • One branch deletes a customer while the other adds orders for that customer. Each branch is valid on its own. Merged, the foreign key breaks.

So branches are used one way. You branch, test a migration or try something, then delete the branch or reset it from its parent. Schema changes reach main through migrations you run there.

What the toy leaves out#

The toyReal Neon
A sorted slice of versions per pageAn LSM tree: an in-memory layer, then L0 delta files, compacted into L1 deltas and image layers, all immutable and stored in S3
Images written only by GCCompaction also writes images, so replays stay short
One mutex around everythingIngest, reads and GC run concurrently. The GC lock only covers branch creation and GC
Write called directlyCompute pushes WAL to the safekeepers, and the pageserver reads it from them
Reads that never waitwait_lsn blocks a read until the WAL for that LSN has arrived
An LSN is a counterAn LSN is a byte offset into the WAL

The storage engine is the biggest gap. The next part will replace the sorted slices with real layer files: flushing, L0 to L1 compaction, and seeing why read amplification makes compaction necessary.

If you want to go further#

Thanks to the Neon team for answering a curious question, and for building this in the open so anyone can read how it works.