For an order, one rule decides it: embed what you read together, reference what must stay current, and copy values that belong to the moment of purchase, like the price paid. In our test, one order stored as a document read in 1 query, while renaming one popular product rewrote 1,178 order documents and changed 1 row in normalized tables.
What embed and reference mean
Embedding stores related data inside its parent record. An order document holds the customer, the shipping address and every line item, with each product name copied in. Referencing stores an ID that points to a record kept elsewhere, so the order line holds a product ID and the name lives once, in the products table. MongoDB's own modeling guide says the same: embed data that is queried together, reference data that grows without bounds.
Reading one order
We built the same shop twice from a fixed seed: 10,000 orders, 500 products and 2,000 customers, in two in-memory SQLite databases, one captured run on an Apple M2 Pro with Node v22.13.1. Reading one full order:
- Document, fetch by key then parse the JSON: 1 query, median 4.2 microseconds
- One join across five tables: 1 query, median 18.2 microseconds
- Five separate queries: 5 queries, median 17.9 microseconds
On one machine with no network, the document read took about a quarter of the join time, and all three are tiny next to a round trip. At an assumed 0.5 ms per round trip, the document and the single join cost about 0.50 ms per order, while the five query pattern costs 2.52 ms.
What a rename costs
The most popular product, Classic Charger 1, appears in 1,178 of the 10,000 orders. Renaming it in normalized tables changed 1 row, because the name lives in one place. In order documents, every copy had to be rewritten: 1,178 documents read, changed and written back, 719.1 KiB of JSON handed to the update. A helper table indexed on product and order ID found the matching orders without scanning every document.
Which fields to copy
The rename only hurts if old orders must show the current name. Often they should not. Line items and quantities belong to the order, so embed them. The price paid is a snapshot at checkout, so copy it into the order and old receipts keep the old price. A customer's current email is live data, so reference it: a stale copy there is a bug.
Our take
Store an order as one document when the app mostly reads whole orders, and keep inside it the fields that belong to that order or to the moment it was placed. Point to anything that must stay current everywhere. When the same data is read far more than it changes, start from what the app does most, and let that pick the shape.
Read the full article with the test setup, the rename table and the limits: https://systemdesignsimple.com/embed-vs-reference-order-document/
Top comments (0)