What are preview environments and where does their cost come from?
A preview environment is a short-lived, full copy of your application deployed automatically for a single pull request and torn down when the PR closes. Reviewers click a link and test the actual change instead of reading the diff and imagining the result. QA can verify behavior before merge, and product or design feedback arrives while the author still remembers the code.
The cost follows a simple formula:
monthly cost = open PRs × cost per environment-hour × hours alive
Most teams try to shrink resources per environment first. Hours alive usually matters more. An always-on environment runs 24×7, but people only use it during working hours. Nights, weekends, and PRs abandoned for weeks all add hours that nobody looks at.
Illustrative estimate (assumed numbers, not a benchmark)
Assume 20 open PRs and $0.15 per environment-hour. TTL cleanup removes stale PRs, which leaves 12 active environments. Sleep schedules keep them up 10 hours a day on 22 workdays.
| Strategy | Envs | Hours/month | Monthly cost |
|---|---|---|---|
| Always-on | 20 | 730 | 20 × 0.15 × 730 = $2,190 |
| TTL + sleep schedule | 12 | 220 | 12 × 0.15 × 220 = $396 |
The cost per environment-hour did not change. The reduction comes entirely from cutting idle hours and orphaned environments.
To judge whether the spend is worth it, compare it to time saved. Count the reviewer and QA hours no longer spent pulling branches locally or chasing bugs after merge. A modest monthly saving in engineering time usually covers the reduced bill. The section on saving engineering time below shows how to work this out.
How do preview environments work?
A typical setup has four stages. Each one is triggered by the Git host and runs without anyone doing anything by hand:
- Build. When a PR is opened or updated, CI builds container images from the PR branch and tags them with the commit SHA. That way every deployment can be traced to exact code.
- Provision. A controller or pipeline job creates an isolated slice of infrastructure for the PR. This is usually a Kubernetes namespace named after the PR number, plus whatever the app needs outside the cluster, such as a database schema, a queue prefix, and a DNS record. The same templates are rendered for every PR, with the PR number filled in, so environments are consistent and disposable.
- Deploy and publish. The images are deployed into that namespace, seed data is loaded, and an ingress rule routes a predictable hostname (for example, one derived from the PR number under a wildcard domain) to the app. Once readiness checks pass, a bot comments the URL on the PR.
- Tear down. When the PR is merged or closed, or its TTL expires, the namespace and every per-PR resource are deleted.
Everything else in this article is about controlling stages 2 and 4. That means deciding which PRs get an environment, how big it is, how long it stays up, and making sure teardown really happens. The next sections cover the lifecycle controller, TTLs, sleep schedules, and shared backing services in detail.
Who should use per-PR environments, and when should you avoid them?
Per-PR environments pay off when reviewing a change requires more than reading a diff. Typical cases:
- Multi-service backends, where a change to one API only makes sense alongside its consumers.
- Teams with frequent UI or API review by product or design.
- Parallel QA, where several testers need isolated data at the same time.
They are rarely worth it for small teams, for monoliths that already start cleanly on a laptop, or for repositories that see a handful of PRs a week. In those cases most of the cost is the platform itself. Someone has to maintain templates, DNS, secrets, seed data and cleanup jobs, and those hours belong in your development cost.
| Option | Isolation | Idle cost | Maintenance burden |
|---|---|---|---|
| Per-PR environments | High | Grows with open PRs | High |
| Few shared staging slots | Medium (booked) | Fixed, low | Low |
| Manually triggered on demand | High when used | Low | Medium |
| Local dev setup | Per developer | None in the cloud | Varies with stack complexity |
If you do adopt them, gate creation:
- Opt-in labels. Only PRs that need review get an environment.
- Path filters. Skip docs-only or test-only changes.
- Per-repo concurrency limits. Queue or reject requests once a cap is reached.
Limits create friction in release weeks, when PR volume spikes and queued requests block reviews. Decide in advance whether release branches bypass the cap. Otherwise engineers will look for ways around it.
#!/usr/bin/env bash
set -euo pipefail
PR_LABELS="${PR_LABELS:-}" # comma-separated, e.g. "preview,frontend"
BASE_REF="${BASE_REF:-origin/main}" # branch the PR merges into
TARGET_BRANCH="${TARGET_BRANCH:-main}"
ACTIVE_ENVS="${ACTIVE_ENVS:-0}" # current preview envs for this repo, from your platform
MAX_ENVS="${MAX_ENVS:-5}" # per-repo cap
case ",${PR_LABELS}," in
*,preview,*) ;;
*) echo "skip: PR is not labelled 'preview'"; exit 0 ;;
esac
changed=$(git diff --name-only "${BASE_REF}...HEAD")
relevant=$(printf '%s\n' "$changed" | grep -Ev '^(docs/|tests?/|.*\.md$)' || true)
if [ -z "$relevant" ]; then
echo "skip: only docs/test files changed"
exit 0
fi
if [[ "$TARGET_BRANCH" != release/* ]] && (( ACTIVE_ENVS >= MAX_ENVS )); then
echo "queued: ${ACTIVE_ENVS}/${MAX_ENVS} preview envs in use"
exit 75 # distinct code so CI can retry later (queue) instead of failing
fi
echo "create: preview environment approved"
A CI gating script that creates a preview environment only for PRs labelled 'preview', skips docs- or test-only changes, and queues requests above a per-repo cap while letting release branches bypass it.
What are the alternatives to per-PR preview environments?
Per-PR environments are one point on a spectrum. The table above summarizes the trade-offs. In more detail:
- Shared staging slots. Keep a fixed pool of long-lived environments, say three or four, that PRs book and deploy into. The cost is fixed and predictable, and the platform is simpler because there is no dynamic DNS, no per-PR IaC, and no cleanup reconciler. The downside is contention. Engineers wait for a free slot, and someone can deploy over a colleague's branch in the middle of a review unless you enforce booking.
- On-demand environments. Use the same tooling as per-PR environments, but creation only happens when someone runs a CI job or comments a command on the PR. Most PRs never get one, so idle cost stays low. You still carry most of the maintenance burden, because templates, DNS, and teardown have to work.
- Local development stacks. A scripted, containerized local setup lets each developer and reviewer run the branch on their own machine. It costs nothing in the cloud, but it only works while the stack fits on a laptop. Non-engineers such as product, design, and support reviewers usually cannot use it.
- Request-routed sandboxes in a shared environment. Deploy only the services a PR changed into a shared baseline environment. Route requests that carry a specific header or cookie to those versions, and let everything else fall through to the baseline. This is much cheaper than full copies for large microservice systems. It requires context propagation through every service and message path, and it gives weaker isolation for shared data.
- Feature flags with staged rollout. Merge behind a flag and review in staging or production with the flag turned on for reviewers. No per-PR infrastructure is needed, but review happens after merge, and flag cleanup becomes its own ongoing chore.
- Frontend-only previews. If most reviewable changes are UI changes, deploy only the static frontend per PR and point it at a shared backend. This is cheap and fast, but backend changes are not covered.
Many teams combine these. They use frontend-only previews by default, opt-in full environments for cross-service changes, and a shared staging slot for release candidates.
How does a PR-driven environment lifecycle work?
A controller sits between the Git host and your infrastructure and turns pull request events into environment operations. Each event maps to one action:
- Create when a PR is opened, or when someone adds a label such as
preview. Opt-in labels keep documentation and dependency-bump PRs from consuming capacity. - Update on each push to the PR branch. The controller redeploys the new image into the existing namespace and does not rebuild the stack, so the URL and seeded data stay the same for reviewers.
- Destroy when the PR is merged or closed. The controller tears down the namespace, removes the IaC-managed resources it created, and releases any per-PR slice of shared services, such as a schema or queue prefix.
Each component owns one part of the state. The Git host owns the truth about which PRs exist. The cluster runs the workloads. Shared services hold the per-PR data. The IaC state records the cloud resources the controller provisioned outside the cluster, such as DNS records, buckets, and IAM roles. The controller's job is to keep these four in agreement.
Webhooks alone cannot do this reliably. Deliveries fail during controller deploys or outages. Some Git hosts give up after limited retries. Branch deletions and force-pushed history can produce sequences the controller never expected. Each missed closed event leaves an environment billing indefinitely.
The fix is a periodic reconciler. On a schedule, it lists every environment the controller manages, queries the Git host for the matching PR, and destroys any environment whose PR is closed or no longer exists. Webhooks provide speed, and the reconciler guarantees that missed events eventually get cleaned up.
+----------------------------------------+
| Git host |
| source of truth: which PRs exist and |
| whether they are open, merged, closed |
+----------------------------------------+
webhook events | ^ periodic reconciler:
(fast, but can | | query PR state for
be missed) | | every managed env
v |
+--------------------------------------------------------------+
| PR env controller |
| opened / label preview -> CREATE env for PR |
| push to PR branch -> UPDATE redeploy image only |
| merged / closed -> DESTROY env, release slices |
| PR gone (reconciler) -> DESTROY orphaned env |
+--------------------------------------------------------------+
| | |
| apply / delete | claim / release | plan / destroy
v v v
+-----------------+ +-------------------+ +-------------------+
| Cluster | | Shared services | | IaC state |
| per-PR | | per-PR schema, | | DNS records, |
| namespace and | | queue prefix, | | buckets, IAM |
| workloads | | seeded data | | roles per PR |
+-----------------+ +-------------------+ +-------------------+
Webhooks from the Git host trigger fast create, update, and destroy actions. A periodic reconciler checks PR state against the environments the controller manages so that missed events still lead to cleanup across the cluster, shared services, and IaC state.
How do you implement TTL cleanup without frustrating reviewers?
Closing a PR is not the only way an environment goes stale. Long-running drafts and abandoned branches can keep a PR open for weeks while nobody looks at the deployment. TTL cleanup handles that case.
Record four facts on the namespace or stack when it is created: creation time, owner, PR number, and an absolute expiry timestamp. Store the expiry as a timestamp rather than a duration so the cleanup job makes a simple comparison and never has to work out intent. A scheduled job lists everything carrying your management label and deletes whatever has passed its expiry.
Reviewers get frustrated when an environment disappears in the middle of a review. The fix is a cheap way to extend expiry, not a way to disable it. A PR comment command or a label such as extend-ttl can push the expiry forward by a fixed amount, and the bot should post the new deadline back to the PR. Avoid offering a "never expire" option. Those exemptions tend to become permanent without anyone deciding they should, and a year later you are paying for twenty environments nobody remembers. If you need exemptions, give them a mandatory end date as well.
Deleting by label means a single mislabeled resource can take down something important. Before the job runs unattended:
- Run it in dry-run mode for a while and compare what it would delete against what you expect.
- Scope its credentials to a dedicated cluster, account, or project, so a bad match cannot reach production.
- Alert on every deletion, and on unusually large batches, before you trust it to act on its own.
#!/usr/bin/env bash
set -euo pipefail
EXPECTED_CONTEXT="preview-cluster" # refuse to run against any other cluster
SELECTOR="app.kubernetes.io/managed-by=preview-env"
DRY_RUN="${DRY_RUN:-true}"
MAX_BATCH="${MAX_BATCH:-10}" # abort if an unusually large set looks expired
[[ "$(kubectl config current-context)" == "$EXPECTED_CONTEXT" ]] || { echo "wrong context, aborting" >&2; exit 1; }
now=$(date +%s)
mapfile -t rows < <(kubectl get namespaces -l "$SELECTOR" -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.annotations.preview\.example\.com/expires-at}{"\t"}{.metadata.labels.preview\.example\.com/pr}{"\n"}{end}')
expired=()
for row in "${rows[@]}"; do
IFS=$'\t' read -r ns expires pr <<< "$row"
# Never delete on missing or malformed data; surface it for a human instead.
if [[ ! "$expires" =~ ^[0-9]+$ ]]; then echo "SKIP $ns: no valid expires-at" >&2; continue; fi
(( expires <= now )) && expired+=("$ns|$pr")
done
if (( ${#expired[@]} > MAX_BATCH )); then
echo "ALERT: ${#expired[@]} namespaces expired at once (limit $MAX_BATCH); not deleting" >&2
exit 2
fi
for entry in "${expired[@]}"; do
ns="${entry%%|*}"; pr="${entry##*|}"
if [[ "$DRY_RUN" == "true" ]]; then
echo "[dry-run] would delete $ns (PR #$pr)"
else
kubectl delete namespace "$ns" --wait=false
echo "deleted $ns (PR #$pr)" # forward this line to your alerting channel
fi
done
A scheduled cleanup script that compares each managed namespace's absolute expiry annotation against the current time and runs in dry-run mode by default. It refuses to run outside the dedicated preview cluster context and aborts without deleting anything when an unusually large batch looks expired.
How do scale-to-zero and sleep schedules reduce idle cost?
A preview environment spends most of its life waiting. Reviewers open it a few times, then it sits untouched overnight and over weekends while still paying for every replica. Scaling deployments to zero removes that compute cost and keeps the namespace, config, and data in place. Two triggers cover most cases: a sleep schedule that scales down outside working hours, and an inactivity window that scales down after a set period with no requests.
Waking requires a proxy or activator in front of the environment's ingress. It buffers the incoming request, scales the deployment back up, waits for readiness probes to pass, and then forwards the request. If the wait runs longer than a few seconds, have the proxy return an "asleep, waking up" page that refreshes automatically. Without that page, a sleeping environment returns a timeout or a 503, and reviewers report it as a broken deploy.
Some components do not wake cleanly:
- Background workers and queue consumers receive no HTTP traffic, so the activator never sees a request for them. Wake them together with the web tier.
- Stateful services add volume attach and cache warm-up to cold start. Leave them running at minimal size, or accept the slower wake.
Illustrative estimate (assumed numbers, not a benchmark)
- Saving = slept hours × hourly env cost. With 118 h/week asleep at $0.50/h, that is $59/week.
- Wake cost = wakes × wait minutes × reviewer rate. With 15 wakes × 1.5 min at $90/h, that is $33.75/week.
The net gain is real but small. At a 4-minute cold start, the wake cost reaches $90/week and sleeping loses money, so shorten cold start before you tighten the inactivity window.
#!/usr/bin/env bash
set -euo pipefail
ACTION="${1:?sleep|wake}"
NS="${2:?namespace}"
KEY='preview.example.com/replicas'
DEPLOYS=$(kubectl get deploy -n "$NS" -l 'preview.example.com/keep-awake!=true' -o name)
if [ "$ACTION" = sleep ]; then
for d in $DEPLOYS; do
replicas=$(kubectl get "$d" -n "$NS" -o jsonpath='{.spec.replicas}')
[ "$replicas" -eq 0 ] && continue
# Remember the original size so wake restores it exactly.
kubectl annotate "$d" -n "$NS" --overwrite "$KEY=$replicas"
kubectl scale "$d" -n "$NS" --replicas=0
done
else
# Wake every Deployment, including queue workers that never receive HTTP
# traffic and would otherwise stay asleep while the web tier comes back.
for d in $DEPLOYS; do
replicas=$(kubectl get "$d" -n "$NS" \
-o jsonpath='{.metadata.annotations.preview\.example\.com/replicas}')
kubectl scale "$d" -n "$NS" --replicas="${replicas:-1}"
done
# Block until readiness probes pass. The proxy serves the 'asleep, waking up'
# page until this returns, then forwards buffered requests.
for d in $DEPLOYS; do
kubectl rollout status "$d" -n "$NS" --timeout=300s
done
fi
A minimal sleep/wake script that scales a preview namespace's Deployments to zero, records their original replica counts in annotations, and on wake restores web and worker Deployments together. It then waits for readiness and leaves StatefulSets running.
Should each PR get its own database, or share backing services?
A full stack per PR gives every branch its own database server, broker, and ingress. That is the most faithful setup, and it is also where most of the per-PR spend goes, because stateful services rarely scale to zero cleanly. The cheaper default is to run only the app containers per PR and point them at shared services:
| Backing service | Full stack per PR | Shared, namespaced per PR |
|---|---|---|
| Database | Dedicated server | One server, a database or schema per PR |
| Message broker | Dedicated instance | One broker, prefixed topics or a vhost per PR |
| Ingress | Load balancer per PR | Shared ingress, wildcard DNS and wildcard TLS cert |
Sharing has costs in isolation. A destructive migration that targets the wrong database or schema can damage other PRs' data. One PR with a connection leak can use up the server's connection limit, so set per-role connection caps. Broker-level configuration changes affect every tenant. Some bugs only show up on a dedicated instance, such as ones involving server settings, extensions, or contention. Make full isolation an explicit opt-in, for example through a PR label, and use it for changes that need it.
Seed environments with small, deterministic fixtures, not production snapshots. Snapshots copy personal data into short-lived, loosely controlled environments, which widens your compliance scope and your breach surface. Fixtures also make reviews reproducible. They have their own costs. Someone has to update them with every schema change, and they miss data-shape bugs: skewed distributions, legacy nulls, very large rows, and the odd encodings that real production data contains.
Right-sizing, cost visibility, and catching orphaned cloud resources
Preview workloads rarely see real traffic, so set CPU and memory requests close to observed idle usage rather than copying production values. Requests determine how many pods fit on a node, and inflated requests are the main reason preview clusters scale out. Add a ResourceQuota to each PR namespace. It caps what one environment can claim and turns a runaway deployment into a scheduling error instead of a surprise on the bill.
Run previews on a dedicated, autoscaling node pool, with taints and tolerations keeping other workloads off it. This lets the pool shrink to near zero overnight. Spot or interruptible capacity is a good fit for environments that reviewers click through. Avoid it for anything running integration tests. An eviction in the middle of a suite produces a flaky failure, and one engineer spending an hour investigating a phantom bug costs more than the compute discount saves.
Attribution and metrics
Label every resource with the PR number, repository, and owning team. Cost tooling and cloud billing exports can only attribute spend to labels and tags that actually exist. Track three numbers: active environment count, average environment lifetime, and orphans found per week. If average lifetime keeps rising, your TTL policy is being bypassed.
Out-of-cluster resources
Buckets, queues, DNS records, and load balancers created by IaC survive namespace deletion. Run a per-PR IaC destroy step in the same teardown pipeline that removes the namespace, and make that pipeline fail loudly if the destroy step errors. As a backstop, schedule a sweep that lists cloud resources tagged with a PR number and flags any whose PR is closed.
How can preview environments save engineering time?
The cloud bill is the visible cost. The case for preview environments rests on engineering time, which is usually the larger number. The savings come from a few specific places:
- Reviewers stop rebuilding branches. Without a preview, reviewing a behavior change means fetching the branch, installing dependencies, running migrations, and seeding data, or skipping all of that and approving based on the diff. With a link on the PR, the reviewer goes straight to testing.
- Non-engineers review before merge. Product, design, and support can check a change themselves instead of asking an engineer to screen-share or waiting for it to reach staging. Feedback arrives while the author still has the context, so fixes are cheaper.
- QA runs in parallel. Each tester works against an isolated environment with known data, rather than queueing for a shared staging slot or debugging state another tester left behind.
- Fewer post-merge regressions. Integration problems that only appear when services run together show up on the PR. Without a preview, they surface in staging after several other changes have landed, which makes the culprit harder to find.
- Shared staging stays stable. When half-finished branches no longer go to staging, it breaks less often, and fewer people lose time to "is staging broken or is it my change?"
To decide whether the trade is worth it for your team, measure these rather than assuming them. Track time from PR open to first review, how often reviewers ask for a demo or screenshots, how long PRs wait for a staging slot, and how many bugs are found after merge that a running environment would have exposed.
Illustrative estimate (assumed numbers, not a benchmark)
Assume 60 PRs a month get a preview environment. Assume each one saves a reviewer 20 minutes of local checkout and setup, and that the team's loaded engineering cost is $90/h.
- Time saved = 60 × 20 min = 20 h/month, worth 20 × $90 = $1,800/month.
- Compare that with the $396/month TTL-plus-sleep bill from the first section.
Subtract the platform's own upkeep. If you assume 8 hours a month maintaining templates, seed data, and cleanup jobs, that is $720/month. The net is still positive under these assumptions. If your actual savings per PR are a few minutes, or the platform needs a large share of an engineer's time, the numbers can flip. That is the signal to fall back to one of the cheaper alternatives above.
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 environments cost, 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.