sqitchcraft

Designing the database

The tools make a schema change easy to write, review and ship. That matters most when the schema carries rules every service relies on. This is how Kronor designs a database to hold them.

Rules live in the database

A rule written in one service is a rule every other service can break. Put shared rules where every reader and writer has to pass through them, preferring, in this order:

Application code then reads and writes through a narrow, well-named surface, and a bug in one service cannot write a row that another service has to defend against. This is also why cheap schema changes matter: rules in the database have to be as easy to change as rules in code, or people stop putting them there.

Schemas by context

Split the database into schemas by what the data is about, not by technical layer. Each schema is created in the first change, base_schemas, with a comment saying what belongs in it.

create schema if not exists billing;
comment on schema billing is 'Invoices, payments against them, and their lifecycles.';

create schema if not exists customer_data;
comment on schema customer_data is
  'Personal data about customers. Protected by GDPR; other schemas refer to it by id only.';

create schema if not exists portal_api;
comment on schema portal_api is
  'Views and functions the merchant portal reads. Nothing else is exposed to it.';

The folder structure follows: database/deploy/billing/…, database/deploy/portal_api/…. sqiff takes --exclude-schema for infrastructure schemas you do not manage in the plan.

Lifecycles as statecharts

An invoice is drafted, sent, then paid or voided. The usual way to model that is a status column, and the usual result is that every writer has to know which moves are allowed, some of them get it wrong, and the history is overwritten with each update.

We model a lifecycle like that as a statechart that PostgreSQL runs with pg_statecharts. The chart is an SCXML file in the repository. The database makes only the moves the chart has and ignores late or repeated events, runs a function on entering or leaving a state, commits the new state with the caller's data, and keeps every state a row has been in.

Lifecycles works through an invoice: the bugs a status column invites, the chart and its callbacks, and real output for late and duplicate events, rollbacks, a race between two requests, and a new chart version.

Roles per duty

Give each kind of work a group role with only the grants it needs, and give each service's login user one of them.

create role read_only_role nologin;
create role worker_role nologin;
create role portal_role nologin;

grant usage on schema portal_api to portal_role;
grant select on all tables in schema portal_api to portal_role;
alter default privileges in schema portal_api grant select on tables to portal_role;

grant portal_role to portal_service;   -- the login user

Roles and grants are files in the plan like everything else, and reworked when they change. sqiff keeps an object's grants when it drops and recreates it.

Say why, in the schema

Comment every schema, table and column with comment on. The comment travels with the object into psql, GraphQL descriptions and sqiff's describe output, where a comment in a source file never goes. Use SQL comments in the deploy file for the reasons behind a decision: why a table is insert-only, why a lock is taken up front.

Never break running code

The database deploys before the new application code, and the old code keeps running against the new schema until the rollout finishes. Every change has to work with both.

hasql-check turns this into a test: before deploying, check the queries of the code that is currently running against the new schema. If any statement fails to prepare, the migration would break production. See CI and deploys.

Respect the locks

On a busy database, the danger in a migration is rarely the change itself but the lock it waits for, because every query queues behind a waiting ACCESS EXCLUSIVE request. The templates and linters agree on a small set of habits:

HabitWritten byChecked by
Bound every lock with lock_timeout = 50ms, and retry the deploy rather than raising itcreate-migration templatespsql-retry retries it
Build indexes concurrently, in a change of their owncreate-migration add-index, sqiffsqint lock/create-index
Add checks and foreign keys not valid, validate latervalidate-constraint, sqiffsqint lock/add-constraint
Avoid type changes that rewrite the table, or know you are making onesqiff reports the hazardsqint lock/alter-column-type, observed locks
Backfill in batches, committing between thembulk-updatesqint deferred/unfinished-backfill, if you register backfills in deferred.migration
Use set_config(…, false) in blocks that commit; set local is lost at COMMITtemplatessqint txn/set-local-across-commit
Avoid exception when in do blocks; each one opens a subtransactiontemplatesreview; psql-retry retries instead
Do not cast or call functions on indexed columns in predicatesyousqint index/cast-on-column, index/defeated