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

📚 Interview question

After a refactor, your API starts caching error responses for an hour, some outgoing calls are retried far more often than configured, and every log line appears twice. You suspect the order of decorators and HttpClient handlers. How do you diagnose and fix it?

Debugging decorator and DelegatingHandler ordering: fallbacks cached by a cache decorator, timeouts and retries layered in the wrong order or twice (custom handler plus AddStandardResilienceHandler), duplicate logging from double registration; inspecting IServiceCollection descriptors, the resolved decorator chain, handler order, and OpenTelemetry span nesting; tests that lock the order.

Senior Debugging Advanced debugging decorator delegatinghandler dependency-injection design-patterns polly

🎯 Key points

  • Wrapper order defines behaviour: the outermost decorator or handler runs first on the way in and last on the way out, and can short-circuit everything inside it
  • Cached errors: a cache decorator outside an exception-swallowing fallback stores the fallback's empty result for the full TTL; put the fallback outermost so exceptions pass through the cache (HybridCache doesn't cache exceptions)
  • Retry storms: retries in two layers multiply (3 × 3 = 9+ attempts); a total timeout placed inside retry, or only per-attempt timeouts, changes semantics
  • AddStandardResilienceHandler's order is rate limiter → total timeout → retry → circuit breaker → attempt timeout; don't add a second retry layer around or inside it
  • Duplicate logs: a decorator or handler registered twice (Scrutor Decorate called in two extension methods), or a custom logging handler on top of IHttpClientFactory's built-in logging
  • Order rules are opposite: Scrutor's last Decorate call is outermost; AddHttpMessageHandler's first call is outermost
  • Diagnose: list ServiceDescriptors for the service type, resolve it and walk the inner chain, inspect handler registrations, and read OpenTelemetry/Application Insights span nesting and attempt counts
  • Fix: compose each chain in one place, make each concern exist once, and lock it with unit tests that assert the resolved decorator order and count attempts against a failing fake HttpMessageHandler

⏱ 30-second answer

All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.

  • Cached errors: the cache sits outside a fallback that turns exceptions into "empty" results, so it stores the outage for the full TTL. Put the fallback outermost (Fallback → Cache → real search): exceptions pass through the cache uncached, and the empty answer is never stored.
  • Retry storms: retries in two layers multiply attempts, for example a custom handler on top of AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.
  • Duplicate logs: a decorator or handler is registered twice, or a custom logging handler sits on top of the built-in HttpClient logging.

To diagnose, list the ServiceDescriptors, walk the resolved chain, inspect the handler order, and read span nesting in traces. Then compose the chain in one place and add tests that assert its order and attempt counts.

🗣 Full answer (senior)

How I would answer this in an interview

"All three symptoms point at the same thing: wrappers in the wrong order, or the same wrapper twice. Order matters because the outermost decorator or handler sees the call first and the result last, and it can short-circuit everything inside it. So I'd start by getting the actual chain, not the one I think we have. For DI decorators, I list the ServiceDescriptors registered for the interface, and in a unit test I resolve the service and walk the inner fields to print the runtime chain. For HttpClient, I look at the order of AddHttpMessageHandler calls and any AddStandardResilienceHandler, and then at a trace. In Application Insights or any OpenTelemetry backend, nested spans show every attempt and every handler.

Then the symptoms map to causes. Cached errors: there's a fallback decorator that catches exceptions and returns an empty list, and the caching decorator sits outside it. The cache sees a normal-looking result and stores the outage for an hour. The fix is to make the fallback the outermost layer. Exceptions from the real search then pass through the cache, which doesn't store exceptions, and only then does the fallback answer. Too many retries: someone added a custom retry handler, or a Polly retry in the client class, on top of the standard resilience handler, which already retries. That's three times three attempts, and if a total timeout ended up inside the retry instead of outside, the overall request can run far longer than intended. Double logs: a decorator registered twice, typically Decorate called in two extension methods, or a custom logging handler duplicating the built-in IHttpClientFactory logging. For example, at [company] a refactor moved registrations into feature modules and [the cache ended up outside the fallback], so [a 2-minute upstream outage became an hour of empty search results]. [I reordered the chain, removed the duplicate handler and added chain-order tests.]

The fix is to compose each chain in one place and make every concern exist exactly once. I lock it in with unit tests that assert the resolved decorator order and count attempts against a fake handler. If the order of your decorators isn't tested, it isn't designed."


Symptom → likely cause

Symptom Likely cause Fix
Errors or empty results served for the whole TTL Cache outside an exception-swallowing fallback Fallback outermost: Fallback → Cache → real call
Attempts ≈ product of configured retries Two retry layers (custom handler + standard handler, or Polly in code + handler) One retry layer
Requests take far longer than the configured timeout Total timeout inside retry, or only per-attempt timeouts Total timeout outermost, attempt timeout innermost
Breaker never opens / opens too fast Breaker outside retry (sees one failure per sequence) or duplicated Breaker inside retry (standard order)
Every log line twice Decorator/handler registered twice; built-in + custom HTTP logging Register once; remove the duplicate
Cached data crosses tenants Tenant missing from the cache key, or cache outside tenant filtering Tenant in the key

Diagnostic toolbox

Tool What it shows
services.Where(d => d.ServiceType == typeof(IX)) How many registrations, which wins (last)
Resolve + walk inner fields (test helper) The real runtime decorator chain
IOptionsMonitor<HttpClientFactoryOptions> Handler builder actions for a named client
Application Insights / OpenTelemetry traces Nested spans per attempt, timing, retries
Polly telemetry (resilience events) Retry attempts, breaker state changes
Logs with attempt number and handler name Duplicate or extra layers

Production example

In a search API, a module-based refactor reversed two Scrutor Decorate calls, putting the cache outside the fallback. When the upstream search cluster had a 2-minute outage, the fallback returned empty results, the cache stored them for 60 minutes, and the site showed "no products found" long after recovery. Restoring Fallback → Cache → Elastic and adding a chain-order test fixed it. The same review found a duplicate logging handler that had doubled log ingestion cost.

🔍 What the interviewer is checking

Checks the ability to debug composition problems in real .NET services: DI decorator order, DelegatingHandler order, resilience ordering and duplication.

Green flags

  • Connects each symptom to an ordering or duplication cause.
  • Knows the opposite order rules (Scrutor vs AddHttpMessageHandler) and the standard resilience order.
  • Uses descriptors, chain walking and trace span nesting to see the real chain.
  • Fixes with single-place composition and tests for order and attempt counts.

Red flags

  • Guesses at fixes without inspecting the actual chain.
  • Adds more retries to "fix" reliability.
  • Doesn't see that caching a fallback caches the outage.

📚 Learn in depth

1. Order semantics

Request →  [A]  →  [B]  →  [C]  → real call
Response ← [A]  ←  [B]  ←  [C]  ←
  • A sees everything first and can short-circuit (a cache hit never reaches B or C).
  • C sees each individual attempt if B retries.
  • An exception thrown by the real call passes through C, then B, then A; whoever catches it first decides what the outer layers see.

2. How order is determined

Mechanism Order rule
Manual factory delegates Whatever you new up
Keyed inner services Explicit in constructors
Scrutor Decorate Each call wraps the current registration: last call is outermost
AddHttpMessageHandler<T>() First added is outermost
AddStandardResilienceHandler() One handler; inside it: rate limiter → total timeout → retry → circuit breaker → attempt timeout
Multiple AddX() extension methods Execution order of the extension methods in Program.cs

The inverse rules (last-is-outermost vs first-is-outermost) are a common source of bugs when registrations move between files.

3. Resilience ordering in detail

  • Total timeout outermost bounds the whole operation, including all retries.
  • Retry around the breaker means each attempt is recorded by the breaker, and once it opens, attempts fail fast instead of waiting.
  • Attempt timeout innermost bounds each individual try, so one slow attempt doesn't consume the whole budget.
  • Adding another retry outside the standard handler multiplies attempts and ignores its total timeout; adding one inside (a custom handler after it) retries each attempt.

4. Making fallbacks cache-safe

The simplest correct order is Fallback → Cache → real call. A failure in the real call throws through the cache factory; HybridCache doesn't store exceptions, so nothing is cached, and the fallback catches the exception outside and returns its degraded answer. If the cache must be outermost (for example, a shared cache in front of several strategies), the fallback must mark its result (SearchResult.IsDegraded) and the cache must refuse to store marked results, or store them with a very short TTL.

5. Tests that lock the chain

  • Decorator order: resolve IProductSearch and assert the runtime chain is FallbackSearch → CachedSearch → ElasticProductSearch. Reach the inner via an internal property or reflect on the primary-constructor field.
  • Attempt count: a fake HttpMessageHandler that always returns 503 and counts calls; assert the count equals the configured attempts.
  • Single registration: assert exactly one descriptor for each decorator type.

Try it yourself

  1. Register cache and fallback decorators in both orders and simulate an outage; observe what's cached.
  2. Add a custom retry DelegatingHandler before AddStandardResilienceHandler; count attempts against a failing fake handler.
  3. Write the chain-walking test helper and use it on your real Program.cs registrations.
  4. Open a failed request's trace in Application Insights and count attempt spans.

💻 Code

The corrected chain (Fallback → Cache → Elastic) and tests that lock it:

namespace Search;

using Microsoft.Extensions.Caching.Hybrid;

public interface IProductSearch
{
    Task<SearchResult> SearchAsync(string query, CancellationToken ct);
}

public sealed record SearchResult(IReadOnlyList<string> Items, bool IsDegraded);

// Cache: read-through; if the inner call throws, nothing is cached and the exception propagates
public sealed class CachedSearch(IProductSearch inner, HybridCache cache) : IProductSearch
{
    private static readonly HybridCacheEntryOptions Ttl = new() { Expiration = TimeSpan.FromMinutes(60) };

    public async Task<SearchResult> SearchAsync(string query, CancellationToken ct) =>
        await cache.GetOrCreateAsync(
            $"search:v1:{query.ToLowerInvariant()}",
            async innerCt => await inner.SearchAsync(query, innerCt),
            Ttl,
            cancellationToken: ct);
}

// Fallback: OUTERMOST, so its degraded answer never reaches the cache
public sealed class FallbackSearch(IProductSearch inner, ILogger<FallbackSearch> logger) : IProductSearch
{
    public async Task<SearchResult> SearchAsync(string query, CancellationToken ct)
    {
        try
        {
            return await inner.SearchAsync(query, ct);
        }
        catch (HttpRequestException ex)
        {
            logger.LogWarning(ex, "Search unavailable, returning degraded result");
            return new SearchResult([], IsDegraded: true);
        }
    }
}
// Program.cs: compose the chain in ONE place. Scrutor rule: last Decorate is outermost
builder.Services.AddHybridCache();
builder.Services.AddScoped<IProductSearch, ElasticProductSearch>();
builder.Services.Decorate<IProductSearch, CachedSearch>();     // inner wrapper
builder.Services.Decorate<IProductSearch, FallbackSearch>();   // outermost

builder.Services.AddHttpClient<ElasticProductSearch>()
    .AddStandardResilienceHandler();                           // the ONLY retry layer; no custom retry handler
// No custom logging handler: IHttpClientFactory already logs request start/end per client
namespace Search.Tests;

using System.Net;
using System.Reflection;

public sealed class CountingHandler(HttpStatusCode code) : HttpMessageHandler
{
    public int Calls;
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage r, CancellationToken ct)
    {
        Interlocked.Increment(ref Calls);
        return Task.FromResult(new HttpResponseMessage(code));
    }
}

public class ChainTests
{
    [Fact]
    public void Decorators_are_in_the_designed_order()
    {
        using var app = new TestAppFactory();                 // WebApplicationFactory<Program>
        using var scope = app.Services.CreateScope();
        var chain = Walk(scope.ServiceProvider.GetRequiredService<IProductSearch>()).Select(o => o.GetType().Name);

        Assert.Equal(["FallbackSearch", "CachedSearch", "ElasticProductSearch"], chain);
    }

    [Fact]
    public async Task Only_one_retry_layer()
    {
        var failing = new CountingHandler(HttpStatusCode.ServiceUnavailable);
        var services = new ServiceCollection();
        services.AddHttpClient("search").ConfigurePrimaryHttpMessageHandler(() => failing).AddStandardResilienceHandler();
        HttpClient client = services.BuildServiceProvider().GetRequiredService<IHttpClientFactory>().CreateClient("search");

        using HttpResponseMessage _ = await client.GetAsync("http://search.test/q");
        Assert.Equal(4, failing.Calls);                       // 1 attempt + 3 retries (standard default), not 16
    }

    // Walks fields of type IProductSearch (primary-constructor captures) to list the runtime chain
    private static IEnumerable<object> Walk(object? o)
    {
        while (o is not null)
        {
            yield return o;
            o = o.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                 .FirstOrDefault(f => f.FieldType == typeof(IProductSearch))?.GetValue(o);
        }
    }
}

⚠ Common mistakes

  • Mistake: Assuming registration order equals runtime order without checking the rule. Why it is wrong: Scrutor's last-call-is-outermost and AddHttpMessageHandler's first-is-outermost are opposite. Instead: Inspect the resolved chain and test it.
  • Mistake: Putting a cache outside a fallback that swallows exceptions. Why it is wrong: Outages are cached as valid empty results for the full TTL. Instead: Fallback outermost so exceptions pass through the cache uncached; or mark degraded results and refuse to cache them.
  • Mistake: Adding a custom retry handler or Polly retry in client code on top of AddStandardResilienceHandler. Why it is wrong: Attempts multiply and the standard total timeout no longer bounds the operation. Instead: Configure the standard handler's retry options; keep one retry layer.
  • Mistake: Putting the total timeout inside the retry. Why it is wrong: Each retry gets a fresh "total" budget, so the request can run attempts × timeout. Instead: Total timeout outermost, per-attempt timeout innermost.
  • Mistake: Spreading registrations across feature modules that each decorate the same service. Why it is wrong: Order depends on which module's extension method runs first, and duplicates appear silently. Instead: Compose each decorator chain in one place.
  • Mistake: Adding a custom HTTP logging handler without checking built-in logging. Why it is wrong: IHttpClientFactory already logs per client; you double log volume and cost. Instead: Tune the built-in logging categories or replace it deliberately.
  • Mistake: Adopting Scrutor without the team knowing its order rule. Why it is wrong: The convenience hides composition; reordering two lines silently changes behaviour. Instead: Use it with a chain-order test, or compose manually with factory delegates if the team prefers explicit wiring.
  • Mistake: Fixing the order without adding a test. Why it is wrong: The next refactor reintroduces it. Instead: Chain-order and attempt-count unit tests.

🏛 Senior insight: trade-offs

Ordering bugs are hard because each piece is correct on its own; the defect is in the composition, which usually lives in Program.cs or scattered extension methods that nobody reviews carefully. I treat the composition of decorators and handlers as architecture: it's written once, in one place, documented, and tested.

Option When it fits Cost When not to
Manual composition (factory delegates) Few decorators, explicit is better Verbose Many services with the same chain
Scrutor Decorate Several decorators, readable Order rule easy to forget Registrations spread across modules
AddStandardResilienceHandler HTTP resilience Must not be duplicated Non-HTTP dependencies (use a ResiliencePipeline)
Generic pipeline (MediatR-style behaviours) Same chain for every handler Library and indirection Few handlers

In production I watch for the symptoms directly: retry attempt counts and breaker state from resilience telemetry, cache entries with degraded flags, and log volume per category (a sudden doubling is a duplicate registration).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains why the cache must not store fallback results Why: Checks writing a correct caching decorator
    How to answer

    The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.

    • Keys include everything that changes the result: product:v1:{tenant}:{id}.
    • Writes go through the decorator and invalidate after the inner write succeeds.
    • Exceptions aren't cached. Caching null is a deliberate choice with a short TTL.

    Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.

  2. When: Candidate says each concern should exist in exactly one layer Why: Checks where each responsibility belongs among wrappers
    How to answer

    All four wrap something, but for different reasons:

    Pattern Interface Wraps Purpose
    Adapter Different from the wrapped type One object Convert it to what the client expects
    Decorator Same One object Add behaviour; stackable
    Proxy Same One object Control access: lazy creation, remoting, permissions
    Facade New, simpler Many classes Simplify a subsystem

    The quick test is three questions. Does the interface change? Is it one object or many? Does it add features or control access?

    The distinction matters because it tells you where a responsibility belongs. Put retries in an adapter that already sits behind a resilience handler, and every failure is retried twice over.

🛠 Real-world problems: how you handle them

Two-minute search outage became an hour of 'no products found'
Situation
A retail search API on .NET [10] with Scrutor decorators (cache, fallback) over an Elasticsearch client, [~1,500] searches per second. A refactor moved registrations into feature modules.
Signals
After a [2-minute] Elasticsearch outage, the site kept showing 'no products found' for popular searches for [~60 minutes]; conversion dropped [~30%] during that hour; logs showed every HTTP log line twice since the refactor.
Investigation
Wrote a test that resolved `IProductSearch` and printed the runtime chain: `CachedSearch → FallbackSearch → ElasticProductSearch`. The design was `FallbackSearch → CachedSearch → Elastic`; the refactor had swapped the two `Decorate` calls, so the fallback's empty results were going into a 60-minute cache. Listing descriptors showed a logging `DelegatingHandler` added in two modules on top of built-in client logging.
Resolution
Immediate: flushed the search cache keys; results returned. Real fix: composed the chain in one place with the fallback outermost, removed the duplicate logging handler, and confirmed a single retry layer via the standard resilience handler.
Prevention
Unit tests asserting decorator order, one descriptor per decorator, and attempt counts against a failing fake handler; an ADR describing the chain; an alert when the share of degraded search results exceeds [1%].

How to tell it (STAR)

**S:** At [company] a [two-minute] search cluster outage left our site showing 'no products found' for about an hour. **T:** I needed to explain why recovery took so long and stop it happening again. **A:** I wrote a test that printed the real decorator chain. A refactor had swapped two registrations, putting the cache outside the fallback, so the fallback's empty results went into a 60-minute cache. The same check showed a logging handler registered twice. I flushed the cache to recover, recomposed the chain in one place with the fallback outermost, removed the duplicate handler and added chain-order tests. **R:** The next upstream outage recovered as soon as the cluster did, log ingestion fell by [~45%], and the tests have caught [one] ordering regression since.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me