Course contentsShow
← System Design
Lesson 292 of 1,9198. Database Performance OptimizationFree lesson

Embedding vs Referencing in Documents

Design document schemas with embedded data for related entities to eliminate lookups.

Embedding vs Referencing in Documents

You'll learn: How to design document schemas that embed related data directly instead of splitting it across multiple documents, eliminating expensive lookups.

The Core Idea

In document databases (like MongoDB), you have two ways to model relationships between entities: embedding and referencing.

Embedding means storing related data directly inside the parent document—like keeping all order items inside an order document. Referencing means storing only an ID pointer to another document—like storing a customer ID in an order and fetching customer details separately.

Why This Matters

Think of embedding like keeping your frequently-used spices right on your kitchen counter, while referencing is like storing them in a basement pantry—you can get to them, but it takes extra trips.

When you embed data, a single database query retrieves everything you need. When you reference, you need multiple queries or joins to assemble the complete picture, adding latency and load.

When to Embed

Embed related data when:

  • The child data is always accessed with the parent (e.g., order line items with orders)
  • The child data is small and bounded (won't grow indefinitely)
  • You need fast read performance for the complete entity

Example mental model:

// Embedded approach - one query
{
  "order_id": 12345,
  "customer_name": "Alice",
  "items": [
    {"product": "Widget", "qty": 2},
    {"product": "Gadget", "qty": 1}
  ]
}

Instead of splitting orders and items into separate collections requiring multiple lookups.

Trade-offs

Embedding trades write complexity (updating nested data) for read simplicity (one query gets everything). It works best when data is read-together and doesn't update independently often.

Key Takeaway: Embedding related entities in document schemas eliminates the need for separate lookups, dramatically improving read performance when data is accessed together—but requires careful consideration of data size and update patterns.