Designing Active‑Active Multi‑Region .NET 8 APIs with Azure Front Door and Cosmos DB Multi‑Master

Mahmut Sarıkaya 4 dk okuma 14 Görüntülenme 0
Designing Active‑Active Multi‑Region .NET 8 APIs with Azure Front Door and Cosmos DB Multi‑Master

Why active‑active matters for modern .NET 8 APIs

Imagine a user in Tokyo experiencing a 2‑second latency while your API runs in a single West‑Europe data centre. According to the 2023 Cloud Latency Report, 42% of global users abandon a request that exceeds 1.5 seconds. An active‑active architecture distributes traffic across several regions, keeping the round‑trip time under 80 ms for 90% of users. .NET 8 introduces native support for minimal APIs, async streams, and improved TLS handling, making it the perfect foundation for a truly global service.

Choosing Azure Front Door as the global entry point

Azure Front Door acts as a layer‑7 load balancer that routes HTTP/HTTPS requests to the nearest healthy region. Its latency‑based routing, SSL termination, and Web Application Firewall (WAF) let you enforce security policies before traffic reaches your .NET 8 services. To enable caching of static assets and reduce origin calls, configure a 5‑minute default TTL.

az network front-door create \
  --name MyFrontDoor \
  --resource-group MyRG \
  --backend-pool-name api-pool \
  --backend-address myapi-eastus.azurewebsites.net myapi-westeurope.azurewebsites.net \
  --frontend-endpoint-name www.myapi.com \
  --routing-rule-name default-route \
  --accepted-protocols Https \
  --patterns-to-match "/*" \
  --enable-waf true

The command creates a Front Door instance with two back‑ends representing East US and West Europe. After deployment, verify that az network front-door show reports a health status of "Healthy" for each region.

Implementing Cosmos DB multi‑master for true data locality

Cosmos DB multi‑master replicates data to every configured region, providing low‑latency writes without a single‑region write‑lock. Set the consistency level to "Session" to balance performance and correctness for most e‑commerce scenarios. In .NET 8, the CosmosClient can be instantiated with ApplicationRegion so the SDK prefers the nearest replica.

using Microsoft.Azure.Cosmos;

var client = new CosmosClient(
    "AccountEndpoint=https://myaccount.documents.azure.com:443/;AccountKey=***;",
    new CosmosClientOptions
    {
        ApplicationRegion = "East US",
        ConsistencyLevel = ConsistencyLevel.Session,
        ConnectionMode = ConnectionMode.Gateway
    });

var container = client.GetContainer("OrdersDb", "Orders");
await container.CreateItemAsync(order, new PartitionKey(order.CustomerId));

Because each region holds a writable replica, a user in Germany will write to the West Europe replica, and the change propagates to East US within 200 ms on average, according to Microsoft’s internal benchmark of 2023.

Leveraging distributed caching with Azure Cache for Redis

Even with multi‑master, repeated reads of hot catalog data can overload Cosmos DB RU/s. Azure Cache for Redis provides a fast, in‑memory layer that can be shared across regions through geo‑replication. Store product listings for 10‑minute intervals, and fall back to the database on a cache miss.

using StackExchange.Redis;

var redis = ConnectionMultiplexer.Connect("myredis.redis.cache.windows.net:6380,password=***,ssl=True,abortConnect=False");
IDatabase db = redis.GetDatabase();

string cacheKey = $"product:{productId}";
string json = await db.StringGetAsync(cacheKey);
if (json == null)
{
    var product = await container.ReadItemAsync(productId, new PartitionKey(productId));
    await db.StringSetAsync(cacheKey, JsonSerializer.Serialize(product), TimeSpan.FromMinutes(10));
    return product;
}
return JsonSerializer.Deserialize(json);

This pattern reduces RU consumption by up to 70% for read‑heavy workloads, according to the Azure Cache performance guide published in March 2024.

Resilient patterns: retry, circuit breaker, and idempotency

Network partitions between regions are inevitable. Polly, the .NET resilience library, lets you declaratively add retries with exponential back‑off, circuit breakers that open after five consecutive failures, and fallback policies that serve stale cache data.

using Polly;
using Polly.CircuitBreaker;

var retryPolicy = Policy.Handle<CosmosException>()
    .WaitAndRetryAsync(3, attempt => TimeSpan.FromMilliseconds(200 * Math.Pow(2, attempt)));

var circuitBreaker = Policy.Handle<Exception>()
    .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));

var resilientPolicy = Policy.WrapAsync(retryPolicy, circuitBreaker);

await resilientPolicy.ExecuteAsync(async () =>
{
    await container.ReadItemAsync<Order>(orderId, new PartitionKey(orderId));
});

Combine this with idempotent command design—use a deterministic request ID stored in Cosmos DB—to guarantee that retries do not create duplicate orders.

Putting it all together: a step‑by‑step deployment checklist

1. Provision two Azure App Service plans (East US, West Europe) and deploy the same .NET 8 API package. 2. Create an Azure Front Door instance with both back‑ends and enable WAF rules for OWASP Top 10. 3. Set up a Cosmos DB account with multi‑master enabled in the same regions; configure Session consistency. 4. Deploy Azure Cache for Redis with geo‑replication and add the caching layer to the data‑access code. 5. Add Polly policies to every external call and store a unique CorrelationId for tracing. 6. Verify end‑to‑end latency with Azure Application Insights by generating traffic from three continents; aim for <150 ms average response time. 7. Enable Azure Monitor alerts for circuit‑breaker trips and RU‑exhaustion.

Conclusion

Designing an active‑active multi‑region .NET 8 API is no longer a theoretical exercise; Azure provides a cohesive toolbox—Front Door for global routing, Cosmos DB multi‑master for low‑latency writes, and Redis for distributed caching. By coupling these services with proven resilience patterns like retry and circuit breaker, you can deliver sub‑200 ms experiences to users worldwide while keeping operational costs predictable.

Sources

Microsoft Azure Documentation – Front Door, Cosmos DB Multi‑Master, Azure Cache for Redis; Polly Project GitHub README; 2023 Cloud Latency Report (CloudNative Insights)

Author: Mahmut Sarıkaya — sarikayadev.com

Etiketler: #dotnet 8 #active‑active architecture #azure front door #cosmos db multi‑master #distributed caching
Paylaş:
M

Yazar

Mahmut Sarıkaya

yazılım Geliştirici

Yorumlar

Henüz yorum yok. İlk yorumu siz yapın!

Yorum Bırakın

4 + 4 =