Highlights

Contents

Part III
03

Document stores: MongoDB

We keep related values together when readers and writers use them together. Flexible shape does not remove growth limits, invariants, or migration work. We will choose aggregate boundaries, compare embedding with references, and trace index maintenance.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Access-pattern-drivendesign2Key-value stores: Redis,DynamoDB3Document stores: MongoDB4Wide-column: Cassandra,Bigtable5Graph databases and SQLvs NoSQL6Eventual consistency andquorums7Case study: a completedata model

#Section 11Document aggregates

A viewer opens a clip and needs its title, owner, thumbnail key, and available encodings. A document store keeps named fields and nested values in one record. An aggregate is the bounded group of values the application treats as a useful read or update unit.

Keeping the clip’s encoding metadata together makes the common lookup local. Heron’s illustrative document has an 800-byte base and three 200-byte variant descriptors, totaling 800+3×200=1,400800+3\times200=1,400 bytes. These are metadata descriptors, not the video files themselves. Object storage owns the large media bytes.

The aggregate boundary should follow ownership and lifecycle. A variant descriptor belongs to the clip and normally disappears with it. A shared owner profile has its own updates and can outlive the clip, so copying every profile field creates another propagation problem. A reference preserves that independent ownership.

MongoDB writes are atomic at the single-document level, and it also supports multi-document transactions under its documented conditions. Those facts do not make every related value a good embedding candidate. MongoDB atomicity documentation explains the operation boundaries. Choose a bounded aggregate first, then check the invariants that remain outside it.

A DOCUMENT KEEPS ONE OWNED AGGREGATE TOGETHERA DOCUMENT KEEPS ONE OWNED AGGREGATE TOGETHER{ clip: c9, title: ..., owner: ..., thumbnail_key: ..., variants: [ encoding A, encoding B ]}owned child datathe boundary follows ownership and bounded growth
Figure 4.11Illustrative clip metadata groups owned fields; the computed three-variant document is 1,400 bytes.

#Section 12Embedding versus references

A clip accumulates comments long after upload. Embedding every comment makes a single read convenient at first, but the collection grows independently. Embedding stores a related value inside its owning document. A reference stores an identifier used to find a separate record.

Assume 100,000 illustrative comments of 200 bytes each beside an 800-byte base. The embedded payload becomes 800+100,000×200=20,000,800800+100,000\times200=20,000,800 bytes. Even before product limits, reading or updating a growing aggregate changes the working set and write contention. An independently paged comment collection avoids loading the whole history for a clip overview.

Embedding is useful when values are bounded, read together, and updated within the same ownership boundary. References are useful when values grow independently, have many owners, or change under a separate lifecycle. MongoDB data-modeling guidance describes these tradeoffs; the decision still depends on Heron's concrete access patterns.

A reference adds another access path, so plan the read. Batch the comment-owner identifiers instead of blindly making one remote lookup per comment. If a page requires a consistent relationship snapshot, state how the database or application provides it. Splitting records removes one growth problem while introducing coordination and lookup work.

EMBED WHAT IS OWNED AND BOUNDED; REFERENCE WHAT GROWSEMBED WHAT IS OWNED AND BOUNDED; REFERENCE WHAT GROWSclip documentbase fields 800 Bvariant 1: 200 Bvariant 2: 200 Bvariant 3: 200 B800 + 3 × 200 = 1,400 Bcomments: separate, paged records100,000 × 200 B = 20,000,000 Beach comment points at clip idthe metadata document is not the video bytes
Figure 4.12Illustrative bounded encoding metadata is compared with an independently growing comment collection.

#Section 13Schema evolution without surprise readers

A clip title changes from a string field to a translated-title map. Old readers still expect a string. Schema evolution changes stored shape or meaning while readers and writers continue to operate. The database's flexibility does not automatically make incompatible application versions agree.

Begin with a reader that accepts the old and new representations. Then deploy a writer for the new representation, migrate old records in a bounded background process, and verify that no unsupported old records remain before removing compatibility. During the overlap, define which representation wins when both exist.

Store a schema version when it helps distinguish meaning, but do not treat the number as the migration itself. A reader must actually interpret each supported version. Defaults need care: an absent visibility field may mean legacy public content, unknown content, or a malformed record. Choose the meaning before filling the field.

A migration can be retried after failure, so make each transformation idempotent and preserve source identity. Count progress by source records rather than attempted writes. Heron should also reject unsupported future shapes safely, because a rollback may encounter records written by the newer version. Compatibility includes deployment reversal, not just forward migration.

FOUR DEPLOY STATES: READ BOTH, WRITE NEW, BACKFILL, THEN DROP OLDFOUR DEPLOY STATES: READ BOTH, WRITE NEW, BACKFILL, THEN DROP OLD1 reader readsv1 and v22 writersemit v23 backfillrewrites v14 removev1 supportv1 recordv2 recorda rollback must still read v2 recordsbackfill is idempotent and counts progress by source record
Figure 4.13Illustrative compatible reader, new writer, backfill, and removal form distinct deployment states.

#Section 14Secondary indexes and write amplification

A viewer asks for clips owned by a scorer, but only knows the owner identifier. A secondary index provides another lookup path using fields other than the base key. Its entries point to records or include selected fields needed by the query.

Heron can order clips by owner and creation time, then page through that owner's range. Assume 100,000 illustrative entries of 40 bytes each. One index adds 4,000,000 payload bytes; two add 8,000,000 before structural overhead and replicas. This index-entry size is an input to the exercise, not a product benchmark.

An update that changes indexed values may remove old entries and add new ones. For an illustrative record with two affected indexes, count one base update plus two removals and two additions, or five logical mutations. Actual implementations may batch or represent those mutations differently, but the maintenance obligation remains.

A distributed index can use a different key and freshness boundary from the base store. A fresh base record does not establish that a query through a stale index finds it. State whether the index is authoritative enough for the query, whether missing results are tolerated, and how deletions and repairs propagate to its entries.

AN OWNER-AND-TIME INDEX FINDS CLIP IDS, THEN THE BASE STORE FETCHES CLIPSAN OWNER-AND-TIME INDEX FINDS CLIP IDS, THEN THE BASE STORE FETCHES CLIPSowner=ana, last 7 daysindex (owner, time)ana · 10-01c41ana · 10-02c57ana · 10-03c63ben · 10-01c12idsclip recordsthe index has its own freshness: a new clip can be in the base storeand not yet in the index
Figure 4.14Illustrative owner-and-time index locates clip identifiers before base-record retrieval.
CHANGING ONE INDEXED FIELD COSTS FIVE WRITESCHANGING ONE INDEXED FIELD COSTS FIVE WRITESclip c41owner: ana→ owner: ben1 base updateindex A (owner, time)ana · c41ben · c41index B (owner, title)ana · c41ben · c412 removals + 2 additions1 + 2 + 2 = 5 logical mutations
Figure 4.15Illustrative two-index key change requires five logical mutations including the base update.

#Section 15Building an index while writes continue

Heron adds an owner-and-time view after clips already exist. Backfill populates a new derived structure from existing authoritative records. A scan alone is insufficient when new writes continue, because records can change after their scanned position or appear after the scan's boundary.

Take a consistent source boundary, begin recording changes from it, scan existing records, and apply captured changes in version order. The exact snapshot and change-stream mechanism depends on the source. The invariant is that every relevant source state after the boundary has a route into the new view.

An illustrative 100,000-record scan at 1,000 records per second takes 100 seconds. If 20 new updates per second continue, 2,000 updates arrive during the scan. Replaying at 1,000 per second while new updates continue at 20 gives spare rate 980; clearing that backlog takes 2,000/980=2.04082,000/980=2.0408 seconds, rounded to four decimals.

Do not route readers merely because the scan completed. Verify source coverage, captured-change progress, version ordering, and a known readiness boundary. Compare selected query results with the authoritative source. Keep the old read path until the new one meets its correctness and performance contract, and retain a rebuild plan for a missed update.

A 100 S SCAN LEAVES 2,000 CHANGES; 980/S SPARE CLEARS THEM IN 2.0408 SA 100 S SCAN LEAVES 2,000 CHANGES; 980/S SPARE CLEARS THEM IN 2.0408 Ssourcescan 100 snew viewmeanwhile 20 changes/s20 × 100 = 2,000 waitingreplay 1,000/s− new 20/s980/s spare2,000 ÷ 980 = 2.0408 sthen verify coveragebefore routing reads
Figure 4.16Illustrative 100-second scan accumulates 2,000 updates; catch-up uses spare replay capacity, not total replay rate.