Migrate function apps from Azure Cosmos DB extension version 3.x to version 4.x

This article highlights considerations for upgrading your existing Azure Functions applications that use the Azure Cosmos DB extension version 3.x to use the newer extension version 4.x. Migrating from version 3.x to version 4.x of the Azure Cosmos DB extension has breaking changes for your application.

Important

On August 31, 2024 the Azure Cosmos DB extension version 3.x will be retired. The extension and all applications using the extension will continue to function, but Azure Cosmos DB will cease to provide further maintenance and support for this extension. We recommend migrating to the latest version 4.x of the extension.

This article walks you through the process of migrating your function app to run on version 4.x of the Azure Cosmos DB extension. Because project upgrade instructions are language dependent, make sure to choose your development language from the selector at the top of the article.

Changes to item ID generation

Item ID is no longer auto populated in the Extension. Therefore, the Item ID must specifically include a generated ID for cases where you were using the Output Binding to create items. To maintain the same behavior as the previous version, you can assign a random GUID as ID property.

Update the extension version

.NET Functions use bindings that are installed in the project as NuGet packages. Depending on your Functions process model, the NuGet package to update varies.

Functions process model Azure Cosmos DB extension Recommended version
In-process model Microsoft.Azure.WebJobs.Extensions.CosmosDB >= 4.3.0
Isolated worker model Microsoft.Azure.Functions.Worker.Extensions.CosmosDB >= 4.4.1

Update your .csproj project file to use the latest extension version for your process model. The following .csproj file uses version 4 of the Azure Cosmos DB extension.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.21.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.CosmosDB" Version="4.6.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.16.4" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Update the extension bundle

By default, extension bundles are used by non-.NET function apps to install binding extensions. The Azure Cosmos DB version 4 extension is part of the Microsoft Azure Functions version 4 extension bundle.

To update your application to use the latest extension bundle, update your host.json. The following host.json file uses version 4 of the Microsoft Azure Functions extension bundle.

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

Rename the binding attributes

Both in-process and isolated process C# libraries use the CosmosDBTriggerAttribute to define the function.

The following table only includes attributes that were renamed or were removed from the version 3 extension. For a full list of attributes available in the version 4 extension, visit the attribute reference.

Version 3 attribute property Version 4 attribute property Version 4 attribute description
ConnectionStringSetting 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.
CollectionName ContainerName The name of the container being monitored.
LeaseConnectionStringSetting 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.
LeaseCollectionName LeaseContainerName (Optional) The name of the container used to store leases. When not set, the value leases is used.
CreateLeaseCollectionIfNotExists 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 won't be able to start.
LeasesCollectionThroughput 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.
LeaseCollectionPrefix 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.
UseMultipleWriteLocations Removed This attribute is no longer needed as it's automatically detected.
UseDefaultJsonSerialization Removed This attribute is no longer needed as you can fully customize the serialization using built in support in the Azure Cosmos DB version 3 .NET SDK.
CheckpointInterval Removed This attribute has been removed in the version 4 extension.
CheckpointDocumentCount Removed This attribute has been removed in the version 4 extension.

Rename the binding attributes

Update your binding configuration properties in the function.json file.

The following table only includes attributes that changed or were removed from the version 3.x extension. For a full list of attributes available in the version 4 extension, visit the attribute reference.

Version 3 attribute property Version 4 attribute property Version 4 attribute description
connectionStringSetting 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.
collectionName containerName The name of the container being monitored.
leaseConnectionStringSetting 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.
leaseCollectionName leaseContainerName (Optional) The name of the container used to store leases. When not set, the value leases is used.
createLeaseCollectionIfNotExists 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 won't be able to start.
leasesCollectionThroughput 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.
leaseCollectionPrefix 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.
useMultipleWriteLocations Removed This attribute is no longer needed as it's automatically detected.
checkpointInterval Removed This attribute has been removed in the version 4 extension.
checkpointDocumentCount Removed This attribute has been removed in the version 4 extension.

Modify your function code

The Azure Functions extension version 4 is built on top of the Azure Cosmos DB .NET SDK version 3, which removed support for the Document class. Instead of receiving a list of Document objects with each function invocation, which you must then deserialize into your own object type, you can now directly receive a list of objects of your own type.

This example refers to a simple ToDoItem type.

namespace CosmosDBSamples
{
    // Customize the model with your own desired properties
    public class ToDoItem
    {
        public string id { get; set; }
        public string Description { get; set; }
    }
}

Changes to the attribute names must be made directly in the code when defining your Function.

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

namespace CosmosDBSamples
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "databaseName",
            containerName: "containerName",
            Connection = "CosmosDBConnectionSetting",
            LeaseContainerName = "leases",
            CreateLeaseContainerIfNotExists = true)]IReadOnlyList<ToDoItem> input, ILogger log)
        {
            if (input != null && input.Count > 0)
            {
                log.LogInformation("Documents modified " + input.Count);
                log.LogInformation("First document Id " + input[0].id);
            }
        }
    }
}

Note

If your scenario relied on the dynamic nature of the Document type to identify different schemas and types of events, you can use a base abstract type with the common properties across your types or dynamic types like JObject (when using Microsoft.Azure.WebJobs.Extensions.CosmosDB) and JsonNode (when using Microsoft.Azure.Functions.Worker.Extensions.CosmosDB) that allow to access properties like Document did.

Additionally, if you are using the Output Binding, please review the change in item ID generation to verify if you need additional code changes.

Modify your function code

After you update your host.json to use the correct extension bundle version and modify your function.json to use the correct attribute names, there are no further code changes required for cases where you are using Input Bindings or Trigger. If you are using the Output Binding, please review the change in item ID generation to verify if you need additional code changes.

Next steps