Video in progress

"Orphan" rows and impossible statuses are showing up in the database. At which layers do you protect data invariants?

The cheapest and most reliable protection is constraints in the database itself: NOT NULL, FK, unique, CHECK, exclusion. Application validation is for a clear error message to the user, and the database is the last barrier. Regular check jobs also reveal violations early.

📖 Answer

This is usually how data gets corrupted: a script that bypassed the application validation, two services writing to one table, a race between parallel requests, or an UPDATE done by hand "temporarily". A check in the application protects against none of these.

In the database:

ALTER TABLE payment
  ADD CONSTRAINT payment_order_fk FOREIGN KEY (order_id) REFERENCES orders(id) NOT VALID;
ALTER TABLE payment VALIDATE CONSTRAINT payment_order_fk;

ALTER TABLE orders
  ADD CONSTRAINT orders_paid_has_date
  CHECK (status <> 'PAID' OR paid_at IS NOT NULL) NOT VALID;

If the table already has violating rows, I use NOT VALID to stop new violations immediately, and run VALIDATE after cleaning up the old ones.

There are invariants that can't be expressed in the database: "the order total equals the sum of its lines", "every active subscription has a next payment date", consistency across services. For those:

-- daily invariant job
SELECT o.id
FROM orders o
JOIN order_items i ON i.order_id = o.id
GROUP BY o.id, o.total
HAVING o.total <> sum(i.price * i.qty);

If the result isn't empty, an alert and a ticket. I keep such check queries in the code, and with every new business rule another one is added.

My rule at the organization level: when I review a new table, I ask "which invariant is held by whom?". An answer of "only in the application" is a warning sign. Application validation stays, but it's for UX, not for integrity.