Normalization vs denormalization
Why storing each fact once prevents a class of bugs, when joins become too expensive, and how to copy data on purpose without letting the copies drift.
The problem
A small shop keeps everything in one orders table. Each row holds the order id, the customer’s name, email and address, the product name and price, and the quantity. It is easy to read. Then three things go wrong.
- Update anomaly. A customer with 340 orders changes their email. That is 340 rows to change. A bug or a crash part of the way through leaves the customer with two addresses and nothing to say which is right.
- Insertion anomaly. A new product cannot be added until somebody orders it, because there is no row to put it in.
- Deletion anomaly. Delete a customer’s only order and the customer’s details go with it.
Edgar Codd’s normal forms, published in the early 1970s, remove these bugs by design: split the data so that each fact is stored exactly once.
The shop grows and meets the opposite problem. The order history page now joins six tables. A profile page counts a seller’s two million orders on every view. The data is split across shards and services, so a join has become a chain of network calls. The team starts copying data on purpose so that a read touches one row. That is denormalization, and it brings the update anomaly back as something you have to manage.
This lesson covers both directions and how to choose.
The normal forms that matter in practice
Three forms cover nearly every real schema.
| Form | Rule | Violation | Fix |
|---|---|---|---|
| 1NF | One value per column, no repeating groups | product_ids = '12,15,19' in an order row |
An order_items table, one row per item |
| 2NF | No column depends on only part of a composite key | order_items(order_id, product_id, product_name) |
Move product_name to products |
| 3NF | No non-key column depends on another non-key column | orders(order_id, customer_id, customer_email) |
Move customer_email to customers |
The old summary is that every non-key column must depend on “the key, the whole key, and nothing but the key”. Higher forms exist (BCNF, 4NF, 5NF) and seldom come up. Third normal form is the working target.
Normalized data has clear benefits. An update touches one row. Foreign keys let the database reject an order for a customer who does not exist. Rows are small, so more of them fit in memory. See ACID and isolation levels for the guarantees that go with this.
The join cost at scale
On one machine with the right indexes, a join is cheap. Fetching an order with its five items is a handful of B-tree lookups and takes well under a millisecond when the pages are in memory. “Joins are slow” is not a reason to denormalize. Joins become a real cost in four situations.
- Large fan-out or aggregation. Counting a celebrity’s 40 million followers on every profile view reads 40 million index entries each time.
- Several joins on a hot path. Six lookups for each of 30 items on a page, at 3,000 requests per second, is 540,000 lookups per second for one screen.
- Shards and services. When the tables live on different shards or belong to different services, the join moves into application code as network calls, about a millisecond each at best, with no shared transaction. See sharding.
- Stores without joins. Key-value and wide-column stores expect each query to read one partition. See key-value, document and wide-column stores.
Denormalization techniques
Denormalizing means storing a fact in more than one place so that a read does less work. All of these move cost from the read to the write.
- Duplicated columns. Copy
author_nameandavatar_urlonto each post. The feed needs no join. A rename now has to reach every post. - Precomputed aggregates. Keep
follower_counton the user row andorder_totalon the order, and adjust them on each write. A very hot counter makes every writer queue for the same row, so busy systems update counts in batches. - Materialised views. The database stores the result of a query as a table. In PostgreSQL a materialised view is recomputed in full when you run
REFRESH MATERIALIZED VIEW, so it suits reports that can be minutes or hours old. Some databases and streaming systems maintain views incrementally as the data changes. - Read models. Build a separate table or store shaped for one screen: a home timeline written when a post is created (see news feed), a search index, or a cache entry (see caching patterns). All of these are derived data.
Keeping copies consistent
A copy is only useful if you know how it gets updated. There are three honest options.
- In the same transaction. If the copy is in the same database, change both in one transaction. Readers never see a mismatch. The write gets slower, and hot rows cause contention.
- Asynchronously, from the log. The service writes only to the source of truth. A change data capture process reads the database’s log and publishes each change, and consumers update the copies. The copies lag by milliseconds to seconds. Consumers must be idempotent, because events can be delivered more than once.
- Recomputed on a schedule. A batch job rebuilds the copy every hour or night. This is simple, and it suits reports. It is also the repair tool for the first two options when you suspect drift.
Step 1 of 8
A user's display name is stored once, in the users database. To avoid a lookup on every feed read, each post also carries a copy of its author's name, and so does the search index. Now there are three places to keep in step.
Read the steps as text
- A user's display name is stored once, in the users database. To avoid a lookup on every feed read, each post also carries a copy of its author's name, and so does the search index. Now there are three places to keep in step.
- The user changes their name. The profile service updates the users database in one ordinary transaction and does nothing else. It does not write to the other stores itself, because if one of those writes failed the copies would silently disagree.
- The database has already recorded the change in its own log. A change data capture connector reads that log and turns every committed change into an event. A change cannot be skipped, because the log is what the database itself recovers from.
- The connector publishes the event to a Kafka topic, using the user id as the key. Events with the same key go to the same partition, so two quick changes to one user are processed in the order they happened.
- One consumer updates the copy on every post by that author. The update sets the name to a given value, so applying it twice gives the same result. That makes it safe when an event is delivered again after a crash.
- A second consumer updates the search index. The consumers are independent. If the search cluster is down, its consumer falls behind and catches up later, and neither the name change nor the posts update is blocked.
- For a second or two in the middle, a feed request could still see the old name. That is the price of this design. The copies are eventually consistent, and the product has to be able to live with a short delay.
- The pattern has four parts. One source of truth, copies fed from its log instead of from application code, consumers that are safe to run twice, and a batch job that can rebuild any copy from the source when you suspect drift.
For any copy you add, be ready to state four things: which store is the source of truth, how the copy is updated, how stale it may be, and how you rebuild it from scratch.
When to choose each, and when not to
Normalize by default. It is the right shape for the system of record, for write-heavy data, and for anything where a wrong value costs money: balances, stock, bookings. Do not insist on it for a read path that has been measured and cannot afford its joins.
Denormalize when a specific read is hot and expensive, reads outnumber changes by a wide margin (100 to 1 is a common rule of thumb), the join would cross a shard or a service, and the screen can tolerate data that is a few seconds old.
Do not denormalize when the copied value changes often and is copied widely, when readers need the exact current value, or when you cannot say how the copy would be repaired. Try an index or a cache first. They are easier to remove.
In the interview
Draw the data model normalized first. It shows you know what the facts are, and it is the easiest form to reason about. Then denormalize one thing, out loud, with a reason.
A strong answer takes about a minute: “Users, posts and follows are separate tables, and that is my source of truth. The feed shows the author’s name and avatar on every post, and reads outnumber renames by thousands to one, so I copy those two fields onto the post. The users table stays the owner. A rename flows through change data capture to a consumer that updates the copies, so the feed may show the old name for a few seconds, which is fine. The follower count is a stored counter updated in batches, and I can rebuild it from the follows table.”
That answer names the source of truth, the update path, the staleness and the repair, and those are the four things interviewers probe.
Key takeaways
- Normalization stores each fact once. That removes update, insertion and deletion anomalies and keeps writes cheap.
- Third normal form is the practical target: every non-key column depends on the key, the whole key and nothing but the key.
- Joins are cheap on one machine with good indexes. They become the problem with large fan-outs, hot read paths, shards, separate services and stores that have no joins.
- Denormalization is a deliberate copy: duplicated columns, precomputed aggregates, materialised views or a read model shaped for one screen.
- Every copy needs one source of truth, a named way of being updated, a stated staleness limit and a way to rebuild it.
- Do not update two stores from application code and hope both writes succeed. Feed the copies from the database's log.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What are the three anomalies that normalization removes?
Update anomaly (a fact stored in many rows gets changed in only some), insertion anomaly (you cannot record one fact without another), and deletion anomaly (deleting one fact destroys another).
State 1NF, 2NF and 3NF in a line each.
1NF, one value per column and no repeating groups. 2NF, no column depends on only part of a composite key. 3NF, no non-key column depends on another non-key column.
When do joins become a real cost?
When one side fans out to very many rows, when a hot path chains several joins at high request rates, when the tables are on different shards or services, or when the store has no joins.
Name four denormalization techniques.
Duplicated columns, precomputed aggregates and counters, materialised views, and read models built for one query such as a timeline table or a search index.
What is the dual-write problem?
Application code writes to two stores with no shared transaction. If one write fails, the stores disagree and nothing repairs them. Use change data capture or a transactional outbox instead.
What four things should you be able to say about any denormalized copy?
Which store is the source of truth, how the copy is updated, how stale it is allowed to be, and how it is rebuilt if it drifts.