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

πŸ“š Interview question

What is the Chain of Responsibility pattern? Explain how ASP.NET Core middleware and DelegatingHandler implement it, why the order of handlers matters, how short-circuiting works, and how the classic "handle it or pass it on" chain differs from a pipeline.

Chain of Responsibility intent and structure, the classic handle-or-pass chain (approval limits) vs the pipeline variant where every handler can act before and after next, ASP.NET Core middleware (RequestDelegate next), DelegatingHandler, short-circuiting, the recommended middleware order, and the costs of long implicit chains.

Intermediate Theory Intermediate aspnet-core chain-of-responsibility delegatinghandler design-patterns middleware

🎯 Key points

  • Chain of Responsibility passes a request along a chain of handlers; each decides to handle it, pass it on, or both, and the sender doesn't know which handler acts
  • Classic variant: the first handler that can handle it stops the chain (approval by amount: team lead, manager, director)
  • Pipeline variant: every handler can act before and after calling next; ASP.NET Core middleware and DelegatingHandler work this way
  • Short-circuiting: a handler returns without calling next (auth returning 401, static files serving a file, a cache hit), so later handlers never run
  • Middleware order is execution order: exception handling first, then HTTPS redirection, static files, routing, CORS, authentication, authorisation, endpoints
  • DelegatingHandler chains are built outermost-first by AddHttpMessageHandler; the primary handler (SocketsHttpHandler) is the end of the chain
  • A request nobody handles must have a defined outcome (404, default handler, exception), not silently disappear
  • Costs: long implicit chains are hard to trace; order lives in Program.cs, not in the handlers

⏱ 30-second answer

Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.

  • Classic variant: the first handler that can deal with it stops the chain, like an expense approval going team lead β†’ manager β†’ director by amount.
  • Pipeline variant: every handler can act before and after calling next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.

Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.

The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Chain of Responsibility is about decoupling the sender of a request from whoever ends up handling it. You line up handlers, give the request to the first one, and each handler either deals with it or passes it to the next. The textbook example is an expense approval: a team lead can approve up to $1,000, a manager up to $10,000, a director above that. The request walks the chain until someone with enough authority takes it, and the person submitting it doesn't need to know who that is.

In .NET you mostly meet the pipeline variant, where every handler gets a chance to act before and after the next one. ASP.NET Core middleware is exactly that: each middleware receives the HttpContext and a RequestDelegate next, does some work, calls await next(context), and can do more work as the response comes back. Outgoing HTTP is the mirror image: each DelegatingHandler overrides SendAsync, does something, and calls base.SendAsync to reach the inner handler, ending at SocketsHttpHandler. Short-circuiting is just not calling next: the static files middleware serves the file and stops; the authorisation middleware returns 401 or 403; a response cache returns the cached body. Everything after that never runs.

Which is why order matters so much. If exception handling isn't first, exceptions in earlier middleware escape it. If authorisation runs before authentication, there's no user to authorise. If static files sit after authentication, every image request pays for auth. The mistake I see is adding middleware in whatever order it was written and only finding out in production that, say, the rate limiter runs after an expensive step it was meant to protect. In a chain, the order is part of the design; I read Program.cs top to bottom as the request's path."


Classic chain vs pipeline

Classic Chain of Responsibility Pipeline (middleware, handlers)
Who acts The first handler that can handle it Potentially every handler
Before/after Only one action point Code before and after next
Typical example Approval limits, support escalation, event routing ASP.NET Core middleware, DelegatingHandler, MediatR behaviours
Unhandled request Falls off the end: needs a default Reaches the terminal handler (endpoint, SocketsHttpHandler)

Recommended ASP.NET Core middleware order

Position Middleware Why there
1 UseExceptionHandler / UseDeveloperExceptionPage Must wrap everything to catch exceptions
2 UseHsts, UseHttpsRedirection Redirect before doing work
3 UseStaticFiles Short-circuits file requests cheaply
4 UseRouting Selects the endpoint (added implicitly by WebApplication if omitted)
5 UseCors Needs the endpoint, before auth for preflight
6 UseAuthentication, UseAuthorization Identify, then authorise
7 UseRateLimiter, UseOutputCache Need the endpoint and user
8 Endpoints (MapControllers, MapGet) Terminal handlers

Production example

An API placed a custom request-logging middleware that read the whole request body before UseRateLimiter. During a scraping burst, every rejected request still paid for body buffering, and memory hit about 1.8 GB. Moving the rate limiter ahead of the logging middleware (and only logging bodies for accepted requests) cut memory under the same load to about 400 MB and rejected requests in under 1 ms.

πŸ” What the interviewer is checking

Checks that the candidate recognises Chain of Responsibility in middleware and HTTP handlers, understands short-circuiting and knows why order matters.

Green flags

  • Distinguishes the classic first-match chain from the pipeline variant.
  • Explains next and short-circuiting with concrete middleware.
  • Gives a sensible middleware order with reasons.
  • Mentions the unhandled-request case.

Red flags

  • Thinks middleware order doesn't matter.
  • Can't explain what happens after a short-circuit.
  • Confuses Chain of Responsibility with Observer (all handlers notified regardless).

πŸ“š Learn in depth

1. Structure

Client ──▢ Handler1 ──next──▢ Handler2 ──next──▢ Handler3 ──▢ (default / terminal)
             β”‚                   β”‚                   β”‚
        handle or pass      handle or pass      handle or pass

Β«abstractΒ» Handler
  next: Handler?
  Handle(request) { if (CanHandle) ... else next?.Handle(request) }

The sender only knows the head of the chain. Handlers know only the abstraction of the next handler, so the chain can be rearranged or extended without touching the sender.

2. How ASP.NET Core builds the middleware chain

app.Use(...) adds a Func<RequestDelegate, RequestDelegate> to a list. When the app starts, ApplicationBuilder.Build() walks that list in reverse, wrapping the terminal delegate (which returns 404 if nothing matched) with each middleware, so the first registered middleware ends up outermost:

Request ─▢ ExceptionHandler ─▢ StaticFiles ─▢ Routing ─▢ Auth ─▢ Endpoint
Response ◀─ ExceptionHandler ◀─ StaticFiles ◀─ Routing ◀─ Auth β—€β”€β”˜
  • app.Use(async (ctx, next) => { ...; await next(ctx); ... }): pre and post.
  • app.Run(...): terminal; never calls next.
  • app.Map("/path", branch) / MapWhen: branches the chain.
  • Convention-based middleware classes take RequestDelegate next in the constructor and expose InvokeAsync(HttpContext); IMiddleware implementations are resolved from DI per request.

3. DelegatingHandler chains

Each DelegatingHandler has an InnerHandler. IHttpClientFactory builds the chain from AddHttpMessageHandler<T>() calls, with the first call outermost and the primary handler (SocketsHttpHandler) innermost. A handler can short-circuit by returning an HttpResponseMessage without calling base.SendAsync, which is how fake handlers in tests and cache handlers work.

4. Short-circuiting and response state

Once a middleware starts writing the response, headers are sent and later middleware can't change status codes or headers (HttpResponse.HasStarted). A middleware that short-circuits should set the status and write the body itself. Middleware after a short-circuit sees nothing, so logging or metrics middleware must sit outside anything that might short-circuit if it needs to see every request.

5. Classic chains in application code

Useful when rules are ordered and the first match wins: approval limits, discount eligibility, routing a support ticket, choosing a parser by file signature. In DI, register handlers in order and build the chain from IEnumerable<IHandler> (registration order is preserved), or iterate the list and stop at the first handler that returns a result. Always define what happens when nobody handles the request.

6. Costs

  • One delegate call per handler: negligible for HTTP, but deep chains lengthen stack traces.
  • The order is defined in one place (Program.cs) and invisible from the handler classes; reviewers must read the whole registration.
  • A handler that forgets to call next silently swallows requests.

Try it yourself

  1. Add three app.Use middleware that log before and after next; confirm the nested order in the console.
  2. Make the second one short-circuit for /health and see which logs disappear.
  3. Move UseAuthorization above UseAuthentication and observe the 401s on an [Authorize] endpoint.
  4. Build an approval chain from IEnumerable<IApprovalHandler> and test an amount nobody can approve.
  5. Write two DelegatingHandlers and verify their order with AddHttpMessageHandler.

πŸ’» Code

A pipeline-style middleware that short-circuits, the order in Program.cs, and a classic first-match chain.

namespace Api;

// Pipeline variant: acts before next, may short-circuit, can act after
public sealed class ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
{
    private readonly string? _expected = config["ApiKey"];

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("X-Api-Key", out var key) || key != _expected)
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;   // short-circuit: next never runs
            return;
        }

        await next(context);                                                   // pass it on
        context.Response.Headers.Append("X-Handled-By", "api");                // only if headers not yet sent
    }
}
// Program.cs: the order below IS the request path
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", w => { w.PermitLimit = 100; w.Window = TimeSpan.FromMinutes(1); }));

var app = builder.Build();
app.UseExceptionHandler("/error");     // 1. wraps everything below
app.UseHttpsRedirection();             // 2.
app.UseStaticFiles();                  // 3. short-circuits file requests before auth
app.UseRouting();                      // 4.
app.UseAuthentication();               // 5. who are you
app.UseAuthorization();                // 6. are you allowed
app.UseRateLimiter();                  // 7. after routing so endpoint policies apply
app.UseMiddleware<ApiKeyMiddleware>();
app.MapGet("/orders", () => Results.Ok()).RequireRateLimiting("api");   // terminal handler
app.Run();
namespace Expenses;

// Classic variant: the first handler that can handle it wins
public sealed record ExpenseClaim(string Employee, decimal Amount);

public interface IApprovalHandler
{
    string? TryApprove(ExpenseClaim claim);   // returns approver, or null to pass on
}

public sealed class TeamLeadApproval : IApprovalHandler
{
    public string? TryApprove(ExpenseClaim c) => c.Amount <= 1_000m ? "Team lead" : null;
}

public sealed class ManagerApproval : IApprovalHandler
{
    public string? TryApprove(ExpenseClaim c) => c.Amount <= 10_000m ? "Manager" : null;
}

public sealed class DirectorApproval : IApprovalHandler
{
    public string? TryApprove(ExpenseClaim c) => c.Amount <= 100_000m ? "Director" : null;
}

// IEnumerable<T> preserves registration order, so the chain order is the DI order
public sealed class ApprovalChain(IEnumerable<IApprovalHandler> handlers)
{
    public string Approve(ExpenseClaim claim) =>
        handlers.Select(h => h.TryApprove(claim)).FirstOrDefault(a => a is not null)
        ?? throw new InvalidOperationException($"No approver for {claim.Amount:C}; escalate to the board.");
}

// builder.Services.AddSingleton<IApprovalHandler, TeamLeadApproval>();
// builder.Services.AddSingleton<IApprovalHandler, ManagerApproval>();
// builder.Services.AddSingleton<IApprovalHandler, DirectorApproval>();
// builder.Services.AddSingleton<ApprovalChain>();

⚠ Common mistakes

  • Mistake: Registering UseExceptionHandler after other middleware. Why it is wrong: Exceptions thrown before it in the chain escape it and return raw 500s. Instead: Register exception handling first.
  • Mistake: UseAuthorization before UseAuthentication. Why it is wrong: No user has been established, so [Authorize] endpoints reject everyone. Instead: Authentication, then authorisation, both after routing.
  • Mistake: Putting expensive middleware (body logging, decompression) before a cheap short-circuit like rate limiting or static files. Why it is wrong: Every rejected or static request pays the cost. Instead: Put cheap short-circuits as early as their dependencies allow.
  • Mistake: Modifying headers after await next(context) without checking Response.HasStarted. Why it is wrong: Headers have already been sent, so it throws or is ignored. Instead: Use Response.OnStarting or set headers before calling next.
  • Mistake: A handler that forgets to call next on some code path. Why it is wrong: Requests silently stop with an empty 200. Instead: Make every path either call next or write a full response; test both.
  • Mistake: A classic chain with no defined outcome for unhandled requests. Why it is wrong: Requests fall off the end and nothing happens. Instead: End with a default handler or throw a clear exception.
  • Mistake: Writing a chain where a simple ordered if/else would do. Why it is wrong: Extra types for three fixed rules that never change. Instead: Use a chain when handlers are added, reordered or configured independently.

πŸ› Senior insight: trade-offs

Most of the value of Chain of Responsibility in .NET comes from using the framework's chains correctly rather than building your own. My review checklist for any pipeline is: what can short-circuit, what must see every request (so sits outside those), and what is expensive (so sits after the cheap rejections).

Option When it fits Cost When not to
ASP.NET Core middleware Concerns for every HTTP request Order is global and implicit Per-endpoint concerns (use endpoint filters)
Endpoint filters / MVC filters Concerns for specific endpoints Only within routing App-wide concerns
DelegatingHandler Outgoing HTTP concerns Per named/typed client Non-HTTP dependencies
Custom classic chain Ordered first-match business rules One class per rule Two or three fixed rules
Ordered if/else Small, stable rule set Edits one method Rules added or reordered by others

When diagnosing order problems, I log middleware entry and exit in a test environment or use Microsoft.AspNetCore debug logging, and I keep a test that hits a protected endpoint without credentials to catch auth-order regressions.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says the order of handlers matters Why: Checks diagnosing order bugs in decorator and handler chains
    How to 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.

  2. When: Candidate mentions DelegatingHandler wrapping an inner handler Why: Checks how DelegatingHandler is also a decorator and how decorators differ from a classic chain
    How to answer

    Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).

    .NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.

    The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().

    The trade-off is that order matters and long chains are harder to debug.

  3. When: Candidate mentions pipelines around handlers Why: Checks MediatR pipeline behaviours as another pipeline-style chain
    How to answer

    The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).

    MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.

    It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.

    Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.

    Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

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