Search code examples
azure-cosmosdbblazor-client-sideblazor-webassembly

Assign CosmosClientOptions.ApplicationRegion based on user's location in Blazor web assembly project


I am using Microsoft.Azure.Cosmos.Client for connecting cosmos database from blazor web assembly project. My Cosmos database has multiple read regions, i.e South Korea (base location) and Japan East(Read region).

I want my blazor client application to load data from nearest cosmos database location. For that I was hoping that cosmos database automatically routes request to the nearest server, but it was always loading data from South Korea. To solve that I tried to specify CosmosClientOptions.ApplicationRegion property with fixed value like code below:

            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                ConnectionMode = ConnectionMode.Gateway,
                ApplicationRegion = Regions.JapanEast // need to set this property dynamically based on users location
                
                //ApplicationPreferredRegions = new List<string>() { Regions.JapanEast, Regions.KoreaSouth } //Also tried this, but always loading from Japan east even if accessed from South Korea
            };

            client = new CosmosClient(Credentials.EndPoint, Credentials.ResourceToken, clientOptions);

In that case it always load data from Japan East server. I also tried setting LimitToEndpoint = true property but couldn't get myself much clarified on it.

Any suggestions?


Solution

  • The Cosmos client does not have any network metrics that automatically tells it what is the closest region to connect to. You have to specify that value. Preferred regions is simply an array of regions to connect to in order should a region become unavailable.

    Customers often specify the value for region name in the regional deployment for the application. So you should look to your deployment scripts to pass this value.