Roll-Forward SQLite Migrations for a One-Server SaaS
A small paid product does not need Postgres. It needs a database that is backed up, migrated, and restored correctly — and SQLite can do all three on a single box, provided you stop treating schema changes as "just run some SQL before restarting."
The version of this that bites you is familiar: you deploy a new feature, the code expects a column, the column is missing on the server, and the app 500s at 2 a.m. Or worse: the migration runs twice, a CREATE TABLE fails the second time, the deploy script aborts halfway, and the site is down with the database in a partially migrated state.
This is the migration and deploy model I use on FundScope, built around one rule: every migration is safe to run on a database that already ran it.
PRAGMA user_version is enough
SQLite has no migration framework by default, and for one process on one server you do not need one. It has a built-in integer in the file header:
PRAGMA user_version; -- 0 for a fresh file
Store the schema version there. On startup, read it, compare it to the highest migration in code, and apply only the missing ones in order:
const db = new Database(env.DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
const migrations = [
{ version: 1, up: (db) => db.exec(`CREATE TABLE ...`) },
{ version: 2, up: (db) => db.exec(`ALTER TABLE ...`) },
// ...
];
function migrate(db) {
const current = db.pragma('user_version', { simple: true });
for (const m of migrations) {
if (m.version <= current) continue;
const tx = db.transaction(() => {
m.up(db);
db.pragma(`user_version = ${m.version}`);
});
tx();
console.log(`[migrate] applied v${m.version}`);
}
}
Three properties matter here:
-
The version bump is inside the transaction. If a migration fails halfway, the transaction rolls back and
user_versionstays where it was. The next run retries the same migration from a clean state instead of skipping it because the version already advanced. -
The version lives in the file, not in a table you also have to create. A
schema_migrationstable is fine, but it means migration 1 is "create the table that records migrations" — a bootstrap special case you can avoid entirely. - Startup fails if a migration throws. Do not catch and continue with "best effort". A server running against a half-migrated database is worse than a server that refuses to start, because the second one pages you immediately.
journal_mode = WAL is set once and persists. It matters more than people expect: with the default rollback journal, a long read can block the writer, and an HTTP handler that holds a read transaction while awaiting an upstream fetch will stall checkout writes. WAL lets readers and the single writer coexist, which is exactly the access pattern of a small web app.
Order the migrations by what they depend on
The version numbers are not decorative; they encode dependency. The sequence that has survived five feature releases looks like this:
| Version | Content | Why it had to come here |
|---|---|---|
| v1 |
users, sessions, email_tokens
|
Auth is the base for every tier decision |
| v2 |
orders, entitlements
|
Fulfillment needs a user identity to attach to |
| v3 | usage_daily |
Quotas need tiers, tiers need entitlements |
| v4 |
watchlists, report_logs
|
Product features that reference users and quotas |
| v5 |
audit_events, indexes |
Observability and query performance at the end |
The temptation is to squash these into one schema.sql for a fresh install. Resist it for the same reason you keep Git history: the order is the part that documents why a column exists. It also means a new environment and an old environment converge through the same code path, so the fresh install is constantly tested by every deploy.
If you do want a fast path for empty databases, make it a derived artifact: run all migrations, then VACUUM INTO 'seed.db'. Never hand-maintain a second schema definition — it will drift, and the drift appears as a bug that only affects new customers.
Idempotent seed data, not "insert if empty"
Reference data is the second source of upgrade pain. A table of preset watchlists, plan definitions, or category mappings needs to exist on a fresh install, needs to stay current on an old one, and must not duplicate on a rerun.
INSERT ... ON CONFLICT DO NOTHING on a natural key handles all three:
INSERT INTO presets (key, label, fund_codes, sort_order)
VALUES
('broad-index', 'Broad market index', '["000001","000300"]', 10),
('dividend', 'Dividend tilt', '["000012"]', 20)
ON CONFLICT (key) DO UPDATE SET
label = excluded.label,
fund_codes = excluded.fund_codes,
sort_order = excluded.sort_order;
DO UPDATE rather than DO NOTHING is deliberate: curated lists should be corrected by a deploy, not frozen at whatever the first install wrote. The natural key (key) is what makes it safe, and it must be a stable identifier, never a display name that a copy edit would change.
The counterexample is user data. Never seed, never upsert, never "fix up" rows that belong to customers. If a migration needs to backfill a user column, do it as an explicit, versioned step with a deterministic rule (UPDATE users SET tier='free' WHERE tier IS NULL), and treat the result as data loss if it touches anything non-null.
Backup before migrate, not after
The deploy order is: stop taking writes if you can, copy the database, run migrations, restart, health check. The copy is not cp on a live WAL database — that can capture a torn state. Use SQLite's own backup API, which takes a consistent snapshot:
sqlite3 api/data/app.db ".backup 'api/data/backups/app-2026-11-26T101500.db'"
Keep a bounded number of backups (ten is plenty for a small product) and never let the cleanup step be "delete everything except the newest" — a corrupted newest backup plus aggressive cleanup is how people lose a day of orders. Rotate by timestamp, keep ten, and verify the newest one opens:
sqlite3 app-2026-11-26T101500.db "PRAGMA integrity_check;"
An unverified backup is a file, not a backup.
The failure mode this prevents is specific: a migration that drops or rewrites a column and is discovered to be wrong after the deploy. With a snapshot from five minutes earlier, recovery is a copy and a restart. Without one, it is a reconstruction from provider dashboards and email receipts.
Deploy with a health check and an automatic rollback
The publish script does five things in order, and any failure stops the chain:
1. git fetch + reset to the target commit
2. pnpm install --prod (skipped if the lockfile is unchanged)
3. backup database
4. run migrations
5. restart the process, then poll /api/health for 15s
If step 5 never returns 200, the script resets to the previous commit, restores nothing (the database is forward-migrated, so it restarts with the older code), and restarts:
if ! check_health; then
git reset --hard "$PREV_COMMIT"
pm2 restart app --update-env
echo "rollback to $PREV_COMMIT"
fi
This works only because migrations are additive and backward-compatible for one release: the old code must still run against the new schema. That is a constraint, not an accident. Dropping a column in the same release that stops using it breaks the rollback path; the sequence is "stop writing it", deploy, wait, then drop it in a later release. For a one-server product with one deploy window, that discipline is cheap insurance.
Two more script details that prevent expensive mistakes:
-
Never rsync
--deleteover the data directory. Deployment copies code;api/data/is state. A sync that mirrors the repository onto the server will happily delete the database and the backups. Keep data outside the synced tree or exclude it explicitly. - Log the deploy. Commit, timestamp, migration versions applied, backup filename, health result, and rollback decision, appended to one file. When something goes wrong at 2 a.m., the first question is "what changed", and this file answers it without SSH archaeology.
The one-writer assumption, stated out loud
SQLite allows one writer at a time. On a single Express process that is a feature: writes serialize, busy_timeout absorbs short contention, and there is no distributed lock to misconfigure.
db.pragma('busy_timeout = 5000');
The assumption breaks in three ways, and each has a known answer:
- Multiple processes. Two PM2 instances in cluster mode both open the same file and both try to migrate. Set the app to one instance, or move migrations into a separate one-shot command that runs before the app starts. I run one instance; the traffic does not justify more, and the failure mode is not worth the complexity.
- Long write transactions. Wrapping an upstream HTTP fetch inside a transaction holds the write lock for seconds. Keep transactions to local statements only; fetch first, then write.
- Network filesystems. A database on NFS or a synced folder is a corrupted database waiting for a lock timeout. Local disk only, and the backup is the only thing that should ever be copied elsewhere.
Stating these out loud matters more than any benchmark. A one-server design is a set of promises about concurrency, and the promises are what you actually operate.
What this buys
Five schema versions later, the properties I care about still hold:
- A fresh install and a year-old server reach the same schema through the same code.
- Any migration can be re-run without error, because the version check and the transaction both guard it.
- Every deploy has a consistent backup and a rollback that works for one release.
- The data directory is never touched by code deployment.
None of this requires a migration library, a container orchestrator, or a second database. It requires treating the schema as versioned code and the database file as state that gets copied before it gets changed.
That distinction — code is disposable, data is not — is most of the operational maturity a small paid product needs.
More notes on small-scale product engineering are at wuhuajin.com.
Originally published on wuhuajin.com.
Top comments (0)