Reviewing a hot path for blocking I/O under a lock, unsafe shared state, repeated LINQ materialisation, string concatenation and boxing, then rewriting it and proving the improvement with measurement.
Ranked by severity:
.Result): every message queues behind one write, throughput is capped at 1 / write latency, and blocked threads risk ThreadPool starvation.ToList() and multiple enumeration: copies the data several times and repeats filtering.object: boxing on every write, plus casts.The rewrite does I/O asynchronously, outside any lock, batched; makes one pass over the data; builds the key with string.Create or a StringBuilder; and uses generics. I prove it with a benchmark and a load test. The trade-off: batching adds a little latency per message for much higher throughput.
"I rank by impact on production. The worst issue is the lock around the database write, especially with a blocking wait inside it. A lock only blocks threads that try to take it, but here every message takes the same static lock, so all message handling in the process funnels through it, and throughput can't exceed one divided by the write latency: at 8 milliseconds that's about 125 messages a second, whatever the hardware. Each waiting thread is blocked rather than returned to the pool, so under load the ThreadPool starves and unrelated work on the box slows down too.
For example, at [company] I reviewed [a consumer like this] that topped out at [about 120] messages a second. We moved the write out of the lock, made it async, and batched writes through a bounded channel. What the lock really protected was a read-modify-write on an in-memory total, which isn't safe with a plain
TryGetValuethen set; we replaced it withConcurrentDictionary.AddOrUpdate, which makes that update atomic per key without a global lock. Throughput went to [2,800] messages a second on the same pods. The CPU-level issues came next: three chainedWhere/Select/ToListcalls copied the list three times, the key was built with+=in a loop, and aDictionary<string, object>boxed every number. A single loop,string.Joinand a typed dictionary took allocations from [1.9 KB] to [180 B] per message in BenchmarkDotNet.The mistake I see in reviews is leading with the micro-optimisations because they're easy to spot, while the lock around I/O, which caps the whole service, gets a 'nit'. I mark the lock and the blocking call as blocking comments, the rest as suggestions with benchmark numbers, and I turn on analysers so the next PR doesn't need me."
public sealed class MessageProcessor(IDbWriter db)
{
private static readonly object Gate = new();
private static readonly Dictionary<string, object> Totals = new(); // 2 static, unbounded; 5 boxing
public void Process(Message message)
{
var lines = message.Lines.Where(l => l.Quantity > 0).ToList(); // 3
var skus = lines.Select(l => l.Sku).ToList(); // 3
var valid = skus.Where(s => !string.IsNullOrEmpty(s)).ToList(); // 3
var key = "";
foreach (var sku in valid) key += sku + "|"; // 4
lock (Gate) // 1
{
Totals[key] = (Totals.TryGetValue(key, out var t) ? (int)t : 0) + lines.Count; // 5 unbox + box
db.WriteAsync(message.Id, key, lines.Count).Wait(); // 1 I/O + sync-over-async under the lock
}
}
}
| # | Severity | Finding | Impact |
|---|---|---|---|
| 1 | Stall | One process-wide lock held across a DB write with .Wait() |
All messages serialise; throughput capped at 1/write latency; blocked threads cause starvation |
| 2 | Wrong data / memory | Static mutable dictionary, unbounded growth, per-process totals | Memory leak; totals silently differ between pods |
| 3 | CPU/allocations | Three ToList() calls, multiple passes |
3 list copies and closures per message |
| 4 | CPU/allocations | += concatenation in a loop |
O(n²) copying, n intermediate strings |
| 5 | Allocations/design | Dictionary<string, object> |
Boxing per update, casts, no type safety |
See the code example: a single pass to build the key, a typed ConcurrentDictionary<string, int> with AddOrUpdate for the atomic read-modify-write, and the write moved to an async, batched writer fed by a bounded Channel<T>.
Microsoft.VisualStudio.Threading.Analyzers (VSTHRD002 for blocking waits), CA1851 (multiple enumeration) and the CA string analysers; add a load test for the consumer.lock.After the rewrite, the consumer went from [120] to [2,800] messages a second, lock contention dropped to near zero, and alloc-rate fell [85%], letting us cut the pod count from [10] to [3].
Checks whether the candidate can prioritise performance findings by production impact, rewrite the code correctly and back the review with measurements.
Green flags
Red flags
Little's law: throughput through a serial section = 1 / time in the section. Everything else in the method could be infinitely fast and the service would still cap at that rate.
msg1 --[lock: 8 ms DB]--
msg2 ...........waiting--[lock: 8 ms DB]--
msg3 ..........................waiting--[lock: 8 ms DB]--
=> max ~125 msg/s per process; waiting threads are blocked, not free
.Result makes it worseThe thread inside the lock is blocked on I/O, and every waiter is blocked on the lock. None of them return to the ThreadPool, so the pool injects threads slowly and other work (health checks, timers, other consumers) queues behind them.
Each ToList() allocates a new list (and grows it by doubling) and each lambda that captures nothing still costs a delegate invocation per element. Three chained materialisations means three passes and three lists. One foreach that filters and builds the output does it in one pass. Since .NET 9 LINQ is faster for arrays and lists, but materialisation still allocates.
Strings are immutable: key += sku + "|" copies the whole key each iteration, so n items of length k cost O(n²k) character copies plus n garbage strings. string.Join("|", valid) or StringBuilder does it in one buffer; string.Create can do it in exactly one allocation when the length is known.
Storing an int in an object slot allocates a 24-byte box on the heap (64-bit). Every update unboxes, adds and boxes again. Typed generics (Dictionary<string, int>) store the value inline.
A bounded Channel<T> decouples message handling from the database: the handler writes to the channel (waiting asynchronously if it's full, which is backpressure), and a background writer reads batches and does one round trip per batch (SqlBulkCopy, a table-valued parameter or EF Core AddRange + one SaveChangesAsync). Ten writes per round trip instead of one gives roughly ten times the throughput at the cost of a few milliseconds of added latency.
[MemoryDiagnoser] for the in-memory part (key building, filtering).monitor-lock-contention-count, alloc-rate and threadpool-queue-length before and after.string.Join vs string.Create for 5 and 50 SKUs.The rewrite: one pass, typed concurrent totals, no lock, and asynchronous batched writes through a bounded channel.
using System.Collections.Concurrent;
using System.Threading.Channels;
namespace Ingestion;
public sealed record MessageLine(string? Sku, int Quantity);
public sealed record Message(Guid Id, IReadOnlyList<MessageLine> Lines);
public sealed record WriteItem(Guid MessageId, string Key, int LineCount);
public interface IDbWriter
{
Task WriteBatchAsync(IReadOnlyList<WriteItem> batch, CancellationToken ct); // one round trip per batch
}
public sealed class MessageProcessor(ChannelWriter<WriteItem> writes)
{
// Typed values: no boxing. Instance-owned and bounded by the key space of real SKUs.
private readonly ConcurrentDictionary<string, int> _totals = new();
public async ValueTask ProcessAsync(Message message, CancellationToken ct)
{
// One pass: filter and collect SKUs without intermediate lists per stage.
var skus = new List<string>(message.Lines.Count);
var lineCount = 0;
foreach (var line in message.Lines)
{
if (line.Quantity <= 0) continue;
lineCount++;
if (!string.IsNullOrEmpty(line.Sku)) skus.Add(line.Sku);
}
var key = string.Join('|', skus); // single buffer instead of O(n^2) concatenation
_totals.AddOrUpdate(key, lineCount, (_, existing) => existing + lineCount); // atomic, no lock
// Backpressure: waits asynchronously if the writer is behind, never blocks a thread.
await writes.WriteAsync(new WriteItem(message.Id, key, lineCount), ct);
}
}
public sealed class BatchWriter(ChannelReader<WriteItem> reads, IDbWriter db) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var batch = new List<WriteItem>(100);
while (await reads.WaitToReadAsync(stoppingToken))
{
while (batch.Count < 100 && reads.TryRead(out var item)) batch.Add(item);
await db.WriteBatchAsync(batch, stoppingToken); // async I/O outside any lock
batch.Clear();
}
}
}
// Program.cs registration
var channel = Channel.CreateBounded<WriteItem>(new BoundedChannelOptions(5_000)
{
FullMode = BoundedChannelFullMode.Wait, SingleReader = true
});
builder.Services.AddSingleton(channel.Writer);
builder.Services.AddSingleton(channel.Reader);
builder.Services.AddSingleton<MessageProcessor>();
builder.Services.AddHostedService<BatchWriter>();
lock with SemaphoreSlim around the same DB call. Why it is wrong: It's async now but still serialises every write. Instead: Remove I/O from the critical section and batch.Interlocked calls. Why it is wrong: Each call is atomic, but the sequence isn't; invariants spanning several values still race. Instead: Use Interlocked only for single-value updates; use AddOrUpdate, a CompareExchange loop or a short lock for compound logic.Wait for backpressure.ConcurrentDictionary makes compound logic atomic. Why it is wrong: TryGetValue then indexer set is a race. Instead: AddOrUpdate or GetOrAdd.Good performance reviews rank by blast radius: anything that serialises or blocks the process outranks allocation work by orders of magnitude. Seniors also look past the method: why is per-message state kept in process memory at all, and is the database the right place to aggregate? Often the best rewrite is moving aggregation into SQL or a stream processor and keeping the handler stateless.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Move I/O out of the lock | Always | Re-check invariants | n/a |
| Batch writes via a channel | High-volume writes tolerating ms of delay | At-least-once semantics on crash; needs idempotent writes | Each write must be confirmed before acking the message |
| Single-pass loops | Per-message hot paths | Less declarative | Cold paths where LINQ reads better |
string.Join/string.Create |
Building keys at volume | Minor | One-off strings |
Generics over object |
Always for value types | None | n/a |
First I prove the method is hot: dotnet-counters shows a high allocation rate and an allocation profile points at it. Then I write a BenchmarkDotNet benchmark with [MemoryDiagnoser] so every change shows Mean and Allocated bytes.
The usual fixes:
ReadOnlySpan<char> slicing instead of Substring and Split, which allocate a string per piece.string.Create (or stackalloc plus TryFormat) to build the final string once.ArrayPool<T>.Shared for temporary buffers, returned in finally.The trade-off is readability: span-based code is harder to maintain, so I only do it where the profile and the benchmark justify it.
I use StringBuilder when I'm appending an unknown or large number of pieces, usually in a loop, because += creates a new string and copies everything on every iteration. For a fixed number of pieces, a + b + c or interpolation compiles to a single string.Concat or handler call, which is just as fast. Internally StringBuilder keeps a chunked mutable buffer, so it grows without recopying old text, and ToString() allocates the final string once. Alternatives are string.Join for collections, string.Create when I know the exact length, and streaming to a writer for very large output.
Any call that holds a request thread while waiting is a blocking call: sync-over-async (.Result, .Wait()), synchronous I/O (Stream.Read on the request body, File.ReadAllText, EF Core ToList()/SaveChanges(), HttpClient.Send), Thread.Sleep, long lock sections and synchronous logging to slow sinks. Kestrel disallows synchronous request and response body I/O by default (AllowSynchronousIO = false) and throws InvalidOperationException if you try. Replace them with async equivalents (ReadAsync, ToListAsync, SaveChangesAsync, SendAsync, Task.Delay, SemaphoreSlim.WaitAsync), find them with analysers (CA1849), stack snapshots and load tests.
How to tell it (STAR)
**S:** At [company] our order-events consumer topped out at about [120] messages a second per pod, and we needed [2,000] for [the seasonal peak]. **T:** I reviewed the code and owned the fix. **A:** I ranked the findings: a lock around a synchronous database write was capping throughput, so that was blocking; LINQ copies, string concatenation and boxing were suggestions with benchmark numbers attached. I moved writes to an async batch writer behind a bounded channel, made them idempotent, cleaned up the hot path, and added analysers and a replay load test. **R:** Throughput rose to [2,800] messages a second per pod, allocations fell [85%], and we cut the pod count from [10] to [3].
Last updated 23 Nov 2026.