0

I have been reading this Microsoft blog around optimizing CosmosDB initialisation. TLDR; you can improve latency on your first few calls by using CreateAndInitializeAsync

As my application is hosted on AKS the pods could potentially be restarted so this optimization would be nice to have.

I would typically use ConfigureServices to register a singleton instance of CosmosClient in an IServiceCollection, however this cannot be run asynchronously. I could run CreateAndInitializeAsync synchronously instead but that could potentially block application start-up. A transient failure with CreateAndInitializeAsync could also block start-up if used here.

Is there a way of safely utilizing CreateAndInitializeAsync in a .NET Core Application?

Amicable
  • 3,115
  • 3
  • 49
  • 77
  • Resolving instances can never be asynchronous. This is simply not something that MS.DI (or any other DI container for that matter) supports. You should, therefore, consider other options, such as hiding `CosmosDB` behind an application-specific abstraction so that you can ensure either eager loading at startup or lazy loading at runtime, without application code needing to be affected by this. See for instance [this](https://stackoverflow.com/a/43240576/264697). – Steven Jul 06 '23 at 14:49

1 Answers1

0

CreateAndInitializeAsync should handle transient failures correctly in order to still complete execution even if there are network conditions affecting the initialization optimization.

The only scenarios where an exception should be thrown is if the inputs to the method are invalid (for example, you are passing an empty list of Containers, or the names are null, or the authentication keys/tokens are empty).

Matias Quaranta
  • 13,907
  • 1
  • 22
  • 47