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

πŸ“š Interview question

Code review: a CurrencyService exposes a hand-rolled static Instance, caches rates in a plain Dictionary, creates new HttpClient() and new AppDbContext() itself, calls .Result on async code, and picks a rate provider with a switch on a config string. What is wrong, in order of severity, and how would you rewrite it with DI?

Code review of creational anti-patterns: racy static singleton, unsynchronised Dictionary, HttpClient per call, DbContext held by a singleton, sync-over-async, switch factory with silent fallback and hard-coded secret; rewrite with DI lifetimes, typed HttpClient, HybridCache, keyed or options-driven provider selection.

Senior CodeReview Advanced code-review dependency-injection design-patterns factory-method httpclient singleton

🎯 Key points

  • Rank findings: stall/crash (.Result starvation, HttpClient socket exhaustion, shared DbContext, Dictionary corruption) → wrong data (stale cache, silent provider fallback) → security/diagnostics (hard-coded API key, no timeouts or logs) → design (static Instance, switch factory)
  • .Result on async I/O blocks thread-pool threads and causes starvation under load
  • new HttpClient() per call leaves sockets in TIME_WAIT and exhausts ports; use IHttpClientFactory typed clients (handler rotation every 2 minutes) or one client with PooledConnectionLifetime
  • A singleton owning a DbContext shares a non-thread-safe context across requests ('A second operation was started on this context instance') and leaks tracked entities
  • Concurrent writes to Dictionary<TKey,TValue> can corrupt buckets and spin threads at 100% CPU; use HybridCache/IMemoryCache or ConcurrentDictionary
  • The root cause is one thing: infrastructure objects created by hand instead of by the DI container, which owns lifetimes (scoped DbContext, pooled handlers) and makes dependencies visible and testable
  • Switch factory with a default branch silently uses the wrong provider and violates Open/Closed; select once at startup from validated options (ValidateOnStart) or keyed services; secrets go to Key Vault
  • Close the review with blocking vs suggested comments, analysers (CA2000, VSTHRD002/103, CA2016, banned APIs), logging and metrics on provider calls, and a checklist

⏱ 30-second answer

I'd rank the findings by production impact:

  1. Stall or crash. .Result blocks thread-pool threads (starvation). new HttpClient() per call exhausts sockets. A singleton holding a DbContext shares a non-thread-safe context across requests. A plain Dictionary written concurrently can corrupt itself and spin at 100% CPU.
  2. Wrong data. Rates are cached forever, and the switch silently falls back to a default provider.
  3. Security and diagnostics. There's a hard-coded API key, no timeout and no logging.
  4. Design. A racy static Instance hides every dependency, and a switch factory edits the class for each new provider.

In the rewrite the service is registered with DI. It gets a typed HttpClient with a resilience handler, HybridCache with expiry, a provider chosen once at startup from validated options, an audit writer using IDbContextFactory, async all the way with a CancellationToken, and the secret in Key Vault.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I'd go through this by impact, not line by line. First, the things that will stall or crash the service under load. Convert calls .Result on an async method, so every call blocks a thread-pool thread while it waits for HTTP, and at a few hundred requests per second that's thread-pool starvation. Every cache miss creates a new HttpClient, and each one opens a new connection whose socket sits in TIME_WAIT after disposal, so you run out of ports. The singleton owns a DbContext, which isn't thread-safe, so concurrent requests get 'A second operation was started on this context instance', and its change tracker grows forever. The cache is a plain Dictionary written from many threads, which can corrupt its buckets and leave threads spinning at 100% CPU. Second, wrong data: the rates never expire, and the switch has a default branch, so a typo in config silently uses a different provider. Third, there's a hard-coded API key, which is a secret in source control.

Then design. The static Instance is racy (??= isn't atomic) and hides every dependency, and the switch means every new provider edits this class. For example, at [company] we had [a rates service like this] that took [the checkout] down at [month-end]. A dump showed [~200] threads blocked in .Result and [the Dictionary spinning]. I rewrote it the way I'd suggest here, and [p99 went from timeouts to ~40 ms, with zero incidents in the following year].

The rewrite is an ICurrencyConverter registered with DI. It's async with a CancellationToken, and it uses HybridCache with a 15-minute expiry plus stampede protection. Each provider is a typed HttpClient with AddStandardResilienceHandler, chosen once at startup from validated options, with the key in Key Vault. Audits go through IDbContextFactory. Every creational problem here, from singleton and factory to client and context, is something the container already does better."


Code under review

public class CurrencyService
{
    private static CurrencyService? _instance;
    public static CurrencyService Instance => _instance ??= new CurrencyService();       // 1

    private readonly Dictionary<string, decimal> _rates = new();                           // 2
    private readonly AppDbContext _db = new AppDbContext();                                // 3

    public decimal Convert(decimal amount, string from, string to)
    {
        var rate = GetRateAsync(from, to).Result;                                          // 4
        return amount * rate;
    }

    private async Task<decimal> GetRateAsync(string from, string to)
    {
        if (_rates.TryGetValue(from + to, out var cached)) return cached;                  // 5

        using var client = new HttpClient();                                               // 6
        IRateProvider provider = CreateProvider(AppConfig.RateProvider);
        decimal rate = await provider.GetRateAsync(client, from, to);

        _rates[from + to] = rate;                                                          // 2, 5
        _db.RateAudits.Add(new RateAudit(from, to, rate, DateTime.Now));                   // 3, 9
        await _db.SaveChangesAsync();
        return rate;
    }

    private IRateProvider CreateProvider(string name) => name switch                       // 7
    {
        "xe"  => new XeProvider("sk_live_9f2c..."),                                       // 8
        "rba" => new RbaProvider(),
        _     => new XeProvider("sk_live_9f2c...")                                         // 7
    };
}

Severity 1: stalls and crashes

(4) .Result on async I/O. It blocks a thread-pool thread for the whole HTTP and database round trip. The pool injects threads slowly once it believes it's starved, so latency climbs across the whole service, not just this endpoint. It also wraps failures in AggregateException.

(6) new HttpClient() per call. Each client owns a handler and a connection pool; disposing it closes the connection, leaving the socket in TIME_WAIT for up to 240 seconds on Windows. Under load you get SocketException: Only one usage of each socket address… or "Too many open files" on Linux. No timeout is set, so the default 100 seconds applies.

(3) A DbContext owned by a singleton. It's created once and shared by every request. EF Core throws on concurrent use, and the change tracker keeps every RateAudit ever added in memory.

(2) Plain Dictionary with concurrent writes. Dictionary<TKey,TValue> isn't thread-safe for writes. Concurrent inserts during a resize can corrupt the bucket chains, and readers can then loop forever at 100% CPU.

Severity 2: wrong data

(5) Cache never expires. Rates move during the day; the service returns the first rate it ever saw until restart. There's also no stampede protection: 500 concurrent misses make 500 provider calls.

(7) Silent default provider. A typo such as "RBA" falls through to Xe without a warning, giving different rates and different costs. The switch also violates Open/Closed.

Severity 3: security and diagnostics

(8) Hard-coded live API key. It's in source control, build artefacts and every developer's clone. Rotate it now, move it to Key Vault-backed configuration and enable secret scanning in CI.

(9) DateTime.Now and no logging. Local time on the server makes audits ambiguous across regions and daylight saving; no logging or metrics means provider failures are invisible. Use TimeProvider and structured logs.

Severity 4: design

(1) Static Instance with ??=. ??= is not atomic, so two threads can create two instances (and two DbContexts). More importantly, it hides HttpClient, DbContext, configuration and the provider choice, so nothing is testable or configurable.

The rewrite

namespace Currency;

using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Options;

public interface IRateProvider
{
    Task<decimal> GetRateAsync(string from, string to, CancellationToken ct);
}

public sealed class XeRateProvider(HttpClient http) : IRateProvider   // typed client: base address, key header, resilience set in Program.cs
{
    public async Task<decimal> GetRateAsync(string from, string to, CancellationToken ct)
    {
        RateResponse? r = await http.GetFromJsonAsync<RateResponse>($"/v1/convert?from={from}&to={to}", ct);
        return r?.Rate ?? throw new InvalidOperationException($"No rate returned for {from}/{to}.");
    }
}

public interface ICurrencyConverter
{
    ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct);
}

public sealed class CurrencyConverter(
    IRateProvider provider,
    HybridCache cache,
    IRateAuditWriter audit,
    ILogger<CurrencyConverter> logger) : ICurrencyConverter
{
    private static readonly HybridCacheEntryOptions RateTtl = new() { Expiration = TimeSpan.FromMinutes(15) };

    public async ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct)
    {
        string key = $"fx:{from}:{to}";   // separator avoids ambiguous keys
        decimal rate = await cache.GetOrCreateAsync(key, async innerCt =>
        {
            decimal fresh = await provider.GetRateAsync(from, to, innerCt);   // one call per key even under a stampede
            await audit.RecordAsync(from, to, fresh, innerCt);
            logger.LogInformation("Fetched FX rate {From}/{To} = {Rate}", from, to, fresh);
            return fresh;
        }, RateTtl, cancellationToken: ct);

        return amount * rate;
    }
}

public sealed class RateAuditWriter(IDbContextFactory<AppDbContext> contexts, TimeProvider time) : IRateAuditWriter
{
    public async Task RecordAsync(string from, string to, decimal rate, CancellationToken ct)
    {
        await using AppDbContext db = await contexts.CreateDbContextAsync(ct);   // short-lived context per write
        db.RateAudits.Add(new RateAudit(from, to, rate, time.GetUtcNow()));
        await db.SaveChangesAsync(ct);
    }
}

public sealed class RateOptions
{
    public required string Provider { get; init; }   // "xe" | "rba", validated at startup
    public required string XeApiKey { get; init; }   // from Key Vault, never in code
}
// Program.cs
builder.Services.AddOptions<RateOptions>()
    .BindConfiguration("Rates")
    .Validate(o => o.Provider is "xe" or "rba", "Rates:Provider must be 'xe' or 'rba'.")
    .ValidateOnStart();                                            // a typo fails deployment, not checkout

builder.Services.AddHttpClient<XeRateProvider>((sp, c) =>
{
    c.BaseAddress = new Uri("https://api.example-fx.com");
    c.DefaultRequestHeaders.Add("X-Api-Key", sp.GetRequiredService<IOptions<RateOptions>>().Value.XeApiKey);
}).AddStandardResilienceHandler();                                 // timeouts, retry with jitter, circuit breaker
builder.Services.AddHttpClient<RbaRateProvider>().AddStandardResilienceHandler();

builder.Services.AddTransient<IRateProvider>(sp =>                 // chosen once per resolution from validated options
    sp.GetRequiredService<IOptions<RateOptions>>().Value.Provider == "rba"
        ? sp.GetRequiredService<RbaRateProvider>()
        : sp.GetRequiredService<XeRateProvider>());

builder.Services.AddHybridCache();
builder.Services.AddDbContextFactory<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Main")));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IRateAuditWriter, RateAuditWriter>();
builder.Services.AddScoped<ICurrencyConverter, CurrencyConverter>();

How I'd close the review

Blocking: .Result, new HttpClient() per call, the singleton DbContext, the unsynchronised Dictionary and the hard-coded key (plus: rotate the key today). Required: expiry on cached rates, fail-fast provider configuration. Suggested: TimeProvider, structured logs and a metric for provider latency.

Guardrails: analysers VSTHRD002/VSTHRD103 (sync waits), CA2016 (forward CancellationToken), CA2000 (dispose objects), and a banned-API rule (Microsoft.CodeAnalysis.BannedApiAnalyzers) for new HttpClient() and DateTime.Now in application code; secret scanning in the pipeline; ValidateOnBuild in tests; and a review checklist entry: "no static Instance, no new of infrastructure types in services."

Production example

A rates service with exactly these problems took checkout down at month-end in one retailer: a memory dump showed about 200 threads blocked in .Result and two threads spinning in Dictionary.FindValue. After the rewrite, p99 for conversion dropped to about 40 ms with a 98% cache hit rate, and provider calls fell from roughly 2,000 a minute to 30.

πŸ” What the interviewer is checking

Checks whether the candidate can review real code by severity, connect creational anti-patterns to production failures, and rewrite with idiomatic .NET DI.

Green flags

  • Leads with starvation, socket exhaustion, the shared DbContext and the Dictionary race.
  • Explains why each fails, with mechanisms (TIME_WAIT, change tracker, bucket corruption).
  • Treats the hard-coded secret as urgent (rotate, Key Vault).
  • Rewrites with typed clients, HybridCache, options validation and a proportionate design.
  • Proposes analysers and a checklist.

Red flags

  • Only comments on the static singleton or naming.
  • Replaces .Result with GetAwaiter().GetResult().
  • Makes HttpClient static forever, or adds layers of patterns to the rewrite.

πŸ“š Learn in depth

1. Findings mapped to failure modes

# Problem Failure in production How you'd detect it Fix
1 Racy static Instance Two instances, two contexts; hidden dependencies Code review; constructor counter DI registration
2 Dictionary concurrent writes 100% CPU, infinite loops, lost entries dotnet-dump stacks in FindValue/TryInsert HybridCache/ConcurrentDictionary
3 Singleton-owned DbContext Concurrency exceptions, memory growth EF exceptions, dumpheap -stat IDbContextFactory, scoped context
4 .Result Thread-pool starvation, timeouts dotnet-counters thread-pool queue length rising async/await end to end
5 No expiry, no stampede control Stale rates; provider overload on cold cache Business reports; provider 429s TTL + HybridCache single-flight
6 HttpClient per call Socket exhaustion netstat showing thousands of TIME_WAIT Typed client via IHttpClientFactory
7 switch with default Wrong provider silently Cost anomaly, rate differences Validated options, fail fast
8 Hard-coded secret Credential exposure Secret scanning Key Vault configuration, rotation
9 DateTime.Now, no logs Ambiguous audits, invisible failures Support tickets TimeProvider, structured logging

2. Why new HttpClient() exhausts sockets

HttpClient is a thin wrapper over an HttpMessageHandler (SocketsHttpHandler) that owns a connection pool. A new client means a new pool and a new TCP (and TLS) connection, costing a handshake each time. Disposing closes the connection; the side that closes first keeps the socket in TIME_WAIT (up to 4 minutes on Windows, 60 seconds by default on Linux). At a few hundred calls per second you run out of ephemeral ports. The opposite mistake, one static client forever, ignores DNS changes. IHttpClientFactory rotates handlers (default HandlerLifetime of 2 minutes), and a single client with SocketsHttpHandler.PooledConnectionLifetime achieves the same.

3. Why a corrupted Dictionary spins

Entries are chained through an int[] buckets array and an Entry[] array with next indexes. Two threads inserting during a resize can create a cycle in a chain. A later lookup walks the chain forever. .NET added a concurrent-operation check that throws InvalidOperationException for some cases, but not all races are detected, so the safe rule is: never write to a Dictionary from multiple threads without synchronisation.

4. HybridCache (.NET 9+)

HybridCache (Microsoft.Extensions.Caching.Hybrid) combines an in-process L1 cache with an optional distributed L2 (Redis, SQL Server) and adds stampede protection: concurrent GetOrCreateAsync calls for the same key share a single factory call. Registered with AddHybridCache(). It replaces the hand-written "check dictionary, fetch, store" pattern and its race conditions.

5. Choosing the provider: three options

Option Pros Cons
Factory delegate from validated options (shown) Simple, fails at startup on bad config Change needs restart (fine for this)
Keyed services + resolver Supports run-time choice per request More moving parts
Feature flag (Azure App Configuration) Switch provider without deploy Needs flag infrastructure and tests for both paths

6. Review technique

  1. Read for lifetimes: what is created where, and who owns it?
  2. Read for blocking: any .Result, .Wait(), GetAwaiter().GetResult()?
  3. Read for shared mutable state: statics, singletons, caches.
  4. Read for failure paths: timeouts, defaults, swallowed errors.
  5. Read for secrets and data handling.
  6. Only then, design and naming.

Try it yourself

  1. Run the original under a k6 load test at 200 RPS and watch dotnet-counters (threadpool-queue-length, threadpool-thread-count).
  2. Count TIME_WAIT sockets with netstat -an | grep TIME_WAIT | wc -l (Linux) during the test.
  3. Write a test with 1,000 parallel ConvertAsync calls for the same pair and assert the fake provider is called once (HybridCache stampede protection).
  4. Add Microsoft.CodeAnalysis.BannedApiAnalyzers with new HttpClient() banned and check the build fails on the original.

πŸ’» Code

The core of the rewrite, with a test that proves stampede protection and expiry:

namespace Currency;

using Microsoft.Extensions.Caching.Hybrid;

public sealed class CurrencyConverter(IRateProvider provider, HybridCache cache) : ICurrencyConverter
{
    private static readonly HybridCacheEntryOptions Ttl = new() { Expiration = TimeSpan.FromMinutes(15) };

    public async ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct)
    {
        decimal rate = await cache.GetOrCreateAsync(
            $"fx:{from}:{to}",
            async innerCt => await provider.GetRateAsync(from, to, innerCt),   // single flight per key
            Ttl,
            cancellationToken: ct);
        return amount * rate;
    }
}
namespace Currency.Tests;

using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

public sealed class CountingProvider : IRateProvider
{
    private int _calls;
    public int Calls => _calls;
    public async Task<decimal> GetRateAsync(string from, string to, CancellationToken ct)
    {
        Interlocked.Increment(ref _calls);
        await Task.Delay(50, ct);   // slow provider makes the stampede visible
        return 0.65m;
    }
}

public class CurrencyConverterTests
{
    [Fact]
    public async Task Concurrent_misses_call_the_provider_once()
    {
        var services = new ServiceCollection();
        services.AddHybridCache();
        HybridCache cache = services.BuildServiceProvider().GetRequiredService<HybridCache>();

        var provider = new CountingProvider();
        var sut = new CurrencyConverter(provider, cache);

        await Parallel.ForAsync(0, 500, async (_, ct) => await sut.ConvertAsync(100m, "AUD", "USD", ct));

        Assert.Equal(1, provider.Calls);
    }
}

⚠ Common mistakes

  • Mistake: Reviewing line by line and leading with naming or style. Why it is wrong: The author fixes the trivia and the starvation bug ships. Instead: Rank by severity: stalls/crashes, wrong data, security/diagnostics, design.
  • Mistake: "Fixing" the HttpClient by making it static forever. Why it is wrong: It avoids socket exhaustion but never picks up DNS changes. Instead: Typed clients via IHttpClientFactory, or PooledConnectionLifetime on a single SocketsHttpHandler.
  • Mistake: Wrapping the Dictionary writes in lock and keeping the design. Why it is wrong: It fixes corruption but not expiry, stampedes or testability. Instead: HybridCache with a TTL.
  • Mistake: Keeping the singleton and making the DbContext field [ThreadStatic] or locking around it. Why it is wrong: Still a long-lived context with a growing change tracker; thread-static breaks with async. Instead: IDbContextFactory<T> per operation, or a scoped consumer.
  • Mistake: Replacing .Result with GetAwaiter().GetResult(). Why it is wrong: It blocks exactly the same way; only the exception wrapping changes. Instead: Make Convert async and propagate to callers.
  • Mistake: Moving the API key to appsettings.json in the repo. Why it is wrong: It's still a committed secret. Instead: Key Vault-backed configuration (managed identity), user secrets locally, and rotate the exposed key.
  • Mistake: Keeping the switch default branch "for safety". Why it is wrong: It turns a configuration error into silently wrong rates and costs. Instead: Validate options at startup and fail fast.
  • Mistake: Over-engineering the rewrite with a mediator, an Abstract Factory and a plugin loader. Why it is wrong: Two providers chosen by configuration need one factory delegate. Instead: The smallest design that fixes the issues.

πŸ› Senior insight: trade-offs

This code is a catalogue of creational mistakes: every object that should be owned by the container (singleton, client, context, provider) is created by hand. The senior move is to see that one root cause, explain the production impact of each symptom in order, and fix it with the framework's mechanisms rather than with more patterns.

Finding Framework mechanism Why not hand-roll
Static singleton AddScoped/AddSingleton Lifetimes, disposal, testability
new HttpClient() AddHttpClient<T>() + AddStandardResilienceHandler() Handler pooling, rotation, resilience
new DbContext() AddDbContext/AddDbContextFactory Correct per-operation lifetime
Dictionary cache HybridCache Expiry, stampede protection, optional L2
switch factory Options + ValidateOnStart, keyed services Fail-fast configuration, Open/Closed
Hard-coded key Key Vault configuration provider Rotation, audit, no secrets in Git

I'd also keep the rewrite proportionate. Two providers chosen by configuration don't need a plugin framework. To show the fix worked, I'd compare before and after on thread-pool queue length, TIME_WAIT socket count, cache hit rate and p99 latency under the same load test.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate flags new HttpClient() per call Why: Checks diagnosing socket exhaustion and TIME_WAIT
    How to answer

    Two different limits produce similar errors:

    1. Descriptor exhaustion (EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.
    2. Ephemeral port exhaustion (EADDRNOTAVAIL, "Cannot assign requested address"): too many outbound connections to the same destination, usually closed sockets stuck in TIME_WAIT for 60 s.

    The classic .NET cause is new HttpClient() per request. Fix it with a shared HttpClient using SocketsHttpHandler { PooledConnectionLifetime = ... }, or IHttpClientFactory. Diagnose with ls /proc/<pid>/fd | wc -l, lsof -p, ss -s and ss -tan state time-wait.

  2. When: Candidate flags the DbContext owned by a singleton Why: Checks captive dependencies and DI lifetime validation
    How to answer

    A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.

    ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.

    The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.

  3. When: Candidate replaces the switch factory Why: Checks run-time implementation selection without a service locator
    How to answer

    This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:

    • Keyed services (.NET 8+): AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.
    • IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.
    • Typed resolver over keyed services: IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.

    To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.

πŸ›  Real-world problems: how you handle them

Rates service took checkout down at month-end
Situation
A checkout API on .NET [10] in Azure App Service, [~400] requests per second at peak, calling a `CurrencyService.Instance` for every international order.
Signals
At [month-end], p99 latency jumped from [300 ms] to timeouts; App Service showed CPU pinned at [100%] on two instances and low on others; logs showed `SocketException` and EF 'A second operation was started on this context instance'.
Investigation
Collected a dump with `dotnet-dump collect`. `clrstack -all` showed [~200] threads blocked in `Task.Result` inside `Convert`, and two threads looping in `Dictionary.FindValue`. `netstat` on the instance showed [~14,000] sockets in `TIME_WAIT`. Code review confirmed `new HttpClient()` per miss and a singleton-owned `DbContext`.
Resolution
Immediate: restarted instances and scaled out to buy time, then hot-fixed with a static `ConcurrentDictionary` and a shared `HttpClient`. Real fix: the DI rewrite with typed clients, `AddStandardResilienceHandler`, `HybridCache` with a 15-minute TTL, `IDbContextFactory` for audits and async end to end. Rotated the exposed API key.
Prevention
Banned-API analyser for `new HttpClient()` and `DateTime.Now`; VSTHRD002 as an error; secret scanning in CI; a load test at 2× peak in the release pipeline; dashboard alerts on thread-pool queue length.

How to tell it (STAR)

**S:** At [company] our checkout timed out at [month-end] peak, and two instances sat at 100% CPU. **T:** As [the senior on call], I had to restore checkout and fix the root cause in the shared currency service. **A:** A memory dump showed [~200] threads blocked on `.Result` and two threads spinning in a corrupted `Dictionary`, and `netstat` showed [~14,000] sockets in `TIME_WAIT` from `new HttpClient()` per call. We restarted and scaled out, hot-fixed the cache and client, and then I led a rewrite onto DI with typed clients, a resilience handler, `HybridCache` and short-lived `DbContext`s, plus rotating the hard-coded key. **R:** p99 for conversion dropped to [~40 ms] with a [98%] cache hit rate, provider calls fell from [~2,000] to [~30] a minute, and the analysers have blocked [several] similar changes since.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me