Chain of Responsibility
Passing a request along a chain of handlers until one handles it — middleware pipelines, validation chains, approval workflows, and the variant where every handler participates.
Intent: avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle it. Chain the receiving objects and pass the request along the chain until an object handles it.
Two flavours:
- Classic: each handler either handles the request (and stops) or passes it on. Example: a support escalation (bot → agent → manager), or event bubbling in the DOM.
- Pipeline / middleware: every handler does some work and then calls the next — or short-circuits. Example: HTTP middleware (logging → auth → rate limit → handler).
If auth fails, it returns 401 without calling next(); later handlers never run.
Classic chain: expense approvals
abstract class Approver {
private Approver next;
Approver setNext(Approver next) { this.next = next; return next; } // fluent chaining
void handle(Expense e) {
if (canApprove(e)) approve(e);
else if (next != null) next.handle(e);
else throw new IllegalStateException("No one can approve " + e.amount());
}
protected abstract boolean canApprove(Expense e);
protected void approve(Expense e) { System.out.println(getClass().getSimpleName() + " approved " + e.amount()); }
}
class TeamLead extends Approver { protected boolean canApprove(Expense e) { return e.amount() <= 1_000; } }
class Manager extends Approver { protected boolean canApprove(Expense e) { return e.amount() <= 10_000; } }
class Director extends Approver { protected boolean canApprove(Expense e) { return e.amount() <= 100_000; } }
Approver chain = new TeamLead();
chain.setNext(new Manager()).setNext(new Director());
chain.handle(new Expense(4_500)); // Manager approved 4500class Approver:
limit = 0
def __init__(self, next_approver=None):
self.next = next_approver
def handle(self, expense):
if expense.amount <= self.limit:
print(f"{type(self).__name__} approved {expense.amount}")
elif self.next:
self.next.handle(expense)
else:
raise PermissionError(f"no one can approve {expense.amount}")
class TeamLead(Approver): limit = 1_000
class Manager(Approver): limit = 10_000
class Director(Approver): limit = 100_000
chain = TeamLead(Manager(Director()))
chain.handle(Expense(4_500)) # Manager approved 4500type Handler = (e: Expense) => boolean; // true = handled
const approver = (name: string, limit: number): Handler => (e) => {
if (e.amount > limit) return false;
console.log(`${name} approved ${e.amount}`);
return true;
};
const chain: Handler[] = [approver("TeamLead", 1_000), approver("Manager", 10_000), approver("Director", 100_000)];
function handle(e: Expense) {
if (!chain.some((h) => h(e))) throw new Error(`no one can approve ${e.amount}`);
}Pipeline chain: HTTP middleware
Each middleware receives the request and a next function. It can act before and after the rest of the chain — like decorators around the final handler.
type Ctx = { req: Request; res?: Response; user?: User };
type Middleware = (ctx: Ctx, next: () => Promise<void>) => Promise<void>;
const logging: Middleware = async (ctx, next) => {
const t = Date.now();
await next(); // run the rest of the chain
console.log(ctx.req.method, ctx.req.url, ctx.res?.status, `${Date.now() - t}ms`);
};
const auth: Middleware = async (ctx, next) => {
const user = await verify(ctx.req.headers.get("authorization"));
if (!user) { ctx.res = new Response("Unauthorized", { status: 401 }); return; } // short-circuit
ctx.user = user;
await next();
};
function compose(mws: Middleware[], handler: (ctx: Ctx) => Promise<void>) {
return (ctx: Ctx) => {
const run = (i: number): Promise<void> =>
i < mws.length ? mws[i](ctx, () => run(i + 1)) : handler(ctx);
return run(0);
};
}
const app = compose([logging, auth], async (ctx) => { ctx.res = Response.json({ hello: ctx.user!.name }); });# WSGI/ASGI middleware and Django middleware follow this shape
from typing import Awaitable, Callable
Handler = Callable[[Request], Awaitable[Response]]
Middleware = Callable[[Request, Handler], Awaitable[Response]]
async def logging_mw(req, next_):
start = time.perf_counter()
resp = await next_(req)
log.info("%s %s %s %.1fms", req.method, req.path, resp.status, (time.perf_counter() - start) * 1000)
return resp
async def auth_mw(req, next_):
if not (user := await verify(req.headers.get("authorization"))):
return Response(status=401) # short-circuit
req.state.user = user
return await next_(req)
def compose(middlewares: list[Middleware], handler: Handler) -> Handler:
for mw in reversed(middlewares):
handler = (lambda m, nxt: lambda req: m(req, nxt))(mw, handler)
return handler// Servlet filters / Spring's HandlerInterceptor / OkHttp interceptors
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
var http = (HttpServletRequest) req;
if (http.getHeader("Authorization") == null) {
((HttpServletResponse) res).sendError(401); // short-circuit
return;
}
chain.doFilter(req, res); // pass along
}
}In the wild
- Web middleware: Express, Koa, ASP.NET Core, Django, Servlet filters.
- DOM event bubbling: an event goes from the target up through ancestors until one calls
stopPropagation(). - Exception handling: an exception propagates up the call stack until a matching
catch. - Logging frameworks: loggers pass records to parent loggers.
- Validation pipelines, spam filters, support ticket routing, approval workflows.
Key takeaways
- Chain of Responsibility passes a request along handlers; the sender doesn't know who handles it.
- Classic: the first handler that can, handles it.
- Pipeline (middleware): every handler acts and calls next, or short-circuits.
- Middleware can run code before and after the rest of the chain.
- Order matters; plan for unhandled requests.