Database / Azure Cosmos DB interview questions
How do you model one-to-many relationships in Cosmos DB?
Cosmos DB is a document database with no foreign key enforcement and no JOIN between containers, so one-to-many relationship modeling requires deliberate design decisions based on your access patterns. There are three main strategies, each with different tradeoffs:
1. Embedding (denormalization) — Store the "many" items directly inside the "one" parent document as an array. A blog post with its comments embedded:
{
"id": "post-101",
"title": "Cosmos DB tips",
"comments": [
{ "id": "c1", "text": "Great post!", "author": "alice" },
{ "id": "c2", "text": "Helpful!", "author": "bob" }
]
}This is ideal when the "many" side is small, always accessed with the parent, and not queried independently. One point read fetches everything. Avoid this when the array can grow unboundedly — it could approach the 2 MB per-item limit and degrade write performance as every comment addition rewrites the entire document.
2. Referencing with cross-container lookup — Store comments in a separate container with postId as the partition key. The post document contains only an ID reference. Query comments by WHERE c.postId = 'post-101'. Suitable when comments are numerous, independently paginated, or subject to independent TTL. The tradeoff: two operations to fetch a post with its comments.
3. Denormalized buckets (time-bounded embedding) — A hybrid that bounds the array size by grouping related items into "bucket" documents (e.g., one document per month of comments per post). Each bucket holds up to N comments, new buckets are created as limits are hit. More complex but avoids both the unbounded growth problem and the separate container overhead for read-heavy data.
The right model depends almost entirely on: how often the relationship is read together vs. independently, how large the "many" side can grow, and which side drives the query access pattern.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
