Lesson 3 of 3 Vector Search and Change Feed in Azure Cosmos DB

Processing the Change Feed in Python

This lesson explains the Azure Functions Cosmos DB trigger and the pull model, and how to avoid duplicate processing and feedback loops.

Learning outcomes

After completing this lesson, you will be able to:

  • Choose between the Functions trigger and the pull model.
  • Describe the role of the lease container and its prefix.
  • Explain continuation tokens in the pull model.
  • Explain how a content hash prevents feedback loops.

Two ways to consume the feed from Python

The change feed processor library is not available in the Python SDK, so Python developers choose between a push model provided by Azure Functions and a pull model in the SDK. Both read the same change feed, with the same per-partition ordering and the same at-least-once character.

Functions Cosmos DB trigger
Who manages progressThe Functions runtime, with a lease container
ScalingAutomatic with the function app
PacingChanges are pushed as they arrive
Best forEvent-driven processing with least effort
Choose when React to every change automatically
Pull model (query_items_change_feed)
Who manages progressYour code, with a continuation token you store
ScalingYour code divides work by feed range
PacingYour code decides when to read
Best forBatch catch-up, custom hosting, controlled pace
Choose when Read on your own schedule or in a container or job

The Azure Functions Cosmos DB trigger

The Cosmos DB trigger runs the change feed processor inside the Functions host. It needs a lease container, which it can create when the connection allows management operations; with Microsoft Entra authentication through data plane roles, the lease container must be created in advance, because data plane roles cannot create containers. The function receives a list of changed documents.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.cosmos_db_trigger(arg_name="docs", database_name="retail", container_name="products",
                       connection="CosmosDB", lease_container_name="leases",
                       lease_container_prefix="embedder")
def embed_changed_products(docs: func.DocumentList):
    for doc in docs:
        logging.info("Changed product %s", doc["id"])
        # generate an embedding and store it, idempotently

The connection value names a prefix of app settings. With identity-based connections, the setting CosmosDB__accountEndpoint holds the account URL and the function app's managed identity provides the credential. lease_container_prefix keeps two functions that share a lease container independent. Other options include start_from_beginning and max_items_per_invocation. If the function throws, the batch is retried, so the code must tolerate repeats.

True or false

The Cosmos DB trigger

Exam skills 2.1.4 · 3.2.1

Decide whether each statement about the Functions Cosmos DB trigger is true.

Log in to try this activity Interactive activities are free with an account.

The pull model

In the pull model, the application calls query_items_change_feed and receives changes since a starting point. After processing a page, it saves the continuation token, which the SDK returns in the etag response header; the next call passes the token and receives only newer changes. Storing the token durably, for example in a small Cosmos DB item or a blob, lets a restarted process continue where it stopped.

def read_changes(container, continuation=None):
    if continuation:
        feed = container.query_items_change_feed(continuation=continuation)
    else:
        feed = container.query_items_change_feed(start_time="Beginning")
    for item in feed:
        handle(item)                       # idempotent processing
    return container.client_connection.last_response_headers["etag"]   # save this token

For parallelism, container.read_feed_ranges() returns the container's feed ranges, and each worker can read one range with the feed_range argument and its own token. The pull model suits a Container Apps job that catches up every few minutes, a migration that reads the whole history once, or a consumer that must control its pace.

Scenario questions

Trigger or pull model?

Exam skills 2.1.4

Choose how a Python application should consume the change feed.

Log in to try this activity Interactive activities are free with an account.

Idempotency and feedback loops

Two problems recur in change feed handlers. The first is duplicate delivery: because delivery is at least once, a handler may see the same change twice, so its effects must be safe to repeat. Upserting a result keyed by the source item's id, rather than appending, achieves this.

The second is a feedback loop. A handler that generates an embedding and writes it back into the same item creates a new change, which triggers the handler again, which writes again. Two techniques break the loop: store a hash of the embedded text in the item and skip items whose text hash has not changed, or write the embedding to a different container. The hash approach also avoids paying for embeddings when only an unrelated property, such as stock level, changed.

import hashlib

def handle(item):
    text = f"{item['name']}\n{item['description']}"
    digest = hashlib.sha256(text.encode()).hexdigest()
    if item.get("embeddingHash") == digest:
        return                                   # our own write, or no text change
    item["embedding"] = embed(text)
    item["embeddingHash"] = digest
    container.upsert_item(item)                  # creates one more change, which is then skipped

The following diagram shows how the function decides which changes to re-embed.

Keeping embeddings current with the Azure Functions Cosmos DB trigger. The function receives changes within seconds through an identity-based connection and a pre-created lease container. It compares a hash of the description with the stored hash, so stock updates and its own embedding writes are skipped, and only real description changes call the embedding model.
The hash check also stops the function from looping on its own writes.
Select all that apply

Safe change feed handlers

Exam skills 2.1.4

Identify the practices that make an embedding handler safe.

Log in to try this activity Interactive activities are free with an account.
Worked example

Keeping product embeddings current

Product descriptions in Cosmos DB are edited by merchandisers throughout the day, and stock levels change thousands of times an hour. The search feature needs each product's embedding regenerated within a minute of a description change. The team works in Python and wants the least operational effort and no stored keys.

A Python function with the Cosmos DB trigger on the products container, using an identity-based connection and a pre-created lease container, receives changes within seconds. The handler compares a hash of the description with the stored hash, so stock updates and its own embedding writes are skipped, and only real description changes call the embedding model. Failures are logged to an error container so that one bad item does not block its partition.

A timer function that queries for recently modified items would be polling and could miss changes between runs. A pull-model worker in a container would work but needs its own hosting, scaling and token storage, which is more effort. A handler without the hash check would re-embed on every stock change and loop on its own writes.

Check yourself

In the pull model, how does an application continue from where it stopped after a restart?

Show answer

It saves the continuation token returned in the etag response header after each page, and passes it to query_items_change_feed(continuation=...) on the next run.

Exam Tips

Remember for the exam

  • The change feed processor library is .NET and Java only; Python uses the Functions trigger or the pull model.
  • With data plane roles, create the lease container in advance.
  • Pull model: save the continuation token from the etag header; split work by feed range.
  • Make handlers idempotent and skip unchanged content to avoid feedback loops.