Video in progress
When does deliberately departing from normalization pay off, and what price do you pay?
Denormalization pays off when reads or aggregates are expensive and the data changes rarely: for example, a copy of the product price on an order, or comment_count on a post. The price is keeping the copies in sync, and the risk of inconsistency.
📖 Answer
I make every denormalization only after answering "where is the copy updated, and what happens if it's wrong".
The cases where it's really justified:
- A historical fact.
order_item.unit_priceisn't really denormalization, it's a separate fact. The product price changes tomorrow, and the old order must not change. - Counters.
post.comment_count, so you don't runcount(*)on every list. But on a hot post this creates contention on a single row. - A read model. A joined table or a materialized view for search or a dashboard.
-- update the copy in the same transaction
BEGIN;
INSERT INTO comment(post_id, body) VALUES (:p, :b);
UPDATE post SET comment_count = comment_count + 1 WHERE id = :p;
COMMIT;
The price:
- every code path that writes must remember to update the copy (or a trigger does it, but triggers are hidden logic);
- over time the copy "drifts", and you'll need a correction job that recomputes it;
- writes get slower.
A materialized view is a lighter option: REFRESH MATERIALIZED VIEW CONCURRENTLY (requires a unique index) refreshes without blocking reads, but the data goes stale between refreshes.
My order of work: first a normal schema and the right indexes. Denormalization comes after I've measured and proven that a specific query is slow.
Sign up to mark studied questions and save your progress.