Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 13 of 28
❮Prev Next❯

Cosmos DB Change Feed Processor

Module 2: Data for AI ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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 needed

    Exam 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.

    Azure portal: React to changes with the change feed Wire a change feed trigger with a lease container.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. The change feed processor tracks its progress in a lease container. Create leases with partition key /id.
    2. In the function app, a Cosmos DB trigger points at the monitored container and the lease container.
    3. CosmosDb__accountEndpoint means identity-based connection: no key. Give the app’s identity a Cosmos DB data role.
    4. Back in Data Explorer, add a product and Save. Inserts and updates show up in the change feed.
    5. Within a second the function picks it up. Nobody polled the database; the feed pushed the change.
    6. 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.

    😟 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
    🛠️ Solved with: Change feed processor

    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.

    ▶ Explainer video See it in motion 7 steps · 1 min 38 sec

    An animation of inserts and updates appended in order to a Cosmos DB change feed for two partition key ranges. A processor with a lease container reads them, the delegate embeds each item and the checkpoint moves only after success, a second worker takes over one lease, a write-back is skipped by a text hash check, a delete is missing from latest version mode so a soft delete with a TTL is used, and the Python route uses the Azure Functions Cosmos DB trigger.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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

    PartWhat it is
    Monitored containerThe container with your data, such as products. Its changes are what you read.
    Lease containerStores one lease per partition key range: the checkpoint and which instance owns it. Its partition key must be /id.
    Compute instanceWherever the processor runs: an App Service, a container app, a VM. Each has a unique instance name.
    DelegateYour 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 processorName and 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. WithStartTime sets 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 WithErrorNotification so 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 updatesYes, latest version of each item onlyYes, every intermediate version
    DeletesNoYes, including TTL expiries
    Start from the beginning or a timeYesNo: from now or a saved checkpoint within the retention period
    RequirementsNoneContinuous 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. 1 Save

      The app upserts a product into the monitored container.

    2. 2 Feed

      The change appears in the change feed for its partition key range.

    3. 3 Deliver

      The processor (or Functions trigger) passes the batch to your delegate.

    4. 4 Embed

      The delegate creates the vector and stores it, skipping unchanged text.

    5. 5 Checkpoint

      Only after success, the lease records the new position.

    Keeping embeddings fresh with the change feed
    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

    Online marketplace

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    You implement a change feed processor in .NET that generates embeddings for new and updated products. The processor runs on three App Service instances.

    Which component stores the processing progress for each partition key range and coordinates the work between the instances?

    Question 2

    Question 2 of 5

    A change feed processor uses the default latest version mode. Items that are deleted from the monitored container must also be removed from a downstream search index. What should you do?

    Question 3

    Question 3 of 5 · Select 2

    You plan to scale a change feed processor across four compute instances so that the instances share the work. Which TWO configuration requirements must be met?

    Question 4

    Question 4 of 5

    A Python team must run code every time an item is inserted or updated in a Cosmos DB container. The team does not want to host or scale the processing infrastructure. What should you use?

    Question 5

    Question 5 of 5

    A function triggered by the Cosmos DB change feed generates an embedding and writes it back into the same item. The function now runs continuously, even when no user changes data. What is the most likely cause?

    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. 1.What stores the processor's checkpoints?Show

      The lease container.

    2. 2.What is the code that handles each batch called?Show

      The delegate.

    3. 3.Does latest version mode record deletes?Show

      No.

    4. 4.What delivery guarantee does the change feed processor give?Show

      At least once.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.