Skip to main content

Chapter 16 — Data Modeling as a Discipline

Part IV · Data & Storage | Prerequisites: Ch 15 | Builds: Pulsely modeled end-to-end (conceptual → logical → physical)

Earlier you built the relational machinery: relations as sets, keys, constraints, joins, normalization, and the load-bearing idea that correctness should be a property of the data, not of whichever service happened to write it. That gave you a way to say things to a database engine. This chapter is about deciding what to say — and it's a harder, more consequential skill. The relational grammar you already have lets you form statements; data modeling is the act of authoring sentences that will still be true in three years, under load you can't predict, queried by services that don't exist yet.

Here is the claim this chapter defends: a data model is a theory of your domain, and the database is the place where that theory is enforced. It is the single artifact that outlives every framework migration, every service rewrite, every team reorg. Your Express handlers will be rewritten in NestJS, then in Go, then in something not yet invented; the claims table will be carried, blinking, through all of it, because rewriting data is an order of magnitude more dangerous than rewriting code. That asymmetry is the whole reason modeling deserves to be a deliberate discipline rather than an emergent side-effect of "just add a column." We're going to model Pulsely — a connected-care platform: scheduling, charting, orders, monitoring, and the revenue cycle, all under HIPAA — end-to-end, conceptual, then logical, then physical, and you'll finish with a per-aggregate storage decision recorded in an ADR you could defend in a design review.

This is a design-heavy chapter. There's real DDL, but the load-bearing content is the reasoning that precedes the DDL. Slow down on the mental model.


1. The problem: schemas rot when nobody is modeling​

Let me show you two failures, because they're the two halves of this chapter and you've probably already lived one of them.

The 41-column patient. Pulsely's patients table was clean on day one: id, mrn, full_name, date_of_birth. Beautiful. Then intake needed a referral source, so someone added referral_source. Then billing arrived and bolted on insurance_member_id, legacy_coverage_json, plan_tier, plan_tier_v2 (because the first coverage-tier scheme was wrong and nobody dared drop the column). Then the patient portal wanted contact preferences, so in went notif_pref_blob — a stringified JSON object the app parses by hand. Then a half-finished address feature left address_2 stranded, NULL in 99% of rows. Eighteen months later the table has 41 columns, most nullable, and when a new engineer asks "what is a patient in this system?" nobody can answer without reading three services and a Slack thread. The schema stopped being a model of anything. It became a junk drawer with a primary key — and a junk drawer full of PHI is a compliance problem on top of a design one.

Nothing here was a single bad decision. Each addition was locally reasonable — a five-minute migration, an ORM field, ship it. The rot is emergent: it's what you get when you make a hundred local "add a field" decisions and never once make a global "what is this entity, and what is it allowed to be" decision. Modeling is the practice of making that global decision on purpose, and re-making it deliberately as the domain genuinely changes.

The 2 a.m. orphan. Different failure, same root. Pulsely let billing staff hard-delete rows from the service catalog — the fee-schedule entries that map a billable service to a CPT code and a charge amount. Reasonable: a procedure is retired, the row goes. But claim_line_items had a foreign key service_id → billable_services.id. One night a biller deleted a service that three already-submitted claims pointed at. With ON DELETE RESTRICT the delete would have failed; someone had set ON DELETE CASCADE "to keep things tidy," so the delete quietly took the claims' line references with it — and now the claim-detail page throws a 500 because it joins to a service that no longer exists, RCM can't reconcile the month's billing, and a payer that just remitted $400 against a claim is looking at a line item that references nothing. The model never decided a fundamental question: is a service-catalog entry live configuration, or is it immutable history the moment a claim captures it? Those are different things, and a schema that conflates them will eventually contradict itself at the worst possible hour.

🧭 The cost curve is backwards from your intuition. Code is cheapest to change early and gets more expensive as it accretes callers. Data models are worse: they get more expensive to change exactly as they get more valuable — because by the time the model matters, there are millions of rows in production shape, a dozen services reading it, and a migration means coordinating a live rewrite of the most important asset you own. The model you ship in month two is the constraint you fight in year two. That's not a reason to over-engineer; it's a reason to think before you CREATE TABLE.

Why does modeling get skipped? Because the tooling makes the deferral invisible. ORMs make "add a field" feel free — one annotation, one auto-generated migration, done. Migrations feel reversible, so the stakes feel low. And the cost is deferred and silent: it doesn't show up as an error, it shows up two years later as a 7-join worklist query that falls off a latency cliff, or a delete that destroys billing history, or a patients table nobody understands. The bill always arrives; modeling is paying a small, legible cost now instead of a large, mysterious one later.

So the thesis, stated as a promise this chapter pays off: a model designed deliberately — from domain intent, through normalized structure, down to physical layout chosen for actual access patterns — encodes your business invariants in the one layer that enforces them and survives years of change. A model that accretes does neither. The difference is entirely method, and the method is what follows.


2. The mental model: three altitudes and an aggregate​

Hold two pictures. The first is a descent; the second is a unit of design.

Three altitudes​

Modeling happens at three altitudes, and the cardinal sin is skipping one and landing in the wrong place:

CONCEPTUAL what things exist and how they relate, in the language of
(domain) the business. No tables, no engine. "A provider offers many
appointment slots. A claim is for one encounter, billed to
one patient."
│ derive ▼
LOGICAL entities, attributes, keys, relationships, fully normalized.
(model) Still engine-neutral. "appointment_slots(id, provider_id FK,
starts_at, status...); claims(id, patient_id FK, encounter_id
FK...)."
│ derive ▼
PHYSICAL tables/collections, column types, indexes, partitioning,
(schema) embed-vs-reference — engine-specific and access-driven.
"Postgres BIGINT identity PK, snapshot CPT + charge data into
claim line items, partial index WHERE deleted_at IS NULL."

Each level is derived from the one above. Conceptual is about meaning. Logical is about structure that removes redundancy. Physical is about serving the actual queries at acceptable cost on a specific engine. When you jump straight from "we need claims" to CREATE TABLE claims, you've made conceptual and logical decisions implicitly and badly — you've decided what a claim relates to and how it's normalized without ever examining those choices. The altitudes exist to force each decision into the open where you can argue about it.

🧭 Mental model. Conceptual asks "what is true about the world?" Logical asks "what is the minimal, non-redundant structure that represents those truths?" Physical asks "given how this data is actually read and written, how do I lay it out so the engine serves it fast without losing the truths above?" You descend. You never start at the bottom and hope the top is implied.

The model is a contract over the whole lifecycle​

A beginner models the row that exists right now: a patient who's registered, a slot that's open, a claim that's been submitted. A senior models every state the entity will ever reach. A patient is active, then maybe inactive, then merged (a duplicate MRN reconciled into one chart), then maybe purged for right-to-erasure. A claim is drafted, then submitted (an 837 to the clearinghouse), then adjudicated, then paid or denied, then — and this is the part the 2 a.m. incident missed — referenced forever by billing history even after the underlying service is retired. The model isn't a snapshot of valid data; it's a contract that must hold for every state in the entity's life. If your schema can represent a state the business should never be in — a claim that's both paid and never submitted, a chart with no owning patient — that's a bug waiting for traffic.

Shape follows access​

Here is the idea that separates modeling-as-tidiness from modeling-as-engineering. The conceptual model is access-neutral — it states what's true regardless of how you query it. But the physical model is owed to the queries. You do not design tables for abstract elegance; you design them for how the data is actually read and written. A provider's worklist is read thousands of times for every time an encounter is charted, so the worklist's physical shape is whatever makes that read cheap. An audit log is written constantly and read almost never, so its shape is whatever makes appends cheap and damn the read ergonomics. "Query-first design" means: enumerate the access patterns before you write DDL, and treat the physical model as the answer to them.

The aggregate boundary is the unit of design​

The single most useful concept in this chapter — more useful, day to day, than the normal forms — is the aggregate: a cluster of data that changes together, is read together, and has exactly one consistency owner. A claim plus its line items is an aggregate: you create them in one transaction, you read them as a unit on the claim page, and the claim is the boss of its line items. A patient and their thousands of encounters are not one aggregate: encounters are charted independently, read independently (a provider's worklist pulls encounters across many patients), and an encounter's lifecycle isn't owned by the patient row.

The aggregate boundary, more than any normalization rule, is what decides whether two things live together (embed, or a tightly-coupled table pair) or apart (reference across a clean boundary). When we get to embed-vs-reference in §3 and §4, the question underneath every decision will be: are these the same aggregate?

🔑 The aggregate invariant. Data inside one aggregate can be made consistent in a single atomic write. Data across aggregate boundaries cannot be assumed consistent at any instant — only eventually, meaning the copies catch up after a short delay. (This is the same shape as an optimistic UI update in React Query: the screen shows the new value instantly, then reconciles with the server on the next refetch. For a moment the two disagree, then they agree.) So the line you draw around an aggregate is the line inside which the database keeps everything in lock-step for you, for free — and outside which you've signed up to do the catching-up yourself: some piece of your own code (a background job, a database trigger, or a multi-step workflow — we'll name that pattern in a later chapter) has to reconcile the copies. Draw aggregate boundaries where your transactional needs are, not where the diagram looks neat.

Finally, the framing that defuses the holy war you'll inherit:

🧭 Normalization and denormalization are not good and evil. They are two settings on one dial. Normalized means every fact lives in exactly one place — correct by construction, cheap to write, sometimes expensive to read because the truth is scattered across tables you must join. Denormalized means you've copied a fact to where it's read — cheap to read, but now you own a consistency obligation forever. The discipline is not "always normalize" or "denormalize for speed." It's: choose the setting per aggregate, deliberately, with the consistency cost named and assigned an owner. A senior engineer can tell you, for every denormalized field in their schema, what the source of truth is and what keeps the copy fresh. If you can't answer that, the denormalization is a bug you haven't been billed for yet.


3. Theory & invariants​

A mental model tells you how to think. The theory tells you the precise vocabulary and the rules that don't bend. Most of this you can derive rather than memorize, and we will.

ER vocabulary, precisely​

Entity-relationship modeling is the conceptual/logical language. Used loosely it's hand-waving; used precisely it's a design tool. The pieces:

  • Entity type vs entity. An entity type is Patient; an entity is the patient with MRN A-4471. You model types.
  • Attributes come in flavors that matter: simple (email), composite (an address that decomposes into street/city/zip), derived (age, computable from date_of_birth — a flag that it probably shouldn't be stored), and multivalued (a patient's phone_numbers, or an encounter's diagnoses — a flag that it probably needs its own table, because multivalued attributes violate 1NF).
  • Identifier / candidate key vs primary key. The conceptual identifier is whatever uniquely names the entity in the domain (a patient's MRN within a clinic). The primary key is the one you choose to enforce identity with — often a surrogate, as we'll argue.
  • Relationship. A named association between entity types: a Provider offers AppointmentSlots; a Patient is billed for Claims.
  • Participation: total vs partial. Does every instance participate? Every claim_line_item belongs to some claim (total participation — a line item cannot exist without a claim). Not every patient has a claim (partial). Total participation becomes a NOT NULL foreign key; partial allows the absence.
  • Cardinality: 1:1, 1:N, M:N. A slot has one provider, a provider has many slots (1:N). An encounter can carry many diagnoses and an ICD-10 code can appear on many encounters (M:N).

🔑 Every M:N resolves to a junction entity. A relational table cannot directly express "many-to-many" — there's no column shape for it. An M:N relationship always becomes a third table, the junction (or associative) entity, whose rows are the pairings: encounter_diagnoses(encounter_id, icd10_code) with a composite primary key (encounter_id, icd10_code) and a foreign key to each side. This isn't a workaround; it's the model telling you the relationship was itself an entity worth naming. Often the junction grows attributes of its own (when the diagnosis was coded, by whom, whether it's primary or secondary) — proof it was always a thing, not just a link.

🏭 Code systems are first-class reference data. ICD-10 (diagnoses), CPT/HCPCS (procedures), LOINC (lab observations), RxNorm (medications), SNOMED (clinical terms) are the domain's shared vocabularies. In the model they are reference tables keyed by the code itself — icd10_codes(code PK, description, ...), cpt_codes(code PK, description, ...). A note doesn't store diagnoses as a comma-separated string (that violates 1NF); it links to the code table through a junction. The code is a rare, legitimate natural key: stable, externally defined, and meaningful — one of the few places you don't reach for a surrogate. Treat these tables as slowly-changing, versioned reference data you load from an authority, not something clinicians type freehand.

Weak entities​

A weak entity has no independent identity — it exists only inside the context of an owner, and its key is partial (unique only within the owner). A Pulsely claim_line_item is the canonical example: line item "row 2" means nothing globally; it's "row 2 of claim 8841." Its full identity is (claim_id, line_no). Weak entities are existence-dependent — kill the claim and the line items are meaningless — and that dependency is the single strongest signal in the whole chapter that a thing should be embedded or tightly coupled rather than referenced across a boundary. A weak entity is almost always part of its owner's aggregate.

STRONG entity WEAK entity
┌──────────┐ owns ┌────────────────────────┐
│ Claim │────────▶│ ClaimLineItem │
│ (id PK) │ 1 N │ (claim_id, line_no) │ ← partial key;
└──────────┘ │ existence-dependent │ identity borrowed
└────────────────────────┘ from the owner

Normal forms, derived from one idea​

You've already seen the formal definitions; here's the one idea they all express so you never have to memorize them again: a fact should live in exactly one place. Run that idea forward and the normal forms fall out:

  • 1NF — atomic values, no repeating groups. diagnoses = 'E11.9,I10,Z79.4' stores three facts in one cell; you can't query, join, or constrain them. The fix (a junction table to the ICD-10 code list) is just "give each fact its own row."
  • 2NF — no non-key attribute depends on only part of a composite key. If a fact depends on half the key, it's being repeated for every value of the other half. Move it.
  • 3NF / BCNF — the intuition first: if one non-key column decides another (an icd10_code tells you its description), then the description is really a fact about the code, not about this encounter row — so store it once, in a table keyed by the code, and reference it. (The formal names for this rule are 3NF and BCNF; the piece of jargon is a transitive dependency — a non-key column determined by another non-key column instead of by the key.)

Each form removes redundancy, and redundancy is just "a fact in more than one place," which is exactly the condition for the three anomalies:

🔑 The three anomalies are the invariants normalization buys you. Update anomaly: a fact stored in N rows must be changed in N places, and the run that misses one leaves the database self-contradictory (an ICD-10 description spelled two ways). Insertion anomaly: you can't record a fact without inventing an unrelated parent fact ("can't add a payer until some claim uses it"). Deletion anomaly: deleting a row destroys an unrelated fact that happened to ride along in it ("delete the last claim for a payer and the payer's address vanishes"). Normalization is not aesthetic. It is the structural guarantee that these three classes of corruption are impossible, because there's only ever one copy to get wrong.

Deliberate denormalization is a controlled violation​

When you denormalize, you are deliberately reintroducing redundancy — copying a fact to where it's cheaply read. An observation_count on an encounter is a denormalization: the true count is SELECT COUNT(*) FROM observations WHERE encounter_id = ?, but recomputing that every time a worklist renders is brutal, so you cache it in encounters.observation_count. The instant you do that, you've taken on an obligation: the copy and the source can drift, and something must keep them in sync. That something must be named and owned — a database trigger, an application-layer write inside the same transaction, or an async job. Denormalization without a named consistency mechanism isn't an optimization; it's a scheduled outage.

📎 Borrowed on credit: deriving indexes from access patterns. Several times below we'll say "this read path is hot, so the physical model bends toward it." The specific tool that makes a read path cheap without denormalizing — an index — is named here but not built. Why it matters now: knowing an index exists changes some modeling decisions (you might not denormalize because an index on the normalized table is enough). The full treatment of how an engine uses an index, and how to derive index shape from selectivity and access pattern, is Ch 18 and Ch 19. For now: assume a well-chosen index can make a single-table filtered read fast, and let that temper your urge to copy data.

Query-first / access-pattern-driven design​

The structured version of "shape follows access": before any DDL, you write down the access patterns. For each one — what's the entry point (which key am I starting from), what cardinality comes back, how frequent is it, what's the latency budget, how fresh must it be? That inventory is the design input. A read that's 10,000×/second with a 20 ms budget that starts from mrn and must be strongly consistent dictates a very different physical model than a report that runs nightly, starts from a date range, returns a million rows, and tolerates being an hour stale. You can't design the model until you've written the queries it serves, even informally.

Temporal invariants: two clocks​

Modeling time trips up nearly everyone because there are two different clocks and people conflate them:

  • Valid time — when the fact was true in the world. "This CPT code's charge was $50 from Jan 1 to Mar 3." "This patient's coverage was active from Jan 1."
  • Transaction time — when the database knew it. "We recorded the $50 charge on Jan 1 at 14:22, and recorded the change to $60 on Mar 3 at 09:10."

They differ constantly: you back-date a correction (valid time in the past, transaction time now), or you learn about a coverage change late. Three increasingly strong points sit on the history axis: soft delete (just remember that something was removed, via deleted_at), audit log (remember what changed and when the DB learned it — transaction time), and full temporal tables (remember what was true when, in the world — valid time, the strongest and most expensive). Pick the weakest one that satisfies the actual requirement; each step up costs storage, query complexity, and a permanent "remember the filter" tax. In healthcare the middle rung is not optional — the audit log is a compliance requirement, and we'll treat it as first-class in §4 and §8.

Relational vs document: what each guarantees, and what each makes expensive​

This is the modeling tradeoff this chapter introduces, so state it precisely and symmetrically:

  • Relational guarantees row-level normalization, cross-entity joins, and engine-enforced referential integrity. It makes the multi-entity, ad-hoc, join-heavy query cheap. It makes assembling one logical object scattered across five tables relatively expensive (you join).
  • Document guarantees co-located reads (the whole aggregate in one fetch) and atomic single-document writes. It makes "give me this entire claim with its line items in one read" cheap and atomic. It makes "join claims to patients to services to compute a cross-cutting RCM report," and "enforce that every service_id references a real service," expensive or impossible — the engine doesn't do referential integrity or joins for you.

🔑 They are mirror images: each makes the other's easy operation hard. Relational nails the cross-entity join and the integrity constraint and pays on aggregate assembly. Document nails aggregate assembly and atomic aggregate writes and pays on cross-entity queries and integrity. This is why "one database paradigm for the whole app" is a non-answer: different aggregates have different shapes. The discipline is to match each aggregate to the store whose guarantee aligns with that aggregate's dominant access — and we'll do exactly that for Pulsely in §5 and the ADR.

🛑 What we deliberately did not explain. The patterns of document modeling — when to embed vs reference inside Mongo specifically, the bucket pattern (ideal for the RPM vitals firehose), the subset pattern, the computed/extended-reference patterns — are not here. This chapter introduces the relational-vs-document tradeoff and the aggregate-driven embed-vs-reference principle; the document-store craft that operationalizes them is Ch 20. Migration mechanics (how to run an expand/contract safely against a live table) are named in §5 but built in Ch 19 and Ch 38. We're drawing the boundaries here; the neighboring chapters furnish the rooms.


4. Under the hood: turning the model into bytes​

Now we descend to the physical altitude and actually translate. Postgres is the primary lane; Mongo and JPA appear where the contrast teaches something a single engine can't.

From logical to physical in Postgres​

Entities become tables. Each gets a surrogate primary key — an engine-generated identifier with no business meaning — and the natural key (MRN, code) becomes a UNIQUE constraint so the engine still enforces business uniqueness without making it the identity. The choice of surrogate type matters more than beginners expect:

-- bigint identity: 8 bytes, monotonically increasing, perfect index locality.
-- In plain terms: monotonically increasing means each new id is bigger than the
-- last, so new rows pile up neatly at one end of the index instead of scattering
-- through it — which keeps inserts cheap. (The B-tree / hot-pages machinery behind
-- that is Ch 18; take it on faith for now.)
-- Downside: sequential and guessable — never expose it in a URL (see §8; for PHI
-- that's not a nuisance, it's a breach vector).
CREATE TABLE patients (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
org_id BIGINT NOT NULL, -- tenant: MRN is unique *within* an org
mrn TEXT NOT NULL, -- medical record number (natural key)
email CITEXT,
full_name TEXT NOT NULL,
date_of_birth DATE NOT NULL,
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active','inactive','merged','deceased')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ, -- NULL = live (soft delete)
CONSTRAINT patients_mrn_unique UNIQUE (org_id, mrn)
);

A 1:N relationship becomes a foreign key on the many side, and participation drives nullability: total participation (the child cannot exist without the parent) is a NOT NULL FK; partial participation allows NULL. The ON DELETE action encodes your lifecycle decision — and as the 2 a.m. incident proved, this is a modeling choice, not a default to copy:

CREATE TABLE appointment_slots (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
provider_id BIGINT NOT NULL -- total participation
REFERENCES providers(id) ON DELETE RESTRICT,
starts_at TIMESTAMPTZ NOT NULL,
duration_min INT NOT NULL CHECK (duration_min > 0),
status TEXT NOT NULL DEFAULT 'open' -- finite inventory: one booking only
CHECK (status IN ('open','held','booked','cancelled')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
CONSTRAINT slot_no_overlap UNIQUE (provider_id, starts_at) -- no two slots at one instant
);

An M:N becomes a junction table with a composite primary key — which simultaneously is the relationship and prevents duplicate pairings for free. Here the "many" side on the right is a code-system reference table:

CREATE TABLE encounter_diagnoses (
encounter_id BIGINT NOT NULL REFERENCES encounters(id) ON DELETE CASCADE,
icd10_code TEXT NOT NULL REFERENCES icd10_codes(code) ON DELETE RESTRICT,
is_primary BOOLEAN NOT NULL DEFAULT false, -- the junction grew an attribute
coded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (encounter_id, icd10_code)
);

Note the asymmetric cascade: deleting an encounter should remove its diagnosis links (CASCADE — the links are meaningless without the encounter), but deleting an ICD-10 code should be blocked if encounters still reference it (RESTRICT — you never quietly rewrite coded history). That asymmetry is the lifecycle theory, written in DDL.

Embedding the same aggregate in a document store​

Now the contrast. A claim plus its line items is one aggregate (§2): created together, read together, owned by the claim. In Postgres that's two tables joined on read. In a document store it's one document, and the difference is instructive:

// Mongo: the whole aggregate in one document — one atomic write, one read, no join.
{
_id: ObjectId("..."),
patientId: 42,
encounterId: 9001,
status: "submitted", // 837 sent to the clearinghouse
submittedAt: ISODate("2026-06-19T10:00:00Z"),
lineItems: [ // the weak entity, embedded
{ cptCode: "99213",
descriptionSnapshot: "Office visit, established patient, low complexity",
chargeAmountCentsSnapshot: 40000, units: 1 }
],
totalChargeCents: 40000
}

The relational equivalent reads the claim, then joins claim_line_items:

SELECT c.*, li.*
FROM claims c
JOIN claim_line_items li ON li.claim_id = c.id
WHERE c.id = $1;

Both are correct. The document version makes "fetch this whole claim" one read and makes creating the claim-with-lines a single atomic write (no transaction spanning two tables). The relational version makes "find all claims that billed CPT 99213 across all patients" a trivial indexed query, while in the document store that's an awkward scan into nested arrays. Same aggregate, opposite ergonomics — exactly the mirror-image tradeoff from §3.

The test that decides embed vs reference​

Embed when ALL are true: Reference when ANY is true:
───────────────────────── ─────────────────────────────
• owned (one consistency • shared (read by many parents,
owner, part of the aggregate) or independently)
• bounded (can't grow without • unbounded (grows forever —
limit) a patient's encounters, an audit log)
• read together with parent • queried independently of parent
• written atomically with it • huge (would bloat the parent doc)

Apply it: a claim's line items are owned, bounded (a claim has a handful of lines), read with the claim, written with it → embed. A patient's encounters are not owned by the patient aggregate, grow without bound over a lifetime of care, are read independently (the worklist pulls encounters across patients), and would blow past document size limits → reference, always. Embedding patient.encounters[] is the single most common document-modeling disaster: every new visit rewrites the entire patient document, the document eventually hits the engine's size cap (16 MB in Mongo), and a read that only wanted the patient's name now drags their entire clinical history off disk — a performance and a minimum-necessary-access problem.

The modeling layer in Node/TS — and where it lies to you​

ORMs express these decisions, but they also paper over them, and a senior engineer knows where the paper is thin:

// Prisma: the relation is declared, but the ORM's conveniences hide costs.
model Claim {
id BigInt @id @default(autoincrement())
patientId BigInt
patient Patient @relation(fields: [patientId], references: [id])
lineItems ClaimLineItem[] // a "relation" — lazy access here = N+1 hazard
status ClaimStatus
}

Three honest cautions:

  • Lazy relations hide N+1. claim.lineItems looks like a field; accessing it per-claim in a loop fires one query per claim. The model didn't change, but the access pattern silently did. (The cure — eager loading / batching — is real, but you have to know to apply it.)
  • @unique is not a composite constraint. A field-level uniqueness annotation won't enforce "unique combination of (encounter_id, icd10_code)"; you need a real composite constraint in the migration, and ORMs vary in whether they generate it.
  • Soft delete is not free. A deleted_at column means every query must add WHERE deleted_at IS NULL or it leaks dead rows. Most ORMs won't enforce this globally by default; the one forgotten filter is a data-leak or a correctness bug — and when the leaked row is a merged patient's chart, it's a reportable one. (We make this safer with a partial index and a discipline below.)

Java/Spring contrast, where it genuinely teaches​

JPA forces the embed-vs-reference decision into the type system in a way that's clarifying. @Entity means "this is an aggregate root with its own identity and lifecycle"; @Embeddable / @ElementCollection means "this is a value object that lives inside its owner and has no independent identity." Writing @Embeddable ClaimLineItem is declaring "line item is a weak entity inside the claim aggregate" — the framework makes you say it explicitly:

@Entity
class Claim {
@Id @GeneratedValue Long id;
@ElementCollection // embedded, owned, no independent identity
List<ClaimLineItem> lineItems; // == the weak-entity / aggregate decision, as a type
}

@Embeddable
class ClaimLineItem { // a value object: identity is the owner's
String cptCode;
long chargeAmountCentsSnapshot;
int units;
}

Hibernate's identity-and-equality contract also forces you to confront natural-vs-surrogate keys earlier than a TS developer usually does — you can't write equals()/hashCode() for an entity without deciding what makes two instances "the same," which is exactly the key question. Earlier you saw the runtime contrast between the two ecosystems; this is the modeling contrast — the JVM world's value-object-vs-entity distinction is a genuinely transferable lesson, whatever language you write in.

Denormalization plumbing: three ways to keep a copy fresh​

Recall the obligation from §3. Implementing encounter.observation_count (each observation is a vital sign or result recorded during the visit) makes the three mechanisms concrete, each with a different cost:

-- (1) Synchronous, same transaction: zero staleness, but write amplification on the
-- hot row — every new observation now also writes the same counter row, so one
-- clinical action becomes two writes hammering one row.
BEGIN;
INSERT INTO observations (encounter_id, loinc_code, value) VALUES ($1, $2, $3);
UPDATE encounters SET observation_count = observation_count + 1 WHERE id = $1;
COMMIT;

-- (2) Trigger: the DB enforces the invariant; logic hidden in the engine, still a hot-row write.
CREATE TRIGGER bump_obs_count AFTER INSERT ON observations
FOR EACH ROW EXECUTE FUNCTION increment_encounter_obs_count();

-- (3) Async (outbox/event): the observation write returns instantly; a consumer
-- (a background worker reading a queue of change-events — the "outbox" pattern)
-- updates the counter a moment later. Lowest write latency, but the count is
-- briefly stale (eventual).

Synchronous trades write latency and hot-row contention for zero staleness. Trigger moves the same work into the engine (good for "every writer is covered," bad for "the logic is now invisible in the app"). Async buys the cheapest, fastest write at the cost of a staleness window — fine for an observation count on a busy monitoring feed, not fine for a paid-claim balance. The point isn't which is best; it's that the choice is a real engineering decision with a named cost, recorded next to the column.

Modeling time concretely — including the HIPAA audit​

-- Soft delete: a nullable timestamp + a PARTIAL index so live-row queries stay fast
-- and only ever scan the live set.
ALTER TABLE appointment_slots ADD COLUMN deleted_at TIMESTAMPTZ;
CREATE INDEX slots_active_idx ON appointment_slots (provider_id, starts_at)
WHERE deleted_at IS NULL; -- the index itself excludes dead rows

-- Audit log: append-only, transaction-time history. Never updated, only inserted.
CREATE TABLE encounter_audit (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
encounter_id BIGINT NOT NULL,
changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
changed_by BIGINT, -- which provider/staff account
old_row JSONB,
new_row JSONB
);

-- HIPAA access audit: in healthcare you log READS, not just writes. Every time a chart
-- is *viewed*, that view is a recorded event — this is a compliance requirement, and it
-- answers "who looked at this patient's record, and when?" Append-only, tamper-evident.
CREATE TABLE chart_access_audit (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
patient_id BIGINT NOT NULL,
accessed_by BIGINT NOT NULL, -- the viewing account
accessed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
access_type TEXT NOT NULL, -- 'view' | 'export' | 'break_glass'
justification TEXT -- required for break-glass / emergency access
);

-- Valid-time history: separate _history rows with [valid_from, valid_to) so you can ask
-- "what was the charge for CPT 99213 on the service date?" — the strongest, most expensive
-- option, and exactly what RCM needs to defend a claim against a later fee-schedule edit.
CREATE TABLE service_charge_history (
service_id BIGINT NOT NULL REFERENCES billable_services(id),
charge_cents BIGINT NOT NULL,
valid_from TIMESTAMPTZ NOT NULL,
valid_to TIMESTAMPTZ, -- NULL = currently in effect
PRIMARY KEY (service_id, valid_from)
);

Pick the weakest that meets the requirement. Soft delete answers "is it gone?". The audit tables answer "who changed or viewed what, and when did we record it?" — and in healthcare the read audit is non-negotiable. Valid-time history answers "what was true in the world at time T?" — only pay for that where the business (or a payer's appeal, or a compliance reconstruction) genuinely needs to replay the past.


5. In production: modeling Pulsely end-to-end​

This is the chapter's center of gravity: a real model, built the disciplined way, with the per-aggregate decisions a senior engineer would actually defend.

Step 1 — The conceptual ER model​

Before a single table, name the entities and their relationships in domain language:

┌──────────┐ offers ┌────────────────┐ ┌─────────┐ billed to ┌──────────┐
│ Provider │1──────N │ AppointmentSlot│ │ Claim │N─────────1│ Patient │
│ │ │ (finite inv.) │ │ │ │ │
└────┬─────┘ └────────────────┘ └────┬────┘ └────┬─────┘
│1 documents N │1 owns N │1 has N
┌────┴──────┐ M N ┌───────────┐ ┌──────┴────────┐ ┌─────┴──────┐
│ Encounter │─────────│ ICD-10 code│ │ ClaimLineItem │ │ Encounter │
└────┬──────┘ enc_dx └───────────┘ │(claim_id,line) │ │ (see left) │
│ appears in (denormalized projection) └────────────────┘ └────────────┘
┌────┴──────┐ ┌───────────────┐ ┌────────────┐ ↑ WEAK entity
│ Timeline/ │ │ Alert │ │ Search │
│ Worklist │ │(append-only, │ │(derived │
│(projection) │ per-provider) │ │ index) │
└───────────┘ └───────────────┘ └────────────┘

Read off the structure: Provider and Patient are distinct roles (documenting vs receiving care) — a hint that role/identity is relational, split by RBAC, not one duplicated entity. AppointmentSlot is finite inventory offered by one provider (the seed of the no-double-booking problem). Claim is billed to one patient, owns many line items (the weak entity). Encounter↔ICD-10 is M:N (junction). Timeline/Worklist, Alert, and Search are flagged in the diagram as derived/projection, not sources of truth — a conceptual decision that will save us in §6.

Step 2 — The access-pattern inventory​

Now, before finalizing physical shape, the query table. This artifact lives in the repo next to the schema; it's the design input, not documentation-after-the-fact.

#Access patternEntry keyCardinalityFreqp99 budgetConsistency
1Look up patient by MRNmrn1high20 msstrong
2Render worklist / chart timeline for providerprovider_id~30very high50 msseconds-stale OK
3Encounter detail w/ observation & result countsencounter_id1high30 msseconds-stale OK
4Search open slots by provider + dateprovider_id, date~50high100 msseconds-stale OK
5Claim detail (with line items)claim_id1medium40 msstrong
6Patient's claim / billing historypatient_id~50medium80 msstrong
7Book appointment slot (claim finite slot, write appt)slot_id1 writemedium200 msstrong
8Acknowledge critical-value alertsprovider_idN writeshigh50 msstrong

Read it like a senior would: pattern 2 (worklist) is very high frequency and tolerates staleness → a denormalized read-optimized projection is justified. Pattern 3's counts are read constantly and tolerate seconds of lag → denormalized counters are justified. Pattern 1 demands a fast lookup by MRN → an index, not a denormalization. Pattern 7 is the sharp one: a strong-consistency write against finite inventory — booking a slot that must never be double-booked. It's one of three distinct concurrency problems Pulsely faces, and they're worth naming here because the model must leave room for all three:

  • No double-booking — a finite appointment slot claimed by exactly one booking (a slot lock, or a UNIQUE constraint that makes the second booking fail).
  • Exactly-once claim submission — never dual-submit the same 837 to the clearinghouse (an outbox/idempotency key, not two writers racing).
  • Concurrent charting — two clinicians editing one note without silently clobbering each other (optimistic locking + note versioning + co-sign).

All three are the subject of Ch 17; the modeling job now is to shape the tables so those solutions are possible (a slot has a status and a uniqueness constraint; a claim carries a submission idempotency key; a note carries a version column). The inventory told us where to bend the model.

Step 3 — Per-aggregate physical decisions​

Now decide each aggregate against the principles, and record why:

  • Patients → relational, normalized. Heavily referenced (every encounter, claim, appointment, observation FKs to it), integrity-critical, queried ad-hoc many ways, and PHI-governed. This is exactly the shape relational guarantees. No embedding; references in, references out.

  • Encounters + Timeline/Worklist → reference, with denormalized counters and a read-optimized projection. Encounters reference patients (unbounded over a care lifetime, independently read — never embed in the patient). observation_count/result_count are denormalized onto encounters (consistency owner: async aggregation, seconds-stale per the inventory). The worklist/timeline is a separate read-optimized projection (a per-provider precomputed list, or a materialized view) — derived from encounters, never the source of truth. This is the cure for the 7-join worklist problem before it happens. The RPM vitals firehose (device readings streaming in continuously) is the extreme case: a high-write, high-read denormalized store best served by a document engine's bucket pattern — that's Ch 20's territory, but the modeling rule is the same: it's a projection, not the clinical source of truth.

  • Appointment slots + Claims → relational, with claims capturing an immutable snapshot. This is the decision the 2 a.m. incident demanded. A claim line does not hold a live foreign key to the service's current CPT and charge; it holds a snapshot of them as they were on the service date:

    CREATE TABLE claim_line_items (
    claim_id BIGINT NOT NULL REFERENCES claims(id) ON DELETE RESTRICT,
    line_no INT NOT NULL,
    service_id BIGINT, -- nullable ref: provenance, may be retired
    cpt_code_snapshot TEXT NOT NULL, -- frozen at service date
    description_snapshot TEXT NOT NULL, -- frozen at service date
    charge_amount_cents_snapshot BIGINT NOT NULL, -- frozen at service date
    units INT NOT NULL CHECK (units > 0),
    PRIMARY KEY (claim_id, line_no) -- weak entity: composite key
    );

    Now a biller can retire a service from the catalog and the month's billing stays reconcilable, because the claim is the historical record — it captured what was actually billed, at the charge in effect on the service date. The live catalog and the claim's view of it are correctly decoupled. (Line items are embedded-in-spirit: weak entity, composite key, ON DELETE RESTRICT so a claim can't be orphaned.) This is the same snapshot invariant an encounter note relies on — it captures the patient's demographics, coverage, and coded diagnoses as of the visit, immune to later chart edits.

  • Alerts → append-only, document-friendly. Written constantly (critical values, result-ready, appointment reminders, task assignments), read as a per-provider list, rarely updated except an acknowledged_at flag. Append-only relational table, or a document store if the payload shapes vary wildly by alert type. Partition/retain from day one (it grows forever — see §8).

  • Search → derived projection, never the source of truth. Patient search (exact mrn/date_of_birth match plus full-text on name) and clinical search are built from the relational tables, and every result must be access-scoped — a clinician sees only patients within their care relationship, so search filters by permission before it returns a row. If the index disagrees with the relational tables, the relational tables win. Eligibility responses (the 271 you get back after a 270 check) are cached in Redis with a short TTL — a derived, expiring copy, never the billing truth. Ch 22 builds the search infrastructure; the modeling rule is just: search is a copy, and a copy of PHI is still PHI.

Step 4 — Schema evolution as routine, not event​

The model will change; the discipline is changing it without locking the table and praying. The pattern is expand/contract (a.k.a. parallel change): make additive changes first, backfill, switch reads, then remove the old shape — never a single destructive ALTER:

1. EXPAND add the new nullable column / new table (additive, no lock pain)
2. BACKFILL populate it in batches; dual-write from the app
3. MIGRATE switch reads to the new shape; verify
4. CONTRACT enforce NOT NULL / drop the old column (destructive, last)

Every model change ships with a forward migration and a tested rollback path. The naive ALTER TABLE ... ADD COLUMN NOT NULL DEFAULT ... that rewrites a live 50M-row claims table under a lock is how you turn a "small schema change" into an outage — and an outage on a clinical system is a patient-safety event, not just a bad afternoon. The mechanics of doing this safely against Postgres — concurrent index builds, lock-timeout discipline — are Ch 19; operationalizing migrations in a deploy pipeline is Ch 38. The discipline — additive-first, destructive-last, every change reversible — is a modeling concern and it's yours now.

🏭 Standards that prevent rot, applied to every table. created_at/updated_at on everything. Money as integer minor units (charge_amount_cents BIGINT) or NUMERIC — never float (floating point and money is a guaranteed reconciliation bug, and payers do not accept "rounding"). Timezone-aware timestamps only (TIMESTAMPTZ, never naive TIMESTAMP — a visit time is meaningless without a zone). Enums as CHECK (status IN (...)) or a lookup table, never a bare string the app validates. Code-system references (icd10_code, cpt_code) as FKs to reference tables, not freehand text. A consistent naming convention (snake_case, provider_id, explicit constraint names so error messages are diagnosable). These aren't bikeshedding; they're the small disciplines whose absence is the 41-column junk drawer.

The ADR​

This is the artifact that makes the decisions defensible and durable. ADR-016 records, per aggregate, the storage paradigm, the embedding boundary, and every denormalization with its consistency owner.

ADR-016 — Per-aggregate storage & normalization choices (Pulsely) Status: Accepted · Context: Pulsely's aggregates have divergent access shapes (see access-pattern inventory). A single storage paradigm serves none of them well, and PHI raises the cost of getting it wrong. Decision (per aggregate):

AggregateStoreEmbed/ReferenceNormalizationConsistency owner of any copy
PatientsRelational (PG)referencenormalizedn/a (source of truth)
EncountersRelational (PG)reference (never embed in patient)normalized + observation_count/result_count denormalizedasync aggregator; seconds-stale budget
Timeline/WorklistRelational projection / MVderiveddenormalized read modelrebuild job from encounters; not source of truth
Appointment slotsRelational (PG)referencenormalizedn/a (finite inventory, uniqueness-enforced)
Claims + line itemsRelational (PG)line items as weak entity (embedded-style)normalized, + CPT/charge snapshotsnapshot is immutable by design — no sync needed
AlertsAppend-only (PG or doc)self-containeddenormalized payloadper-row, write-once
SearchExternal index + Redis eligibility cachederiveddenormalizedreindex from PG; relational tables win on conflict; access-scoped
Rejected: "one paradigm for everything" (serves no aggregate's dominant access); embedding encounters in patients (unbounded growth, 16 MB cap, rewrite-the-world updates, minimum-necessary violation); live FK from claims to the service catalog (destroys service-date billing history — the 2 a.m. incident).
Consequences: Claims are immune to upstream catalog changes/retirements. Worklist and counters can drift up to seconds (acceptable per inventory). We own several derived copies (worklist, counters, search, eligibility cache) and have named the refresh mechanism for each — undocumented copies of PHI are forbidden.

6. Common pitfalls​

Each is signature → fix: the symptom, then the principle that resolves it.

EAV (entity-attribute-value). Signature: an attributes(entity_id, key, value) table where every logical query becomes a pile of self-joins, with no types, no constraints, and no way to enforce "a claim must have a charge." Someone reached for it to avoid "too many columns" or to allow "flexible" intake fields. Fix: model known attributes as real, typed columns — the engine's type and constraint system is the entire point. Reserve a single typed JSONB column for genuinely open/sparse fields (a rarely-used intake questionnaire), with documented limits and the knowledge that you've waived integrity for those fields specifically. EAV everywhere is rebuilding a worse database inside your database — and a worse database that happens to be full of PHI you can no longer classify.

God table. Signature: one clinical_items table with a type column ('encounter' | 'claim' | 'appointment') and 60 mostly-NULL columns, because they were "kind of similar." Every query filters on type, every column is nullable, and no constraint is meaningful because it must hold for all three types at once. Fix: split by entity type. If there's a real shared abstraction (genuine common behavior), use a shared base table plus per-type tables — but only if the abstraction survives scrutiny. "They both have an id and a created_at" is not a shared abstraction; it's a coincidence.

Polymorphic foreign key. Signature: attachments(attachable_id, attachable_type) pointing at "an encounter or a claim," with no foreign key constraint possible (a column can only reference one table). Referential integrity is gone; orphaned attachments accumulate silently; the database can no longer protect you — and an orphaned attachment might be a scanned document full of PHI pointing at nothing. Fix: separate join tables per parent type (encounter_attachments, claim_attachments) each with a real FK, or a typed link table — anything that lets the engine enforce the reference. Convenience that surrenders referential integrity is the trade EAV makes in a different costume.

Over-normalization. Signature: rendering one worklist row requires a 7-table join, and under load the p99 falls off a cliff because join cost scales with concurrency. The model is correct and unusable. Fix: keep the normalized model as the write-side source of truth, and deliberately denormalize the read path — a projection, a materialized view, or denormalized counters — with the consistency mechanism named (the Pulsely worklist in §5). Over-normalization is the failure mode of treating normalization as a virtue rather than a tool.

Unbounded embedded array. Signature: patient.encounters[] (or encounter.observations[]) embedded in the parent document; it grows forever, eventually hits the size cap, and every append rewrites the entire parent. Fix: reference — children in their own collection/table, keyed back to the parent. Apply the bounded test: if it grows without limit or is read independently, it is not part of the parent aggregate.

Hard delete destroying history. Signature: retiring a service breaks every historical claim that billed it (the 2 a.m. incident); or deleting a provider account erases the audit trail of what they charted. Fix: snapshot immutable facts into the records that need them (claims capture CPT + charge at the service date); soft-delete or archive the live record instead of destroying it. Decide per entity whether a thing is live configuration (retireable) or historical fact (immutable).

Nullable-as-state-machine. Signature: claim status encoded as three nullable timestamps — submitted_at, paid_at, denied_at — that can contradict each other (a row that's both paid and denied, or denied but never submitted). The state machine lives implicitly and inconsistently across columns. Fix: an explicit status enum (CHECK (status IN (...))) as the single source of state, plus a state-transition guard (a constraint, a trigger, or an audit row recording each transition). Timestamps can still record when each state was entered, but status is the truth.


7. Tradeoffs​

Senior modeling is the ability to name the spectrum and say why you're standing where you stand — and what would make you move.

Normalize ↔ denormalize. Normalized is correct-by-construction, cheap to write, expensive to read when truth is scattered. Denormalized is fast to read, but pays write amplification and carries permanent consistency debt. Reverse toward denormalized when the read:write ratio is heavily read-skewed and the copied fact changes rarely and you can name the refresh mechanism. Reverse back toward normalized when the consistency-keeping job becomes your new incident source — the day "the worklist counts are wrong" pages you more than the slow read ever did, the denormalization stopped paying.

Embed ↔ reference. Embed wins for owned, bounded, read-together data that's written atomically (claim line items). Reference wins for shared, unbounded, independently-queried data (a patient's encounters). Reverse from embed to reference the moment a child starts being queried on its own, or an embedded array starts growing unbounded — both are signs the child was never really part of the aggregate.

Relational ↔ document for an aggregate. Relational for integrity-heavy, multi-entity, join-and-ad-hoc-query domains (Pulsely patients, encounters, claims). Document for self-contained aggregates with predictable single-document access (an alert payload, a burst of RPM device readings).

🚫 A framing this book rejects. "Pick one database paradigm and use it for the whole app." It's seductive — fewer moving parts, one mental model — and it's wrong, because aggregates have genuinely different shapes and forcing them all into one store makes some of them expensive or unsafe. Polyglot-per-aggregate is legitimate and senior; the ADR is precisely the artifact that makes it accountable rather than chaotic. The discipline isn't "one store" or "many stores" — it's "the right store for each aggregate, written down with its reasons."

Surrogate ↔ natural keys. Surrogate keys are stable, opaque, and index well; natural keys are self-describing and free uniqueness but are mutable and leaky. Default to surrogate PK + a UNIQUE constraint on the natural key (MRN within a tenant). Lean natural only for small, truly-immutable reference data — the code-system tables (ICD-10, CPT, LOINC, RxNorm) are the textbook case: the code is the identity, externally governed and stable, so icd10_codes(code PK) is correct. Lean surrogate the instant the "natural" value can ever change — because a key that changes is a key that breaks every foreign reference to it, and an MRN can be reassigned on a patient merge.

Soft delete ↔ hard delete ↔ archive. Soft delete is recoverable and auditable but pollutes every query with a filter you can forget, and keeps PHI alive in tension with right-to-erasure. Hard delete is clean but irreversible (and destroys history if you didn't snapshot). Archive (move to cold storage) is the compliance-friendly middle. Choose per entity, not globally: a patient chart soft-deletes/merges (recoverable, referenced by history and retention rules); a one-time password-reset token hard-deletes (no value once used); billing and audit records archive (retention requirements forbid both deletion and clutter).

Snapshot ↔ live reference. Snapshot (claims freezing CPT + charge; encounters freezing coverage as of the visit) gives correct history immune to upstream change, at the cost of storage and an inability to retroactively "fix" the captured value. Live reference is always current but breaks the "what was actually billed / what was the coverage that day" invariant the moment the source changes. Pulsely claims snapshot — because a claim is a historical fact submitted to a payer, and historical facts don't get edited when the present changes.


8. Security & scale notes​

Modeling decisions are security and scale decisions; they just don't look like it until production — and in a HIPAA system, "until production" can mean "until the breach notification."

Sequential PKs in URLs are an enumeration / IDOR vulnerability — and with PHI, a reportable breach. If /patients/1041 is an auto-incrementing integer, an attacker increments it and walks your entire patient table — and if your authorization check is weak, reads other patients' charts (Insecure Direct Object Reference). A broken access check here isn't a bug ticket; it's a reportable HIPAA breach. The modeling fix is to never expose the sequential surrogate externally: keep the fast BIGINT PK internal and expose an opaque public identifier (a UUID, or a random external id) in URLs. Authorization that checks "does this clinician have a care relationship with this patient" — plus break-glass access that demands a logged justification for emergencies — is the other half; the modeling job is to not hand attackers a sequential map of your PHI.

Every read is an audit event. In most domains you log writes. In healthcare you must also log reads: who viewed which chart, when, and (for emergency/break-glass access) why. That obligation shapes the model — a first-class, append-only, tamper-evident chart_access_audit table (§4), written on the read path, separable from the clinical data. "Who has looked at this patient's record" is a query the compliance office will run, so it has to be cheap.

EAV and JSONB blobs evade column-level security and PHI classification. A value column in an EAV table, or an unstructured JSONB, can hold anything — including PHI — which makes field-level access control and "where do we store personal health data?" audits nearly impossible. Real typed columns let you classify, restrict, and reason about each field; a blob is a place where governance goes to die. This is a security argument for modeling, not just a tidiness one.

Soft delete collides with right-to-erasure. deleted_at keeps the PHI physically present, which conflicts with erasure requests — while HIPAA retention rules simultaneously require you to keep some records for years. Model a real hard-purge or crypto-shred path for erasable personal data (delete the row or destroy the key that decrypts it), and keep audit and billing records — which you often must retain — separable from the erasable personal data, so you can purge one without losing the other.

Denormalized counters become hot rows. A high-frequency monitoring device — say a continuous monitor streaming a reading every few seconds — hammers the same enrollment.reading_count (or observation_count) row, and write contention on one row serializes all those writers, so a counter that worked fine becomes the bottleneck that stalls ingestion for a whole panel of patients. The modeling-time awareness is that a single hot denormalized cell doesn't scale; the mitigations (sharded counters across N sub-rows, async aggregation, or moving the firehose into a document store) are real, but you must anticipate the hot row, not discover it when a device floods it. Ch 17 covers the contention mechanics.

Over-normalized read paths collapse first under load, because join cost scales with concurrency, not just data size — the 7-join worklist query that's tolerable at 10 req/s melts at 10,000. That's the scale argument for the read-side denormalization in §5: you denormalize the hot read path before it's the thing on fire during a morning clinic rush.

Append-only and temporal tables grow without bound and will, left alone, be the table that fills the disk — and in healthcare that's the audit log, the alert stream, and the RPM readings, all of which you're often required to keep. Plan partitioning and retention from day one — by month, by time range — so old data can be archived as a partition swap rather than a catastrophic mass-delete, and so retention means "moved to cold storage," not "gone." Unbounded growth is a slow-motion outage you schedule at design time.

Schema migrations are an availability concern. A naive ALTER TABLE ADD COLUMN NOT NULL DEFAULT or a non-concurrent index build can take a lock and stall every write to a live table — a "small change" becomes a full outage, and an outage on a system clinicians are charting in mid-visit is a patient-safety event. Expand/contract plus concurrent index builds aren't hygiene; they're how you change the model without taking the service down, which makes them a reliability property.


9. Interview lens & exercises​

Interview questions​

The same question separates levels by whether the answer is a reasoning process or a recited rule.

"Walk me from a domain description to a physical schema."

  • Junior answer: jumps straight to CREATE TABLE, listing columns. The model is whatever the first features needed.
  • Senior answer: names the three altitudes and descends them — conceptual ER first ("here are the entities and relationships in domain language"), then logical/normalized, then physical driven by an access-pattern inventory written before any DDL. Justifies key choices and any denormalization by the queries they serve. The signal is that tables come last, as the answer to questions already asked.

"When would you denormalize, and what does it cost you?"

  • Junior: "for performance" — full stop, no obligation attached.
  • Senior: frames it as one setting on a read/write dial, justified by a read-skewed ratio and a slow read path, and — crucially — names the consistency-keeping mechanism and the staleness budget ("worklist counters update async, tolerable to seconds; source of truth stays the observations table"). A denormalization without a named owner is a bug they'd flag in review.

"Embed or reference for a claim's line items? For a patient's encounters?"

  • Junior: one blanket rule for both ("always embed children" or "always reference").
  • Senior: applies the owned/bounded/read-together/written-atomically test and gets opposite answers — embed the line items (weak entity, bounded, atomic with the claim), reference the encounters (unbounded over a care lifetime, independently read, would blow the document cap). The ability to get different answers from one principle is the whole point.

"How do you retire a service (or delete a provider) that has historical claims?"

  • Junior: ON DELETE CASCADE — and destroys billing history.
  • Senior: distinguishes live configuration from historical fact; the claim snapshotted the CPT and charge at the service date, so the service soft-deletes or archives while claims remain intact and reconcilable. Names the invariant ("a claim is an immutable record of what was billed, at the charge in effect that day") that the cascade would have violated.

"What's wrong with EAV or a polymorphic FK — and when is each actually OK?"

  • Junior: loves it ("so flexible!") or hates it ("never") unconditionally.
  • Senior: names exactly what's lost — type safety, constraints, referential integrity, query simplicity, PHI classifiability — and the narrow legitimate case (genuinely sparse, open, user-defined fields via a typed JSONB column with documented limits). Conditional judgment, not dogma.

Exercises & the Pulsely increment​

Do these with pen and paper first, then commit the artifacts to the repo. The goal is a model you could defend in a design review.

  1. Pulsely conceptual ER diagram. Draw all entities — patients, providers, encounters, appointment slots, claims, alerts, search — with cardinality and participation notation. Box the weak entities (claim_line_item) and draw the junction table for every M:N (encounter_diagnoses → ICD-10). For each relationship, write the ON DELETE action you'd choose and one sentence of why. If you can't justify a cascade, it should be RESTRICT.

  2. Access-pattern inventory. Write the query table — 12–15 real Pulsely reads and writes, each with entry key, cardinality, frequency, p99 budget, and consistency need. Then use it to justify two specific denormalizations by pointing at the rows that demand them. This artifact is the design input; it should exist before any DDL.

  3. Per-aggregate physical decisions + ADR-016. For each aggregate, decide relational-vs-document and embed-vs-reference, write the DDL (or collection schema), and record every choice in the ADR with its tradeoff and named consistency owner. The acceptance test: a reviewer reading only the ADR can tell, for every copied field, what the source of truth is and what keeps the copy fresh.

  4. Refactor a god table. Take a deliberately bad 50-column clinical_items table (encounters + claims + appointments mashed together, type column, columns NULL for two of the three types) and decompose it into properly-typed per-entity tables. Express the change as an expand/contract migration — additive first, backfill, switch reads, drop old — and write the rollback for each step. Name the specific anomaly each decomposition removes.

  5. Time-modeling drill. Pick three Pulsely facts that need history — a service's charge over time (fee schedule), a patient's deletion/merge, a provider's amendment or co-sign on a signed note. For each, choose the weakest sufficient mechanism (soft delete vs audit log vs valid-time history) and justify why a stronger one would be over-engineering and a weaker one insufficient — remembering that a chart view is itself an audited event.


Key takeaways​

  • A data model is a theory of your domain enforced by the database — the one artifact that outlives every code rewrite, so it earns deliberate design, not emergent accretion. The cost of changing it grows as it matters; think before you CREATE TABLE.
  • Model at three altitudes — conceptual (what's true), logical (normalized structure), physical (access-driven layout) — and descend them. Skipping altitudes is how you get accidental design.
  • Shape follows access: the conceptual model is access-neutral, but the physical model is owed to the queries. Write the access-pattern inventory before the DDL.
  • The aggregate — data that changes together, is read together, has one consistency owner — is the unit of design and the thing that decides embed-vs-reference. Inside an aggregate you get atomic consistency; across boundaries you must manage it (the copies only catch up eventually).
  • Normalization and denormalization are one dial, not good vs evil. Normalize for correctness by default; denormalize deliberately, per aggregate, with the consistency-keeping mechanism and staleness budget named and owned.
  • Embed owned/bounded/read-together/atomic data; reference shared/unbounded/independently-queried data. The same test gives opposite answers for claim line items vs a patient's encounters.
  • Relational and document are mirror images: each makes the other's easy operation hard. Match each aggregate to the store whose guarantee fits its dominant access — polyglot-per-aggregate is legitimate, recorded in an ADR.
  • Model the whole lifecycle, including history: snapshot immutable facts (claims capture CPT + charge at the service date) so a hard delete can't destroy the past; pick the weakest sufficient time-modeling mechanism — and in healthcare, treat the read audit as first-class.
  • Avoid the anti-patterns — EAV, god tables, polymorphic FKs, over-normalization, unbounded embedded arrays, nullable-as-state-machine — each surrenders something (types, constraints, integrity, performance, PHI classifiability) the database existed to give you.
  • Treat schema evolution as routine: expand/contract, additive-first, destructive-last, every change reversible — because migrating data under load is an availability concern, and on a clinical system that's a patient-safety one.

← Previous: Ch 15 — Relational Foundations · Up: Part IV overview · Master TOC · Next: Ch 17 — Transactions, ACID & Isolation →