Skip to content

Preview Environments per Pull Request

Ephemeral environments per pull request shorten feedback and make reviews concrete: you click through the change instead of imagining it from the diff.

≈ 11 min readSoftwareDelivery

Preview Environments per Pull Request

“Is staging free?” – this question in the team chat is the real bottleneck. As long as one environment has to serve everyone, the order of the queue decides when someone even gets to see a change. If, instead, every pull request gets its own disposable instance, the relationship flips: the review doesn’t wait for the environment, the environment comes into being with it.

The problem behind the diff#

A review often ends right here: someone opens a pull request, a colleague reads the diff, imagines the behavior that goes with it and writes “LGTM”. That is a guessing game. A diff shows which lines changed – not how the application feels afterward. Whether the new checkout flow is usable on a smartphone, whether the loading state flickers, whether an edge case in the domain is right: none of that is in any git diff.

The classic answer was a shared staging environment. One team, one environment, one queue. If you want to test, you deploy your branch, overwrite the previous one and block everyone else. With two parallel features, that is a source of conflicts; with five, a permanent traffic jam. The actual goal – fast, concrete feedback – gets lost in the coordination.

And the jam is only the visible side. The invisible one is that a shared staging environment never has a defined state: it always carries the leftovers of the last deploy, half-migrated schemas, test data from someone else’s feature. When a reviewer sees something odd there, nobody knows for sure whether it is the current PR or an artifact from yesterday. Exactly this “is it my change or the environment?” eats up time and trust. A freshly spun-up instance doesn’t have this problem – it starts from the same reproducible zero state on every run.

The thesis of this article is simple: every pull request gets its own disposable environment with its own URL. Reviewers click through the running change instead of imagining it. And because the environment is ephemeral, it disappears again on merge – without a cleanup ritual, without a growing bill.

The outcome, not the mechanics#

Before we get to app.json and CI pipelines, it pays to look at the why. The benefit lies in the shorter feedback loop – and that pays directly into measurable delivery performance.

Accelerate (Forsgren, Humble, Kim, 2018) backed this up with data: small batches, short lead time for changes and high deployment frequency are the drivers of high-performing software delivery. A preview environment per pull request pushes exactly there. It rewards small changes – a tiny PR can be deployed in seconds and reviewed in minutes. It lowers the threshold to integrate at all, because feedback doesn’t have to wait for the next staging slot. That fits seamlessly with Trunk-Based Development and with what Humble and Farley described back in 2010 in Continuous Delivery: short-lived branches, fast integration, the PR as the unit of integration.

Perhaps the most underestimated effect is social. As soon as there is a clickable URL, people who don’t set up a development environment can review too: QA, product management, design. A designer who sees the real implementation in the browser gives feedback in five minutes that would otherwise take a meeting and three screenshots. That is the point where a technical feature turns into a delivery advantage.

Conceptually, this is closely related to the build-measure-learn loop from Ries’ Lean Startup (2011). A preview is a concrete artifact you can measure and learn from before anything goes to production. The smaller the batch, the faster the loop can become. Economically, though, an environment per PR only works if provisioning, data, runtime and teardown are under control. Otherwise, the preview merely shifts the friction from the review into operations.

The lifecycle of an ephemeral environment#

The mechanics are the same across all established products – whether Heroku “Review Apps”, GitLab “Review Apps”, Netlify “Deploy Previews” or Vercel’s “Preview Deployments”. The PR is the trigger, the merge is the end.

sequenceDiagram
    participant Dev as Developer
    participant PR as Pull Request
    participant CI as CI Pipeline
    participant Env as Preview Environment
    Dev->>PR: open / push commit
    PR->>CI: trigger build (HEAD commit)
    CI->>Env: deploy isolated instance (own URL + own DB)
    Env-->>PR: post preview URL as commit status
    Dev->>Env: reviewer clicks and tests
    Dev->>PR: push new commit
    PR->>CI: rebuild and redeploy
    Dev->>PR: merge or close
    PR->>Env: destroy environment

The important word is isolated. Instead of one staging environment for everyone, n previews run in parallel – each with its own URL, ideally with its own data layer. The contrast with the old model is the whole point:

graph LR
    subgraph Classic["One staging for all"]
        A[PR 1] --> S[Shared Staging]
        B[PR 2] --> S
        C[PR 3] --> S
        S --> Q[Queue and conflicts]
    end
    subgraph Ephemeral["Preview per PR"]
        D[PR 1] --> P1[preview-1.example.com]
        E[PR 2] --> P2[preview-2.example.com]
        F[PR 3] --> P3[preview-3.example.com]
    end

Declarative instead of a script graveyard#

The most elegant approach describes the environment declaratively instead of assembling it from a chain of shell steps. Heroku shows how with an app.json: everything a review app needs – add-ons, migrations, feature flags – sits in one place, versioned in the repository.

{
  "name": "my-app",
  "environments": {
    "review": {
      "addons": ["heroku-postgresql:hobby-dev"],
      "scripts": {
        "postdeploy": "bundle exec rake db:migrate db:seed"
      },
      "env": {
        "FEATURE_FLAGS": "preview"
      }
    }
  }
}

The appeal lies in the postdeploy hook: every preview gets a fresh database, migrates the schema and loads seed data. This makes the environment reproducible from nothing – and that is exactly what makes it disposable.

If you aren’t on a PaaS like Heroku or Netlify, you build the same pattern yourself with GitHub Actions. The three steps stay the same: build, deploy into an isolated instance, write the URL back into the PR. How the deploy script works internally – whether it talks to a container host, spins up an app on your own platform or ships a static bundle – is secondary for this skeleton; what matters is the clean contract of name, image and host.

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

jobs:
  deploy-preview:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Build and push image
        run: |
          docker build -t registry.example.com/app:${{ github.sha }} .
          docker push registry.example.com/app:${{ github.sha }}

      - name: Deploy preview instance
        run: |
          ./scripts/deploy-preview.sh \
            --name "pr-${{ github.event.number }}" \
            --image "registry.example.com/app:${{ github.sha }}" \
            --host "pr-${{ github.event.number }}.preview.example.com"

      - name: Comment preview URL
        run: |
          gh pr comment ${{ github.event.number }} \
            --body "Preview ready: https://pr-${{ github.event.number }}.preview.example.com"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Teardown is just as important as deployment. A preview that nobody cleans up is not a feature but a cost center. That is why a second workflow belongs with it, cleaning up when the PR is closed:

name: preview-teardown
on:
  pull_request:
    types: [closed]

jobs:
  destroy-preview:
    runs-on: ubuntu-latest
    steps:
      - name: Tear down environment
        run: |
          ./scripts/destroy-preview.sh --name "pr-${{ github.event.number }}"

Whether the deploy target is a Kubernetes namespace, a Heroku app or a static Netlify build doesn’t matter conceptually. The pattern is portable: PR opens, instance comes up, URL lands in the PR, merge cleans up.

Ephemeral environments as a test bench#

An isolated, production-like instance is more than a click-through preview. It is a clean place to run automated checks against a real deployment – not just against mocks. Two examples that prove themselves in practice:

Contract tests with Pact check whether a service still meets the expectations of its consumers. Verified against a real, running PR instance, that is more meaningful than against a stub. And architectural fitness functions, as Ford, Parsons and Kua describe them in Building Evolutionary Architecture (2017), can be armed against the running preview: response times, dependency rules, bundle sizes. This turns the preview into a gate that answers not only “looks good” but “sticks to the rules”.

Feature flags complete the picture. A preview with FEATURE_FLAGS=preview set shows the target state while the same change stays dark in production – review and rollout are decoupled. If you take the flag idea seriously, you can merge a change several times without enabling it and take it live later via a toggle. That reduces long feature branches and fits the trunk-based idea: integrate, make visible, roll out in a controlled way.

The line of thought behind this is the same as with blue-green or canary: you separate “deployed” from “visible to everyone”. In this sense, a preview is a canary for exactly one reviewer – the smallest conceivable rollout stage. Once you have internalized this separation, you no longer think of deployment and release as the same step, and that is one of the most effective reliefs for a team that wants to ship often and calmly.

Where it really hurts#

None of this is frictionless. The hard part is never deploying the web process – it is everything underneath.

The data layer is the hardest. If all previews share one database, they contaminate each other: one PR migrates a schema, another trips over it. A database per PR solves this, but costs provisioning time and money – and every migration has to run cleanly from zero. That, by the way, is an underestimated side effect: if you take previews seriously, you also test your migration path on a greenfield with every PR. Migrations that only work on grown datasets show up immediately here instead of surprising you at the next fresh setup. External services make the picture even sharper: payments, email delivery, third-party APIs must never fire for real from a preview. That takes sandbox modes or stubs, and they have to be configured before the first reviewer clicks – otherwise the preview of a marketing feature accidentally sends real emails to real addresses.

The second perennial issue is the lifecycle. Forgotten environments cost money and drift away from the current state. The teardown on merge or close has to work reliably, supplemented by a TTL or an idle shutdown for PRs that stay open for weeks. A single close event that never fired – say, because a PR was deleted into the void – must not leave an orphaned instance behind, so in addition to event-driven teardown you need a regular cleanup job that sweeps by age or inactivity. And the feedback advantage flips when the build takes ten minutes: cold starts and long pipelines undermine exactly what you build the whole thing for. A fast, aggressively cached build is the precondition for the short loop to stay short at all.

Third, secrets and access. Preview URLs are often public and guessable – pr-42.preview.example.com is not a security boundary. Unprotected, such previews leak unfinished features or real data. Secrets have to be injected securely, access belongs behind basic auth, SSO or password protection. Netlify offers password protection for deploy previews for exactly this reason.

And finally, config skew. A preview is only useful if it is close to production. If it deviates too much, you get the worst of all outcomes: green review, red prod deploy. Then the environment has created trust it couldn’t back up. The countermeasures are unspectacular but effective: pass the same container image through from the preview all the way to production, control configuration consistently through environment variables instead of diverging build paths, and keep the few deliberate differences – sandbox endpoints, smaller resources, active feature flags – visible in one place. The closer the preview is to production, the more a green review is actually worth.

The common thread#

In 2021, preview environments per pull request are common, productized practice – from Heroku through GitLab and Netlify to Vercel. The core is the same everywhere and told in a few sentences: the PR creates an isolated, disposable instance with its own URL, every new commit deploys again, the merge cleans up.

The gain is the shorter and more honest feedback loop. Reviewers judge running behavior instead of lines in the diff. Non-developers can have a say. Small batches are rewarded, the staging jam disappears. That is the Accelerate logic in its purest form: friction out, cycles shorter, quality visible earlier.

Getting started is therefore unspectacular: start with the outcome, not with the platform. The hard questions are the database, the lifecycle and access protection – not deploying the web process. If you solve them cleanly, you get reviews you click through instead of imagining. And that is the difference between “LGTM” and “I’ve seen it”.

Further reading#

Revised and translated from German with the help of AI.