Study guide · System design

Data design: from entities to storage

Entities and relationships, keys, normalisation, indexes, denormalisation, datastore families, partitioning and schema evolution, with a definition at every new term and practice questions at the end.

Contents
  1. ·Learning objectives
  2. §1Core concepts
  3. §2Entities, relationships and cardinality
  4. §3Access patterns and the order of design
  5. §4Keys and integrity constraints
  6. §5Functional dependencies and normalisation
  7. §6Indexes
  8. §7Denormalisation and read models
  9. §8Choosing a datastore family
  10. §9Partitioning and hot keys
  11. §10Schema evolution
  12. ·Common mistakes
  13. ·Practice questions
  14. ·Review checklist

Start here

Learning objectives

  1. Explain what a data model contains, distinguish the conceptual, logical and physical models, and say how much of the model to specify at the high-level and at the low-level design stage.
  2. Model a domain as entities, attributes and relationships, state the cardinality and participation of each relationship, resolve a many-to-many relationship into an associative entity, and distinguish an entity from a value object.
  3. Derive the access patterns of a system from its API surface and use them to justify every later storage decision.
  4. Choose primary and foreign keys and declare integrity constraints, distinguishing natural from surrogate keys.
  5. Identify functional dependencies, recognise the anomalies they cause, and decompose a table into third normal form or Boyce–Codd normal form.
  6. Calculate the depth of a B-tree index and the pages a query reads with and without it, order the columns of a composite index, and justify a denormalisation or read model with the mechanism that keeps it consistent.
  7. Choose a datastore family and a partition key from access patterns, calculate the load on the hottest shard, and plan a schema change with expand–migrate–contract.

§1 · Definitions

Core concepts

This section defines the central term, data model, and the terms every later section relies on: schema, entity, attribute, relationship, value object, and the three stages of data modelling. Each definition is set out in a callout where the term is first introduced, and the prose after it explains the mechanism.

A data model must account for entities, their relationships, and the queries the system will run, and the inclusion of queries is deliberate: two models with identical entities can need different storage if they are read differently. The word schema comes from the Greek skhēma, shape or plan. The model is the design and the schema is that design expressed in the vocabulary a particular engine accepts. Values change constantly while the model changes rarely, which is why code is written against the model and keeps working as the data grows.

The word entity comes from two traditions that are both still in use, and they explain why data design appears at both levels of design. The first is the entity–relationship model, which Peter Chen introduced in 1976 for designing databases: data is described as entities, their attributes and the relationships between them, and drawn as an entity–relationship diagram. In a relational schema an entity usually becomes a table, an attribute a column, and a relationship either a column that refers to another table or, for a many-to-many relationship, a table of its own.

The second tradition is domain-driven design, from Eric Evans's 2003 book of that name. There an entity is an object defined by a stable identity rather than by its values: an order stays the same order when its status changes from paid to shipped. A value object has no identity, so £40.00 is the same as any other £40.00, and changing it means replacing it. The distinction decides persistence as well as class design. An entity needs a key, because something must stay fixed while its attributes change; a value object is usually stored inline as columns of the entity that owns it, or embedded in its document, and needs no key of its own.

The three stages exist because the questions at each stage have different owners and change at different rates. Whether an order may exist without a customer is a business rule settled with domain experts. Whether the customer's details are stored once or repeated on each order is a structural decision settled by reasoning about dependencies. Whether to add a structure that speeds lookups by order date is a performance decision settled by the queries. Keeping the stages apart means a change of database product touches only the physical model, and a change of indexing never alters what the data means.

Conceptual and logical modelling usually belong to high-level design (HLD), which describes a system as components and their connections, and physical modelling to low-level design (LLD), which describes what happens inside one component. The mapping is rough: choosing a database type and deciding how to distribute records across machines are physical decisions, yet they are taken at the HLD stage. They are taken early because they shape the architecture diagram, whereas column types and indexes do not. The following diagram shows the three stages, the input that drives each one, and where the HLD and LLD boundary falls.

Diagram
 conceptual model          logical model                physical model
 entities, relationships ─► attributes, keys,         ─► tables or collections, types,
 business rules             normalised dependencies      indexes, partitioning, denormalisation
       ▲                          ▲                             ▲
 domain experts             dependency analysis           access patterns and measured load
 ├──────────────── HLD ─────────────────┤  + datastore family and partition key
                                        ├──────────────── LLD ──────────────────┤

Read the diagram from left to right: each stage adds detail to the one before it, and the input underneath each stage is what justifies the detail it adds. The HLD bracket covers the first two stages plus the two physical decisions that shape the architecture; the LLD bracket covers the rest of the physical model.

The confusion learners most often have with the term data model is to treat it as a synonym for the list of tables. A list of tables is one physical rendering of a model, and it omits most of what the model contains: the business rules that make relationships mandatory or optional, the dependencies that justify how attributes were grouped, the access patterns that justify the indexes and the datastore, and the reasons for any departure from the logical design. Two databases with identical tables can encode different models, for example if one requires every order to have a customer and the other allows orphaned orders.

§2 · Conceptual model

Entities, relationships and cardinality

To state relationships precisely, this guide uses an online shop as a running example: customers place orders, each order contains one or more lines, and each line refers to a product. The example is illustrative.

The method is to read the requirements for nouns the business needs to keep facts about, which become candidate entities, and for verbs connecting them, which become candidate relationships. A noun that only describes another, such as "email address" in "each customer has an email address", is an attribute. The test for promoting an attribute to an entity is whether the system must record facts about it in turn: a delivery address printed once on a label can be a value object stored on the order, but an address that customers save, name and reuse across orders has facts and an identity of its own, and becomes an entity.

Cardinality is borrowed from set theory, where it means the number of members of a set. In modelling it answers "at most how many?", and participation answers "at least how many?", so together they give each end of a relationship a range such as 0..* or 1..1. A customer places zero or more orders, because a newly registered customer has none, while an order is placed by exactly one customer, because an order without a customer has no one to bill. Both ends matter because they turn into different physical constructs: every order must store the identity of an existing customer, while the customer needs no column listing its orders.

The relationship between orders and products is many-to-many: one order holds several products and one product appears in many orders. A relational table cannot represent this with one column, because a column holds one value per row, and storing a list of product identifiers in one field makes each pairing harder to query and constrain; the formal rule is explained in "Functional dependencies and normalisation".

In the shop the associative entity is the order line. It replaces one many-to-many relationship with two one-to-many relationships, and it gives a home to facts that belong to neither side alone: the quantity ordered and the price charged on that order for that product. The price charged is a property of the sale, not of the product, which is why the order line is an entity and not merely a pair of pointers. The following diagram shows the shop's conceptual model, with each relationship labelled by its verb and each end by its range.

Diagram
 ┌──────────┐ 1..1     places     0..* ┌──────────┐ 1..1   contains   1..* ┌────────────┐ 0..*  refers to  1..1 ┌──────────┐
 │ Customer │──────────────────────────│  Order   │────────────────────────│ Order line │────────────────────────│ Product  │
 └──────────┘                          └──────────┘                        └────────────┘                        └──────────┘
  id, email, name                       id, created_at                      quantity, unit_price                  id, sku, name, list_price

Read each range as belonging to the entity it sits next to: the 0..* beside Order says a customer places zero or more orders, and the 1..1 beside Customer says each order has exactly one customer. The 1..* beside Order line says an order has at least one line, a rule that the link from each line to its order cannot enforce on its own, because it constrains each line rather than the order; it is usually checked by the application, or by inserting the order and its lines in one transaction.

§3 · Design order

Access patterns and the order of design

The conceptual model in "Entities, relationships and cardinality" says what exists; access patterns say how it is used, and they are the decisive input to every storage decision. Choose a database type to serve the access patterns, rather than choosing a type first. Access patterns matter most at the HLD stage, because they decide the storage choice and the partitioning. An access pattern is more than a query: its frequency and latency target decide whether it needs a faster lookup structure, a copy, or a different store.

The dependency between the API and the data model can be resolved in four steps. A short list of entity names comes first, because API resources are those entities. The API surface comes second, because each endpoint is a read or write the storage layer must serve. The data model and storage choice come third, derived from the access patterns those endpoints imply, and the architecture comes fourth. Designing the schema first means choosing storage before knowing which queries it must serve, which leads to tables no endpoint reads and to a datastore chosen by habit.

The following table lists the shop's main access patterns, and it is useful because every later decision in the guide refers back to one of its rows. The frequencies are assumptions for this example.

EndpointAccess patternAssumed frequencyWhat it requires of the data model
GET /orders/{id}Read one order with its lines and product names500 per secondLookup by order key, lines grouped by order
GET /customers/{id}/ordersLatest 20 orders for a customer, newest first300 per secondIndex on (customer_id, created_at)
POST /ordersCreate an order, its lines and a stock decrement atomically50 per secondMulti-entity transaction across order, lines and stock
GET /products/{id}/ordersOrders containing a product, for support staff1 per secondIndex on order_line(product_id)

Read across each row and the right-hand column is the justification every storage decision needs: this endpoint needs this query, and this query needs this store and this key. The third row, an atomic write across three entities, is the one that points to a relational store in "Choosing a datastore family", and the second row is the one that motivates a lookup by customer and date in "Indexes". The process is not strictly linear: modelling the data often exposes a query no endpoint asked for, and the right response is to add the endpoint rather than treat the API as finished.

§4 · Logical model

Keys and integrity constraints

Rules for identifying rows, referring to rows in other tables, nullability and uniqueness are detailed design decisions. Translating the conceptual model into a logical relational model needs a way to identify each row and a way for one table to refer to another, and keys provide both.

A customer table might have a customer number and an email address that are each unique, so both are candidate keys. Minimality is what separates a candidate key from its supersets: the pair (customer number, email) is also unique but is not a candidate key, because the customer number alone suffices. Choosing which candidate becomes the primary key is a design decision, and the main criterion is stability, because every row that refers to it must be updated when its value changes. This is the persistence form of the entity–value object distinction in "Core concepts": the primary key is the identity that stays fixed while everything else about the entity changes.

The trade-off is between meaning and stability. A natural key needs no extra column and is readable, but it inherits every change the outside world makes to it: customers change email addresses and suppliers reissue product codes. A surrogate key never needs to change, because nothing outside depends on its value, but it does not prevent duplicates, since the same customer registered twice receives two surrogate values. The common practice is a surrogate primary key plus a unique constraint on the natural candidate key, which keeps references stable and still rejects duplicates. A URL shortener is a case where the natural key is the right primary key: short_code is generated by the system, never changes, and is the value every lookup supplies.

Foreign keys turn relationships into structure. "A customer places orders" becomes a customer_id column on the order table, on the "many" side, and the participation rule "every order has exactly one customer" becomes NOT NULL. When a referenced row is deleted the schema declares what happens: RESTRICT refuses the deletion, CASCADE deletes the referring rows too, and SET NULL clears the reference. The choice follows from the domain: cascading the deletion of a customer into their orders would destroy financial records. Database constraints enforce correctness in the engine rather than in every application that touches the table. The illustrative schema that follows applies these rules to the shop.

SQL
CREATE TABLE customer (
  customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- surrogate key: stable identity
  email       TEXT NOT NULL UNIQUE,                            -- natural candidate key kept as a constraint
  name        TEXT NOT NULL
);
CREATE TABLE product (
  product_id  BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku         TEXT NOT NULL UNIQUE,                            -- supplier code, may be reissued
  name        TEXT NOT NULL,
  list_price  NUMERIC(10,2) NOT NULL CHECK (list_price >= 0)   -- CHECK encodes a business rule
);
CREATE TABLE customer_order (                                  -- ORDER is a reserved word in SQL
  order_id    BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id BIGINT NOT NULL                                  -- mandatory participation: 1..1
              REFERENCES customer (customer_id) ON DELETE RESTRICT, -- keep financial history
  created_at  TIMESTAMPTZ NOT NULL
);
CREATE TABLE order_line (                                      -- associative entity
  order_id    BIGINT NOT NULL REFERENCES customer_order (order_id) ON DELETE CASCADE,
  product_id  BIGINT NOT NULL REFERENCES product (product_id),
  quantity    INTEGER NOT NULL CHECK (quantity > 0),
  unit_price  NUMERIC(10,2) NOT NULL,                          -- price charged: a fact of the sale
  PRIMARY KEY (order_id, product_id)                           -- one line per product per order
);

The composite primary key on order_line states a business rule as well as an identity: a product appears at most once per order, so a second unit raises the quantity. If the business wanted two lines for the same product at different discounts, the key would become a line number within the order, which shows that key choice is a statement about the domain.

Keys and constraints also depend on the datastore. For example, a URL shortener might store ShortUrl in a key-value store partitioned on short_code. A key-value store enforces no foreign keys, so a column declared as owner_id BIGINT REFERENCES users(id) is a relational construct it cannot provide. It serves "list my links" only if the database or application maintains a separate lookup from owner to links, and that lookup must stay consistent. A relational schema with a foreign key is a defensible choice for a URL shortener at moderate scale; a key-value design replaces the foreign key with an application-level check and names the additional lookup it needs. Either is workable, provided the storage choice made at the HLD stage and the schema written at the LLD stage agree.

§5 · Logical model

Functional dependencies and normalisation

Normalisation decides how far data is split into separate tables so that each fact is stored once, and this section explains the theory behind it. Keys say which attributes identify a row; normalisation uses the same idea to decide which attributes belong together, so that no fact is stored in many rows where the copies could disagree.

A functional dependency is a statement about the domain, not about the rows present: customer_id → customer_email holds because the business assigns one email per customer, and it would hold in an empty table. A candidate key is exactly a minimal set of attributes that determines every other attribute. Normalisation finds dependencies whose determinant is not a key and moves them into tables where it is.

E. F. Codd, who proposed the relational model at IBM in 1970, defined the first three normal forms in 1970 and 1971, borrowing the term from mathematics, where a normal form is a standard representation of an object. Each form forbids one shape of dependency, so they can be learned as a sequence of questions asked of a table.

The mechanism behind each form is the same. A partial or transitive dependency means some attribute is determined by something smaller than the row's key, so the same determinant value, and with it the same dependent value, recurs in every row that shares it. Moving the dependency into its own table, keyed by its determinant, stores the dependent value once per determinant value instead of once per row.

For a split into two tables, the decomposition is lossless when the shared attributes form a key of at least one part, which is why each normalisation step keeps the determinant in both tables: as the primary key of the new table and as a foreign key in the old one.

Worked examplenormalising the shop's order data

Suppose a prototype stores everything in one table, sales(order_id, created_at, customer_id, customer_name, customer_email, product_id, product_name, list_price, quantity, unit_price), one row per product per order, with primary key (order_id, product_id). Every field holds one value, so it is in 1NF.

Step 1 writes the dependencies from the business rules: order_id → created_at, customer_id; customer_id → customer_name, customer_email; product_id → product_name, list_price; and (order_id, product_id) → quantity, unit_price.

Step 2 checks 2NF. created_at and customer_id depend on order_id alone, and product_name and list_price on product_id alone; all four are partial dependencies. Splitting them out gives order(order_id, created_at, customer_id, customer_name, customer_email), product(product_id, product_name, list_price) and order_line(order_id, product_id, quantity, unit_price).

Step 3 checks 3NF. In order, order_id → customer_id → customer_name, customer_email, and customer_id is not a key of order, so the name and email are transitively dependent. Splitting gives customer(customer_id, customer_name, customer_email) and order(order_id, created_at, customer_id), which is the schema in "Keys and integrity constraints".

Step 4 measures the redundancy removed. Assume 200 customers, 1,000 orders of 3 lines each, and 30-byte emails; these are assumptions for the example. The single table has 1,000 × 3 = 3,000 rows, so each email is stored 3,000 ÷ 200 = 15 times on average, occupying 3,000 × 30 = 90,000 bytes, against 200 × 30 = 6,000 bytes in customer. As a check, 90,000 ÷ 6,000 = 15, the average number of copies. Storage is the smaller benefit: in the single table a change of email must update 15 rows, and any row missed leaves the customer with two emails. The table also has an insertion anomaly, because a new product cannot be recorded until someone orders it, and a deletion anomaly, because deleting the only order for a product deletes its name and price.

The following diagram shows the decomposition as a tree, each split labelled by the normal form that required it.

Diagram
 sales(order_id, product_id, created_at, customer_id, customer_name, customer_email, product_name, list_price, quantity, unit_price)
   ├── 2NF: order_id → … ──► order(order_id, created_at, customer_id, customer_name, customer_email)
   │                           └── 3NF: customer_id → … ──► customer(customer_id, customer_name, customer_email)
   │                                                        order(order_id, created_at, customer_id)
   ├── 2NF: product_id → … ─► product(product_id, product_name, list_price)
   └── whole key ───────────► order_line(order_id, product_id, quantity, unit_price)

Read each branch as one dependency leaving the parent table together with its determinant, which stays behind as a foreign key so the split remains lossless. The leaves are the four tables of the final schema.

Raymond Boyce and Codd defined BCNF in 1974 to close a gap in 3NF, which constrains only dependencies of non-key attributes. The gap appears with overlapping composite candidate keys. In a tutoring service where each tutor teaches one course and each student has one tutor per course, tutoring(student, course, tutor) has (student, course) → tutor and tutor → course, so both (student, course) and (student, tutor) are candidate keys. Every attribute belongs to a candidate key, so the table is in 3NF, yet tutor → course repeats each tutor's course for every student. Splitting into tutor_course(tutor, course) and tutor_student(student, tutor) reaches BCNF, at the cost that "one tutor per student per course" can no longer be enforced by a key on one table. The shop has no overlapping keys, so there 3NF and BCNF coincide.

§6 · Physical model

Indexes

The normalised model in "Functional dependencies and normalisation" says what is stored; the physical model decides how, so that the access patterns from "Access patterns and the order of design" run fast enough. The questions are which indexes the queries need and what each costs. Databases store tables in fixed-size pages, typically 4 to 16 KB, and read whole pages at a time, so the cost of a query is approximately the number of pages it touches.

Rudolf Bayer and Edward McCreight described the B-tree at Boeing in 1970; the meaning of the B was never officially stated. The structure works because its fanout is large: each level multiplies the reachable rows by hundreds, so depth grows with the logarithm of the row count to the base of the fanout. A lookup reads one page per level from root to leaf, then the table page the leaf points to.

Worked examplechecking the page-read estimate

Consider a composite index on (customer_id, created_at) for fetching a customer's latest 20 orders from a table of 50 million rows. Assume 8,192-byte pages, 16-byte index entries and 200-byte rows, and ignore page headers; these are assumptions for the example.

The fanout is 8,192 ÷ 16 = 512. Two levels reach 512 × 512 = 262,144 rows, fewer than 50,000,000; three reach 262,144 × 512 = 134,217,728, more, so the index is 3 levels deep (check: log 50,000,000 ÷ log 512 = 7.699 ÷ 2.709 = 2.84, rounded up to 3). The descent reads 3 pages, and the 20 adjacent entries for one customer fit in one leaf, since 20 × 16 = 320 bytes. Fetching the 20 rows can then cost up to 20 table pages, because a customer's orders are scattered across the table in the order they were placed. The indexed query reads up to 3 + 20 = 23 pages.

Without the index, each page holds 8,192 ÷ 200 = 40.96, so 40 whole rows, and the scan reads 50,000,000 ÷ 40 = 1,250,000 pages, about 1,250,000 ÷ 23 = 54,348 times as many. The index traversal reads only a few pages, but fetching the rows can dominate the query cost. An index that also holds the needed result columns removes those row fetches and brings the query down to the 3 pages of the descent, or 4 if the customer's entries straddle two leaves.

Column order in a composite index comes from the query: equality conditions first, then the column used for a range or sort. (customer_id, created_at) serves "this customer's orders, newest first", because one customer's entries are contiguous and already sorted by time, but it cannot serve a query on created_at alone, because rows from one day are scattered across every customer's range. Two failures are common: ordering the columns wrongly, and wrapping the indexed column in a function, as in WHERE date(created_at) = …, which hides the stored values from the planner. Selectivity sets the limit from the other side: a condition matching 30% of the 50 million rows needs up to 15,000,000 random page reads through the index, twelve times the 1,250,000 sequential reads of a scan, so the planner ignores the index.

Indexes are paid for on every write. Each insert, delete, and update of an indexed column must change every index, so a table with four secondary indexes turns one row insert into one table-page write and four index-leaf writes, five instead of one, before page splits. The rule that follows is to index for the access patterns the system has, not for every column a query might mention. The illustrative statements below index the shop's two non-key patterns.

SQL
CREATE INDEX order_by_customer_time
  ON customer_order (customer_id, created_at DESC)  -- equality column first, sort column second
  INCLUDE (order_id);                               -- covering for a list of order ids and dates: no table read

CREATE INDEX order_line_by_product
  ON order_line (product_id);                       -- PK leads with order_id, so it cannot serve this lookup

§7 · Physical model

Denormalisation and read models

Indexes make it cheaper to find rows; denormalisation makes it cheaper to assemble them, by storing the result of a join or computation in advance. It is a detailed design decision: data deliberately duplicated for read speed. It differs from an unnormalised design in that it is a decision taken after normalising, for a named read, with a named mechanism for consistency. It reintroduces exactly the update anomaly that "Functional dependencies and normalisation" removed, so it pays only where the read is far more frequent than the write it complicates.

Worked examplea stored order total

The order history page shows each order's total, which otherwise means reading and summing every line. An order has three lines: 2 units at £12.50, 1 at £40.00 and 3 at £4.00. The line amounts are 2 × 12.50 = £25.00, 1 × 40.00 = £40.00 and 3 × 4.00 = £12.00, and the total is 25.00 + 40.00 + 12.00 = £77.00. Adding order_total to customer_order lets the page read one row per order instead of one per line. The column is a second copy of a fact the lines determine, so the lines and the total are written in one transaction, or a trigger recomputes the total when a line changes, and a reconciliation query that recomputes totals from lines checks that the mechanism works. Orders rarely change once placed, so the write cost is small and the saving applies to every page view.

CQRS generalises denormalisation from one column to whole read models. For example, an order-history page can read a customer_order_summary document built from order, payment and shipment events, instead of joining four tables per request. Because the read model is updated after the write commits, typically from an event stream or change data capture, it lags its source, and the contract of the screen must tolerate that lag. The general risk of every denormalisation is updating the copy from some write paths but not others, so the copies drift permanently. Routing all updates through one propagation path, rather than through each piece of code that writes, is what prevents it.

§8 · Storage choice

Choosing a datastore family

The sections up to "Denormalisation and read models" assume a relational store; to decide which storage technology fits the queries, answer five questions before naming a product: what the queries are, the read and write shape, the consistency each operation needs, the access keys, and the operational reality.

The access key matters most: whether there is a single natural partition key that almost every query includes decides between relational and the other families more often than anything else. When every query supplies the key, data can be spread across machines by that key and each query sent to one machine. When queries filter on different attributes, or join entities, a store that only finds data by key cannot answer them without copies. The following table compares the five families across these dimensions, and it is useful because each family's strength is another's weakness.

FamilyModelGood atBreaks whereChoose when
RelationalNormalised tables, foreign keys, ACID transactions, query plannerMulti-entity transactions, queries nobody anticipated, constraints enforced by the engineWrite throughput on one primary, working set beyond RAM, cross-shard joinsTransactions, relationships or unknown future queries
DocumentSelf-contained JSON-like documents with secondary indexesAggregates read and written whole, heterogeneous fieldsCross-document consistency, unanticipated queries, duplication driftEach access pattern reads one aggregate
Key-valueGet and put by keySub-millisecond lookups, caches, sessions, countersNo query without the key, memory-bound, hot keysEvery access supplies a known key
Wide-columnPartitions by partition key, sorted columns within eachVery high ordered write volume under a known keyNew queries need new tables, no joins, unbounded partitionsWrite volume beyond a sharded relational cluster and stable key-based access
GraphNodes and edges with direct neighbour pointersDeep, variable-length traversalsBulk analytics, high write load, one or two hopsTraversal depth is the query, usually as a secondary store

Reading down the "Breaks where" column, each family past relational gives up the ability to answer an unplanned question in exchange for scale or speed on planned ones, which is why a relational store is a sensible starting point until a specific, named constraint forces otherwise. Applied to the shop, the atomic order creation in "Access patterns and the order of design" needs a multi-entity transaction, so orders, lines and stock belong in a relational store, and Postgres is a suitable choice for this online shop. Two points qualify the comparison. A document store is not schemaless: the schema moves from the database into every application version that ever wrote data, an approach called schema-on-read, and Postgres JSONB offers most of the document benefits with transactions and constraints. And every additional engine is an operational cost: another backup, another migration path and another system to keep running.

§9 · Partitioning

Partitioning and hot keys

The partition key from "Choosing a datastore family" also decides how data is spread across machines once one machine is not enough. The partition key belongs to HLD for this reason: it determines which queries stay on one machine, and so shapes the architecture.

Hash assignment spreads keys evenly by count; range assignment keeps neighbouring keys together so range queries touch few shards, at the risk that new keys, such as today's timestamps, all land on one shard. For example, a system can partition orders by a hash of customer_id across 16 shards, so each customer's orders sit on one shard and a per-customer query touches one node, while a query by product touches all 16. The partition key thus fixes both the balance of load and the cost of every query that does not include it. The key should spread traffic as well as data, and the common failure is checking balance by key count rather than traffic.

Worked examplethe hottest shard

Suppose one tenant generates 40% of requests. With 16 shards partitioned by a hash of tenant, an even spread would give each shard 100 ÷ 16 = 6.25% of traffic. The hot tenant's 40% lands on one shard, and the other 60% spreads over all 16, adding 60 ÷ 16 = 3.75% to each. The hot shard carries 40 + 3.75 = 43.75%, which is 43.75 ÷ 6.25 = 7 times the average, while the other 15 carry 3.75% each. As a check, 43.75 + 15 × 3.75 = 43.75 + 56.25 = 100%.

Salting the tenant's key with 8 suffixes, assuming they hash to 8 different shards, spreads its 40% as 40 ÷ 8 = 5% per shard. Those 8 shards carry 5 + 3.75 = 8.75% each, 8.75 ÷ 6.25 = 1.4 times the average, and the other 8 carry 3.75% (check: 8 × 8.75 + 8 × 3.75 = 70 + 30 = 100%). The cost is that every read of that tenant's data must now query 8 partitions and merge the results, which is why salting is applied only to keys known to be hot. Wide-column stores face the related problem of unbounded partitions, handled by bucketing, partitioning a chat channel's messages by channel and month so that no partition grows without limit.

§10 · Schema evolution

Schema evolution

Every decision so far addresses today's requirements. The schema must also be able to change without breaking running code. The difficulty comes from deployment: in a system serving traffic, the database changes at one moment but application servers are replaced one by one, so old and new code run against the same schema at the same time. A change that removes something the old code reads causes errors for as long as any old server runs, and a change that destroys data cannot be undone by reverting code.

Consider renaming user.name to full_name. The following diagram shows the steps as states, each deployed and verified before the next.

Diagram
 v1: reads and writes name
   ──► expand: add full_name (nullable)              old code unaffected
   ──► dual-write name and full_name; backfill rows in batches
   ──► switch reads to full_name                     rollback still possible
   ──► stop writing name
   ──► contract: drop name, in a later release       the only irreversible step

Read it from top to bottom as a sequence in which every state is safe for both the code version before it and the one after it. While both columns are written, the system can return to reading name at any point. The common failure is collapsing the last two states: dropping the column in the same release that stops writing it breaks instances of the previous version still running during a rolling deploy. The illustrative migrations that follow implement the steps.

SQL
-- Migration 1, expand: nullable, so existing inserts that omit it still succeed
ALTER TABLE app_user ADD COLUMN full_name TEXT;

-- Deploy code that writes both columns, then backfill in batches to avoid long locks
UPDATE app_user SET full_name = name
 WHERE full_name IS NULL AND user_id BETWEEN 1 AND 10000;   -- repeat per range; idempotent

-- Migration 2, once backfilled: enforce the rule on the new column
ALTER TABLE app_user ALTER COLUMN full_name SET NOT NULL;

-- Deploy code that reads full_name; later, code that stops writing name

-- Migration 3, contract, in a later release than the one that stopped writing name
ALTER TABLE app_user DROP COLUMN name;

The price is time and temporary complexity: the change spans several releases and doubles the write paths while it runs. The same pattern handles changes of cardinality, such as letting a customer hold several emails, where the expand step creates a customer_email table rather than a column, and it handles moving data between datastores, where the dual write goes to two engines.

Review

Common mistakes

Each mistake below is set out in the same four parts: what goes wrong, why the mistake is easy to make, what to do instead, and the section that explains the fix.

Choosing a datastore before listing the access patterns

What goes wrong
The costs appear only when a query arrives that the store cannot serve. The typical result is a document or wide-column store chosen "for scale", followed by a need for joins and multi-row transactions it does not provide.
Why it happens
A familiar product, or one described as scalable, feels like a safe starting point.
What to do instead
Follow the order of design: entity names, then endpoints, then access patterns, and only then the family, defaulting to relational until a named constraint forces otherwise.

Using a changeable natural key as the primary key

What goes wrong
When a value such as an email address changes, every foreign key referring to it must change in the same transaction, and external systems holding the old value point at nothing.
Why it happens
The value is already unique and saves a column.
What to do instead
Use a surrogate primary key and declare the natural key unique, unless the natural key is system-generated and immutable, like a short code.

Reading a historical value from where the current value lives

What goes wrong
If an order line's price is read from the product table, every past invoice changes when the price list changes.
Why it happens
“Price” looks like one attribute when the domain has two: the product's current list price and the price charged on a past sale.
What to do instead
Store unit_price on the order line, as the dependency analysis shows. This is not denormalisation, because the two prices are different facts.

Checking partition balance by key count rather than traffic

What goes wrong
One key carrying a large share of requests still saturates its shard; in the worked example in “Partitioning and hot keys”, one shard carries 7 times the average load.
Why it happens
Hash partitioning makes key counts even by construction, and the dashboard shows equal shard sizes.
What to do instead
Measure traffic per key, choose a partition key whose traffic spreads, and salt or isolate the keys known to be hot.

Finishing a change before every reader and writer has caught up

What goes wrong
Dropping an old column in the same release that stops writing it breaks instances of the previous version still running during a rolling deploy. Updating a denormalised copy from only some write paths leaves the missed paths producing stale copies.
Why it happens
Both changes look complete from the point of view of the newest code.
What to do instead
Keep the irreversible contract step for a later release, and propagate every denormalised copy through one path.

Exercises

Practice questions

The questions that follow mix recall, calculation and application across the whole guide. Each answer is collapsed beneath its question; open it once you have worked out your own answer.

Question 1 · recall

For each decision about the shop, state whether it belongs to the conceptual, logical or physical model, and whether it is taken at the HLD or the LLD stage.

  1. Every order is placed by exactly one customer.

    Answer

    Conceptual, and HLD: it is a business rule a domain expert can confirm without knowing anything about databases.

  2. Orders are stored in Postgres and partitioned by a hash of customer_id.

    Answer

    Physical, but taken at HLD: the datastore family and partition key shape the architecture, which is why they are taken at the HLD stage although they are physical decisions.

  3. The order table has a covering index on (customer_id, created_at).

    Answer

    Physical, and LLD: it changes how fast a query runs, not what the data means, and it does not change the architecture.

Question 2 · distinction

Distinguish an entity from a value object, and say how each is usually persisted.

Answer

An entity has a stable identity that persists while its attributes change, as an order stays the same order when its status changes; a value object has no identity and is defined by its values, as £40.00 equals any other £40.00. An entity therefore needs a primary key. A value object is usually stored inline, as columns of the entity that owns it or embedded in its document, and is replaced rather than updated.

Question 3 · calculation

A table holds 2,000,000,000 rows. Its B-tree index uses 8,192-byte pages and 20-byte entries. How many levels does the index have, and how many page reads does a single-row lookup need, counting the table page?

Answer

The fanout is 8,192 ÷ 20 = 409.6, so 409 whole entries. Three levels reach 409 × 409 × 409 = 167,281 × 409 = 68,417,929 rows, fewer than 2,000,000,000; four reach 68,417,929 × 409 = 27,982,932,961, more, so the index has 4 levels. As a check, log 2,000,000,000 ÷ log 409 = 9.301 ÷ 2.612 = 3.56, rounded up to 4. A lookup reads 4 index pages and 1 table page, 5 in total.

Question 4 · calculation

A dataset is hash-partitioned across 32 shards, and one key carries 25% of all traffic. What share does the hottest shard carry, relative to the average? What does salting the key with 16 suffixes, landing on 16 different shards, reduce that to?

Answer

The average shard carries 100 ÷ 32 = 3.125%. The other 75% spreads as 75 ÷ 32 = 2.34375% per shard, so the hot shard carries 25 + 2.34375 = 27.34375%, which is 27.34375 ÷ 3.125 = 8.75 times the average. With 16 salts the key adds 25 ÷ 16 = 1.5625% to each of 16 shards, which then carry 1.5625 + 2.34375 = 3.90625%, or 3.90625 ÷ 3.125 = 1.25 times the average. Check: 16 × 3.90625 + 16 × 2.34375 = 62.5 + 37.5 = 100%. Reads of that key now query 16 partitions.

Question 5 · application

A university records enrolment(student_id, student_name, module_code, module_title, lecturer_id, lecturer_name, grade), one row per student per module, and each module has exactly one lecturer. State the dependencies and key, the normal form violated, and a 3NF decomposition.

Answer

The dependencies are student_id → student_name, module_code → module_title, lecturer_id, lecturer_id → lecturer_name and (student_id, module_code) → grade, so the key is (student_id, module_code).

  • The table violates 2NF, because student_name depends only on student_id, and module_title and lecturer_id only on module_code.
  • After removing those, a module table holding lecturer_name would violate 3NF through module_code → lecturer_id → lecturer_name.
  • The 3NF schema is student(student_id, student_name), module(module_code, module_title, lecturer_id), lecturer(lecturer_id, lecturer_name) and enrolment(student_id, module_code, grade); each determinant stays behind as a foreign key, so the decomposition is lossless.

Question 6 · misconception

A colleague proposes a document store "because it is schemaless, so we will never need migrations". What is wrong with the reasoning?

Answer

A document store does not remove the schema; it moves it from the database into every application version that wrote data, an approach called schema-on-read. Old documents keep their old shape, so the code must either handle every shape ever written or the documents must be migrated, and without engine-side constraints nothing reports how many shapes exist. Changing a field still needs expand–migrate–contract, with the backfill rewriting documents instead of rows. If flexible fields are the real need, Postgres JSONB provides them with transactions and constraints.

Question 7 · open-ended, combining subtopics

The shop now sells clothing in sizes and colours, takes payment in euros as well as pounds, and expects one wholesale customer to place 30% of all orders. Describe the changes to the data model, covering entities and relationships, keys, normalisation, indexes, partitioning, and how you would deploy the change.

Answer

A complete answer combines the subtopics as follows.

  • Entities: add product_variant in a one-to-many relationship with product, because size and colour describe the item sold and stock is held per variant; give it a surrogate key and unique constraints on its SKU and on (product_id, size, colour), and make order_line refer to the variant.
  • Normalisation: price now depends on the pair (variant, currency), so add variant_price(variant_id, currency, amount) rather than two price columns; add currency to the order and keep unit_price on the line as the amount charged, a historical fact. Money is a value object, an amount with its currency, stored inline.
  • Indexes: add product_variant(product_id) for the product page, which lists all variants of one product.
  • Partitioning: if orders are sharded by customer_id, the wholesale customer makes one shard hot; salt that customer's key, or give it a dedicated partition, and measure traffic per key rather than key counts.
  • Deployment: use expand–migrate–contract, creating the new tables, backfilling one default variant and one GBP price per product, dual-writing, switching reads, and dropping product.list_price and the old line reference in a later release.

Finish

Review checklist

After studying this guide, you should be able to explain what a data model contains beyond a list of tables and place each decision at the conceptual, logical or physical stage and at HLD or LLD; model a domain as entities, attributes and relationships with cardinality and participation at both ends, resolve a many-to-many relationship into an associative entity, and tell an entity from a value object; derive access patterns from an API surface and use them to justify each storage decision; choose primary and foreign keys and constraints, justify a primary key by its stability, and spot a schema that mixes relational constructs into a key-value design; write a table's functional dependencies, name the anomalies they cause, and decompose it losslessly into 3NF, recognising when BCNF differs; calculate B-tree depth and the pages a query reads with and without an index, including row fetches, and order a composite index's columns; justify a denormalisation or read model by its read and its consistency mechanism; choose a datastore family from its access patterns, consistency needs, access keys and operational costs; calculate the load on the hottest shard and the effect of salting; and plan a schema change with expand–migrate–contract in which only the final step is irreversible. A reader who can do all of these has covered the material.