Azure Functions and Azure Cosmos DB trigger

This article explains how to use the Azure Cosmos DB trigger for Azure Functions. The Azure Cosmos DB output binding is also covered.

When you use an Azure Cosmos DB trigger, a function runs in response to changes in an Azure Cosmos DB container. The trigger provides a document that contains the changes that occurred.

Azure Cosmos DB trigger

The Azure Cosmos DB trigger is a pull model trigger. When the trigger starts, it creates a task that polls the Azure Cosmos DB container for changes. If changes are detected, the task receives a batch of documents that contain the changes. The task then provides these documents to your function.

The following table describes the properties that you can configure for the Azure Cosmos DB trigger:

Property Description Required
Connection The name of an app setting or connection string that stores the Azure Cosmos DB connection string. Yes
DatabaseName The name of the Azure Cosmos DB database. Yes
ContainerName The name of the Azure Cosmos DB container to monitor for changes. Yes
CreateLeaseContainerIfNotExists If true, a lease container is created if it doesn't exist. No (default: false)
LeaseContainerName The name of the lease container. If not specified, the default value is leases. No
PartitionKeyRangeID Use to limit the scope of the trigger to a specific partition key range. This is an advanced scenario. No
PreferredLocations A comma-separated list of Azure regions that are preferred for the trigger to connect to. No
StartFromBeginning If true, the trigger will attempt to read all documents from the beginning of the container. Use with caution in production environments. No (default: false)
MaxItemsPerInvocation The maximum number of documents to retrieve per function invocation. No (default: 20)

Azure Cosmos DB Trigger Attributes

When developing with C#, you can define the trigger using attributes. Here's an example:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;

public static class CosmosDbTriggerFunction
{
    [FunctionName("CosmosDbTrigger")]
    public static void Run(
        [CosmosDBTrigger(
            "ToDoList",
            "Items",
            Connection = "CosmosDBConnection",
            LeaseContainerName = "leases",
            CreateLeaseContainerIfNotExists = true)]IReadOnlyList<Document> documents,
        TraceWriter log)
    {
        log.Info($"Documents received: {documents.Count}");
        foreach (var document in documents)
        {
            log.Info($"Processing document: {document.Id}");
        }
    }
}

In this example:

  • ToDoList is the database name.
  • Items is the container name to monitor.
  • CosmosDBConnection is the name of the app setting that holds your Azure Cosmos DB connection string.
  • leases is the name of the lease container.
  • CreateLeaseContainerIfNotExists = true ensures the lease container is created if it doesn't exist.
  • The function receives a list of Document objects.

Lease Container

The lease container is used by the Azure Cosmos DB trigger to maintain state and coordinate multiple instances of your function. It stores lease documents that represent the current state of processing. Ensure that the lease container has a partition key defined, typically /id, for optimal performance.

Note: When using the CreateLeaseContainerIfNotExists property, Azure Functions will automatically create the lease container with a default throughput if it doesn't exist.

Azure Cosmos DB Output Binding

The Azure Cosmos DB output binding allows your function to write documents to an Azure Cosmos DB container. This is useful for tasks such as transforming data, logging events, or storing results.

The following table describes the properties that you can configure for the Azure Cosmos DB output binding:

Property Description Required
Connection The name of an app setting or connection string that stores the Azure Cosmos DB connection string. Yes
DatabaseName The name of the Azure Cosmos DB database. Yes
ContainerName The name of the Azure Cosmos DB container to write documents to. Yes
CreateIfNotExists If true, the container is created if it doesn't exist. No (default: false)

Azure Cosmos DB Output Binding Attributes

Here's an example of using the output binding in C#:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.Documents;
using System.Threading.Tasks;

public static class CosmosDbOutputFunction
{
    [FunctionName("CosmosDbOutput")]
    public static async Task Run(
        [QueueTrigger("myqueue-items")] string myQueueItem,
        [CosmosDB(
            "ToDoList",
            "ProcessedItems",
            Connection = "CosmosDBConnection",
            CreateIfNotExists = true)] out dynamic outputDocument,
        TraceWriter log)
    {
        log.Info($"C# Queue trigger function processed: {myQueueItem}");

        // Example of creating a document to be written to Cosmos DB
        var document = new Document
        {
            ["id"] = System.Guid.NewGuid().ToString(),
            ["message"] = myQueueItem,
            ["processedTimestamp"] = System.DateTime.UtcNow
        };

        outputDocument = document;
        log.Info($"Document written to Cosmos DB.");
    }
}

In this example:

  • The function is triggered by a message in a queue.
  • ToDoList is the database name.
  • ProcessedItems is the container name where documents will be written.
  • CosmosDBConnection is the app setting for the connection string.
  • CreateIfNotExists = true ensures the output container is created if it doesn't exist.
  • The out dynamic outputDocument parameter is used to pass the document to be written.

Best Practices

  • Partitioning: Design your Azure Cosmos DB containers with appropriate partition keys to ensure scalability and performance.
  • Throughput: Configure adequate Request Units (RUs) for both your main container and the lease container.
  • Error Handling: Implement robust error handling and retry mechanisms in your functions.
  • Monitoring: Monitor your Azure Functions and Azure Cosmos DB for performance and potential issues.
  • Connection Strings: Store connection strings securely in app settings or Key Vault, not directly in your code.
Tip: For large documents or high-volume writes, consider using the Azure Cosmos DB SDK directly within your function for more fine-grained control.