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.

Intermediate 2 min readLesson 20 of 24

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:

  1. 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.
  2. Pipeline / middleware: every handler does some work and then calls the next — or short-circuits. Example: HTTP middleware (logging → auth → rate limit → handler).
next()next()next()RequestLoggingAuthRate limitHandler

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 4500

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 }); });

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.