/
How to manage connections ?

How to manage connections ?

Functions in a function app share resources. Among those shared resources are connections: HTTP connections, database connections, and connections to services such as Azure Storage.

The potentiel issue

Functions running in concurrency mode (>600 active connections that is the limit per instance)

The method to avoid to use more connections that we need

We can reuse client instances rather than creating new ones with each function invocation : use a single static client (for example, .NET clients - HttpClient, DocumentClient, Azure Storage Clients,…).

Static client helping to reuse connections

Example with Http request

// Create a single, static HttpClient private static HttpClient httpClient = new HttpClient(); public static async Task Run(string input) { var response = await httpClient.GetAsync("https://example.com"); // Rest of function }

Remark : We don't dispose of a static client because we aren't done using it when the function ends. We want the static client to live for the duration of the application. So, we don’t need to implement the IDisposable Interface in code.

Example with zure Cosmos DB client

#r "Microsoft.Azure.Cosmos" using Microsoft.Azure.Cosmos; private static Lazy<CosmosClient> lazyClient = new Lazy<CosmosClient>(InitializeCosmosClient); private static CosmosClient cosmosClient => lazyClient.Value; private static CosmosClient InitializeCosmosClient() { // Perform any initialization here var uri = "https://youraccount.documents.azure.com:443"; var authKey = "authKey"; return new CosmosClient(uri, authKey); } public static async Task Run(string input) { Container container = cosmosClient.GetContainer("database", "collection"); MyItem item = new MyItem{ id = "myId", partitionKey = "myPartitionKey", data = "example" }; await container.UpsertItemAsync(document); // Rest of function } //don't forget to add the below content in the "function.proj" <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.23.0" /> </ItemGroup> </Project>