Scrivio Interview library
DesignPrincipal6 min read · updated 12 November 2026

Twenty years ago many systems kept business rules in stored procedures and triggers; then the industry moved rules into application code. Where should integrity rules live today, and how do you decide for a new platform?

Invariants about the data itself, such as uniqueness, references, allowed ranges and non-overlap, belong in the database as declarative constraints, because that is the cheapest and only race-free place to enforce them. Workflow and cross-aggregate business rules belong in application or domain code, where they are testable, versioned and observable; triggers and stored procedures are kept for narrow uses like audit or derived data. Rules that span services become eventually consistent and need sagas and reconciliation, and the whole split is written down once as a platform principle.

Background to this question

The pendulum between 'logic in the database' and 'logic in the application' has swung twice in many engineers' careers, and teams still argue about it at the start of every project. A principal engineer is asked this to see whether they can explain why the industry moved, what it lost by moving too far, and turn that into a rule a new platform can apply without re-arguing it. In this answer, we will look at why rules left the database, sort rules into kinds, place each kind, handle rules across services, and write the principle.

1Why Rules Moved Out of the Database

Twenty years ago many systems put business logic in stored procedures (programs stored and run inside the database) and triggers (code the database runs automatically on insert, update or delete). That had real advantages: logic ran next to the data, every client was forced through it, and one DBA team controlled it.

The problems grew with the systems. Procedure code was hard to unit test, hard to version and review alongside the application, hard to debug and observe (no tracing, few logs), and tied the company to one vendor's dialect. Triggers made writes do invisible work, so a simple insert could fire a chain of updates nobody remembered. Scaling meant scaling the one database that ran all the logic. When teams moved to frequent releases, CI pipelines and services, the logic moved into application code where those practices worked.

But the move often went too far. Many teams also dropped declarative constraints, which never had those problems, and lost the guarantees with them.

2Sorting Rules Into Kinds

The useful question is not 'database or application' but 'what kind of rule is this?'. Different kinds have different natural homes.

Kinds of rules and where they live
Kind of ruleExampleBest home
Data invariant on one tableemail unique, amount > 0Declarative constraint
Reference within one databaseline belongs to an existing orderForeign key
Non-overlap, rangesno double booking of a roomExclusion or CHECK constraint
Workflow and policyorders over 10,000 need approvalDomain code, tested
Cross-aggregate rulecredit limit across open ordersDomain service with locking
Audit and derived datahistory rows, updated_atTrigger or CDC, sparingly
Rule across servicesshipment needs a paid orderSaga plus reconciliation

3Invariants Go in Declarative Constraints

A data invariant is a fact that must hold for every row no matter who wrote it: uniqueness, a valid reference, a value range, a non-overlapping time slot. Declarative constraints (PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, NOT NULL, EXCLUDE) express these in one line, are enforced atomically with every write, and cannot race. Application checks for the same rules read and then write, so two concurrent requests can both pass.

Constraints also avoid the problems that drove the move away from procedures. They are declarative, so there is no procedural code to test. They live in versioned migrations next to the application. And when they fire, the error names the constraint, which is easy to observe. So the principle is not a return to database logic; it is keeping the part of database enforcement that was never the problem.

SQL
ALTER TABLE accounts ADD CONSTRAINT accounts_balance_nonneg CHECK (balance >= 0);
UPDATE accounts SET balance = balance - 500 WHERE id = 1; -- balance was 300
-- ERROR: new row for relation "accounts" violates check constraint "accounts_balance_nonneg"

4Workflow and Cross-Aggregate Rules Go in Domain Code

Rules about processes and policies change often, depend on context and need explanation: 'an order over 10,000 needs a manager's approval unless the customer is on the trusted list'. That belongs in domain code, where it is written in the team's main language, unit tested with examples, reviewed in pull requests, versioned with the release and visible in logs and traces.

Cross-aggregate rules, which involve several entities, also live there, but they need care with concurrency. 'Total of open orders must not exceed the customer's credit limit' cannot be a column constraint, and a naive check races. The domain service locks a single row that stands for the rule, here the customer row with SELECT ... FOR UPDATE, then checks and writes in one transaction. The database still provides the locking; the code provides the rule.

5Rules Across Services Become Eventual

Once data is split across services with their own databases, no transaction spans them, so a rule like 'a shipment may only be created for a paid order' cannot be checked atomically. The shipping service learns about payment through an event. Such rules are implemented as sagas: a sequence of local transactions, each publishing an event, with a compensating action if a later step fails (for example cancelling the shipment and refunding if the order turns out not to be payable).

Because the rule is now eventually consistent, we also need reconciliation: a regular job that looks for states that should never persist, such as shipments without a paid order after one hour, and alerts or repairs them. That is the price of service boundaries, and it is a reason to keep strongly related data inside one service.

Step throughWhere rules are enforced on a new platform
  1. Across servicesSagas, compensations, reconciliation jobs
  2. Domain codeWorkflow, policies, cross-aggregate rules with locks
  3. Database constraintsKeys, references, checks, exclusion constraints
  4. Triggers and CDCAudit history and derived data only

4 layers, from the top down. Step through them one at a time.

Each rule is enforced at the lowest layer that can express it reliably.

6Writing the Platform Principle

For a new platform I would write the split down once, in a short architecture decision record, so teams do not repeat the debate per project. In summary: data invariants are declared as database constraints, and an exception needs a written reason; workflow and policy rules are domain code with tests; triggers are allowed only for audit and derived data and must be listed in the service's documentation; cross-service rules are sagas with a named reconciliation job. Then templates and migration linters enforce the mechanical parts, and design reviews check the rest.

The test for any new rule becomes a simple question: can it be stated as a fact about rows in one database? If yes, it is a constraint. If it needs a process, context or other systems, it is code.

7Follow-up questions

Are there cases where a stored procedure is still the right choice?

Yes, a few. Heavy set-based data processing that would otherwise ship millions of rows to the application, such as a monthly rebate calculation, can be far faster as SQL run in the database. The difference from the old days is that it is kept in the repository, applied by migrations, tested against a real database in CI, and treated as an exception rather than the default.

How do you test database constraints?

With integration tests against the same database engine, for example PostgreSQL in Testcontainers, that try to insert invalid data and assert the specific constraint violation. Those tests are short and document the rule for the next developer.

Doesn't duplicating rules in code and constraints violate DRY?

Somewhat, but the two serve different purposes. Code validation gives the user a friendly message before the write; the constraint is the guarantee for every writer. The duplication is small, because constraints are one line each, and the constraint is the one that is always right.

8Conclusion

In this answer, we saw why business logic left stored procedures and triggers (hard to test, version, observe and scale) and why that move should not have taken declarative constraints with it. We sorted rules into kinds: data invariants as constraints, workflow and cross-aggregate rules in domain code with proper locking, triggers only for audit and derived data, and cross-service rules as sagas with reconciliation. Writing that split down as a platform principle ends the per-project debate.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by separating two things the industry moved away from together. Stored procedures and triggers left the database for good reasons: procedural code there was hard to test, version, review, debug and scale, and triggers made writes do invisible work.

Then, if they want more

But many teams also dropped declarative constraints, which never had those problems, and that was a mistake. So my split is by kind of rule. Invariants about the data itself, like uniqueness, valid references, value ranges and non-overlap, are declared as constraints: primary and unique keys, foreign keys, checks and exclusion constraints.

They are one line, enforced on every write by every client, race-free and versioned in migrations. Workflow and policy rules, like approvals over a threshold, live in domain code where they are unit tested and observable.

Cross-aggregate rules also live in code, but they lock a row that stands for the rule, such as the customer row for a credit limit. Triggers I keep for audit history or derived columns, documented. Across services there is no shared transaction, so rules become eventually consistent: sagas with compensations, and reconciliation jobs that catch states that should not persist.

For a new platform I would write this once as a decision record, with a simple test: if the rule can be stated as a fact about rows in one database, it is a constraint; otherwise it is code.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Twenty years ago many systems kept business rules in stored procedures and triggers...": https://scrivio-interview-library.netlify.app/databases/data-modeling/2ad685dc58/