Rules That Must Always Hold
A bug report comes in: order 88213 shipped, and the customer was never charged. You open the orders table and find the row. is_paid is false, is_shipped is true, is_cancelled is false. The warehouse screen showed the order in its "ready to ship" list because that list filters on is_cancelled = false AND is_shipped = false, and nothing in it checked payment. The payment step had failed silently a day earlier.
The agent that built this wrote clean code. Each flag is set in the right place on the happy path. The flaw is in the shape of the data. Three independent booleans can hold eight combinations, and the business allows only a few of them. The table happily stores the other ones, and sooner or later some code path writes one.
The repair starts before any code: name the things in the problem and the states they move through, write down the rules that must always be true about them, and then put those rules somewhere every write has to pass through.
Nouns, identity and the words you use for them
Start by naming the things in the domain. In a shop there are customers, orders, products, payments and shipments. Some of these keep an identity over time: order 88213 is still the same order after its address changes. Those are entities. Others are defined entirely by their contents: an amount of 25.00 EUR is interchangeable with any other 25.00 EUR, and an address is just its fields. Those are values. The distinction matters because entities have lifecycles and values do not. You track what happens to an order. You replace an amount.
Then write down how they relate. An order has exactly one customer. An order has one or more lines. A payment belongs to exactly one order. Each of those sentences is a rule, and several of them will become invariants.
Use the same words everywhere. If the business says "fulfilled", the spec says "shipped", the code says dispatched and the database stores status = 3, then checking the code against a business rule needs a translation at every step. Pick one term per concept and use it in conversation, specs, code and schema. Domain-driven design calls this a ubiquitous language. The practical test is whether a person from operations could read your state names and nod.
A lifecycle is a state machine
The order in the bug report moves through a lifecycle: it is created, it is paid, it is shipped, it is delivered. At some points it can be cancelled. That is a state machine: a fixed set of states and a fixed set of allowed moves between them.
The boolean model tries to describe the same lifecycle with flags. Count what it allows. Three booleans give 2 × 2 × 2 = 8 combinations:
| is_paid | is_shipped | is_cancelled | Meaning |
|---|---|---|---|
| false | false | false | Awaiting payment |
| true | false | false | Paid, ready to ship |
| true | true | false | Shipped |
| false | false | true | Cancelled before payment |
| true | false | true | Cancelled after payment, refund due |
| false | true | false | Shipped but never paid |
| false | true | true | Shipped, cancelled, never paid |
| true | true | true | Shipped and cancelled |
The business recognizes five of those rows, and they cover five of the six states in the machine below. The last three rows are states the business says cannot happen, and the schema can hold all of them. The bug report is row six. There is no row for "delivered" at all, so the next feature will add a fourth boolean and double the table to sixteen rows.
Written as a state machine, the lifecycle has six states and a short list of transitions:
awaiting_payment --pay--> paid
awaiting_payment --cancel--> cancelled
paid --ship--> shipped
paid --cancel--> refund_pending
shipped --deliver--> deliveredAnything not on this list is forbidden. You cannot ship from awaiting_payment. You cannot cancel a shipped order; that would be a return, which is a different process with its own states. Writing the forbidden moves down explicitly is as useful as writing the allowed ones, because the forbidden moves are where bugs live.
Make the illegal states impossible to write
The next step is to choose types so the impossible rows cannot be constructed. In TypeScript a discriminated union does this. Each state carries only the data that makes sense in that state:
type Order =
| { status: "awaiting_payment"; id: string; totalCents: number }
| { status: "paid"; id: string; totalCents: number; paymentId: string }
| { status: "shipped"; id: string; totalCents: number; paymentId: string; trackingNumber: string }
| { status: "delivered"; id: string; totalCents: number; paymentId: string; trackingNumber: string; deliveredAt: Date }
| { status: "cancelled"; id: string; totalCents: number }
| { status: "refund_pending"; id: string; totalCents: number; paymentId: string };
function ship(order: Order, trackingNumber: string): Order {
if (order.status !== "paid") {
throw new Error(`cannot ship order ${order.id} in status ${order.status}`);
}
return { ...order, status: "shipped", trackingNumber };
}Look at what the type rules out. A shipped order must carry a paymentId, so the compiler rejects { status: "shipped", trackingNumber: "X" } and "shipped but never paid" cannot be written by accident. The guarantee is narrow: the type says a shipped order carries a payment ID string and nothing more. It does not say the payment succeeded, that the ID names a real payment, or that the caller went through ship, because anyone can write an object literal with an invented ID.
The rule "only paid orders ship" lives in ship, where you can read it, and that function refuses every state except paid. The rest has to be enforced where every write passes: ship and its siblings should check that the payment actually succeeded, and the database should refuse records the type cannot.
In the database you get the same effect with a single status column and constraints that tie the other columns to it. This block runs on SQLite and plays the bulk import that writes rows directly:
PRAGMA foreign_keys = ON; -- SQLite checks foreign keys only when asked
CREATE TABLE payments (id TEXT PRIMARY KEY, status TEXT NOT NULL);
CREATE TABLE orders (
id TEXT PRIMARY KEY,
status TEXT NOT NULL CHECK (status IN
('awaiting_payment','paid','shipped','delivered','cancelled','refund_pending')),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
payment_id TEXT REFERENCES payments (id),
tracking_number TEXT,
CHECK (status NOT IN ('paid','shipped','delivered','refund_pending') OR payment_id IS NOT NULL),
CHECK (status NOT IN ('shipped','delivered') OR tracking_number IS NOT NULL)
);
INSERT INTO payments VALUES ('pay-1', 'succeeded'), ('pay-2', 'failed');
-- The import never calls ship(). OR IGNORE skips a row that breaks a CHECK
-- instead of stopping. It does not cover foreign keys: a row naming a payment
-- that does not exist stops the whole import with an error.
INSERT OR IGNORE INTO orders VALUES ('o-1', 'awaiting_payment', 2500, NULL, NULL);
INSERT OR IGNORE INTO orders VALUES ('o-2', 'shipped', 2500, 'pay-1', 'T-100');
INSERT OR IGNORE INTO orders VALUES ('o-3', 'shipped', 2500, NULL, 'T-101'); -- shipped, never paid
INSERT OR IGNORE INTO orders VALUES ('o-4', 'paid', 2500, NULL, NULL); -- paid, no payment
INSERT OR IGNORE INTO orders VALUES ('o-5', 'shipped', 2500, 'pay-1', NULL); -- shipped, no tracking
INSERT OR IGNORE INTO orders VALUES ('o-6', 'shipped', 2500, 'pay-2', 'T-102'); -- payment failed
SELECT o.id, o.status, o.payment_id, p.status AS payment_status
FROM orders o LEFT JOIN payments p ON p.id = o.payment_id
ORDER BY o.id;Output
The two table-level checks say: if the order is in a paid-or-later state, it has a payment; if it has shipped, it has a tracking number. The foreign key means the payment ID must name a row in payments, so a write that bypasses ship cannot invent one. Of the six rows the import tries, the three that break a check never reach the table. Order o-6 does get in, shipped against a payment that exists and failed. That the payment's status is succeeded is left to the write path, or to a composite key that includes the payment's status. The same CREATE TABLE works in PostgreSQL, which enforces foreign keys without being asked.
Invariants, and where to enforce them
An invariant is a rule that must hold at every moment, for every record, no matter which code wrote it. "An account balance never goes below zero." "Every order has exactly one customer." "A shipped order has a payment." The word "every" is doing the work. A rule that holds on the main path and breaks on another path does not hold.
Systems usually have more write paths than the person designing the main one remembers. There is the web request. There is also the CSV bulk import someone wrote for a big customer, the admin tool support staff use to fix records, the nightly job that expires stale carts, and the migration script from last year. A common agent mistake is to put the rule in the request handler, because that is the code it was asked to change. The bulk import calls the database directly and never goes near the handler, so the rule is silently skipped there.

To find the right place, list every path that writes the data and ask which layer all of them pass through. That gives you two good answers and one weak one:
- The database, through types,
NOT NULL, foreign keys, unique constraints andCHECKconstraints. Every path that writes a row goes through it, including tools written years from now. Use it for any rule it can express. - One module that owns the entity, where every write goes through functions like
shipandcancel. Use it for rules the database cannot express, such as "only the account owner can cancel", and make sure the import and the admin tool call it too. - Validation in a request handler or a form. Useful for giving the user a clear message. Weak as enforcement, because only one path runs it.
A good habit is to parse data into the strong type at the edge and pass only the strong type inward. The bulk import then has to produce an Order, which it cannot do for an impossible combination. Alexis King's essay "Parse, don't validate" makes this argument at length.
One word, several meanings
The third common modeling mistake is stretching one object to cover several concepts that share a name. An agent builds a User type. Then it adds isAdmin for staff, then billingEmail and vatNumber for the person who pays the invoice, then permissions for team members. Now a change to how billing contacts work touches the same type the login code depends on, and a support admin who is also a customer has one row trying to be two people.

User type stretched over three meanings becomes three types, one per department. Where two of them are the same human, they share an ID and nothing else.These are different things that the business happens to call "user" in different departments. Sales means a customer. Support means a staff member with an admin role. Finance means whoever receives the invoice, who may never log in at all. Domain-driven design calls each of those areas a bounded context: a part of the system inside which a word has one meaning. The fix is separate types, Customer, StaffMember and BillingContact, linked by ID where they refer to the same human. Each context can then change its own model without breaking the others.
The warning sign in code is a type whose fields are mostly optional and mostly used by different parts of the program. Ask which fields each caller reads. If the answer splits cleanly into groups, you have found the boundaries.
Stating a rule precisely enough for a machine to attack it
Once an invariant is written precisely, a program can search for a counterexample. Property-based testing generates many random inputs and checks that a rule holds for each one. Here the input is a random sequence of events thrown at an order, and the property is the invariant. A library such as fast-check generates the inputs and shrinks failures for you. This version does both by hand so it can run on the page, against a pay that skips the check and one that makes it:
type Order =
| { status: "awaiting_payment"; id: string }
| { status: "paid" | "refund_pending"; id: string; paymentId: string }
| { status: "shipped" | "delivered"; id: string; paymentId: string; trackingNumber: string }
| { status: "cancelled"; id: string };
type OrderEvent =
| { type: "pay"; paymentId: string }
| { type: "ship"; trackingNumber: string }
| { type: "deliver" }
| { type: "cancel" };
type Apply = (order: Order, e: OrderEvent, succeeded: Set<string>) => Order;
// The transitions from the state machine. This version takes the set of
// payments that succeeded and never looks at it.
const applyBuggy: Apply = (order, e) => {
if (e.type === "pay" && order.status === "awaiting_payment") return { ...order, status: "paid", paymentId: e.paymentId };
if (e.type === "ship" && order.status === "paid") return { ...order, status: "shipped", trackingNumber: e.trackingNumber };
if (e.type === "deliver" && order.status === "shipped") return { ...order, status: "delivered" };
if (e.type === "cancel" && order.status === "awaiting_payment") return { status: "cancelled", id: order.id };
if (e.type === "cancel" && order.status === "paid") return { ...order, status: "refund_pending" };
throw new Error(`cannot ${e.type} an order in status ${order.status}`);
};
// The fix: refuse a payment that did not succeed, then apply as before.
const applyFixed: Apply = (order, e, succeeded) => {
if (e.type === "pay" && !succeeded.has(e.paymentId)) throw new Error(`payment ${e.paymentId} did not succeed`);
return applyBuggy(order, e, succeeded);
};
// An independent model of the world: the payments that really succeeded.
// "pay-bad" is never in it, so any order that ends up holding it is wrong.
const succeeded = new Set(["pay-1", "pay-2"]);
// The property: no sequence of events leaves an order shipped or delivered
// with a payment that is not in the model.
function holds(apply: Apply, events: OrderEvent[]): boolean {
let order: Order = { status: "awaiting_payment", id: "o-1" };
for (const e of events) {
try {
order = apply(order, e, succeeded);
} catch {
// A rejected transition leaves the order unchanged.
}
if ((order.status === "shipped" || order.status === "delivered") && !succeeded.has(order.paymentId)) return false;
}
return true;
}
const choices: OrderEvent[] = [
{ type: "pay", paymentId: "pay-1" },
{ type: "pay", paymentId: "pay-2" },
{ type: "pay", paymentId: "pay-bad" },
{ type: "ship", trackingNumber: "T-1" },
{ type: "deliver" },
{ type: "cancel" },
];
const show = (events: OrderEvent[]) => events.map((e) => (e.type === "pay" ? `pay ${e.paymentId}` : e.type)).join(", ");
// Shrinking: drop one event at a time while the sequence still fails.
function shrink(apply: Apply, events: OrderEvent[]): OrderEvent[] {
for (let i = 0; i < events.length; i++) {
const shorter = [...events.slice(0, i), ...events.slice(i + 1)];
if (!holds(apply, shorter)) return shrink(apply, shorter);
}
return events;
}
// Throws 100 random sequences of up to 20 events at one version. The random
// numbers are seeded, so every run tries the same sequences.
function check(name: string, apply: Apply) {
let seed = 42;
const random = () => (seed = (seed * 48271) % 2147483647) / 2147483647;
for (let run = 1; run <= 100; run++) {
const events = Array.from({ length: Math.floor(random() * 21) }, () => choices[Math.floor(random() * choices.length)]);
if (!holds(apply, events)) {
console.log(`${name}: run ${run} failed with ${events.length} events: ${show(events)}`);
console.log(`${name}: shrunk to: ${show(shrink(apply, events))}`);
return;
}
}
console.log(`${name}: 100 runs, no counterexample`);
}
check("buggy", applyBuggy);
check("fixed", applyFixed);Output
The test makes no claim about which sequences are sensible. It throws up to a hundred random ones at each version (also fast-check's default run count), stopping at the first counterexample, and checks that no sequence ever produces a shipped or delivered order whose payment ID is missing from the model of successful payments. A weaker property that only checked the ID exists would pass an order paid with pay-bad. The buggy version fails on a long, noisy sequence, and dropping events while it still fails leaves pay pay-bad followed by ship, which points at the missing check. fast-check also tries to shrink a failing sequence to a simpler one; neither it nor this loop promises the smallest possible case.

pay pay-bad, then ship, which points at the missing check.An agent can write this kind of test quickly. Deciding what the property is, that shipped implies paid with a payment that really succeeded, is the part that stays with you.
Reading a bug report as a broken rule
Many data bugs are an invariant that was never stated or was enforced on only one path. When a report comes in, ask three questions. What rule does the business believe about this data? Is that rule written anywhere the code enforces it? Which path wrote the bad record, and does that path go through the enforcement?
For order 88213, the rule is "an order ships only after it is paid". It was never stated; it existed only as the order the happy path happened to set flags in. The warehouse list, a separate reader, trusted flags that could disagree with each other. The fix is a status column with six values, transitions that refuse to skip payment, and a database foreign key that rejects a shipped order whose payment does not exist, from any path at all.
A rule is enforced when there is no code path, including ones not yet written, that can store a record breaking it.