How to Set Up Preview Environments for Pull Requests Without Wasting Cloud Resources
preview environmentsCI/CDpull requestsdeveloper workflowtestingcloud deployments

How to Set Up Preview Environments for Pull Requests Without Wasting Cloud Resources

AAppCraft Studio
2026-11-15
7 min read

Build pull-request preview environments with isolated data, safe secrets, automatic cleanup, and a repeatable cloud-cost estimate.

Preview environments for pull requests let reviewers test a change in a realistic app before it is merged. This guide shows how to build them without creating uncontrolled cloud spend, unsafe data exposure, forgotten resources, or fragile deployment workflows. You will get a provider-neutral setup process, a repeatable cost estimate, a configuration checklist, and a pull-request review template.

Overview

A preview environment is a temporary deployment connected to a pull request or branch. It usually includes the application, selected environment variables, a test database or database branch, and a URL that reviewers can open. When the pull request is closed or its preview expires, the resources are removed or returned to a low-cost state.

The goal is not to reproduce production perfectly for every change. The goal is to provide enough realism for useful review while keeping the environment isolated, predictable, and disposable. A frontend-only change may need only a deployment and mocked data. A change involving migrations, permissions, or background jobs may require a temporary backend, database, object storage, and authentication flow.

Preview environments work best when each resource has a clear owner and lifetime. Use a naming convention such as pr-184 or feature-checkout-184 across deployments, database branches, logs, and test data. That identifier makes both automated cleanup and manual investigation easier.

Before selecting an app deployment platform, compare how it handles branch deployments, build minutes, runtime resources, environment variables, access controls, logs, and teardown hooks. The details vary between providers, so treat their current documentation and plan limits as inputs to your design rather than assuming that one workflow applies everywhere.

How to estimate

Estimate preview-environment cost by separating fixed resources from usage-based resources. A simple monthly model is:

Estimated monthly cost = active previews × cost per preview × average active time + shared CI/CD cost + data, storage, and observability cost.

For usage-based services, replace the cost-per-preview figure with measurable units:

Usage cost = build minutes + runtime hours + database hours or storage + requests + logs and artifacts.

Record the following values for a representative month:

  • Pull requests opened: Include draft pull requests if they trigger deployments.
  • Average preview lifetime: Measure from creation to merge, closure, or automatic expiration.
  • Concurrent previews: Use the average and the peak. Peak concurrency matters for quotas and database capacity.
  • Resources per preview: List the web service, worker, database branch, storage bucket, cache, and scheduled jobs.
  • Build and test usage: Count installation, build, test, migration, and deployment steps separately when the provider bills them differently.
  • Cleanup success rate: A failed teardown can turn a temporary environment into a recurring charge.

For a quick estimate, use a spreadsheet with one row per resource. Enter the provider's current unit or plan cost, expected usage, and whether the resource is shared or dedicated. Keep an uncertainty column for values you have not measured. After two or three review cycles, replace assumptions with actual deployment, database, and CI records.

Do not count only the visible application URL. A preview that launches a database, object storage, background worker, or monitoring stream can cost more than the web process. Conversely, a static preview may be nearly free beyond build and storage usage. The architecture determines the estimate.

Inputs and assumptions

Branch-based deployment workflow

  1. A developer opens or updates a pull request.
  2. CI validates formatting, tests, dependency installation, and the build.
  3. The deployment platform creates a preview from the pull request's commit, not from an uncommitted local state.
  4. A setup job creates or selects isolated supporting resources using the pull-request identifier.
  5. Seed data and safe configuration are applied.
  6. The deployment URL is posted as a pull-request comment or status check.
  7. Closing, merging, or expiring the pull request triggers teardown.

Make updates idempotent. Running the setup job twice should not create two databases or duplicate seed records. Store the resource identifiers created for each preview so cleanup does not have to guess from names alone.

Temporary databases and seeded data

Choose the lightest isolation level that supports the review. A database branch may be appropriate when the provider supports it and schema changes need realistic behavior. A separate temporary database may be safer when reviewers could modify records or when branch support does not cover the required database features. For simple interface reviews, a local fixture or read-only test dataset may be enough.

Never copy production data into a preview by default. Use synthetic records that exercise empty states, long text, unusual characters, permissions, time zones, failed requests, and representative file sizes. If a sanitized dataset is necessary, document who owns it, how it is refreshed, and which fields are removed or transformed.

Authentication, secrets, and access protection

Use a test identity provider, dedicated test accounts, or a controlled authentication mode. Do not put production tokens, signing keys, payment credentials, or private API keys into preview variables. Separate public configuration from secrets, and grant each preview only the permissions it needs.

Protect non-public previews with an access gate, identity-aware proxy, temporary password, or equivalent control. A preview URL is not a security boundary. Confirm that search indexing is disabled where the platform allows it, but rely on authentication rather than obscurity. Test login, logout, callback URLs, cookie settings, and role-based permissions in the preview itself. For a deeper review of these checks, use the API authentication testing guide and the low-code app security checklist.

Environment variables and background work

Maintain a version-controlled list of required variables, but keep values in the deployment platform or secret manager. Include the preview URL, API base URL, database connection, storage endpoint, authentication callback, and feature flags. Validate required variables during startup so a missing value produces a clear failure.

Disable production schedules, email delivery, payment capture, webhooks, and irreversible jobs. If a preview must run a scheduled task, namespace its data and use a short, explicit schedule. A central scheduler can be preferable to creating one cron job per preview; review scheduling behavior with the guidance in Cron Jobs for Web Apps.

Expiration and teardown

Set an expiration rule based on inactivity or a maximum lifetime. Teardown should run when a pull request closes, when a branch is deleted, and through a periodic reconciliation job that finds expired resources. Make deletion safe: tag resources with the repository, pull-request identifier, owner, creation time, and expiration time. Require extra confirmation for anything that could be production-owned.

Log setup and teardown results. A failed cleanup should create an alert or visible status rather than disappear in CI output. Review resource usage regularly with a cost review process such as the one described in this cloud app cost review template.

Worked examples

Example 1: Frontend preview

Assume a team has 40 pull requests in a month, each preview remains active for two days, and the app is a static or mostly frontend deployment. The estimate should include build minutes, artifact storage, preview requests, and any access-control service. No database branch is created. The main cost-control measures are automatic expiration, avoiding rebuilds for unrelated changes, and deleting old artifacts.

Example 2: Full-stack preview

Assume the same team needs a web service, API, temporary database, seeded records, and an authentication callback for each preview. The estimate now includes runtime hours, database capacity or branch usage, migration and seed jobs, logs, and any worker or storage resource. If previews remain active for five days instead of two, the resource lifetime—not the number of pull requests—becomes the most important variable.

To compare options, calculate both scenarios with the same inputs. If a provider offers shared infrastructure, record the trade-off: lower direct cost may come with slower builds, limited isolation, or more complicated cleanup. If a branch-based database is unavailable, include the operational work of creating, migrating, and deleting separate databases. The cheapest line item is not always the cheapest workflow.

Pull-request review template

Use a consistent comment so reviewers know what was deployed:

  • Preview: URL and commit identifier
  • Access: test account or approved access instructions; never post a secret
  • Data: seed version and notable test scenarios
  • Checks: build, automated tests, migration, and smoke-test status
  • Known limits: disabled email, payments, webhooks, jobs, or third-party integrations
  • Expiration: planned cleanup time and owner for exceptions

When to recalculate

Recalculate the estimate when provider pricing inputs, included quotas, database branching features, deployment limits, or authentication behavior changes. Also review it after a CI/CD migration, a change in pull-request volume, a longer review cycle, or the addition of workers, queues, file storage, observability, or scheduled jobs.

At least every six months, inspect actual preview lifetimes, peak concurrency, build usage, failed teardowns, database growth, and the number of resources with no active pull request. Compare those measurements with your spreadsheet assumptions. Update the expiration policy if environments routinely outlive their reviews, and add reconciliation if manual cleanup is common.

Start with one repository and a narrow resource set. Confirm that setup is repeatable, secrets are isolated, test data is safe, access is protected, and teardown works before enabling previews for every project. Then document the workflow in the repository and make the preview status visible in each pull request. A small, observable preview system is more useful than an ambitious system that the team cannot control.

Related Topics

#preview environments#CI/CD#pull requests#developer workflow#testing#cloud deployments
A

AppCraft Studio

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.