Data Modeling & Denormalization: Designing Around Access Patterns
A team ports its order service from Postgres to DynamoDB. They copy the schema table for table: customers, orders, order_items, products. The order history page used to be one SQL query with two joins. Now it is a Query for the customer’s orders, then one BatchGetItem for the items, then another for the product names: three sequential round trips, 9 ms each on a good day, and 40 ms at p99 when one batch retries on a throttled partition.
Nothing is wrong with DynamoDB. The team modeled entities, the way you do for a relational database, in a store that only answers questions you designed the keys for. In a key-value store, the data model is the query plan.
The opposite mistake is just as common: a relational schema so normalized that the product page needs nine joins, or so denormalized that changing a customer’s email means updating 40,000 order rows. This article is about where to draw that line.
What data modeling is
Data modeling is deciding what you store, how records relate, and how they are physically laid out so that your important reads and writes are cheap and your invariants hold.
Normalization stores each fact exactly once and links facts by keys. It makes writes simple and keeps data consistent by construction.
Denormalization stores some facts more than once, on purpose, so that a read can be served from one place without joins or extra round trips. You pay with more storage, more work per write, and the job of keeping the copies in sync.
Neither is “correct”. The access patterns, their rates and the consistency each one needs decide where you land.
How it works
Normalization in five minutes
Start from a spreadsheet-style order table and fix it step by step:
| order_id | customer_email | customer_city | products | product_names |
|---|---|---|---|---|
| 9001 | ana@example.com | Pune | 5, 9 | Kettle, Mug |
- First normal form (1NF): each column holds one atomic value and there are no repeating groups.
productsholds a list, so split line items into their ownorder_itemstable with one row per product. - Second normal form (2NF): every non-key column depends on the whole key. In
order_itemskeyed by (order_id, product_id),product_namedepends only on product_id, so it moves toproducts. - Third normal form (3NF): no column depends on another non-key column.
customer_citydepends on the customer, not the order, so it moves tocustomers.
The result is the textbook schema: customers, orders, order_items, products. Each fact lives in one row, so an update touches one row and anomalies such as two different cities for the same customer cannot happen.
One fact looks like duplication but is not: the price a customer paid. order_items.unit_price is a different fact from products.price, because the catalogue price changes and the price paid must not. Snapshotting it at purchase is correct modeling, not denormalization.
Access-pattern-first modeling
Relational modeling starts from entities and relies on the planner to answer any query. Key-based stores invert that: you list the queries first and design keys and tables so each one is a single key lookup or a single range read.
For any store, write the access patterns as a table before drawing a schema:
| Access pattern | Rate (peak) | Latency target | Consistency |
|---|---|---|---|
| Get order with its items | 2,000 per second | p99 under 20 ms | Read-your-writes after checkout |
| List a customer’s orders, newest first | 800 per second | p99 under 30 ms | Seconds of staleness fine |
| Pending orders for the warehouse, oldest first | 5 per second | p99 under 500 ms | Seconds of staleness fine |
| Revenue by category per month | A few per day | Minutes | Hours fine, run in the warehouse |
That last row is a reminder that not every pattern belongs in the operational database. Reporting goes to a warehouse; see OLTP vs OLAP.
When denormalization pays
Denormalize when a read is frequent, latency-sensitive and would otherwise need a join or extra round trip, and when the duplicated data changes rarely or can tolerate brief staleness. Typical moves:
- Embed a small, bounded set of child data in the parent (order line items in the order document).
- Copy a few fields of a related entity into the record that displays them (product name and image URL on the line item). MongoDB calls this the extended reference pattern.
- Precompute aggregates: an
order_counton the customer, alikescount on the post. - Duplicate whole tables per query in Cassandra, one for each access pattern.
- Fan out on write: copy a new post into each follower’s feed so reads are a single partition scan. The trade-offs, including the celebrity problem, are worked through in design a news feed.
Embedding vs referencing in document stores
Embed when the child data is read with the parent, bounded in size, and owned by the parent: order line items, a user’s 3 shipping addresses. Reference (store an ID and fetch separately) when the child is shared across many parents, grows without bound, or changes independently: products referenced by orders, comments on a viral post. MongoDB caps documents at 16 MB and rewrites the document on update, so an embedded array that keeps growing is a performance and correctness hazard long before it hits the cap.
DynamoDB single-table design
DynamoDB items are addressed by a partition key (PK) and an optional sort key (SK). A Query reads all items with one PK, in SK order, optionally filtered to an SK range or prefix. Global secondary indexes (GSIs) are copies of the table keyed differently, updated asynchronously, so GSI reads are always eventually consistent.
Single-table design stores several entity types in one table with generic key attribute names, so related items share a partition key and come back in one Query. An item collection is the set of items sharing a PK. This is the “pre-join”: you put together at write time what you would join at read time.
AWS documents both single-table and multi-table approaches. Single-table design minimises round trips for known patterns, but it makes ad hoc analysis and schema changes harder, so it fits stable, high-throughput access patterns best.
Cassandra query-first tables
Cassandra’s primary key has a partition key, which decides the node, and clustering columns, which sort rows inside the partition. A query must name the full partition key, and range conditions can only apply to clustering columns in order. So you design one table per query and write to all of them:
CREATE TABLE orders_by_customer (
customer_id bigint,
order_date timestamp,
order_id bigint,
total_cents bigint,
status text,
PRIMARY KEY ((customer_id), order_date, order_id)
) WITH CLUSTERING ORDER BY (order_date DESC, order_id DESC);
CREATE TABLE orders_by_status_day (
status text,
day date,
created_at timestamp,
order_id bigint,
PRIMARY KEY ((status, day), created_at, order_id)
);
The second table puts day into the partition key so a single status does not become one enormous partition. A common guideline is to keep partitions under about 100 MB and well under 100,000 rows.
Worked example: one order domain, two models
Relational
erDiagram
CUSTOMER ||--o{ ORDERS : places
ORDERS ||--|{ ORDER_ITEM : contains
PRODUCT ||--o{ ORDER_ITEM : "appears in"
CUSTOMER {
bigint id PK
text email
text city
}
ORDERS {
bigint id PK
bigint customer_id FK
text status
timestamptz created_at
}
ORDER_ITEM {
bigint order_id FK
bigint product_id FK
int qty
int unit_price_cents
}
PRODUCT {
bigint id PK
text name
int price_cents
}
Indexes follow the access patterns from indexing internals: orders (customer_id, created_at) for order history, a partial index orders (created_at) WHERE status = 'pending' for the warehouse, and the primary key on order_items (order_id, product_id) for fetching items. The order page is one query with two joins and one round trip. Checkout is one transaction inserting an order and its items and decrementing stock.
Key-value, single table
| Entity | PK | SK | GSI1PK | GSI1SK |
|---|---|---|---|---|
| Customer | CUST#42 |
PROFILE |
||
| Order header | ORDER#9001 |
HEADER |
CUST#42 |
2026-11-30T10:15:00Z |
| Line item | ORDER#9001 |
ITEM#001 |
||
| Line item | ORDER#9001 |
ITEM#002 |
Each line item carries product_name and unit_price_cents copied at purchase. Pending orders also carry GSI2PK = PENDING#3 and GSI2SK = created_at, and those two attributes are removed when the order ships, making GSI2 a sparse index of only pending orders.
How each access pattern is served:
- Order with items:
Query PK = ORDER#9001returns the header and all items in one request. - Customer’s orders, newest first:
Query GSI1 PK = CUST#42, descending by GSI1SK, with a limit of 20. - Pending orders, oldest first:
Query GSI2across the shard keysPENDING#0toPENDING#9and merge by date. - Customer profile:
GetItem PK = CUST#42, SK = PROFILE.
Keeping denormalized copies consistent
Every copy is a promise to update it. Options, from strongest to weakest:
- Same transaction, same database. In Postgres, update the counter and insert the row in one transaction. In DynamoDB,
TransactWriteItemsupdates up to 100 items atomically. Best when the copies live together. - Database-maintained copies. Postgres materialized views refreshed on a schedule (
REFRESH MATERIALIZED VIEW CONCURRENTLYneeds a unique index and does not block readers), DynamoDB GSIs, and triggers. The database does the work, though GSIs and refreshed views are stale for a while. - Change data capture. Write the source of truth once, then stream its changes to update the copies: a search index, a per-customer summary, a Cassandra query table. Use the transactional outbox or log-based CDC rather than dual writes from the application, as described in outbox, inbox and CDC. Consumers must be idempotent because events can be delivered more than once.
- Reconciliation. A periodic job that recomputes copies from the source and fixes drift. Even with CDC, run one for anything money-related.
Cassandra has built-in materialized views, but they are marked experimental and are disabled by default in recent versions because they can drift from the base table; most teams maintain query tables themselves.
Counters
A likes counter on a viral post is denormalization under contention. At 5,000 likes per second on one row, every increment queues for the same row lock. Options: atomic increments (SET likes = likes + 1) which avoid lost updates but still serialize on the row; sharded counters, where 20 sub-rows each take about 250 increments per second and reads sum them; or buffering increments in Redis or Valkey and flushing every few seconds, accepting a small loss window. Cassandra has a counter column type, but counter updates are not idempotent, so a retried write can double count.
flowchart LR APP["Order service"] -->|"one transaction"| SRC["orders table<br/>source of truth"] APP -->|"same transaction"| OB["outbox table"] OB -->|"CDC relay"| BUS["Event log"] BUS --> C1["Customer summary<br/>order_count, last_order"] BUS --> C2["Search index"] BUS --> C3["orders_by_status<br/>query table"] REC["Nightly reconciliation"] -.->|"recompute and fix drift"| C1 style SRC fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style OB fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style BUS fill:#F1EFE8,stroke:#888780,color:#444441 style C1 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style C2 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style C3 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style REC fill:#FAEEDA,stroke:#854F0B,color:#633806
Where it breaks
Unbounded partitions. A Cassandra partition per user that never expires, or a DynamoDB item collection that keeps growing, eventually becomes slow to read and impossible to repair or rebalance. Bucket by time (user plus month) whenever a partition can grow forever.
Hot keys. Low-cardinality partition keys (status, country, today’s date) concentrate traffic on one partition. Add a shard suffix or a higher-cardinality component.
Fan-out amplification. Fan-out on write for a user with 10 million followers turns one post into 10 million writes. Hybrid models (fan-out for normal users, fan-in for celebrities) exist because of this.
Update anomalies. If the customer’s email is copied into every order, an email change is a background rewrite of every order or a known stale field. Copy only fields that never change (price paid, name at the time) or that may be stale.
Rigid single-table schemas. A new access pattern in a single-table design may require a new GSI and backfilling attributes into millions of items. If the product is young and queries change weekly, start relational and denormalize later.
Denormalizing too early. A join on indexed keys over a few million rows takes milliseconds. Denormalize after measuring, not because joins have a bad reputation.
Real-world systems
- Postgres: normalized schemas with JSONB for flexible attributes, materialized views for precomputed reads, triggers or logical decoding for CDC.
- DynamoDB: item collections, sparse and overloaded GSIs,
TransactWriteItemsfor atomic multi-item writes, and DynamoDB Streams for change capture. - Cassandra and ScyllaDB: one table per query, partition key plus clustering columns, time-bucketed partitions, batched writes to the query tables of one logical entity.
- MongoDB: embedding and referencing guided by its documented schema design patterns, such as the extended reference, subset, computed and bucket patterns.
How to apply it
A modeling checklist:
- List the access patterns with rate, latency target and consistency need, like the table above.
- Start normalized (3NF) if you use a relational database; add indexes for each pattern.
- Denormalize one pattern at a time, only where measurements show the join or extra round trip hurts.
- For each copy, write down its source of truth, how it is updated (transaction, CDC, refresh) and how stale it may be.
- Check every partition key for unbounded growth and hot keys, with peak numbers.
- Plan a reconciliation job for copies that matter.
| Situation | Model |
|---|---|
| Young product, queries still changing | Normalized relational, add indexes |
| Read-heavy page needing 4 or more joins at high QPS | Denormalize the fields the page needs, or a materialized view |
| Every read by key at very high scale | Key-value or wide-column, one table or index per pattern |
| Child data bounded and read with parent | Embed |
| Child data shared or unbounded | Reference |
Interview questions
1. When should you denormalize a relational schema?
When a specific read is frequent and latency-sensitive, the join or extra lookup is measurably the bottleneck, and the duplicated fields either never change (price at purchase) or can be briefly stale (a follower count). Start with indexes, and try a materialized view before denormalizing tables. For each copy, define the source of truth and how it is kept in sync: in the same transaction if possible, otherwise from a change stream with idempotent consumers, plus reconciliation. Do not denormalize fields that change often and must be consistent everywhere, such as account status used for authorization.
2. How would you model “latest 50 messages in a chat channel” in Cassandra?
Partition by channel and time bucket, for example PRIMARY KEY ((channel_id, bucket), message_id) with clustering order descending, where the bucket is a time window such as 10 days and message_id is time-ordered. Reading the latest 50 is a single partition read in clustering order with a limit, possibly continuing into the previous bucket. The bucket keeps active channels from creating unbounded partitions. Discord’s public write-ups describe this channel-plus-bucket shape. A second table is needed for any other query, such as messages by author.
3. What is single-table design in DynamoDB and when would you avoid it?
It stores several entity types in one table with generic PK and SK attributes, so items that are read together share a partition key and come back from one Query, and it overloads GSIs to serve other access patterns. It reduces round trips and keeps costs predictable for known, stable patterns. Avoid or limit it when access patterns are still changing, when teams need ad hoc analytics on the operational data, or when different entities have very different throughput, backup or retention needs. Multiple tables with GSIs are also a valid, documented approach.
✅ Key takeaways
- Normalize to 3NF by default in relational databases; snapshotting values such as price paid is correct modeling, not duplication.
- Model key-value and wide-column stores from a written list of access patterns; the key design is the query plan.
- Denormalize only for measured, frequent reads, and copy fields that never change or may be stale.
- DynamoDB single-table design groups related items under one partition key and serves other patterns with sparse or overloaded GSIs, which are eventually consistent.
- Keep copies in sync with same-transaction writes where possible, otherwise CDC with idempotent consumers, plus reconciliation.
- Check every partition key for unbounded growth and hot keys at peak load.
🧠 Check your understanding
0 / 4-
1An order_items table stores unit_price copied from the products table at checkout. Is this denormalization that must be kept in sync?
The price at purchase is its own fact and must not change when the catalogue does. Treating it as a copy to keep in sync is the tempting mistake and would rewrite historical orders.
-
2In a DynamoDB single-table design, why is the pending-orders GSI keyed PENDING#0 to PENDING#9 instead of just PENDING?
A single partition key value lives on one partition, which supports roughly 1,000 write units per second, so a busy status would throttle. GSIs are never strongly consistent regardless of key design.
-
3You need to keep a customer summary in a search index in sync with an orders table in Postgres. What is the safest approach?
The outbox or log-based CDC makes the change and its event commit atomically, and the consumer can retry idempotently. Dual writes from the application look simpler, but a crash between the two writes leaves the copies inconsistent.
-
4When should you embed child data in a parent document rather than reference it?
Embedding suits bounded, owned data read with the parent, such as order line items. Unbounded or shared children should be referenced; growing arrays make every update rewrite a larger document and eventually hit the 16 MB cap.
Where to go next
- Zero-downtime schema migrations: how to change a model in production once it has data.
- Outbox, inbox and CDC: the mechanics of keeping denormalized copies in sync.
- Sharding and partitioning: choosing partition keys when one node is not enough.
- Event sourcing and CQRS: taken to the limit, every read model is a denormalized projection of an event log.
Finished this lesson?
Mark it complete to track your progress across the roadmap.