19 — Database swap runbook
Database swap — Replacing the whole production database with a new version, carrying over user accounts and data. The hardest operation in The Craft — it has its own runbook and needs explicit consent. more in the glossary → out the whole Environment (dev / prod) — Separate places where the app runs: “dev” for safe tests, “prod” for real users. Dev is a playground, prod is where real users are — the rules for each are completely different. more in the glossary → database — e.g. for a rebuilt, cleaned-up catalogue you’ve worked on locally for weeks — while keeping every live account and everything users created is the hardest operation in this doctrine. It happens rarely, so there’s no habit; it touches user data, so there’s no margin for error. Chapter 19 (split out of the old chapter 05 in 1.1.1) is a Runbook — A written step-by-step guide for production operations, with numbered lessons from incidents. The memory of outages can’t live in someone’s head — the next deploy starts by reading the runbook. more in the glossary → written from a real swap in the reference project. Below is what stands behind the rules.
What has to be kept
“Users” is many tables. ↗
The first, intuitive version of the plan goes: “we swap the database but keep the users table”. After such a swap the accounts exist, but reviews, likes, badges, carts, chat history and quotas disappear — everything users did. So you start by listing every table with a Foreign key (FK) — A column that points to a record in another table — e.g. a review points to its user. It prevents “dangling” references to things that don’t exist, and sets the order of operations. more in the glossary → to the user. Some tables have no direct user_id — e.g. chat messages belong to a chat session, and only the session belongs to the user — and they’re mapped through the parent. Each step first checks that the table and column exist at all, because the old and new databases may have different schemas (11).
Map by a stable key (Slug — A readable, short part of a page address that describes its content in words instead of a mysterious number. Better for humans and SEO; a stable slug doesn’t break links when things change. more in the glossary → → new id), never by the old id. ↗
This is the hardest lesson of the operation. After duplicates are merged, the product with id 1041 in the old database may have id 977 in the new one — or id 1041 may belong to a completely different product. A review carried over by the old id lands on the wrong product, silently, with no error at all. So a review is moved by the product’s slug to its new id, and a review whose product doesn’t exist in the new database is skipped and written to the log — so someone can decide deliberately what to do with it, instead of squeezing it in somewhere.
Where to take the accounts from
The source of truth for accounts is live prod ↗
Migrating accounts from a Snapshot — A saved state of data from a specific moment — e.g. a database copy or a file of computed statistics. It speeds things up and keeps them safe, but is stale from the moment it’s taken — you need to know where fresh data comes from. more in the glossary → taken in the morning is tempting: everything can be prepared and checked calmly. But a snapshot from a few hours ago doesn’t know about the sign-ups, reviews and orders from those hours — after the swap they’re simply gone. So accounts are read from live production, in the Maintenance window — A short, planned period when users see a “work in progress” page while the database or configuration changes behind it. It guarantees the app never runs, even briefly, on half-changed data. more in the glossary →, after the app process is stopped, when nothing in the database changes any more and its state is consistent.
FK-safe order: ↗
Foreign keys impose an order: when deleting, children first, then parents (review likes first, then reviews); when inserting, the other way round (chat sessions first, then their messages). The wrong order ends in an error halfway through — in the middle of the maintenance window, with half-moved data.
The safety net
Back up live prod right before the swap ↗
A Backup — A copy of your data saved earlier, which you return to when something goes wrong. It’s the only way to undo a change to data — code comes back from git, data only from a backup. more in the glossary → of production made with .backup right before the swap, named clearly (replaced-prod-<date-time>.db), is the only way to roll this operation back (04). A backup from last week isn’t enough — it doesn’t contain the latest accounts.
Verify the merged database: ↗
Before the new database takes its place, it passes a check by numbers: the account count equals production, zero reviews left hanging without a product (so the slug mapping worked), integrity_check: ok, and no more foreign-key violations than the pre-existing state. That last point matters: the old database may have had minor violations for ages — what counts is that the operation doesn’t add new ones (03).
Sessions live in their own store ↗
If login sessions live in the same database you’re swapping, the swap logs everyone out. If they live in the process’s memory, every restart and every Deploy — Releasing a new version of the app “live”, where real people use it. It’s the moment a change reaches real people — which is why it happens only on an explicit “deploy”. more in the glossary → logs them out. A separate file for sessions (e.g. sessions.db) means neither the catalogue swap nor a restart touches logged-in users (14).
The sequence in three phases
Live phase: ↗
Everything that can be done without downtime is done before the window, while the service is still running: pushing the code, uploading the new database snapshot to the server and — easy to miss — copying images and other files that are in .gitignore. Those won’t arrive through Push / pull — Push sends your commits to the remote repository; pull fetches changes from there into your copy. A push is an “outward” action — in The Craft it needs explicit consent, like a deploy. more in the glossary →. In the reference project they were copied from the local machine (rsync or tar over SSH — An encrypted connection to a server for sending it commands and transferring files. An SSH key is access to production — guard it like your most important password. more in the glossary →, only the missing files), because the server lacked the tools to generate them. The new images sit unused until the database changes — so they do no harm. Moving gigabytes during the maintenance window means downtime measured in minutes rather than seconds.
Window (seconds, atomic,
set -e): ↗
The window itself is a single script that stops at the first error (set -e): maintenance page on → pull the code → stop the process → back up live production → migrate users from production into the new database → swap the file (removing the old database’s -wal/-shm files and switching WAL — Write-Ahead Log: a database mode where changes go to a journal first, then to the data. Gives safety (recovery after a crash) and better read/write concurrency. more in the glossary → mode back on) → start → Smoke test — A quick “does it even work” test right after a deploy — checks the most important paths (e.g. login). Catches disasters in 30 seconds before a user sees them. A cheap way to sleep well after a deploy. more in the glossary → → maintenance page off. Rehearsed beforehand on Preprod (staging) — A faithful copy of production with no real users, where you rehearse a deploy. A migration that fails on preprod is an ordinary Tuesday; in production it’s an incident. more in the glossary →, with the time measured (18).
Smoke via localhost — The address a computer (or server) uses to connect to itself. On a server it lets you check the new version “from inside” before users see it. more in the glossary → ↗
The smoke test goes through localhost, bypassing the nginx — A program at the front of the server that takes traffic from the internet and routes it to your app. Handles HTTPS, serves static files, balances traffic — the server’s proven “reception desk”. more in the glossary → maintenance page — users still see the maintenance page while you’re already checking the new version: key pages return 200, redirects (e.g. from merged products to the surviving one) work, the database numbers add up and the process logs are clean. If a trivial and safe bug turns up in the window, it’s fixed right away instead of releasing a known 500 error (03).
After: ↗
A deploy tag, cleaning up temporary files on the server and locally, refreshing link previews on social media and in search engines if they changed — and a runbook entry with every lesson this swap taught (05). The next swap, six months from now, starts by reading that entry.