SevyDevy

Preview Environments Explained: A Disposable Stack per Pull Request

, Last updated , 20 min read

Summary

  • Preview environments are short-lived copies of your app, one per pull request. A pull request is a proposed code change waiting for review. Each copy gets its own link.
  • The copy is created when the pull request opens, updated on every new push, and deleted when it is merged or closed. A CI system, the robot that runs builds, does this work.
  • Fill each copy with seed data: made-up starting records created by a script. Never copy real customer data into a preview.
  • Cost stays low through small size limits, an expiry date for forgotten previews, and a cleanup job. Payments and email are faked; the database is real.
  • Beginners can stop after the section on what to fake. Engineers get tested quota errors, a database clone in under 50 ms, and why deletes get stuck.

What goes wrong when every pull request shares one staging server?

Changes collide, and that is the problem preview environments solve. When everyone deploys to the same shared test server, called staging, one person's half-finished work breaks another person's review. Nobody can tell whose change caused a bug.

Picture a common setup. A team of twelve engineers runs a food-ordering app with one staging server. The setup is made up, but the collisions are real. On a busy day, four pull requests wait to be tested.

One engineer changes the checkout page. Another changes the orders table in the database. A third deploys a menu change over both of them. The reviewer opens staging, sees a broken checkout, and blames the wrong change.

So people start queueing for staging in a group chat. Reviews wait hours for a turn. Someone resets the staging database to fix their test and wipes everyone else's test orders. The shared server has become a traffic jam.

Preview environments remove the queue. Every pull request gets its own small, full copy of the app with its own database. The reviewer clicks one link and sees exactly that change, nothing else.

Which words do you need before building preview environments?

You need five words: pull request, CI, stack, seed data and teardown. Each one gets a plain meaning below.

  • Pull request (PR). A request to merge a branch of code into the main code. Reviewers read it and test it before it is merged.
  • CI (continuous integration). A service that runs builds and tests automatically when code changes. GitHub Actions is one example.
  • Stack. All the parts your app needs to run together: the web app, the API, the database, a cache and any background workers.
  • Seed data. Starting records loaded into a fresh database by a script, so the app has something to show. In a preview, every record is made up.
  • Teardown. Deleting everything a preview created: its containers, its database, its link and its cloud resources.

What are preview environments and how do they work?

Preview environments are disposable copies of your full stack, created automatically for each pull request and deleted when it closes. Netlify calls its version Deploy Previews.

They work by listening to pull request events. An event is a message the code host sends when something happens to a pull request. Your CI or deploy tool reacts to three moments: opened, new commits pushed, and closed.

Think of a hotel room for each guest. The guest checks in when the pull request opens. The room is made up from a standard layout, which is your seed data. When the guest checks out, housekeeping clears the room for the next guest.

Where the picture breaks: hotel guests always check out. Pull requests are often abandoned without being closed, so the room stays occupied and keeps costing money. That is why previews also need an expiry date.

The life of one preview environment

Notice that the same pull request number links every step. It names the namespace, the database and the link, so teardown knows exactly what to delete.

Diagram connections:

  • PR 123 opened to CI workflow runs
  • CI workflow runs to Namespace pr-123
  • Namespace pr-123 to Database pr_123
  • Database pr_123 to Preview link posted
  • Preview link posted to New commit pushed (Review continues)
  • New commit pushed to PR merged or closed (Review done)
  • PR merged or closed to Teardown job (Yes)
  • PR 123 opened: Engineer asks to merge a branch
  • CI workflow runs: Reacts to the opened event
  • Namespace pr-123: Isolated space with a size budget
  • Database pr_123: Cloned from the seeded template
  • Preview link posted: Reviewer tests only this change
  • New commit pushed: synchronize event: redeploy
  • PR merged or closed: closed event fires
  • Teardown job: Deletes namespace and database

Hosted platforms do this for you within their own world. Vercel deploys every push by default and comments a unique preview link on each pull request. Netlify builds a Deploy Preview when a pull request opens, at an address containing the pull request number.

Render covers backends too. It copies services, databases and environment groups for each pull request, and destroys the copy when the pull request is merged or closed. As of 30 October 2026, Render requires a Pro workspace plan or higher for this.

How do you seed a preview environment with safe data?

Generate the data with a script, load it once into a template database, and clone that template for each pull request. Never copy production data into a preview.

Previews are shared by link and protected less than production. A real customer's phone number in a preview is a data leak waiting to happen. Generated data also makes tests repeatable, because every preview starts from the same records.

Use addresses that can never reach a real person. RFC 2606, an internet standard, reserves example.com, example.net and example.org for examples. So customer17 at example.com is safe to email by mistake.

PostgreSQL makes the clone cheap. Its CREATE DATABASE command works by copying an existing database, called the template. Seed the template once, then make one copy per pull request.

sql
CREATE DATABASE seed_template;
-- connect to seed_template, create tables, then:
INSERT INTO customers
SELECT g, 'Test Customer ' || g,
       'customer' || g || '@example.com',
       '+91-90000-' || lpad(g::text, 5, '0')
FROM generate_series(1, 5000) g;

-- one copy per pull request
CREATE DATABASE pr_123 TEMPLATE seed_template;

On PostgreSQL 16.15, we seeded 5,000 customers and 50,000 orders, then cloned it. The clone took 39 ms and 46 ms in two runs on our test machine. Deleting 1,000 orders in pr_123 left the template's 50,000 untouched.

There is one catch. The PostgreSQL docs say the copy fails if any other session is connected to the template. We saw it happen: source database seed_template is being accessed by other users. Keep apps and people out of the template.

The pull request's own migrations should then run against its clone. A migration is a script that changes the database structure. Running it on fresh seed data catches a broken migration before it reaches staging.

Hosted platforms follow the same rule. Render's docs say preview copies of databases do not include data from the original. Render offers an initialDeployHook, a command that runs once after the first successful deploy, to seed the new database.

What should a preview environment fake and what should it run real?

Run real anything your change could break in a way a fake would hide. Fake anything that costs money, touches real people, or cannot be created per pull request.

A starting point for the food-ordering app (our recommendation, not a rule)
Part of the stackIn the previewWhy
Web app and APIReal, built from the pull requestThis is the change under review
DatabaseReal engine, same major version, seeded cloneMigrations and queries behave differently on fakes
Cache and queueReal, small, one per previewCheap to run and often where bugs hide
PaymentsProvider test mode with test keysTest-mode payments move no money
Email and SMSCaptured by a fake inboxReal messages could reach real people
Maps or other paid APIsRecorded responses or a stubPer-call fees add up across many previews
LoginReal login code with test usersAuth bugs are serious and need the real path

For payments, use the provider's own test mode. Stripe's docs, for example, describe a sandbox whose transactions do not move funds. They also say to use test API keys and never real card details when testing.

Keep secrets apart, too. Give previews their own test keys, never production keys. Render, for example, does not copy variables marked sync false into previews, so secrets you mark that way stay behind.

For engineers

Beginners can stop here. You now know what a preview is, where its data comes from and what to fake. The rest is for engineers: event wiring, quotas, cost and teardown that really finishes.

Which pull request events should create, update and delete a preview?

Create on opened and reopened, redeploy on synchronize, and tear down on closed. In GitHub Actions, you must ask for the closed event yourself, because it is not in the default list.

Nothing runs, and the preview lives on. GitHub's docs say a pull request workflow runs only for opened, synchronize and reopened by default. Synchronize means new commits were pushed to the branch. Without closed in your list, nothing ever deletes the preview.

GitHub pull request activity types and what a preview should do (GitHub Actions docs, as of 30 October 2026)
Activity typeRuns by default?What happenedPreview action
openedYesA new pull request was createdCreate the stack and post the link
synchronizeYesNew commits were pushedRedeploy the new commit
reopenedYesA closed pull request was opened againCreate the stack again
closedNo, add itMerged or closed without mergingTear everything down

There is no merged activity type. A merge arrives as closed, and the event says whether it was merged. We checked this with actionlint 1.7.7, a workflow linter: it rejected the type merged as invalid.

Here is a workflow that creates, updates and deletes one preview per pull request. The two scripts are your own deploy and delete scripts. It passed actionlint 1.7.7 with no errors; we did not run it on GitHub itself.

yaml
name: preview
on:
  pull_request:
    types: [opened, synchronize, reopened, closed]
concurrency:
  group: preview-${{ github.event.pull_request.number }}
  cancel-in-progress: true
permissions:
  contents: read
jobs:
  deploy:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    environment:
      name: preview
      url: ${{ steps.up.outputs.url }}
    env:
      PR: ${{ github.event.pull_request.number }}
      SHA: ${{ github.event.pull_request.head.sha }}
    steps:
      - uses: actions/checkout@v4
      - id: up
        run: ./scripts/preview-up.sh "pr-$PR" "$SHA"
  teardown:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    env:
      PR: ${{ github.event.pull_request.number }}
    steps:
      - uses: actions/checkout@v4
      - run: ./scripts/preview-down.sh "pr-$PR"

Three lines do the important work. The types line adds closed, so teardown can run. The concurrency group, keyed by pull request number, allows at most one run per pull request, and cancel-in-progress stops an older deploy when a newer push arrives. The same rule lets a reopen cancel a running teardown, one more reason for a cleanup sweep.

The environment url comes from a step output, which GitHub allows for this field. GitHub then shows a View deployment button on the pull request timeline, so reviewers never hunt for the link.

Three event surprises that leave previews broken or stale

  • Forks get no secrets. For pull requests from a forked repository, GitHub does not pass secrets, and the built-in token is read-only. A deploy that needs cloud keys will fail there.
  • Merge conflicts pause everything. GitHub does not run pull_request workflows while the pull request has a merge conflict, so the preview keeps showing old code.
  • The pull_request_target event is not a fix. GitHub warns against building or running pull request code with it, because it can expose secrets or give write access to untrusted code.

Vercel handles forks in a similar way. It asks a team member to authorise a deploy from a fork, which protects environment variables from leaking.

How do you isolate one preview per pull request in Kubernetes 1.33?

Give each pull request its own namespace, with a size budget and default limits. A namespace is a named space inside a Kubernetes cluster that groups resources and keeps their names apart.

Name it after the pull request, such as pr-123. Names only need to be unique within a namespace, so every preview can use the same app name, web, without clashing. Some objects, like nodes and storage classes, are cluster-wide and not isolated this way.

Next, add a ResourceQuota, a Kubernetes object that caps the total resources one namespace can use. Add a LimitRange too. It gives default CPU and memory sizes to any container that does not state its own.

yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: preview-budget
spec:
  hard:
    pods: "3"
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.cpu: "2"
    limits.memory: 2Gi
    services.loadbalancers: "0"
    persistentvolumeclaims: "1"
---
apiVersion: v1
kind: LimitRange
metadata:
  name: preview-defaults
spec:
  limits:
  - type: Container
    default: {cpu: 500m, memory: 512Mi}
    defaultRequest: {cpu: 250m, memory: 256Mi}

We applied this to a namespace called pr-123 on k3s v1.33.1, a small Kubernetes distribution. Here is what happened, with the real error messages shortened.

  1. Quota only, no defaults

    A pod with no CPU or memory settings was rejected: failed quota, must specify limits.cpu, limits.memory, requests.cpu and requests.memory.

  2. Add the LimitRange

    The same pod was accepted. Kubernetes filled in requests of 250m CPU and 256Mi memory, and limits of 500m and 512Mi.

  3. Hit the pod cap

    The fourth pod was refused: exceeded quota, requested pods=1, used pods=3, limited pods=3.

  4. Ask for a load balancer

    A LoadBalancer service was refused, because the quota allows zero. That blocks a paid cloud load balancer per preview.

Read the units carefully. 250m CPU means a quarter of one CPU core. Mi means mebibytes, so 256Mi is about 268 million bytes. You can check usage any time with kubectl describe resourcequota in the namespace.

One limit to know: the Kubernetes docs say changing a quota does not affect resources that already exist. Tighten a quota today, and running previews keep their old size until they are redeployed.

How do you control the cost of preview environments?

Cap each preview's size, keep the number of live previews low, and delete previews nobody is using. Each forgotten preview bills like a small server that nobody uses.

Here is the made-up maths for the food-ordering app. Say one preview costs Rs 40 a day (made up) in compute and storage. Twelve engineers with 30 open pull requests means Rs 1,200 a day, about Rs 36,000 a month.

In this team, most pull requests are reviewed within two days (made up), so most of that spend is idle previews. The levers below cut it.

  • Size budgets. A ResourceQuota per namespace, like the one above, puts a hard ceiling on CPU, memory and pods.
  • No per-preview load balancers. Set services.loadbalancers to zero and route every preview through one shared entry point by host name, such as pr-123 on a wildcard domain.
  • Smaller plans. Render's previews.plan and previews.numInstances settings run previews on a smaller plan and fewer instances than production.
  • Opt-in previews. Render's manual mode creates a preview only when the pull request title contains render preview in square brackets.
  • Cancel stale builds. The concurrency group in the workflow stops an old deploy when a new commit arrives.

Expiry matters most, and Kubernetes will not do it for you. In v1.33, the version we tested, a namespace has no expiry field. Its spec holds only finalizers.

Render offers previews.expireAfterDays, which deletes a preview after that many days without new commits. As of 30 October 2026, its docs say the default is no expiry, and each push resets the timer.

How do you make sure preview environments get torn down?

Use two cleanup paths: delete on the closed event, and run a scheduled sweep that deletes anything past its expiry date. The sweep catches every preview the first path missed.

The closed event misses more than you expect. A teardown job can fail, a workflow can be cancelled, and abandoned pull requests never close. Treat the event as the fast path, not the only path.

Two paths to teardown

Notice that both paths end at the same delete step. The scheduled sweep is the safety net for previews whose closed event never cleaned up.

Diagram connections:

  • PR closed event to Delete namespace
  • Nightly sweep job to Past expires-at?
  • Past expires-at? to Delete namespace (Yes)
  • Past expires-at? to Keep for now (No)
  • Delete namespace to Drop PR database
  • Delete namespace to Still Terminating? (After 10 minutes)
  • PR closed event: Fast path: runs as the PR closes
  • Nightly sweep job: Lists namespaces labelled preview
  • Past expires-at?: Compares annotation with current time
  • Keep for now: Recent push or still in review
  • Delete namespace: Removes everything inside it
  • Drop PR database: DROP DATABASE pr_123
  • Still Terminating?: Alert: a finalizer is blocking

For the sweep, label each preview namespace when you create it, for example preview=true. Add an annotation, a free-text note on the object, holding an expires-at timestamp. Push it forward on every deploy.

We ran this sweep on k3s v1.33.1. It found pr-123 with an expiry in the past and deleted the namespace. Within about 15 seconds, the namespace and its pods, quota and LimitRange were all gone.

Why a namespace can get stuck while deleting

A finalizer is a marker on an object that says some cleanup must finish before the object can disappear. A controller, a program watching the cluster, removes it when that cleanup is done.

If no controller ever removes it, the namespace waits forever. We tested this with a made-up finalizer on one ConfigMap. Twenty seconds after the delete, the namespace still showed Terminating.

Its status named the cause: NamespaceFinalizersRemaining, with the finalizer's name and one resource instance. Once we removed the finalizer, the namespace disappeared. In a real cluster, look for a controller that was uninstalled or is failing, because nothing else removes its finalizer.

The nearest built-in timer is narrow. The ttlSecondsAfterFinished field works only for Jobs, and has been stable since v1.23. It cleans up finished seed or test Jobs, not whole namespaces.

Argo CD, a GitOps tool that syncs a cluster to what is in Git, has a pull request generator. It discovers open pull requests and creates one Application per pull request. An Application is Argo CD's record of what to deploy and where. Its docs say the Application is removed when the pull request no longer meets the criteria.

Its deletion docs say generated Applications get a finalizer that also deletes their deployed resources, unless you set preserveResourcesOnDeletion to true. Its default polling interval is 30 minutes, as of 30 October 2026. Add its webhook so previews are created and removed as events arrive, not up to half an hour later.

Should you use a hosted platform or build preview environments yourself?

Use a hosted platform when your app already runs there; build your own when your stack lives in your own Kubernetes cluster. The table compares what each documents, as of 30 October 2026.

Preview options compared from their official docs (as of 30 October 2026)
OptionWhat it previewsWhen it is createdTeardown and expiry
VercelYour project, built from each pushEvery push, link commented on the pull requestRemoved later by retention: previews kept 30 days on Hobby, 180 on Pro by default
Netlify Deploy PreviewsYour siteWhen a pull request opens, updated on each pushKept until the deploy is deleted
RenderServices, databases and environment groupsEach pull request, automatic or opt-inOn merge or close, optional expireAfterDays
Argo CD pull request generatorAnything you deploy to KubernetesOn discovery, polling every 30 minutes or by webhookApplication removed when the pull request stops matching
Your own CI workflowAnything your scripts can createOn the events you chooseOnly what your scripts and sweep delete

You can also mix them. The frontend uses a hosted preview, and its link points at a backend preview running in the team's cluster.

In the interview

How do you explain preview environments in a system design interview?

Frame it as a lifecycle with a budget, and spend most of your time on isolation, data and cleanup.

  1. State the problem

    One shared staging server makes changes collide and reviews queue. Each pull request needs its own full copy of the stack.

  2. Draw the lifecycle

    Opened creates, synchronize redeploys, closed deletes. Name everything after the pull request number.

  3. Explain isolation

    One namespace per pull request with a ResourceQuota and a LimitRange. One shared entry point routes by host name.

  4. Explain the data

    Generated seed data in a template database, cloned per pull request. No production data, ever.

  5. Say what you fake

    Payments in test mode, email captured, paid APIs stubbed. The app, database and cache run for real.

  6. Close with cost and cleanup

    Expiry annotations, a nightly sweep, alerts for stuck deletes, and a cap on open previews.

Add one number to sound grounded. For example: thirty open pull requests at Rs 40 a day (made up) is Rs 1,200 a day, so expiry pays for itself quickly.

Questions people ask

What is the difference between a preview environment and staging?

Staging is one long-lived shared environment, while a preview environment belongs to a single pull request and is deleted with it. Staging is good for testing several merged changes together before release. Previews are better for reviewing one change alone, because nobody else's work can break it.

Are preview environments expensive?

They can be, mostly because forgotten previews keep running. Each one is small, but thirty of them running all month adds up. Size caps, an expiry date and a nightly cleanup job keep the bill close to what active reviews actually need.

Can I use a copy of production data in a preview environment?

You should not. Previews are shared by link and guarded less carefully than production, so real customer records there are a privacy risk. Generate realistic fake data with a script instead, using reserved domains like example.com for email addresses. If you truly need production-shaped data, mask it before it ever leaves production.

Why did my GitHub Actions teardown job never run?

A common cause is that closed is not in your types list. By default, pull_request workflows run only for opened, synchronize and reopened. Add closed to the types, then guard the teardown job so it runs only when the event action is closed.

Do preview environments work for pull requests from forks?

Only partly, by default. GitHub does not pass secrets to workflows triggered from forks, and the built-in token is read-only, so deploys that need cloud keys fail. Vercel asks a team member to authorise fork deploys. Avoid working around this with pull_request_target, which GitHub warns against for running pull request code.

Does Kubernetes delete idle namespaces automatically?

No, not by itself. In Kubernetes v1.33, which we tested, a namespace has no expiry field. You need your own cleanup, such as a scheduled job that deletes namespaces whose expiry annotation has passed. The built-in ttlSecondsAfterFinished timer only cleans up finished Jobs.