Skip to content

Environments, Deploys and Rollbacks

Summary

Covers local, staging and production environments, hosting platforms, builds, deploy checklists, rollbacks and protecting work in flight during a deploy.

Concepts Covered

This chapter covers the following 22 concepts from the learning graph:

Concept Concept Impact Score
Environment 88
Local Environment 1
Staging Environment 12
Production Environment 74
Environment Parity 11
Hosting Platform 62
Vercel 1
Railway 1
Platform Secret Store 3
Domain and DNS 1
Deploy 55
Build Step 3
Dev vs Production Build 2
Dev-Only Code in Production 1
Deploy Config in Git 11
Preview Deployment 11
Rollback a Deploy 10
Deploy Checklist 10
In-Flight Work at Deploy 7
Graceful Shutdown 3
Job Queue 3
Feature Flag 1

Prerequisites

This chapter builds on concepts from:


The Dress Rehearsal

Think of a small-town theater putting on a play. For six weeks the cast rehearses in a church basement. They read from scripts, stand in for doors with folding chairs, and stop every few minutes to argue about a line. Nobody minds when things go wrong down there. That is what the basement is for.

The week before opening, they move to the real stage for the dress rehearsal. Now there are costumes, lights, the finished set and the stairs the actors will climb. Things go wrong that never went wrong in the basement. A costume change takes forty seconds when the scene allows twenty. A spotlight lands a foot to the left of the actor. The front door of the set sticks. Each of these is cheap to fix on Tuesday night, with nobody in the seats.

Rehearse Before Opening Night

Sawyer waving welcome Every push to main can reach your members within minutes. This chapter gives you a place to rehearse, a way to undo a bad deploy, and a way to ship without cutting off a scan halfway. Most deploys are gates you can walk back through. You'll learn to spot the few that aren't.

On Friday the audience arrives. From now on, every mistake happens in front of people who paid to be there. The stage crew learns a second lesson, too. When the set needs changing, they wait for the lights to go down between scenes. Nobody carries a sofa across the stage while two actors are mid-sentence.

The theater has three places where the play runs, and each one is there to catch a different kind of mistake. It also has a rule about changing things while the show is running. Your app needs the same three places and the same rule. This chapter covers both.

Three Places Your App Runs

An environment is one complete, separate copy of everything your app needs to run: the code, the server, the database, the secret keys and the outside services it calls. Two environments can run the same code and behave differently, because they connect to different databases, use different keys and serve different people. When something works "on my machine" and fails for members, the code is usually the same and the environment differs. Most apps need three.

The local environment is the copy that runs on your own computer while you and your agent build. It's the church basement. It usually runs a development server that reloads the page the moment code changes, it uses a database on your laptop or a small test database, and only you can reach it. Mistakes here cost seconds.

The staging environment is a private copy that runs on the same kind of servers as the live app, set up the same way, used only for testing before a change reaches members. It's the dress rehearsal. Staging has its own database of made-up data and its own keys, so a test payment can't charge anyone and a test scan can't touch a member's photos. It catches the mistakes that show up only on the real stage. A setting exists on your laptop but not on the server. A build breaks when it's packaged. A database change is fine on ten rows and stalls on ten thousand.

The production environment is the live copy members use, with their accounts, photos and payments. It's opening night. Every mistake here reaches a person. You change it only on purpose, through a deploy, and you watch it after every change.

Question Local Staging Production
Who can reach it? Only you You and anyone you invite Members and the public
What data does it hold? Made-up data Made-up data shaped like members' data Members' data
Which keys does it use? Test keys Test keys, set on the server Live keys
How is the code run? Development server, reloads on change Production build, same as live Production build
What does a mistake cost? A few seconds A few minutes Harm to a member
How often does it change? Every few seconds Whenever you want to test Only through a deploy

The Running Example: Two Environments, Not Three

The dating-safety app launched with two environments. The builder worked locally with the agent, and when a change looked right, it went straight to production. There was no staging. That was one of the gaps found later.

Skipping staging is common, and for a while it works. Most changes are gates in the Chapter 1 sense, cheap to get wrong and fix: a button label, a page layout. If one breaks in production, it's fixed in minutes. The load-bearing walls are different: how scans are scored, a new payment flow, a database migration. Without staging, those get tested for the first time with members in the seats.

Here is what a staging environment for the dating-safety app would hold.

Part Production Staging
Express server The live server A second copy of the same server, from the same code
Postgres database Members' accounts and scans A separate database with made-up members and scans
Photo storage Private bucket with members' photos A separate private bucket with sample photos the builder owns
Stripe Live keys, real charges Stripe test-mode keys; test card numbers, no real money
AI and search vendors Live keys Separate keys with a low spending cap, or the vendor's sandbox if it has one
Text-message vendor Sends to members Sends only to the builder's own number, or is turned off
Web address The app's main domain A separate address such as staging. in front of the domain

Notice the last three rows. Staging should be as close to production as possible, but it must never reach a member, a member's data or a member's money. A staging copy that can text members can harm them as production can, and nobody is watching it.

Tell your agent

"List every environment this app runs in today, and for each one tell me which database, which storage bucket, which Stripe keys and which vendor keys it uses. If any two environments share a database, a bucket or a live key, flag it. Then write a plan for a staging environment that matches production but can't reach any member's data or money. Don't create anything yet."

Where the App Lives: Hosting Platforms

A hosting platform is a company that runs your app's code on its servers, gives it a web address, and looks after the machines underneath. You connect it to your GitHub repository and tell it how to build and start the app. It packages your code, runs it, restarts it when it crashes, and sends web traffic to it. Two platforms come up often with apps built by AI agents.

Vercel is built mainly for front ends and server functions: small pieces of server code that start when a request arrives and stop when they've answered it. A Vercel function can run for up to five minutes by default, and longer on paid plans. But it ends with its request, so Vercel is not the place for a server that stays running or a background worker. It's a good fit for a React or Next.js site. Vercel builds a fresh copy of the site for every push to GitHub, which matters later in this chapter.

Railway runs long-lived servers and databases side by side. An Express server that stays running, a Postgres database and a background worker can all live in one Railway project. The dating-safety app's server and database run on Railway. Railway also lets one project hold more than one environment, so staging can sit next to production with its own database and settings.

Both platforms give you three tools the rest of this chapter relies on.

The first is the platform secret store: the screen in the platform's dashboard where you set environment variables (Chapter 6) for each environment, so live keys sit on the platform rather than in your code. The store is per environment. On Vercel you set a value for Production, Preview and Development separately; on Railway each environment has its own variables. That's how staging gets Stripe's test keys and production the live ones, from the same code.

The second is your own web address. A domain is the name people type to reach your app, and DNS, the Domain Name System, is the internet's address book that turns that name into the location of a server. You buy a domain from a registrar, a company that sells domain names. Then you add a DNS record, which the platform gives you, pointing the name at the platform. You can point part of it, such as staging., at a different environment. DNS changes can take minutes to hours to reach everyone, so set up a new address well before launch day.

The third is the deploy itself.

Mapping the Running Example

Here is where each part of the dating-safety app lives, and what the builder would need to rebuild it if the hosting account vanished tomorrow.

Part Where it runs Where its settings live
Express server and React front end Railway service Start command, build command and health check set in the Railway dashboard
Postgres database Railway database Connection string in the Railway secret store
Photos Private storage bucket Bucket name and keys in the Railway secret store
Live keys for Stripe and eight vendors Railway secret store Only in the dashboard
Domain Registrar, pointed at Railway by DNS DNS records at the registrar

Every setting in the right-hand column lives only in a dashboard, none of it in git. If someone changes the start command by mistake, nothing records the old value. The section on deploy config fixes this.

Tell your agent

"Make a table of every place this app runs: hosting platform, database, storage, domain registrar and every outside vendor. For each one, list the settings that live only in a dashboard and not in this repository. Write the table to docs/hosting.md, with variable names only and never their values."

Keeping Environments Alike

A dress rehearsal on a different stage, with different stairs and a different door, would miss the mistakes it was meant to find. Environment parity is how closely your environments match in everything except their data and keys: the same code, the same build, the same versions of the language and database, the same settings. Every difference is a place where a bug can pass staging and still reach members. Some differences are on purpose, such as made-up data and a smaller server. The dangerous ones are those nobody chose.

Five Ways Environments Drift

Here are five common differences between a laptop, staging and production, with the bug each can hide. They are illustrative, not from the dating-safety app's history. (Node is the program that runs your server's JavaScript.)

Difference How it creeps in What it hides
Node version The laptop updated itself; the platform still runs an older default Code that uses a newer feature works locally and crashes on the server
Postgres version Local database installed last year; production upgraded A query that behaves differently on the newer version
A missing environment variable The agent added a new key to the local .env and nobody added it to the platform The feature works locally and fails in production with "undefined"
Dev server instead of a build Locally the app runs through the development server; production runs the packaged build Anything that breaks only when the code is packaged
Data size Local database has ten scans; production has a hundred thousand A page or migration that's fast on ten rows and stalls on many

The fixes are small and mostly one-time. Pin the Node version in the repository so every environment reads the same number. Use the same major version of Postgres everywhere. Keep a list of required environment variables in the code, and have the server refuse to start when one is missing. Chapter 6 covers that check. Run the production build in staging, never the development server. Fill staging with enough made-up data to make slow queries show up.

Parity is never perfect. Good enough parity means every difference between staging and production is one you chose and wrote down.

Tell your agent

"Compare this app's local setup with production: the Node version, the Postgres version, the environment variables the code reads, and how the app is started. Tell me which variables exist locally but not in production. Then show me a plan to pin the Node version in the repository and make the server refuse to start when a required variable is missing. Don't change anything until I approve, and check that production has every required variable before that start-up check goes live."

What Happens in a Deploy

A deploy is making a new version of your code the version that runs in an environment. Usually it means a deploy to production, the moment your change reaches members. On Railway and Vercel a deploy usually starts on its own when you push to the main branch on GitHub, so treat every push to main as a change to production. Here are the steps, in order, for a server like the dating-safety app's on Railway.

  1. You push. New commits land on the main branch in GitHub.
  2. The platform notices and fetches the new code.
  3. The build step runs. The platform installs packages and packages the code (more on this below).
  4. The new version starts next to the old one. The old one is still serving members.
  5. The health check runs. The platform calls a page on the new version, often /health, and waits for an answer that says the server is up.
  6. Traffic switches. New requests go to the new version.
  7. The old version is told to stop. The platform sends it a signal and, after a short wait, shuts it down.
  8. You watch. Errors, logs and alerts tell you whether members are fine. Chapter 12 covers how.

If the build fails at step 3, or the health check fails at step 5, the platform keeps the old version running and members never notice. That safety net only catches failures loud enough to stop the server. A change that starts cleanly and quietly gives wrong answers passes all eight steps.

The Build Step

The build step is the stage of a deploy that turns your source code into the files that run. For the dating-safety app, it installs every package listed in package.json, then runs Vite, which turns the React code into a few small files the browser can load quickly. The server sends those built files to members' browsers.

Many deploy failures show up here. A file is imported as Header.tsx but saved as header.tsx; a Mac forgives the difference in capital letters and the platform's Linux build server doesn't. A type error the development server ignored stops the build, if the build script runs the TypeScript checker first, as most Vite starter projects do. Each is a reason to run npm run build locally, or in staging, before you push to main.

You can step through a deploy in the diagram below.

Diagram: A Deploy, Step by Step

Run the A Deploy, Step by Step MicroSim Fullscreen

A Deploy, Step by Step

Type: workflow sim-id: deploy-step-by-step
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain what each of the eight steps of a production deploy does, by naming the step at which each of four given problems would be caught or would slip through.

Prerequisites: deploy, build step, health check, production environment, graceful shutdown (deploy, build step and health check are defined in the section "What Happens in a Deploy"; graceful shutdown is introduced by name there and defined in "Work in Flight").

Evidence of Mastery: After exploring the flow, the learner answers four questions, each naming one problem and offering the eight steps plus "None: it slips through" as choices. An answer is correct when it matches the answer in Content. Mastery is 4 of 4 correct. Clicking steps to read their infoboxes is exploration, not evidence.

Misconceptions: (1) If the deploy finished, the change works. (2) The health check tests whether the app gives correct answers. (3) The old version is gone the moment you push.

Instructional Rationale: Explaining a process means knowing what each step can and can't catch. Asking the learner to locate where a specific problem is stopped, or to see that nothing stops it, tests that knowledge directly rather than recall of the step names.

Content:

Nodes, in order, each with the infobox text shown when clicked:

# Node label Infobox text
1 Push to main New commits reach the main branch on GitHub. On most platforms this starts a production deploy on its own.
2 Platform fetches code The hosting platform sees the new commit and downloads it.
3 Build step Packages are installed and the code is packed into the files that will run. A build error stops the deploy here, and the old version keeps running.
4 New version starts The new version starts next to the old one. Members are still using the old one.
5 Health check The platform calls a page such as /health on the new version. If it doesn't answer with success, the deploy stops and the old version keeps running. It checks that the server is up, not that its answers are right.
6 Traffic switches New requests go to the new version.
7 Old version stops The platform signals the old version to stop and force-stops it after a short wait. Work still running in the old version is lost unless it shuts down gracefully or the work lives in a job queue.
8 Watch Errors, logs and alerts show whether members are fine. A rollback starts from here if they aren't.

Edges: 1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 6, 6 to 7, 7 to 8. A side branch from 3 labeled "build fails" and a side branch from 5 labeled "check fails" each lead to a node "Old version keeps running." A side branch from 8 labeled "something is wrong" leads to a node "Roll back to the previous deploy."

Extra nodes and their infobox text: "Old version keeps running": "Members never notice a failed build or a failed health check." "Roll back to the previous deploy": "The platform runs the last good build again. Code goes back; database changes don't."

Questions, in this order:

# Problem Correct answer Why (feedback)
1 A file is imported as Header.tsx but saved as header.tsx, so the Linux build server can't find it 3. Build step The build fails, so the deploy stops and the old version keeps serving members.
2 The server crashes on startup because an environment variable is missing 5. Health check The new version never answers the health check, so traffic never switches to it.
3 A scan that started two minutes before the deploy is cut off halfway 7. Old version stops The old version is force-stopped with the scan still running inside it.
4 A change to the scoring code makes every score 10 points too high None: it slips through The server starts and answers the health check. Only watching, tests or a member will reveal it.

Provenance: The steps describe the usual deploy flow on hosting platforms such as Railway and Vercel, as given in the section "What Happens in a Deploy." Problem 3 comes from the dating-safety app (a deploy killed scans in flight, research/seed-notes.md). Problems 1, 2 and 4 are illustrative and must be labeled "illustrative."

Rules: Each question has exactly one correct answer from the nine choices (the eight steps plus "None: it slips through"). Every node is clickable and shows its infobox text. Edge meanings appear as edge labels, not as clickable edges.

Learner Activity:

  1. The learner sees the full flow and clicks any node to read its infobox.
  2. The learner opens the questions and answers each by choosing a step or "None: it slips through."
  3. After each answer, the chosen step and the correct step are marked in the flow and the Why text is shown.
  4. The learner should notice that only two steps stop a bad deploy on their own, and both stop only loud failures.

Feedback: Four questions, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. The answer is [correct answer]. " followed by the Why text. If the learner picks step 5 for question 4, add: "The health check asks whether the server is up, not whether its answers are right." A count "Correct: n of 4" is shown.

Starting State: The full flow is shown with no node selected. The prompt reads "Click each step. Then decide where four problems would be caught."

Chapter Anchors: The chapter lists eight deploy steps in this order: push, fetch, build step, new version starts, health check, traffic switches, old version stops, watch. A failed build or failed health check leaves the old version running. A change that starts cleanly and gives wrong answers passes all eight steps.

Dev Versus Production Builds

Your app is built two ways, and the split between a dev vs production build exists because the two have opposite goals. A development build, made by the development server while you work, reloads on every change, shows detailed error screens and loads extra tools that help you debug. A production build, made for members, is packed small, with those tools left out and detailed errors hidden.

Vite knows which one it's making. A plugin (an add-on that extends Vite) can be marked in vite.config.ts to apply only while serving in development, and code can check import.meta.env.DEV to run only in development. Without those guards, the development tools ride along into the production build.

When Dev-Only Code Reaches Members

Dev-only code in production is any tool, plugin, script or setting meant for the builder's eyes that ends up in the version members use. It's easy to miss because nothing crashes. The extra code runs for every member, unseen.

The dating-safety app had this gap: development plugins in the Vite config were shipped to members' browsers. To see why that matters, picture a hypothetical one: a session-capture script, which records what a person clicks and types so a developer can replay it while debugging. On a laptop, that's handy. In a dating-safety app, it would watch members while they upload photos and describe a match, which no member agreed to. Chapter 8's rule of collecting only what you need would apply to every byte.

The fix has two parts. Mark every development plugin and debugging script to load only in development. Then add a check that fails if the production build contains a name it shouldn't, so the fix can't quietly come undone. Chapter 17 shows how to run that check on every push.

Tell your agent

"Run a production build of this app. List every plugin in the Vite config and every script that loads in the browser, and tell me which ones are meant only for development. Show me that list before changing anything. Once I approve, make each development-only plugin and script load only in development, rebuild, and search the built files in dist/ to show me none of them are there."

Deploy Config in Git

Every hosting platform needs a few settings to run your app: the build command, the start command and the health check page. It also needs to know how much memory the app gets, which region (part of the world) it runs in, and how long to wait before force-stopping an old version. Together these are the deploy config.

They usually get set by clicking through the dashboard, and they stay there. A dashboard has no history. If someone changes the start command, nothing records what it was, who changed it or why. A new staging environment means copying every setting by hand, and moving platforms means rebuilding them from memory.

Deploy config in git means keeping those settings in a file in your repository, so they get the same history, review and undo as your code. Railway reads railway.json or railway.toml; Vercel reads vercel.json. When the file exists, the platform uses it on every deploy. Secrets still stay in the platform secret store; the file holds settings, never keys.

Moving Deploy Config Into Git

The dating-safety app's deploy config was not in git. Its start command, build command and health check lived only in the Railway dashboard. Here is the move, in four steps.

  1. Write down what's there. Ask the agent to list every setting on the Railway service's settings page: build command, start command, health check path and timeout, restart policy (what to do when the app crashes), region. Copy each value as it is today.
  2. Put them in a file. The agent writes a railway.json at the root of the repository with those same values. Nothing changes yet. The file only describes what's already true.
  3. Deploy and compare. Push the file to a branch and deploy it to staging, or to production if there's no staging yet. Open the Railway dashboard and check that every setting now reads from the file and matches the old value.
  4. From now on, change the file, not the dashboard. A new health check path or a longer shutdown wait is a commit with a message, reviewed like any other change.

After this, when something breaks, the git history shows whether a setting changed, when, and why.

Tell your agent

"List every setting on this app's hosting platform that isn't in the repository: build command, start command, health check, restart policy, region, and anything else on the settings page. Write them into the platform's config file (railway.json for Railway, vercel.json for Vercel) with the values exactly as they are now. Don't change any value. Then tell me how to confirm the platform is reading the file."

Preview Deployments

A preview deployment is a temporary copy of your app built from one branch or pull request and given its own web address, so you can click through a change before it's merged. Vercel makes one for every push to a branch other than the production branch and posts the link on the pull request. It keeps old previews for a while, so a link can keep working after the merge. Railway can make a short-lived environment for each pull request and deletes it when the pull request is merged or closed.

Chapter 5 showed how to review a diff. A preview shows you what that diff does. For a builder who judges screens faster than code, that's often the better review: open it on your phone, run a scan with sample data, send the link to a friend.

A preview is also an environment, so ask which database and which keys it uses. A preview on production's environment variables is your code connected to members' data, at an address nobody is watching.

A Preview That Touches Production

Here's how that can happen, as a hypothetical. A builder sets up the app's front end on Vercel. When adding the database address and the Stripe key, they tick all three boxes, Production, Preview and Development, because it's quicker. Weeks later, the agent works on a branch that changes how old scans are cleaned up. Vercel builds a preview of the branch. The builder opens it to see whether the cleanup page looks right and presses the button to test it. The preview is using the production database. The cleanup runs against members' scans.

Each step made sense on its own. Ticking all three boxes saved a minute, and testing the button was the point of the preview. The gap was a preview that shared production's keys. The fix has three parts.

  • Give previews their own values in the platform secret store: a staging or preview database, Stripe test keys, and vendor keys with a low cap.
  • Never tick "Preview" on a live key. On Railway, make sure pull-request environments copy staging's variables, not production's.
  • Ask the agent to make the app print which environment it's in at startup, and show a small "Preview" or "Staging" label on every page outside production, so nobody mistakes one for the other.

Tell your agent

"Check every environment variable on our hosting platform and tell me which ones are shared between production and preview deployments. For any database address, storage key, payment key or vendor key that preview deployments share with production, propose a separate test value. Show me that list before changing any setting. Then add a visible label on every page that shows which environment the app is running in, hidden only in production."

When a Deploy Goes Wrong: Rolling Back

Sometimes a deploy passes every step and still breaks something: errors climb, a page stops loading, a member writes in. The first job is to stop the harm, and the fastest way is usually to go back to the version that worked.

To roll back a deploy is to make the previous good version the running version again, without waiting for a fix. Hosting platforms keep a list of recent deploys, each with the exact build that ran. On Vercel you promote an earlier deployment back to production; on Railway you pick an earlier deployment and roll back to it. Because the platform reuses the old build, a rollback takes seconds to a minute.

You often want a git revert as well, the new commit from Chapter 5 that undoes the bad one. The rollback stops the harm. The revert makes the code in git match what's running, so the next push to main doesn't deploy the bad change again.

Rollback has one large limit: it brings back old code, not old data. If the deploy ran a database migration that dropped a column, rolling back gives you old code that expects a column that's gone. Chapter 11 covers how to write migrations the old code can live with.

One Question Before You Push

Sawyer giving a tip Ask your agent: "If I roll this back five minutes after it goes out, does the old code still work?" If the answer mentions the database, try the change in staging first.

Rolling Back a Bad Scoring Change

Here's how a rollback would go for the dating-safety app, as a hypothetical. At 2:10 in the afternoon, the builder merges a change to how the photo check reports its result. The deploy passes its health check. By 2:25, the error tracker shows the photo check failing on every scan, and every scan is showing "not checked" for photos. The no-false-all-clear rule is doing its job: members see a gap, not a pass. Still, every scan is now missing a check.

  1. 2:26. Decide. The builder doesn't try to debug in production. The change is fifteen minutes old, and the deploy before it worked.
  2. 2:27. Roll back. In the platform's deploy list, the builder rolls back to the 1:40 deploy. Within a minute the old build is serving traffic.
  3. 2:30. Confirm. New scans show the photo check passing and failing normally again. The error rate drops.
  4. 2:35. Revert in git. The agent opens a pull request that reverts the merge, so the next deploy won't bring the bad change back.
  5. Later. Fix calmly. The agent finds the bug on a branch, with a test that would have caught it, and tries it in staging before it goes out again.

The whole incident lasts about twenty minutes, and most of that is noticing. A rollback makes a deploy a two-way door in Chapter 1's sense. That holds only while the deploy hasn't changed the database in a way the old code can't handle.

Tell your agent

"Write down the exact steps to roll back a production deploy on our hosting platform, including where the list of past deploys is and what to click. Then check whether any migration in this repository would break if we rolled the code back after it ran. Put both in docs/rollback.md."

Work in Flight

The stage crew waits for the lights to go down before moving the sofa. A server needs the same patience, and by default it doesn't have it.

In-flight work at deploy is any task the old version of the app has started but not finished when a deploy stops it. A page request lasts a fraction of a second, so few are caught. A scan is different: its eight checks call outside services that can take many seconds, so a scan can run a minute or more.

The dating-safety app had this gap. Scans ran inside the Express server, and when a deploy replaced the server, scans in flight were killed partway. The app's sweep for orphaned scans kept the database tidy afterward, but the member's scan was still lost, and the vendor calls it had paid for were wasted. There are two fixes, and they work best together.

Graceful Shutdown

When a hosting platform stops an old version, it first sends the server a signal called SIGTERM, which means "please stop." Then it waits, and force-stops the server if it's still running. The wait is a setting whose default can be close to zero. On Railway it's called the draining time, and it can go in the deploy config. Set it long enough to cover a typical scan.

Graceful shutdown is code in your server that listens for that signal and uses the wait well: it stops taking new requests, lets the work in progress finish, and then exits. Without it, a server that gets SIGTERM stops mid-scan. Its limit is the wait: if a scan needs ninety seconds and the platform waits thirty, the scan is still cut off.

Code Without a Wait

Sawyer warning A common trap is adding graceful-shutdown code and leaving the platform's wait at its default. If the wait is near zero, the code never gets time to run, and scans are lost just as before. Set the wait in the deploy config, then deploy to staging with a scan running and check that it finishes.

Job Queues

A job queue is a list of tasks waiting to be done, kept outside your server, usually in the database. Workers are programs that take a task from the list, do it and mark it finished. If a worker stops before marking a task finished, the task goes back on the list and another worker picks it up.

For the dating-safety app, when a member starts a scan, the server writes a job to the queue and answers right away. A worker runs the eight checks. If a deploy stops that worker, the job returns to the queue and a worker on the new version starts it again. The member waits a little longer and still gets a result. Libraries such as pg-boss keep the queue in the Postgres database the app already has. One caution: a job that may run twice must be safe to run twice, so a step that charges the member or sends a text must not do it again. Chapter 9 covers retries.

Where the Work Lives

Sawyer thinking Notice what the queue moves. The scan's progress now lives in the database, not inside one running server. Once no server holds anything it can't afford to lose, you can replace any server at any time.

You can try a hard stop, graceful shutdown and a job queue in the simulation below.

Diagram: Deploying While Scans Are Running

Run the Deploying While Scans Are Running MicroSim Fullscreen

Deploying While Scans Are Running

Type: microsim sim-id: deploy-during-scans
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: calculate
Learning Objective: The learner will calculate how many of eight scans are lost and how many are delayed when a deploy happens at 60 seconds, under a hard stop, a graceful shutdown and a job queue, for a given shutdown wait.

Prerequisites: deploy, in-flight work at deploy, graceful shutdown, SIGTERM, job queue (all defined in the section "Work in Flight").

Evidence of Mastery: For three strategies at a 30-second shutdown wait, the learner commits the number of scans lost before the run is shown. Then the learner commits the smallest shutdown wait at which graceful shutdown alone loses no scans. Each answer is correct when it equals the value in Content. Mastery is 4 of 4 correct. Moving the shutdown-wait control in free exploration is not evidence.

Misconceptions: (1) A deploy only affects requests that arrive during the deploy. (2) Graceful shutdown always saves every task. (3) A job queue makes tasks finish on time, rather than finish late.

Instructional Rationale: Committing a count before the timeline plays forces the learner to apply each strategy's rule to every scan, which is the skill needed to judge their own app. The final question shows why a longer wait alone can't keep up with long tasks.

Content:

The timeline runs from 0 to 180 seconds. The deploy happens at 60 seconds: at that moment the new version is already healthy, all new scans go to it, and the old version receives SIGTERM.

Scan Starts at (s) Takes (s) Would end at (s) Running on
1 0 40 40 Old version
2 15 50 65 Old version
3 30 25 55 Old version
4 40 45 85 Old version
5 45 70 115 Old version
6 52 30 82 Old version
7 58 60 118 Old version
8 70 30 100 New version

The learner can change one quantity:

Quantity Min Max Step Default Unit
Shutdown wait (time between SIGTERM and force-stop) 0 120 10 30 seconds

Strategies: Hard stop; Graceful shutdown; Job queue (with graceful shutdown).

Committed questions and answers, in this order:

# Question Correct answer Why (feedback)
1 Hard stop, wait 30 s. How many scans are lost? 5 Scans 2, 4, 5, 6 and 7 are still running at 60 s, and a hard stop ends them at once.
2 Graceful shutdown, wait 30 s. How many scans are lost? 2 Force-stop comes at 90 s. Scans 2, 4 and 6 finish by then; scans 5 and 7 don't.
3 Job queue, wait 30 s. How many scans are lost? 0 Scans 5 and 7 go back on the queue at 90 s and restart on the new version. They finish late (at 160 s and 150 s), but they finish.
4 Graceful shutdown alone: what is the smallest wait that loses no scans? 60 Scan 7 ends at 118 s, so force-stop must come at 118 s or later. The first step that reaches it is 60 s (force-stop at 120 s).

Provenance: The problem comes from the dating-safety app: a deploy killed scans in flight, and the fix named was a job queue (research/seed-notes.md). All scan times are illustrative and must be labeled "illustrative." The SIGTERM-then-force-stop sequence is the usual behavior of hosting platforms, as described in the section "Graceful Shutdown."

Rules: Let D = 60 s be the deploy time and w the shutdown wait. A scan is in flight when it runs on the old version, starts before D, and would end after D. Scans that end at or before D finish normally. Scan 8 runs on the new version and is never affected. Hard stop: every in-flight scan is lost; w has no effect. Graceful shutdown: an in-flight scan finishes when its end time <= D + w; otherwise it is lost at D + w. Job queue: an in-flight scan with end time <= D + w finishes normally; otherwise it is returned to the queue at D + w and restarts from the beginning on the new version at D + w, ending at D + w + its duration, and is counted as delayed, not lost. With w = 0, graceful shutdown loses the same 5 scans as a hard stop. With w >= 60, graceful shutdown loses 0. A scan ending exactly at D + w counts as finished.

Learner Activity:

  1. The learner sees the eight scans as bars on a timeline, the deploy marked at 60 s, and the strategy set to Hard stop with a 30 s wait.
  2. The learner types the number of scans lost for question 1 and presses Check. The timeline plays; lost scans are marked as cut off at the moment they are stopped.
  3. Step 2 repeats for questions 2 and 3, with the strategy switched to Graceful shutdown and then Job queue. In the job-queue run, restarted scans appear again on the new version's side, starting at 90 s.
  4. The learner answers question 4 with a wait in seconds.
  5. Free exploration unlocks: the learner changes the strategy and the wait, and the counts "Lost: n" and "Delayed: n" update at once. The learner should notice that raising the wait helps graceful shutdown only until it covers the longest scan, while the job queue loses nothing at every wait.

Feedback: Four questions, fixed order, two attempts each. Correct: "Right. " followed by the Why text. Incorrect on the first attempt: "Not quite. Check which scans are still running at 60 seconds, and when each one would end." Incorrect on the second attempt: the correct answer and the Why text are shown and the question counts as missed. A count "Correct: n of 4" is shown.

Starting State: The timeline shows the eight scans before the deploy plays, with Hard stop selected and a 30 s wait. The prompt reads "A deploy happens at 60 seconds. How many of these scans will members never get back?"

Chapter Anchors: The deploy happens at 60 seconds. Five scans are in flight. With a 30-second wait, a hard stop loses 5, graceful shutdown loses 2, and a job queue loses 0 and delays 2. Graceful shutdown alone needs a 60-second wait to lose none.

Tell your agent

"Find every task in this app that can take longer than a few seconds, starting with scans. For each one, tell me what happens to it if the server is stopped halfway. Then show me a plan for graceful shutdown (on SIGTERM, stop taking new work, let running work finish, and exit) and a plan for moving scans onto a job queue in our Postgres database, including how each check avoids charging twice if a job runs again. Don't write either until I approve."

Feature Flags: Shipping Code That Is Turned Off

A deploy puts new code in front of every member at once. A feature flag is a switch, read by the code while it runs, that turns a feature on or off without a new deploy. The new code ships turned off. You then turn it on for yourself, then for a few members, then for everyone, and turn it off again in seconds if something goes wrong. The simplest flag is an environment variable such as NEW_RESULTS_PAGE=on. More advanced flags live in a database table or a flag service and can be set per member.

Two Moments, Pulled Apart

Sawyer thinking A deploy joins two moments: when the code arrives and when members see it. A flag pulls them apart. The code can sit in production, tested and switched off, until you choose who sees it.

Flags suit good-enough-for-now changes you want to try on a few members, such as a new results-page layout. Never put a must-be-right rule like no-locate behind a flag someone could turn off. Each flag is also a small piece of debt: once a feature is fully on, ask the agent to remove its flag. Chapter 15 covers tracking debt.

Tell your agent

"Add a feature flag for the next change to the results page, read from an environment variable and off by default. Show the new version only when the flag is on. Add a note to our debt list to remove the flag once the new page is on for everyone."

Practice choosing where a piece of work belongs in the simulation below.

Diagram: Where Should You Try This First?

Run the Where Should You Try This First? MicroSim Fullscreen

Where Should You Try This First?

Type: microsim sim-id: environment-choice-sorter
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: classify
Learning Objective: The learner will classify twelve tasks from the dating-safety app by the cheapest environment that can test each one truthfully (local, staging or production), with at least ten of twelve correct.

Prerequisites: environment, local environment, staging environment, production environment, environment parity, platform secret store, feature flag (all defined in the chapter above).

Evidence of Mastery: The learner places each of twelve task cards into one of three bins and presses Check. A placement is correct when it matches the Correct bin column in Content. Mastery is 10 of 12 correct on the first attempt. Opening a card's hint is exploration, not evidence.

Misconceptions: (1) Everything should be tested in staging, even a color change. (2) Production is never the right place to learn anything. (3) Local is good enough for anything involving payments or the server's settings.

Instructional Rationale: Classifying tasks by environment makes the learner apply one rule, "the cheapest environment that can show this truthfully," to cases that look alike on the surface. Committing a placement before the answer is shown makes the learner reason from what each environment can and can't show.

Content:

Bins: Local, Staging, Production.

# Task shown to the learner Correct bin Why (feedback)
1 Change the color of the trust score Local The development server shows the change in a second, and nothing outside your laptop is involved.
2 Try a new Stripe checkout flow end to end, including the webhook Stripe sends back Staging It needs a server Stripe can reach and the same setup as production, with test keys so no real money moves.
3 Show a friend a redesigned results page before merging it Staging It needs a link someone else can open, and no member should see it yet.
4 Run a new database migration against a copy of the schema filled with made-up data Staging Migrations need production's shape and a realistic amount of data, without members' data at risk.
5 Check that a deploy while scans are running doesn't lose them Staging It needs the same platform restart behavior as production, with no member's scan on the line.
6 Count how many scans members ran yesterday Production Only production has members' activity.
7 Try a new AI prompt for the message check on made-up messages Local A fast loop with sample text is all it needs.
8 Find out how members respond to a new results-page layout, shown to a few of them behind a feature flag Production Only members can tell you how members respond; the flag keeps it to a few and lets you turn it off.
9 Fix a typo in an error message Local A one-line change you can see right away.
10 Check that a new environment variable is set on the server before the feature that needs it goes live Staging The platform secret store is per environment, so staging is where you prove the server has it.
11 Step through a bug line by line while editing code Local Debugging needs the fastest loop and full control, which only your laptop gives.
12 Learn that a vendor started timing out overnight Production Vendor behavior under members' traffic only shows up in production's monitoring.

Hint text for every card: "Ask: what is the cheapest place that can show this truthfully? Does it need a server others can reach, production's setup, or real members?"

Provenance: Tasks 2, 4, 5 and 10 come from the sections "Three Places Your App Runs," "Keeping Environments Alike" and "Work in Flight." Task 12 relates to the vendor failures described in Chapter 9. Tasks 1, 3, 6, 7, 8, 9 and 11 are illustrative and must be labeled "illustrative."

Rules: Each card has exactly one correct bin. The rule is: choose the cheapest environment, in the order Local, then Staging, then Production, that can show the result truthfully. Four cards are Local (1, 7, 9, 11), five are Staging (2, 3, 4, 5, 10), and three are Production (6, 8, 12).

Learner Activity:

  1. The learner sees twelve cards in a shuffled stack and three empty bins.
  2. The learner moves each card into a bin. A card's hint can be opened at any time. Cards can be moved between bins until Check.
  3. When all twelve are placed, the learner presses Check. Each card shows whether it is correct and its Why text.
  4. The learner should notice that tasks 3 and 8 are both about a results-page redesign and land in different bins.

Feedback: Twelve cards, shuffled order, one attempt. Correct: "Right. " followed by the Why text. Incorrect: "This one belongs in [correct bin]. " followed by the Why text. If tasks 3 and 8 were placed in the same bin, add: "Showing a design and learning how members react need different environments." The score "n of 12 correct" is shown after Check, with "Mastery reached" at 10 or more.

Starting State: Three empty bins labeled Local, Staging and Production, and a stack of twelve cards. The prompt reads "Where is the cheapest place to try this truthfully?"

Chapter Anchors: The chapter names three environments: local, staging and production. Staging uses Stripe test-mode keys. The dating-safety app launched with no staging environment.

A Deploy Checklist

Pilots run a checklist before every takeoff, even after ten thousand flights. Most deploys go fine, which is why their steps get skipped.

A deploy checklist is a short written list of checks you run before and after every production deploy. Keep it in the repository so the agent can read it too. Keep it short enough to run every time, because one that takes more than a few minutes gets skipped.

The Running Example's Checklist

Here is a checklist for the dating-safety app, built from the gaps in this chapter. It assumes a staging environment exists.

Before the deploy:

  1. Tests pass, and the production build runs without errors.
  2. The change has run in staging, and a sample scan finished there.
  3. Any new environment variable is set in production's secret store, by name.
  4. Any database migration has run in staging and can live with the old code if you roll back.
  5. No development plugin or script appears in the production build.
  6. Note the current production deploy, so you know what to roll back to.
  7. If many scans are running, wait for a quiet moment, or confirm that scans are on the job queue.

After the deploy:

  1. Run one scan in production and confirm it finishes with a score.
  2. Watch the error tracker for fifteen minutes.
  3. If errors rise or a scan fails, roll back first and investigate after.

Each line traces back to a section of this chapter. Many can later become automatic checks that run on every push, the subject of Chapter 17. Until then, the checklist holds them.

Tell your agent

"Write a deploy checklist for this app in docs/deploy-checklist.md: what to check before a production deploy and what to check in the fifteen minutes after. Base it on our setup: our hosting platform, our database migrations, our environment variables and our long-running scans. Keep it under twelve lines. Before the next deploy, read it back to me and tell me which lines you checked."

Back to the Theater

The small-town theater doesn't skip the dress rehearsal, even though it costs a night. The stuck door and the slow costume change get fixed there, with nobody in the seats. During the show, the crew moves the set only when the lights go down.

An app built with an agent can ship faster than any theater can rehearse, and that speed is worth keeping. A staging copy, settings in git, a known way to roll back and a queue for long scans don't slow a builder down much.

Ready for Opening Night

Sawyer celebrating You can now map where every part of your app runs, keep its settings in git, roll back a bad deploy in a minute, and keep scans alive through a restart. Next, Chapter 15 looks at the shortcuts you took to get here and how to keep track of them.

Key Takeaways

  • Run three environments: local for building, staging for the dress rehearsal, production for members. Keep them alike except for data and keys, and never let staging or a preview deployment use production's keys.
  • Vercel suits front ends and server functions that end with each request; Railway runs long-lived servers and databases.
  • Keep deploy config in git, and run a short deploy checklist before and after each deploy.
  • To roll back a deploy is the fastest way to stop harm. It restores code, not data.
  • Graceful shutdown lets short work finish during a deploy; a job queue lets long work survive it.

See Annotated References