skip to content

denormalizing on purpose

counters, snapshots and copies you choose to keep, and the trigger that keeps them honest.

address
everything.design.denormalization
part
part 7, schema design
chapter
chapter 7 of 13
reading time
7 min

denormalizing is storing a fact twice on purpose: a count next to the rows it counts, a total on the order, a copy of a name in a search table. reads get cheaper, and every write that touches the original now has to update the copy too.

the copy is only worth having if something guarantees it stays right: a trigger in the same transaction, a materialized view you refresh, or a cache you're willing to have be stale. "the app remembers" isn't a guarantee.

the picture

you know the comment count under every post? counting comments on every page view is a query per post, so sites store the number. then one day the count says 3 and the post has 2, and nobody can say when it went wrong.

think of a shop's till total written on a whiteboard at the end of each sale (the copy), next to the till roll (the original). reading the whiteboard is instant. but if anyone ever rings up a refund without updating the board, the board is wrong forever, and only re-adding the roll finds out.

before anything runs
posts, after this step
posts after: start
idint4titletextcomment_countint4real_countint8
1why pages are 8 KB00
2the left-handed teapot00
(2 rows)
changed

the stored count and the real count, side by side.

step 1/5
real output, postgres 18.6 (PGlite 0.5.12) · counter
a stored comment_count next to the real count, computed by postgres in the same query. step through. the app keeps it right while it remembers; a script that doesn't makes the rows drift. after a trigger takes over, the same careless script can't break it.

why bother: the read you're saving

the bank dataset keeps accounts.balance, which is the opening balance plus every transfer in, minus every transfer out. that's a denormalization: the balance is derivable from transfers. first, is it right?

sqldb=bank
SELECT count(*) AS accounts,
       count(*) FILTER (WHERE a.balance <> a.opening_balance + coalesce(i.total, 0) - coalesce(o.total, 0)) AS wrong
FROM accounts AS a
LEFT JOIN (SELECT to_id, sum(amount) AS total FROM transfers GROUP BY to_id) AS i ON i.to_id = a.id
LEFT JOIN (SELECT from_id, sum(amount) AS total FROM transfers GROUP BY from_id) AS o ON o.from_id = a.id;
output, from postgres 18.6
SELECT 1
accountsint8wrongint8
10000
(1 row)

all 1,000 right. now the price of not having it. computing one account's balance from transfers (no index on from_id or to_id, as in most schemas that "will add one later") reads every transfer:

sqldb=bank
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT a.opening_balance
       + coalesce((SELECT sum(amount) FROM transfers WHERE to_id = a.id), 0)
       - coalesce((SELECT sum(amount) FROM transfers WHERE from_id = a.id), 0)
FROM accounts AS a WHERE a.id = 500;
output, from postgres 18.6
EXPLAIN
Index Scan using accounts_pkey on accounts a (actual rows=1.00 loops=1) Index Cond: (id = 500) Index Searches: 1 SubPlan 1 -> Aggregate (actual rows=1.00 loops=1) -> Seq Scan on transfers (actual rows=13.00 loops=1) Filter: (to_id = a.id) Rows Removed by Filter: 19987 SubPlan 2 -> Aggregate (actual rows=1.00 loops=1) -> Seq Scan on transfers transfers_1 (actual rows=18.00 loops=1) Filter: (from_id = a.id) Rows Removed by Filter: 19982

two seq scans of 20,000 transfers, for one number that's sitting in balance, one primary key lookup away. with indexes on from_id and to_id the computed version gets fast again, until an account has a million transfers. that's the trade: denormalize when the derivation is expensive and read far more often than the inputs change.

keeping the copy honest

the figure's trigger is the core pattern: the copy is updated in the same transaction as the original, so they commit or roll back together. a crash, a rollback, a second app or a psql session can't split them.

predict the output
sql
-- the trigger from the figure is in place. comment_count is 0.
BEGIN;
INSERT INTO comments (post_id, body) VALUES (1, 'a'), (1, 'b');
ROLLBACK;
INSERT INTO comments (post_id, body) VALUES (1, 'c');
SELECT comment_count FROM posts WHERE id = 1;
sqlempty db · session trig
continues session trig (1 earlier block run first)
BEGIN;
INSERT INTO comments (post_id, body) VALUES (1, 'a'), (1, 'b');
ROLLBACK;
INSERT INTO comments (post_id, body) VALUES (1, 'c');
SELECT comment_count, (SELECT count(*) FROM comments) AS real_count FROM posts WHERE id = 1;
output, from postgres 18.6
#1 · BEGIN
#2 · INSERT 0 2
#3 · ROLLBACK
#4 · INSERT 0 1
#5 · SELECT 1
comment_countint4real_countint8
11
(1 row)

a row trigger fires once per row, so a bulk insert of 10,000 comments runs 10,000 UPDATEs on posts. for bulk paths, a statement-level trigger with a transition table does one grouped UPDATE instead. and a trigger misses what bypasses triggers: TRUNCATE doesn't fire row triggers, and session_replication_role = replica (used by some loaders) skips them. (triggers has the details.)

the hot row

a counter in one row is one row lock. every transaction that bumps it has to wait for the previous one to commit:

T1
·
T2
·
1
BEGIN; UPDATE posts SET comment_count = comment_count + 1 WHERE id = 1→ UPDATE 1
lock manager
  • T1RowExclusiveLockposts
  • T1RowExclusiveLockposts_pkey
  • T1ExclusiveLockxid 759
  • T1ExclusiveLock4/4

T1 adds a comment and bumps post 1's counter. its transaction is still open, so it holds the row lock.

step 1/5
real output, a postgres 18.6 server · hot-counter
two real sessions on a postgres 18.6 server, both adding a comment to post 1. T2's UPDATE waits (dashed) until T1 commits, then applies its +1 on top of T1's. correct, and strictly one at a time. the panel is pg_locks.

the increments are never lost (an UPDATE ... SET n = n + 1 re-reads the newest version after the wait, see lost updates). but the counter has become a queue. if a transaction holds it for 50 ms, that row can absorb about 20 writes a second, no matter how many cores you have. fixes, from simplest:

  • keep transactions that touch the counter short, and bump it last.
  • split the counter: N rows per post (post_id, slot, n), each writer picks a slot, readers sum(n). N times the throughput, slightly costlier reads.
  • don't keep it live: insert one row per event (no contention), and roll up periodically or with a materialized view.

the menu

hover a stage.

ways to keep a derived value, from always-correct to fastest. each step down trades freshness or effort for read speed.

some "copies" aren't denormalization at all. the price on an order line is the price then, a different fact from the product's price now, and it must not follow the product (normal forms has the long version). the shop dataset keeps both on purpose.

keylines

  • denormalizing stores a derivable fact twice, to make reads cheaper.
  • the copy is only as good as what keeps it in sync: a trigger in the same transaction is the strong option.
  • a counter kept by hand drifts the first time some code path forgets.
  • one counter row is one lock: every writer waits in line.
  • measure first, then write the invariant as a query and keep checking it.