Home / Azure

AzureTroubleshootingAdvanced

Cosmos DB change feed processor falling behind - lease ownership, stuck partitions and poison batches

Find why a Cosmos DB change feed processor or Functions trigger lags. Measure lag per lease, spot hot or stuck partitions, poison batches, shared lease containers and lease throttling, then fix each.

Deepak Bhardwaj8 min read

Applies toAzure Cosmos DB for NoSQL, .NET SDK v3 / Java SDK v4 change feed processor, Azure Functions Cosmos DB trigger (extension 4.x)

Symptom

Downstream systems (search index, cache, event bus) fall behind the source container. Some documents show up minutes or hours late, or not at all. Adding instances or Function workers doesn't help. Sometimes only some partitions are behind while the rest are current.

The change feed processor (CFP) splits the work into leases, one per feed range (roughly one per physical partition). Each lease is owned by one instance at a time and checkpointed in a lease container. Almost every lag problem is one of these:

What you see Usual cause
All leases lag equally Handler too slow, poll delay too high, or source throttling
One or two leases lag, the rest are current Hot partition, or a poison batch retrying forever
Lag doesn't fall when you add instances More instances than leases. Extra instances sit idle.
Roughly half the changes never arrive Two processors share a lease container and processor name or prefix
Leases change owner constantly Lease container throttled, or instances too busy to renew
Changed start time but nothing reprocessed Leases already exist, so the start time is ignored

1. Measure lag per lease

Don't guess from downstream timestamps. Use the estimator, which reads the leases and asks the service how far each one is behind.

// .NET SDK v3
Container monitored = client.GetContainer("shop", "orders");
Container leases    = client.GetContainer("shop", "leases");

ChangeFeedEstimator estimator = monitored.GetChangeFeedEstimator("orders-to-search", leases);

using FeedIterator<ChangeFeedProcessorState> it = estimator.GetCurrentStateIterator();
while (it.HasMoreResults)
{
    foreach (ChangeFeedProcessorState s in await it.ReadNextAsync())
    {
        Console.WriteLine($"{s.LeaseToken,-8} owner={s.InstanceName ?? "<none>",-30} lag={s.EstimatedLag}");
    }
}

The processor name passed to the estimator must match the one the processor uses. For a Functions trigger, the processor name is derived from the function, and the lease documents are prefixed with LeaseContainerPrefix if you set one. Read the lease container (next step) to find the exact names.

Read the output like this:

  • owner=<none> on a lagging lease. Nobody is processing it. Check that instances are running and can renew (step 5).
  • One lease with a large lag and an owner. Either a hot partition or a poison batch. Step 3 tells them apart.
  • Lag grows on every lease. Throughput problem. Go to step 4.

Run the estimator on a schedule and push EstimatedLag as a custom metric. That's the alert you actually want.

2. Look inside the lease container

az cosmosdb sql container show -g rg-data -a cosmos-shop -d shop -n leases \
  --query "resource.partitionKey.paths" -o tsv

The lease container must be partitioned on /id. If it isn't, create a new one. You can't change a partition key in place.

Query the leases in Data Explorer to see owners, checkpoint times and prefixes:

SELECT c.id, c.Owner, c.LeaseToken, c._ts
FROM c
WHERE IS_DEFINED(c.LeaseToken)
ORDER BY c._ts ASC

Field names differ slightly between SDK versions and the Functions extension, so check one document first. Leases with an old _ts haven't been renewed or checkpointed. If you see two sets of ids for the same monitored container with different prefixes, two processors are running. That's fine if they're meant to be separate consumers.

Warning

Two different Functions or services that use the same lease container, processor name and prefix compete for the same leases. Each one gets only the changes for the leases it holds. Nothing errors, and each consumer quietly misses part of the data. Give every logical consumer its own LeaseContainerPrefix (Functions) or processor name (SDK).

3. Poison batch or hot partition?

In the .NET SDK, if the handler delegate throws an unhandled exception, the processor doesn't checkpoint. It retries the same batch from the last checkpoint. One document that always throws (a schema the code can't parse, a downstream 400) stalls that lease forever, while every other lease stays current.

Check your app logs for the same exception repeating, and look at the source container's request logs for the stuck partition:

CDBDataPlaneRequests
| where TimeGenerated > ago(1h)
| where CollectionName in ("orders", "leases")
| summarize requests = count(), ru = sum(RequestCharge), throttled = countif(StatusCode == 429)
          by CollectionName, OperationName, bin(TimeGenerated, 5m)
| order by TimeGenerated desc
  • The same batch is read again and again, at a steady rate, and the downstream write fails. That's a poison batch.
  • One partition's write rate is far higher than the others. That's a hot partition. Check NormalizedRUConsumption split by PartitionKeyRangeId.
ACC=$(az cosmosdb show -g rg-data -n cosmos-shop --query id -o tsv)
az monitor metrics list --resource $ACC --metric NormalizedRUConsumption \
  --dimension PartitionKeyRangeId --filter "CollectionName eq 'orders' and PartitionKeyRangeId eq '*'" \
  --interval PT5M --offset 3h --aggregation Maximum -o table

Fix a poison batch by catching per-document exceptions in the handler and sending failures to a dead-letter store (a Service Bus queue or a separate container) along with the error. Then let the batch complete:

static async Task HandleAsync(ChangeFeedProcessorContext ctx, IReadOnlyCollection<Order> changes, CancellationToken ct)
{
    foreach (var doc in changes)
    {
        try { await indexer.UpsertAsync(doc, ct); }
        catch (Exception ex) when (!IsTransient(ex))
        {
            await deadLetter.SendAsync(doc.id, ctx.LeaseToken, ex.Message, ct);
        }
    }
}

Let transient errors throw so the batch retries. Catch the permanent ones only. Otherwise you silently drop data during a downstream outage.

A hot partition is a data model problem. The CFP can't split work below a lease. Short-term fixes: make the handler faster (batch downstream writes, raise MaxItems). Long-term: a partition key with more cardinality.

4. Throughput tuning

Setting SDK (.NET) Functions trigger Effect
Poll interval WithPollInterval FeedPollDelay (ms) How long a lease waits when it has caught up. Lower means less latency and more RU spent on empty reads.
Batch size WithMaxItems MaxItemsPerInvocation More documents per handler call. Helps when downstream supports bulk writes.
Lease timings WithLeaseConfiguration(acquire, expiration, renew) LeaseAcquireInterval, LeaseExpirationInterval, LeaseRenewInterval Rebalancing speed vs ownership churn
Instance name WithInstanceName Set by the host Must be unique per instance

Parallelism tops out at the number of leases. If the estimator shows ten leases, the eleventh instance does nothing. To go faster, make each lease faster: async downstream I/O, bulk writes, no per-document round trips to Cosmos DB inside the handler.

Check the source container for 429s too. CFP reads use RUs on the monitored container, and a container that's saturated by the main workload starves the processor.

5. Lease churn and the lease container

Leases are renewed on a timer. If an instance can't renew in time, because the lease container is throttled or the instance is CPU-starved and the renew loop doesn't run, another instance takes the lease. The batch in flight is then processed twice and progress stalls during each handover.

az cosmosdb sql container throughput show -g rg-data -a cosmos-shop -d shop -n leases -o json
  • Give the lease container its own throughput (or autoscale) instead of sharing a busy database's pool.
  • Look for 429 on leases in the query from step 3. Any sustained throttling there is a bug, not a tuning detail.
  • Keep handlers idempotent anyway. The CFP guarantees at least once delivery, and lease handovers re-deliver.

6. Reprocessing and start position

WithStartTime, WithStartFromBeginning and the Functions StartFromBeginning only apply when no leases exist for that processor. After the first run they're ignored. To replay:

  1. Stop all instances.
  2. Deploy with a new processor name (or a new LeaseContainerPrefix) and the start option you want. Leave the old leases alone until the new consumer catches up, so you can roll back.
  3. Delete the old lease documents afterwards.

Caution

Replaying from the beginning pushes the whole container through the handler. Make sure downstream writes are idempotent and that downstream can take the load. Otherwise a replay becomes an incident of its own.

Remember that the default (latest version) change feed mode shows only the latest version of each item and doesn't include deletes. If you need deletes and intermediate updates, use the all versions and deletes mode. It has its own requirements, such as continuous backup, so check current docs.

Prevent it next time

  • Alert on estimator lag per lease, not just on the total.
  • One lease container prefix or processor name per consumer, enforced in code review.
  • Per-document error handling with a dead-letter path in every handler.
  • Dedicated throughput on the lease container, and alerts on 429s against it.
  • Load-test the handler against your expected partition count, since that's your ceiling for parallelism.