📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

What is your scaling strategy for a web system as load grows? Compare vertical and horizontal scaling, explain why stateless services matter, and when you would add caching, read replicas, partitioning and queues — in what order, and why.

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.

Mid-Level Theory Intermediate caching horizontal-scaling partitioning read-replicas scalability system-design

๐ŸŽฏ Key points

  • Vertical scaling (bigger instance) is simplest but has a ceiling, a single failure point and rising cost per unit
  • Horizontal scaling needs stateless services: no in-memory session, shared cache, external Data Protection keys
  • Scale the cheap tier first: stateless app instances behind a load balancer with autoscale
  • Cache reads (HybridCache/Redis) before scaling the database; accept staleness up to the expiry
  • Read replicas offload reads but add replication lag (read-your-writes issues)
  • Queues level load spikes and decouple slow work from the request path
  • Watch database connection limits: instances × pool size must stay under the server's limit
  • Measure the bottleneck and the cost first (Application Insights, Query Store, Cost Management); each step adds operational overhead

โฑ 30-second answer

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:

  • Scale out stateless app instances with autoscale.
  • Cache hot reads (HybridCache, Redis), then add read replicas.
  • Move slow or spiky work to queues (Service Bus).
  • Partition data only when one database can't handle the writes or size.

Each step trades simplicity for capacity: caches and replicas bring staleness, queues bring eventual consistency, and sharding brings cross-shard queries and operational pain.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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 vs horizontal

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

The scaling ladder

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

Capacity check

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

Production example

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.

๐Ÿ” What the interviewer is checking

Checks whether the candidate scales systematically from measurement, understands statelessness, and knows the cost of each scaling step.

Green flags

  • Measures the bottleneck before choosing a lever
  • Knows ASP.NET Core statelessness details (Data Protection keys, sessions)
  • Orders steps from cheap to complex
  • Mentions replica lag and idempotent consumers

Red flags

  • "Add Kubernetes and microservices" as the scaling plan
  • Sticky sessions as the answer to state
  • Sharding before caching or indexing

๐Ÿ“š Learn in depth

1. Why statelessness is the precondition

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.
  • Data Protection keys stored on the local file system (cookies and antiforgery tokens fail across instances).
  • Files written to local disk.
  • IMemoryCache used for data that must be consistent across instances.

2. Where bottlenecks move

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.

3. Caching mechanics

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.

4. Read replicas and lag

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.

5. Queue-based load levelling

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.

6. Partitioning last

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.

Try it yourself

  1. Run an ASP.NET Core app with two instances behind a local YARP proxy and log in; observe cookie failures without shared Data Protection keys, then fix them.
  2. Load test one instance with k6 or Azure Load Testing to find its real requests/s.
  3. Add HybridCache to a read endpoint and compare database calls per second in Application Insights before and after.
  4. Configure a read-only connection string with ApplicationIntent=ReadOnly and measure replica lag by writing then reading immediately.
  5. Move an email-sending call into a Service Bus queue and compare p95 latency of the API.

๐Ÿ’ป Code

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);

โš  Common mistakes

  • Mistake: Scaling out a stateful app. Why it is wrong: In-memory sessions, local files and local Data Protection keys break as soon as requests land on another instance. Instead: Externalise state: Redis, Blob Storage, a shared key ring.
  • Mistake: Relying on sticky sessions. Why it is wrong: They unbalance load and lose state on scale-in, deploys and failures. Instead: Make the service stateless and turn affinity off.
  • Mistake: Ignoring database connection limits when scaling out. Why it is wrong: Each instance has its own ADO.NET pool (default max 100), so 40 instances can try to open 4,000 connections and hit the Azure SQL tier's session or worker limits, causing failures that look like a database outage. Instead: Calculate instances ร— max pool size against the tier's limits, cap Max Pool Size, and alert on connection counts.
  • Mistake: Scaling the database before caching. Why it is wrong: A bigger tier is expensive and often unnecessary for repeated reads. Instead: Cache hot reads and fix slow queries first.
  • Mistake: Reading your own writes from a replica. Why it is wrong: Asynchronous replication means the replica may be behind, so users don't see what they just saved. Instead: Route read-after-write paths to the primary.
  • Mistake: Sharding early. Why it is wrong: It adds cross-shard queries, rebalancing and operational cost for a problem you may not have. Instead: Partition when write throughput or size measurably exceeds one database.
  • Mistake: Autoscaling on the wrong signal. Why it is wrong: CPU may stay low while requests queue on a downstream dependency, so more instances only add load to the bottleneck. Instead: Scale on the constrained resource and check the dependency first.
  • Mistake: Scaling without measuring or costing. Why it is wrong: You may scale the tier that isn't the bottleneck, or buy capacity whose monthly cost exceeds the problem. Instead: Use Application Insights dependency timings and Query Store to find the bottleneck, and Azure Cost Management to see what each step costs.

๐Ÿ› Senior insight: trade-offs

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

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate adds a cache in front of the database Why: Checks how they keep caches consistent across many instances
    How to answer

    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.

  2. When: Candidate mentions partitioning or sharding a SQL database Why: Checks practical knowledge of partitioning, Hyperscale and elastic pools
    How to answer

    I start with numbers: data size and growth, hot versus cold data, read/write ratio and tenant distribution. Then:

    • Partitioning (by date) is mainly a manageability tool: 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.
    • Archive cold data to cheaper storage or a history database.
    • Tenant layout: shared schema for many small tenants, database per tenant in an elastic pool for isolation, a hybrid for large tenants.
    • Hyperscale for one large database (up to 128 TB, fast scaling, read replicas); elastic pools for many small databases sharing compute.

    Shard only when scale-up, read scale-out and archiving are exhausted: it moves complexity into the application.

  3. When: Candidate puts instances behind a load balancer Why: Checks understanding of load balancing, health checks and draining
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

๐Ÿ›  Real-world problems: how you handle them

Sales-day database saturation fixed without a bigger tier
Situation
[Company]'s [retail] API on App Service with one Azure SQL database served about [n] requests/s normally and [m] during sales events.
Signals
Azure SQL DTU/CPU at 95–100% during sales; p95 latency rising from [x] ms to [y] s; Application Insights showing SQL dependency time dominating; timeouts on checkout.
Investigation
Query Store showed [the top queries] were repeated product and price lookups; Application Insights dependency telemetry confirmed [percentage]% of SQL calls were reads of the same few thousand products. A load test reproduced the saturation at [k] requests/s.
Resolution
Immediately scaled the database up one tier for the event. Then added HybridCache over Redis for product and price reads with tag invalidation on price changes, and routed reporting queries to a readable secondary.
Prevention
Load test before each sales event with Azure Load Testing; Azure Monitor alerts on DTU above 80% and cache hit ratio below [threshold]; ADR documenting the cache and invalidation design.

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.

โ†ฉ Usually asked after

More in Core System Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me