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

📚 Interview question

Your ASP.NET Core API's throughput stops increasing under load while CPU is only at 40%, and latency climbs. You suspect lock contention. How do you confirm it with dotnet-counters and dotnet-trace, find the contended lock, and fix it?

Diagnosing lock contention in a .NET service with dotnet-counters (monitor-lock-contention-count), dotnet-trace contention events and dumps, then removing it with smaller critical sections, lock-free structures, sharding or immutable snapshots.

Senior Debugging Advanced concurrency debugging dotnet-counters dotnet-trace lock-contention performance

🎯 Key points

  • Symptom: throughput plateaus with spare CPU; latency rises with concurrency
  • dotnet-counters: monitor-lock-contention-count (EventCounter since .NET Core 3.0; also the dotnet.monitor.lock_contentions Meter on .NET 9+)
  • Read it relative to load: contentions per request rising while threadpool-queue-length stays modest points at locks, not starvation
  • dotnet-trace with the Contention keyword (--clrevents contention) gives stacks and wait durations
  • dotnet-dump + syncblk / clrstack -all shows many threads waiting on the same Monitor
  • Fix: shrink the critical section, never hold a lock across I/O or await
  • Replace with ConcurrentDictionary, Interlocked, immutable snapshot swap, or per-key/sharded locks; System.Threading.Lock (.NET 9+) is faster but doesn't fix the design
  • Verify: contention count down, RPS up at the same CPU, p95 down under the same load test

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The fingerprint is a service that stops scaling: I add load, requests per second flatten, latency climbs, and CPU sits at 40%. That means threads are waiting. The usual suspects are blocking I/O, ThreadPool starvation and lock contention, and dotnet-counters separates them: with contention, monitor-lock-contention-count climbs steeply with load while the ThreadPool queue may stay modest.

For example, at [company] we had [a pricing service] where a static Dictionary cache was guarded by a single lock, and on a miss the code called the database while holding it. I captured a 30-second dotnet-trace with the contention keyword during a load test, opened it in PerfView, and the contention stacks all pointed at PriceCache.Get, with average waits of [40 ms]. A dotnet-dump confirmed it: [70] threads waiting on the same sync block. We moved the database call outside the lock, then replaced the dictionary and lock with ConcurrentDictionary plus a per-key Lazy<Task<T>> so only one caller loaded a given key. Throughput went from [900] to [3,400] requests a second on the same pods.

The mistake I see is swapping lock for a fancier primitive, like ReaderWriterLockSlim or the new System.Threading.Lock, without changing what's inside it. A faster lock around a database call is still a queue. The fix is almost always holding locks for less time, or not needing them at all."


Telling waiting problems apart

Symptom Lock contention ThreadPool starvation Slow dependency
CPU Moderate, flat Low Low
monitor-lock-contention-count Rising steeply Low Low
threadpool-queue-length May grow a little Grows steadily Low
Dependency durations Normal Normal or inflated High
Dump stacks Many in Monitor.Enter / Lock.Enter Many in .Result / Wait Few threads, awaits pending

Fix options

Fix When it fits Watch out for
Shrink the critical section Lock protects more than shared state (I/O, logging, serialisation) Check the invariant is still protected
ConcurrentDictionary / Interlocked Simple shared maps and counters Compound operations still aren't atomic
Immutable snapshot + Interlocked.Exchange / ImmutableInterlocked Read-mostly config or lookup tables Writers copy the whole structure
Sharded or per-key locks Contention on independent keys Memory per key; lock ordering
SemaphoreSlim (async) Must serialise async work Still serialises; keep it short

Production example

Removing the database call from inside the lock and switching to ConcurrentDictionary with per-key lazy loading took contention from [12,000] events a second to under [50], throughput from [900] to [3,400] RPS and p95 from [850 ms] to [120 ms] at the same CPU allocation.

🔍 What the interviewer is checking

Checks whether the candidate can distinguish contention from other waiting problems, locate the exact lock with real tools, and fix the design rather than the primitive.

Green flags

  • Names the contention counter and the dotnet-trace contention events
  • Uses a dump with syncblk or clrstack to find waiters
  • Explains hold time as the throughput ceiling
  • Removes I/O from inside the lock and verifies with the same load test

Red flags

  • 'Add more instances' or 'raise min threads' as the fix
  • Swaps lock types without changing the critical section
  • No verification

📚 Learn in depth

1. What contention is

A lock (Monitor or, from .NET 9, System.Threading.Lock) lets one thread in at a time. Uncontended acquisition is a few nanoseconds (an interlocked compare-exchange on the object header or lock word). When another thread holds it, the waiter spins briefly, then blocks on a kernel event. Each block and wake is a context switch costing microseconds, and the thread is unavailable to the ThreadPool while it waits.

requests --> [T1 holds lock: 40 ms DB call] --> others queue:
             T2 waiting...
             T3 waiting...
             T4..T70 waiting...   throughput = 1 / hold time = 25 req/s through this lock

Little's law makes it concrete: if each request holds the lock for 40 ms, that lock can never pass more than 25 requests a second, whatever the hardware.

2. Confirming with counters

dotnet-counters monitor -n MyApi --counters System.Runtime shows Monitor Lock Contention Count per interval. On .NET 9+ the System.Runtime Meter publishes dotnet.monitor.lock_contentions, so it also appears in OpenTelemetry/Azure Monitor dashboards. A count that grows with load while CPU stays flat is the signal.

3. Finding the lock

  • dotnet-trace: dotnet-trace collect -n MyApi --clrevents contention --duration 00:00:30 enables the runtime's Contention keyword. ContentionStart/Stop events include the waiting thread's stack and duration (and, on .NET 8+, the lock owner thread id). Open the .nettrace in PerfView or Visual Studio and group by stack.
  • dotnet-dump: dotnet-dump collect, then dotnet-dump analyze with syncblk (owner and waiter count for Monitor locks) and clrstack -all / parallelstacks to see where threads are parked.
  • Visual Studio: the Concurrency/thread-time views of the Performance Profiler show blocked time per stack.

4. Fixing it

  1. Hold for less time: compute outside, lock only to publish. Never await or do I/O inside a lock (the compiler blocks await in lock, but .Result sneaks through).
  2. Avoid the lock: ConcurrentDictionary.GetOrAdd, Interlocked.Increment, or build a new immutable dictionary and swap the reference atomically.
  3. Split the lock: stripe by key hash so independent keys don't block each other.
  4. Coalesce work: per-key Lazy<Task<T>> so one caller loads and the rest await the same task (or use HybridCache, which does this for you).

5. System.Threading.Lock

.NET 9 added a dedicated Lock type; lock (myLock) on it uses Lock.EnterScope() instead of Monitor. It's somewhat faster and clearer, but it doesn't change the maths of hold time.

Try it yourself

  1. Write an endpoint that locks a static object and sleeps 20 ms inside; load it with k6 at 100 VUs and watch the contention counter.
  2. Capture dotnet-trace --clrevents contention and find the stack in PerfView.
  3. Take a dump and run syncblk to see the waiter count.
  4. Move the sleep outside the lock and repeat; compare RPS.
  5. Benchmark lock on object vs System.Threading.Lock uncontended with BenchmarkDotNet.

💻 Code

Before: a cache that holds a lock across a database call. After: lock-free reads with per-key coalescing, fully async.

using System.Collections.Concurrent;

namespace Perf.Contention;

public sealed record Price(string Sku, decimal Amount);

public interface IPriceRepository
{
    Task<Price> LoadAsync(string sku, CancellationToken ct);
}

// BEFORE: every request serialises on one lock, and a miss holds it during I/O.
public sealed class LockedPriceCache(IPriceRepository repo)
{
    private readonly Dictionary<string, Price> _cache = new();
    private readonly Lock _gate = new(); // .NET 9+ Lock type: faster, but the design is still wrong

    public Price Get(string sku)
    {
        lock (_gate)
        {
            if (!_cache.TryGetValue(sku, out var price))
            {
                price = repo.LoadAsync(sku, CancellationToken.None).GetAwaiter().GetResult(); // I/O under lock + sync-over-async
                _cache[sku] = price;
            }
            return price;
        }
    }
}

// AFTER: no global lock. Hits are lock-free reads; concurrent misses for the same key share one load.
public sealed class ConcurrentPriceCache(IPriceRepository repo)
{
    private readonly ConcurrentDictionary<string, Lazy<Task<Price>>> _cache = new();

    public async Task<Price> GetAsync(string sku, CancellationToken ct)
    {
        // GetOrAdd's factory can run more than once under a race; Lazy guarantees one load per key.
        var lazy = _cache.GetOrAdd(sku, key =>
            new Lazy<Task<Price>>(() => repo.LoadAsync(key, CancellationToken.None),
                                  LazyThreadSafetyMode.ExecutionAndPublication));
        try
        {
            // WaitAsync is asynchronous (it does not block a thread): this caller can stop
            // waiting on cancellation without cancelling the shared load other callers await.
            return await lazy.Value.WaitAsync(ct);
        }
        catch (Exception) when (lazy.Value.IsFaulted)
        {
            // Don't cache failures: remove only this exact entry so the next caller retries.
            _cache.TryRemove(new KeyValuePair<string, Lazy<Task<Price>>>(sku, lazy));
            throw;
        }
    }
}
# Confirm, then locate
dotnet-counters monitor -n PricingApi --counters System.Runtime[monitor-lock-contention-count,cpu-usage,threadpool-queue-length]
dotnet-trace collect -n PricingApi --clrevents contention --duration 00:00:30
dotnet-dump collect -n PricingApi && dotnet-dump analyze <dump> -c "syncblk" -c "clrstack -all"

Reading the output: a contention count that scales with RPS (say from 50/s at 100 RPS to 12,000/s at 900 RPS) while threadpool-queue-length stays near zero means threads are queuing on a lock, not waiting for a pool thread. In the trace, sort contention stacks by total wait time, not count: one lock with long waits matters more than many short ones.

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: Low CPU plus high latency can be starvation or a slow dependency; you may 'fix' the wrong thing. Instead: Confirm with the contention counter and a contention trace.
  • Mistake: Micro-optimising cold paths, such as replacing every lock with lock-free code. Why it is wrong: Uncontended locks cost nanoseconds; lock-free code is error-prone. Instead: Fix only the locks that show up contended.
  • Mistake: Holding a lock across I/O or .Result. Why it is wrong: The lock's throughput becomes 1 / I/O latency. Instead: Do I/O outside, lock only to publish results.
  • Mistake: Swapping lock for ReaderWriterLockSlim or Lock and calling it fixed. Why it is wrong: Hold time, not lock type, sets the ceiling. Instead: Shrink or remove the critical section.
  • Mistake: Assuming ConcurrentDictionary.GetOrAdd runs the factory once. Why it is wrong: The factory can run concurrently for the same key. Instead: Store Lazy<T> or Lazy<Task<T>>.
  • Mistake: Caching a faulted task forever. Why it is wrong: One transient failure poisons the key. Instead: Remove faulted entries.
  • Mistake: Locking on this, a Type or a string. Why it is wrong: Other code can lock on the same object and cause contention or deadlock. Instead: Lock on a private dedicated object.

🏛 Senior insight: trade-offs

Contention is a design smell: a global lock means the system has a single serialisation point. Seniors look for why shared mutable state exists at all, often a hand-rolled cache, a static counter or a singleton holding per-request data, and remove the sharing. Framework features usually beat custom code: HybridCache already coalesces concurrent misses; ConcurrentDictionary and ImmutableInterlocked cover most shared-map cases. Architecturally, designs that avoid shared mutable state (immutable snapshots, single-writer actors or a Channel-fed worker that owns the state, partitioned processing by key) remove contention rather than manage it.

Across instances the problem changes shape: an in-process lock only protects one pod. Don't reach for a distributed lock (Redis, blob leases) to fix throughput; it adds network latency to every critical section. Prefer idempotent operations, optimistic concurrency in the database, or partitioning so one consumer owns a key.

Option When it fits Cost When not to
Shorter critical section Always the first step Re-check invariants n/a
Concurrent collections Shared maps, queues, counters Compound ops need care Multi-object invariants
Immutable snapshot swap Read-mostly data refreshed occasionally Copy on write Frequent writes to large data
Striped locks Independent keys Complexity, lock ordering Few keys
Single owner (Channel worker, partitioning) State updated from many sources Queueing latency Synchronous request/response needs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions System.Threading.Lock or Monitor Why: Checks they understand how lock works and what changed in .NET 9
    How to answer

    lock (x) { ... } gives mutual exclusion: only one thread at a time runs the block for the same lock object, and entering and leaving act as memory barriers. For a normal object the compiler emits Monitor.Enter(x, ref lockTaken) in a try/finally with Monitor.Exit. Since .NET 9 and C# 13, if x is a System.Threading.Lock, the compiler instead uses x.EnterScope() and disposes the scope, which is a dedicated, slightly faster lock type. Locks are re-entrant on the same thread, you cannot await inside one (CS1996), and you should lock on a private, readonly object and keep the block short.

  2. When: Candidate mentions lock-free updates Why: Checks they can build a correct CompareExchange loop
    How to answer

    Interlocked provides atomic operations on shared variables: Increment, Decrement, Add, Exchange, CompareExchange, Read (for 64-bit values on 32-bit platforms), and And/Or (.NET 5+). Each is a single indivisible hardware operation and a full memory fence. CompareExchange(ref x, newValue, expected) writes only if x still equals expected and returns the original value, which is the building block for lock-free algorithms: read, compute, try to swap, and retry if another thread changed it. Use it for counters, flags and reference swaps; use a lock when several values must change together.

  3. When: Candidate mentions ConcurrentDictionary Why: Checks they know the GetOrAdd factory caveat and compound operations
    How to answer

    System.Collections.Concurrent types are safe for many threads at once. ConcurrentDictionary uses lock-free reads and fine-grained (striped) locks for writes. Each single method is atomic, but check-then-act across two calls is not, so use GetOrAdd, AddOrUpdate, TryUpdate or TryRemove. Caveat: the value factory in GetOrAdd/AddOrUpdate can run more than once under contention (only one result is stored), so wrap expensive or side-effecting work in Lazy<T>. Count, IsEmpty and ToArray take every lock, so avoid them in hot paths. ConcurrentQueue/ConcurrentStack are lock-free FIFO/LIFO. ConcurrentBag is unordered, optimised for the same thread adding and taking. BlockingCollection adds bounding and blocking Take but blocks threads; for async producer/consumer use Channel<T>.

🛠 Real-world problems: how you handle them

Global lock around a cache miss caps throughput at 900 RPS
Situation
A pricing API on [6] App Service instances served product prices from an in-process cache guarded by a single lock. Traffic for a [sale event] was forecast at [3x] normal.
Signals
The pre-sale load test plateaued at [900] RPS with CPU at [40%]; p95 rose from [90 ms] to [850 ms]; dotnet-counters showed monitor-lock-contention-count at [12,000] per second; ThreadPool queue grew slightly.
Investigation
Captured dotnet-trace with --clrevents contention during the k6 run and opened it in PerfView: contention stacks pointed at PriceCache.Get with average waits of [40 ms]. A dotnet-dump showed syncblk with [70] waiters on one object; clrstack showed the owner thread inside a SQL call via GetAwaiter().GetResult().
Resolution
Immediate: moved the database call outside the lock (double-checked publish). Real fix: replaced the cache with ConcurrentDictionary<string, Lazy<Task<Price>>> for per-key coalescing and async loading, later migrated to HybridCache.
Prevention
Added the contention counter to the service dashboard with an alert; added a load-test stage that fails if throughput regresses; review checklist item: no I/O or blocking inside lock; enabled the VSTHRD and CA analysers for sync-over-async.

How to tell it (STAR)

**S:** Before a [sale event] at [company], our pricing API plateaued at [900] requests a second in load testing with CPU only at [40%]. **T:** I had [two weeks] to get it to [3x] headroom. **A:** dotnet-counters showed lock contention climbing with load; a contention trace in PerfView and a dump with syncblk pointed at one lock around the cache, held during a SQL call. I moved the I/O out, then replaced the design with a ConcurrentDictionary of lazy tasks so concurrent misses shared one load, and added a contention alert. **R:** Throughput rose to [3,400] RPS on the same instances, p95 fell to [120 ms], and the sale ran without incident.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me