Quick revision
The short answer
I would respond with the evidence: a foreign key check costs one index lookup per write, which is tiny next to 3 percent orphaned order lines and the cleanup they need, and ORM checks race under concurrency and are bypassed by scripts, migrations and other services. We clean the orphans first, then add the constraint as NOT VALID and run VALIDATE CONSTRAINT separately so PostgreSQL never holds a long blocking lock. Legitimate exceptions exist, such as sharded or cross-service data, but they must be explicit decisions with reconciliation jobs, not a blanket ban.
What to remember
In this answer, we answered the claim with numbers: one index lookup per write against 3 percent orphaned lines. We saw that ORM checks race and are bypassed by scripts and other writers, cleaned the orphans by classifying them and deciding to restore, reassign or delete, and added the constraint as NOT VALID followed by VALIDATE CONSTRAINT to avoid a long lock. Skipping foreign keys is legitimate for sharded, very high-volume or cross-service data, but only as an explicit decision backed by reconciliation.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would respond with the evidence: a foreign key check costs one index lookup per write, which is tiny next to 3 percent orphaned order lines and the cleanup they need, and ORM checks race under concurrency and are bypassed by scripts, migrations and other services. We clean the orphans first, then add the constraint as NOT VALID and run VALIDATE CONSTRAINT separately so PostgreSQL never holds a long blocking lock. Legitimate exceptions exist, such as sharded or cross-service data, but they must be explicit decisions with reconciliation jobs, not a blanket ban.
Why this question is asked
'Foreign keys are slow' is a belief many teams hold, often from one bad experience years ago. The audit result turns the debate from opinion into fact, and interviewers ask this scenario to see how we handle both the technical repair and the conversation with the team. In this answer, we will look at what a foreign key really costs, why the ORM did not protect the data, how to clean up and add the constraint without downtime, when skipping foreign keys is reasonable, and how to make the decision explicit in the future.
1What a Foreign Key Actually Costs
A foreign key from order_lines.product_id to products.id makes the database check, on every insert or update of product_id, that the product exists. That check is a lookup in the primary key index of products, which is almost always in memory: a few microseconds. On the parent side, deleting a product makes the database look for referencing lines, which is cheap if order_lines.product_id is indexed and painfully slow if not.
So the honest cost is one indexed lookup per child write, plus an index on the child column that we usually want for joins anyway. Benchmarks on typical OLTP tables show single-digit percent overhead on insert throughput. Compare that with 3 percent of order lines pointing nowhere: every report that joins lines to products silently drops or miscounts those rows, and someone must now investigate each one.
2Why the ORM Did Not Prevent the Orphans
'Our ORM handles integrity' usually means the application loads the product before saving a line. That check runs in the application, outside any lock on the product row, so it races with a concurrent delete.
4 messages in order. Play them, or step through them one at a time.
Without a constraint the database has no reason to refuse the insert.
And the ORM only sees writes that go through it. Data migrations written in SQL, a cleanup script run by an operator, a second service sharing the same database, or a bulk import with COPY all bypass it entirely. A constraint in the database is the only check that applies to every writer, every time.
3Cleaning the Orphans First
We cannot add the constraint while orphans exist, and we should not delete them blindly, because they may be real sales. First we measure and classify.
For each group the business decides. Products deleted by mistake can be restored from backups or recreated as inactive placeholder products, which keeps the sales history correct. Lines with obviously invalid ids may be reassigned from another source, such as the payment record. Only lines that are truly garbage (test data, duplicates) are deleted. We record what we did, because finance will ask.
4Adding the Constraint Without a Long Lock
A plain ALTER TABLE ... ADD FOREIGN KEY checks every existing row while holding a lock that blocks writes to order_lines, which on a big table can mean minutes of failed checkouts. PostgreSQL lets us split this into two steps.
- Find and classify orphansRestore, reassign or delete each group
- Index order_lines(product_id)CREATE INDEX CONCURRENTLY
- ADD CONSTRAINT ... NOT VALIDNew writes are checked from now on
- VALIDATE CONSTRAINTExisting rows checked, writes continue
- Validation passed?YesConstraint fully enforcedNoFix the reported rows, validate again
5 steps in order. Play them, or step through them one at a time.
NOT VALID creates the constraint and enforces it immediately for every new insert and update, but skips checking the existing rows. That takes only a brief lock. VALIDATE CONSTRAINT then scans the existing rows; it takes a SHARE UPDATE EXCLUSIVE lock on order_lines, which allows normal inserts, updates and deletes to continue. Once validation succeeds, the constraint is fully trusted. If validation finds a missed orphan, it fails without harm and we fix the row and run it again.
5When Skipping Foreign Keys Is Legitimate
There are real cases. When data is sharded across several databases, a line and its product may live on different servers, so no single database can check the reference. Very high-volume append-only logs, such as click events, sometimes drop constraints because a missing reference is harmless and the volume is enormous. And across services, a reference to another service's data is just an id, since each service owns its own database.
In those cases the integrity work does not disappear; it moves. We need reconciliation jobs that look for dangling references, metrics on how many there are, and an owner who acts on them. Notice that this team's case is none of these: products and order lines are in the same database, written by the same service.
6Making the Decision Explicit
I would not answer the team with a new blanket rule in the other direction. Instead, the design review template asks for every reference whether it has a foreign key, and if not, why not and what reconciliation replaces it. A migration linter can flag new reference columns without a constraint, so the choice is always conscious. And I would share the audit numbers with the team, because the strongest argument is the 3 percent they can see in their own data.
7Follow-up questions
What does NOT VALID do exactly?
It adds the constraint to the table's definition and enforces it for all future inserts and updates, but marks it as not yet validated, so PostgreSQL does not scan the existing rows and needs only a short lock. The planner also does not rely on an unvalidated constraint. VALIDATE CONSTRAINT later checks the existing rows under a lock that still allows normal writes, and on success marks the constraint as valid.
Will the foreign key make bulk imports slow?
It adds an index lookup per row, which is noticeable for multi-million row loads but rarely dominant. For large one-off loads we can load into a staging table, check and clean there, then insert into the real table. Dropping constraints for imports is risky, because the import is exactly when bad references arrive.
How do you convince a team that has had a bad experience with foreign keys?
Usually the bad experience was a missing index on the foreign key column, which made parent deletes scan the child table, or a cascade that deleted more than expected. I would show that both are fixable, measure the actual overhead on their workload, and set it next to the cost of the orphan cleanup.
8Conclusion
In this answer, we answered the claim with numbers: one index lookup per write against 3 percent orphaned lines. We saw that ORM checks race and are bypassed by scripts and other writers, cleaned the orphans by classifying them and deciding to restore, reassign or delete, and added the constraint as NOT VALID followed by VALIDATE CONSTRAINT to avoid a long lock. Skipping foreign keys is legitimate for sharded, very high-volume or cross-service data, but only as an explicit decision backed by reconciliation.
Open with
I would start from the audit, because three percent of order lines pointing at missing products is a real cost, not a theoretical one: every report joining lines to products is wrong and someone has to investigate each row.
Then, if they want more
Then the performance claim: a foreign key check is one primary key index lookup per child write, which is microseconds, and the parent side is cheap as long as the child column is indexed. The ORM argument does not hold either.
An application check reads the product outside any lock, so it races with a concurrent delete, and it is bypassed by SQL migrations, operator scripts, bulk loads and any other service touching the same database.
For the repair, I would first group the orphans and let the business decide per group whether to restore the product, reassign the lines or delete garbage.
Then I would add the constraint in PostgreSQL as NOT VALID, which enforces it for new writes with only a brief lock, and run VALIDATE CONSTRAINT separately, which scans existing rows while normal writes continue. I would also index order_lines product_id concurrently.
I would acknowledge that skipping foreign keys is legitimate for sharded data, huge append-only logs or cross-service references, but then reconciliation jobs replace the constraint. Going forward, every reference without a foreign key is an explicit, written decision in design review.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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 "A team says 'we do not use foreign keys because they slow down writes and our ORM...": https://scrivio-interview-library.netlify.app/databases/data-modeling/09f604f7b4/