The shared staging database is the single worst piece of infrastructure most teams own, and nobody wants to admit it. It is the thing two engineers fight over on a Thursday afternoon because one of them ran a migration that renamed a column the other one’s branch still depends on. It is the reason your CI is flaky: test suite A truncates a table that test suite B assumed had three rows. It is the pile of orphaned test accounts, half-applied migrations, and “do not delete, prod depends on this” rows that nobody has touched since 2023.

Every team past three developers has felt this. The usual fixes do not work. You cannot give everyone a local Postgres that matches production data, because production data is huge and often sensitive. You cannot spin up a fresh RDS instance per pull request, because that takes minutes and costs real money and somebody has to remember to tear it down. So you share one staging database, you write a Slack message asking people not to run destructive migrations, and you accept the pollution as a cost of doing business.

Neon’s branching model makes that whole tradeoff obsolete. It can hand every pull request its own full Postgres database, branched from production, in under a second, for a cost that rounds to zero while nothing is querying it. This is not a demo trick. It changes what a reasonable CI pipeline looks like.

Why the naive approaches break

Start with the obvious ways teams try to solve isolated test databases and watch each one fail.

Approach one: one shared staging database. Cheap, simple, and the default. It breaks the moment two branches need incompatible schemas at the same time. Branch A adds a NOT NULL column with no default; branch B’s seed script, written last week, does not supply that column and now its inserts fail. Tests that pass locally fail in CI depending on merge order. You spend Friday debugging a bug that does not exist in your code.

Approach two: spin up a real database per PR. Correct in isolation, wrong in practice. A new RDS or Cloud SQL instance takes several minutes to provision, and restoring a realistic dataset into it takes longer. If a developer opens five PRs, that is five instances billing by the hour whether or not anyone is testing. You need a reaper job to tear them down, the reaper job sometimes fails, and three weeks later you find forty idle instances on the bill.

Approach three: Dockerized Postgres in CI with a seed script. This is where most serious teams land. It is isolated and fast to start. The problem is the data. Your seed script is a fiction. It has ten users and three orders. Production has ten million users and a long tail of weird states: the account that signed up in 2019 before you added email verification, the order with a null shipping address because of a bug you fixed but never backfilled. Your migration works perfectly against the seed data and then locks a table for nine minutes against production. The seed script cannot teach you that.

The thing all three are missing is the ability to cheaply copy a large, realistic dataset and throw the copy away. That is exactly the operation Neon made cheap.

What copy-on-write branching actually does

Neon separates storage from compute. This is the whole trick, so it is worth being precise about it.

In a normal Postgres deployment, the compute process (the thing that parses SQL and runs query plans) and the storage (the actual data files on a disk) are fused together on one machine. To copy the database you copy the bytes.

Neon splits them. Storage lives in a multi-tenant service that keeps data as an append-only log of page versions, backed by object storage. Compute is a stateless Postgres process that reads pages from that storage service on demand and caches them locally. Because storage is versioned and immutable at the page level, creating a branch does not copy any data. It just records a pointer: “branch pr-482 starts from the parent’s state at log position X.”

                   Neon storage (versioned page log, backed by S3)
                   =========================================
   main   ---------o----o----o----o----o----o----o----->  (LSN grows over time)
                                     \
   pr-482 (branch) .................. o----o--->   writes only; reads fall
                                      ^            through to the shared
                                  branch point     history before this point

A read on the branch for a page it has not modified falls through to the parent’s history. A write on the branch creates a new page version that only the branch sees. The parent never notices. This is copy-on-write, the same idea that makes filesystem snapshots and container layers fast, applied to a Postgres data directory.

Two consequences matter for per-PR databases:

  1. Creating a branch is nearly instant and nearly free. You are not copying a 200 GB dataset. You are writing a pointer. Neon advertises sub-second branch creation and in practice it is fast enough that a GitHub Actions step does not notice it.
  2. A branch only costs storage for what it changes. If your PR’s tests insert a thousand rows and your migration rewrites one table, you pay to store those diffs, not a second full copy of the database. Delete the branch and those diffs disappear.

Scale-to-zero is what makes it affordable

Cheap storage alone would not be enough. If every branch kept a compute instance running, forty open PRs would mean forty idle Postgres processes burning CPU hours. Neon’s second lever is that compute scales to zero.

When no client has queried a branch for a few minutes, Neon suspends its compute entirely. You pay nothing for compute while it sleeps. The next connection wakes it in a few hundred milliseconds (a “cold start” you will notice in the first query and then never again during a test run). For a per-PR database this is close to ideal: your CI run connects, hammers the branch for ninety seconds, finishes, and the compute goes back to sleep. Across a day of open PRs, the integral of actual compute used is tiny.

The pricing model follows from this. You are billed roughly on:

DimensionWhat you pay forPer-PR reality
ComputeActive hours, in “compute units” (vCPU + RAM), billed while awakeMinutes per CI run, then zero
StorageYour main dataset plus the unique diff each branch holdsDiffs are small and deleted on merge
Data transferEgress, depending on planNegligible for internal CI

The branch itself is not a line item. A branch that exists but is never queried and never written to is almost pure accounting. This is the difference that lets you say “every PR gets a database” without the finance team noticing.

Wiring it into GitHub Actions

Here is the actual pattern. Neon maintains official Actions for creating and deleting branches, and they are thin wrappers over the Neon API, so you can drop to curl if you prefer. The shape is: create a branch when a PR opens or updates, run migrations and tests against it, delete it when the PR closes.

Create the branch and capture its connection string:

name: pr-database
on:
  pull_request:
    types: [opened, reopened, synchronize]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Create Neon branch for this PR
        id: branch
        uses: neondatabase/create-branch-action@v5
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          branch_name: pr-${{ github.event.number }}
          parent: main
          api_key: ${{ secrets.NEON_API_KEY }}

      - name: Run migrations
        env:
          DATABASE_URL: ${{ steps.branch.outputs.db_url_pooled }}
        run: |
          npm ci
          npm run migrate:up

      - name: Run integration tests
        env:
          DATABASE_URL: ${{ steps.branch.outputs.db_url_pooled }}
        run: npm run test:integration

The important output is db_url_pooled, a complete Postgres connection string pointing at a brand new branch whose data is a copy-on-write snapshot of main. Your migration tool runs against it. Your tests run against it. Nothing you do here touches the parent branch, and no other PR’s branch touches yours.

Delete the branch when the PR closes, so merged and abandoned PRs clean up after themselves:

name: cleanup-pr-database
on:
  pull_request:
    types: [closed]

jobs:
  cleanup:
    runs-on: ubuntu-latest
    steps:
      - name: Delete the PR branch
        uses: neondatabase/delete-branch-action@v3
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          branch: pr-${{ github.event.number }}
          api_key: ${{ secrets.NEON_API_KEY }}

That closed event fires whether the PR was merged or just abandoned, so you do not need a separate reaper for forgotten branches. The one gap to watch: PRs that sit open for months still hold a branch. A weekly scheduled job that lists branches older than N days and deletes ones with no recent compute activity closes that hole.

The branch connection string pattern

The detail that trips teams up is naming and reaching the right branch. Neon gives every branch its own endpoint hostname, so the connection string is not “the production string with a flag.” It is a genuinely different host.

A Neon connection string looks like this:

postgresql://user:[email protected]/dbname?sslmode=require

The ep-cool-darkness-... part is the endpoint, and each branch has its own. That is why you capture the action’s output and inject it as DATABASE_URL rather than templating the host yourself. Two more things worth knowing:

  • Use the pooled connection string in CI. Neon offers a direct endpoint and a pooled one (it runs PgBouncer in front). Test suites often open many short-lived connections, and the pooled string (db_url_pooled) avoids exhausting the connection limit. Use the direct string only for migrations that need session-level features the pooler does not support, like advisory locks or CREATE DATABASE.
  • Stamp the branch name with the PR number, not the git SHA. You want the branch to persist across pushes to the same PR so your data accumulates sensibly within one review, and you want the closed event to find it by a predictable name. pr-${{ github.event.number }} does both.

If you deploy preview environments (an ephemeral app instance per PR, the way Vercel or your own setup does it), point that preview app at the same per-PR branch. Now your preview environment reads realistic data and your reviewer can click around a real app backed by a real snapshot, and none of it can corrupt staging.

Branching from production data, safely

The angle that makes this genuinely useful is branching from production, not from a thin seed. That gives your migrations a real target. But two risks come with it, and ignoring them is how this blows up.

Risk one: sensitive data in a thousand throwaway branches. A branch from production is production data. If your main branch holds real emails, payment tokens, or personal data, every PR branch now holds a copy, readable by anyone who can see CI logs or the preview app. The right move is to not branch from raw production. Keep a sanitized branch (call it main-sanitized) that is periodically refreshed from production through a job that masks PII, and set that as the parent for PR branches. You keep the realistic shape and volume of the data without spraying secrets across ephemeral environments.

Risk two: destructive migrations are still destructive, just contained. The whole point is that a bad migration on a branch cannot hurt production, and that is true. But a migration that takes a nine-minute lock on a large table will take nine minutes on the branch too, because the branch has the same data volume. That is a feature: you want CI to surface the slow migration before it reaches production. Set a statement timeout in your migration step and let the branch catch the lock problem for you.

# A pre-deploy check you can run against the PR branch in CI.
# Fails the build if a migration would hold a lock too long,
# instead of discovering that during the production deploy.
import os
import psycopg

ACCESS_EXCLUSIVE = "AccessExclusiveLock"

def check_migration_locks(migration_sql: str, max_lock_ms: int = 2000) -> None:
    conn = psycopg.connect(os.environ["DATABASE_URL"], autocommit=False)
    with conn.cursor() as cur:
        # Abort any statement that runs longer than the budget.
        cur.execute(f"SET statement_timeout = '{max_lock_ms}ms'")
        cur.execute(f"SET lock_timeout = '{max_lock_ms}ms'")
        try:
            cur.execute(migration_sql)
        except psycopg.errors.LockNotAvailable:
            conn.rollback()
            raise SystemExit(
                "Migration could not acquire a lock within "
                f"{max_lock_ms}ms. It will block production. "
                "Rewrite it to be online-safe."
            )
        # Roll back: we only wanted to prove it is safe, not apply it here.
        conn.rollback()
    conn.close()

Because the branch is a cheap, isolated, realistic copy, you can afford to run this kind of destructive check on every PR. That is the real unlock. It is not just test isolation; it is a safe place to find out that your migration is a problem before anyone merges it.

Neon versus the alternatives

The obvious comparison is Supabase, which also sells managed Postgres and is excellent at the application-platform layer (auth, realtime, storage, generated APIs). The distinction that matters for this specific use case is the branching primitive.

ConcernNeonSupabasePlain RDS / Cloud SQL
Per-PR databaseInstant copy-on-write branchBranching exists, heavier and newerFull instance, minutes to provision
Idle costScales to zero, pay nothingCompute generally always onBilled per hour, always
Branch from prod dataNative, near-freePossible, more copyingSnapshot restore, slow and costly
TeardownDelete pointer, diffs vanishDelete branchMust run a reaper job
Bundled app platformMinimal, it is PostgresRich (auth, storage, APIs)None

If you want a batteries-included backend, Supabase is a strong pick and its own branching has improved. If the specific thing you want is a disposable, production-shaped Postgres per pull request at near-zero idle cost, Neon’s architecture is built for exactly that and it shows.

Honest assessment

What works, with no asterisks: branch creation is genuinely fast, the GitHub Actions integration is a few lines of YAML, and scale-to-zero makes the economics real rather than aspirational. If your pain is a polluted shared staging database and flaky CI caused by shared state, this fixes the root cause instead of papering over it. The ability to run destructive-migration checks against production-shaped data on every PR is worth the migration on its own.

What does not work, or needs care: cold starts are real. The first query against a slept branch pays a few hundred milliseconds, which is invisible in CI but can surprise you if you point latency-sensitive production traffic at a scale-to-zero compute. Long-lived open PRs leak branches unless you add a scheduled cleanup. And branching from raw production data is a compliance landmine; if you skip the sanitized-parent step, you will eventually have a bad day. Neon is also a comparatively young company running a novel storage architecture, so treat it as you would any infrastructure dependency: understand your backup and export story before you are all in.

What to actually do: if you are on Postgres and sharing a staging database across more than three engineers, run the experiment. Create a sanitized parent branch, wire up the create-on-open and delete-on-close Actions, and point your integration tests at the per-PR connection string for two weeks. The failure mode you are trying to kill, debugging a test failure that is really a data-pollution failure, is expensive and constant, and this is the cleanest fix I have seen for it. Keep your production database wherever it is for now; adopt the branching for CI and previews first, and let it earn the rest.