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:
- Types and constraints for what a value may be: domains such as
email_addressortext_64,checkconstraints, foreign keys, exclusion constraints. - Generated columns and views for what can be computed from other data, so no service computes it differently.
- Functions for operations that have to happen together, called as one statement in one transaction.
- Statecharts for how an entity moves through its life.
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.';
- Domain schemas such as
billinghold tables and the functions that own them. - Personal data sits in its own schema, so its grants, retention and audits are in one place.
- API schemas hold only views and functions. They are the contract a consumer such as a GraphQL layer reads, and you can change the tables underneath without changing it.
- Transient data, such as a checkout in progress or a job queue, gets a schema of its own so it is never mistaken for a record.
- Infrastructure keeps its own schemas:
fsmfor statecharts, and others for partitioning or scheduling.
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.
- Expand, then contract. Add the new column, function or view in one release. Remove the old one in a later release, once nothing uses it.
- Add parameters with defaults. A new function parameter without a default breaks every existing caller.
- Keep composite types stable. Code that builds a value with
row(…)::some_typebreaks when the type gains a field. - Rename in two steps.
create-migration rename-column-step-1keeps both names in sync; step 2 ships after the code has moved.
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:
| Habit | Written by | Checked by |
|---|---|---|
Bound every lock with lock_timeout = 50ms, and retry the deploy rather than raising it | create-migration templates | psql-retry retries it |
Build indexes concurrently, in a change of their own | create-migration add-index, sqiff | sqint lock/create-index |
Add checks and foreign keys not valid, validate later | validate-constraint, sqiff | sqint lock/add-constraint |
| Avoid type changes that rewrite the table, or know you are making one | sqiff reports the hazard | sqint lock/alter-column-type, observed locks |
| Backfill in batches, committing between them | bulk-update | sqint deferred/unfinished-backfill, if you register backfills in deferred.migration |
Use set_config(…, false) in blocks that commit; set local is lost at COMMIT | templates | sqint txn/set-local-across-commit |
Avoid exception when in do blocks; each one opens a subtransaction | templates | review; psql-retry retries instead |
| Do not cast or call functions on indexed columns in predicates | you | sqint index/cast-on-column, index/defeated |