Lesson 228 of 296
Migrations, soft deletes, audit trails and multi-tenant schemas
What you will learn
- What migrations are and why they are versioned
- Writing safe migrations on a live database
- The expand and contract pattern
- Soft deletes and their trade-offs
- Audit trails with a trigger
- Multi-tenant schema design (database view)
On this page
Migrations
A migration is a file that changes the database structure step by step, stored in Git with the code:
migrations/
20261101120000_create_customers.sql
20261105093000_add_city_to_customers.sql
20261120160000_create_orders.sqlA migration tool (Prisma Migrate, Knex, TypeORM, Flyway, Liquibase, node-pg-migrate) records which migrations have already run in a table of its own, and applies only the new ones, in order. Benefits:
- Every environment (your laptop, CI, staging, production) gets the same schema.
- Changes are reviewed in pull requests and are repeatable.
- The history explains how the schema evolved.
Rules: never edit a migration that has already run in a shared environment (write a new one); never change production schemas by hand; run migrations automatically in the deployment pipeline (Lesson 251).
Safe migrations on a live database
On a busy production database, some changes lock tables and stop the application, or break the old version of the code still running during a deployment.
| Change | Risk | Safer approach |
|---|---|---|
| Add a nullable column | Safe | |
| Add a column with a constant default | Safe in PostgreSQL 11+ (no table rewrite) | |
Add a NOT NULL column to a big table | Fails if rows exist without a value | Add nullable, backfill in batches, then add NOT NULL |
| Create an index | Blocks writes while building | CREATE INDEX CONCURRENTLY |
| Add a foreign key or CHECK | Scans the table while locking | Add NOT VALID, then VALIDATE CONSTRAINT separately |
| Rename or drop a column | Breaks running code that still uses it | Expand and contract |
| Change a column type | May rewrite the whole table | New column, backfill, switch, drop old |
Also set a lock_timeout in migrations, so a migration waiting for a lock fails quickly instead of queuing every other query behind it.
Expand and contract
Renaming customers.name to full_name without downtime:
- Expand: add
full_name. Deploy code that writes both columns and reads the old one. - Migrate data: backfill
full_namefromnamein batches. - Switch: deploy code that reads
full_name. - Contract: stop writing
name; later, drop the column.
Each step is backward-compatible with the code running at that moment. Interviewers love this answer for "how do you deploy schema changes with zero downtime?"
Soft deletes
Instead of deleting a row, mark it: deleted_at timestamptz NULL. Queries then filter WHERE deleted_at IS NULL.
| Pros | Cons |
|---|---|
| Undo and restore are easy | Every query must remember the filter; forgetting it shows deleted data |
| History is kept for support and audit | Unique constraints still see deleted rows (re-registering with the same email fails). Fix: a partial unique index UNIQUE (email) WHERE deleted_at IS NULL |
| Foreign keys stay valid | Tables grow; UK GDPR may require really erasing personal data on request |
Make the filter automatic (a view, an ORM extension or a repository), and plan hard deletion or anonymisation for personal data. Alternatives: move deleted rows to an archive table, or rely on an audit log.
Audit trails
"Who changed what, and when?" is required in finance, healthcare, legal and many B2B products. Options:
- Application-level: the service writes an
audit_logrow (actor, action, entity, before and after, timestamp, request ID) in the same transaction as the change. Knows the user, which the database does not. - Database trigger: a function that runs automatically on every change, so nothing is missed, even manual fixes:
CREATE TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
table_name text NOT NULL,
row_id text NOT NULL,
action text NOT NULL,
old_data jsonb,
new_data jsonb,
changed_by text,
changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION audit_changes() RETURNS trigger AS $$
BEGIN
INSERT INTO audit_log (table_name, row_id, action, old_data, new_data, changed_by)
VALUES (
TG_TABLE_NAME,
COALESCE(NEW.id, OLD.id)::text,
TG_OP,
CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) END,
CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) END,
current_setting('app.user_id', true)
);
RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER products_audit
AFTER INSERT OR UPDATE OR DELETE ON products
FOR EACH ROW EXECUTE FUNCTION audit_changes();The application sets app.user_id at the start of each transaction (SELECT set_config('app.user_id', '42', true)) so the trigger can record who made the change. Make audit tables append-only: the application's database user may insert but not update or delete them.
Multi-tenant schemas (database view)
Lesson 203 described the three models (shared tables, schema per tenant, database per tenant). For shared tables, the schema checklist:
tenant_idNOT NULL on every tenant-owned table, with a foreign key totenants.- Composite unique constraints include the tenant:
UNIQUE (tenant_id, invoice_number). - Indexes start with
tenant_id:(tenant_id, created_at DESC), because almost every query filters by tenant first. - Foreign keys between tenant tables can include the tenant (
FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id)) so a row can never point at another tenant's record. - Row-Level Security as a safety net. Tested in this course's database: with a policy
USING (tenant_id = current_setting('app.tenant_id')::integer)and the tenant set to 10, a restricted role saw only tenant 10's invoices (2 of 3 rows), while the table owner still saw all 3, because owners bypass RLS unlessFORCE ROW LEVEL SECURITYis set. So the application must connect as a non-owner role.
How to say it in an interview
"Schema changes go through versioned migrations in Git, applied automatically and never edited after they have run. On a live database I avoid long locks: indexes CONCURRENTLY, constraints NOT VALID then validated, NOT NULL columns added in steps with batched backfills, and renames done with expand and contract so old and new code both work during deployment. Soft deletes with a deleted_at column make undo easy but need automatic filtering, partial unique indexes and a plan for GDPR erasure. For audit trails I write audit rows in the same transaction or use a trigger, with the user ID passed through a session setting. For shared-table multi-tenancy I put tenant_id in every table, unique constraint and leading index, include it in foreign keys, and add row-level security with a non-owner application role."
Key words
| Word | Meaning |
|---|---|
| Migration | A versioned file that changes the schema |
| Backfill | Filling a new column for existing rows |
| Expand and contract | Changing schemas in backward-compatible steps |
| Soft delete | Marking rows as deleted instead of removing them |
| Partial unique index | A unique rule that applies only to some rows |
| Audit trail | A record of who changed what and when |
| Trigger | A function the database runs automatically on changes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.