I'm looking for a robust way to to handle database failres in Azure Function in a robust manner. In this example provided to use Lazy to reuse connection.
https://learn.microsoft.com/en-us/azure/azure-functions/manage-connections?tabs=csharp
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);
}
However, the code above is not robust, if the database is not available, the Lazy caches the wrong value. This actually happeneed to a deployment, database was shutdown, an API was called, and error persists even when the database came back online. I had to manually restart the Azure Function from portal.
I tried the Lazy with LazyThreadSafetyMode.PublicationOnly but it didn't work. What's the correct way to store db connection
- Robust to handle if database has connections errors, but comes back online later without needing to restart Azure Function.
- In scalable way across multiple instances