Skip to content

Core system concepts · Concept lesson

Data modeling

Represent domain facts in durable structures with explicit identity, relationships, constraints, query patterns, and evolution paths.

Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.

Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.

What you will be able to explain

  • Translate domain facts into entities, relationships, and constraints.
  • Evaluate normalization and denormalization against integrity and query needs.
  • Plan a safe additive schema evolution.

How a data model expresses rules

A data model gives names, identities, relationships, and constraints to facts the system must remember. Start by asking what the business considers the same object over time: a person may change an email address but retain identity, while an address itself may be a value rather than an entity. Relational tables represent sets of rows with declared types and keys; foreign keys connect references, and uniqueness or check constraints make invalid combinations harder to store. Normalization separates facts that change independently, reducing anomalies such as updating one customer's address in several order rows. A model also reflects access patterns: indexes and relationship direction affect query cost. The storage model should preserve authoritative facts; response-specific aggregates can be derived or materialized where necessary. Avoid copying a domain diagram mechanically into tables. State the invariants, expected queries, retention needs, and ownership boundaries before choosing structures.

Entities, relationships, and constraints
1. Customer

Stable identity and customer-owned attributes.

2. Order

A durable transaction linked to its customer.

3. Order line

A product, quantity, and historical agreed price.

4. Constraints

Keys and checks reject invalid relationships or values.

  1. Customer → Order: one customer may place orders
  2. Order → Order line: contains line items
  3. Constraints → Customer: identity and uniqueness
  4. Constraints → Order: foreign key and valid state
  5. Constraints → Order line: positive quantity and unique line

Worked example: orders and line items

Suppose a product's current list price is 18 dollars, but the order placed yesterday used a discounted agreed price of 15 dollars. If the line stores only product_id and quantity, a later invoice that joins to today's catalog can silently rewrite the apparent historical amount to 18 dollars. Store the transaction fact, such as unit_price_minor = 1500 cents, with the line; keep the catalog's current price in its own authoritative record. A constraint can require quantity > 0 and unit_price_minor >= 0, while application validation explains the rejection to a user. For a new tax-rate field, do not backfill every old row with today's rate and imply that it was historically charged. Add a nullable or versioned field, deploy writers that capture the effective rate for new orders, determine historical values only from reliable records, and leave unknown history explicitly unknown. Verify row counts and a sample of invoices before requiring the field for new records. This correctness example separates mutable reference data from an immutable transaction fact and shows how a staged migration preserves historical meaning.

Model an order with a stable order_id, customer_id, created_at timestamp, and status; model each line with order_id, product_id, quantity, and the agreed-at unit price. A line quantity must be an integer greater than zero, and an order should not have two identical product lines unless the domain allows it. A unique key on (order_id, product_id) can enforce that rule; a check quantity > 0 protects against invalid writes from any client. Store the historical unit price on the line because current catalog price can change after purchase. If one order has 4 lines and a customer's order page returns 25 orders, a naive separate line query per order can issue 25 + 1 database round trips; a join or bounded batch query may fetch the related lines in fewer trips. That calculation informs access design, but does not justify duplicating every product attribute into every order. Define transaction and ownership rules for the final model.

Modeling alternatives

A normalized relational model is useful when relationships, constraints, and transactions are central. Document databases can store an aggregate as a nested document, making common reads convenient while making cross-document constraints harder. Key-value models fit direct key lookups but require careful key design for queries. Wide-column stores and partitioned databases favor known access patterns and predictable distribution. An event log preserves changes over time, but consumers may need projections to answer current-state queries. These are not interchangeable formats: data size, relationship shape, query patterns, consistency, and operational skills matter. Denormalization can improve a hot read by storing a summary, but then update paths and repair procedures must be explicit. A migration from relational to document storage does not eliminate modeling; it moves constraints and joins into application logic or projection processes. Select structures based on the invariants the system must enforce and the reads it must serve.

Failure and recovery

Poor models produce duplicate facts, nullable ambiguity, orphan references, and expensive migrations. Enforce essential invariants in the datastore as well as at the API boundary, since background jobs and future clients may bypass one validation path. If an additive column is introduced, define a default or nullable phase, backfill in bounded batches, verify, then require it only after all writers populate it. A failed migration should be restartable and should not hold a long table lock unexpectedly. For derived data, preserve a way to rebuild from authoritative records or events. Backups protect against loss but do not correct a logically invalid model. Use checksums or count comparisons when copying data, and define ownership during cutover. If a denormalized value disagrees with its source, document which is authoritative and how to repair the projection without overwriting newer facts.

When not to over-model

Do not create a separate table or service for every noun in a speculative domain diagram. A one-off value with no identity or independent lifecycle may belong as a field or value object. Avoid normalizing so aggressively that a common page requires dozens of remote calls; denormalization can be appropriate when read cost and update semantics are understood. Equally, avoid storing large repeated JSON blobs when the application needs constraints, selective updates, or relational reporting. Do not use a generic entity-attribute-value scheme simply to avoid making schema decisions; it weakens type guarantees and queryability. Model the requirements that exist, preserve plausible extension points, and use migrations to evolve the schema as real behavior emerges. The best model is neither maximally normalized nor maximally flexible; it protects important facts with the least complexity compatible with actual queries and change.

Senior followups

Ask what constitutes identity, which fields are historical facts, and what must be unique at the moment of commit. Is a relationship optional, and can deletion leave audit requirements? Which query patterns drive indexes, and what is their write amplification? How large will the table become at expected retention, and does the model support partitioning later without changing identity semantics? Are data classification, retention, and user deletion requirements represented in lifecycle decisions? If the system is split into services, who owns the authoritative record and how do consumers obtain changes? How will a schema evolve while old and new application versions run simultaneously? For each denormalized field, identify its source, freshness expectation, and repair path. These questions expose the operational lifecycle of stored data, which is often longer than any one service implementation.

Operational practice

Review a schema through real queries and sample volumes. Check query plans, index selectivity, lock duration, and expected write rate before adding an index to a large table. Give columns explicit units and timestamps a clear time-zone convention. Use constraints for durable invariants and application validation for useful user feedback. During migrations, monitor lock waits, replica lag, backfill rate, and error counts. Keep change scripts versioned and repeatable; do not make a production change depend on an undocumented manual edit. Test backup restoration and the rebuild of derived projections. Data-quality checks can count orphan references, invalid states, and unexpected nulls. A model is healthy when teams can explain where each fact is authoritative, how it is queried, and how it is corrected after a bug. The database is part of the architecture contract, not merely a persistence detail.

Terms in plain language

Entity
A domain object with identity that remains meaningful across changes to its attributes.
Normalization
Structuring relational data to reduce unintended duplication and update anomalies.
Constraint
A database-enforced rule that restricts stored values or relationships to valid states.
Denormalization
Deliberately storing derived or repeated data to support access patterns, accepting a consistency cost.

Preparing practice controls…

Check your understanding

These checks explain concepts. They do not measure architecture seniority or update readiness.

1. Why store the agreed unit price on an order line instead of reading only the current catalog price?
2. What is a principal benefit of a database constraint for a key invariant?

Design independently

Design a minimal relational model for a library lending workflow with members, books, copies, and loans. State identities and constraints, describe two key queries, and outline a safe schema evolution for a new due-date policy.

Hints, not a solution
  • Separate a title from a physical copy.
  • A copy should not have two simultaneously active loans.
  • Treat historical policy values differently from current defaults.

0 / 20,000 characters · Not saved

Your learning notes

Sign in to save

Marking a lesson read and reviewing an exercise are separate actions. Neither implies mastery. Saved work is account-owned; saves are explicit and do not queue offline.

References and boundaries

Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.

PostgreSQL Documentation: Constraints

Primary database documentation for keys, checks, and referential constraints.

PostgreSQL Documentation: Data Definition

Primary documentation on relational schema definitions and evolution primitives.

Back to curriculum