Skip to content

Data Modeling

Intermediate 25 min read Part 5 of 18

Entities, relationships and ER diagrams; normalization and denormalization; modeling for access patterns; NoSQL keys and single-table design; schema evolution.

Summary#

Data modeling decides what you store and how it is laid out. Start with entities (things), their attributes (fields) and relationships (one-to-many, many-to-many), drawn as an ER diagram. In relational databases, normalize (to about 3NF) so each fact is stored once, then denormalize selectively where reads are too slow. In NoSQL, model from the access patterns: choose partition keys that spread load and sort keys that return a query's data in one read, often storing several entity types in one table (single-table design). Decide between embedding and referencing related data, and plan schema changes that never break running code.

Why It Exists#

The data model outlives the code. A table design that does not support a key query forces full scans, slow joins or a painful migration later. A NoSQL partition key chosen badly creates hot spots that no amount of hardware fixes. Good modeling makes the important queries cheap and keeps the data correct. This page builds on SQL vs NoSQL.

How It Works#

Entities, attributes and relationships#

  • An entity is a thing the system must remember: Customer, Order, Product.
  • Attributes describe it: email, status, price_cents. One attribute (or a set) is the key that identifies it.
  • Relationships connect entities, with a cardinality:
    • One-to-one: a customer has one loyalty account.
    • One-to-many: a customer places many orders.
    • Many-to-many: orders contain many products, and products appear in many orders. This needs a join entity (OrderItem) that can carry its own attributes (quantity, price at purchase).

In an interview, the "core entities" step is exactly this list, usually 3-6 entities.

Entities, attributes and relationships in depth#

Where modeling shows up in a design. In an interview, modeling comes up twice. The first time is during requirements. Once the functional requirements are clear, you name the core entities, and each one usually becomes a table or a collection. The second time is in the high-level design. When you draw the database box, you sketch a small schema next to it: the key fields of each entity, how the entities connect, and one note on how you will index or partition for the main queries. The bar is lower than in a data-engineering interview. Nobody expects a fully normalized schema with every column. They expect a model that is clear, works for the stated features, and will not fall over under the expected load. A sloppy model hurts you later, because scaling reads, scaling writes, consistency and auditing all build on it. A good-enough model keeps the rest of the conversation on the interesting parts.

Start from the requirements, not from the tables. Three questions shape the model before you write a single column:

  1. How much data, and how fast does it grow? A table of 50,000 products and a table of 50 billion click events need different designs. The first fits in memory on any server. The second needs partitioning from day one.
  2. What are the access patterns? Which queries run on every page view, and which run once a night? A query that runs 20,000 times a second deserves its own index, or even its own copy of the data. A nightly report can scan.
  3. What consistency does each piece of data need? A bank balance, a seat reservation or a stock count must be exact. A like counter or a "people also viewed" list can lag by seconds. This often decides which store a piece of data lives in, not just how it is shaped.

Choose the kind of database before the schema. The database model changes how you shape everything else, so pick it first. The safe default in almost every interview is a relational database, and PostgreSQL in particular, unless the requirements clearly call for something else. Picking an exotic store to look clever usually backfires: you must then defend its weak points. Knowing when other models fit still matters, and the ER section below compares them.

Keys: how an entity is identified. Every entity needs a primary key, a value that is unique for each row and never changes.

  • A natural key is a real-world value, such as an email, an ISBN or a national ID. It looks convenient, but real-world values change. People change email addresses, and companies merge. If email is the primary key, every foreign key that points to it must be rewritten when it changes.
  • A surrogate key is a value the system creates and that means nothing outside the system, such as user_id = 81723. It never needs to change. The natural value becomes an ordinary column with a UNIQUE constraint. Prefer surrogate keys for primary keys.

How you generate surrogate keys has real costs:

ID schemeSizeSortable by timeNotes
Auto-increment integer8 bytesYesSimple and compact. Needs one central sequence, and it leaks how many rows you have.
UUID v4 (random)16 bytesNoCan be generated anywhere. Random inserts scatter across the B-tree and hurt cache hit rates.
UUID v716 bytesYesStarts with a timestamp, so inserts land at the end of the index. Unlike v1, it does not expose a MAC address.
Snowflake ID8 bytesYesTimestamp + machine ID + per-machine sequence. Used by Twitter and Discord.
ULID16 bytesYesTimestamp plus randomness, written as 26 readable characters.

The point about index locality matters at scale. A B-tree index stays fast when new keys arrive in order, because only the rightmost page is hot and it stays in memory. With random UUID v4 keys, each insert touches a random leaf page. Once the index is larger than RAM, many inserts cause a disk read. Time-ordered IDs avoid this, and they also give you "newest first" ordering for free.

Relationships and their cardinality in practice.

  • One-to-many (1:N) is the most common. You store the parent's key on the child, so posts.user_id points to users.id. The "many" side carries the foreign key.
  • Many-to-many (N:M) needs a third table, often called a join table or junction table. likes(user_id, post_id, created_at) links users to posts. The join table's primary key is usually the pair (user_id, post_id), which also stops someone liking the same post twice.
  • One-to-one (1:1) is rarer than it looks. If every user has exactly one settings row and you always read them together, the two tables are often one entity split for no reason, so consider merging them. Splitting makes sense when one part is large and rarely read (a profile photo blob), has a different security level (payment details), or is optional for most rows.

Each relationship also has an optionality. Must an order have a shipping address (digital goods might not)? Can a post exist without an author (after account deletion)? Writing these down early answers future questions about NULL columns and cascading deletes.

Constraints: let the database guard the data. Constraints are rules the database enforces on every write, no matter which service or script does the writing.

  • NOT NULL for required fields.
  • UNIQUE for natural identifiers such as email or username.
  • CHECK for value rules, such as CHECK (quantity > 0) or CHECK (status IN ('pending','paid','shipped')).
  • FOREIGN KEY so that a child row cannot point to a parent that does not exist.

Foreign keys have a cost. Every insert into a child table must check that the parent exists, and every delete of a parent must check or cascade to its children. On a single database this cost is small and usually worth it. At very large scale, some teams drop foreign keys and enforce the rules in application code instead. They do this because the tables live on different shards, where the database cannot check across machines anyway. They may also do it because cascading deletes over millions of rows cause long locks. If you drop them, say how you will catch orphaned rows, for example with a nightly job that finds them.

ER diagrams#

An entity-relationship (ER) diagram shows entities as boxes, attributes inside them, and relationships as lines with cardinality marks. Here is the worked example used on this page, a small online shop:

Note unit_price_cents on ORDER_ITEM: the price at purchase time is a separate fact from the product's current price. Spotting facts like this is a large part of modeling.

ER diagrams in depth#

Reading the notation. The diagram above uses crow's foot notation, the most common style in industry tools. Each end of a line shows two things: the minimum (zero or one) and the maximum (one or many).

MarkMeaning
||Exactly one
o|Zero or one
|{One or more
o{Zero or more

So CUSTOMER ||--o{ ORDER reads "each order belongs to exactly one customer, and a customer has zero or more orders". The older Chen notation draws entities as rectangles, relationships as diamonds and attributes as ovals. It comes from Peter Chen's 1976 paper "The Entity-Relationship Model: Toward a Unified View of Data" in ACM Transactions on Database Systems. You will see it in textbooks more than in engineering teams.

Three levels of model. Teams often talk about three levels, and knowing which one you are drawing avoids confusion:

  1. Conceptual model: entities and relationships only, no columns. This is the interview's "core entities" list: User, Post, Like, Follow.
  2. Logical model: entities with attributes, keys and cardinalities, but not tied to one product. The diagram above is roughly logical.
  3. Physical model: real tables, types, indexes, partitions and storage settings for one database, for example bigint vs uuid, or a partial index on status = 'pending'.

In an interview, you move from conceptual (in requirements) to a light physical sketch (in high-level design). You list only the columns the features need, and add a note such as "index on (user_id, created_at)" or "partition key chat_id".

How the database model changes the diagram. The same entities look different in each kind of store. Here is a social app with users, posts and likes in each model:

  • Relational (PostgreSQL, MySQL, SQLite). Three tables: users(id, username, email, created_at), posts(id, user_id, content, created_at) and likes(id, user_id, post_id, created_at). Foreign keys link them, and ACID transactions protect writes. Joins make questions like "all posts by people I follow, newest first" easy to write. But multi-table joins over large tables can become slow at scale, so any reporting-style query on the hot path should make you ask whether it needs a precomputed or denormalized result. Relational is the right fit for most problems: social apps, shops, booking systems. When strong consistency is a requirement, such as no double charges and no overselling, it is the natural choice. The claim that relational databases "do not scale" is mostly exaggerated. Read replicas, sharding, connection pooling and caching take them a very long way. Facebook's social graph lives in sharded MySQL behind a caching layer, which the 2013 USENIX ATC paper "TAO: Facebook's Distributed Data Store for the Social Graph" (Bronson et al.) describes.
  • Document (MongoDB, Firestore, CouchDB). A user document might embed the user's posts as an array. Reading a profile with its posts becomes one fetch with no joins. But editing one post means finding and rewriting part of a large user document, and the array grows without limit. Document stores fit when records vary a lot in shape, when data is deeply nested and would need many joins in SQL, or when the schema changes often. An example is user profiles where some users have long work histories with nested projects and others have almost nothing. Interview problems usually have a fixed, small feature set, so "the schema keeps changing" rarely applies there. Modeling in a document store means embedding and denormalizing more, which trades storage and update work for read speed.
  • Key-value (Redis, Memcached, DynamoDB used as a key-value store). The only question you can ask is "give me the value for this key". The schema becomes flat. To serve two access patterns, you store the data twice under two keys, for example user:42:profile and username:alice -> 42. Reads are very fast, but keeping copies in sync is your job. Key-value stores fit caching, sessions, feature flags, rate-limit counters and other single-ID lookups. In practice they sit next to SQL rather than replace it: SQL stays the source of truth, and Redis in front serves the hot keys.
  • Wide-column (Cassandra, HBase, ScyllaDB). Rows are grouped by a partition key and sorted by a clustering key inside it. A new post is a new row keyed by (user_id, created_at). Rows for the same user sit together on disk, so writing appends to the partition and reading a user's recent posts scans one contiguous range. These stores fit very high write volume, time-series data, telemetry, event logs and IoT readings. You model around queries even more strictly than in SQL, and you often copy the same data into several tables, one per query. Time is usually part of the key.
  • Graph (Neo4j, Amazon Neptune). Nodes and edges, built for walking relationships many hops deep. They sound like a natural fit for social networks, but they are rarely the right interview answer. The main social-graph queries (friends of a user, followers of a user) are one-hop lookups that an indexed relational table handles well, and large companies run their core relationship data on SQL. Bring up a graph database only for deep, variable-length traversals, such as fraud rings or multi-hop recommendations, and be ready to explain the extra operational work it brings.

The chart is a starting point, not a rule. Most real systems end up with a relational source of truth plus one or two specialised stores fed from it.

Normalization (1NF to 3NF) and denormalization#

Normalization removes duplication so each fact lives in one place, which prevents update anomalies (changing a customer's email in one row but not another).

  • 1NF (first normal form): each column holds a single value and there are no repeating groups. Not items = "A1,B2,C3"; use one row per item.
  • 2NF: every non-key column depends on the whole key. In order_items(order_id, sku, quantity, product_name), product_name depends only on sku, so it belongs in products.
  • 3NF: no non-key column depends on another non-key column. In orders(id, customer_id, customer_email), the email depends on customer_id, so it belongs in customers.

A short memory aid: every column depends on "the key, the whole key, and nothing but the key".

Denormalization deliberately duplicates or precomputes data to make reads faster: storing customer_name on orders for a list page, keeping an order_count on customers, or a materialized view of daily sales. The cost is extra writes and the risk of copies disagreeing, so you need a clear way to keep them in sync (same transaction, triggers, or events). Normalize first; denormalize where a measured read path needs it.

Normalization and denormalization in depth#

The idea underneath: functional dependencies. Normal forms sound abstract, but they all rest on one idea. A functional dependency A -> B means "if you know A, you know B". In a products table, sku -> name holds: one SKU always has one name. Normalization means putting each dependency in the table whose key is the left-hand side. If sku -> name holds but name sits in order_items, whose key is (order_id, sku), then the same name is repeated on every order line for that SKU. That repetition causes three kinds of anomaly:

  • Update anomaly: you rename the product, update some rows and miss others. Now the database disagrees with itself.
  • Insert anomaly: you cannot record a new product until someone orders it, because the product name only lives on order lines.
  • Delete anomaly: you delete the last order for a product and lose the product's name with it.

Edgar F. Codd introduced the relational model in "A Relational Model of Data for Large Shared Data Banks" (Communications of the ACM, 1970), and the normal forms grew out of that work. Beyond 3NF there is BCNF (Boyce-Codd normal form, where every dependency's left side is a key) and 4NF (no independent multi-valued facts in one table). Most practical schemas that reach 3NF are already in BCNF. The higher forms matter mostly when one table mixes two independent lists. For example, employee_skills_languages(employee, skill, language) forces you to store every skill-language pairing. Splitting it into two tables fixes that.

A worked decomposition. Suppose a team starts with one wide table to "keep it simple":

orders_flat(order_id, created_at, customer_id, customer_email,
            customer_city, sku, product_name, quantity, unit_price_cents)

The dependencies are order_id -> created_at, customer_id, customer_id -> customer_email, customer_city, sku -> product_name and (order_id, sku) -> quantity, unit_price_cents. Each left-hand side becomes a table: orders(order_id, created_at, customer_id), customers(customer_id, email, city), products(sku, name) and order_items(order_id, sku, quantity, unit_price_cents). That is exactly the ER diagram above.

Note what stays on order_items: unit_price_cents. It looks like a copy of products.price_cents, but it is a different fact, the price agreed at purchase time. Normalization never forces you to throw away historical facts. It only stops you from storing the same fact twice.

The cost of copying a field. Here is a common example. A posts table stores author_username next to user_id, so the feed can render without a join. It works until a user renames themselves. A heavy poster may have 200,000 posts, so a rename becomes 200,000 row updates. While it runs, some posts show the old name and some the new one. The normalized design stores the username once in users and joins at read time. The join is cheap, because it is a primary-key lookup per post, or one batched WHERE id IN (...) for a page of 20 posts.

When denormalization is the right call. There are honest reasons to break the rules:

  • Analytics and warehouses. Analysts want one wide fact table with dimensions attached (a star schema: a central fact table of events joined to small dimension tables). Columnar warehouses such as BigQuery, Snowflake and Redshift compress repeated values well, so copying is cheap there.
  • Snapshots for audit and history. An invoice must show the address and price as they were when it was issued. Copying them into the invoice row is required, not a shortcut.
  • Search indexes. Elasticsearch and OpenSearch have no joins, so each search document must carry everything it is searched or filtered on: product name, brand name and category path together.
  • Hot read paths with measured pain. A feed query joining five tables at 30,000 requests per second may be worth replacing with a precomputed row.

The durable pattern: normalized truth, denormalized views. The safest way to get both correctness and speed is to keep one normalized source of truth and build every denormalized form from it. Caches, materialized views, search indexes and feed tables are then derived data. If one goes wrong, you rebuild it from the source rather than repair it by hand.

Ways to keep copies in sync, and how each one fails.

MechanismHow it worksFailure mode
Same transactionUpdate the source and the copy in one ACID transactionOnly works when both live in the same database. Hot counters cause lock contention.
TriggerThe database updates the copy automatically on writeHidden logic that is hard to test, and it adds work to every write.
Materialized viewThe database stores a query result and refreshes itStale between refreshes. A full refresh of a big view is expensive.
Outbox + consumerWrite an event row in the same transaction, then a worker publishes itCopies lag by milliseconds to seconds. Consumers must be idempotent.
CDC (change data capture)Read the database's own change log and stream changes outSame lag as the outbox. Schema changes must be handled in the stream.
Dual write from app codeThe app writes to the database, then to the copyCrash between the two writes and the copies disagree forever. Avoid this.

Counters are the most common denormalization. Showing "1.2M likes" by running COUNT(*) over the likes table on every view is too slow for popular posts. So you store like_count on the post. Under heavy traffic, a single counter row becomes a hot spot, because every like takes a lock on the same row. Common fixes are: split the counter into N sub-counters and sum them on read; buffer increments in Redis and flush them in batches; or accept an approximate count that a stream job computes. The like table stays the truth. The counter is a view that you can always recompute.

Modeling for access patterns#

Write down every important query before finalising the model, with its rate:

#Access patternRate
1Get customer profile by IDHigh
2List a customer's orders, newest first, paginatedHigh
3Get one order with its itemsHigh
4Get product by SKUVery high
5Daily revenue by productLow (analytics)

In a relational model, each pattern maps to a query and an index: pattern 2 needs an index on orders(customer_id, created_at DESC). Pattern 5 belongs in an analytics store, not the main database. See Database Indexing.

Modeling for access patterns in depth#

Why access patterns rule: how a database actually reads. Data lives on disk in fixed-size pages: 8 KB in PostgreSQL, 16 KB in MySQL's InnoDB. To read a row, the database loads its whole page into memory (the buffer pool). A query with no useful index must load every page of the table and check each row, which is a full table scan. An index is a separate structure, usually a B-tree, that tells the database which few pages hold the matching rows. Every indexing decision comes down to reading fewer pages. Sequential reads (scanning neighbouring pages) are still much cheaper than random reads (jumping to scattered pages), even on SSDs, because of read-ahead and per-request overhead. A design that keeps the rows a query needs close together wins twice.

A worked example with numbers. Take an orders table with 100 million rows of about 200 bytes each, so 20 GB of data.

  • One 8 KB page holds about 40 rows, so the table is about 2.5 million pages.
  • The query "a customer's 20 newest orders" without an index must scan all 2.5 million pages. At about 1 GB/s of sequential read, that is roughly 20 seconds, and it pushes useful pages out of the cache.
  • With a B-tree on (customer_id, created_at DESC), the database walks 3 or 4 index pages from root to leaf, reads 20 index entries that sit next to each other, then fetches up to 20 table pages. That is about 25 page reads, often all from memory, which takes well under a millisecond on warm cache and a few milliseconds cold.

This is why the model is not finished until every high-rate access pattern has a matching index or key.

Map each endpoint to an index. The access pattern list connects directly to the API. For a social app:

EndpointQueryIndex
GET /users/:id/postsWHERE user_id = ? ORDER BY created_at DESC LIMIT 20posts(user_id, created_at DESC)
GET /posts/recentORDER BY created_at DESC LIMIT 50posts(created_at DESC)
POST /posts/:id/likeInsert, reject duplicatesPrimary key likes(user_id, post_id)
GET /posts/:id/likersWHERE post_id = ?likes(post_id, created_at)
LoginWHERE email = ?Unique index on users(email)

Notice the composite index in the first row. A single-column index on user_id finds the user's rows but then has to sort them. The composite index already stores them in the right order, so the database reads the first 20 and stops.

Column order in composite indexes. A composite B-tree index sorts by the first column, then by the second inside it, like a phone book sorted by surname and then first name. So (user_id, created_at) can serve WHERE user_id = ?, and WHERE user_id = ? AND created_at > ?, but not WHERE created_at > ? on its own. This is the leftmost-prefix rule. Put equality filters first and the range or sort column last.

Covering indexes. If an index includes every column a query needs, the database answers from the index alone and never touches the table. This is called an index-only scan. PostgreSQL's INCLUDE clause adds non-key columns to the index for this: CREATE INDEX ON posts (user_id, created_at DESC) INCLUDE (title).

Every index has a write cost. Each insert updates the table plus every index on it. A table with 8 indexes does roughly 9 structure updates per insert, and the indexes take disk space and memory. A good model indexes the patterns that matter and drops the ones that do not. PostgreSQL's pg_stat_user_indexes shows indexes that are never scanned.

Pagination is part of the model. OFFSET 100000 LIMIT 20 makes the database walk past 100,000 rows to throw them away. Cursor (keyset) pagination remembers the last row seen and asks for rows after it: WHERE user_id = ? AND (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20. With the composite index, every page costs the same, however deep the user scrolls. Adding id as a tie-breaker matters when two rows share a timestamp.

Patterns that do not belong in the main store. Some access patterns are better served elsewhere, and saying so is part of good modeling:

  • Full-text search with ranking goes to a search engine fed by CDC.
  • Analytics (revenue by product by day over two years) goes to a columnar warehouse.
  • "Users near me" needs a geospatial index (PostGIS, or geohash keys in a key-value store). See Geospatial Indexing.
  • Counts and leaderboards at high rates go to Redis sorted sets or counters, rebuilt from the source if lost.

NoSQL modeling: partition keys, sort keys and single-table design#

In key-value and wide-column stores such as DynamoDB and Cassandra, each table has a partition key that decides which node stores an item, and an optional sort key that orders items within a partition. Queries must name the partition key; inside it you can read a range of sort keys. So you design keys so that each access pattern reads one partition, one contiguous range.

Single-table design (common in DynamoDB) stores several entity types in one table, using generic key names and prefixes, so related items sit together and one query fetches them:

PKSKAttributesServes pattern
CUSTOMER#42PROFILEname, email1
CUSTOMER#42ORDER#2026-11-30#981status, total_cents2 (query PK, SK begins_with ORDER#, descending)
ORDER#981SUMMARYcustomer_id, status, address3
ORDER#981ITEM#A1quantity, unit_price_cents, product_name3 (one query returns summary + items)
PRODUCT#A1METAname, price_cents4

Notice the trade-offs: order status is stored twice (under the customer and under the order), so a status change must update both, usually in one transaction. Product name is copied into each item. Patterns not designed for (such as "all orders containing product A1") need a secondary index or another table.

Rules for good keys:

  • High cardinality and even spread: user ID or order ID, not country or status. A hot partition (one celebrity, one large tenant) caps throughput, because each partition has a limit.
  • Bounded partition size: for unbounded data (messages in a busy chat), add a time bucket to the partition key: (chat_id, month).
  • Sort keys that encode the query: timestamps for "newest first", prefixes for entity type.

NoSQL modeling in depth: query-driven design#

Entity-driven vs query-driven. Relational modeling is entity-driven. You store each entity once, link entities with foreign keys, and let joins assemble whatever a query needs. Cassandra and DynamoDB have no joins, no foreign keys and no referential integrity, and each query reads a single table. So modeling there is query-driven. You list the queries first, then design one table (or one key layout) per query, and you accept that the same data is copied into several places. Four questions shape every such table:

  1. Partition key: which value decides where a row lives? Every query must supply it.
  2. Partition size: how big can one partition get in the worst case, and can it grow forever?
  3. Clustering (sort) key: how are rows ordered inside the partition, and does the query need that order?
  4. Denormalization: what data must be copied into this table so that the query never needs a second lookup?

Example 1: chat messages, and why partitions need a bound. Discord has written publicly about storing messages in Cassandra, and the story shows each of the four questions in turn. Channels behave like big group chats. Users nearly always read the most recent messages and scroll back a little. The first schema put each channel in one partition, newest first:

CREATE TABLE messages (
  channel_id bigint,
  message_id bigint,
  author_id  bigint,
  content    text,
  PRIMARY KEY (channel_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

Two details are worth copying.

  • The clustering key is a Snowflake ID, not a timestamp. In Cassandra, two rows with the same primary key overwrite each other silently. Two messages in the same channel within the same millisecond would collide if the key were created_at. A Snowflake ID is unique and still sorts by time.
  • One channel lives on one partition. So "recent messages in channel X" goes to one set of replicas and reads one contiguous range. There is no scatter-gather across the cluster.

The weakness was partition size. Busy channels collected enormous partitions, and Cassandra handles very large partitions poorly. Compaction, repair and reads all slow down, and memory pressure rises. Worse, every channel's partition grew forever. The fix was to add a time bucket to the partition key. Each bucket covers a fixed 10-day window, counted from Discord's own epoch of 1 January 2015:

CREATE TABLE messages (
  channel_id bigint,
  bucket     int,
  message_id bigint,
  author_id  bigint,
  content    text,
  PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);

Even the busiest channel's 10 days fits comfortably in one partition, and old buckets stop growing. Most reads still touch one partition, because recent messages sit in the current bucket. The exceptions are reads just after a bucket boundary and reads in quiet channels, which must step back through earlier buckets until they find enough messages. Quiet channels were a small share of traffic, so the trade was worth it. The bucket function is simple: bucket = floor((message_time - epoch) / 10 days).

Example 2: ticket browsing, and denormalizing for the UI. Picture a ticket site's seat map for an event. It does not need strict consistency. Seats change while you look, and the real check happens in a strongly consistent store when you try to buy. It does need to always load, because many people browse and few buy. A first schema treats every seat as a ticket, partitioned by event:

CREATE TABLE tickets (
  event_id bigint,
  seat_id  bigint,
  price    bigint,
  PRIMARY KEY (event_id, seat_id)
);

This works for small venues. For a 50,000-seat stadium, though, the map's summary ("Section 104: 37 seats from $120") forces the database to read and add up tens of thousands of rows on every page view. Popular events get many page views. The fix comes from looking at how the UI is used. First you see a venue map with a summary per section. Then you click into one section and see its seats. So the model follows the screens:

CREATE TABLE tickets (
  event_id   bigint,
  section_id bigint,
  seat_id    bigint,
  price      bigint,
  PRIMARY KEY ((event_id, section_id), seat_id)
);
 
CREATE TABLE event_sections (
  event_id    bigint,
  section_id  bigint,
  num_tickets bigint,
  price_floor bigint,
  PRIMARY KEY (event_id, section_id)
);

Now each section is its own small partition, spread across the cluster, and the seat view reads only one. The venue overview reads one event_sections partition with fewer than about 100 rows. The counts in event_sections are denormalized and updated in the background. They may be slightly stale, which the UI tolerates. Ticket sites often show "100+" rather than an exact number anyway. This is query-driven modeling in a nutshell: the screens decided the tables.

How DynamoDB stores keys under the hood. A DynamoDB primary key is either a partition key alone or a partition key plus a sort key.

  • The partition key is hashed. A request router looks up the hash in a partition metadata service, which maps hash ranges to storage nodes. This resembles consistent hashing, but the map is managed centrally rather than by a peer-to-peer ring as in the 2007 Dynamo paper. The metadata service also splits partitions as they grow.
  • Within a partition, items are kept in a B-tree ordered by the sort key. So a query first hashes to the right node, then walks the B-tree to a starting sort key and reads forward or backward.

That two-level layout is why DynamoDB can grow horizontally and still answer range queries quickly. It also explains the rules. A Query must give an exact partition key, and it may add a condition on the sort key (=, between, begins_with, >, <).

Sort keys need uniqueness, too. For a group chat, chat_id as partition key and message_id as sort key lets you read a chat's messages in order. As in Cassandra, a raw timestamp is a poor sort key, because two messages can share a millisecond. Use an ID that is both unique and time-ordered: a per-partition counter, UUID v7, a Snowflake ID or a ULID.

Secondary indexes: GSI and LSI. To query by an attribute other than the table's key, DynamoDB offers two kinds of index:

Global secondary index (GSI)Local secondary index (LSI)
KeyDifferent partition key (and optional sort key)Same partition key, different sort key
StorageIts own partitions, replicated separatelyStored alongside the base table's partitions
UpdatesAsynchronous, so reads are eventually consistent onlySynchronous with the base write, so strong reads are possible
ThroughputIts own capacityShares the base table's capacity
Size limitNone per keyEach partition key's items plus LSI entries are capped at 10 GB
LifecycleAdd or remove at any timeOnly at table creation; cannot be removed
CountUp to 20 per tableUp to 5 per table

In the chat example, "all messages a user has sent across chats" needs a GSI with partition key user_id and sort key message_id. "Messages in this chat with the most attachments" can use an LSI with sort key num_attachments. Because LSIs must be chosen when the table is created, you have to know that query up front. A GSI is really a second table that DynamoDB keeps in sync for you. Every write to the base table also costs write capacity on each GSI it touches, and a GSI that cannot keep up can throttle writes to the base table.

Query vs Scan. A Query reads one partition (optionally a sort-key range). A Scan reads every item in the table or index, page by page, and filters afterwards, so you pay for everything it reads, not for what it returns. A scan of a 500 GB table is a batch job, not a request. Good key design exists to turn every user-facing request into a Query or GetItem. DynamoDB also accepts PartiQL, a SQL-like syntax (SELECT * FROM users WHERE user_id = 101). It is a convenience layer: a PartiQL statement without the partition key still turns into a scan.

You always pay for the whole item. DynamoDB reads whole items. A ProjectionExpression trims what comes back over the network, but the read is still billed on the item's full size. One read capacity unit (RCU) covers a strongly consistent read of up to 4 KB, and items can be at most 400 KB. So large, rarely needed attributes should live in separate items. Consider a business-listing app. If each business item carried all its reviews, every "show name and address" request would read hundreds of kilobytes. Put the reviews in their own items under the business's partition key (PK = BUSINESS#7, SK = REVIEW#...) or in a separate table. Then the profile read stays at a few KB. In this one case, NoSQL modeling pushes you back toward splitting things apart.

Partition throughput limits and hot keys. Each DynamoDB partition supports up to about 3,000 read units and 1,000 write units per second. Adaptive capacity moves capacity to busy partitions, but it cannot make one key exceed those limits. So a single partition key receiving 5,000 writes a second (a viral post's like counter, a global "latest events" key) throttles no matter how much capacity the table has. The usual fix is write sharding. Append a suffix from 0 to N-1 to the key (POST#9#3), spread writes across N partitions, and have reads query all N and merge. Cassandra has the same issue in a different form: one huge or hot partition overloads its few replica nodes while the rest of the cluster sits idle. See Scaling Writes for the general pattern.

Sharding a relational model follows the same logic. When a relational database outgrows one machine, you pick a shard key, and the same rules apply:

  • Shard by the main access pattern. If most queries are "posts by user", shard by user_id. Then a user's posts, likes and settings live on one shard, and those queries never cross machines.
  • Be careful with time-based sharding. Sharding by month sounds good for "recent posts", but all current writes land on the newest shard. That is a hot shard by design, the same trap as an unbucketed timestamp partition key. Time ranges suit archives and analytics, where writes are spread out or finished.
  • Avoid cross-shard queries on hot paths. A timeline showing posts from 300 followed users, sharded by author, must ask many shards and merge the results. This is the classic reason feed systems precompute timelines. See Pattern: Scaling Reads.
  • Treat the shard key as permanent. Changing it means moving every row while the system stays live. See Data Migration. Choose it from the access patterns, not from what is convenient today.

Embedding vs referencing#

In document databases (and JSON columns), related data can be embedded inside the parent document or referenced by ID.

EmbedReference
ExampleOrder document contains its items and shipping addressOrder stores customer_id; customer is a separate document
ReadOne fetch returns everythingExtra lookup or join
WriteUpdate one document atomicallyUpdate each document separately
FitsChild data owned by the parent, read together, bounded in sizeShared data, many-to-many, large or unbounded children

Rule of thumb: embed what you always read together and what belongs only to the parent; reference what is shared or grows without limit. Comments on a viral post can grow into the millions, so reference them rather than embedding.

Embedding vs referencing in depth#

What embedding really costs. Picture the document version of the social app, where each user document embeds an array of the user's posts. Reading a profile page is one fetch. But consider what each write does. Editing one post rewrites part of the user's document. Two devices adding posts at once compete for the same document. A heavy poster's document keeps growing until it hits the store's size limit: 16 MB per document in MongoDB, and 400 KB per item in DynamoDB. Long before that limit, every read of the profile drags the full post history over the network. Embedding is a bet that the parent and its children are read together, written together and stay small.

Questions that decide it. Ask these about each relationship:

  1. Ownership: does the child belong to exactly one parent and die with it? Order lines belong to an order, so embedding fits. A product appears in many orders, so reference it.
  2. Read together? If 95% of reads want the parent and children together, embedding saves a round trip each time.
  3. Bounded? An order has at most a few hundred lines. A post's comments or a user's followers have no limit, so reference them.
  4. Updated independently? If children change often on their own (a like count on each comment), embedding turns small updates into rewrites of a big document and creates contention.
  5. Queried on their own? "Find all comments by user X" across posts is awkward when comments are buried inside post documents.

Middle-ground patterns. Document-store practice has names for the common compromises:

  • Subset pattern: embed the newest N children (the 10 most recent reviews on a product page) and keep the full list in a separate collection. The common read is one fetch, and the document stays small.
  • Extended reference: store the reference plus a few fields that rarely change and are always displayed, such as {author_id, author_name} on a comment. This is a small, deliberate denormalization with a known sync cost.
  • Bucket pattern: group many small children into fixed-size bucket documents, for example one document per sensor per hour holding 3,600 readings. Document counts and index sizes stay manageable. It is the same idea as Cassandra time buckets.
  • Outlier pattern: model for the normal case (embed the followers of a typical user) and flag the rare huge case (has_overflow: true) to be handled with a separate collection.

The same choice in relational databases. PostgreSQL's JSONB columns let a row embed flexible, nested data, such as product attributes that differ by category. A GIN index makes queries inside the JSON fast. The same rules apply. Embed attributes owned by the row and read with it. Keep shared entities and anything that needs foreign keys or joins in real tables.

Schema evolution basics#

Schemas change constantly. The goal is changes that never break the code running during a deploy, when old and new versions run side by side.

  • Add, don't change: add new nullable columns or optional fields; avoid renaming or changing types in place.
  • Expand and contract for breaking changes: (1) add the new column, (2) write to both, (3) backfill old rows, (4) switch reads, (5) stop writing the old column, (6) drop it later.
  • Large tables: in some databases, adding a column with a default or building an index can lock or rewrite the table. Use online schema-change tools (gh-ost, pt-online-schema-change for MySQL) or concurrent index builds (CREATE INDEX CONCURRENTLY in PostgreSQL).
  • Schemaless stores still have schemas: code must handle old document shapes, often with a schema_version field and lazy upgrade on read.

Schema evolution in depth#

Why changes break things. During a rolling deploy, old and new versions of a service run side by side for minutes. During a canary, it can be hours. Mobile apps can stay on old versions for months. Any schema change must work with every version that can still read or write the data. That gives two compatibility goals. Backward compatible means new code can read data written by old code. Forward compatible means old code can read data written by new code, usually by ignoring fields it does not know.

A worked expand-and-contract: renaming name to full_name. On a users table with 200 million rows, a one-step RENAME COLUMN would break every running instance of the old code immediately. Done safely, it takes several deploys:

  1. Expand: ALTER TABLE users ADD COLUMN full_name text;. In PostgreSQL, adding a nullable column is instant, because it only changes metadata. Since PostgreSQL 11, adding a column with a constant default is also metadata-only.
  2. Dual write: deploy code that writes both name and full_name on every insert and update.
  3. Backfill: copy old rows in batches, for example 10,000 rows at a time by primary-key range, with short pauses. This keeps lock times tiny and lets replicas keep up. At 10,000 rows per batch and about 50 ms per batch, 200 million rows take around 20,000 batches, or roughly 20 to 30 minutes plus pauses. A single giant UPDATE would hold locks and bloat the table instead.
  4. Switch reads: deploy code that reads full_name. Compare both columns in a verification job before trusting it.
  5. Contract: stop writing name, wait until no running version uses it, then drop it.

Each step is reversible until the last one. That is the real value of the method: at any point a bad deploy can be rolled back without losing data.

Making changes online.

  • Adding NOT NULL to a big table normally scans the table under a strong lock. In PostgreSQL, first add CHECK (full_name IS NOT NULL) NOT VALID, which is instant. Then run VALIDATE CONSTRAINT, which checks existing rows under a weaker lock while traffic continues.
  • Building indexes: CREATE INDEX CONCURRENTLY in PostgreSQL builds without blocking writes, at the cost of a slower build. If it fails, you must drop the invalid index it leaves behind.
  • MySQL table rewrites: gh-ost (from GitHub) and pt-online-schema-change copy the table in the background, replay ongoing changes, and swap tables at the end. Recent MySQL versions can also do many changes instantly or in place.
  • Lock timeouts: set a short lock_timeout on migration sessions. Then a migration that cannot get its lock fails fast and retries, instead of queueing behind a long query and blocking all traffic behind it.

Schemas outside the database. Events in Kafka, messages between services and cached JSON blobs have schemas, too, and they often live longer than table rows. Serialization formats with explicit field numbers or names help. Protocol Buffers and Avro let you add optional fields safely. Old readers skip unknown fields, and new readers apply defaults for missing ones. A schema registry (such as Confluent Schema Registry) can reject incompatible changes before they ship. The rules are: never reuse a field number or name for a different meaning, never change a field's type in place, and treat a published event's shape as a public API.

Document stores: versioned documents. In MongoDB or DynamoDB, nothing stops new documents from looking different from old ones, so code must handle every shape that exists. Store a schema_version field. Old documents can be upgraded lazily, when they are next read and written back. They can also be upgraded eagerly, by a background job, which avoids carrying old-shape code forever. "Schemaless" only means the database does not enforce the schema. The schema then lives, unchecked, in application code.

Worked example: modeling a photo-sharing app end to end#

This example puts the whole process together for a small Instagram-like app, step by step, the way you would talk it through.

1. Requirements and numbers. Users post photos with captions, follow other users, like posts and view (a) a profile grid and (b) a home feed. Assume 20 million daily active users and 2 million new posts a day, which averages about 23 posts per second with peaks near 100. Assume 200 million likes a day, about 2,300 per second on average and around 10,000 at peak. Feed and profile reads might reach 100,000 per second at peak. Photos themselves go to object storage, and only their URLs live in the database. A post row is about 300 bytes. Two million posts a day is about 0.6 GB a day, or roughly 220 GB a year: big, but well within a single PostgreSQL primary for the first years. Likes are about 50 bytes each including index overhead, so 200 million a day is about 10 GB a day. That table grows fastest.

2. Core entities. User, Post, Follow, Like. Photo is an attribute of Post (a URL), not an entity of its own, unless a post can hold several photos.

3. Logical model.

4. Physical schema and indexes.

CREATE TABLE users (
  id           bigint PRIMARY KEY,          -- Snowflake ID
  username     text NOT NULL UNIQUE,
  display_name text NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE posts (
  id         bigint PRIMARY KEY,            -- time-ordered ID
  user_id    bigint NOT NULL REFERENCES users(id),
  image_url  text NOT NULL,
  caption    text CHECK (length(caption) <= 2200),
  like_count int  NOT NULL DEFAULT 0,       -- denormalized counter
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX posts_by_user ON posts (user_id, created_at DESC);
CREATE TABLE follows (
  follower_id bigint NOT NULL,
  followee_id bigint NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX followers_of ON follows (followee_id, follower_id);
CREATE TABLE likes (
  user_id    bigint NOT NULL,
  post_id    bigint NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (post_id, user_id)
);

Choices to say out loud:

  • Primary keys are time-ordered Snowflake IDs. Inserts append to the end of each index, and IDs can be made on any app server.
  • follows is stored once with two indexes. The primary key answers "whom does X follow", and followers_of answers "who follows Y". The relationship is not stored twice in two tables.
  • likes uses (post_id, user_id) as its primary key. That blocks double likes and also answers "did I like this post?" with one key lookup.
  • like_count is a deliberate denormalization. It is incremented in the same transaction as the like insert. For viral posts it would become a hot row, so the deep-dive plan is to buffer increments in Redis and flush them every few seconds.
  • The username is not copied onto posts. The feed joins to users by primary key in one batched lookup per page.

5. Access patterns mapped. Profile grid: posts_by_user, keyset-paginated. Like or unlike: primary-key insert or delete plus a counter update. Follower list: followers_of. Home feed: the hard one. Computing it at read time means "posts from the 400 people I follow, newest first", a merge over 400 index ranges on every feed load. At 100,000 feed reads a second, that is too expensive, so a precomputed feed is added below.

6. Scaling the model. At 10 GB of likes a day, the likes table needs partitioning first. Shard likes by post_id, so all likes for a post sit together and counting stays local. Shard posts by user_id, so the profile grid stays on one shard. The home feed would otherwise cross shards, so a feed table is precomputed. When someone posts, a worker writes (follower_id, post_id) rows into each follower's feed: fan-out on write. Celebrities with millions of followers are the exception. Their posts are merged in at read time instead, a hybrid many feed systems use. The feed table is derived data. It can be rebuilt from posts and follows.

7. The same model in DynamoDB. If the interviewer asks for a NoSQL version, design one key layout per access pattern:

Access patternTable / indexPKSK
Profile gridPosts tableUSER#idPOST#postId (time-ordered, read descending)
Get one postPosts GSI1POST#postIdMETA
Did I like this?Likes tablePOST#postIdUSER#userId
Who follows YFollows GSIFOLLOWEE#idFOLLOWER#id
Home feedFeed tableFEED#userIdPOST#postId, with a TTL to drop old rows

Each request becomes one Query on one partition. Like counts on viral posts would use write sharding, as described above. The price is that a new access pattern, such as "posts with a hashtag", needs a new GSI or a new table backfilled from a stream. Expect this flexibility question in a follow-up.

When to Use It#

  • At the start of every design, right after requirements: list entities and relationships.
  • Before choosing NoSQL keys: list access patterns with rates.
  • When adding features that change data shape: plan the migration path.

When NOT to Use It#

  • Do not normalize analytics tables the same way as transactional ones; warehouses favour wide, denormalized tables (star schemas).
  • Do not use single-table design when access patterns are still unknown or changing quickly; it is hard to change later.
  • Do not denormalize before measuring a slow read.

How to Implement It#

  1. List entities, attributes and relationships; draw the ER diagram.
  2. Normalize to 3NF for the transactional store.
  3. List access patterns with expected rates; map each to a query and index.
  4. Denormalize only the hot read paths, with a defined sync mechanism.
  5. For NoSQL, design partition and sort keys per pattern; check for hot and unbounded partitions.
  6. Plan schema changes with expand-and-contract and online migrations.
TechnologyFits when
dbdiagram.io, draw.io, MermaidDrawing ER diagrams
Flyway, Liquibase, Alembic, Prisma MigrateVersioned schema migrations
gh-ost, pt-online-schema-changeOnline schema changes on large MySQL tables
NoSQL Workbench (DynamoDB)Designing and testing single-table key layouts

Trade-offs#

ChoiceGainCostPick when
NormalizedOne copy of each fact, flexible queriesJoins on readTransactional core data
DenormalizedFast reads, fewer joinsDuplicate writes, sync riskHot read paths, feeds
Single-table NoSQLOne query per access pattern at any scaleRigid; new patterns need indexes or backfillsStable patterns, very high scale
EmbeddingOne read, atomic updateLarge documents, duplicationOwned, bounded children
ReferencingShared data stays consistentExtra lookupsShared or unbounded data
Surrogate keysStable IDs that never changeOne extra unique index for the natural keyAlmost always
Time-ordered IDs (UUID v7, Snowflake)Append-friendly indexes, sortableExpose creation time, need a generatorHigh insert rates, feeds
Foreign keys enforcedDatabase guarantees integrityWrite checks, cascade locks, single-node onlyOne database, moderate scale
Time-bucketed partitionsBounded partition sizeReads may span several bucketsUnbounded per-key data such as messages
Derived views via CDCFast reads, rebuildable from truthSeconds of lag, more moving partsSearch, feeds, counters

Common Pitfalls#

  • Storing lists in a single text column (breaks 1NF, cannot index or join).
  • Losing history by referencing a mutable value (current price) instead of copying it at the time of the event.
  • Low-cardinality partition keys creating hot partitions.
  • Unbounded embedded arrays that grow until documents hit size limits.
  • Renaming columns in one deploy and breaking the old code still running.
  • Using timestamps as unique keys, so rows in the same millisecond silently overwrite each other.
  • Choosing a shard key from the data shape instead of the main access pattern, then querying every shard.
  • Sharding or partitioning by time on a write-heavy table, sending all writes to one hot shard.
  • Running COUNT(*) or aggregations on the hot path instead of keeping a derived counter.
  • Dual-writing a denormalized copy from application code with no outbox or CDC.
  • Treating a schemaless store as having no schema, with no version field for old document shapes.

Real-World Examples#

AWS documentation and talks on DynamoDB promote single-table design with composite partition and sort keys, so that each access pattern is served by one query.

Discord's message storage design partitions messages by channel and time bucket, keeping each partition to a bounded size, as described in its engineering blog.

Discord later wrote about moving its message store from Cassandra to ScyllaDB, keeping the query-driven (channel_id, bucket) model. The schema survived a change of database because it came from the access patterns.

Facebook's TAO paper (Bronson et al., USENIX ATC 2013) describes the social graph as objects and associations stored in sharded MySQL with a large caching tier. It is a well-known example of graph-shaped data on a relational base.

GitHub built and open-sourced gh-ost to run online schema migrations on its large MySQL tables without blocking traffic.

In the Interview#

Handling data-model questions in an interview#

A five-step script. Once you introduce the database, follow these steps:

  1. Name the database type and why. The default is "PostgreSQL, because orders and payments need transactions".
  2. List each core entity with only the columns the features need.
  3. Mark keys and relationships: "posts has user_id pointing to users, likes is a join table keyed by (post_id, user_id)".
  4. Name the index or partition key for each high-rate query.
  5. Flag the one or two places you will denormalize, and say how the copy stays in sync.

Do this in two or three minutes, then move on. The schema supports the design; it should not take it over.

Follow-ups to prepare for.

  • "Why not store the username on each post?" A rename would rewrite thousands of rows and leave them inconsistent while it runs. A primary-key join is cheap.
  • "Your partition key is chat_id. What happens with a channel that has a billion messages?" Add a time bucket to the partition key so partitions stay bounded. Reads walk back across buckets.
  • "How would you add a new query later?" In SQL, add an index, built concurrently. In DynamoDB, add a GSI. In Cassandra, add a new table and backfill it from the source or a stream.
  • "How do you change a column without downtime?" Expand and contract: add, dual-write, backfill, switch reads, then drop.
  • "Do you need foreign keys?" Yes, on a single database. Across shards they cannot be enforced, so integrity moves into the application, plus a cleanup job.
  • "Why not a graph database for followers?" Follower queries are one hop. An indexed follows table handles them, and big social networks do the same.

Strong signals. Say which field is a historical snapshot (price at purchase). Choose time-ordered IDs and explain why. Bound partitions before the interviewer asks. Call derived stores rebuildable.

Red flags. A graph database chosen because "it's social". Timestamps as unique keys. Unbounded partitions or arrays. A COUNT(*) on the hot path. A shard key that forces every main query to visit all shards.

Deep Dive: Modeling history, multi-tenancy and hierarchiesShow

History and auditing. Many domains need "what was true when": prices, addresses, account balances. Options: append-only event tables (every change is a row), effective-dated rows (valid_from, valid_to), or full event sourcing. Append-only data also simplifies caching and replication.

Multi-tenancy. SaaS products choose between a shared table with tenant_id on every row (cheap, needs strict filtering and per-tenant indexes), a schema per tenant, or a database per tenant (strong isolation, more operations). Large tenants are often moved to their own shards.

Hierarchies and graphs. Folders, org charts and comment threads can use adjacency lists (parent_id) with recursive queries, materialized paths (/1/4/9/), or closure tables that store every ancestor pair. Choose by whether reads or moves are more frequent.

Deep Dive: Partition sizing math and choosing a bucket widthShow

Sizing a partition. Before settling a partition key, estimate its worst case. Take a chat partitioned by (channel_id, bucket). Suppose the busiest channel gets 50 messages a second at peak and averages 5 a second over a day. At about 300 bytes per message on disk after compression and overhead, that is 5 × 86,400 × 300 ≈ 130 MB a day. A common guideline is to keep Cassandra partitions in the tens of megabytes and well under a few hundred. One day per bucket gives about 130 MB, which is borderline for the busiest channel. A 10-day bucket would be about 1.3 GB for that channel, but it suits typical channels, which send a few thousand messages a day. That is the real tension. A bucket width tuned for the busiest key makes quiet keys scatter their few messages across many nearly empty buckets, so reads walk many partitions to fill one page.

Ways out of the tension.

  • Pick the width for the typical key and cap the outliers. Detect channels whose current bucket is over a size threshold and give them a finer bucket scheme, recording the scheme per channel.
  • Size buckets by message count, not time. Start a new bucket every 100,000 messages, and keep a small index table of (channel_id, bucket_no, first_message_id) so reads know where each bucket starts.
  • Make the read loop cheap. For quiet channels, keep a "last non-empty bucket" pointer so reads jump straight to data instead of probing empty buckets.

Write sharding math for hot keys. If one key must take W writes per second and a partition can take about P, you need at least N = ceil(W / P) shards, plus headroom. A post receiving 8,000 likes a second against a 1,000-writes-per-second partition limit needs N = 8, and 10 or 16 in practice. The suffix can be random (even spread, but reads must query all N) or derived from the user ID (hash(user_id) mod N). A derived suffix means the same user always hits the same shard, which makes "did I like this?" a one-shard lookup. Reads of the total query N partitions in parallel. N is small, so the extra read latency is the slowest of N fast requests.

ID choice and index locality, quantified. Inserting 10,000 rows a second with random UUID v4 primary keys into a B-tree larger than memory means most inserts touch a different leaf page. With 16 KB InnoDB pages and a 100 GB index, the working set is the whole index. The buffer pool then churns, and write amplification rises as pages split in the middle. With time-ordered keys (UUID v7, Snowflake, auto-increment), nearly all inserts hit the same few rightmost leaf pages, which stay in memory, and pages fill completely before the next one starts. Teams that switch from random to time-ordered keys on large tables commonly report much lower insert latency and smaller indexes. The exact gain depends on how far the index exceeds memory.

Key Takeaways#

  • Model entities, attributes and relationships first; ER diagrams make cardinalities explicit.
  • Normalize to 3NF for correctness, then denormalize measured hot read paths with a clear sync method.
  • List access patterns with rates; every important query should map to an index or key design.
  • In NoSQL, partition keys spread load and sort keys serve range queries; single-table design fetches related items in one read.
  • Embed owned, bounded data; reference shared or unbounded data; evolve schemas with expand-and-contract.
  • Start from data volume, access patterns and consistency needs, then pick the database model. The default is relational.
  • Use stable, time-ordered surrogate keys. Never use timestamps alone as unique keys.
  • Keep one normalized source of truth and build caches, search indexes, feeds and counters as rebuildable derived data.
  • In Cassandra and DynamoDB, design one table or index per query, bound every partition, and shard hot keys.
  • Shard by the main access pattern, avoid time-range shard keys for hot writes, and treat the shard key as permanent.