MongoDB Data Modeling Reviews: Embedding, Referencing, Arrays, and Document Growth
In document database engineering, the rule that data accessed together should be stored together becomes a storage-engine outage the moment relationship cardinality shifts from one-to-few to one-to-unbounded.
TL;DR
- Problem: Appending 200-byte items via
$pushinto multi-megabyte documents forces WiredTiger to reconcile and re-compress entire leaf/overflow pages every 60-second checkpoint, inflating EBS write IOPS and risking fatal 16 MBBSONObjectTooLargerejections.- Answer: Bound inline arrays with the Outlier Pattern (for power-law distributions) or Bucket Pattern / native Time Series (for continuous streams), and enforce
maxItemsin the catalog via$jsonSchema.- Watch out: Never deploy
validationLevel: "strict"before draining legacy oversized documents—start withvalidationLevel: "moderate"andvalidationAction: "warn", and pre-indexparent_idon overflow collections.
Production Scope: MongoDB 5.0 – 8.0 on AWS EC2 + EBS
gp3
Situation
Engineering teams adopt MongoDB because its JSON/BSON document model maps directly to domain objects, letting an application fetch an entity and its child attributes in a single index lookup without SQL joins. For one-to-few relationships—such as an order with three shipping addresses or a user profile with five payment methods—embedding delivers predictable single-digit millisecond latency.
In high-concurrency e-commerce, IoT telemetry, and financial event platforms, entities such as product reviews, activity feeds, and sensor readings are frequently modeled as nested arrays inside a parent document. On staging datasets, documents remain small and return in single-digit milliseconds. In production on AWS EC2 (r6g.2xlarge with 64 GB RAM and EBS gp3 volumes), active entities accumulate thousands of array entries, turning sub-kilobyte records into multi-megabyte blobs that degrade WiredTiger cache residency, shrink replica set oplog retention, and eventually hit MongoDB’s hard 16 MB BSON ceiling (16,777,216 bytes).
When a single parent document grows to several megabytes, every $push operation ceases to be a lightweight append. Instead, the storage engine’s checkpoint reconciliation loop, the replication oplog, and the B-tree index cache all pay a compounding penalty proportional to the total document size rather than the size of the newly appended element.
The Problem
Mechanics of the Unbounded Array Trap
Developers often assume $push executes an in-place incremental append on disk. In WiredTiger and MongoDB replication, appending to a large document triggers four compounding constraints:
- WiredTiger Checkpoint Write Amplification: WiredTiger stores documents in row-store B-tree leaf pages (typically 4 KB to 32 KB allocation units, with overflow pages whenever a single document exceeds page size). In-memory edits prepend a
WT_UPDATEdelta structure to the row’s atomic update chain, which appears inexpensive at write time. However, every 60 seconds (or 2 GB of journal writes), the checkpoint thread reconciles dirty pages by reading the base document, resolving the entireWT_UPDATEchain, serializing the full BSON document, compressing it with Snappy or Zstandard, and writing new extents to EBS while freeing old extents. Appending 1,000 items of 200 bytes (200 KB logical) to an 8 MB document forces ~8 MB of physical reconciliation—a40x+write amplification factor that saturates EBSgp3throughput (125 MB/s baseline). - Working Set Cache Eviction: When an application reads a parent document only to check a scalar field (like
priceorstock), WiredTiger loads the entire multi-megabyte document—including its oversized array—into the internal cache (default 50% ofRAM - 1 GB, or ~31.5 GB on anr6g.2xlarge). A handful of multi-megabyte documents evicts gigabytes of hot B-tree index pages, triggering synchronous EBS read page faults across unrelated queries. Even if the application uses a projection ({ price: 1 }),mongodmust still read the full BSON document from WiredTiger into memory unless the query is 100% covered by an index (PROJECTION_COVERED). - Oplog Window Compression and Multikey Index Amplification: Every mutation writes to
local.oplog.rs. Continuous updates to bloated documents and frequent array rewrites consume oplog bytes faster, shrinking the effective replication retention window and leaving secondaries vulnerable to falling intoRECOVERINGstate during network partitions or maintenance restarts. Worse, if any subfield inside the unbounded array is indexed, MongoDB creates a multikey index entry for every array element; a document with 10,000 array items generates 10,000 B-tree keys, turning document deletes or array rewrites into thousands of synchronous B-tree mutations and prohibiting any second array field in the same compound index (cannot index parallel arrays). - The Hard 16 MB BSON Ceiling (
16,777,216bytes): MongoDB enforces a strict 16 MB limit on any single BSON document. Once a viral entity’s array crosses 16 MB, every subsequent$pushfails withBSONObjectTooLarge—blocking writes on the highest-traffic entities in the system. Furthermore, in sharded clusters, oversized documents near 16 MB create indivisible jumbo chunks that the balancer cannot split or migrate across shards. Even before 16 MB, transferring multi-megabyte documents over EC2 ENIs consumes network bandwidth and forces larger application-heap allocations during BSON deserialization.
The core architectural question is: How can platform engineers bound document growth at the database catalog level and refactor unbounded arrays into Outlier or Bucket schemas without application write downtime?
Options Considered
| Pattern | Read Queries (99% Path) | Checkpoint Write Amp | History Retention | Decision |
|---|---|---|---|---|
| Unbounded Embedding | 1 lookup | Extreme (40x+ on multi-MB docs) | Full until 16 MB crash | Rejected: Guarantees BSONObjectTooLarge and EBS saturation |
$push with $slice: -50 | 1 lookup | Still re-encodes full doc on every $push | Discards older items permanently | Rejected for High Velocity: Loses history and still dirties pages |
| Pure Referencing (Normalized) | 2+ queries or $lookup always | Minimal (1x small child insert) | Full | Rejected: Adds extra network RTT to every common read |
| Outlier & Bucket Patterns | 1 lookup for 99% of entities | Bounded to compact ~64 KB docs | Full (overflow or sequential buckets) | Chosen: Preserves 1-query fast path while capping document size |
Unbounded embedding fails at 16 MB, $push with $slice discards historical records while still forcing full-document checkpoint rewrites on high-velocity entities, and pure referencing penalizes the 99% normal-cardinality read path with extra round trips or server-side $lookup joins. The Outlier Pattern and Bucket Pattern keep documents compact in WiredTiger cache while preserving single-query reads for the common case. When evaluating $push with $slice, remember that $slice only caps the logical array length in BSON; if an entity receives hundreds of $push updates per minute, WiredTiger still reconciles and re-compresses the entire document page every checkpoint cycle.
The Bounded Document Architecture: Outlier and Bucket Patterns
Choosing between Outlier and Bucket depends on whether the workload is power-law entity growth (most entities small, a few massive) or continuous sequential streams (all entities append indefinitely).
flowchart TD
WriteReq["Application Write — Append Item ($push)"] --> Gate{"Modeling Pattern Gate"}
Gate -->|Unbounded Array| Unbounded["Single Document — Grows to 16 MB"]
Unbounded --> Crash["Checkpoint Amplification & BSONObjectTooLarge"]
Gate -->|Continuous Stream| Bucket["Bucket Pattern — Fixed 500 Items per Doc"]
Bucket --> Compact["Predictable ~64 KB Doc & Tiny Oplog Deltas"]
Gate -->|Power-Law Outliers| Outlier["Outlier Pattern — has_outlier_overflow flag"]
Outlier --> Inline["First 50 Items Inline in Parent"]
Outlier --> Overflow["Extras Routed to reviews_overflow Collection"]
1. The Outlier Pattern for Power-Law Distributions
In e-commerce catalogs and social feeds, 99% of items have fewer than 50 child records while 0.1% of viral items accumulate tens of thousands. Under the Outlier Pattern:
- Keep up to 50 recent items inline in the parent document alongside
has_outlier_overflow: false. - Once the inline array reaches 50 items, set
has_outlier_overflow: trueand insert all subsequent items as standalone documents in a dedicatedproducts_reviews_overflowcollection indexed on{ parent_id: 1, created_at: -1 }. - Standard product page reads execute a single
findOneonproducts; only outlier pages wherehas_outlier_overflowistruetrigger a paginated query against the overflow collection. For deep pagination inside the overflow collection, use keyset pagination ({ parent_id: id, created_at: { $lt: last_ts } }) backed by{ parent_id: 1, created_at: -1 }rather thanskip(), which scans and discards skipped index entries on every page. - To prevent the parent document and overflow collection from drifting during network failures, either update
has_outlier_overflowand insert the overflow document inside a multi-document ACID transaction, or run an idempotent reconciler that scans forreviews.49existing without a matching overflow flag.
2. The Bucket Pattern for Continuous Event Streams
For IoT telemetry, audit trails, or financial event streams, group measurements into fixed-capacity buckets (e.g., 500 readings or 1 hour per document) with pre-aggregated summary metrics (temp_min, temp_max, temp_avg):
{
"_id": "DEVICE_9912_B_0042",
"device_id": "DEVICE_9912",
"bucket_id": 42,
"count": 500,
"metrics": { "temp_min": 68.2, "temp_max": 74.5, "temp_avg": 71.3 },
"readings": [ { "ts": ISODate("2026-05-01T00:00:01Z"), "val": 71.2 } ]
}
When count reaches 500, the writer opens bucket_id: 43 (using an atomic findOneAndUpdate with upsert: true filtered on { device_id: "DEVICE_9912", count: { $lt: 500 } }). Older buckets become immutable on disk, keeping active WiredTiger leaf pages compact (~64 KB) and oplog entries tiny. Pre-aggregating metrics inside each bucket also lets dashboard queries read summary statistics without scanning individual readings arrays.
Sizing the bucket capacity is an explicit tradeoff between index B-tree reduction and WiredTiger checkpoint cost. If each event is ~120 bytes, 500 events per bucket yields ~60 KB BSON documents and reduces index B-tree entries by 500x compared to one document per event; pushing bucket size to 10,000 events (~1.2 MB) reintroduces multi-page checkpoint rewrites, whereas shrinking buckets below 50 events increases index overhead. For pure time-series workloads on MongoDB 5.2+, native Time Series collections automate this bucketing internally with columnar compression (delta, delta-of-delta, RLE, object, and 6.0+ array compression) inside buckets, provided metaField cardinality stays bounded. For custom bucket or overflow collections with monotonically ordered keys on MongoDB 5.3+, creating the collection with clusteredIndex: { key: { _id: 1 }, unique: true } stores documents directly inside the _id B-tree leaf pages, eliminating the secondary _id index lookup on range scans.
Diagnostic Telemetry: BSON Size Sampling and reslen Auditing
Sample document BSON sizes with Object.bsonsize() before enforcing schema caps, and compare against db.products.stats().avgObjSize:
db.products.aggregate([{ $sample: { size: 1000 } }]).forEach((doc) => {
const bytes = Object.bsonsize(doc);
if (bytes > 2 * 1024 * 1024) {
print(`_id=${doc._id} sizeMB=${(bytes / 1048576).toFixed(2)} reviews=${(doc.reviews || []).length}`);
}
});
Because avgObjSize hides power-law skew when 99% of documents are 2 KB and 0.1% are 14 MB, $sample combined with Object.bsonsize() exposes the heavy tail. Pair sampling with mongod.log reslen filtering to catch oversized payloads already hitting the wire and consuming network egress:
grep "Slow query" /var/log/mongodb/mongod.log \
| jq -r 'select(.attr.reslen > 2097152) | {ns: .attr.ns, reslen_mb: (.attr.reslen / 1048576), ms: .attr.durationMillis}'
Engine-Level Enforcement via $jsonSchema
Enforce array bounds in the catalog with collMod so batch jobs and microservices cannot bypass application validation:
db.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["sku", "title"],
properties: {
reviews: { bsonType: "array", maxItems: 50 },
has_outlier_overflow: { bsonType: "bool" }
}
}
},
validationLevel: "moderate",
validationAction: "warn"
});
Automated Overflow Auditor (mongo_doc_auditor.py)
#!/usr/bin/env python3
import argparse, time
from bson import BSON
from pymongo import MongoClient
def migrate_overflow(client, namespace, array_field, max_items, dry_run):
db_name, coll_name = namespace.split(".", 1)
db = client[db_name]
src, dst = db[coll_name], db[f"{coll_name}_{array_field}_overflow"]
for doc in src.find({f"{array_field}.{max_items}": {"$exists": True}}):
arr = doc.get(array_field, [])
print(f"_id={doc['_id']} items={len(arr)} bytes={len(BSON.encode(doc))}")
if dry_run:
continue
dst.insert_many([{"parent_id": doc["_id"], "idx": max_items + i, "payload": v} for i, v in enumerate(arr[max_items:])])
src.update_one({"_id": doc["_id"]}, {"$set": {array_field: arr[:max_items], "has_outlier_overflow": True}})
time.sleep(0.05) # Throttle writes to protect oplog window
How It Rolls Out
- Phase 1 — Index Overflow Collection & Audit: Pre-create
{ parent_id: 1, idx: 1 }(or{ parent_id: 1, created_at: -1 }) on the overflow collection, and run the dry-run auditor ({ "reviews.50": { $exists: true } }) to count oversized documents. Checkingreviews.50via$exists: trueuses dot-notation array indexing without downloading the full array payload across the network. - Phase 2 — Deploy
moderate+warnValidation: Apply$jsonSchemawithvalidationLevel: "moderate"andvalidationAction: "warn". Invalid writes succeed while logging detailed violation warnings tomongod.logso you can catch un-updated writers. UndervalidationLevel: "moderate", MongoDB only enforces schema rules on inserts and on updates to documents that already satisfied the validator prior to the update; legacy documents that already exceed 50 items remain exempt from themaxItems: 50check during unrelated scalar updates (such as inventory or price changes) until their arrays are drained below 50. - Phase 3 — Throttled Backfill & Code Cutover: Deploy application code that routes items past 50 to the overflow collection, then run the throttled migrator (
time.sleepbetween batches) while watching secondary replication lag. Never run unthrottledupdateManyloops across millions of documents, as the resulting oplog surge can exhaustlocal.oplog.rsretention. - Phase 4 — Enforce
errorandstrict: SwitchvalidationActionto"error"(which returns Error 121DocumentValidationFailurewitherrInfo.detailspinpointingschemaRulesNotSatisfiedandpropertiesNotSatisfied). Once zero legacy documents exceedmaxItems, promotevalidationLevelto"strict". Rollback: setvalidationAction: "warn"viacollMod.
In Practice
Documented MongoDB and WiredTiger storage behaviors govern both the write-amplification problem and the remediation tradeoffs:
- WiredTiger Page Reconciliation: Per WiredTiger’s row-store architecture, updates to an in-memory document append
WT_UPDATEdeltas, but checkpoint reconciliation re-serializes and re-compresses the full document leaf/overflow page on disk. Bounding documents to compact sizes via Outlier or Bucket patterns directly reduces the number of bytes reconciled per checkpoint and prevents single documents from occupying overflow pages. Keeping documents compact also preserves WiredTiger cache capacity for hot B-tree index pages rather than caching multi-megabyte historical arrays. - Oplog Retention & Batch Pruning: Because
local.oplog.rsrecords every document mutation, unthrottled batch scripts trimming millions of oversized arrays can flood the oplog and shrink retention hours for secondaries. Rate-limiting migration batches and monitoringrs.status()lag preserves replication headroom. - MongoDB 5.2+ – 8.0 Schema & Time Series Features: MongoDB 5.2+ added columnar bucket compression (delta, delta-of-delta, RLE, object, and 6.0+ array compression) for native Time Series collections, and MongoDB 5.3+ added Clustered Collections (storing documents in
_idB-tree order to eliminate separate_idindex lookups on bucketed range scans). On schema enforcement, MongoDB returns structurederrInfo.details(schemaRulesNotSatisfied,propertiesNotSatisfied) on Error 121DocumentValidationFailure, while MongoDB 8.0 slow logs surfaceworkingMillisalongsidetotalTimeQueuedMicrosto separate validation CPU cost from lock-queue wait time.
Where It Breaks
| Operational Pattern | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
validationLevel: "strict" Too Early | Enforcing maxItems while legacy oversized docs exist. | Unrelated writes to legacy docs fail with Error 121. | Start with "moderate" + "warn", drain arrays, then tighten. |
| Unindexed Overflow Foreign Keys | Missing index on parent_id in overflow collection. | Paginated overflow reads trigger COLLSCAN. | Pre-build { parent_id: 1, created_at: -1 } before cutover. |
| In-Memory Bucket Merging | App loads 50 buckets into RAM before paginating. | Spikes JVM/Node.js heap and GC pauses. | Stream cursors and paginate at bucket boundaries. |
| Oversized Docs in Sharded Clusters | Multi-MB documents prevent chunk splitting. | Creates indivisible jumbo chunks and shard skew. | Bound document growth before enabling sharding. |
| Outlier Flag Desync | has_outlier_overflow: true set without overflow insert. | UI shows “Load More” that returns empty results. | Wrap parent update + overflow insert in a transaction or idempotent job. |
| Unthrottled Batch Array Trimming | Script trims millions of arrays at full speed. | Oplog surge pushes secondaries into RECOVERING. | Rate-limit batches and monitor secondary lag continuously. |
$push with $slice High Velocity | Assuming $slice: -50 avoids checkpoint rewrites. | Still reconciles and re-compresses the document on disk. | Use Bucket Pattern or Time Series for append-heavy streams. |
High-Cardinality metaField | Time Series metaField has millions of unique values. | Proliferates internal buckets and exhausts WT cache. | Keep metaField bounded to low/medium-cardinality entity IDs. |
Key Takeaways
- WiredTiger checkpoints rewrite full document pages: Even small
$pushdeltas force full-document reconciliation and compression on disk, amplifying EBS IOPS on multi-megabyte records. - 16 MB BSON is a hard cliff: Unbounded arrays inevitably fail with
BSONObjectTooLargeon your highest-value, most active entities. - Match pattern to cardinality: Use the Outlier Pattern for Zipfian power-law entities and the Bucket Pattern (or native Time Series) for continuous event streams.
- Roll out
$jsonSchemain stages: Start withvalidationLevel: "moderate"andvalidationAction: "warn", pre-index overflow collections, and throttle legacy array draining to protect the oplog.
What to Do Next
- Problem: Identify collections with unbounded arrays that drive WiredTiger checkpoint write amplification, cache eviction, and
BSONObjectTooLargerisk. - Solution: Refactor power-law arrays to the Outlier Pattern, move continuous event streams to the Bucket Pattern or native Time Series, and enforce
maxItemsvia$jsonSchema. - Proof: Run
Object.bsonsize()across$samplebatches and filtermongod.logforreslen > 2097152(2 MB). - Action: Audit your top three write-heavy collections this week, deploy
validationLevel: "moderate"+"warn"on any array-bearing schema, and pre-index overflow collections before migrating legacy records.