Connecting Azure Functions to Cosmos DB

Learn how Cosmos DB integrates with Azure Functions, from triggers to bindings.

Azure Functions

Cosmos DB works exceptionally well in a serverless architecture thanks to its change feed and binding for Azure Functions. In this lesson, we’ll see a realistic example of architecture and code for the following:

  • Triggers

  • Input binding

  • Output binding

Triggers

A trigger starts an Azure Function. For example, a trigger can be an HTTP request or a timer. In our case, we want to listen to container changes, and to do so, we need to use CosmosDBTrigger. The function is called automatically when documents change in a container.

The trigger requires some parameters to work:

  • databaseName: This is the name of the Cosmos DB database.

  • containerName: This is the name of the container.

  • connection: This is the name of the setting that contains the connection string.

The following are other optional parameters that can be useful:

  • LeaseContainerName: The name of the container lease information is stored (optional, default: "leases")

  • LeaseDatabaseName: The name of the database lease information is stored (optional, default: databaseName)

  • CreateLeaseContainerIfNotExists: If true, it creates the lease collection automatically (optional, false).

  • LeaseContainerPrefix: Consumer prefix in case we want to use the same lease container for multiple independent consumers

Note: We are referring to Microsoft.Azure.WebJobs.Extensions.CosmosDB v4, which uses Microsoft.Azure.Cosmos v3.

Let’s see a basic example: a trigger for our iotEvents container.

Get hands-on with 1200+ tech skills courses.