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.
All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.
AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.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.
"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. ForHttpClient, I look at the order ofAddHttpMessageHandlercalls and anyAddStandardResilienceHandler, 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
Decoratecalled in two extension methods, or a custom logging handler duplicating the built-inIHttpClientFactorylogging. 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 | 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 |
| 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 |
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.
Checks the ability to debug composition problems in real .NET services: DI decorator order, DelegatingHandler order, resilience ordering and duplication.
Green flags
AddHttpMessageHandler) and the standard resilience order.Red flags
Request → [A] → [B] → [C] → real call
Response ← [A] ← [B] ← [C] ←
| 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.
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.
IProductSearch and assert the runtime chain is FallbackSearch → CachedSearch → ElasticProductSearch. Reach the inner via an internal property or reflect on the primary-constructor field.HttpMessageHandler that always returns 503 and counts calls; assert the count equals the configured attempts.DelegatingHandler before AddStandardResilienceHandler; count attempts against a failing fake handler.Program.cs registrations.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);
}
}
}
AddHttpMessageHandler's first-is-outermost are opposite. Instead: Inspect the resolved chain and test it.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.IHttpClientFactory already logs per client; you double log volume and cost. Instead: Tune the built-in logging categories or replace it deliberately.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).
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.
product:v1:{tenant}:{id}.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.
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.
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.
Last updated 18 Nov 2026.