A staged scaling strategy: vertical vs horizontal scaling, stateless ASP.NET Core services, caching, read replicas, queue-based load levelling and partitioning, with the order to apply them and the trade-offs of each.
Vertical scaling means a bigger machine โ simple, but it has a ceiling and stays a single point of failure. Horizontal scaling means more instances, which requires stateless services: no in-memory sessions, a shared cache, and shared ASP.NET Core Data Protection keys.
My order, driven by where the bottleneck is:
Each step trades simplicity for capacity: caches and replicas bring staleness, queues bring eventual consistency, and sharding brings cross-shard queries and operational pain.
"I scale in the order that gives the most capacity for the least complexity, and only after measuring where the bottleneck actually is. Vertical scaling is the first lever because it's one setting โ move the App Service plan or the Azure SQL tier up โ but it has a ceiling, it costs more per unit at the top, and it's still one box.
Horizontal scaling is the real answer for the app tier, and it depends on the service being stateless. In ASP.NET Core that means no in-memory session, no local file uploads, a distributed or hybrid cache, and Data Protection keys stored centrally โ Blob Storage protected by Key Vault โ otherwise auth cookies issued by one instance fail on another. Once it's stateless I put it behind a load balancer with autoscale rules on CPU or request queue length. For example, on [system] we [scaled from n to m instances during peak] by [what you changed].
Usually the database becomes the bottleneck next. I cache hot reads first โ HybridCache in .NET 9 and later gives a local L1 plus Redis L2 with stampede protection โ then add read replicas for read-heavy queries, accepting replication lag. Slow or spiky work, like sending emails or generating PDFs, moves off the request path into Service Bus so the queue absorbs bursts. Only when writes or data size outgrow a single database do I partition or shard. The mistake I see is teams jumping to sharding or microservices when a cache and one index would have bought them three years."
| Vertical (scale up) | Horizontal (scale out) | |
|---|---|---|
| How | Bigger SKU | More instances |
| Limit | Largest SKU | Shared dependencies (DB, cache) |
| Failure | Single point | Survives instance loss |
| Needs | Nothing | Stateless design, load balancer |
| Typical use | Databases, early stage | App tier, workers |
| Step | Solves | Introduces | Azure / .NET |
|---|---|---|---|
| 1. Scale out app | CPU/thread limits on app | Need for statelessness | App Service / Container Apps autoscale |
| 2. Cache | Repeated reads | Staleness, invalidation | HybridCache, Azure Managed Redis |
| 3. CDN | Static and cacheable content | Purge strategy | Azure Front Door |
| 4. Read replicas | Read load on primary | Replication lag | Azure SQL readable secondaries (ApplicationIntent=ReadOnly) |
| 5. Queues | Spikes, slow work | Eventual consistency, retries | Service Bus, BackgroundService |
| 6. Partition / shard | Write throughput, size | Cross-partition queries, rebalancing | Cosmos DB, Azure SQL Hyperscale, elastic pools |
| Item | Value |
|---|---|
| Peak requests/s | 3,000 |
| Per-instance capacity (load tested) | ~600/s |
| Instances at peak (70% target) | 3,000 รท (600 ร 0.7) โ 8 |
| DB reads after 90% cache hits | 3,000 ร 0.8 reads ร 0.1 โ 240/s |
Front Door
|
+-------+-------+
| App x N | stateless ASP.NET Core
+---+-------+---+
| |
Redis Service Bus --> workers
|
Azure SQL primary --> readable secondary
A retail API hit 95% DTU on its Azure SQL database during sales. Adding HybridCache for product and price reads (5-minute expiry with tag invalidation on price change) cut database reads by about 85%, and routing reporting queries to a readable secondary removed the remaining spikes. The planned move to a larger tier, roughly doubling cost, was not needed.
Checks whether the candidate scales systematically from measurement, understands statelessness, and knows the cost of each scaling step.
Green flags
Red flags
A load balancer may send consecutive requests from one user to different instances. Any state held in memory on one instance โ session, an upload in progress, a cache entry, a Data Protection key ring โ is missing on the others. Sticky sessions hide the problem but break on scale-in, deployments and instance failure.
In ASP.NET Core, the usual offenders are:
AddSession with the in-memory IDistributedCache.IMemoryCache used for data that must be consistent across instances.load -> app CPU -> scale out app
DB reads -> cache, replicas
DB writes -> batch, queue, partition
one hot key -> re-key, split, cache
external API limits -> queue + rate limiter
Each fix moves the bottleneck to the next layer. That's expected; measure again after every step.
HybridCache (Microsoft.Extensions.Caching.Hybrid) combines a per-instance in-memory L1 with a distributed L2 such as Redis and collapses concurrent misses for the same key into one factory call, which prevents a cache stampede. Tags allow invalidating groups of entries. The cost is staleness up to the expiry, or the work of explicit invalidation.
Azure SQL Premium/Business Critical and Hyperscale offer readable secondaries; connecting with ApplicationIntent=ReadOnly routes to them. Replication is asynchronous to readable replicas, so a user who just saved data may not see it on the replica. Route read-your-writes paths to the primary.
A queue between the request path and slow work turns a spike of 5,000 requests into a backlog that workers drain at a steady rate. The API returns 202 Accepted with a status URL. You need idempotent consumers (messages can be delivered more than once), dead-letter handling and an alert on queue age.
Partitioning splits data by a key so writes spread across nodes. It's powerful and expensive: choosing the key, avoiding hot partitions, cross-partition queries and rebalancing all become your problem. Do it when write throughput or size demands it, not before.
HybridCache to a read endpoint and compare database calls per second in Application Insights before and after.ApplicationIntent=ReadOnly and measure replica lag by writing then reading immediately.Making an ASP.NET Core service ready to scale out: shared Data Protection keys, HybridCache over Redis, and slow work handed to a queue.
// Program.cs โ .NET 10
using Azure.Identity;
using Azure.Messaging.ServiceBus;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Caching.Hybrid;
var builder = WebApplication.CreateBuilder(args);
var credential = new DefaultAzureCredential();
// 1. Shared key ring so cookies issued by one instance are valid on all of them.
builder.Services.AddDataProtection()
.SetApplicationName("shop-api")
.PersistKeysToAzureBlobStorage(new Uri(builder.Configuration["DataProtection:BlobUri"]!), credential)
.ProtectKeysWithAzureKeyVault(new Uri(builder.Configuration["DataProtection:KeyUri"]!), credential);
// 2. L1 in-process + L2 Redis, with stampede protection.
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddHybridCache(o => o.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5),
LocalCacheExpiration = TimeSpan.FromMinutes(1),
});
// 3. Queue client for work that shouldn't block the request.
builder.Services.AddSingleton(new ServiceBusClient(builder.Configuration["ServiceBus:Namespace"], credential));
var app = builder.Build();
app.MapGet("/products/{id:guid}", async (Guid id, HybridCache cache, CancellationToken ct) =>
await cache.GetOrCreateAsync($"product:{id}",
async token => await LoadProductAsync(id, token),
tags: ["products"], cancellationToken: ct));
app.MapPost("/reports", async (ReportRequest request, ServiceBusClient bus, CancellationToken ct) =>
{
await using var sender = bus.CreateSender("reports");
await sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromObjectAsJson(request)) { MessageId = request.RequestId.ToString() }, ct);
return Results.Accepted($"/reports/{request.RequestId}");
});
app.Run();
static Task<Product> LoadProductAsync(Guid id, CancellationToken ct) =>
Task.FromResult(new Product(id, "Sample", 10m)); // stand-in for EF Core
public sealed record Product(Guid Id, string Name, decimal Price);
public sealed record ReportRequest(Guid RequestId, DateOnly From, DateOnly To);
Max Pool Size, and alert on connection counts.Seniors scale the bottleneck, not the architecture. They measure first, change one thing, and measure again, because every fix moves the bottleneck. They also know that more app instances can make things worse: each instance opens its own connection pool to the database, so scaling the app from 5 to 50 instances can exhaust database connections or worker limits.
They weigh each step against cost and the team's capacity to run it. A Redis cluster, read replicas and a queue each add monitoring, alerting, runbooks and on-call knowledge; a small team may be better served by a bigger database tier than by three new moving parts. Geography matters too: for users spread across regions, latency is dominated by distance, so a CDN or regional read replicas help more than extra instances in one region โ but for an Australian-only audience, one region (Australia East) with zone redundancy is usually enough. Every step is also a consistency decision: caching and replicas mean stale reads, queues mean the user sees 'processing', partitioning means some queries become expensive.
| Lever | When it fits | Cost | When not to |
|---|---|---|---|
| Scale up | Quick relief, databases | Price at top tiers, ceiling | Need for redundancy |
| Scale out app | CPU-bound stateless app | Connection pressure on DB | App is stateful |
| Cache | Read-heavy, tolerate seconds of staleness | Invalidation, another service to run | Must always be fresh |
| Read replica | Reporting, heavy reads, distant users | Lag, replica cost | Read-your-writes paths |
| Queue | Spikes, slow work | Async UX, idempotency | User needs result immediately |
| Partition | Write/size limits | Cross-partition queries, team skill | One database still copes |
With 20 instances, a local cache is fastest but each instance holds its own version, while a distributed cache (Redis) gives one shared version at the cost of a network hop. I usually combine them: a short-lived L1 in each instance in front of a shared L2, which is exactly what HybridCache provides.
To keep L1 copies in line, I publish invalidation messages (Redis pub/sub or an Azure Service Bus topic) that every instance uses to evict keys. Messages can be missed, so the L1 lifetime is the real staleness bound.
I choose per data class: data that must agree everywhere skips L1, tolerant data gets longer L1. The trade-off is latency and Redis load versus how long instances may disagree.
I start with numbers: data size and growth, hot versus cold data, read/write ratio and tenant distribution. Then:
SWITCH makes archiving and purging metadata-only and enables partition-level index rebuilds. It is not an automatic speed-up and needs queries that allow partition elimination.Shard only when scale-up, read scale-out and archiving are exhausted: it moves complexity into the application.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
How to tell it (STAR)
**S:** At [company], our [retail] API's database hit 100% during sales and checkout started timing out. **T:** I needed to stop it happening at the next sale without doubling the database cost. **A:** I used Query Store and Application Insights to show that most load was repeated product and price reads. I added HybridCache over Redis with tag-based invalidation when prices changed, moved reporting queries to a readable secondary, and load-tested at [k] requests/s. **R:** Database reads dropped by about [percentage]%, peak CPU stayed under [x]%, p95 stayed under [y] ms during the next sale, and we avoided the bigger tier.
Last updated 23 Nov 2026.