Edit

Azure Cosmos DB trigger for Azure Functions 2.x and higher

The Azure Cosmos DB Trigger uses the Azure Cosmos DB change feed to listen for inserts and updates across partitions. The change feed publishes new and updated items, not including updates from deletions. For an end-to-end scenario that uses the Azure Cosmos DB trigger, see Quickstart: Respond to database changes in Azure Cosmos DB using Azure Functions.

For information on setup and configuration details, see the overview.

Cosmos DB scaling decisions for the Consumption and Premium plans are done via target-based scaling. For more information, see Target-based scaling.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.

Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.

The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.

This article supports both programming models.

For a complete end-to-end example of using the Azure Cosmos DB trigger, see Respond to database changes in Azure Cosmos DB using Azure Functions.

Example

The usage of the trigger depends on the extension package version and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

The following examples depend on the extension version for the given C# mode.

This example uses app settings references and includes error handling. First, define your model type:

public class ToDoItem
{
    public string? Id { get; set; }
    public string? Description { get; set; }
}

The following function runs when inserts or updates occur in the specified database and container:

[Function("CosmosTrigger")]
public void Run([CosmosDBTrigger(
    databaseName: "%COSMOS_DATABASE_NAME%",
    containerName: "%COSMOS_CONTAINER_NAME%",
    Connection = "COSMOS_CONNECTION",
    LeaseContainerName = "leases",
    CreateLeaseContainerIfNotExists = true)] IReadOnlyList<ToDoItem> documents,
    FunctionContext context)
{
    if (documents is not null && documents.Any())
    {
        _logger.LogInformation("Documents modified: {count}", documents.Count);
        foreach (var doc in documents)
        {
            try
            {
                _logger.LogInformation("Processing document Id: {id}", doc.Id);
                // Add your business logic here
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing document {id}", doc.Id);
                // Continue processing remaining documents
            }
        }
    }
}

[Function("health")]
public IActionResult HealthCheck([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "health")] HttpRequest req)
{
    return new OkResult();
}

The preceding example uses app settings references (%VAR_NAME%) instead of hardcoded values. For configuration details, see the app settings and local development guidance in the in-process tab.

This function is invoked when there are inserts or updates in the specified database and container.

Because of schema changes in the Azure Cosmos DB SDK, version 4.x of the Azure Cosmos DB extension requires azure-functions-java-library V3.0.0 for Java functions.

    @FunctionName("CosmosDBTriggerFunction")
    public void run(
        @CosmosDBTrigger(
            name = "items",
            databaseName = "ToDoList",
            containerName = "Items",
            leaseContainerName="leases",
            connection = "AzureCosmosDBConnection",
            createLeaseContainerIfNotExists = true
        )
        Object inputItem,
        final ExecutionContext context
    ) {
        context.getLogger().info("Items modified: " + inputItems.size());
    }

In the Java functions runtime library, use the @CosmosDBTrigger annotation on parameters whose value comes from Azure Cosmos DB. Use this annotation with native Java types, plain-old Java objects (POJOs), or nullable values by using Optional<T>.

The following example shows an Azure Cosmos DB trigger TypeScript function. The function writes log messages when Azure Cosmos DB records are added or modified.

import { app, InvocationContext } from '@azure/functions';

export async function cosmosDBTrigger1(documents: unknown[], context: InvocationContext): Promise<void> {
    context.log(`Cosmos DB function processed ${documents.length} documents`);
}

app.cosmosDB('cosmosDBTrigger1', {
    connection: '<connection-app-setting>',
    databaseName: 'Tasks',
    containerName: 'Items',
    createLeaseContainerIfNotExists: true,
    handler: cosmosDBTrigger1,
});

The following example shows an Azure Cosmos DB trigger JavaScript function. The function writes log messages when Azure Cosmos DB records are added or modified.

const { app } = require('@azure/functions');

app.cosmosDB('cosmosDBTrigger1', {
    connection: '<connection-app-setting>',
    databaseName: 'Tasks',
    containerName: 'Items',
    createLeaseContainerIfNotExists: true,
    handler: (documents, context) => {
        context.log(`Cosmos DB function processed ${documents.length} documents`);
    },
});

The following example shows how to run a function as data changes in Azure Cosmos DB.

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "<connection-app-setting>",
    "databaseName": "Tasks",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": true
}

Note that some of the binding attribute names changed in version 4.x of the Azure Cosmos DB extension.

In the run.ps1 file, you have access to the document that triggers the function via the $Documents parameter.

param($Documents, $TriggerMetadata) 

Write-Host "First document Id modified : $($Documents[0].id)" 

The following example shows an Azure Cosmos DB trigger binding. The example depends on whether you use the v1 or v2 Python programming model.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="CosmosDBTrigger")
@app.cosmos_db_trigger(arg_name="documents", 
                       database_name="%COSMOS_DATABASE_NAME%", 
                       container_name="%COSMOS_CONTAINER_NAME%",
                       connection="COSMOS_CONNECTION",
                       lease_container_name="leases",
                       create_lease_container_if_not_exists="true")
def cosmos_trigger(documents: func.DocumentList) -> str:
    if documents:
        for doc in documents:
            try:
                logging.info('Processing document id: %s', doc['id'])
                # Add your business logic here
            except Exception as e:
                logging.error('Error processing document %s: %s', doc.get('id', 'unknown'), str(e))
                # Continue processing remaining documents

@app.function_name(name="health")
@app.route(route="health", methods=["GET"])
def health_check(req: func.HttpRequest) -> func.HttpResponse:
    """Health check endpoint for monitoring."""
    return func.HttpResponse("OK", status_code=200)

The preceding example uses app settings references (%VAR_NAME%) instead of hardcoded values.

App settings

Configure these application settings for identity-based connections:

Setting Description Example
COSMOS_DATABASE_NAME Name of the Azure Cosmos DB database my-database
COSMOS_CONTAINER_NAME Name of the container to monitor my-container
COSMOS_CONNECTION__accountEndpoint Azure Cosmos DB account endpoint https://mycosmosdb.documents.azure.com:443/
COSMOS_CONNECTION__credential Set to managedidentity for UAMI managedidentity
COSMOS_CONNECTION__clientId Client ID of the user-assigned managed identity 00000000-0000-0000-0000-000000000000

Local development

For local development, create a local.settings.json file:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "python",
        "COSMOS_DATABASE_NAME": "my-database",
        "COSMOS_CONTAINER_NAME": "my-container",
        "COSMOS_CONNECTION__accountEndpoint": "https://mycosmosdb.documents.azure.com:443/"
    }
}

Tip

For local development, omit COSMOS_CONNECTION__credential and COSMOS_CONNECTION__clientId. The DefaultAzureCredential tries multiple credentials in order, including your Azure CLI login credentials.

Prerequisites for local development:

The following example shows an Azure Cosmos DB trigger function that logs each changed document:

package main

import (
	"context"
	"log"

	"github.com/azure/azure-functions-golang-worker/sdk"
	"github.com/azure/azure-functions-golang-worker/sdk/bindings"
	"github.com/azure/azure-functions-golang-worker/worker"
)

func main() {
	app := sdk.FunctionApp()
	app.CosmosDB("cosmosDBTrigger", processChanges,
		sdk.WithDatabase("mydb"),
		sdk.WithContainer("mycontainer"),
		sdk.WithConnection("CosmosDBConnection"),
	)
	worker.Start(app)
}

func processChanges(ctx context.Context, docs []bindings.CosmosDocument) error {
	for _, doc := range docs {
		log.Printf("Document modified: %s", doc.ID)
	}
	return nil
}

Attributes

Both in-process and isolated process C# libraries use CosmosDBTriggerAttribute to define the function. C# script instead uses a function.json configuration file as described in the C# scripting guide.

The specific properties depend on both the process model and the extension version:

Isolated worker process libraries use CosmosDBTriggerAttribute from the Microsoft.Azure.Functions.Worker namespace, which defines these properties:

Attribute property Description
Connection The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being monitored. For more information, see Connections.
DatabaseName The name of the Azure Cosmos DB database with the container being monitored.
ContainerName The name of the container being monitored.
LeaseConnection (Optional) The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account that holds the lease container.

When not set, the Connection value is used. This parameter is automatically set when the binding is created in the portal. The connection string for the leases container must have write permissions.
LeaseDatabaseName (Optional) The name of the database that holds the container used to store leases. When not set, the value of the databaseName setting is used.
LeaseContainerName (Optional) The name of the container used to store leases. When not set, the value leases is used.
CreateLeaseContainerIfNotExists (Optional) When set to true, the leases container is automatically created when it doesn't already exist. The default value is false. When using Microsoft Entra identities if you set the value to true, creating containers is not an allowed operation and your Function won't be able to start.
LeasesContainerThroughput (Optional) Defines the number of Request Units to assign when the leases container is created. This setting is only used when CreateLeaseContainerIfNotExists is set to true. This parameter is automatically set when the binding is created using the portal.
LeaseContainerPrefix (Optional) When set, the value is added as a prefix to the leases created in the Lease container for this function. Using a prefix allows two separate Azure Functions to share the same Lease container by using different prefixes.
FeedPollDelay (Optional) The time (in milliseconds) for the delay between polling a partition for new changes on the feed, after all current changes are drained. Default is 5,000 milliseconds, or 5 seconds.
LeaseAcquireInterval (Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. Default is 13000 (13 seconds).
LeaseExpirationInterval (Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will move to another instance. Default is 60000 (60 seconds).
LeaseRenewInterval (Optional) When set, it defines, in milliseconds, the renew interval for all leases for partitions currently held by an instance. Default is 17000 (17 seconds).
MaxItemsPerInvocation (Optional) When set, this property sets the maximum number of items received per Function call. If operations in the monitored container are performed through stored procedures, transaction scope is preserved when reading items from the change feed. As a result, the number of items received could be higher than the specified value so that the items changed by the same transaction are returned as part of one atomic batch.
StartFromBeginning (Optional) This option tells the Trigger to read changes from the beginning of the container's change history instead of starting at the current time. Reading from the beginning only works the first time the trigger starts, as in subsequent runs, the checkpoints are already stored. Setting this option to true when there are leases already created has no effect.
StartFromTime (Optional) Gets or sets the date and time from which to initialize the change feed read operation. The recommended format is ISO 8601 with the UTC designator, such as 2021-02-16T14:19:29Z. This is only used to set the initial trigger state. After the trigger has a lease state, changing this value has no effect.
PreferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, "East US,South Central US,North Europe".

Decorators

Applies only to the Python v2 programming model.

For Python v2 functions defined by using a decorator, the cosmos_db_trigger (Extension 4.x) supports the following properties:

Property Description
arg_name The variable name used in function code that represents the list of documents with changes.
database_name The name of the Azure Cosmos DB database. Supports %VAR_NAME% syntax to reference app settings.
container_name The name of the Azure Cosmos DB container being monitored. Supports %VAR_NAME% syntax.
connection The name of an app setting or setting prefix for identity-based connections (for example, COSMOS_CONNECTION resolves to COSMOS_CONNECTION__accountEndpoint, and so on).
lease_container_name The name of the container used to store leases.
create_lease_container_if_not_exists When true, automatically creates the lease container if it doesn't exist.

For Python functions defined by using function.json, see the Configuration section.

Annotations

Because of schema changes in the Azure Cosmos DB SDK, version 4.x of the Azure Cosmos DB extension requires azure-functions-java-library V3.0.0 for Java functions.

Use the @CosmosDBTrigger annotation on parameters that read data from Azure Cosmos DB. The annotation supports the following properties:

Attribute property Description
connection The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being monitored. For more information, see Connections.
name The name of the function.
databaseName The name of the Azure Cosmos DB database with the container being monitored.
containerName The name of the container being monitored.
leaseConnectionStringSetting (Optional) The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account that holds the lease container.

When not set, the connection value is used. This parameter is automatically set when the binding is created in the portal. The connection string for the leases container must have write permissions.
leaseDatabaseName (Optional) The name of the database that holds the container used to store leases. When not set, the value of the databaseName setting is used.
leaseContainerName (Optional) The name of the container used to store leases. When not set, the value leases is used.
createLeaseContainerIfNotExists (Optional) When set to true, the leases container is automatically created when it doesn't already exist. The default value is false. When using Microsoft Entra identities if you set the value to true, creating containers isn't an allowed operation and your function app isn't allowed to start.
leasesContainerThroughput (Optional) Defines the number of Request Units to assign when the leases container is created. This setting is only used when CreateLeaseContainerIfNotExists is set to true. This parameter is automatically set when the binding is created using the portal.
leaseContainerPrefix (Optional) When set, the value is added as a prefix to the leases created in the Lease container for this function. Using a prefix allows two separate Azure Functions to share the same Lease container by using different prefixes.
feedPollDelay (Optional) The time (in milliseconds) for the delay between polling a partition for new changes on the feed, after all current changes are drained. Default is 5,000 milliseconds, or 5 seconds.
leaseAcquireInterval (Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. Default is 13000 (13 seconds).
leaseExpirationInterval (Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. If the lease isn't renewed within this interval, it expires and ownership of the partition moves to another instance. Default is 60000 (60 seconds).
leaseRenewInterval (Optional) When set, it defines, in milliseconds, the renewal interval for all leases for partitions currently held by an instance. Default is 17000 (17 seconds).
maxItemsPerInvocation (Optional) When set, this property sets the maximum number of items received per Function call. If operations in the monitored container are performed through stored procedures, transaction scope is preserved when reading items from the change feed. As a result, the number of items received could be higher than the specified value so that the items changed by the same transaction are returned as part of one atomic batch.
startFromBeginning (Optional) This option tells the Trigger to read changes from the beginning of the container's change history instead of starting at the current time. Reading from the beginning only works the first time the trigger starts, as in subsequent runs, the checkpoints are already stored. Setting this option to true when there are leases already created has no effect.
preferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, East US,South Central US,North Europe.

Configuration

Applies only to the Python v1 programming model.

The following table explains the properties that you can set on the options object you pass to the app.cosmosDB() method. The type, direction, and name properties don't apply to the v4 model.

The following table explains the binding configuration properties that you set in the function.json file, where properties differ by extension version:

function.json property Description
type Must be set to cosmosDBTrigger.
direction Must be set to in. This parameter is set automatically when you create the trigger in the Azure portal.
name The variable name used in function code that represents the list of documents with changes.
connection The name of an app setting or setting collection that specifies how to connect to the Azure Cosmos DB account being monitored. For more information, see Connections.
databaseName The name of the Azure Cosmos DB database with the container being monitored.
containerName The name of the container being monitored.
leaseConnection (Optional) The name of an app setting or setting container that specifies how to connect to the Azure Cosmos DB account that holds the lease container.

When not set, the connection value is used. This parameter is automatically set when the binding is created in the portal. The connection string for the leases container must have write permissions.
leaseDatabaseName (Optional) The name of the database that holds the container used to store leases. When not set, the value of the databaseName setting is used.
leaseContainerName (Optional) The name of the container used to store leases. When not set, the value leases is used.
createLeaseContainerIfNotExists (Optional) When set to true, the leases container is automatically created when it doesn't already exist. The default value is false. When using Microsoft Entra identities if you set the value to true, creating containers is not an allowed operation and your Function won't be able to start.
leasesContainerThroughput (Optional) Defines the number of Request Units to assign when the leases container is created. This setting is only used when createLeaseContainerIfNotExists is set to true. This parameter is automatically set when the binding is created using the portal.
leaseContainerPrefix (Optional) When set, the value is added as a prefix to the leases created in the Lease container for this function. Using a prefix allows two separate Azure Functions to share the same Lease container by using different prefixes.
feedPollDelay (Optional) The time (in milliseconds) for the delay between polling a partition for new changes on the feed, after all current changes are drained. Default is 5,000 milliseconds, or 5 seconds.
leaseAcquireInterval (Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. Default is 13000 (13 seconds).
leaseExpirationInterval (Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will move to another instance. Default is 60000 (60 seconds).
leaseRenewInterval (Optional) When set, it defines, in milliseconds, the renew interval for all leases for partitions currently held by an instance. Default is 17000 (17 seconds).
maxItemsPerInvocation (Optional) When set, this property sets the maximum number of items received per Function call. If operations in the monitored container are performed through stored procedures, transaction scope is preserved when reading items from the change feed. As a result, the number of items received could be higher than the specified value so that the items changed by the same transaction are returned as part of one atomic batch.
startFromBeginning (Optional) This option tells the Trigger to read changes from the beginning of the container's change history instead of starting at the current time. Reading from the beginning only works the first time the trigger starts, as in subsequent runs, the checkpoints are already stored. Setting this option to true when there are leases already created has no effect.
startFromTime (Optional) Gets or sets the date and time from which to initialize the change feed read operation. The recommended format is ISO 8601 with the UTC designator, such as 2021-02-16T14:19:29Z. This is only used to set the initial trigger state. After the trigger has a lease state, changing this value has no effect.
preferredLocations (Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Values should be comma-separated. For example, "East US,South Central US,North Europe".

For complete examples, see the Example section.

Usage

The trigger requires a second collection that it uses to store leases over the partitions. The trigger works only if both the collection you're monitoring and the collection that contains the leases are available.

Important

If you configure multiple functions to use an Azure Cosmos DB trigger for the same collection, each function should use a dedicated lease collection or specify a different LeaseCollectionPrefix for each function. Otherwise, only one of the functions is triggered. For information about the prefix, see the Attributes section.

Important

If you configure multiple functions to use an Azure Cosmos DB trigger for the same collection, each function should use a dedicated lease collection or specify a different leaseCollectionPrefix for each function. Otherwise, only one of the functions is triggered. For information about the prefix, see the Annotations section.

Important

If you configure multiple functions to use an Azure Cosmos DB trigger for the same collection, each function should use a dedicated lease collection or specify a different leaseCollectionPrefix for each function. Otherwise, only one of the functions is triggered. For information about the prefix, see the Configuration section.

The trigger doesn't indicate whether a document was updated or inserted. It just provides the document itself. If you need to handle updates and inserts differently, implement timestamp fields for insertion or update.

The parameter type supported by the Azure Cosmos DB trigger depends on the Functions runtime version, the extension package version, and the C# modality used.

When you want the function to process a single document, the Cosmos DB trigger can bind to the following types:

Type Description
JSON serializable types Functions tries to deserialize the JSON data of the document from the Cosmos DB change feed into a plain-old CLR object (POCO) type.

When you want the function to process a batch of documents, the Cosmos DB trigger can bind to the following types:

Type Description
IEnumerable<T>where T is a JSON serializable type An enumeration of entities included in the batch. Each entry represents one document from the Cosmos DB change feed.

Connections

The connection and leaseConnection properties are set to keys in application settings that return values used by the Functions runtime to connect to the Azure Cosmos DB account endpoints used by the extension. The value of these property settings depend on the type of connection:

  • Managed identity connection: The connection property is a <CONNECTION_NAME_PREFIX> shared by a group of settings that together define an identity-based connection to the account. For more information, see Define identity connections.
  • Key Vault reference: The connection property setting returns an Azure Key Vault reference to the location where the connection string is centrally maintained. For more information, see Define Key Vault connections.
  • App Configuration reference: The connection property setting returns an Azure App Configuration reference that returns a connection string or a Key Vault reference. For more information, see Azure App Configuration in the connections article.
  • Connection string: The connection property setting returns the actual account connection string. Because the connection string contains shared secret keys, you should consider using a managed identity connection, when possible. For more information, see Define connections.

To learn more about bindings connections, see Manage connection in Azure Functions. To obtain a connection string, navigate to your Azure Cosmos DB account, select Keys, and then copy the PRIMARY CONNECTION STRING or SECONDARY CONNECTION STRING values. These connection strings contain shared secret keys and must be kept secure.

In earlier versions of the extension, the connection properties were named connectionStringSetting and leaseConnectionStringSetting.

Next steps