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.
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.
"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-countclimbs steeply with load while the ThreadPool queue may stay modest.For example, at [company] we had [a pricing service] where a static
Dictionarycache was guarded by a singlelock, and on a miss the code called the database while holding it. I captured a 30-seconddotnet-tracewith the contention keyword during a load test, opened it in PerfView, and the contention stacks all pointed atPriceCache.Get, with average waits of [40 ms]. Adotnet-dumpconfirmed it: [70] threads waiting on the same sync block. We moved the database call outside the lock, then replaced the dictionary and lock withConcurrentDictionaryplus a per-keyLazy<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
lockfor a fancier primitive, likeReaderWriterLockSlimor the newSystem.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."
| 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 | 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 |
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.
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
Red flags
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.
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.
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 collect, then dotnet-dump analyze with syncblk (owner and waiter count for Monitor locks) and clrstack -all / parallelstacks to see where threads are parked.await or do I/O inside a lock (the compiler blocks await in lock, but .Result sneaks through).ConcurrentDictionary.GetOrAdd, Interlocked.Increment, or build a new immutable dictionary and swap the reference atomically.Lazy<Task<T>> so one caller loads and the rest await the same task (or use HybridCache, which does this for you)..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.
dotnet-trace --clrevents contention and find the stack in PerfView.syncblk to see the waiter count.lock on object vs System.Threading.Lock uncontended with BenchmarkDotNet.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.
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..Result. Why it is wrong: The lock's throughput becomes 1 / I/O latency. Instead: Do I/O outside, lock only to publish results.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.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>>.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.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 |
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.
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.
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>.
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.
Last updated 23 Nov 2026.