Database and backups

Create Stater's database with least privilege, check its health in plain language, and run encrypted, scheduled backups and restores.

See it in the tour: Database set-up and backups

On this page

Three things keep the database behind Stater in good order:

  • stater db init makes a database and a user for Stater, with only the rights it needs, and runs the migrations.
  • stater db doctor (and Admin › System health) checks the database in plain language.
  • Backups run inside Stater on a schedule, to a folder on the server and/or S3-compatible storage, encrypted before they leave the server. Admin › Backups shows them; restoring is done on the command line.

None of this is a paid extra. The only licensed part is saving an S3 destination in Admin › Backups (Growth and up). An S3 destination that is already saved keeps working whatever happens to the licence, and one set through STATER_BACKUP_S3_* is never gated.

First install: stater db init#

stater db init connects with an admin connection, then:

  1. creates the login role (no superuser, no CREATEDB, no CREATEROLE), sending PostgreSQL a SCRAM-SHA-256 verifier so the password itself never reaches the server or its logs;
  2. creates a UTF-8 database owned by that role, and lets only that role connect;
  3. gives the role the public schema and installs pg_trgm (or says how to get it);
  4. runs the migrations as that role, so it owns every table.

Every step checks first, so running it again changes nothing.

export STATER_DB_ADMIN_URL_FILE=/etc/stater/admin-url        # postgres://postgres:…@db:5432/postgres
export STATER_DATABASE_URL='postgres://stater:a-long-password@db:5432/stater?sslmode=verify-full'
stater db init
Flag What it does
-admin-url URL The admin connection, instead of STATER_DB_ADMIN_URL(_FILE). A URL on the command line is visible in the process list, so the command warns.
-database NAME, -role NAME Names other than those in STATER_DATABASE_URL.
-password-file F The role's password, from a file.
-no-password A role that signs in another way (peer or certificate authentication).
-print-url Prints the STATER_DATABASE_URL to use, password included, on standard output (progress goes to standard error). Without a password anywhere, one is made.
-reset-password Sets the password again for a role that is already there.
-no-migrate Leaves the migrations to the server's first start.
-dry-run Says what it would do and changes nothing.

On a managed database (Amazon RDS, Azure, Cloud SQL) the admin user is not a superuser. db init then makes the admin a member of the new role, which PostgreSQL 16 and later need for CREATE DATABASE … OWNER. If pg_trgm is not allowed, add it to the allowed extensions (Azure: azure.extensions) and run db init again.

Health: stater db doctor and System health#

stater db doctor            # grouped, with ok / WARN / FAIL
stater db doctor -json      # for support
stater db doctor -queries   # adds the text of long and blocked queries (cut to 120 characters)
stater db doctor -strict    # exit 3 on a caution as well

It exits 0 when nothing is critical, 3 when something is, and 1 when it cannot run at all. A fresh install exits 0. Admin › System health (owners only) shows the same report, refreshed at most every 15 seconds, and Download report saves it as JSON. Query text is never shown in the browser or the download.

Check Caution Critical
Connection the database cannot be reached
Encrypted connection not TLS over the network
PostgreSQL version not 17 older than 16
Text encoding not UTF-8
Search extension pg_trgm missing
Database structure migrations not applied yet migrations from a newer Stater
Clocks more than 2 s apart more than 30 s apart
Time zones a store's time zone unknown to Go or PostgreSQL
Connections the budget is over 80% of what PostgreSQL allows over 100%
Clean-up (vacuum) a table with many dead rows autovacuum off
Replication a standby more than 30 s behind connected to a read-only standby, or a standby over 5 min behind
Long queries, idle in a transaction, waiting for locks any found
Last good backup none yet on a new install, or the last one failed none for twice the schedule's gap
Backup tools pg_dump missing or older than the server
Free space the backup folder has less than twice the last backup free

"No backup yet" is only a note when no destination is set up, a caution while the install is younger than twice the schedule's gap, and critical after that.

The connection budget. Each server opens at most pool_max_conns connections (8 by default). Add 2 for a backup in progress (its snapshot connection and pg_dump) and 3 for an administrator:

servers × pool_max_conns + 2 + 3 ≤ max_connections − reserved connections

Backups#

Backups are pg_dump custom-format archives with a manifest (.json) beside each one: the exact row counts of the main tables taken in the same snapshot, the migrations, the versions, the SHA-256 of the plain and the stored file and, when encrypted, a signature. Sign-in sessions and failed sign-in counts are left out, so a restore signs everyone out.

Objects are named <prefix>/stater/<yyyy>/<mm>/<UTC time>-<backup id>.dump[.enc].

One at a time. Every server runs a backup worker (turn it off with STATER_BACKUP_WORKER=false), but only the one holding the backup leader lock (advisory lock 727301) makes a backup; the command line takes the same lock. A server that stops halfway leaves its run to be marked failed by the next one. The schedule is a background job that adds each time's backup once, however many servers run.

Where to.

  • STATER_BACKUP_DIR: a folder on the server, made 0700, files 0600, written to a .part file and renamed. With several servers it must be shared storage, because any server may be the one backing up. Compose keeps backups in /var/lib/stater/backups on the backups volume, which every replica and podman compose run see. In Kubernetes use S3, or one replica with the volume and STATER_BACKUP_WORKER=false on the rest.
  • S3-compatible storage, set in Admin › Backups or with STATER_BACKUP_S3_* (the environment wins and locks the screen). AWS, MinIO, Garage, Wasabi, Backblaze B2 and Cloudflare R2 work. Uploads are a single PUT, so a backup can be at most 5 GB in S3 for now. Connections go through Stater's address guard: a private or loopback endpoint needs "On my own network" (or STATER_BACKUP_ALLOW_PRIVATE), and STATER_PRIVATE_CONNECTORS=false refuses it anyway. Plain http:// is allowed only for such an endpoint.

A minimal bucket policy for Stater's access key: s3:PutObject, s3:GetObject and s3:ListBucket, plus s3:DeleteObject only when "Delete old backups here" is on. With it off, Stater never deletes; use bucket lifecycle rules instead. An S3 destination set with STATER_BACKUP_S3_* always deletes old backups by the keep rule, so its key needs s3:DeleteObject; set it up in Admin › Backups instead to leave deletion to the bucket. Turning on versioning or Object Lock protects backups from someone who steals the key.

Encryption. With STATER_BACKUP_KEY(_FILE) or, without it, a key derived from STATER_SECRET_KEY, backups are encrypted on the server before they are stored: AES-256-GCM in 64 KiB chunks, so damage, truncation and reordering are all detected, and the manifest is signed. Make a key with stater backup keygen -out FILE. Keep a copy of the key away from the backups and the server: without it the backups cannot be restored. A key derived from STATER_SECRET_KEY changes when that key is rotated; backups made before can then be read only with the old key set as STATER_BACKUP_KEY. Without any key, backups are not encrypted and only their SHA-256 protects them; the screen says so. With a key, only backups whose manifest is signed with it are picked as latest, counted and deleted by the keep rule, or accepted by a check or restore, so a backup someone planted in the folder or bucket is never used by mistake. A plain backup made before there was a key can still be checked or restored by its id with -allow-unsigned; it is never deleted by the keep rule. S3 server-side encryption (AES256 or aws:kms) can be added on top.

Schedule and keeping. Times of day in the company's time zone (the first open store's), up to six, 02:30 by default. A time missed while every server was down is caught up within 12 hours, unless the schedule was changed after it. After each good backup, old ones are deleted from each destination that prunes: a backup is kept while it is younger than keep days (14) or among the newest keep count (7); the newest backup, everything from the last 24 hours, and safety copies from the last 30 days are always kept. 0 and 0 keeps everything.

Checking. By default each backup is read back after it is made (a quick check): it is downloaded, its hashes, encryption and signature checked, and pg_restore --list must read it and find the rows of schema_migrations and users. "Check this backup" in Admin › Backups runs the same check again; stater backup verify does it from the command line.

Commands.

stater backup run [-to DIR] [-verify]     # back up now (to DIR only, when given)
stater backup list [-json]                # what is in the folder and bucket; works without the database
stater backup verify [-allow-unsigned] <id|latest|FILE>
stater backup restore [-force] [-yes] [-no-safety-backup | -safety-to DIR] [-into-file F | -into URL] [-allow-unsigned] <id|latest|FILE>
stater backup keygen -out FILE

Time limits. A backup or check stops after 6 hours. Each S3 request has its own limit (2 minutes for small ones, 10 minutes plus a second per MiB for an upload), and a transfer that moves no data for 2 minutes is ended, so storage that stops answering cannot hold up the next backup.

Alerts. A backup fails, though the folder still has it, when an S3 destination is set up but cannot be used (no secret saved, or one this server's STATER_SECRET_KEY cannot open). A failed backup or check writes backup.failed or backup.verify_failed to the outbox (subscribe a webhook to backup.*; the payload is {backup_id, kind, status, size_bytes, error}, never paths or credentials), to the audit log, to the server log, and to Stater's alert hook, which sends email once email is set up. Live updates about backups go only to people with admin.settings.

Restoring#

Restore is command-line only, by design: nobody can download or replace the whole database from a browser.

  1. Stop every Stater server. A restore refuses while any stater serve is connected to the database.
  2. Run the restore. It downloads the backup, checks it (hashes, encryption, signature, contents), and refuses a backup made by a newer Stater. A database that already holds data is replaced only with -force, after a safety backup to the same destinations. You confirm by typing the database's name (-yes skips that for scripts). pg_restore runs in one transaction, so a failure leaves the database as it was. A database newer than the backup (it has migrations the backup does not, as after an upgrade) is emptied first, because its newer tables may refer to the backup's; with data in it, that needs the safety backup, and if pg_restore then fails, restore the safety backup to put it back. Afterwards the migrations run, everyone is signed out, and the backup history shows the restored backup as made (backups that were waiting at the time are closed without an alert).
  3. Start Stater again.
# compose
podman compose stop stater
podman compose run --rm stater backup restore -force latest
podman compose start stater

# systemd
systemctl stop stater
sudo -u stater stater backup restore -force latest
systemctl start stater

# Kubernetes: scale to 0, then run the Stater image once with the same
# environment (a Job or kubectl debug), with the arguments
#   backup restore -force -yes latest
kubectl scale deploy/stater --replicas=0
kubectl scale deploy/stater --replicas=2   # when it has finished

Things to know:

  • Staff, API tokens and webhooks go back to how they were in the backup. Revoke again anything revoked since.
  • Saved integration passwords (email, directory, AI, S3) need the same STATER_SECRET_KEY as when the backup was made, or must be entered again.
  • -into-file F (a 0600 file holding a database URL) restores somewhere else, such as a test database for a restore drill. Do one every month: restore the latest backup into a scratch database and sign in. -into URL works too, but a URL on the command line is visible to other users in the process list.
  • latest is always the newest backup of the database in STATER_DATABASE_URL, even with -into. Backups of other databases in the same folder or bucket are skipped; restore one by its id. Before you confirm, the restore names the backup's database, its kind (scheduled, safety copy and so on) and when it was made.
  • A database other than the one in STATER_DATABASE_URL never has its safety backup put in the shared folder or bucket. When it holds data (a second restore drill with -force), add -safety-to DIR to keep the safety backup in a folder of its own, or -no-safety-backup if its data can go.

Images#

The standard image is Alpine with the PostgreSQL 17 client tools, which must be at least the database server's major version. Compose mounts the backups volume at /var/lib/stater/backups and uses it by default.

Not yet#

  • Multipart S3 uploads (backups over 5 GB to S3).
  • A full check that restores into a scratch database and compares row counts (backup restore -into covers a drill by hand).
  • Daily, weekly and monthly ("grandfather-father-son") keeping.
  • Backup metrics in /metrics and a "Backups have not run" item on Today.
  • Re-importing backups found in storage into the history after a restore (stater backup list reads storage directly).
  • Point-in-time recovery and WAL archiving (pgBackRest or Barman are the next step for large installs).