Skip to main content

Chapter 20 — NoSQL Thinking & MongoDB: Document Modeling at Scale

Part IV · Data & Storage | Prerequisites: Ch 16–Ch 18 | Builds: Pulsely's clinical activity feed (the provider worklist) on MongoDB with a chosen shard key

For five chapters we've been building the case for the relational model: sets and constraints, modeling as a discipline, transactions that hold under concurrency, the bytes underneath, and Postgres pushed to its sharp edges. You could be forgiven for concluding that the rest of this book is "use Postgres for everything, and learn it well." For most of Pulsely, that is the right answer. This chapter is about the part of Pulsely where it stops being the right answer — and, more importantly, about how to tell the difference without superstition.

"NoSQL" is the worst-named category in our field. It isn't anti-SQL; many NoSQL stores now speak SQL-ish dialects. It isn't "no schema"; the schema just moves. And it is emphatically not "the fast database you switch to when Postgres is slow" — that reflex has wrecked more systems than it has saved. This chapter teaches you to reason about one document store, MongoDB, the same way you'd reason about anything else in this book: from the access pattern of one aggregate up, deciding what to give up in exchange for what you gain, and writing down the decision so the engineer who inherits it knows it was a choice and not an accident. By the end you'll have moved exactly one piece of Pulsely — the clinical activity feed — to Mongo, modeled its document, written its read with the aggregation pipeline, indexed it, replicated it, and signed the partition contract (the shard key) that the collection will live under for the rest of its life.


1. The problem: when relational genuinely breaks down​

Let me start where these decisions actually start: with a slow feed and a pager going off.

Pulsely's clinical worklist is the most-hit endpoint in the product. A clinician opens the app, calls GET /worklist, and expects their last couple hundred events — a potassium result just posted for Maria Reyes, the home BP cuff on a monitored patient reported 190/110, the referral you sent came back accepted — already shaped, already ordered newest-first, ready to render. In the relational world we built, that worklist is assembled on every refresh by a five-table join:

SELECT e.*, p.mrn, p.display_name, o.loinc_code, o.value, r.acknowledged
FROM care_team ct
JOIN events e ON e.patient_id = ct.patient_id
JOIN patients p ON p.id = e.patient_id
LEFT JOIN observations o ON o.id = e.observation_id
LEFT JOIN read_receipts r ON r.event_id = e.id AND r.provider_id = $1
WHERE ct.provider_id = $1
ORDER BY e.created_at DESC
LIMIT 200;

In dev, against ten thousand rows, this returns in three milliseconds and looks fine. In production it does not. As the care-team roster fans out — a clinician on the care team of 800 patients, some of them high-acuity and generating events constantly — the planner has to gather events across hundreds of patient_id values, sort a large intermediate result by created_at, and stitch in patient, observation, and acknowledgement data. Past some threshold the planner switches join strategies, and this is the part worth slowing down on, because it's where the latency cliff hides:

  • A nested-loop join checks each patient's events one row at a time — fine when there are only a few patients to walk.
  • Past a threshold the planner flips to a hash join, which instead builds a lookup table of all the matching events in memory and probes it. That table lives in work_mem — the RAM budget Postgres hands a single query for exactly this kind of scratch space.
  • Once the table outgrows work_mem, Postgres spills it to disk, and every lookup that used to be a memory hit becomes a slow disk seek.

So your p99 worklist latency climbs to 900 ms at exactly the moment traffic peaks. (If you've ever had a React component that memoized fine in development and then started recomputing on every render once the list outgrew its cache, this is the same shape: a fast in-memory path silently degrading to a slow one once the data no longer fits.) You've done everything the relational chapters told you to. The indexes are right. The query is sound. It's still slow, and it's slow structurally.

Now look closely at what this worklist actually needs, because the mismatch is the whole lesson. It has no referential-integrity requirement worth paying for: if an acknowledgement count is a few seconds stale, no chart is wrong and no order is lost. There is no cross-entity invariant: rendering my worklist never has to be transactionally consistent with rendering yours. And the read shape is rigidly fixed: "give me one clinician's last 200 heterogeneous events, already joined, already sorted." We are paying the full price of ACID, referential integrity, and arbitrary-query flexibility for an access pattern that wants none of it. The relational engine is doing expensive, careful work to guarantee things this endpoint doesn't care about.

Two more pressures stack on top. First, write amplification. Pulsely uses fan-out-on-write: when an event happens to a patient, we don't recompute every clinician's worklist on read — we push an event into each care-team member's worklist at write time. Most of the time that's a handful of writes. But two things make the write side the bottleneck:

  • Remote monitoring is a firehose. A chronic-care program with 50,000 enrolled patients, each streaming blood-pressure, glucose, and weight readings every few minutes, generates millions of appends a day — and every append touches the table heap and every index on it.
  • A population event fans out hard. A recalled-medication alert that matches a care manager's entire panel turns one logical action into tens of thousands of worklist inserts in a single burst.

Row-at-a-time relational insert plus index maintenance becomes the bottleneck, and it's a write bottleneck, which no amount of read tuning fixes. Second, schema churn. The worklist grows a new event type almost every sprint — lab_result_ready, order_signed, vitals_alert, patient_message, referral_accepted — and each wants slightly different fields. In the relational model your options are all bad: a fresh ALTER TABLE per type, one wide table of mostly-NULL columns, or an EAV swamp (all three of which you were taught to fear). The events are genuinely heterogeneous, and the relational engine wants them homogeneous.

🚫 A framing this book rejects. "Postgres is slow, switch to Mongo." This is the trap, and it's worth naming loudly because it's the most common bad reason engineers reach for a document store. The worklist's problem is not that Postgres is a slow engine — Postgres is a superb engine and we're keeping it for almost everything. The problem is a mismatch between the shape of one aggregate and the storage model serving it. "We have a lot of data" does not justify leaving Postgres. "We added a JSONB column" does not justify leaving Postgres. What justifies it is a specific, demonstrable mismatch: a pre-joined read tree, unbounded write fan-out, heterogeneous records, and no cross-entity invariant — all at once, on one aggregate. The skill is moving that one aggregate, not the whole app.

So the honest list — the conditions under which relational genuinely breaks down, not the ones people pretend it does:

  • Unbounded fan-out write amplification, where one logical action becomes thousands of row inserts plus index churn.
  • Read shapes that are inherently a pre-joined tree — one entry point, a fixed nested shape, read far more than written.
  • Rigidly heterogeneous records that resist a single column schema and don't share enough structure to normalize cleanly.
  • Multi-region low-latency writes that need per-partition autonomy rather than one global serialization point.

Notice the worklist hits the first three squarely and the fourth not yet. That's enough. Everything else in Pulsely — encounters, orders, claims, the things with money and clinical invariants — fails this test and stays exactly where it is.

Why does this family of databases exist at all? Because in the 2000s the web forced a choice the relational engines of the day made painful. You could scale reads and writes horizontally across many machines, or you could keep a single global relational invariant cheaply — but not both. Relational engines made the global invariant cheap and horizontal scale hard. NoSQL stores made the opposite bargain: give up some global guarantee (cross-document joins, cross-key transactions, ad-hoc queries) and horizontal scale gets cheap. The whole family is variations on what, exactly, do you surrender to make sharding easy.


2. The mental model: store the aggregate the way you read it​

Hold one sentence at the center of everything in this chapter: store the aggregate the way you read it.

A relational schema is optimized for write-side integrity and unknown future queries. You normalize so each fact lives in one place, declare constraints so the engine refuses bad states, and trust that joins will let you answer questions you haven't thought of yet. That's the right bet when you don't know what you'll ask, and when wrong answers cost money.

A document is the opposite bet. A document is a pre-joined, self-contained read unit: you do the join once, at write time, and store the result in the shape the reader wants. The worklist document for a clinician already contains the patient's name and MRN, the observation's LOINC code and value, the acknowledgement state — no read-time join required. You've moved the cost from "every read" to "every write," which is a fantastic trade when you read far more than you write and the read shape is stable, and a terrible one otherwise.

🧭 Mental model. Relational asks "where does this fact belong so it's stored once and stays consistent?" Document asks "what does the reader need in one round trip, and how do I store it already in that shape?" The first optimizes the write and the integrity; the second optimizes the read and the locality. Neither is more advanced. They are two settings on a dial, and the discipline you've been practicing — choosing the setting per aggregate, on purpose, and writing down why — is exactly the discipline here.

Three corollaries fall out of that sentence, and they'll carry you through the rest of the chapter.

Schema doesn't disappear in "schemaless"; it relocates. When MongoDB doesn't enforce a schema, the schema doesn't cease to exist — it moves out of the database and into your application code and your modeling discipline. Every reader of that collection still assumes a shape. The difference is that the engine no longer guards that shape for you; you do, in code, in validators, in review. "Schemaless" is not "no schema." It's "you own the schema now, and the database won't catch your mistakes." For some teams that flexibility is liberating; for undisciplined teams it's a slow-motion data-quality disaster.

Embed versus reference is the whole game. The single decision you'll make over and over is: does this related data live inside the document (embedded) or in a separate document you point at (referenced)? One sentence drives roughly 80% of those calls: embed what is owned, read together, and bounded; reference what is shared, queried independently, or unbounded. An encounter's handful of vitals readings? Owned, read with the encounter, bounded if you cap them — embed. A patient's entire chart history? Read independently, unbounded — reference, always. We'll make this rigorous in §3, but carry the sentence now.

The shard key is a contract you sign for the life of the collection. When the worklist collection outgrows one machine and you spread it across many, the shard key is the field (or fields) that decides which physical node every document lives on — and therefore which node every read and every write lands on. It governs whether load spreads evenly or piles onto one hot machine, and whether a query can be routed to one shard or has to fan out to all of them. And it is, in practice, effectively irreversible: changing it on a large live collection is a major, expensive migration. You choose it once, at design time, with the access pattern in front of you. Treat it with the seriousness of a primary-key choice that you can never alter.

The NoSQL family, as four answers to one question​

Before we commit to documents, place them on the map. Every NoSQL family is an answer to "what do I give up to make horizontal scale cheap?"

ad-hoc query flexibility
▲
│
RELATIONAL ●─────┼────── (joins, constraints, arbitrary queries;
(Postgres) │ horizontal scale is the hard part)
│
┌──────────────────────────┼──────────────────────────┐
│ DOCUMENT (Mongo) │ WIDE-COLUMN (Cassandra) │
│ give up: cross-doc joins │ give up: ad-hoc queries │
│ & multi-doc txns │ (one table per query) │
│ get: pre-joined locality │ get: linear write scale │
├──────────────────────────┼──────────────────────────┤
│ KEY-VALUE (Redis, Dynamo)│ GRAPH (Neo4j) │
│ give up: querying by │ give up: easy sharding │
│ value (key is the path)│ (edges cross partitions)│
│ get: O(1) get/put │ get: cheap traversal │
└──────────────────────────┴──────────────────────────┘
│
▼
easy horizontal scale
  • Document (MongoDB, Couchbase): records are nested JSON-like documents. You get strong single-document atomicity and beautiful read locality; you give up cheap cross-document joins and multi-document transactions. Right when the aggregate boundary equals the document boundary. Pulsely's clinical worklist lives here.
  • Key-value (Redis, DynamoDB-as-KV): O(1) get/put by key, and that's the deal — the access path is the key, and you can't query by value. This is the caching intuition you've already built, and it's the next chapter's whole world. Pulsely's session cache, eligibility cache, and rate limiters live here.
  • Wide-column (Cassandra, Bigtable): a partition key plus clustering columns, where you design one table per query, denormalize aggressively, and accept no joins and eventual consistency in exchange for near-linear write scale. Pulsely doesn't need this yet — the worklist's volume doesn't demand it and we want richer read paths than it offers.
  • Graph (Neo4j): nodes and edges with index-free adjacency, making traversals ("providers two referral-hops away who've seen this patient") cheap. The catch: edges naturally cross partitions, so the model resists sharding. Pulsely's care-team and referral relationships are graph-shaped but small enough to live as relational rows — a real graph DB is a tool we'd reach for only if traversal became the dominant cost.

📎 Borrowed on credit: eventual consistency & quorums. Several stores above (and Mongo's own replica sets, later in this chapter) lean on eventual consistency, quorums, and the trade between consistency and availability when the network partitions. We will use that vocabulary freely here — "majority write," "stale secondary read," "failover window" — but we will not derive it. The real theory (CAP, PACELC, why quorums work, what "linearizable" formally means) is Ch 23–Ch 24. For this chapter, treat the consistency knobs as a menu you order from; the menu's physics comes later.


3. Theory & invariants: the document model and its design patterns​

This is the load-bearing section. Get the invariants here and the rest of the chapter is application.

BSON, collections, and the 16 MB cap​

MongoDB stores documents as BSON — a binary, typed, length-prefixed encoding of JSON-like structures. "Typed" matters: BSON distinguishes an ObjectId, a Date, a Decimal128, an int vs a long, and raw binary, where plain JSON would flatten all of those to strings and numbers. "Length-prefixed" matters for performance: each document and sub-document records its byte length, so the engine can skip over fields it doesn't need without parsing them.

Documents live in collections (the rough analogue of tables), and a collection imposes no enforced schema by default — two documents in the same collection can have wildly different shapes. You can attach a JSON-Schema validator (we will, in §5), but out of the box the discipline is yours.

One number governs an enormous amount of design: a single document cannot exceed 16 MB. Read that not as a limit to fight but as a design constraint that protects you. It's the engine telling you, in advance, that an unbounded embedded array is a bug. If your modeling pushes a document toward 16 MB, the model is wrong — you needed a reference or a bucket, not a bigger document.

The core invariant: single-document atomicity​

Here is the one guarantee that drives every modeling decision in Mongo:

🔑 The single-document atomicity invariant. Any write that touches one document is atomic and isolated: it either applies completely or not at all, and no concurrent reader sees a half-applied state — even when the document is large and the update touches deeply nested fields. There is no extra cost, no transaction to open, no isolation level to pick. This is free and always on. The corollary that runs the whole chapter: make your aggregate boundary your document boundary. If a cluster of data must change together atomically, it must live in one document, because one document is the unit Mongo will mutate atomically for you. Data that doesn't need to change atomically with the rest is a candidate to live elsewhere.

Multi-document transactions do exist in modern MongoDB, and they give you ACID across documents and even collections. But they are the expensive exception, not the default tool — they hold locks, they cost latency, and reaching for them routinely is usually a sign your aggregate boundaries are wrong. The relational world makes cross-row transactions cheap and natural; the document world makes single-document atomicity cheap and natural and cross-document transactions deliberately awkward. Each makes the opposite operation the expensive one. Design with the grain.

Embed vs reference, made precise​

The one-sentence rule — embed owned/bounded/read-together, reference shared/unbounded/independently-queried — decomposes into three orthogonal questions:

  1. Cardinality. One-to-few (an encounter's handful of vitals, an order's line items) embeds happily. One-to-many (a provider's hundreds of patients) references. One-to-squillions (a monitored patient's millions of device readings over time) always references, no exceptions — embedding would blow the 16 MB cap on its own.
  2. Volatility. Data that is shared and changes often should be referenced, because if you embed it you duplicate it, and now every change must fan out to every copy. A patient's display name appears in thousands of worklist events; if you embed it and the name is corrected, you owe thousands of updates. (We'll see in a moment that there's a controlled exception to this — the extended-reference pattern — but the default for volatile shared data is reference.)
  3. Access locality. Data that is read together wants to be embedded so one read returns it all; data read on its own wants its own document so you can query and index it independently.
Is this data OWNED by the parent (exists only with it)?
│ no ──────────────────────────▶ REFERENCE
│ yes
▼
Is it BOUNDED (will not grow without limit)?
│ no ──────────────────────────▶ REFERENCE (and consider Bucket)
│ yes
▼
Is it READ TOGETHER with the parent, almost always?
│ no ──────────────────────────▶ REFERENCE
│ yes
▼
Will it stay well under 16 MB even at the outlier?
│ no ──────────────────────────▶ REFERENCE (or Subset + reference tail)
│ yes
▼
EMBED

For Pulsely's worklist, walk the tree: each worklist event is owned by the recipient clinician's worklist, the per-clinician event stream is unbounded (which the bucket pattern will tame), and an individual event is read together with the rest of the page. So the event payload embeds inside a worklist document, but the unbounded stream is bucketed rather than crammed into one giant document.

The named schema-design patterns​

These are the document modeler's vocabulary — the equivalent of the relational normal forms, but optimizing locality instead of eliminating redundancy. Know them by name; reviewers will reference them like idioms.

  • Bucket. Group a high-volume stream of small items into bounded sub-documents instead of one document per item. Pulsely's worklist becomes one document per clinician per day, holding that day's events in an array, rather than one document per event (too many tiny documents, expensive to page) or one document per clinician forever (unbounded growth, 16 MB cliff). Buckets cap both document size and document count. This is the antidote to unbounded arrays — and it's the pattern that tames the RPM firehose.
  • Subset. Embed only the hot slice and reference the rest. An encounter embeds its last 20 vitals readings (or a note its most recent addenda) for instant render; the full history lives in a separate collection, fetched only when someone opens the full timeline. Keeps the working set — the bytes you actually touch on the common path — small.
  • Extended reference. When you reference another document but always read a few of its fields alongside, duplicate just those few fields next to the reference. A worklist event stores patient: { id, mrn, name } — the id is the real reference, the mrn and name are a denormalized copy that saves a lookup on every render. The price is controlled staleness: if the patient's name is corrected, the copies are briefly wrong until you fan out the update. You accept that consciously, for the fields where stale is harmless.
  • Computed. Precompute and store an aggregate at write time rather than computing it on read. patient.open_orders_count is incremented when an order is created, not COUNT()-ed on every render. (This is the denormalized-counter idea you've already met, native here.)
  • Outlier. Handle the rare oversized case with a different shape, rather than letting it distort the common-case model. 99.9% of patients have small enough care teams to fan out normally; the rare outlier — a complex patient on a large multidisciplinary team, or a population-health broadcast that would fan out to tens of thousands — gets an isOutlier: true flag that switches to fan-out-on-read instead. You don't model everyone for the outlier; you model the common case cleanly and special-case the outlier.

🔑 The duplication-obligation invariant. Every time you embed or extended-reference a copied fact (the patient's name, the observation's value, the open-orders count), you have signed up for an obligation: something, somewhere, must keep the copies consistent, and you must be able to name what that something is. A trigger? An app-layer write? An async fan-out job? An "it's allowed to be stale for N seconds and here's why that's fine"? Undocumented duplication is the single biggest source of "the counts are wrong" bugs in document systems — it's the same trap as undocumented denormalization, just easier to fall into because the engine never warns you.

Consistency vocabulary: write concern, read concern, read preference​

MongoDB hands you three independent knobs that compose into a per-operation consistency choice. You don't set one global level; you choose per operation, which is both powerful and a footgun.

  • Write concern (w, j, wtimeout). How many replica-set members must acknowledge a write before the driver calls it durable. w: 1 = just the primary acked (fast, but lost if the primary dies before replicating). w: "majority" = a majority of voting members acked (survives a single-node failure, costs latency). j: true = the write hit the on-disk journal, not just memory. wtimeout caps how long you'll wait.
  • Read concern (local, majority, linearizable). What guarantee a read gives you. local = whatever this node has, possibly including writes that could still be rolled back. majority = only data that a majority has acknowledged, so it can't be rolled back. linearizable = a read guaranteed to see every write that had already finished before you asked — no stale data at all, at the cost of the most latency. (The formal definition is deferred to the distributed-systems chapters.)
  • Read preference (primary, primaryPreferred, secondaryPreferred, secondary). Which member you read from. primary = always the authoritative node (read-your-writes safe). secondaryPreferred = offload to replicas for throughput, accepting that they may lag.

These compose. "Durable, read-your-writes" is w: "majority" + readConcern: "majority" + primary. "Cheap and staleness-tolerant" is w: "majority" write + secondaryPreferred read. The routine worklist is the second; a claim's submission status is the first. The art is matching the knob to the consequence of being wrong.


4. Under the hood: WiredTiger, indexes, the pipeline, and replica sets​

Theory tells you what to model; this section tells you what the engine actually does with it, so your predictions about performance are grounded in mechanism rather than hope.

BSON on disk and the ObjectId​

We met BSON above; one detail matters for sharding later. The default _id, an ObjectId, is a 12-byte value whose leading 4 bytes are a timestamp. That makes ObjectIds monotonic — meaning each new id is larger than the last, second to second. Convenient for "sort by _id and get newest-last." But here's the consequence that matters, and we'll see it bite in §5: because every new id is bigger than the last, every new write piles onto the same "highest" end of the range — and that end lives on one shard. (The random and counter bytes below the timestamp mean writes within the same second don't strictly order, but that doesn't save you: the timestamp still marches forward.) Filing that away now.

WiredTiger: the storage engine​

Mongo's default storage engine is WiredTiger, and earlier you saw how databases store bytes on disk — most of WiredTiger is that same machinery. It provides:

  • Document-level concurrency via MVCC snapshots — readers see a consistent point-in-time view and don't block writers, writers don't block readers: the same MVCC posture you saw in Postgres, just at document granularity instead of row.
  • B-tree indexes on disk — the same B-tree structure you've already met, same O(log n) with a tiny constant.
  • Compression of both data and indexes, trading CPU for I/O and RAM.
  • A working-set model that is the single most important performance fact about Mongo: reads are fast only when the working set — the documents and index entries you actually touch — plus the indexes themselves fit in RAM. The moment your hot data exceeds RAM, reads start hitting disk randomly and latency falls off a cliff. This is the caching/working-set reasoning you've been building, and it never stops being true.

🏭 The number-one cause of "Mongo got slow overnight" in production is the working set quietly outgrowing RAM. Nothing in your code changed; the collection grew, the indexes grew, the hot pages stopped fitting, and the buffer cache started thrashing. Capacity-plan Mongo by working set vs RAM, not by total data size. This is why the bucket and subset patterns (which shrink the working set) are performance tools, not just tidiness.

Indexing in MongoDB​

Indexes work as you'd expect, with document-specific flavors:

  • Single-field and compound indexes (multiple fields, in a specific order).
  • The ESR rule for compound-index field order: Equality, then Sort, then Range. Fields you match exactly (providerId = X) go first, fields you sort by (createdAt) next, fields you range over (value > Y) last. Field order is not cosmetic — get it wrong and the index can't serve the query, and you'll do a collection scan despite "having an index."
  • Multikey indexes over array fields (Mongo indexes each element) — powerful for tags, with gotchas around how they interact with compound indexes and sorting.
  • Partial indexes (index only documents matching a filter — e.g., only status: "active") to shrink the index, and TTL indexes, which automatically delete documents a set time after a date field. TTL is a perfect fit for aging out old worklist and alert documents: set a 30-day TTL and the engine garbage-collects stale entries with zero application code.
  • Text indexes for basic full-text search (real search is Ch 22's domain).
  • Covered queries: when an index contains all the fields a query needs, Mongo answers from the index alone without touching the document — the fastest possible read.

You diagnose all of this with explain("executionStats"), the Mongo analogue of Postgres's EXPLAIN. The two things to read: IXSCAN (index scan, good) vs COLLSCAN (collection scan, usually bad), and the ratio of totalKeysExamined to nReturned — your health metric. If the engine examined 100,000 keys to return 200 documents, your index isn't selective and the query is doing 500× the necessary work. A healthy query examines roughly as many keys as it returns.

The aggregation pipeline​

The aggregation pipeline is Mongo's analytical query language, and the right way to think about it is: a query plan you write by hand, as a sequence of stages, each transforming the stream of documents and feeding the next.

documents ──▶ $match ──▶ $sort ──▶ $limit ──▶ $project ──▶ result
(filter) (order) (cut) (reshape)

The stages that matter:

  • $match filters — put it first so it can hit an index and shrink the stream immediately.
  • $sort orders — also early, so it can use an index rather than sorting in memory.
  • $limit caps the stream — pair with $sort to get top-N cheaply.
  • $project reshapes each document (pick fields, compute new ones).
  • $group aggregates (the GROUP BY analogue — $sum, $avg, counts).
  • $lookup is a left outer join to another collection. It exists, and it's occasionally the right tool — but if $lookup is the heart of your main read path, that's a smell: you've recreated a relational join in a store that doesn't shard joins well, and you should ask whether this aggregate wanted to be in Postgres. Use it for occasional enrichment, not as your architecture.
  • $unwind explodes an array into one document per element; $facet runs several sub-pipelines in parallel over the same input; $merge/$out write the pipeline's result into a collection — the way you build materialized rollups (precompute a daily analytics summary on a schedule).

The mental discipline is filter and shrink early, reshape late. Every stage processes whatever the previous stage emitted, so a $match that drops 99% of documents up front makes every later stage 100× cheaper.

Replica sets and the oplog​

A production Mongo deployment is never a single node; it's a replica set: one primary that takes all writes, plus secondaries that replicate from it. The replication mechanism is the oplog — an idempotent, ordered operation log the primary writes and the secondaries continuously replay. (Idempotent is the key adjective: replaying an oplog entry twice produces the same state as replaying it once, which is what makes recovery and catch-up safe.)

Members exchange heartbeats; when the primary disappears, the surviving members hold an election and promote a secondary to primary automatically. The gap between "old primary died" and "new primary is serving" is the failover window — typically seconds — during which writes pause. What happens to a write caught in that window depends entirely on its write concern, and it's worth walking slowly:

  • Say the primary accepts your write and replies "done" — that's w: 1 — but dies before copying it to any secondary. When a secondary is promoted, it never saw that write, so the write silently vanishes. (The dead primary's un-copied tail is discarded when it eventually rejoins.)
  • Now say you'd used w: "majority": the primary only replies "done" after a majority of members already have the write. Any new primary is elected from that majority — so it is guaranteed to have your write.

That's the concrete, mechanical reason w: "majority" is the durable choice and w: 1 is the fast-but-loseable one.

📎 Borrowed on credit: elections, quorums, and the failover window. Why a majority is the magic number, how the election protocol guarantees a single new primary, and what "in-flight write" means formally under a network partition — that's distributed-systems theory, and it's Ch 23–Ch 24. Here, use the result: writes pause briefly during failover, majority survives it, w:1 may not.

The Node lane: driver vs ODM​

In TypeScript you have two front doors. The official mongodb driver is the raw, fast, low-magic option — you write queries as plain objects and get documents back. Mongoose is an ODM (object-document mapper) layered on top, adding schemas, type casting, validation, virtuals, and middleware hooks.

// Raw driver: fan-out a clinical event into the care team's worklists with one round trip.
// bulkWrite batches thousands of updates into a single network call —
// this is the right shape for fan-out-on-write.
const ops = careTeamProviderIds.map((providerId) => ({
updateOne: {
filter: { providerId, day: today }, // the bucket for this clinician, today
update: { $push: { events: worklistEvent } }, // append to the day's bucket
upsert: true, // create the bucket if absent
},
}));
await db.collection('worklist').bulkWrite(ops, { ordered: false });

When does Mongoose earn its weight? When you genuinely want app-side schema enforcement, casting, and lifecycle hooks, and you're willing to pay for the abstraction. When does it hurt? When its middleware hides cost (a pre('find') hook firing extra queries you didn't notice), or when its schema lulls you into thinking the database enforces shape (it doesn't — Mongoose validates in your app process; a script writing directly bypasses it entirely). For the worklist's high-throughput fan-out, the raw driver with bulkWrite and cursor/streaming reads (iterate results lazily rather than materializing a giant array in memory) is usually the right call.

🏭 The transferable lesson, and it survives the jump to other ecosystems: an ODM cannot rescue a bad embed/reference decision. Spring Data MongoDB on the JVM gives you the same repository convenience and the same illusion — a @Document annotation and a clean repository interface — but if you embedded an unbounded array, no framework saves you from the 16 MB wall and the rewrite-the-world updates. The modeling choice dominates the framework choice, here even more than in the relational world, because the database is doing less to protect you.


5. In production: moving Pulsely's worklist, and the two ADRs​

Now we apply all of it, and produce the two decisions this chapter exists to make.

The per-aggregate decision (ADR-020a)​

The first ADR is not "should Pulsely use Mongo?" — that question is malformed. It's "for each aggregate, Postgres or Mongo, and why?" Written as a table:

AggregateStoreWhy
Patients, providers, authPostgresHeavily referenced, integrity-critical (MRN uniqueness, coverage, consents), cross-entity joins for reporting and RBAC.
Appointment slots, orderable catalogPostgresFinite inventory (the no-double-booking constraint), referential integrity to encounters, ad-hoc queries.
Encounters, orders, claimsPostgresHard multi-row invariants — no-double-booking on slots, exactly-once claim submission — real ACID, financial reporting joins.
Clinical activity feed (worklist)MongoDBPre-joined read tree, unbounded write fan-out (the RPM firehose), heterogeneous event types, no cross-entity invariant, staleness-tolerant.
Clinical alerts, notificationsMongoDBSame shape as the worklist — append-heavy, read-as-a-list, TTL-expirable — with a stronger path reserved for critical values.

The discipline this table encodes: polyglot persistence per aggregate is legitimate; one paradigm for the whole app is a fashion statement, not an engineering decision. Encounters go one way and the worklist goes the other for stated reasons, and the ADR records both the choice and the rejected alternative ("we considered keeping the worklist in Postgres with aggressive denormalization and a materialized view; rejected because the write fan-out — the RPM firehose — not the read, was the bottleneck, and document-per-clinician buckets serve the fan-out far better").

Modeling the worklist document​

We chose the bucket pattern: one document per clinician per day. Walk the §3 decision tree if you need to re-justify it, then write the shape:

// One worklist bucket = one clinician's events for one day.
interface WorklistBucket {
providerId: string; // recipient clinician (NOT the patient) — the read entry point
day: string; // "2026-06-19" — bounds the bucket
count: number; // computed pattern: events.length, for cheap paging
events: Array<{
eventId: string;
kind: string; // "lab_result_ready" | "vitals_alert" | "order_signed" | "patient_message" | ...
createdAt: Date;
// extended reference — minimum necessary: only what the row must render, not the whole chart
patient: { id: string; mrn: string; name: string };
observation?: { system: "LOINC"; code: string; value: string; unit: string }; // extended ref
schemaVersion: number; // lazy-migration discriminator
}>;
}

Every §3 pattern is visible: bucket (per clinician per day), extended reference (patient and observation fields duplicated for render), computed (count), and the heterogeneous events array that would have been an ALTER TABLE nightmare relationally is just... documents with different optional fields. Note the LOINC-coded observation: the code systems themselves (LOINC, ICD-10, CPT, RxNorm) are small, stable reference data that live in Postgres (or a cache) — the worklist embeds only the coded result it needs to render, not the whole catalog. The schemaVersion field is the schema-validation reality check: in a schemaless store you version your documents and migrate lazily — when a read encounters an old schemaVersion, the app upgrades it in place. You attach a $jsonSchema validator with validationLevel: "moderate" so new writes are guarded without blocking the old documents you haven't migrated yet. Guardrails, not handcuffs.

Building the read​

The worklist read is an aggregation pipeline, filtering and shrinking early:

const worklist = await db.collection('worklist').aggregate([
{ $match: { providerId, day: { $gte: since } } }, // index hit, shrink stream
{ $sort: { day: -1 } }, // newest buckets first
{ $limit: 7 }, // last week of buckets
{ $unwind: '$events' }, // explode to one event per row
{ $sort: { 'events.createdAt': -1 } },
{ $limit: 200 }, // the page the client asked for
{ $project: { _id: 0, event: '$events' } }, // reshape for render
]).toArray();

The supporting index — applying ESR — is a compound index on { providerId: 1, day: -1 }: providerId is the equality match, day is the sort/range. Prove it with explain("executionStats") and confirm IXSCAN, not COLLSCAN, with totalKeysExamined close to the buckets returned. That validation is not optional; it's how you know the index you think serves the query actually does.

Consistency knobs, set deliberately​

The routine worklist tolerates staleness, so: write fan-out with w: "majority" (you don't want acknowledged worklist events vanishing on failover — even a worklist deserves durability once acked), and read with secondaryPreferred to offload the heaviest endpoint onto replicas. The one trap: the clinician's own actions must be read-your-writes. When a clinician signs an order and immediately refreshes their worklist, reading from a lagging secondary shows them stale state and a support ticket. So that specific path reads from primary. Same collection, two read preferences, chosen by consequence of staleness.

One healthcare caveat the social version of this pattern doesn't have: a critical-value alert — a potassium of 6.9, a BP of 200/120 — is not staleness-tolerant at all. Those events ride a separate, stronger path (primary, w: "majority", plus escalation) because a missed critical value is a clinical-safety event, not a stale-count annoyance. The worklist as a whole is staleness-tolerant; the alert lane inside it is not. That distinction is exactly the "match the knob to the consequence of being wrong" discipline, with a consequence that has teeth.

Operational reality​

A few things that bite if ignored: tune the Node driver's maxPoolSize (connection pooling — a fixed, shared set of reusable DB connections the whole server borrows from — is as real here as it was in Postgres); enable retryable writes so a transient failover blip is masked rather than surfaced as an error; watch the oplog window — if a secondary falls so far behind that the oplog has already discarded the entries it still needs, it can't catch up and needs a full resync (an operational fire); and build indexes via rolling builds on secondaries rather than blocking the primary. Audit indexes with $indexStats and drop the unused ones — every index taxes every write and eats working-set RAM, the same write-tax lesson you've already met, with higher stakes because RAM is the whole game.

The shard key (ADR-020b)​

The day the worklist collection outgrows one machine, you shard it — and you do this before you're in pain, not during the incident. Resharding a hot collection live is possible on modern Mongo but expensive and stressful; the shard key is a design-time decision. The candidates:

Shard keyDistributionQuery routingVerdict
_id (ObjectId)Bad — monotonic, all new writes hit one "max" chunk on one shard (hotspot)Poor for worklistReject.
providerId hashedEven — hashing spreads writes across all shardsSingle-shard for "this clinician's worklist" (the dominant read)Choose this.
{ providerId, day } rangedRisks the recent-day hotspot; better locality for day rangesSingle-shard per clinicianViable alternative; loses even write spread.

The reasoning that picks hashed on providerId: the worklist's entire access pattern is "give me one clinician's worklist," so every read and every write naturally keys on providerId. Hashing providerId spreads load evenly across shards (no hotspot), and because a single clinician's data hashes to a single shard, the dominant read is single-shard routed — Mongo sends it to one machine instead of scattering it to all of them. The cost we accept: hashed keys destroy range queries on providerId (you can't ask "all providers between A and M"), but the worklist never asks that, so it's free to give up.

MONOTONIC key (_id): HASHED key (providerId):
all new writes ─┐ writes spread evenly
▼ ┌────┬────┬────┐
┌────┬────┬────┬████┐ │ ▓▓ │ ▓▓ │ ▓▓ │
│ │ │ │████│ ◀ HOT │ ▓▓ │ ▓▓ │ ▓▓ │
└────┴────┴────┴████┘ └────┴────┴────┘
shard0 shard1 shard2 shard3 shard0 shard1 shard2
(3 shards idle, 1 melting) (load balanced)

The ADR records the candidates, the choice, the rejected options with reasons, and — critically — the migration cost of being wrong, because that cost is the whole reason this gets ADR treatment. Pick a low-cardinality key like clinic_id and you get jumbo chunks that can't be split and refuse to balance; pick a monotonic key and you hotspot one shard while the others idle. Either mistake is a major migration to fix on a live system. Write it down so the next engineer knows it was deliberate.

🔑 The shard-key irreversibility invariant. Choose for the dominant access pattern, choose for high cardinality and even distribution, and choose before the collection is enormous. The shard key decides which physical node every read and write touches for the life of the collection, and changing it on a large live collection is a migration, not a config tweak. It is the most consequential and least reversible decision in a sharded document store. Treat it like a primary-key choice you can never ALTER.


6. Common pitfalls​

Unbounded array growth. Signature: a document creeps toward 16 MB, writes slow as the whole document is rewritten on each append, and the working set bloats as one fat document hogs RAM. Fix: bucket or subset; never embed an unbounded one-to-many. The 16 MB cap is telling you the model is wrong — listen to it before you hit it.

Treating Mongo as a faster Postgres. Signature: the app does many round trips, the main read is a $lookup-heavy pipeline reassembling normalized collections, and you've recreated joins in a store that doesn't shard them. Fix: re-model around the read shape (pre-join at write time), or admit honestly that this aggregate's integrity and ad-hoc-query needs mean it belonged in Postgres all along.

No schema enforcement, silent drift. Signature: three variants of the same event type accumulate in one collection, and a query written for one shape silently misses documents in another. Fix: $jsonSchema validators, a schemaVersion discriminator, and consistent extended-reference duplication enforced in one place — not copy-pasted per writer.

Compound index in the wrong field order. Signature: explain shows a COLLSCAN despite "having an index," and totalKeysExamined dwarfs nReturned. Fix: apply ESR (Equality, Sort, Range) and re-check explain. The index order is the index's usefulness.

Monotonic shard key. Signature: one shard runs hot while the others idle; all new writes pile onto the highest chunk. Fix: hash the key, or use a compound key whose leading field spreads writes. This is what _id/ObjectId and raw timestamps do to you.

Low-cardinality shard key. Signature: a few jumbo chunks that can't be split, a balancer that can't even out the cluster. Fix: choose a high-cardinality, evenly distributed key; clinic_id and status are classic mistakes.

Reading your own writes from a secondary. Signature: a clinician signs an order, refreshes, and doesn't see it because the read hit a lagging secondary. Fix: primary/primaryPreferred for read-your-writes paths; secondaryPreferred only for genuinely staleness-tolerant reads.

Default w: 1 on data you'd be sad to lose. Signature: an acknowledged write disappears after a failover election. Fix: w: "majority" for anything durable. w: 1 is for data you can afford to lose.

Assuming cross-document atomicity. Signature: an update meant to touch two documents leaves one changed and one not after a crash mid-operation, because you assumed two writes were one atomic act. Fix: redesign so the invariant lives inside one document (the whole point of aggregate-equals-document), or use a multi-document transaction knowing its cost — sparingly.


7. Tradeoffs​

Embed ↔ reference. Embed wins read locality and free single-document atomicity; it loses on shared data (duplication to keep consistent), volatile data (fan-out on every change), and unbounded growth (the 16 MB wall). Reverse to reference the moment the embedded thing is queried independently or starts growing without bound. The extended-reference pattern is the deliberate middle: embed a few stable fields, reference the rest, accept controlled staleness.

Mongo ↔ Postgres, per aggregate. Choose Mongo for stable pre-joined read shapes with high write fan-out and no cross-entity transactions. Reverse to Postgres the instant you need multi-entity invariants, ad-hoc analytical joins, or financial reporting. The discipline is that this is a per-aggregate call documented in the ADR — the worklist goes one way, encounters the other, both for stated reasons — not an app-wide religious commitment.

Document ↔ wide-column for the worklist. Mongo gives richer queries and secondary indexes; Cassandra gives more linear write scale but forces query-first, one-table-per-query design with no flexibility. Reject Cassandra here because the worklist needs flexible read paths and the volume doesn't yet demand Cassandra's scale. You'd reverse only at a volume Pulsely is nowhere near.

Duplicate (extended-reference/computed) ↔ compute-on-read. Duplication trades write complexity plus staleness for cheap reads. Reverse it when the duplicated data churns faster than you can fan out the updates — at that point the consistency-keeping job becomes your new bottleneck and incident source, and a reference with a read-time lookup is honestly cheaper.

Hashed ↔ ranged shard key. Hashed spreads writes evenly but destroys range queries and locality; ranged preserves locality and range queries but risks hotspots on monotonic fields. The worklist's pure "by providerId" access pattern makes hashed-on-providerId the clear winner — there are no providerId range queries to lose. Flip to ranged when locality of adjacent keys is part of your read pattern and you can avoid monotonicity.

Strong ↔ eventual read consistency. majority reads cost latency and depend on a live quorum; secondaryPreferred buys throughput at the price of staleness. Acceptable for the routine worklist; unacceptable for a claim's submission status or a critical-value alert, where reading a stale or rolled-back value is a correctness — and safety — bug.


8. Security & scale notes​

NoSQL injection is real and underappreciated. The relational world drilled "parameterize, never concatenate" into you. The document world has its own version: operator injection. Because queries are JSON objects and request bodies are JSON, a client can smuggle a query operator where you expected a value — sending { "password": { "$gt": "" } } to Pulsely's login endpoint turns "password equals X" into "password greater than empty string," which matches everything. Fix: validate and coerce every input to its expected scalar type before it touches a query; never spread a raw request body into a query object. Strict TypeScript types and an ODM's casting help, but they do not fully protect you — a typed interface is a compile-time claim, not a runtime guard (the authority invariant again: the client's shape is a claim, not a fact).

Mongo was historically default-open, and the internet is full of exposed clusters precisely because someone skipped this list. In healthcare the stakes rise: an exposed cluster of PHI isn't just an outage, it's a reportable HIPAA breach. Enforce authentication (SCRAM or x.509), role-based access scoped per database (read/readWrite/dbAdmin, least privilege), TLS in transit, encryption at rest, and — non-negotiable — never bind Mongo to a public interface.

PHI scatters when you denormalize. Every extended-reference copy of a patient's name or MRN is a copy of protected health information spread across thousands of worklist documents. Three obligations follow, and all three are cheaper to design in than to retrofit:

  • Right to erasure / correction. When a patient's record must be purged or a name corrected, you must be able to find and fix every copy. Either track exactly where you've duplicated identity fields, or reference (don't embed) anything you'll need to delete in one place.
  • Minimum necessary. Embed only the fields the worklist actually needs to render — name, MRN, the coded result — never the whole chart. A leaked worklist document should leak as little as possible.
  • Audit. Because these documents carry PHI, every read of them is an access event your immutable audit log must record — who viewed which patient's data, not just who wrote it. A denormalized read is still an access.

Scale behavior is dominated by RAM and the shard key. Two cliffs: the working set must fit in RAM or reads fall off into random disk I/O (§4); and a hot or monotonic shard key serializes all write load onto one node while the rest of the cluster idles. A third, quieter one: large $group and $lookup stages have a ~100 MB per-stage memory limit; modern MongoDB (5.0+) spills them to disk automatically when exceeded, while older versions failed the query unless you passed allowDiskUse — either way, a stage that spills is your signal you're running analytics on your operational store, not a reflex to reach for.

Failover and the balancer compete with live traffic. During a primary election (seconds), writes pause; retryable writes mask brief blips but not real outages. A secondary that lags silently weakens your majority-durability guarantee, because "majority acked" depends on enough healthy members. And the balancer's chunk migrations contend with live traffic — schedule balancing windows and watch for jumbo chunks that refuse to move (the low-cardinality shard-key pitfall coming home to roost). Saturation here is the same chain property as ever: one slow or stuck stage backs up everything behind it.


9. Interview lens & exercises​

Interview questions​

"When would you choose MongoDB over Postgres?"

  • Junior answer: "Mongo scales better / it's schemaless / it's faster." All three are either wrong or context-free, and the answer reveals no design judgment.
  • Senior answer: answers per aggregate, by read shape, write fan-out, and transaction needs — "I'd move the clinical activity feed because it's a pre-joined read tree with unbounded write fan-out (the RPM firehose) and no cross-entity invariant, but I'd keep encounters, orders, and claims in Postgres because they need real multi-row transactions — no-double-booking on slots, exactly-once claim submission — and reporting joins" — and explicitly names what stays relational. The signal is treating it as a per-aggregate trade with stated reasons, not a database beauty contest.

"Embed or reference — vitals on an encounter?"

  • Junior: "embed everything."
  • Senior: "depends on cardinality and volatility. Subset-embed the hot 20 vitals for instant render, reference the tail in its own collection, and watch the 16 MB cap so a long-monitored patient doesn't blow the document." Reasons by the cardinality/volatility/locality test, not a blanket rule.

"How do you choose a shard key, and why is it hard to change?"

  • Junior: "shard on the id."
  • Senior: discusses cardinality (avoid low — jumbo chunks), write distribution (avoid monotonic — hotspotting), query routing (you want single-shard for the dominant read), and the fact that it's effectively a permanent partition contract whose mistake costs a live migration. Names hashed-on-providerId for a worklist and why.

"What does w: majority actually guarantee, and what does it cost?"

  • Junior: "it makes writes safe."
  • Senior: "durability across a failover — a majority of voting members acked it, so any newly elected primary necessarily has it, so it survives the loss of a single node. The cost is write latency and a dependence on a live quorum; lose the quorum and majority writes block." Connects it mechanically to the oplog and the election (and defers the formal why to the distributed-systems chapters).

"Your worklist query is slow despite an index — diagnose it."

  • Junior: "add another index."
  • Senior: runs explain("executionStats"), checks IXSCAN vs COLLSCAN, reads totalKeysExamined vs nReturned, verifies ESR field order on the compound index, then asks whether the working set still fits in RAM and whether a lagging secondary is serving stale reads. Measures the actual hop — finds out where the time is really going — before adding anything.

Exercises & the Pulsely increment​

  1. Model the worklist document three ways. Write it as (a) one document per event, (b) one bucket per clinician per day, (c) subset hot-window plus referenced tail. Build the access-pattern table (entry point, cardinality, read frequency, write fan-out, latency budget) and use it to pick the winner; justify the choice explicitly against the 16 MB cap and TTL aging. State the obligation each duplication creates.

  2. Build the worklist read as an aggregation pipeline. $match on providerId → $sort by recency → $limit → extended-reference $project. Add the compound index applying ESR, then prove IXSCAN (not COLLSCAN) with explain("executionStats") and confirm totalKeysExamined ≈ nReturned. If it scans, fix the index order and re-run — don't just add a second index.

  3. Migrate Postgres → Mongo without downtime. Dual-write the worklist from the existing relational pipeline into Mongo, backfill historical data, then cut reads over to secondaryPreferred. Measure p99 against the old five-table JOIN and write down the before/after. Note where you handled read-your-writes for the acting clinician, and where the critical-value alert lane needs the stronger path.

  4. Write both ADRs. (a) The per-aggregate store table — every Pulsely aggregate, its store, and its one-sentence reason, including the rejected alternative for the worklist. (b) The shard-key decision — candidates providerId hashed vs {providerId, createdAt} ranged vs _id, with hotspot analysis, the dominant-read routing consequence, and the resharding cost of being wrong spelled out. These two documents are the deliverable; the code is in service of them.


Key takeaways​

  • "NoSQL" means "what do I give up to scale horizontally": document gives up cross-document joins/transactions, key-value gives up querying by value, wide-column gives up ad-hoc queries, graph gives up easy sharding.
  • Relational genuinely breaks down on unbounded write fan-out, inherently pre-joined read trees, rigidly heterogeneous records, and multi-region write autonomy — together, on one aggregate. "Lots of data" and "a JSONB column" do not justify leaving Postgres.
  • Store the aggregate the way you read it. A document is a pre-joined read unit; you pay the join once at write time. Trade query flexibility for read locality only where the read shape is stable.
  • Single-document atomicity is the core invariant: make your aggregate boundary your document boundary. Cross-document transactions exist but are the expensive exception.
  • Embed owned/bounded/read-together; reference shared/unbounded/independently-queried. The named patterns — bucket, subset, extended reference, computed, outlier — are your modeling vocabulary, and every duplication signs you up for a named consistency obligation.
  • Consistency is three composable knobs — write concern, read concern, read preference — chosen per operation by the consequence of being wrong. The routine worklist reads secondaryPreferred; a claim's status and a critical-value alert do not.
  • Index by ESR (Equality, Sort, Range), diagnose with explain (IXSCAN vs COLLSCAN, keys-examined vs returned), and remember reads are fast only while the working set fits in RAM.
  • The shard key is an irreversible partition contract — choose high-cardinality, evenly distributed, for the dominant access pattern (hashed providerId for the worklist), and choose it before the collection is huge. "Schemaless" just moves the schema into your code; you own it now.

← Previous: Ch 19 — PostgreSQL Deep Dive · Up: Part IV overview · Master TOC · Next: Ch 21 — Redis Beyond Caching →