Cosmos DB Consistency Models

Watch the video to deepen your understanding.
SubscribeComplete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
Lesson: Azure Cosmos DB Consistency Models
Introduction: The CAP Theorem in Practice
In distributed database systems, we often encounter the CAP Theorem, which states that a system can only simultaneously provide two of three guarantees: Consistency, Availability, and Partition Tolerance. Because cloud databases like Azure Cosmos DB must be partition-tolerant to scale globally, developers are left with a trade-off: Consistency vs. Availability.
Cosmos DB offers a unique "spectrum" of five well-defined consistency models. Unlike traditional databases that offer only "Strong" or "Eventual" consistency, Cosmos DB allows you to choose the exact balance that fits your application’s specific requirements. Understanding these models is critical for optimizing performance, latency, and data integrity.
The Five Consistency Models
1. Strong Consistency
Strong consistency guarantees that a read will always return the most recent committed version of an item. A client will never see an uncommitted or partial write.
- Use Case: Financial transactions, inventory management where stock levels must be exact.
- Trade-off: Higher latency and lower availability if the global replication process is interrupted.
2. Bounded Staleness
Data reads may lag behind writes by a user-specified "window" (either by time or by the number of operations).
- Use Case: Applications where a slight delay is acceptable, but the order of operations must be preserved (e.g., social media feeds or sensor data streams).
3. Session Consistency (Default)
This is the most popular model. It provides "read-your-own-writes" guarantees within a single client session. Other sessions might see slightly older data, but the current user always sees their own latest updates.
- Use Case: User profiles, shopping carts, or any application where the user expects their immediate actions to be reflected.
4. Consistent Prefix
Updates are returned in the order in which they were committed. You might not see the latest update, but you will never see an out-of-order update.
- Use Case: Activity logs or messaging apps where the sequence of events is more important than real-time absolute freshness.
5. Eventual Consistency
There is no ordering guarantee. Eventually, all replicas will converge, but reads may return stale data or data out of sequence.
- Use Case: Counting likes on a post, analytics dashboards, or non-critical logging.
- Trade-off: Highest performance and lowest latency.
Practical Implementation
In Azure Cosmos DB, you can configure the default consistency at the account level, but you can also override it on a per-request basis using the SDK.
Configuring in .NET SDK
When performing a read operation, you can specify the ConsistencyLevel to ensure your application behaves as expected for that specific request.
ItemRequestOptions requestOptions = new ItemRequestOptions
{
// Override the account default for this specific read
ConsistencyLevel = ConsistencyLevel.Session
};
ItemResponse<Product> response = await container.ReadItemAsync<Product>(
"id123",
new PartitionKey("category1"),
requestOptions
);
Note: You cannot request a consistency level stronger than what is configured for the account. For example, if your account is set to "Eventual," you cannot request "Strong" consistency for an individual query.
Best Practices
- Start with Session Consistency: For 90% of applications, Session Consistency provides the perfect balance of performance and predictability. It is the default for a reason.
- Use Strong Consistency Sparingly: Strong consistency requires synchronous replication across regions. This significantly increases "Request Units" (RUs) consumption and latency. Only use it when business logic strictly dictates it.
- Monitor Your Staleness: Use the "Observed Staleness" metric in Azure Monitor to determine if your Bounded Staleness window is too tight or too loose for your application's needs.
- Consider the Global Footprint: If your application is deployed across multiple continents, realize that "Strong" consistency will force your users to wait for a round-trip across the globe to confirm a write, which will drastically degrade the user experience.
Common Pitfalls
- Assuming "Strong" is always better: Many developers default to Strong Consistency thinking it is "safer." In a distributed system, this can lead to application timeouts and high costs. Always ask: "Does the user actually need to see this update 50ms after they clicked submit?"
- Ignoring Session Tokens: When using Session Consistency, the SDK manages a "Session Token." If you are building a stateless web API, you must pass this token between the client and the server (usually via headers) so the server can maintain the session consistency guarantee across different HTTP requests.
- Misinterpreting Eventual Consistency: Developers often confuse Eventual Consistency with "data loss." Data is not lost; it is simply not yet replicated to the node you are reading from.
Key Takeaways
- Consistency is a spectrum: It is not a binary choice. Cosmos DB allows you to pick the level that matches your specific feature requirements.
- Performance Impact: As you move from Eventual toward Strong consistency, read/write latency increases, and throughput (RUs) requirements rise.
- Session Consistency is the Gold Standard: It provides the best user experience for web and mobile apps by ensuring users see their own updates immediately.
- Account vs. Request: You set the default for the account, but you can request lower (but not higher) levels of consistency per request to optimize specific operations.
This lesson is part of the "Design Data Storage Solutions" module. Ensure you have the Azure Cosmos DB emulator installed if you wish to test these consistency models locally.
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles your daily points limit so you progress twice as fast, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× daily points limit
- ✓ Distraction-free lessons