What are preview environments and what actually drives their cost?

A preview environment is a short-lived copy of your application deployed automatically for a single pull request. Reviewers test the actual change in isolation instead of queuing for a shared staging server or finding integration bugs after merge, when they cost more to fix.

The cost model is simple:

monthly cost ≈ concurrent environments × hourly cost per environment × hours alive per month + shared fixed costs

Shared fixed costs include load balancers, DNS, databases, and registries. Concurrency follows from how often PRs open and how long they stay open: PRs opened per day × days each environment lives.

Illustrative estimate (assumed numbers, not a benchmark). Assume a 10-engineer team opens 8 PRs per day, each PR stays open 3 days, and each environment costs $0.20/hour. That gives 8 × 3 = 24 concurrent environments. A month has about 720 hours, or about 176 weekday working hours. Shared fixed costs are excluded below.

Scenario Concurrent envs $/env-hour Hours/month Monthly cost
Baseline, always on 24 0.20 720 $3,456
Halve environment size 24 0.10 720 $1,728
Run only during working hours 24 0.20 176 ~$845
Working hours + previews for half of PRs 12 0.20 176 ~$422

Halving environment size cuts the bill by 2×. Limiting the hours environments run cuts it by roughly 4×, and adding opt-in previews cuts it by about 8×. Shrinking an environment usually takes engineering work, while limiting lifetime and concurrency is a policy decision. Put lifecycle rules in the pipeline from day one, because once idle environments are normal, every cleanup policy you add later looks like a regression to someone.

How do preview environments work?

Most implementations follow the same pipeline, regardless of the platform underneath:

  1. A PR event triggers CI. Opening a pull request, pushing a new commit, or adding a label fires a webhook that starts a pipeline job.
  2. CI builds an artifact for that commit. Typically this is a container image tagged with the commit SHA, so every push produces a distinct, traceable build. The same job can run migrations and seed data.
  3. The pipeline deploys into an isolated scope. On Kubernetes this is usually a namespace named after the PR, such as preview-pr-1234. On a cloud platform it may be a resource group, project or stack. The deploy uses the same manifests or charts as other environments, with overrides for replica count, resource sizes and hostnames.
  4. Routing gives each environment a stable URL. A common pattern is a wildcard DNS record pointing at a shared ingress controller or load balancer. Each preview gets a hostname derived from the PR number, for example pr-1234.preview.<your-domain>, and an ingress rule maps that host to the PR's services. Sharing one ingress avoids paying for a load balancer per PR.
  5. The bot posts the URL on the PR. Reviewers click through from the pull request instead of checking out the branch.
  6. Subsequent pushes update in place. A new commit rebuilds the image and rolls the deployment in the same namespace, so the URL stays the same for the life of the PR.
  7. Closing or merging the PR tears it down. A workflow on the closed event deletes the namespace and any external state, such as a per-PR database schema. A scheduled garbage collector catches whatever that step misses.

Configuration and secrets come from the CI secret store or a cluster-level secret mechanism, scoped so that preview environments never receive production credentials. The rest of this article covers how to keep each of these stages from leaking cost.

Who should use per-PR environments, and when should you avoid them?

Per-PR environments earn their cost when review is the bottleneck. That happens when several feature streams run in parallel and would otherwise queue for one staging slot. It also happens when a change needs hands-on review, such as a UI flow or an API contract a consumer wants to call. The strongest case is reviewers outside the team, like product managers, designers or QA, who can't run the branch locally. For them, a URL on the pull request replaces a meeting or a screen recording.

Skip them when the tooling would cost more than it saves. A small team can spend more hours maintaining provisioning, DNS, secrets and cleanup than it ever lost waiting for staging. A monolith with heavy stateful dependencies is hard to clone, because each copy needs its own seeded database, queues and caches. Low PR volume rarely creates contention, so one shared staging environment is usually enough.

Option Cost profile Isolation Maintenance effort
Shared staging Fixed, low None; changes collide Low
Fixed pool of reusable environments Fixed, capped by pool size Per slot, while leased Medium; lease and reset logic
Per-PR environments Variable; scales with open PRs Full per branch High; lifecycle tooling
Local or remote dev environments Per developer Per developer; hard to share Medium
Feature flags in production Near zero extra infra Logical only; shared data Ongoing flag hygiene

A fixed pool is often the middle ground. It caps spend by design, at the price of occasional waiting.

What are the alternatives to per-PR preview environments?

The table above lists the main options. Each one solves part of the problem that per-PR environments solve, with a different cost and failure mode.

  • Shared staging with a deploy lock. One environment, and a branch claims it for review by taking a lock (a chat command, a label, or a pipeline that refuses to deploy while another branch holds it). Costs stay flat. The drawback is serialization: with several reviews in flight, branches wait, and a branch left deployed blocks everyone else until someone notices.
  • Fixed pool of reusable environments. N pre-provisioned slots that a PR leases, deploys into, and releases on close or after a timeout. Spend is capped at N environments by construction. You need lease tracking and a reset step between tenants so one PR's data doesn't leak into the next PR's review.
  • Frontend-only previews against a shared backend. For changes confined to the UI, build the static frontend per PR and point it at a shared staging API. This is far cheaper than cloning the full stack, but it cannot preview backend or schema changes, and it breaks when the frontend change depends on an unmerged API change.
  • Local or remote development environments. Reviewers run the branch themselves, either on their own machine or in a cloud-hosted dev environment. This works for engineers comfortable with the toolchain. It doesn't help non-engineering reviewers, and setup time is paid per reviewer per review.
  • Feature flags in production. Merge behind a flag and enable it for internal users. This needs almost no extra infrastructure and tests against real data and dependencies. It requires disciplined flag cleanup, and it can't safely exercise destructive changes such as schema migrations before merge.
  • Automated checks instead of manual review. Contract tests, visual regression tests and screenshot diffs posted to the PR cover some of what a reviewer would otherwise click through by hand. They catch regressions they were written for, not new behavior nobody has specified yet.

Many teams combine these: feature flags and automated checks for most changes, and per-PR environments only for the subset that needs hands-on review.

How can preview environments save engineering time?

The time savings come from removing waiting and setup, not from making review itself faster:

  • No staging queue. Parallel branches don't wait for each other or overwrite each other's deploys on a shared environment.
  • No local setup for reviewers. Checking out a branch, installing dependencies, running migrations and starting services is replaced by opening a link. This matters most for reviewers who don't work in the codebase daily.
  • Fewer review round-trips. A product manager or designer who can try the change before merge gives feedback while the author still has context, instead of in a follow-up ticket after release.
  • Integration bugs surface before merge. Configuration, routing and migration problems show up in a deployed environment that unit tests and local runs can miss, and are cheaper to fix on the branch than after they land on the main line.
  • Less "is staging broken or is it my change?" debugging. An isolated environment removes interference from other people's deploys.

Illustrative estimate (assumed numbers, not a measured result). Assume the same team from the cost example opens 8 PRs per day and 4 of them need hands-on review. Assume a reviewer spends 20 minutes getting a branch running locally or waiting for a staging slot, versus 5 minutes with a preview link. That is 4 × 15 = 60 minutes saved per working day, or roughly 20 hours per month at an assumed 20 working days. Against that, assume the preview tooling takes 4 hours per month of maintenance (DNS, secrets, cleanup failures, platform upgrades). On these assumptions the net saving is about 16 engineer-hours per month, which you would then weigh against the infrastructure bill from the first section.

The estimate is sensitive to its inputs. If few PRs need hands-on review, or reviewers already have fast local setups, the savings shrink toward the maintenance cost. That is the same condition under which the previous section recommends skipping per-PR environments. Measure your own inputs, such as how long PRs wait for staging and how often reviewers ask for a demo, before committing to the tooling.

How does a cost-bounded preview lifecycle work?

A bounded lifecycle treats every preview environment as something that must be justified on entry and guaranteed to leave. Each stage closes off a specific way that spend leaks.

  1. Creation policy check. A PR event (opened, labeled, synchronized) is evaluated against rules such as label present, paths touched, or author not a bot. Without this gate, dependency-bump PRs and typo fixes each spin up a full stack.
  2. Concurrency cap. Even justified requests queue once the cap is reached. Without a cap, cost scales with team activity rather than with a number you chose.
  3. Provisioning into an isolated namespace or resource group, with tags. Isolation means teardown is a single delete of the container, not a hunt for orphaned volumes, load balancers and DNS records.
  4. Scaled-down runtime. The environment runs with one replica and small requests. It exists for review, not load.
  5. Idle TTL to zero. If nobody has hit the environment within the idle window, workloads scale to zero. Weekends and stalled reviews stop billing compute.
  6. Teardown on close or merge. This is the normal exit path.
  7. Periodic garbage collector. Webhooks get dropped and pipelines fail mid-run. The collector deletes anything past its expiry or whose PR is no longer open. Without it, every missed event becomes a permanent line item.

The tagging scheme

Tag each environment with five values:

  • pr-number
  • repo
  • owner
  • created-at
  • expires-at

The garbage collector selects on expires-at and pr-number/repo. Cost reports group by repo and owner. Audits reconstruct who created what and when. Because one set of metadata drives all three, they cannot drift apart. An untagged resource is itself a signal, and the collector should flag it rather than ignore it.

 PR event (opened / labeled / synchronize / closed / merged)
        |
        v
+------------------------+  reject   +---------------------------+
| 1. Creation policy     |---------->| no env: bot author, docs- |
|    label/paths/author  |           | only change, label absent |
+------------------------+           +---------------------------+
        | allow
        v
+------------------------+  cap hit  +---------------------------+
| 2. Concurrency cap     |---------->| queue until a slot frees  |
+------------------------+           +---------------------------+
        | slot free
        v
+--------------------------------------------------------------+
| 3. Provision isolated namespace / resource group             |
|    tags: pr-number  repo  owner  created-at  expires-at      |
+--------------------------------------------------------------+
        |
        v
+------------------------+  idle > TTL  +------------------------+
| 4. Scaled-down runtime |------------->| 5. Scaled to zero      |
|    1 replica, small    |<-------------|    (compute stops)     |
+------------------------+  on request  +------------------------+
        | PR closed / merged
        v
+------------------------+  missed  +-----------------------------+
| 6. Teardown: one       |<---------| 7. Periodic GC (backstop):  |
|    delete of ns / RG   |  events  | expires-at passed or PR not |
+------------------------+          | open; flags untagged items  |
                                    +-----------------------------+
  Same tags drive: GC selection | cost reports (repo, owner) | audit

A cost-bounded preview lifecycle: policy and concurrency gates control entry, a tagged isolated namespace runs scaled down and idles to zero, and teardown on close/merge is backed by a tag-driven garbage collector.

How do you decide which pull requests get a preview environment?

The cheapest preview environment is the one you never create. Building one for every pull request treats a typo fix and a schema migration the same way. A creation policy keeps spend tied to actual review needs.

Make creation opt-in through a trigger the author controls, such as a preview label or a /preview comment. Layer automatic filters on top of that trigger:

  • Skip draft PRs. The code is still changing, so any environment built now will be rebuilt on the next push. Create the environment when the PR is marked ready for review.
  • Skip docs-only changes. If every changed path matches docs/** or *.md, a running backend shows the reviewer nothing new.
  • Decide on dependency-bot PRs explicitly. These bots can open many PRs a week. A reasonable rule is no preview for patch bumps, and a preview for major-version bumps of runtime dependencies, where behavior changes are most likely.

In the workflow, this becomes one condition on the deploy job. The job runs when the PR is not a draft, carries the preview label, and touches at least one path outside the docs filter. The example below shows the shape.

The trade-off is real. Opt-in lowers spend, but authors forget to add the label, so some changes that needed a preview will ship without one. Reduce that gap by making the trigger cheap to use:

  • Auto-apply the label when a PR touches high-risk paths such as migrations/ or api/.
  • Have the bot post a one-line hint on unlabeled PRs explaining how to request a preview.
name: preview-environment

on:
  pull_request:
    # 'labeled' covers adding the label later; 'ready_for_review' covers draft -> ready.
    types: [opened, synchronize, reopened, labeled, ready_for_review]
    # Docs-only changes: if every changed file matches these patterns,
    # the workflow does not run at all.
    paths-ignore:
      - 'docs/**'
      - '**/*.md'

concurrency:
  group: preview-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  deploy-preview:
    # Opt-in policy:
    #  - never for draft PRs (code is still moving)
    #  - only when the author (or an auto-labeler) applied 'preview'
    #  - dependency-bot PRs are skipped unless a human adds 'preview',
    #    e.g. for a major bump of a runtime dependency
    if: >-
      github.event.pull_request.draft == false &&
      contains(github.event.pull_request.labels.*.name, 'preview') &&
      (github.event.pull_request.user.login != 'dependabot[bot]' ||
       github.actor != 'dependabot[bot]')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # Placeholder for your own deploy script; the name is derived from the PR number.
      - name: Deploy preview
        run: ./scripts/deploy-preview.sh "pr-${{ github.event.pull_request.number }}"

A GitHub Actions workflow that deploys a preview only for non-draft PRs that carry the preview label and change files outside docs. Dependency-bot PRs get a preview only when a human applies the label.

How do you implement TTL cleanup that doesn't leak resources?

Cleanup works best as three independent layers, so a failure in one is caught by the next.

1. Delete on close or merge. The CI workflow that handles the PR closed event tears the environment down. This is fast and catches most cases, but webhooks get dropped and pipelines fail partway through teardown.

2. Idle TTL. Stamp each namespace with labels preview=true, pr=1234, and repo=api (labels are selectable), plus annotations preview/last-commit-at and preview/expires-at (timestamps aren't valid label values). Refresh them on every push, or from ingress access logs if you want "last viewed" semantics.

3. Scheduled garbage collector. A CronJob lists namespaces with preview=true and deletes any whose expires-at has passed or whose PR is no longer open per the Git host's API. The manual equivalent is kubectl delete namespace -l preview=true,pr=1234. Run the job with a dry-run flag first. It should log what it would delete and leave a week of output for review before you enable deletion.

Failure modes to guard against:

  • Overly broad matchers. Never select on preview=true alone outside namespaces. A shared database or DNS zone carrying that label will be destroyed.
  • Untagged children. Resources created by operators or controllers often don't inherit labels. Examples include cloud load balancers, volumes, and DNS records. Have the GC also query the cloud provider by tag or naming convention.

TTL length is a trade-off. A 24-hour TTL frustrates reviewers returning after a weekend. An "extend" label or command fixes that but adds state to track. It also gets applied to every PR by habit. If you add one, cap the number of extensions allowed.

#!/usr/bin/env bash
set -euo pipefail

DRY_RUN="${DRY_RUN:-true}"
now=$(date -u +%s)

kubectl get namespaces -l 'preview=true,pr' -o json \
  | jq -r '.items[] | [.metadata.name, (.metadata.annotations["preview/expires-at"] // "")] | @tsv' \
  | while IFS=$'\t' read -r ns expires; do
      # Missing or unparseable expiry: report it for a human, never auto-delete.
      if [[ -z "$expires" ]]; then
        echo "WARN  $ns: no preview/expires-at annotation, skipping"; continue
      fi
      if ! exp=$(date -u -d "$expires" +%s 2>/dev/null); then
        echo "WARN  $ns: bad expires-at '$expires', skipping"; continue
      fi

      (( exp < now )) || continue

      if [[ "$DRY_RUN" == "true" ]]; then
        echo "DRY   would delete namespace $ns (expired $expires)"
      else
        echo "DEL   namespace $ns (expired $expires)"
        # --wait=false so one namespace stuck on finalizers doesn't stall the sweep.
        kubectl delete namespace "$ns" --wait=false
      fi
    done

A dry-run-by-default garbage collector that finds preview namespaces by label, reads the expires-at annotation, and deletes only expired namespaces that carry both required labels.

How can you shrink each environment with scale-to-zero and shared state?

A TTL bounds how long an environment lives. The next lever is how much each one costs while it is alive.

Run one replica per service, with small resource requests and modest limits, as in the example below. Requests determine scheduling and therefore node count. Previews sit idle most of the day, so production-sized requests reserve capacity that nobody uses. Scale deployments to zero outside working hours with a scheduled job. Where the platform supports request-based activation, wake the environment on the first hit. Reviewers pay for this. The first request waits for scheduling, image pull and application warm-up, which can take tens of seconds for heavier runtimes. Say so in the PR comment so a slow first load isn't filed as a bug.

Stateful services are usually the largest per-environment cost. Run one shared database instance and give each PR its own schema or database, named from the PR number and seeded from small fixtures (see the snippet below). Drop it in the same teardown step that deletes the namespace. Stub third-party APIs and heavy downstream services, or point every preview at one shared instance.

Choice What it saves What it risks
Shared DB, per-PR schema One instance instead of N A migration that touches shared objects (extensions, roles) can break other PRs
Stubbed dependencies External calls and per-PR infrastructure Integration and configuration bugs stay hidden
Small fixtures Seed time and storage Slow queries and pagination bugs only show up at realistic volume

Treat a green preview as evidence that the feature works, not that it performs. Keep a staging environment with real dependencies for the cases a small preview can't cover.

#!/usr/bin/env bash
set -euo pipefail

PR_NUMBER="${1:?usage: $0 <pr-number>}"
[[ "$PR_NUMBER" =~ ^[0-9]+$ ]] || { echo "invalid PR number" >&2; exit 1; }

NS="preview-pr-${PR_NUMBER}"
SCHEMA="pr_${PR_NUMBER}"
DB_URL="${PREVIEW_DB_URL:?set PREVIEW_DB_URL}"

kubectl -n "$NS" scale deployment/web --replicas=1
kubectl -n "$NS" set resources deployment/web \
  --requests=cpu=50m,memory=128Mi \
  --limits=cpu=500m,memory=512Mi

psql "$DB_URL" -v ON_ERROR_STOP=1 \
  -c "DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE" \
  -c "CREATE SCHEMA ${SCHEMA}"

PGOPTIONS="-c search_path=${SCHEMA}" \
  psql "$DB_URL" -v ON_ERROR_STOP=1 -f db/schema.sql -f db/fixtures/small.sql

A provisioning script that pins a preview deployment to one replica with small CPU and memory requests, then creates and seeds a per-PR schema on a shared PostgreSQL instance, with the matching teardown and off-hours scale-down commands noted.

What guardrails and visibility keep preview environment costs from creeping up?

Cost overruns rarely come from one large environment. They come from many small ones nobody is watching, so the first guardrail is a hard ceiling. Cap concurrent previews per repo or team, and back it with a Kubernetes ResourceQuota on each preview namespace (or a per-project quota at the cloud level). The concurrency cap limits how many environments exist. The quota limits how large any single one can grow. Add a budget alert on the account or project as the backstop for whatever slips past both.

Decide in advance what happens when the cap is reached:

Policy Developer experience Cost risk Best when
Queue PR waits, no failure Lowest Previews are nice-to-have
Evict oldest idle Someone loses an environment Low Most previews sit untouched
Refuse with PR comment Clear, immediate feedback Lowest Caps are rarely hit

Caps hurt most during release weeks, when every team needs a preview at the same moment. Raise them temporarily on a schedule instead of letting people request ad-hoc exceptions.

Monitor the costs that sit outside the namespace:

  • Unattached volumes and snapshots
  • Per-environment load balancers and public IPs
  • Log and metric ingestion from noisy previews
  • Image build minutes
  • Cross-zone and egress traffic

Show developers what their environments cost. Post the age, expiry time, and estimated cost on each PR, and send a weekly spend report per repo. This attribution is only as accurate as your tag coverage. Untagged load balancers and snapshots will not show up in any report, so treat a missing tag as a failed deploy.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to preview environment costs, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.