Cosmos DB Change Feed Processor
30-second answer
The change feed is a persistent, ordered record of the inserts and updates in a Cosmos DB container. The change feed processor reads it for you: it watches the monitored container, hands each batch of changes to your delegate, and stores its progress in a lease container, so several instances can share the work and resume after a crash with at-least-once delivery. The default latest version mode doesn't capture deletes; all versions and deletes mode does. An Azure Functions Cosmos DB trigger gives you the same pattern without hosting the processor yourself.
Simulate it » No Azure account neededExam objective: 2.1.4 Implement a change feed processor to detect and handle new or updated items. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
The change feed processor tracks its progress in a <strong>lease container</strong>. Create <code>leases</code> with partition key <code>/id</code>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- The change feed processor tracks its progress in a lease container. Create leases with partition key /id.
- In the function app, a Cosmos DB trigger points at the monitored container and the lease container.
- CosmosDb__accountEndpoint means identity-based connection: no key. Give the app’s identity a Cosmos DB data role.
- Back in Data Explorer, add a product and Save. Inserts and updates show up in the change feed.
- Within a second the function picks it up. Nobody polled the database; the feed pushed the change.
- Each lease stores a continuation token per partition range. Restart the app and it carries on from there. Deletes don’t appear in this mode, so use a soft-delete flag.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Change feed
The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Products arrive without embeddings. Let the change feed notice each new or edited product, write its embedding, and then answer shopper questions with VectorDistance over a DiskANN index.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
New products don’t show up in AI search until a nightly job runs.
😊 THE SOLUTION
React to every insert and update with the change feed processor.
- Nightly batch jobs✓ Changes processed in seconds
- Two workers, same item✓ Leases split the work
- Deletes are invisible✓ Soft-delete flag with TTL
Start with a question
A seller adds a new product. How does your AI search know about it a few seconds later, without a nightly batch job?
Think of a restaurant kitchen. The waiter pins each new order on a rail. The cook takes the next ticket, cooks it, and moves a clip along the rail to show how far they’ve got. If the cook goes on a break, the next cook looks at the clip and carries on from there. Nothing is cooked twice by accident and nothing is missed.
Cosmos DB has that rail: the change feed. The cook is the change feed processor, the clip is a lease, and cooking is your code, the delegate. A new product lands, the processor sees it, and your code embeds it straight away.
Explain it like I’m 10
Visual: the change feed in motion
Follow new products through the change feed, the lease container and two workers, right up to a fresh embedding.
Read the video script
- Writes land in the change feedEvery insert and update in a Cosmos DB container lands in its change feed. It's an ordered record, kept per partition key range, and it's switched on by default.
- A lease container tracks progressThe change feed processor reads it for you. It keeps its progress in a lease container. There's one lease per range, holding the last checkpoint and which instance owns it.
- Delegate first, then the checkpointEach batch goes to your code, called the delegate. Only after the delegate succeeds does the lease move forward. If it fails, the same batch comes back, so delivery is at least once.
- Two workers share the leasesStart a second instance with the same processor name and the same lease container, but its own instance name. The leases are shared out, so each worker takes a different range.
- Write the vector back, with a guardHere the delegate embeds the new description and writes the vector back. That write is an update too, so it comes round again. A text hash check sees nothing changed, and skips it.
- Deletes don’t show upIn the default latest version mode, deletes don't show up at all. The usual fix is a soft delete: set a deleted flag, which the feed does record, and add a TTL to remove the item later.
- In Python: a Functions triggerWriting Python? The Python SDK doesn't include the processor. You use the Azure Functions Cosmos DB trigger instead, and it runs the processor and the leases for you.
The technical explanation
The change feed is on by default for every Cosmos DB for NoSQL container. It’s ordered per partition key range, and it’s persistent, so a reader can start now, at a point in time, or from the beginning (in latest version mode).
The four parts of the processor
| Part | What it is |
|---|---|
| Monitored container | The container with your data, such as products. Its changes are what you read. |
| Lease container | Stores one lease per partition key range: the checkpoint and which instance owns it. Its partition key must be /id. |
| Compute instance | Wherever the processor runs: an App Service, a container app, a VM. Each has a unique instance name. |
| Delegate | Your handler. It receives a batch of changed items and does the work. |
The life cycle loops: read the feed, sleep if there’s nothing new (the poll interval), otherwise call the delegate, and only after the delegate finishes successfully update the lease. If the delegate throws, the same batch comes back again. That’s why delivery is at least once, and why your delegate should be idempotent (safe to run twice on the same item).
The processor in C#
The processor library ships in the .NET and Java SDKs:
Container monitored = client.GetContainer("shop", "products");
Container leases = client.GetContainer("shop", "leases");
ChangeFeedProcessor processor = monitored
.GetChangeFeedProcessorBuilder<Product>(
processorName: "embedProducts",
onChangesDelegate: HandleChangesAsync)
.WithInstanceName(Environment.MachineName) // unique per instance
.WithLeaseContainer(leases)
.WithStartTime(DateTime.UtcNow.AddHours(-1)) // optional; default is "from now"
.Build();
await processor.StartAsync();
static async Task HandleChangesAsync(
ChangeFeedProcessorContext context,
IReadOnlyCollection<Product> changes,
CancellationToken token)
{
foreach (Product p in changes)
{
// embed p.Description and save the vector (idempotently)
}
}
- To scale out, run more instances with the same
processorNameand lease container and different instance names. Leases are shared out between them, and one lease is owned by one instance at a time, so more instances than leases won’t help. - A new processor starts from now by default.
WithStartTimesets a point in time;DateTime.MinValue.ToUniversalTime()reads from the beginning. These only matter the first time; once leases exist, the processor resumes from them. - Register
WithErrorNotificationso you hear about failures, and send items that keep failing to an error store so the processor doesn’t get stuck retrying them.
In Python: an Azure Functions trigger
The Python SDK doesn’t include the processor. The usual Python answer is the Azure Functions Cosmos DB trigger, which runs the processor for you, leases and all:
import azure.functions as func
app = func.FunctionApp()
@app.cosmos_db_trigger(
arg_name="items",
connection="CosmosDbConnection", # app setting (or identity-based settings)
database_name="shop",
container_name="products", # the monitored container
lease_container_name="leases",
create_lease_container_if_not_exists="true",
)
def embed_new_products(items: func.DocumentList):
for doc in items:
if doc.get("textHash") == hash_of(doc["description"]):
continue # vector is already current: skip
vector = embed(doc["description"])
save_vector(doc["id"], doc["category"], vector)
That textHash check matters. If your function writes the embedding back into the same item, that write is an update, which appears in the change feed and fires the function again. Without a guard you get an endless loop and a big RU bill. Either compare a hash of the source text, or write vectors to a separate container.
If you’d rather run your own loop in Python, the change feed pull model (container.query_items_change_feed(...)) reads changes directly, but you store and resume the continuation token yourself.
Change feed modes
| Latest version (default) | All versions and deletes | |
|---|---|---|
| Creates and updates | Yes, latest version of each item only | Yes, every intermediate version |
| Deletes | No | Yes, including TTL expiries |
| Start from the beginning or a time | Yes | No: from now or a saved checkpoint within the retention period |
| Requirements | None | Continuous backup on the account, NoSQL API only |
In latest version mode, if an item is created and then updated before you read the feed, you only see the updated version. To react to deletes without switching modes, use a soft delete: set "deleted": true (which is an update the feed records) and a TTL so the item is removed later.
-
1 Save
The app upserts a product into the monitored container.
-
2 Feed
The change appears in the change feed for its partition key range.
-
3 Deliver
The processor (or Functions trigger) passes the batch to your delegate.
-
4 Embed
The delegate creates the vector and stores it, skipping unchanged text.
-
5 Checkpoint
Only after success, the lease records the new position.
Architect level Watching lag and cost
The change feed processor costs RUs on both containers: reading the monitored container’s feed and reading and writing leases. Give the lease container enough throughput, especially with many partition key ranges.
To see whether the processor keeps up, use the change feed estimator in .NET, which reports how many changes are still waiting per lease. With Functions, watch the trigger’s execution count and duration in Application Insights. If lag grows, add instances (up to the number of leases) or make the delegate faster, for example by embedding a batch of items in one call instead of one call per item.
Use the account’s global endpoint when you create the client for the processor. Leases are scoped to the endpoint you use, so switching to a regional endpoint later creates a fresh set of leases.
Real-world business scenario
Litware Marketplace (fictional)
- The problem
- Sellers added about 20,000 listings a day, but embeddings were generated by a nightly batch job. New listings were invisible to AI search until the next morning, and the batch often ran into business hours.
- What they used
- An Azure Functions app with a Cosmos DB trigger on the listings container and a leases container. The function embeds new or edited descriptions with text-embedding-3-small, skips items whose text hash hasn't changed, and writes the vector back. Removed listings are soft-deleted with a flag and a TTL so the change feed sees them.
- Why that choice
- The change feed delivers every create and update in order with checkpoints in the lease container, so nothing is missed after a restart, and Functions scales the work with the number of changes.
- The result
- New listings show up in semantic search within seconds of being saved, and the nightly batch job was retired.
When to use it and when not to
✓ Use it when…
- You need to react to new or updated items: generate embeddings, refresh a cache, update a search index or send an event.
- You want to copy or move data to another container or store as it changes.
- You need work shared across several workers with automatic checkpoints.
✕ Think twice when…
- You need every delete with no setup. Latest version mode won't show them; plan for all versions and deletes mode or soft deletes.
- You need a guaranteed exactly-once action with no duplicates. Delivery is at least once, so make the handler idempotent.
- You only need a one-off export. A query or a copy job is simpler.
↔ Alternatives to consider
- Azure Functions Cosmos DB trigger for the same pattern without hosting the processor.
- Change feed pull model when you want to control the reading loop and checkpoints yourself.
- Azure Event Grid or Service Bus when the app itself should publish an event or message alongside the write.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What is the Cosmos DB change feed used for?
Model answer
Reacting to data as it changes. Each time an item is created or updated it appears in the change feed, so another process can do follow-up work: generate an embedding, update a search index, send a notification or copy the data somewhere else.
Intermediate What does the lease container do?
Model answer
It's the processor's memory. It holds one lease per partition key range, recording the last point that was processed and which instance owns that range. If an instance crashes, another picks up its leases and carries on from the last checkpoint.
Interviewer follows up
How do you run several instances of the same processor?
You
Same processor name, same lease container, different instance name on each. The processor spreads the leases across them.
Experienced developer Your processor never sees deleted products. Why, and how would you fix it?
Model answer
The default latest version mode doesn't record deletes. I can switch to all versions and deletes mode, which needs continuous backup on the account, or use a soft delete: set a deleted flag, which shows up as an update, and give the item a TTL so it's removed later.
Scenario Your delegate writes the new embedding back into the same item, and now the function runs forever. What's going on?
Model answer
Writing the embedding is itself an update, so it lands in the change feed and triggers the delegate again. I'd store a hash of the source text with the embedding and skip items where the hash hasn't changed, or write the vectors to a separate container.
Architecture & design When would you host the change feed processor yourself instead of using an Azure Functions trigger?
Model answer
If I need full control over hosting, lifecycle notifications, all versions and deletes mode in .NET, or the work already runs in a long-lived service such as a container app. For most event-style work, like embedding new items, the Functions trigger is less to run and scales with the load.
Quick revision
Key points
- Four parts: monitored container, lease container, compute instance, delegate.
- The processor gives at-least-once delivery; make the delegate idempotent.
- By default it starts from now; WithStartTime reads from a time or from the beginning (latest version mode only).
- Latest version mode records creates and updates, not deletes.
- All versions and deletes mode records deletes too and needs continuous backup.
- The processor library is in .NET and Java; Python uses the Functions trigger or the pull model.
Important terminology
- Change feed
- A persistent, ordered record of changes to items in a Cosmos DB container, read per partition key range.
- Change feed processor
- A library in the .NET and Java SDKs that reads the change feed, distributes the work across instances and checkpoints progress.
- Monitored container
- The container whose changes the processor reads.
- Lease container
- A container that stores one lease per partition key range, recording how far the processor has read and which instance owns it.
- Delegate
- Your code that receives each batch of changes and does the work, such as generating an embedding.
- Latest version mode
- The default change feed mode. It records creates and updates, shows only the latest version of an item, and doesn't record deletes.
- All versions and deletes mode
- A mode that records every create, update and delete within the continuous backup retention period. It needs continuous backup on the account.
Common mistakes
- Expecting deletes to appear in latest version mode.
- Writing back to the monitored container from the delegate without a guard, causing an endless loop.
- Giving two instances the same instance name, or different lease containers, and expecting them to share work.
Exam tips
- "Track progress and share work across instances" = the lease container.
- "Process changes without managing hosts" = Azure Functions Cosmos DB trigger.
- "Must capture deleted items" = all versions and deletes mode (or a soft-delete flag plus TTL).
Five quick revision questions
-
1.What stores the processor's checkpoints?Show
The lease container.
-
2.What is the code that handles each batch called?Show
The delegate.
-
3.Does latest version mode record deletes?Show
No.
-
4.What delivery guarantee does the change feed processor give?Show
At least once.
-
5.Which builder method sets where a new processor starts reading?Show
WithStartTime.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Connect to and Query Azure Database for PostgreSQL
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.