Data Modeling for System Design
Every system design ends up as data sitting somewhere. The boxes and arrows on the whiteboard are mostly about moving that data around, and the hardest scaling problems (hot partitions, slow queries, inconsistent counts, painful migrations) usually trace back to how the data was modeled in the first place.
In an interview, the data model shows up in two places. Early on, when you list your core entities and sketch their key fields, you're setting up the design. Later, during deep dives, your interviewer asks how a specific query runs: "How do you fetch a user's 20 most recent posts?" "How do you find all the seats still available for this concert?" If the answer is "scan the table," the design falls apart. If it's "there's a composite index on (author_id, created_at), so it's one index range read," you've shown you can actually build the thing.
You don't need to write a full schema with every column. You need to choose the right entities, know how they relate, know the access patterns that matter, and pick keys and indexes that make those patterns cheap. We'll cover:
- Starting from entities and access patterns.
- Relational modeling: normalization, relationships and indexes.
- When and how to denormalize.
- Modeling for NoSQL: partition keys, sort keys and query-first design.
- Documents: embedding versus referencing.
- IDs, time, history and schema changes, then how to present all of this in an interview.
Start with Entities and Access Patterns
Two lists come before any schema.
Entities are the nouns of the system: users, posts, follows, likes for a social app; events, seats, reservations for ticketing; conversations, messages, participants for chat. Keep it to the handful that the core requirements need. A common mistake is listing fifteen entities and then never using most of them.
Access patterns are the reads and writes the system must serve, with a rough sense of how often each happens:
| Access pattern | Frequency | Notes |
|---|---|---|
| Create a post | ~5,000/s | Write path |
| Get a user's recent posts, newest first | ~50,000/s | Paginated, 20 per page |
| Get a user's home timeline | ~300,000/s | Read-heavy, latency-sensitive |
| Like a post / get its like count | ~100,000/s | Hot posts get most of this |
| Check if I liked this post | With every post view | Needs a point lookup |
This table is what drives everything else. It tells you which queries need indexes, which data should be precomputed, which entities need to be co-located, and which database fits. If you can't say how each important pattern is served, the model isn't finished.
In an interview, list your entities with two or three key fields each, then say "the main access patterns are..." before choosing a database. It makes your database choice look reasoned rather than reflexive, and it gives you a checklist to validate the design against later.
Relational Modeling
A relational database (Postgres, MySQL) is the right default for most interview designs. It gives you flexible queries, transactions, constraints and decades of tooling, and it scales further than many candidates assume. You should leave it for a specific reason, not by default. See /system-design/database-selection.
Normalization
Normalization means storing each fact in exactly one place and linking things by ID. A post doesn't store its author's display name; it stores author_id, and you join to users when you need the name. The benefits:
- Updates are simple and consistent. Changing a display name is one row update, and every post shows the new name.
- Constraints work. Foreign keys ensure a like points at a real post; unique constraints ensure a username is used once.
- The schema is flexible. New queries can usually be answered with a join and an index, without restructuring the data.
Here's a small normalized schema for a social app:
CREATE TABLE users (
id BIGINT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE posts (
id BIGINT PRIMARY KEY,
author_id BIGINT NOT NULL REFERENCES users(id),
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE follows (
follower_id BIGINT NOT NULL REFERENCES users(id),
followee_id BIGINT NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (follower_id, followee_id)
);
CREATE TABLE likes (
post_id BIGINT NOT NULL REFERENCES posts(id),
user_id BIGINT NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (post_id, user_id)
);
Relationships
Three shapes cover almost everything:
- One-to-many: a user has many posts. Put the foreign key on the "many" side (
posts.author_id). - Many-to-many: users follow users, users like posts. Use a join table (
follows,likes) whose primary key is the pair. The primary key doubles as a uniqueness constraint, so a user can't like the same post twice, andINSERT ... ON CONFLICT DO NOTHINGmakes the like idempotent. - Hierarchies: comment threads, folders, org charts. There are several standard encodings:
- Adjacency list: each row has a
parent_id. Simple to write; reading a whole subtree needs a recursive query (WITH RECURSIVEin Postgres). - Materialized path: each row stores its full path, like
/1/4/9/. A subtree is a prefix query (path LIKE '/1/4/%'), which an index can serve; moving a subtree means rewriting paths. - Closure table: a separate table with one row for every ancestor-descendant pair. Fast subtree and ancestor queries, more storage and more rows to maintain on insert.
- Adjacency list: each row has a
For deep, highly connected data where queries are about traversals ("friends of friends who live in Berlin"), a graph database can be a better fit. For one or two hops, like followers, a join table with indexes is fine. See /system-design/graph-databases.
Indexes
An index is what turns "scan 500 million rows" into "read 20 rows." Most relational indexes are B-trees: sorted structures that support equality lookups, range scans and ordered reads in O(log n).
The rule that matters most in interviews is how composite indexes work. An index on (author_id, created_at) is sorted by author first, then by time within each author. That makes these queries cheap:
-- One index range read: jump to author 42, read the newest 20 entries
SELECT id, body, created_at FROM posts
WHERE author_id = 42
ORDER BY created_at DESC
LIMIT 20;
CREATE INDEX posts_by_author_time ON posts (author_id, created_at DESC);
But the same index can't efficiently answer "all posts created in the last hour" across all authors, because created_at is only sorted within each author. The index works for queries that filter on a leftmost prefix of its columns. Put equality columns first, then the column you range over or sort by.
A few more index facts worth having ready:
- Every index slows writes. Each insert updates every index on the table. Index the access patterns you need, not every column.
- Covering indexes include all the columns a query needs, so the database never visits the table itself. Postgres supports
INCLUDE (...)for this. - Reverse lookups need their own index.
followshas a primary key on(follower_id, followee_id), which answers "who do I follow?" To answer "who follows me?", add an index on(followee_id, follower_id). - Cursor pagination beats offsets.
OFFSET 10000still reads and discards 10,000 rows.WHERE (created_at, id) < (:last_created_at, :last_id)with the right index reads only the next page.
When you name an index, name the query it serves. "An index on
(event_id, status)so we can find available seats for an event" is far more convincing than "we'll add indexes where needed."
Denormalization
Normalization optimizes for correctness and flexibility. At high read volume, some joins and aggregations become too expensive to run on every request, and you denormalize: copy or precompute data so reads are cheap, accepting extra work and some risk on writes.
Common forms:
- Counters: store
like_counton the post instead of runningCOUNT(*)over the likes table on every view. Update it in the same transaction as the like insert, or asynchronously from an event. Hot counters need special treatment; see /system-design/likes-counter. - Copied fields: store the author's display name and avatar URL on each post, or on each message, so rendering a feed doesn't need a join per item.
- Precomputed views: a timeline table or cache holding post IDs for each user's home feed, built at write time (fan-out on write). See /system-design/twitter.
- Search and analytics copies: the same data indexed in Elasticsearch for full-text search, or loaded into a column store for analytics.
The costs are real, so be deliberate:
- More writes. One like becomes a row insert plus a counter update. One post becomes an insert plus thousands of timeline updates.
- Staleness and drift. Copies can disagree with the source. If a user changes their display name, old posts may show the old one until a background job updates them. Counters can drift if an update is lost.
- One source of truth. Always know which copy is authoritative. The
likestable is the truth;like_countis a cache of it that can be rebuilt. Derived copies are best kept in sync from the source's change stream (change data capture) rather than by having application code write to several places. See /system-design/change-data-capture.
A practical rule: start normalized, and denormalize specific, measured hot paths, saying in each case how the copy is kept up to date.
Modeling for NoSQL: Query-First Design
Key-value and wide-column stores (DynamoDB, Cassandra, Bigtable, HBase) are built to scale horizontally with predictable latency. The price is that they support few query shapes, and joins usually aren't one of them. So instead of modeling entities and querying them flexibly later, you model the queries: each access pattern gets a key structure that answers it with a single partition read.
Partition Keys and Sort Keys
Most of these stores organize data by two parts of the primary key:
- The partition key decides which node stores the data. All rows with the same partition key live together.
- The sort key (DynamoDB) or clustering key (Cassandra) orders rows within a partition, so range queries and "newest first" reads are cheap.
A query that specifies the partition key and a range on the sort key is one fast, sequential read on one node. A query without the partition key has to touch every partition, which is exactly what these databases are bad at.
Here's chat history in Cassandra, modeled for the access pattern "get the latest messages in a conversation, then page backwards":
CREATE TABLE messages_by_conversation (
conversation_id uuid,
bucket int, -- e.g. month number, caps partition size
message_id timeuuid, -- time-ordered, unique
sender_id uuid,
body text,
PRIMARY KEY ((conversation_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);
SELECT * FROM messages_by_conversation
WHERE conversation_id = ? AND bucket = ?
LIMIT 50;
Note the bucket column. A partition that grows forever, like all the messages of a group chat that's been active for years, becomes a wide partition: slow to read, slow to repair and a hot spot. Cassandra guidance is to keep partitions well under about 100 MB. Adding a time bucket to the partition key caps each partition's size, at the cost of reading two buckets when a page spans a boundary.
One Table per Query (Cassandra)
In Cassandra, the common practice is a separate table for each access pattern, with the same data written to each. "Messages by conversation" and "messages by sender" are two tables with different partition keys. Writes are cheap in Cassandra, so writing twice is fine; reading across partitions is not.
Single-Table Design (DynamoDB)
DynamoDB pushes in a different direction: put several entity types in one table with generic key names, so related items share a partition and can be fetched together in one query.
| PK | SK | Attributes |
|---|---|---|
USER#42 |
PROFILE |
name, email |
USER#42 |
ORDER#2025-03-14#9f3a |
total, status |
USER#42 |
ORDER#2025-03-20#b71c |
total, status |
ORDER#9f3a |
ITEM#1 |
sku, qty, price |
ORDER#9f3a |
ITEM#2 |
sku, qty, price |
- "Get user 42's profile and recent orders":
PK = USER#42, one query, sorted by date because the date is in the sort key. - "Get user 42's orders in March":
PK = USER#42 AND begins_with(SK, "ORDER#2025-03"). - "Get all items in order 9f3a":
PK = ORDER#9f3a. - Other access patterns, like "all orders with status
SHIPPED," get a global secondary index with a different partition key.
Single-table design is powerful but rigid: adding an access pattern later can mean a new index or a backfill. Many teams use a few tables instead of one, which is fine. What matters in an interview is that every access pattern maps to a key query, not a scan. See /system-design/dynamodb and /system-design/cassandra.
Choosing a Good Partition Key
The partition key decides both what's fast and what's hot. A good one:
- Matches the main access pattern. If almost every query is "for this user," partition by
user_id. - Has high cardinality. Millions of distinct values spread load evenly. Partitioning by
countryputs a huge share of traffic on a few partitions. - Avoids hot spots. Partitioning by date sends every write today to one partition. A celebrity's
user_idcan be hot too; very hot keys need sharding into sub-keys or caching. See /system-design/sharding-replication. - Co-locates data that's read or updated together, so that a common operation touches one partition and, if the database supports it, can be a single-partition transaction.
A useful check during deep dives: for each access pattern, say which partition it hits. If the answer is "all of them" for a frequent query, you've found a problem, and either the key or the model needs to change, or that query needs a secondary index or a separate read model.
Documents: Embedding vs Referencing
Document databases (MongoDB, Firestore, Couchbase) store JSON-like documents, and the central modeling choice is whether related data goes inside a document or in a separate one that's referenced by ID.
{
"_id": "order_9f3a",
"user_id": "user_42",
"status": "SHIPPED",
"shipping_address": { "city": "Austin", "zip": "78701" },
"items": [
{ "sku": "BK-101", "qty": 1, "price": 18.00 },
{ "sku": "HP-220", "qty": 1, "price": 79.00 }
]
}
Embed when the data is:
- Read together almost always (an order and its line items).
- Owned by the parent and not shared (an order's shipping address as it was at checkout).
- Bounded in size (an order has a handful of items, not millions).
Reference when the data is:
- Unbounded (a user's posts, a post's comments on a popular thread). MongoDB caps documents at 16 MB, and long before that, rewriting a huge document on every change gets slow.
- Shared by many parents (a product referenced by many orders).
- Updated independently and frequently (a product's price).
The order above embeds a snapshot of the price at purchase time, which is correct: the order should keep showing what the customer paid even if the product's price changes later. That's an important modeling idea in its own right, and it applies to relational schemas too.
IDs, Time and History
Choosing IDs
- Auto-increment integers are compact and sort by creation time, but they need a single sequence (awkward across shards) and leak business information when exposed (order 10,000 tells competitors your volume, and sequential IDs invite enumeration).
- Random UUIDs (v4) can be generated anywhere without coordination, but random inserts scatter across a B-tree index, which hurts write performance and cache locality at scale.
- Time-ordered IDs like Snowflake IDs (64-bit: timestamp, machine ID, sequence), UUIDv7 or ULIDs give the best of both: generated anywhere, roughly sortable by time, and friendly to B-tree inserts because new IDs land at the end of the index. They're a strong default. See /system-design/unique-id-generator.
Use a separate, opaque public ID (or a short code) in URLs when internal IDs shouldn't be exposed.
Modeling State Changes
Data that represents something happening over time deserves care:
- Status fields with explicit states. A reservation is
HELD,CONFIRMED,EXPIREDorCANCELLED, with anexpires_atfor holds. Transitions are conditional updates (UPDATE ... SET status = 'CONFIRMED' WHERE id = ? AND status = 'HELD'), so two requests can't both confirm. See /system-design/ticket-booking. - Constraints as guards. A unique constraint on
(event_id, seat_id)in areservationstable for active reservations makes double-booking impossible at the database level, no matter what the application code does. - Append-only records for money and audits. A ledger never updates a balance in place; it inserts immutable entries and derives balances from them (and caches the result). You get a full history and an easy reconciliation story. See /system-design/ledger.
- Soft deletes (
deleted_at) when you need undo or audit trails, with the caveat that every query and unique constraint must account for them. - Event sourcing, storing every change as an event and deriving current state from the log, is the extreme version. It's powerful for audit-heavy domains, but it adds complexity, so mention it only when history is a core requirement.
Metadata vs Blobs
Large binary data (images, video, documents, attachments) doesn't belong in a database row. Store the bytes in object storage like S3, and keep a metadata row with the object key, size, content type, owner and status. The database stays small and fast, and the blob store handles durability and delivery through a CDN. See /system-design/s3.
Schema Changes
Designs evolve, and an interviewer may ask how you'd add a field or change a key on a live system with billions of rows.
- Additive changes are easy. Adding a nullable column or a new attribute is cheap in most modern databases, and document and key-value stores don't need a schema change at all.
- Breaking changes use expand and contract. To rename or restructure a field: add the new field, write to both old and new, backfill old rows in batches, switch reads to the new field, then stop writing the old one and drop it. Every step is safe to deploy and roll back on its own.
- Index builds on big tables should be online (
CREATE INDEX CONCURRENTLYin Postgres) so they don't lock writes. - Changing a partition key in a NoSQL store means writing the data into a new table with the new key, usually through a backfill plus dual writes or a change stream, then cutting reads over. It's expensive, which is why choosing the key carefully up front matters. See /system-design/data-migration.
Data Modeling in an Interview
How to Present It
- List the core entities with their key fields and IDs. Don't write every column; write the ones that matter for the design (IDs, foreign keys, status, timestamps, counters).
- State the main access patterns and their rough frequencies.
- Pick the database based on those patterns, scale and consistency needs, and say why.
- Show the keys and indexes that serve each important pattern: primary keys, composite indexes, partition and sort keys.
- Point out denormalization and how each copy is kept in sync with its source of truth.
- Name the constraints that protect invariants: unique constraints, conditional updates, foreign keys.
Common Follow-ups
- "How does this query run?" Name the index or the partition and sort keys it uses, and whether it's a point read, a range read or a scan.
- "What happens when this table has a billion rows?" Index range reads still take milliseconds; full scans don't. Then discuss sharding and which key you'd shard by.
- "Why not just store the count?" You can, as a denormalized cache, with a clear way to keep it accurate and rebuild it from the source.
- "How do you stop double bookings / duplicate likes?" A unique constraint or a composite primary key, plus a conditional update for state changes.
- "Would you embed this or reference it?" Embed bounded, owned, read-together data; reference unbounded, shared or independently updated data.
- "How would you add this field later?" Additive change, or expand and contract with a backfill.
The most convincing data models are small. Five entities with the right keys, two composite indexes and one well-justified denormalized counter beat a twenty-table schema every time. Interviewers are checking whether the model serves the access patterns, not whether you can recite normal forms.
Summary
Data modeling starts with two lists: the few entities the core requirements need, and the access patterns the system must serve. In a relational database, normalize by default, link entities by ID, use join tables for many-to-many relationships, pick an encoding for hierarchies, and add composite indexes whose leftmost columns match your filters and whose last column matches your sort. Denormalize specific hot paths (counters, copied fields, precomputed timelines) only with a clear source of truth and a way to keep copies in sync.
In key-value and wide-column stores, model the queries rather than the entities: the partition key decides placement and hot spots, the sort key decides what range reads are cheap, and wide partitions need time buckets. In document stores, embed bounded, owned, read-together data and reference the rest. Choose time-ordered IDs, model state changes as explicit statuses with conditional updates and constraints, keep money as append-only records, store blobs outside the database, and evolve schemas with additive changes or expand and contract. In an interview, show for each important query exactly which key or index serves it.