all postsblog / ephemeral databases

blog

Top 13 Throwaway psql Platforms for Preview Environments (2026)

written by
Ajay Kumar
published
reading time
11 min read
topics

A preview environment is a promise with two halves. The front half is the one everyone builds: open a pull request, get a URL, click around, leave a comment. The back half is the one that decides whether the whole thing works: the URL is backed by an application, the application is backed by a database, and that database has to come into existence before the app boots, change shape every time someone pushes a migration, and stop existing when the pull request closes. Get the back half wrong and the preview either points at a shared staging database, which means three branches are fighting over one schema, or at a fresh database that nobody ever deletes, which means your invoice has a long tail of names like preview-pr-311.

Most roundups of throwaway Postgres grade the create call. That is the wrong unit for previews. A preview database lives through four events — the pull request is opened, a new commit is pushed, the preview app is deployed against it, the pull request is closed or merged — and the interesting failures all happen at the joins between those events, not inside any one of them. So the thirteen entries below are graded on the whole lifecycle. The siblings of this post already cover other axes: Top 12 Disposable psql Platforms for Staging in 2026: Graded on Fidelity to Production grades fidelity to production over a long-lived environment, and Top 6 Burner Postgres Platforms for Pull Requests (2026) is mostly about idle cost and the orphan reconciler. This one is about the coupling between the preview app and its database.

I build PandaStack, which has a managed Postgres product, so it is entry thirteen and its caveats are written by the person with the most incentive to soften them. I have tried not to. The headline one: a PandaStack database takes 30 to 90 seconds to create. That is not instant, and in a preview pipeline it is a delay your app deploy has to wait on.

Everything said here about other vendors is qualitative — shape, fit, and the failure mode I would watch for. No competitor latencies, prices or quotas, because this category re-architects and reprices on a timescale of months. Verify every specific against each vendor's current docs before you wire it into CI, including the PandaStack entry.

The lifecycle, and where it breaks

Here are the four events, in GitHub's vocabulary, with the failure that lives at each one. If a platform makes one of these joins disappear, it earns a place on the list. If it makes none of them disappear, it is just a Postgres with an API.

  1. opened (and reopened): create the database and get schema into it. The trap is ordering. If the preview app deploys in parallel and boots before the database is accepting connections, the app's first health check fails, the preview platform marks the deploy broken, and the reviewer's first impression of your feature is a 502. Creation has to be a dependency of the app deploy, not a sibling of it.
  2. synchronize (a new push): decide what happens to the database. There are three policies — keep the data and roll migrations forward, reset to a fresh copy, or re-branch from the parent — and the right one depends on whether the push changed migrations. The trap is drift: the author rebases, renames 0042_add_index.sql to 0043_add_index.sql, and the preview database now has a migration recorded that the branch no longer contains. Your migration tool will either refuse to run or, worse, run happily against a schema nobody can reproduce.
  3. Deploy: wire the connection string into the preview app. The trap is build time versus run time. Anything baked into a bundle at build time — a NEXT_PUBLIC_ variable, a config file rendered during the image build — is frozen to whichever database existed at build. If a reset or a clone changes the database URL, the app keeps talking to the old one. Inject the URL at run time, as a secret, and treat a URL change as a redeploy.
  4. closed (merged or not): destroy it. The trap is that teardown is wired to merged, and a large share of pull requests are closed without merging. The second trap is that the teardown job is itself code in the repository, so a pull request that broke the workflow cannot run the job that cleans up after it. The event is a fast path; a scheduled sweep that compares live databases against open pull requests is the authority.

Two more things break across all four events and deserve their own line. Secrets: a pull request from a fork does not get your repository secrets under the pull_request trigger, which is correct, and the popular fix — switching to pull_request_target and checking out the fork's head — runs a stranger's code with your database API key in the environment. Don't. Fork previews either get no database or get one created by a separate, trusted workflow that never executes the fork's code. And data: if the preview is seeded from production, every preview is a copy of production data behind a URL whose only protection might be that it is hard to guess. Seed with synthetic or anonymised data, or the preview becomes the least-defended copy of your customers you own.

The thirteen, grouped by how the database arrives

Branch-first: Neon, Supabase branching, Xata, PlanetScale Postgres

1. Neon. Separated storage with copy-on-write branches is the shape the preview case was waiting for: opened becomes "branch from main", which inherits schema and data without a seed step, and compute that scales to zero makes forty idle previews cheap. Neon ships integrations with popular preview hosts that create a branch per preview deploy and inject the URL, which closes the deploy join for you if you are on one of those hosts. On synchronize you choose between keeping the branch and resetting it from its parent; resetting is the clean answer to migration drift. What to watch: branches are cheap enough that nobody notices four hundred of them, and the integration's teardown is only as good as its trigger. Verify current branch limits and reset semantics in their docs.

2. Supabase branching. Preview branches tied to git branches, with the repository's migrations applied to each branch, which makes the synchronize story principled: the migration files in the branch are the source of truth, and the preview database is rebuilt from them. The fit is strongest if your app uses the parts of Supabase that are not Postgres — auth, storage, row-level-security conventions — because then the preview needs those too and nothing else on this list provides them. The drawback is the mirror image: if you only wanted Postgres, you are adopting a platform to get a database. Seed data comes from a seed file you maintain, which is a feature for the privacy problem above.

3. Xata. Postgres branching with anonymisation applied on the copy path, which goes straight at the data trap: a preview branched from production with personal data scrubbed is the thing most teams actually want and rarely build. The product has changed shape more than most in this list over the last couple of years, so read their current docs for the branch and privilege model rather than trusting anyone's summary, including this one.

4. PlanetScale Postgres. PlanetScale's branch-plus-deploy-request model, long associated with MySQL, now has a Postgres offering. The appeal for previews is that a schema change becomes a reviewable artifact next to the code change, which turns the synchronize drift problem into a diff a human looks at. Verify which branching and deploy-request features are available on the Postgres side today before planning around them; the MySQL feature set is not a promise about the Postgres one.

Instant serverless: Prisma Postgres

5. Prisma Postgres. A serverless Postgres aimed at fast creation and tight coupling with the Prisma toolchain, which makes the opened step short and the migration step (prisma migrate deploy) the obvious one. For a preview that only needs an empty schema plus a seed, that is a clean fit. Verify how close to stock Postgres the connection model is for your driver and whether extensions you depend on are available; if your app does not use Prisma, much of the reason to pick it goes away.

The preview platform brings the database: Railway, Render

6. Railway PR environments. If the app already lives on Railway, a pull request environment can duplicate the project's services — database included — and wire the reference variables so the preview app finds its own database without you passing a URL anywhere. That is the deploy join solved by construction, which is the hardest one to solve yourself. The database starts fresh rather than branched, so seeding is a step you own, and the environment's lifetime follows the platform's pull request handling. Verify how data and volumes are treated in duplicated environments.

7. Render preview environments. The same idea in blueprint form: the blueprint file describes services and databases, and a preview environment instantiates all of it per pull request, with teardown when the pull request closes and an expiry setting for the ones that linger. The clean part is that app and database share one lifecycle object, so there is no separate teardown to forget. The cost is the same as Railway's: a fresh, empty database each time, and you are on that platform for the app too. Check how long a preview database takes to provision and whether your seed fits the deploy budget.

The hyperscalers: Aurora and RDS, Cloud SQL

8. Aurora clones and RDS snapshots. Aurora's copy-on-write clone is a real branch primitive at the storage layer and the fastest way in this cohort to give a preview a realistic copy of a parent; plain RDS restores a snapshot into a new instance, which is slower and a full copy. Both produce a new endpoint per preview, so the deploy join is yours, and both produce an instance that bills until something deletes it, so the closed join is yours too. The honest win is parameter-group fidelity to production. The honest loss is that every lifecycle step is a script you maintain against an API built for databases that live for years.

9. Cloud SQL clones. Same shape with a smaller knob set: a clone lands in a new instance with its own address, usable for previews, slower to appear than a storage-layer branch, and an hourly line item until your teardown runs. Pick it when the rest of the stack is on Google Cloud and the preview must match a Cloud SQL production instance, not because it is a good preview database in the abstract.

The Postgres specialist: Aiven

10. Aiven forks. A service can be forked from a source, optionally to a point in time, and configuration is exposed as an API, so a preview can be made parameter-identical to production with a script rather than a ticket. It is a service per preview, not a branch, so creation is a real provisioning step and the instance is a real line item. Good when previews must reproduce a production configuration bug; heavy when they just need a schema.

Local and in-pipeline: Docker Compose sidecar, Testcontainers

11. A Postgres sidecar in the preview itself. If your preview platform runs containers — a Compose stack on a preview VM, a pod per pull request, a sandbox per preview — the cheapest correct answer is often a postgres:16 container next to the app, created and destroyed with it. The lifecycle problem vanishes: app and database are one unit, the URL is localhost, teardown is the preview dying. You get full superuser and any extension you can bake into an image. You lose persistence across preview rebuilds (every redeploy is a fresh database, which is fine if your seed is fast and fatal if it is not), any way to share the database with a teammate's psql, and a real network hop, so you will not catch the bugs that only appear over TLS through a pooler.

12. Testcontainers. Not a preview database, and it is on the list so that nobody uses it as one. Testcontainers gives the CI job that gates the preview a real Postgres for the length of a test run, and that is exactly what it is for: run the migrations from scratch, run the suite, die. It is the right tool to catch migration drift before the preview exists, because a migration that cannot run on an empty database will not run on a preview either. It cannot back a URL a reviewer clicks. Testcontainers, and what comes after it goes further into where that boundary sits.

13. PandaStack managed databases

Each managed database is its own Firecracker microVM running PostgreSQL 16 on a durable volume, with its own guest kernel. You create one with a label, the API answers immediately with provisioning, and the SDK polls until the database is running with credentials — 30 to 90 seconds, because nothing reports ready until Postgres is accepting connections. The endpoint is postgres://pandastack:<pw>@<id>.db.pandastack.ai:5432/pandastack over TLS, stable for the database's whole life, so the preview app's secret survives every push that does not reset the database. RAM is chosen at create time as 1g, 4g or 16g, and is fixed afterwards.

For previews, the useful primitive is clone. client.databases.clone(source_id, target_time=...) restores a parent's backups into a new database, optionally to a point in time at least two minutes in the past, without touching the source, and the clone gets fresh credentials. So "branch from a seeded parent" works, and "show me the preview as it was before that bad migration" works. But the clone is a new database id, which means a new hostname and a new URL, which means the deploy join fires again: the preview app has to be redeployed with the new secret. There is also a REST-only branch route that reflink-copies a running parent's volume on the parent's own host; the Python SDK does not expose it yet.

What you are buying is a kernel boundary per preview database — a reviewer's runaway query or a migration that fills memory is one VM's problem — and a real Postgres server rather than a storage layer pretending to be one. What you are paying is time and RAM: every preview database is a running server, not a branch pointer.

The lifecycle table

Thirteen preview-database options graded on the four lifecycle events. Qualitative; verify every vendor row against current docs.
OptionOn PR openOn new pushWired into preview appOn closeWhat breaks first
NeonCopy-on-write branch from parentKeep, or reset branch from parentVia preview-host integrations, or your scriptIntegration or your job deletes the branchHundreds of forgotten branches
Supabase branchingBranch per git branch, migrations appliedMigrations from the branch re-appliedPlatform-managed for Supabase clientsTied to the git branchAdopting a platform to get a database
XataBranch, anonymised on copyRe-branchYour scriptYour jobShifting product surface; re-verify
PlanetScale PostgresBranchSchema diff via deploy requestYour scriptBranch deletedFeature parity with the MySQL side
Prisma PostgresFast fresh databaseRun prisma migrate deployYour scriptYour jobValue drops outside the Prisma toolchain
Railway PR environmentsDuplicated project incl. databaseRedeploy within the environmentReference variables, automaticEnvironment removed with the PRFresh database; seed is yours
Render preview environmentsBlueprint instantiated per PRRedeploy within the environmentBlueprint env vars, automaticTorn down on close, plus expiryFresh database; provisioning inside the deploy budget
Aurora / RDSAurora clone, or snapshot restoreYour scriptNew endpoint, your scriptYour teardownInstances outliving the PR
Cloud SQLClone into new instanceYour scriptNew address, your scriptYour teardownSlow to appear, bills hourly
AivenFork a serviceYour scriptNew service URI, your scriptYour teardownHeavy for schema-only previews
Postgres sidecarStarts with the previewFresh on every redeploylocalhost, nothing to wireDies with the previewSlow seeds; no shared access
TestcontainersNot applicable — CI job onlyFresh per test runNot reachable by reviewersDies with the jobBeing mistaken for a preview database
PandaStack databasesCreate, 30–90 s until runningKeep and migrate, or clone (new id)Stable TLS URL; clone means a new URLdatabases.delete, irreversibleCreate latency; every DB is a running VM

Wiring it: one workflow, four events

Here is the shape I would copy for any platform whose lifecycle you have to drive yourself, shown against PandaStack. One workflow listens to all four pull request events. A concurrency group keyed on the pull request number serialises them, so a closed that arrives while a create is still running waits for it instead of racing it — and in-progress runs are not cancelled, because cancelling a create mid-flight is how you get a database that exists on the server and in no log. The database step runs before the app deploy in the same job, so the deploy cannot start until the database is running.

yaml
name: preview
on:
  pull_request:
    types: [opened, reopened, synchronize, closed]

concurrency:
  group: preview-${{ github.event.pull_request.number }}
  cancel-in-progress: false   # never kill a create halfway

jobs:
  up:
    # Fork PRs get no secrets under pull_request, so they get no database.
    # Do NOT switch to pull_request_target to "fix" this.
    if: >-
      github.event.action != 'closed' &&
      github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pandastack
      - name: Database (find-or-create, migrate)
        run: python scripts/preview_db.py up
        env:
          PANDASTACK_API_KEY: ${{ secrets.PANDASTACK_API_KEY }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
      - name: Deploy preview app with DATABASE_URL injected at run time
        run: ./scripts/deploy-preview.sh "pr-${{ github.event.pull_request.number }}"

  down:
    if: github.event.action == 'closed'   # merged OR abandoned
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pandastack
      - run: python scripts/preview_db.py down
        env:
          PANDASTACK_API_KEY: ${{ secrets.PANDASTACK_API_KEY }}
          PR_NUMBER: ${{ github.event.pull_request.number }}

The script finds the database by label rather than by a stored id, so every run is stateless and the second, fifth and fortieth push all land on the same database. It masks the connection string before writing it anywhere, because a database URL in a public preview log is a credential in a public preview log. And it has an explicit drift policy: if migrations fail against the existing preview database, it can throw the database away and start fresh — paying another 30 to 90 seconds — instead of leaving a half-migrated schema for the reviewer to find.

python
#!/usr/bin/env python3
"""preview_db.py up|down -- one throwaway Postgres per preview environment."""
import os
import subprocess
import sys

import pandastack

client = pandastack.Client()          # reads PANDASTACK_API_KEY
LABEL = f"preview-pr-{os.environ['PR_NUMBER']}"
RESET_ON_DRIFT = os.environ.get("RESET_ON_DRIFT", "1") == "1"


def find():
    return next((d for d in client.databases.list() if d.get("label") == LABEL), None)


def create():
    # Returns once Postgres accepts connections: budget 30-90 s, not 1 s.
    return client.databases.create(label=LABEL, size="1g", timeout=240)


def migrate(url: str) -> bool:
    env = {**os.environ, "DATABASE_URL": url}
    return subprocess.run(["npx", "prisma", "migrate", "deploy"], env=env).returncode == 0


def publish(url: str) -> None:
    print(f"::add-mask::{url}")         # never let the URL reach the log
    with open(os.environ["GITHUB_ENV"], "a") as fh:
        fh.write(f"DATABASE_URL={url}\n")


def up() -> None:
    db = find()
    db = client.databases.wait_until_ready(db["id"]) if db else create()
    if not migrate(db["connection_url"]):
        if not RESET_ON_DRIFT:
            sys.exit("migrations failed against the preview database")
        # Drift (rebased or renamed migrations): start clean, eat the create time.
        client.databases.delete(db["id"])
        db = create()
        if not migrate(db["connection_url"]):
            sys.exit("migrations fail on a fresh database: fix the branch")
    subprocess.run(["npm", "run", "db:seed"], check=True,
                   env={**os.environ, "DATABASE_URL": db["connection_url"]})
    publish(db["connection_url"])


def down() -> None:
    db = find()
    if db:
        client.databases.delete(db["id"])   # immediate and irreversible
        print(f"deleted {LABEL} ({db['id']})")


if __name__ == "__main__":
    {"up": up, "down": down}[sys.argv[1]]()

Two things this deliberately does not do. It does not reseed on every push when the database was kept; the seed here is written to be idempotent, and if yours is not, gate it on whether the database was just created. And it is not the whole cleanup story. The closed job is the fast path, but it runs the workflow as it exists in the pull request's merge ref, so a pull request that broke the workflow file cannot clean up after itself. Add an hourly sweep that lists every preview-pr-* database, compares the numbers against the open pull requests, and deletes the difference — failing closed when the GitHub read errors or comes back implausibly empty. Top 6 Burner Postgres Platforms for Pull Requests (2026) has a full version of that reconciler, and Wiring preview environments into pull requests covers the app side of the workflow.

PandaStack, without the brochure

  • Create is 30 to 90 seconds, not instant. A copy-on-write branch on a separated-storage product is faster by a wide margin, because it forks a pointer and attaches warm compute; this boots a real server and waits until it answers. On opened that is a one-time wait the app deploy sits behind. With the reset-on-drift policy above, it is paid again on every push that changes migrations incompatibly.
  • Clone and point-in-time restore create a new database id. That is the right semantics — the source is never touched — but the new id is a new hostname, so every clone means re-injecting the URL and redeploying the preview app. If your preview host bakes environment into the build, a clone means a rebuild.
  • Managed databases are persistent. The idle reaper that cleans up ordinary sandboxes does not touch them, and ttl_seconds is not a knob here. A preview database lives until your workflow or your sweep calls client.databases.delete, and that call is immediate and irreversible: no trash, no grace period. Clone anything you want to keep first.
  • Every preview database is a running microVM with its own committed memory. Forty open pull requests is forty Postgres servers. Choose the smallest tier, 1g, unless a preview genuinely needs more, and remember the tier is fixed at create; the resize path is a clone with a different size, which is, again, a new id.
  • There is an idle auto-suspend with wake-on-connect, and it is off by default, so plan your costs around the awake case. When it is on, the reviewer's first query after a quiet afternoon is slower while the database wakes.
  • No shell into the database VM, by design: everything arrives over the wire. Seeds stream from your runner, so a large production-shaped seed is network-bound, and you cannot psql -f on the box.
  • Capacity is real. These are VMs on real hosts and a create that cannot be placed is an error your workflow must handle, which a storage-layer branch product mostly spares you.

The pick, by which join hurts most

If the deploy join hurts most — you are tired of passing URLs between a database API and a preview host — pick the option where one object owns both: Railway or Render preview environments if the app lives there, a Postgres sidecar if your previews already run as containers or sandboxes, or Neon through an integration with your preview host. Those make the wiring disappear rather than making it faster.

If the push join hurts most — rebased branches and renamed migrations leaving previews in states nobody can reproduce — pick a branch-first product and make "reset from parent" your default synchronize policy, or pick Supabase and let the branch's migration files be the only source of truth. Either way, run the migrations from scratch in a Testcontainers job before the preview is created, so drift is caught in CI rather than by a reviewer.

If the data join hurts most — previews that need production-shaped data without production's personal data — look at Xata's anonymised branching first, and otherwise build a seeded parent that every preview clones from. If the preview must match a production instance's configuration, the hyperscaler clones and Aiven forks are the honest answer, and you will write every lifecycle script yourself.

And if you want each preview database to be a real Postgres server behind its own kernel, with a stable TLS URL for the life of the pull request and clone-to-a-point-in-time when a review turns into an investigation, PandaStack is built for that — as long as your pipeline can wait 30 to 90 seconds on opened and redeploy the app whenever a clone hands you a new id. The rate card is on pricing.

Whichever you pick, write the teardown before the creation. Creation is a POST and everyone gets it right. Teardown is the part that runs on the day the workflow is broken, the pull request was abandoned, and the person who opened it has left the company — which is to say, the part that decides whether your preview databases are throwaway or merely thrown somewhere.

faq

Frequently asked questions

Should every preview environment get its own Postgres database?

If previews run migrations or write data, yes. A shared staging database means every open pull request is fighting over one schema, and the first branch that adds a column breaks the previews of every branch that does not have it. The exception is a read-only preview of frontend changes, which can safely point at a shared, seeded database.

How do I handle migrations when a preview branch is rebased?

Pick an explicit policy for the synchronize event. Keeping the database and rolling migrations forward is fast but breaks when migrations are renamed or reordered. Resetting the database from its parent, or recreating it and re-running migrations from scratch, is slower but always reproducible. A common compromise is to try forward migration first and reset only if it fails, which is what the script in this post does.

How do I give preview databases to pull requests from forks safely?

Under the pull_request trigger, fork pull requests do not receive repository secrets, so they cannot create a database, and that is the correct default. Do not switch to pull_request_target and check out the fork's code, because that runs untrusted code with your secrets. If fork previews matter, create their databases from a separate trusted workflow that never executes the fork's code, or give them a sidecar database inside the preview itself.

How long does a PandaStack preview database take to create?

30 to 90 seconds, because the call waits until PostgreSQL inside the database's microVM is accepting connections. Plan the preview app deploy to run after the database step, not in parallel with it. Cloning or point-in-time restore produces a new database id with a new URL, so the preview app must be redeployed with the new connection string.

What stops preview databases from piling up?

Two layers: a teardown on the pull request closed event (not just merged), and a scheduled sweep that lists every preview database by label, compares it with the open pull requests, and deletes the rest. The event is fast but unreliable; the sweep is slow but authoritative. On PandaStack, managed databases are persistent and never idle-reaped, so the sweep is not optional.

links

Keep reading

more posts

Related posts

  • Top 11 Ephemeral Postgres Platforms for CI Pipelines: Time to First Connection, and Whether It Is Real Postgres

    Your CI job does not care about QPS. It cares about two things nobody benchmarks: how long until a connection is actually accepted, and whether the thing accepting it is real Postgres or something wire-compatible. Eleven options graded on those, plus isolation, leak cost and whether a seeded dataset can be reused without re-seeding.

  • Top 5 Scratch Postgres Platforms for CI (2026)

    Before you shop for a disposable-Postgres product: a tuned postgres:16 container plus CREATE DATABASE ... TEMPLATE beats every platform on the board for unit and most integration tests. Five options for the cases where it genuinely doesn't, including the one where my own platform is the slowest thing here.

  • Top 9 Temporary PostgreSQL Database Platforms (2026)

    A temporary Postgres is produced in one of four ways — a process on the runner, a schema inside somebody else's server, a copy-on-write branch, or a server of its own. The factory decides everything else, including whether your migration rehearsal means anything.

  • A staging environment per branch, database included

    Preview URLs are standard now. Preview databases mostly aren't, so every branch still points at the one shared staging database — which is why your migrations still break each other.

  • Preview Environments on microVMs: a Live URL per PR

    Every pull request gets its own live URL backed by a real backend and database — on a Firecracker microVM, so even untrusted forked-PR code is isolated by hardware, not by a shared kernel.

More in Ephemeral databases · See Ephemeral Postgres databases on PandaStack

pandastack

Run code in a microVM in one API call.

50–100 ms cold start. Fork, snapshot, and scale to zero.

measured on the host; your network round trip is extra