🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cosmos DB Partitioning, Indexing, and Change Feed Patterns

Azure Data EngineeringCosmos DB Deep Dive⭐ Premium
Azure Data Engineering

The partition key decision you cannot easily undo

14 min readđŸ”ŦAdvanced

Prerequisites

  • !Cosmos DB containers, items, and Request Units
  • !RU per second provisioning and autoscale
  • !NoSQL query basics and cross-partition semantics

What You'll Learn

  • 1Evaluate candidate partition keys against cardinality and growth limits
  • 2Design indexing policies that cut RU cost without breaking queries
  • 3Build a change feed consumer with correct checkpointing behavior
  • 4Configure multi-region writes and understand conflict resolution

Partition keys: cardinality, growth, and the 10 GB rule

Cosmos DB stores items in logical partitions, all items sharing one partition key value. Each logical partition is capped at 20 GB of storage, and each physical partition is provisioned with up to 10,000 Request Units per second; the service splits physical partitions automatically as they fill, but it cannot split a logical partition. So the partition key must satisfy three constraints simultaneously: enough distinct values to spread load (high cardinality), an even distribution so no single value absorbs a hot slice of traffic, and a growth ceiling so no single key ever approaches 20 GB of items.

The interview trap is a key that looks reasonable on day one. A partition key of order_status works when you have four statuses and a thousand orders, then collapses the day one customer becomes a platinum VIP whose status value alone drives 5 percent of traffic. A partition key of customer_id is excellent if you have millions of customers each with bounded order history, and terrible if your top ten enterprise accounts each hold five million orders. The only way to choose responsibly is to estimate both cardinality and per-key growth from real data, then test with a representative load before committing, because repartitioning after launch means a full data migration.

python
from azure.cosmos import CosmosClient, PartitionKey
from azure.identity import DefaultAzureCredential

client = CosmosClient(
    "https://cosmos-dataeng.documents.azure.com:443/",
    DefaultAzureCredential(),
)
db = client.get_database_client("orders")

# Container with an explicit partition key path
container = db.create_container(
    id="orders",
    partition_key=PartitionKey(path="/customer_id"),
    offer_throughput=4000,
)

def estimate_key_skew(container, sample_size=10000) -> dict:
    """Sample items and report the share held by the top 1 percent of keys."""
    query = """
        SELECT TOP @n c.customer_id
        FROM c
    """
    seen = {}
    for item in container.query_items(
        query=query.replace("@n", str(sample_size)),
        enable_cross_partition_query=True,
    ):
        key = item["customer_id"]
        seen[key] = seen.get(key, 0) + 1

    total = sum(seen.values())
    top = sorted(seen.values(), reverse=True)
    top_one_pct = sum(top[: max(1, len(top) // 100)])
    return {
        "distinct_keys": len(seen),
        "items_sampled": total,
        "top_1pct_share_pct": round(100.0 * top_one_pct / total, 2),
        "max_items_per_key": top[0] if top else 0,
    }

print(estimate_key_skew(container))

A top-one-percent share above roughly 20 percent in the sample is a warning that traffic concentrates; investigate whether that concentration is real business behavior or an artifact of your key design before you provision throughput.

Indexing policies that stop paying for unused paths

By default Cosmos DB indexes every path in every item, which is convenient and expensive. Every indexed path adds write amplification: each insert or update must maintain the index trees, consuming RU on the write path even when nobody queries that field. For a write-heavy ingest container, excluding the large blob or log fields you never filter on can cut write RU by thirty percent or more. The indexing policy is declarative JSON that you version alongside your schema, and it is one of the few container settings that is genuinely cheaper to tune early.

Composite indexes deserve special attention. A query filtering on two properties and ordering by both will, without a composite index, resort to a cross-partition sort that consumes dramatically more RU and has higher tail latency. If your queries regularly filter by sale_date and customer_id together, declare the composite pair. The cost is modest write amplification; the payoff is a query that runs in single-digit milliseconds instead of hundreds.

{
  "indexingPolicy": {
    "automatic": true,
    "indexingMode": "Consistent",
    "includedPaths": [
      {
        "path": "/*",
        "indexes": [
          { "kind": "Range", "dataType": "String", "precision": -1 },
          { "kind": "Range", "dataType": "Number", "precision": -1 }
        ]
      }
    ],
    "excludedPaths": [
      { "path": "/_etag" },
      { "path": "/payload/*" },
      { "path": "/diagnostics/*" }
    ],
    "compositeIndexes": [
      [
        { "path": "/sale_date", "order": "ascending" },
        { "path": "/customer_id", "order": "ascending" }
      ],
      [
        { "path": "/status", "order": "ascending" },
        { "path": "/created_at", "order": "descending" }
      ]
    ]
  }
}

Change feed: the durable audit log you already have

Every write to a Cosmos DB container produces a change feed entry, an ordered, append-only log of creates, updates, and deletes per logical partition. Unlike a message broker, the change feed is not something you provision; it exists automatically and persists for as long as the container exists. That makes it the natural backbone for event-driven architectures: project the feed into a Delta table for analytics, trigger a notification on specific item types, or keep a search index in sync, all without poll source systems.

The critical design decision is checkpointing. Each change feed reader tracks a continuation token, and how you persist that token determines your delivery semantics. Store it after each batch for at-least-once delivery, which is correct for almost every projection scenario because the downstream write is idempotent. Never claim exactly-once from the change feed alone; if your consumer crashes between processing and checkpointing, the batch will be delivered again. Design the sink to tolerate duplicates, using upserts keyed on the item ID rather than blind inserts.

python
from datetime import datetime, timedelta, timezone
from azure.cosmos import CosmosClient, PartitionKey
from azure.identity import DefaultAzureCredential
import json, time

client = CosmosClient(
    "https://cosmos-dataeng.documents.azure.com:443/",
    DefaultAzureCredential(),
)
container = client.get_database_client("orders").get_container_client("orders")

CHECKPOINT_FILE = "change_feed_checkpoint.json"

def load_checkpoint() -> str | None:
    try:
        with open(CHECKPOINT_FILE) as f:
            return json.load(f)["token"]
    except (FileNotFoundError, json.JSONDecodeError):
        return None

def save_checkpoint(token: str) -> None:
    with open(CHECKPOINT_FILE, "w") as f:
        json.dump({"token": token, "at": datetime.now(timezone.utc).isoformat()}, f)

def project_to_delta(batch: list[dict]) -> None:
    """Idempotent projection: upsert keyed on item id, so redelivery is safe."""
    for item in batch:
        # In practice write to Delta, Synapse, or a notification topic here
        print(f"projected {item['id']} status={item.get('status')}")

def run_consumer() -> None:
    token = load_checkpoint()
    while True:
        response = list(container.query_items_change_feed(
            continuation_token=token,
            start_time=datetime.now(timezone.utc) - timedelta(minutes=5),
        ))
        if response:
            project_to_delta(response)
            token = response.continuation_token
            save_checkpoint(token)
        else:
            time.sleep(3)

run_consumer()

Multi-region writes and the conflict question

Cosmos DB offers five well-defined consistency levels, from strong to eventual, and lets you choose per account or per request. Session consistency is the default and the right choice for most data engineering workloads, because it guarantees that a session which writes an item will read its own writes, which is exactly the behavior a single-user or single-tenant ingest pipeline needs without paying the latency cost of strong consistency across regions. For global leaderboards or financial ledgers where stale reads are unacceptable, strong consistency across regions is available at the cost of higher write latency.

Multi-region writes let every region accept writes, with the service resolving conflicts automatically using last-writer-wins by default, based on a client-side timestamp you control. That is safe only if concurrent writes to the same item are rare and the losing write is acceptable. If two regional order services update the same order's quantity simultaneously, last-writer-wins silently discards one update. The fix is either optimistic concurrency with ETags, so the losing writer retries, or a custom conflict resolution policy that merges rather than overwrites. Design for the conflict before enabling multi-region writes, not after.

Consistency levelStaleness boundWrite latencyTypical data engineering use
StrongNoneHighest, cross-region round tripFinancial ledgers, inventory counters
Bounded stalenessConfigurableHighGlobal leaderboards with tolerance
SessionOwn writes always visibleRegionalMost multi-tenant ingest workloads
Consistent prefixNo out-of-order readsModerateAnalytics feeds that tolerate lag
EventualNoneLowestCaches, best-effort telemetry
{
  "properties": {
    "databaseAccountOfferType": "Standard",
    "locations": [
      { "locationName": "East US 2", "failoverPriority": 0, "isZoneRedundant": true },
      { "locationName": "West Europe", "failoverPriority": 1, "isZoneRedundant": true },
      { "locationName": "Southeast Asia", "failoverPriority": 2, "isZoneRedundant": true }
    ],
    "enableMultipleWriteLocations": true,
    "consistencyPolicy": {
      "defaultConsistencyLevel": "Session",
      "maxStalenessPrefix": 10,
      "maxIntervalInSeconds": 5
    }
  }
}

Cost control beyond the RU headline

Provisioned throughput is a fixed monthly commitment; autoscale trades a premium for flexibility, scaling between a floor and a ceiling you define. The wrong choice is expensive in both directions: fixed throughput provisioned for peak leaves you paying for idle capacity off-peak, while autoscale on a spiky workload can exceed what a well-sized fixed allocation would have cost. Analyze the traffic shape first. Steady, predictable ingest favors fixed throughput with scheduled scaling; bursty, event-driven traffic favors autoscale with a floor that covers the baseline.

Two operational habits keep RU costs honest. First, enable diagnostic logs to Log Analytics and build a KQL query that shows RU consumption by partition key value, which surfaces hot keys that aggregate metrics hide. Second, treat query RU as an engineering budget: every unbounded cross-partition scan, every SELECT star that pulls a megabyte payload to read one field, and every missing composite index is a line item on that budget. Reviewing it monthly, alongside storage growth, is the discipline that separates a Cosmos DB bill that scales with the business from one that scales with accumulated neglect.

Common Mistakes

Choosing a partition key that looks balanced today but has unbounded per-key growth

Fix: Estimate both cardinality and maximum per-key item count from real data; if any single key could exceed a fifth of the 20 GB logical partition limit, redesign the key or add a suffix

Relying on last-writer-wins conflict resolution for concurrent updates to the same item

Fix: Use optimistic concurrency with ETags, or implement a custom conflict resolution policy that merges fields rather than overwriting the whole document

Running SELECT star queries on wide documents to read two fields

Fix: Project only the needed paths in the query text; less payload means fewer RU and lower cross-network cost

Leaving the default indexing policy on a write-heavy ingest container

Fix: Exclude payload and diagnostics paths you never query, and add composite indexes for your known multi-property filters to avoid cross-partition sorts

Best Practices

  • Version the indexing policy in source control alongside the container schema
  • Build a KQL dashboard of RU by partition key value to catch hot keys early
  • Persist the change feed continuation token after each batch and design sinks to be idempotent
  • Use session consistency unless you have a specific reason not to, then override per request where needed
  • Load-test the partition key with realistic skew before production, not with uniform synthetic data

Interview Questions

Q1: How do you choose a partition key for Cosmos DB?

It must have high cardinality for even distribution, bounded per-key growth well under the 20 GB logical partition limit, and align with your most common query filter so queries stay single-partition. Avoid timestamps and sequential identifiers, which create hot partitions. Validate with a skew analysis on representative data before committing.

Q2: What is the cost impact of cross-partition queries?

They fan out to every physical partition, consuming RU proportional to the total data scanned rather than the slice you need, and they increase tail latency. Include the partition key in the WHERE clause whenever possible, and add composite indexes for multi-property filters and ORDER BY combinations.

Q3: Explain change feed checkpointing and its delivery guarantee.

Readers receive a continuation token representing their position in the per-partition log. Persisting the token after each batch yields at-least-once delivery. Exactly-once requires an idempotent downstream write, typically an upsert keyed on item ID, because a crash between processing and checkpointing will redeliver the batch.

Q4: When is multi-region write appropriate?

When your application has geographically distributed writers that mostly touch disjoint items, and you have a deliberate conflict strategy, whether optimistic concurrency, custom merge logic, or acceptable last-writer-wins. It is inappropriate when concurrent updates to the same item are common and losing one silently is unacceptable.

Key Takeaways

  • The partition key balances cardinality, evenness, and per-key growth under the 20 GB logical limit; it is effectively irreversible after launch
  • Indexing policies trade write amplification against query RU; exclude unused paths and declare composite indexes for multi-property filters
  • Change feed gives at-least-once by default; make sinks idempotent instead of chasing exactly-once
  • Session consistency is the pragmatic default; strong cross-region consistency is a deliberate latency cost
  • Monitor RU by partition key value to catch hot keys that aggregate dashboards hide
🔒

Premium Content

Cosmos DB Partitioning, Indexing, and Change Feed Patterns

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement