Scrivio Interview library
LeadershipPrincipal6 min read · updated 12 November 2026

Many teams treat the database as a simple store and handle consistency in application code. Over a decade, what does this cost, and how would you rebalance where invariants are enforced?

Invariants that live only in application code break under concurrency, when a new write path is added, and when someone fixes data directly in the database, so over a decade they cost incidents, slow data clean-ups and lost trust in the data. Constraints, unique keys, foreign keys and transactions in the database protect the rules for every client at once. I would rebalance with a simple principle, enforce critical invariants as close to the data as possible, and back it with deeper database skills across teams and a funded source of database expertise.

Why this question is asked

Treating the database as a dumb store is attractive: all the logic is in Java, testable with unit tests, and the schema stays simple. For years it seems to work. The cost arrives slowly, as duplicate customers, orders without lines and balances that do not add up, each one a small incident and a manual clean-up. Interviewers ask senior candidates this question because it is about where responsibility lives in a system over a long time, and how to change an engineering culture rather than one codebase. In this answer, we will see how application-only invariants break, what the database can guarantee instead, the principle I would set, and how to build the skills and support to apply it.

1How Application-Only Invariants Break

An invariant is a rule that must always be true about the data, such as 'email addresses are unique' or 'an order's total equals the sum of its lines'. When the only enforcement is Java code, the rule is true only as long as every write goes through that code, one at a time, and the code is correct. Each of those assumptions fails in practice.

Concurrency breaks check-then-act logic. Two requests both check that the email is free, both find nothing, and both insert. The check was correct for each request and wrong for the system.

Java
public User register(String email) {
if (users.existsByEmail(email)) throw new EmailTakenException(); // both requests: false
return users.save(new User(email)); // both insert
}
// SELECT email, count(*) FROM users GROUP BY email HAVING count(*) > 1;
// alice@example.com | 2

New write paths break it next: a batch import, a second service, an admin tool, a Kafka consumer written by another team. Each must reimplement the rule, and one of them will not. Finally, data fixes, a support engineer running an UPDATE to repair a customer record, bypass application code entirely.

2What the Database Can Guarantee

The database sees every write, from every client, and evaluates constraints inside the transaction, under its own concurrency control. A unique constraint cannot be raced; the second insert fails at commit time, whatever the application did. A foreign key makes orphan rows impossible. A CHECK constraint keeps a balance from going negative. A transaction makes a multi-step change atomic.

SQL
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);
ALTER TABLE order_line ADD CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id);
ALTER TABLE account ADD CONSTRAINT balance_not_negative CHECK (balance >= 0);
-- the same race now:
-- ERROR: duplicate key value violates unique constraint "users_email_key" (second request)
Where a rule is enforced
ThreatApp code onlyDatabase constraint
Two concurrent requestsCheck-then-act raceSecond write rejected
New service or batch jobMust reimplement the ruleCovered automatically
Manual data fixBypassedStill enforced
Bug in one code pathBad data savedWrite fails, bug visible
Rule needs other systems or rich contextPossibleNot possible

In Spring, the violation arrives as DataIntegrityViolationException, which the service can translate into a friendly 'email already registered'. The application still checks first for a good user experience, but the database is what guarantees the rule.

3The Cost Over a Decade

The long-term cost is mostly invisible in any single sprint. Each corrupt record needs an investigation, a fix script and often a customer conversation. Analytics and finance teams build defensive queries that de-duplicate and filter, and those workarounds spread. Migrations become risky, because nobody is sure what the data really contains, and adding a constraint later first requires cleaning years of violations. And trust erodes: when a report and the application disagree, people stop believing either.

There is also a skills cost. Teams that never use constraints, isolation levels or query plans lose the ability to reason about them, which makes the next concurrency bug harder to understand.

4A Principle: Enforce Critical Invariants Close to the Data

The principle I would set is: the more critical an invariant, the closer to the data it is enforced. Rules about identity, money, ownership and references belong in the database as constraints, keys and transactional updates. Rules that need context the database does not have, such as 'a premium customer may cancel within 30 days', stay in the domain model, inside one service and one transaction.

Applying it means a short checklist in design reviews: for each important rule, where is it enforced, and what happens under two concurrent requests, a second writer and a manual fix? Where the answer is 'only in Java', the team either adds a database guard or writes down why it cannot.

Step throughWhere should this rule be enforced?
  1. Is it about uniqueness, references or simple value ranges?
    YesDatabase constraintNoGo on
  2. Does it span rows in one service's data?
    YesTransaction with locking or SERIALIZABLENoGo on
  3. Does it need context outside the database?
    YesDomain model, inside one transactionNoDatabase constraint
  4. Add a reconciliation check for anything only the app enforces

4 steps in order. Play them, or step through them one at a time.

5Building the Skills and the Support

A principle only works if teams can apply it. Many Java developers can write a repository but have never designed a constraint or read an isolation level's guarantees. I would invest in that knowledge deliberately: a course covering constraints, transactions, isolation, locking and query plans, with exercises on our own schemas, and database topics in code review checklists.

Training is not enough on its own, because deep database knowledge takes years. So I would fund expertise as a long-term investment: either a small database platform team that reviews schema changes, owns migration tooling and helps with incidents, or database specialists embedded in the largest product areas. The cost is a few salaries; the return is fewer data incidents, safer migrations, and engineers who learn by working next to an expert.

6Rebalancing an Existing System

For existing systems, the change is incremental. First, measure: queries that find violations of the most important rules, such as duplicate emails or orphan lines, tell us how bad the data is. Then clean, add the constraint as NOT VALID in PostgreSQL so new writes are checked without scanning old rows, and validate it once the clean-up is done. We start with the rules where a violation costs the most, usually money and identity, and track the count of data incidents to show the effect.

7Follow-up questions

Does putting rules in the database make testing harder?

Not with tools like Testcontainers, which run the real database in integration tests. Constraint violations then show up in tests exactly as in production, which is better than unit tests that only exercise the Java check.

Is this a return to stored procedures for business logic?

No. The principle is about invariants, the rules that must never be broken, not about moving business workflows into the database. Constraints and keys are declarative and simple; complex logic stays in the application.

What about microservices that share no database?

Each service enforces its own invariants in its own database. Rules that cross services cannot be constraints, so they need sagas, idempotency and reconciliation, which is one more reason to draw service boundaries around data that must stay consistent.

8Conclusion

In this answer, we saw that invariants enforced only in application code fail under concurrency, new write paths and manual data fixes, and that over years this costs incidents, clean-ups, risky migrations and trust in the data. Database constraints, keys and transactions protect rules for every client, so the principle is to enforce critical invariants as close to the data as possible, supported by training in isolation, locking and query plans and by funded database expertise.

What to say in the interviewAbout 90 seconds aloud

Open with

The cost of keeping invariants only in application code builds up slowly. Check-then-act logic breaks under concurrency, for example two registrations both check an email is free and both insert.

Then, if they want more

Every new write path, a batch job, another service, an admin tool, has to reimplement the rule and eventually one doesn't. And manual data fixes bypass the code completely.

Over a decade that turns into duplicate customers, orphan records and balances that don't add up, each one an incident and a clean-up script, plus defensive queries in analytics and migrations nobody trusts. The database sees every write from every client, so unique constraints, foreign keys, check constraints and transactions protect the rule no matter who writes.

So I'd set a principle: the more critical the invariant, the closer to the data it's enforced. Identity, money, ownership and references go in the database; rules that need context the database doesn't have stay in the domain model inside one transaction.

In design reviews I'd ask, for each important rule, what happens with two concurrent requests, a second writer and a manual fix. To make that possible, teams need deeper database skills, so I'd invest in training on isolation, locking and query plans, and fund expertise long term, either a small database platform team or embedded specialists.

For existing systems, I'd measure violations, clean up, and add constraints incrementally, starting with money and identity.

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 "Many teams treat the database as a simple store and handle consistency in application...": https://scrivio-interview-library.netlify.app/databases/transactions/106cf76269/