Let Postgres say no: CHECK constraints as the last line of defence
An inventory app has one rule that matters more than the rest: you cannot hold less than nothing, and you cannot reserve more than you have. Everything else, the reports, the transfers, the exports, is only useful if the numbers are true.
I built ICS Stock, the stock system for a dental clinic, as the only engineer. When nobody else reviews your code, you want the guarantees that don't depend on your code being right.
The invariant
Every batch of every product, at every location, obeys one line:
0 ≤ reservedQuantity ≤ quantity
quantity is what is physically there. reservedQuantity is what a pending transfer has
claimed but not yet moved. Reserved stock can never exceed what exists, and neither can go
below zero.
Why checking in the service isn't enough
The obvious place for this rule is the service that dispatches stock:
if (batch.quantity - batch.reservedQuantity < requested) {
throw new ConflictException('Not enough stock');
}
await this.batches.update({ where: { id }, data: { reservedQuantity: { increment: requested } } });
This is correct for one request at a time. Now take two people dispatching the last ten gloves at the same moment. Both requests read the batch, both see ten available, both pass the check, and both write. The check and the write are two steps, and another request can run between them.
You can narrow that window with transactions and row locks, and I do (see the post on FEFO
allocation). But a lock is something every code path must remember to take. One forgotten
FOR UPDATE in a future feature and the race is back, silently.
Moving the rule into the database
Prisma's schema can't express a CHECK constraint, so I add it by hand to the migration. I generate the
migration with prisma migrate dev --create-only and append the SQL before applying it:
ALTER TABLE "Batch"
ADD CONSTRAINT stock_non_negative
CHECK ("reservedQuantity" >= 0 AND "reservedQuantity" <= "quantity");
Now the second request in that race fails. Postgres evaluates the constraint on the row as it would look after the write, and refuses a row that breaks the rule. A bug in application code can fail a request. It cannot corrupt the stock.
The same idea works for smaller rules. The schema has batch_offer_is_free, so a free supplier offer can't
carry a price, and batch_units_per_box, so the box-size fields can't contradict each other. None is clever. Each
one removes a class of bad data that no later bug can create.
Turning a violation into a useful answer
A constraint violation arrives in the app as a Postgres error with code 23514
(check_violation). Left alone, that becomes a 500, which tells the user nothing. An exception
filter maps it to a 409 or 422 with a message the form can show: "the stock changed while you
were working, please review and try again."
The constraint is the safety net, not the user experience. The service still validates first and gives the good error in the common case. The database only speaks up when something got past it.
Proving it
A constraint you haven't seen fire is a guess. The test that earns its keep forces the race against a real Postgres and watches the constraint catch it:
it('refuses to reserve more than exists, even when two requests race', async () => {
const batch = await createBatch({ quantity: 10 });
const results = await Promise.allSettled([
reserve(batch.id, 10),
reserve(batch.id, 10),
]);
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
expect(await readBatch(batch.id)).toMatchObject({ reservedQuantity: 10 });
});
Mocks can't give you this test, because the behaviour under test lives in the database.
What it costs
- Migrations carry hand-written SQL. Prisma won't generate it, so you have to remember it when you reset the schema. I keep the constraints in migration files and test that they exist.
- Error mapping is your job. Each constraint you add is one more error to translate.
- Rules must be simple. A CHECK sees one row. Anything that spans rows, like the last active admin, needs a different tool.
In exchange, the most important rule in the system no longer relies on anyone remembering anything.