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

📚 Interview question

You've drawn a design on the whiteboard and the interviewer asks: "Where does this break first as load grows?" How do you find the bottlenecks in a design? Walk me through the usual suspects — the single database, hot partitions, synchronous call chains and shared locks — how you spot each one from the diagram and the numbers, and what you do about it.

Finding bottlenecks in a system design: utilisation from capacity estimates, the single database, hot partitions, synchronous call chains, shared locks and serialisation points, and the fix for each.

Mid-Level Theory Intermediate bottlenecks capacity-estimation hot-partitions performance scalability system-design

🎯 Key points

  • Walk the request path and compute utilisation per component (load ÷ measured capacity) from the capacity table; the highest ratio breaks first
  • Single relational database: writes cannot scale out; mitigate with caching, read replicas, CQRS read models, a bigger tier (Business Critical, Hyperscale), then partitioning
  • Hot partition or hot key: skewed key distribution (celebrity user, today's date, one big tenant) defeats horizontal scaling
  • Synchronous chains multiply latency and failure: p99 of N serial calls, availability = product of each
  • Shared locks and serialisation points: global counters, single-row balances, sp_getapplock, singleton workers
  • Little's Law (concurrency = throughput × latency) explains pool exhaustion: DB connection pools, SNAT ports, ThreadPool
  • Fix order: remove work, cache (with an invalidation plan), make async with a queue, partition; prove it with a load test (Azure Load Testing, k6) and Application Insights
  • Name the next bottleneck after each fix — bottlenecks move, they don't disappear

⏱ 30-second answer

I find bottlenecks by walking the request path with numbers: for each component I compare the expected load from the capacity estimate with what it can handle, and the highest utilisation breaks first. The usual suspects are the single primary database (writes can't scale out), hot partitions where one key gets most of the traffic, synchronous call chains where latencies add up and availabilities multiply, and serialisation points such as a shared lock, a global counter or a single worker. I use Little's Law to check pools: 2,000 req/s × 50 ms = 100 concurrent DB connections, which already exceeds a default pool of 100 at any latency spike. Fixes go in order: remove work, cache, move work off the request path with a queue, then partition. The trade-off is that every fix adds staleness or complexity, and the bottleneck simply moves to the next component.

🗣 Full answer (senior)

How I would answer this in an interview

"I don't look for bottlenecks by staring at boxes — I put numbers on the arrows. I take the capacity estimate, say 3,000 requests per second at peak with 10% writes, and walk one request through the diagram: the gateway, the API instances, the cache, the database, any downstream calls. For each component I ask what it can sustain and divide. If the API tier can do 1,500 req/s per instance and I have four, that's 50% utilisation and fine. If the single Azure SQL primary can take about 2,000 small writes a second at that tier and I'm asking for 300, that's fine today but it's the one thing I can't scale out by adding instances, so I flag it.

Then I check the four usual suspects. One: the single database — every stateless tier scales horizontally, but the primary doesn't, so it is usually where a design breaks first. Two: hot partitions — I've partitioned, but the key is skewed, so one tenant, one product on sale, or today's date takes 40% of the traffic and one partition melts while the others idle. Three: synchronous chains — if a checkout calls inventory, pricing and payment in series, latency adds up and availability multiplies down, and one slow dependency ties up threads everywhere. Four: serialisation points — a shared lock, a single-row counter, a singleton job, anything that forces requests through one at a time. Little's Law ties it together: concurrency equals throughput times latency, so when latency doubles, the connection pool you sized for normal days is suddenly exhausted.

The mistake I see is fixing the bottleneck that's easiest to talk about — adding API instances — when the database is the real limit, which just sends more load to it faster. My order is: remove work, cache, move work off the request path with a queue, and only then partition. And I always say what breaks next, because a bottleneck you fix just moves."


The usual suspects

Bottleneck How you spot it in the design Typical fix What it costs
Single primary database All writes and most reads hit one box; DTU/vCore or log-write rate near its limit Cache reads, read replicas, CQRS read model, then partition writes Staleness, replica lag, cross-partition queries
Hot partition / hot key Key with skew: tenant, celebrity, date, a flash-sale SKU Better key, key salting, split hot tenants, a write-behind counter Scatter-gather reads, more complex key logic
Synchronous call chain Arrows that go A→B→C→D on the request path Parallelise, cache, make it async with events, collapse the chain Eventual consistency, harder debugging
Shared lock / serialisation point Global counters, single-row balances, sp_getapplock, one leader Shard the counter, optimistic concurrency, partition the queue More code, approximate values
Pool / port exhaustion High concurrency × latency against a fixed pool (DB connections, SNAT ports, ThreadPool) Reduce latency, size pools by Little's Law, connection reuse Hidden until a latency spike
Fan-out One request → N downstream calls (feeds, notifications) Precompute (fan-out on write) or batch Storage and write amplification

Working it with numbers

Component Peak load Capacity Utilisation
API (4 × Container Apps replicas) 3,000 req/s 4 × 1,500 = 6,000 req/s 50%
Redis (C2) 2,400 reads/s (80% hit) ~50,000 ops/s 5%
Azure SQL primary 600 reads/s (cache misses) + 300 writes/s ~2,000 mixed/s at this tier (measured) 45%, and it can't scale out
Payment provider 30 req/s 100 req/s contractual rate limit 30%, but an external limit

The interviewer wants the last column, and the comment that the database is the real ceiling even though it's under 50%.

When to fix and when to leave it

Situation Do Don't
Utilisation < 50% at 2× peak Note it and move on Partition 'just in case'
Read-heavy, DB is the limit Cache + read replicas Shard first
Write-heavy, single key Fix the key or the model Add API instances
Slow downstream on hot path Timeout + async + fallback Raise the timeout

Production example

In a [retail] API, adding instances during a sale increased p99 latency from 300 ms to 4 s because each instance opened up to 100 connections against an Azure SQL tier capped at [400] concurrent workers. Caching the product catalogue cut database reads by 85%, and moving order confirmation emails onto Service Bus removed two synchronous calls; peak throughput doubled with the same database tier.

🔍 What the interviewer is checking

Checks whether the candidate can reason quantitatively about where a design fails under load, instead of listing generic scaling techniques.

Green flags

  • Puts numbers on components and computes utilisation
  • Names the single database and hot keys without prompting
  • Uses Little's Law or the queueing curve to explain pool exhaustion
  • Orders fixes from cheapest to most complex and says what breaks next

Red flags

  • "Just add more servers" or "use microservices"
  • Partitions without discussing key skew
  • No measurement or load test to confirm the bottleneck

📚 Learn in depth

1. Utilisation and why queues explode

A component with arrival rate λ and service rate μ has utilisation ρ = λ/μ. In a simple queue (M/M/1) the average time in the system is 1/(μ − λ), which means latency grows slowly up to about 70% utilisation and then explodes:

utilisation:   50%   70%   80%   90%   95%
latency (x):   2x    3.3x  5x    10x   20x   (relative to service time)

That is why a design that runs "fine" at 80% falls over with a 10% traffic bump. Plan for peak at ≤ 60–70% on anything you can't scale quickly.

2. Little's Law

L = λ × W: concurrency equals throughput times latency. It sizes everything with a fixed number of slots:

2,000 req/s × 0.050 s = 100 concurrent DB calls
2,000 req/s × 0.500 s = 1,000 concurrent DB calls   <- latency spike

In .NET, SqlConnection pooling defaults to Max Pool Size=100 per connection string per process. A latency spike turns into InvalidOperationException: Timeout expired... max pool size was reached, which looks like an app bug but is Little's Law.

3. The single database

   [API x N]  --->  [Azure SQL primary]   <- every write lands here
        \                 |
         \----> [read replica] (lag ms..s)

Stateless tiers scale horizontally; the primary scales only vertically (bigger SKU, Hyperscale for storage and read scale-out). Write throughput is bounded by log write rate and lock contention. The escalation ladder: index and query tuning → cache → read replicas (ApplicationIntent=ReadOnly) → CQRS read models → partition by tenant or key.

4. Hot partitions

Partitioning only helps if load spreads evenly. Skew comes from:

  • Time keys (2026-11-22) — all of today's writes on one partition
  • Popular entities — a celebrity account, a flash-sale SKU
  • Big tenants — one customer with 30% of traffic

In Cosmos DB a single logical partition is capped at 10,000 RU/s and 20 GB (as of November 2026), so a hot key throttles with 429s no matter how much total RU you provision.

5. Synchronous chains

client -> API -> pricing -> inventory -> payment
         50ms    +80ms      +60ms        +400ms   = ~590ms p50

Latency adds; tail latency adds worse (the p99 of the chain is close to the sum of p99s). Availability multiplies: 99.9% × 99.9% × 99.9% = 99.7%. And a slow callee holds the caller's threads and connections, so failure cascades upstream unless you have timeouts and bulkheads.

6. Serialisation points

Anything that forces one-at-a-time: an UPDATE Counters SET Value = Value + 1 WHERE Id = 1, a balance row updated on every transaction, a singleton scheduler, a distributed lock. Throughput is capped at 1 / (lock hold time). A 5 ms hold allows at most 200 operations per second, regardless of hardware.

7. Try it yourself

  1. Take a design you know and fill in a utilisation table: peak load, measured capacity, ratio for each component.
  2. Run a k6 or Azure Load Testing ramp against a test API and plot p99 latency against requests per second; find the knee of the curve.
  3. Use dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource to watch active pooled connections while you raise load.
  4. Create a single-row counter table, hit it with 200 concurrent updates, and measure throughput; then shard it into 16 rows and compare.
  5. Compute the availability and p99 of a four-hop synchronous chain using each hop's numbers, then redesign it with one async hop.

💻 Code

A sharded counter removes a classic serialisation point: instead of every request updating one row, writes spread across N rows and reads sum them.

namespace Shop.Counters;

using Microsoft.EntityFrameworkCore;

public sealed class CounterShard
{
    public required string Name { get; init; }
    public int Shard { get; init; }
    public long Value { get; set; }
}

public sealed class CounterDbContext(DbContextOptions<CounterDbContext> options) : DbContext(options)
{
    public DbSet<CounterShard> Counters => Set<CounterShard>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<CounterShard>().HasKey(c => new { c.Name, c.Shard });
}

public sealed class ShardedCounter(CounterDbContext db)
{
    public const int Shards = 16; // 16 rows -> roughly 16x less contention on the hot row

    // Run once when a counter is created, so every shard row exists before writes start.
    public async Task CreateAsync(string name, CancellationToken ct)
    {
        db.Counters.AddRange(Enumerable.Range(0, Shards)
            .Select(i => new CounterShard { Name = name, Shard = i }));
        await db.SaveChangesAsync(ct);
    }

    public async Task IncrementAsync(string name, CancellationToken ct)
    {
        // Pick the shard outside the query so it becomes a plain SQL parameter.
        var shard = Random.Shared.Next(Shards);

        // A single UPDATE ... SET Value = Value + 1 is atomic: SQL Server takes a row lock,
        // so two writers on the same shard are serialised, never lost. No read-modify-write race.
        var rows = await db.Counters
            .Where(c => c.Name == name && c.Shard == shard)
            .ExecuteUpdateAsync(s => s.SetProperty(c => c.Value, c => c.Value + 1), ct);

        if (rows == 0)
            throw new InvalidOperationException($"Counter '{name}' has not been created.");
    }

    public Task<long> ReadAsync(string name, CancellationToken ct) =>
        // Reads pay a small cost (sum of 16 rows) to make writes scale.
        db.Counters.Where(c => c.Name == name).SumAsync(c => c.Value, ct);
}

Sizing a connection pool with Little's Law instead of guessing:

namespace Shop.Capacity;

public static class LittlesLaw
{
    // concurrency = throughput (per second) x latency (seconds)
    public static int RequiredSlots(double requestsPerSecond, TimeSpan latency, double headroom = 2.0) =>
        (int)Math.Ceiling(requestsPerSecond * latency.TotalSeconds * headroom);
}

// Per instance: 500 req/s x 40 ms x 2 headroom = 40 connections, well under Max Pool Size=100.
// Across 10 instances that is 400 concurrent sessions: check it against the Azure SQL tier's worker limit.

⚠ Common mistakes

  • Mistake: Scaling the API tier to fix slowness. Why it is wrong: If the database is the limit, more instances just send more concurrent queries to it and make latency worse. Instead: Find the component with the highest utilisation and fix that one.
  • Mistake: Quoting a database's capacity from memory. Why it is wrong: Throughput depends on the tier (General Purpose, Business Critical, Hyperscale), the vCores, the query mix and the indexes. Instead: Use a measured number from a load test of your workload, and say which tier it came from.
  • Mistake: Choosing a partition key without checking its distribution. Why it is wrong: A skewed key (date, big tenant) creates a hot partition and wastes the rest. Instead: Look at the real key distribution and pick a high-cardinality key with even access, or split known hot keys.
  • Mistake: Planning to run at 90% utilisation at peak. Why it is wrong: Queueing latency grows sharply past ~70%, so a small spike causes a big slowdown. Instead: Target 60–70% at peak for anything that can't autoscale quickly.
  • Mistake: Ignoring fixed-size pools. Why it is wrong: DB connection pools, SNAT ports and worker limits cap concurrency; a latency spike exhausts them. Instead: Size them with Little's Law and alert on pool usage.
  • Mistake: Long synchronous call chains on the hot path. Why it is wrong: Latency adds, availability multiplies down, and one slow service cascades. Instead: Parallelise, cache, or move non-essential steps to async messages.
  • Mistake: Adding a cache without an invalidation plan. Why it is wrong: It moves the bottleneck to correctness: stale prices, stampedes when hot keys expire. Instead: Choose TTLs per data type, use explicit or tag-based invalidation, and protect hot keys from stampedes (HybridCache does this for you).
  • Mistake: Treating a global counter or single balance row as free. Why it is wrong: It serialises every write; throughput is capped at 1 / lock hold time. Instead: Shard the counter, use optimistic concurrency, or compute it asynchronously.
  • Mistake: Finding bottlenecks only from the diagram. Why it is wrong: Real systems surprise you; the estimate is a hypothesis. Instead: Confirm with a load test and production telemetry (Application Insights application map and dependency timings, Azure SQL Query Store waits, Azure Monitor metrics), and alert on the saturation of each limit.
  • Mistake: Declaring the bottleneck fixed. Why it is wrong: Removing one limit exposes the next. Instead: After each fix, name what breaks next and at what load.

🏛 Senior insight: trade-offs

Bottleneck analysis is the cheapest senior signal in a design interview: it shows you think in numbers, not boxes. The two habits that separate seniors are using utilisation (not raw throughput) and saying what breaks next. Pair every claim with how you'd verify it: a load test with a step profile, Application Insights dependency timings, Query Store top waits.

Fix When it fits Cost When not to
Cache Read-heavy, tolerant of seconds of staleness Invalidation, stampedes Strongly consistent reads (balances)
Read replicas Reads dominate, some lag OK Replica lag, routing logic Write-bound systems
Queue / async Work not needed for the response Eventual consistency, ops User must see the result now
Partition / shard Writes exceed one node Cross-partition queries, resharding Before cheaper fixes are exhausted
Bigger SKU Short-term relief Money, a ceiling As the only plan for 10× growth

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says they would add read replicas, caching or partitioning Why: Checks the order in which they apply scaling techniques and why
    How to 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.

  2. When: Candidate mentions shared locks or serialisation points Why: Checks they can confirm lock contention in a real .NET service with tools
    How to answer

    Throughput that plateaus with spare CPU points at threads waiting, not working. I confirm with dotnet-counters: monitor-lock-contention-count (the dotnet.monitor.lock_contentions metric) climbing with load. Then I find which lock with dotnet-trace using the contention events (--clrevents contention), which record the waiting stack and duration, or a dotnet-dump where clrstack -all shows dozens of threads in Monitor.Enter on the same object.

    Fixes, in order: shrink the critical section and never hold a lock across I/O; replace it with ConcurrentDictionary, Interlocked or an immutable snapshot swapped atomically; or shard the lock per key. Then I verify with the same load test. The trade-off: lock-free designs are harder to get right, so I take the simplest one that removes the contention.

  3. When: Candidate refers to the capacity estimate Why: Checks they can produce the numbers the bottleneck analysis depends on
    How to answer

    A capacity estimate turns user numbers into load. Start with daily active users × actions per user to get requests per day, divide by ~86,400 s (round to 10^5) for average requests/s, then multiply by a peak factor (2–10×, often 3×). For storage, multiply writes per day by record size and 365, then add indexes and replicas. For bandwidth, multiply requests/s by payload size.

    Example: 10M DAU × 20 reads = 200M reads/day ≈ 2,300/s average, ~7,000/s peak.

    The point is not precision — it's deciding whether one database and a cache are enough or you need partitioning. The trade-off is speed versus accuracy: round hard, but state every assumption.

🛠 Real-world problems: how you handle them

Adding API instances during a sale made checkout slower
Situation
[Retail] e-commerce API on [Azure Container Apps] with one [Azure SQL General Purpose 8 vCore] database, [~2,500 req/s] at peak during a [Click Frenzy] sale.
Signals
p99 latency rose from 300 ms to 4 s as replicas scaled from 6 to 20; `max pool size was reached` exceptions; Azure SQL showed worker usage at 100% while API CPU was 35%.
Investigation
Application Insights application map showed 70% of request time in SQL dependencies; Query Store showed the product catalogue query as top by executions; a back-of-the-envelope with Little's Law showed 20 replicas × up to 100 pooled connections far exceeded the tier's worker limit.
Resolution
Immediately capped replicas at 8 and raised the SQL tier for the sale. Then cached the catalogue in Redis with a 60 s TTL (85% fewer reads) and moved confirmation emails and loyalty points onto Service Bus to remove two synchronous calls.
Prevention
A utilisation table in the design doc, a quarterly load test at 2× last peak in Azure Load Testing, alerts on SQL worker % and pool usage, and an ADR stating the database is the scaling limit.

How to tell it (STAR)

**S:** During a [Click Frenzy] sale our checkout API got slower the more we scaled it. **T:** I had to find the real bottleneck while the sale was live. **A:** I used the application map and Query Store to show the time was in SQL, and Little's Law to show our extra replicas were exhausting the database's workers. I capped replicas, scaled the database for the day, then cached the catalogue and moved emails to a queue. **R:** Database reads fell [85%], p99 returned to [~300 ms], and the next sale handled [2×] the traffic on the same tier.

↩ Usually asked after

More in Senior Design Focus

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me