Video in progress

Denormalization — duplicating data to speed up reads: when is it right, and what does it cost?

If a heavily read page does a heavy join every time, copying the needed fields in advance (for example, the customer name on the order, the comment count on the post) makes reads cheaper. The cost is that writes get more complicated and the copies can drift out of sync.

📖 Answer

In a normalized schema, each fact lives in one place. That's ideal for writes. But if a feed page assembles the author name, avatar, comment count and like count for each post with joins and COUNT, the DB struggles when the page is opened thousands of times a second.

Examples of denormalization:

  • a posts.comment_count column — +1 on every comment;
  • orders.customer_name — a copy of the name at the time of the order;
  • in NoSQL, the product name and price inside the order document.

When it's right:

  • reads outnumber writes by a wide margin;
  • a slightly stale copy does no harm, or the copy has to be a historical fact (the price on an order must not change later — that's actually the correct model).

The cost:

  • every write updates several places — if you forget one, the data diverges;
  • if a user changes their name, do you need to update the copy in their 10 thousand posts? Often the answer is "no, we store only the ID and take the name from the cache".
-- the counter in one transaction
BEGIN;
INSERT INTO comments(post_id, author_id, body) VALUES (42, 7, '...');
UPDATE posts SET comment_count = comment_count + 1 WHERE id = 42;
COMMIT;

And a check job from time to time: does comment_count match the real COUNT(*)? If they differ, that's a bug signal.