Database / Azure Cosmos DB interview questions
What are Cosmos DB materialized views and how do they differ from containers?
Cosmos DB materialized views (in preview as of 2024) are automatically maintained read-only containers that are derived from a source container via a defined query or projection. When data changes in the source container, Cosmos DB updates the materialized view automatically and asynchronously — similar to how the analytical store works but for operational read patterns rather than analytical ones.
The problem they solve: Cosmos DB forces you to choose a single partition key per container. If your source container is partitioned by /userId (efficient for user-centric queries), a query like "find all orders for product X" becomes a cross-partition scan. Without materialized views, you have to either build a Change Feed processor that maintains a second container keyed by /productId, or accept the expensive cross-partition query.
With materialized views, you declare the derived container's partition key and projection, and Cosmos DB handles the Change Feed-based maintenance automatically:
// Source container: partitioned by /userId
// Materialized view: same data partitioned by /productId
{
"materializedViewDefinition": {
"sourceCollectionName": "orders",
"definition": "SELECT c.id, c.productId, c.userId, c.amount FROM orders c",
"partitionKey": { "paths": ["/productId"] }
}
}Key differences from a regular container:
- Materialized views are read-only — writes go only to the source container.
- They are automatically maintained — no Change Feed processor code required.
- They may have a short lag between source write and view update (eventual consistency).
- Storage and throughput for the view are billed separately.
Compared to manually maintaining a secondary container via the Change Feed, materialized views eliminate significant operational code and failure-handling complexity.
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...
