Articles
Azure Cosmos DB Interview Questions: Consistency Levels, Partition Keys, and Request Units
Prepare for Azure Cosmos DB interview questions on consistency levels, session tokens, partition keys, RU budgets, point reads, and hot-partition diagnosis.
A checkout API saves an order, returns success, and then shows an empty confirmation page. Meanwhile, the database reports throttling even though the account's average throughput looks comfortable. An Azure Cosmos DB interview can connect both symptoms: what the reader is allowed to observe, where requests land, and how much work those requests consume.
This guide focuses on Azure Cosmos DB for NoSQL. Official facts come from linked Microsoft documentation. The checkout scenario, calculations, and proposed interview answers are original practice exercises, not production measurements. No candidate reports are used, and these prompts are not presented as questions asked by a particular employer.
For the broader replication tradeoffs, start with the distributed systems interview guide. Here, the central argument is specific: choose the read guarantee, preserve the partition address, and measure request charges before choosing capacity.
What does each consistency level actually guarantee?
Official fact: Cosmos DB exposes five consistency levels. Strong gives linearizable reads; bounded staleness limits how far reads may trail writes by configured versions or time; session provides guarantees within a client session; consistent prefix preserves write order; eventual permits temporary divergence that converges when writes stop. These are different promises, not five names for replication speed. Microsoft consistency definitions.
Suppose one order changes from created to paid to shipped. Name the observation that would violate the chosen contract. A reader seeing created after payment is not automatically evidence of corruption. First establish the consistency setting, the participating session, and when each operation completed.
For our exercise, the confirmation page needs to observe its own successful write. A public aggregate may tolerate delayed updates. That suggests evaluating session consistency for the interactive flow rather than automatically demanding strong reads everywhere. This is a design inference; whether it meets the product contract depends on who must observe whose writes.
Ask a sharper follow-up: must a second device immediately see a payment written by the first device? That requirement is broader than one SDK client's session. Naming “session consistency” without defining the session boundary leaves the design unfinished.
Why can another web server miss my successful write?
Official fact: Cosmos SDK clients track session tokens. An application spread across independent web instances may need to propagate the token so a later request participates in the same session. Tokens are partition-bound. A request-level consistency override can relax the account default; it cannot strengthen a weaker account into a stronger one. Managing consistency and session tokens.
Consider this diagnostic sequence:
- Web instance A writes order
o-731for customerc-42. - The browser receives success and the application preserves the relevant session context.
- The confirmation request reaches web instance B, which has a different SDK client.
- B reads the same item address with the propagated session token.
The crucial interview question is what changes if step three loses that context. A fresh client does not automatically inherit A's read-your-writes history simply because both servers belong to the same website.
My proposed investigation checks the item ID, partition key, token propagation, requested consistency, and SDK diagnostics before changing account settings. Capture operation identifiers and timing without putting sensitive order contents into logs. Also distinguish a stale document from a wrong address: querying the wrong customer partition is a routing bug that stronger consistency cannot repair.
An application cache introduces another boundary. If the confirmation response comes from a cache populated before payment, the database may satisfy its contract while the user still sees old information. Trace the complete response path rather than treating every stale page as a replication problem.
Which partition key fits the order workload?
Official fact: A logical partition groups items with the same partition-key value. Cosmos manages physical partitions beneath that model. A regular logical partition has a 20 GB storage limit, and choosing a key affects distribution and query routing. The key cannot simply be changed in place after container creation. Partitioning documentation.
Our hypothetical service has many customers, order-detail reads, customer order-history queries, and a few unusually large merchants. Compare candidates against those operations rather than choosing the field with the largest number of distinct values.
| Candidate key | What becomes convenient | What must be challenged |
|---|---|---|
/customerId | Customer history and related order records share a key | One dominant customer can concentrate traffic and retained data |
/id | A known order has a direct address and orders distribute independently | Customer history must find orders across keys |
Synthetic customerId + bucket | Large customers can spread work across chosen buckets | History reads need bucket discovery or fan-out; related records may separate |
For this workload, I would begin by testing /customerId, then examine the largest customer's forecast rather than the median customer. The exercise does not prove that this is the correct production key. A merchant with millions of transactions may overturn the choice even when most tenants fit comfortably.
Hierarchical partition keys offer another design option, but they do not excuse ignoring the access pattern. Microsoft's guidance explicitly warns that a workload concentrated on one key can still become hot. Evaluate the full hierarchy and the queries it routes. Hierarchical partition keys.
Before accepting a bucketed design, explain how a caller computes the bucket for an existing order. If the answer is “search every bucket first,” include that lookup in the cost model. Moving complexity into an address-discovery query does not remove it.
Does a partition key also define the transaction boundary?
Official fact: A transactional batch groups operations sharing a partition key within a container, with all operations succeeding or failing together. This is a different property from the visibility guarantee selected for reads. Transactional batch operations.
Imagine storing an order and its corresponding reservation record together under customerId. That arrangement may support a useful batch for those records. It does not automatically include global inventory stored under productId in another partition.
My interview answer would draw both records and annotate their complete addresses before claiming atomicity. If the invariant spans customer orders and product stock, discuss a different data model or an explicit coordination workflow. State what happens when the second operation fails and how the system detects incomplete work.
A useful counterquestion is whether duplicate submission can create a second reservation. Read consistency alone does not define request deduplication. Keep visibility, atomicity, and application retry semantics separate so that fixing one does not create a false guarantee about another.
How do RU, RU/s, and point reads differ?
Official fact: A request unit normalizes database work across CPU, memory, and I/O. RU describes an operation's charge; RU/s describes a throughput rate. A request count is therefore not a capacity estimate unless the mix and charges of those requests are known. Request units.
A point read addresses one item using its ID and partition key through an SDK or REST operation. A SQL query filtering on those same fields is still a query. Microsoft's reference example charges 1 RU for a 1 KB point read under the weaker read consistency levels; stronger read consistency changes that cost. Do not generalize “one read equals one RU” to every item or query. Read and write cost optimization.
Here is an address illustration, not an executed SDK benchmark:
Container partition path: /customerId
Item: { "id": "o-731", "customerId": "c-42", "state": "paid" }
Point-read address: item ID o-731 + partition key c-42
Different operation: SELECT * FROM c WHERE c.id = "o-731"
In this exercise, the API response would retain both address components for subsequent reads. That small interface decision prevents an efficient detail endpoint from depending on an avoidable search.
Measure response charges on representative data. For paginated queries, total the charges for all pages needed by the operation. Returning only the first page in a benchmark changes the work being compared. Record item size, query shape, indexing, and consistency alongside the result so another engineer can reproduce the comparison.
Can you calculate a defensible throughput estimate?
The following numbers are invented inputs for an arithmetic exercise, not measured Cosmos DB prices or benchmark results. Assume representative profiling has supplied the charges shown, and all operations occur in the same one-second interval.
| Operation | Rate per second | Assumed RU per operation | RU/s contribution |
|---|---|---|---|
| Order point read | 600 | 1 | 600 |
| Customer history query, all required pages | 80 | 8 | 640 |
| Order write | 100 | 6 | 600 |
| Total | 780 | — | 1,840 |
An illustrative 30% planning margin gives 1,840 × 1.30 = 2,392 RU/s. That arithmetic is only a starting estimate. It says nothing about permitted provisioning increments, burst distribution, regional configuration, or whether one partition can serve its assigned work.
If the reference point-read component doubles under a stronger consistency choice, it contributes 1,200 RU/s instead of 600. Recalculate the query component under the new consistency too; do not double the entire workload indiscriminately, because writes are a different operation category.
In an interview, label every number as supplied, measured, or assumed. Then propose the missing experiment: replay the actual operation mix against representative data, collect per-operation charges and latency, and inspect traffic concentration. A precise multiplication with undocumented inputs is still a weak capacity answer.
Why can 429s appear below aggregate capacity?
Official fact: Rate limiting can occur when demand exceeds the relevant throughput budget. The SDK may retry 429 responses, so server throttling counts and application-visible failures are different observations. Diagnose the error context rather than assuming every 429 has the same cause. Microsoft's 429 troubleshooting guide.
For a deliberately simplified manual-throughput example, assume two physical partitions each have a 2,000 RU/s allocation. One receives 2,500 RU/s of demand and the other 500. Aggregate demand is 3,000 against 4,000 provisioned, yet the first partition exceeds its allocation.
Microsoft recommends inspecting normalized RU consumption by partition-key range to find uneven utilization. An aggregate average can hide the busiest range. Monitoring normalized RU consumption.
My diagnostic order is to compare latency and retry counts, identify the affected operations, inspect partition-level utilization, and map the busiest keys back to workload behavior. A burst from one merchant suggests a different remedy from an expensive query shared by every merchant.
Increasing throughput may buy time, while a query rewrite, better address propagation, or a partition redesign addresses the underlying work. Choose among them from the observed bottleneck. A retry policy should respect the service's delay and the application's deadline; unlimited immediate retries can turn a localized overload into a larger queue of unfinished requests.
Sources and Further Reading
- Microsoft: Consistency levels
- Microsoft: Manage consistency and session tokens
- Microsoft: Partitioning and horizontal scaling
- Microsoft: Hierarchical partition keys
- Microsoft: Transactional batch operations
- Microsoft: Request units
- Microsoft: Optimize read and write costs
- Microsoft: Troubleshoot 429 responses
- Microsoft: Monitor normalized RU consumption