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

📚 Interview question

Code review: a hot-path method that runs for every incoming message chains several LINQ calls with repeated ToList(), builds a key by concatenating strings in a loop, stores values as object, and holds a lock while it writes to a database. What problems do you find, ranked by severity, and how would you rewrite it?

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.

Senior CodeReview Advanced allocations boxing code-review linq lock-contention performance

🎯 Key points

  • Most severe: every message takes the same lock, which is held across synchronous database I/O, so all message handling serialises and waiting threads are blocked
  • Sync-over-async (.Wait()/.Result) inside the lock adds ThreadPool starvation risk
  • Repeated ToList() and multiple enumeration: O(n) copies and repeated work
  • String concatenation in a loop: O(n²) copying and many intermediate strings
  • Storing values as object boxes every int/decimal and loses type safety
  • Rewrite: async I/O outside any lock, batching, atomic AddOrUpdate for the read-modify-write, single pass, string.Join/string.Create, generics
  • Prove it: BenchmarkDotNet for the CPU part, load test for throughput, dotnet-counters for alloc-rate and contention
  • Close the review: blocking comments for lock and I/O, suggestions for the rest, analysers

⏱ 30-second answer

Ranked by severity:

  1. A lock held across database I/O (and .Result): every message queues behind one write, throughput is capped at 1 / write latency, and blocked threads risk ThreadPool starvation.
  2. Shared mutable state the lock was meant to protect, which needs a proper concurrent design rather than a coarse lock.
  3. Repeated ToList() and multiple enumeration: copies the data several times and repeats filtering.
  4. String concatenation in a loop: O(n²) copying and garbage.
  5. Storing values as 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 TryGetValue then set; we replaced it with ConcurrentDictionary.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 chained Where/Select/ToList calls copied the list three times, the key was built with += in a loop, and a Dictionary<string, object> boxed every number. A single loop, string.Join and 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."


Code under review

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
        }
    }
}

Findings by severity

# 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

The rewrite

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>.

How I'd close the review

  • Blocking: finding 1 (lock + I/O + blocking wait) and finding 2 (unbounded static state). Must change before merge.
  • Suggested, with numbers: findings 3–5, with the BenchmarkDotNet table attached.
  • Tooling: enable Microsoft.VisualStudio.Threading.Analyzers (VSTHRD002 for blocking waits), CA1851 (multiple enumeration) and the CA string analysers; add a load test for the consumer.
  • Checklist item: no I/O or blocking inside lock.

Production example

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].

🔍 What the interviewer is checking

Checks whether the candidate can prioritise performance findings by production impact, rewrite the code correctly and back the review with measurements.

Green flags

  • Ranks the lock around I/O and sync-over-async first
  • Explains the throughput ceiling of a serial section
  • Rewrites with async batching and backpressure
  • Attaches benchmark and load-test evidence; proposes analysers

Red flags

  • Spends most of the answer on LINQ style
  • Swaps lock for SemaphoreSlim and stops
  • Proposes an unbounded queue

📚 Learn in depth

1. Why the lock dominates

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

2. Why .Result makes it worse

The 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.

3. LINQ materialisation costs

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.

4. Concatenation in a loop

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.

5. Boxing

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.

6. Batching the writes

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.

7. Proving it

  • BenchmarkDotNet with [MemoryDiagnoser] for the in-memory part (key building, filtering).
  • A load test (or a replay of messages) for end-to-end throughput.
  • dotnet-counters monitor-lock-contention-count, alloc-rate and threadpool-queue-length before and after.

Try it yourself

  1. Benchmark the original key-building code vs string.Join vs string.Create for 5 and 50 SKUs.
  2. Run the original processor with 50 concurrent producers against a fake DB that delays 8 ms; record throughput and contention.
  3. Replace it with the channel-based writer and compare.
  4. Enable CA1851 and VSTHRD002 and see which lines they flag.

💻 Code

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

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: Review comments without numbers turn into opinion debates and may target the wrong line. Instead: Attach a benchmark for CPU changes and a load-test result for throughput changes.
  • Mistake: Micro-optimising cold paths. Why it is wrong: The same LINQ in a once-a-day admin job doesn't deserve a comment. Instead: Treat code as hot only if it runs per message or per request at volume (thousands of calls a second) or shows up in a CPU or allocation profile; everything else stays readable.
  • Mistake: Leading the review with LINQ and string nits. Why it is wrong: The lock around I/O caps the service; nits distract from it. Instead: Rank findings by production impact.
  • Mistake: Replacing 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.
  • Mistake: Replacing a multi-step update with separate 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.
  • Mistake: Unbounded channels or queues. Why it is wrong: If the DB slows, memory grows until the pod is killed. Instead: Bounded channel with Wait for backpressure.
  • Mistake: Static mutable dictionaries keyed by message data. Why it is wrong: Unbounded memory growth and hidden cross-instance inconsistency. Instead: Bound it, scope it, or move aggregation to the database.
  • Mistake: Assuming ConcurrentDictionary makes compound logic atomic. Why it is wrong: TryGetValue then indexer set is a race. Instead: AddOrUpdate or GetOrAdd.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions reducing allocations Why: Checks they can apply spans, pooling and string.Create on a hot path with proof
    How to answer

    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.
    • Plain loops instead of LINQ and capturing lambdas in tight loops (enumerator and closure allocations).

    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.

  2. When: Candidate mentions string concatenation Why: Checks their understanding of StringBuilder and string.Create internals
    How to answer

    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.

  3. When: Candidate mentions .Result or blocking Why: Checks they know which blocking calls hurt ASP.NET Core and their replacements
    How to answer

    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.

🛠 Real-world problems: how you handle them

Message consumer capped at 120 msg/s by a lock around a database write
Situation
An order-events consumer on [AKS, 10 pods] processed Service Bus messages. Peak volume was growing towards [2,000] messages a second ahead of [a seasonal peak].
Signals
Throughput plateaued at roughly [120] msg/s per pod; Service Bus active message count grew at peak; dotnet-counters showed monitor-lock-contention-count high, threadpool-queue-length rising and CPU at [25%]; alloc-rate [300 MB/s].
Investigation
Code review and a dotnet-dump showed most threads waiting on Monitor.Enter while one thread sat in a SQL write via .Result. A BenchmarkDotNet run of the in-memory part showed [1.9 KB] allocated per message from LINQ materialisation, concatenation and boxing. A replay test with a fake 8 ms DB reproduced the ceiling.
Resolution
Immediate: scaled pods while the fix was built. Fix: moved the write to an async batch writer fed by a bounded Channel, replaced the static object dictionary with a typed ConcurrentDictionary and AddOrUpdate, single-pass filtering and string.Join for keys; made the DB write idempotent on message id.
Prevention
Enabled VSTHRD002, CA1851 and string analysers as warnings-as-errors; added a replay load test to the pipeline with a throughput threshold; review checklist item: no I/O inside locks.

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].

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me