Patterns for behaviour · Chapter 20

Chain of Responsibility pattern

Pass a request along a chain of handlers until one deals with it, or let each do its part. Approval chains and middleware pipelines in Java and Python, plus the ordering bugs to avoid.

IntermediateInterview priority: Medium50 min
On this page
  1. The problem: the sender has to know everyone
  2. The idea: handlers in a line, each knowing only the next
  3. Build the classic chain
  4. The modern form: middleware pipelines
  5. Chain, Decorator, Observer: how they differ
  6. When not to use it
  7. Where you meet it in real code
  8. In the interview
  9. Quiz

The problem: the sender has to know everyone

A company reimburses expense claims. A team lead can approve up to $500, a manager up to $5,000, a director up to $50,000, and the CEO anything. The first version puts the whole policy in the code that submits a claim:

void submit(Claim c) {
    if (fraudService.isFlagged(c))      fraudService.block(c);
    else if (c.dollars() <= 500)        teamLead.approve(c);
    else if (c.dollars() <= 5_000)      manager.approve(c);
    else if (c.dollars() <= 50_000)     director.approve(c);
    else                                ceo.approve(c);
}

Every sender (the web form, the mobile app, the batch importer) needs this ladder, and every policy change (a new "finance review" step for travel, a different limit in one country) edits all of them. The sender knows every approver and the order they come in.

Each approver can pass a claim to the next

  1. Expense claims need approval. A team lead can approve up to 500 dollars, a manager up to 5,000, a director up to 50,000, and the CEO anything. The person submitting a claim shouldn’t have to know who to send it to.
  2. In a chain of responsibility, each handler holds a link to the next one. A request goes to the first handler. If it can deal with it, it does; if not, it passes it on.

The idea: handlers in a line, each knowing only the next

In a chain of responsibility, each handler holds a reference to the next handler. The sender gives the request to the first handler only. Each handler either deals with the request or passes it on. Nobody except the code that builds the chain knows the full order.

There are two flavours, and interviewers like it when you name both:

FlavourWhat each handler doesStops whenExamples
Classic (first one wins)Handles the request or passes it onOne handler takes itApproval limits, support escalation, event bubbling in a UI
Pipeline (everyone takes part)Does its bit, then passes it on; any handler may stop earlyA handler refuses, or the request reaches the endWeb middleware, servlet filters, HTTP client interceptors
RoleIn the approval exampleResponsibility
Handler (base class or interface)ApproverHolds next; handle() either processes or forwards
Concrete handlersFraudCheck, TeamLead, Manager, Director, CeoDecide whether they can handle it, and do so
ClientThe submit codeBuilds the chain once, then sends every request to its head

Build the classic chain

1. The base class holds next and implements handle() once: process it, forward it, or reject it when the chain runs out. setNext returns its argument so the chain can be built in one line.

2. Concrete handlers only answer "can I handle this?" and "how?".

3. The client builds the chain and only ever talks to the head.

handle() either does the work or forwards to next

  1. In code, every handler shares one small base class. handle() either does the work or forwards the request to next.
// ---------- Client ----------
public class ApprovalDemo {
    public static void main(String[] args) {
        Approver chain = new FraudCheck();                    // the sender only knows the first handler
        chain.setNext(new TeamLead()).setNext(new Manager()).setNext(new Director()).setNext(new Ceo());

        chain.handle(new Claim("taxi", 40, false));
        chain.handle(new Claim("conference", 3_000, false));
        chain.handle(new Claim("new office", 120_000, false));
        chain.handle(new Claim("gift cards", 450, true));

        Approver noCeo = new TeamLead();                      // a chain with no catch-all
        noCeo.setNext(new Manager());
        noCeo.handle(new Claim("servers", 9_000, false));
    }
}

record Claim(String what, int dollars, boolean flagged) {}

// ---------- The handler base class ----------
abstract class Approver {
    private Approver next;

    /** Returns the handler it was given, so calls can be chained: a.setNext(b).setNext(c). */
    Approver setNext(Approver next) { this.next = next; return next; }

    final void handle(Claim c) {
        if (canHandle(c)) process(c);
        else if (next != null) next.handle(c);                // pass it along
        else System.out.println(c.what() + ": rejected, nobody could approve " + c.dollars());
    }
    protected abstract boolean canHandle(Claim c);
    protected abstract void process(Claim c);
}

// ---------- Concrete handlers ----------
final class FraudCheck extends Approver {                     // handles (stops) flagged claims only
    protected boolean canHandle(Claim c) { return c.flagged(); }
    protected void process(Claim c) { System.out.println(c.what() + ": blocked by fraud check"); }
}

class LimitApprover extends Approver {
    private final String role; private final int limit;
    LimitApprover(String role, int limit) { this.role = role; this.limit = limit; }
    protected boolean canHandle(Claim c) { return c.dollars() <= limit; }
    protected void process(Claim c) { System.out.println(c.what() + ": approved by " + role); }
}

final class TeamLead extends LimitApprover { TeamLead() { super("team lead", 500); } }
final class Manager  extends LimitApprover { Manager()  { super("manager", 5_000); } }
final class Director extends LimitApprover { Director() { super("director", 50_000); } }
final class Ceo      extends LimitApprover { Ceo()      { super("CEO", Integer.MAX_VALUE); } }

Both print:

taxi: approved by team lead
conference: approved by manager
new office: approved by CEO
gift cards: blocked by fraud check
servers: rejected, nobody could approve 9000

The last line is the classic trap: a chain without a catch-all at the end. The base class must decide what "fell off the end" means (reject, raise, return a default) rather than silently doing nothing.

Reordering or adding a handler touches no other handler

  1. The sender only knows the first handler, and handlers only know the next one. So you can add, remove or reorder handlers, like putting a fraud check at the front, without changing any of the others.

Adding FraudCheck at the front was one new class and one change where the chain is built. Neither the approvers nor the senders changed. That is the payoff: the order and membership of the chain is configuration, not code spread across callers.

The modern form: middleware pipelines

Every web framework is a chain of responsibility in the pipeline flavour. A request passes through a list of middleware (code that runs around every request: logging, authentication, rate limiting, compression) before it reaches your endpoint, and the response travels back out through the same layers in reverse.

A request flows through middleware before your code sees it

  1. Web servers work this way: a request flows through a middleware pipeline (logging, then authentication, then rate limiting) before your code sees it. Button clicks in a web page bubble up through parent elements the same way. Just make sure something handles a request that falls off the end.

Here each middleware is a function of the request and next. That is all the "link to the next handler" needs to be:

  • Pass it along: call next(req) and return its response (optionally doing work before and after).
  • Stop: return a response without calling next. Auth returns 401; the rate limiter returns 429.
import java.util.*;

// ---------- Client ----------
public class PipelineDemo {
    public static void main(String[] args) {
        Handler app = req -> {                                        // the endpoint itself
            if (req.path().equals("/crash")) throw new RuntimeException("bug");
            return new Response(200, "orders for " + req.attrs().get("user"));
        };
        // Outermost first: logging sees every outcome, errors become 500s, auth before rate limit
        Handler server = Pipeline.build(app, new Logging(), new ErrorHandler(), new Auth(), new RateLimit(2));

        server.handle(Request.of("GET", "/orders", "token-ana"));
        server.handle(Request.of("GET", "/orders", null));            // no token: stops at Auth
        server.handle(Request.of("GET", "/orders", "token-ana"));
        server.handle(Request.of("GET", "/orders", "token-ana"));     // third in the window: 429
        server.handle(Request.of("GET", "/crash", "token-bo"));       // endpoint throws: 500

        System.out.println("-- wrong order: Auth before Logging");
        Handler wrong = Pipeline.build(app, new ErrorHandler(), new Auth(), new Logging(), new RateLimit(2));
        wrong.handle(Request.of("GET", "/orders", null));             // rejected, and nothing is logged
    }
}

record Request(String method, String path, String token, Map<String, String> attrs) {
    static Request of(String method, String path, String token) { return new Request(method, path, token, new HashMap<>()); }
}
record Response(int status, String body) {}

@FunctionalInterface interface Handler { Response handle(Request req); }

/** A middleware does its part, then either calls next (pass along) or returns a response (stop). */
@FunctionalInterface interface Middleware { Response handle(Request req, Handler next); }

final class Pipeline {
    static Handler build(Handler endpoint, Middleware... chain) {
        Handler h = endpoint;
        for (int i = chain.length - 1; i >= 0; i--) {                 // wrap from the inside out
            Middleware m = chain[i]; Handler next = h;
            h = req -> m.handle(req, next);
        }
        return h;
    }
}

// ---------- Middlewares ----------
final class ErrorHandler implements Middleware {
    public Response handle(Request req, Handler next) {
        try { return next.handle(req); }
        catch (RuntimeException e) { return new Response(500, "internal error"); }   // never leak the stack trace
    }
}

final class Logging implements Middleware {
    public Response handle(Request req, Handler next) {
        Response res = next.handle(req);                              // code after next() runs on the way out
        System.out.println(req.method() + " " + req.path() + " -> " + res.status());
        return res;
    }
}

final class Auth implements Middleware {
    private static final Map<String, String> TOKENS = Map.of("token-ana", "ana", "token-bo", "bo");
    public Response handle(Request req, Handler next) {
        String user = req.token() == null ? null : TOKENS.get(req.token());
        if (user == null) return new Response(401, "log in first");   // stop: next is never called
        req.attrs().put("user", user);                                // later handlers can rely on this
        return next.handle(req);
    }
}

final class RateLimit implements Middleware {                         // per user, so it must run after Auth
    private final int perWindow;
    private final Map<String, Integer> counts = new HashMap<>();      // a real one resets each window
    RateLimit(int perWindow) { this.perWindow = perWindow; }
    public synchronized Response handle(Request req, Handler next) {
        int n = counts.merge(req.attrs().get("user"), 1, Integer::sum);
        if (n > perWindow) return new Response(429, "slow down");
        return next.handle(req);
    }
}

Both print:

GET /orders -> 200
GET /orders -> 401
GET /orders -> 200
GET /orders -> 429
GET /crash -> 500
-- wrong order: Auth before Logging

The last request is rejected with a 401, and no log line appears, because Logging sits after Auth and never runs. That is the most common chain bug in production: the code is right, the order is wrong.

The same thing in real frameworks

FrameworkA handler isPass alongStopOrder set by
Java servlet filtersFilter.doFilter(req, res, chain)chain.doFilter(req, res)Write a response and returnweb.xml order or @Order / FilterRegistrationBean in Spring
Spring SecurityOne of a dozen built-in filtersSame as servlet filterse.g. return 401 or 403Fixed internal order; you insert with addFilterBefore
Express (Node.js)(req, res, next) => …next()res.status(401).send()Order of app.use() calls
DjangoA class with __call__(request)self.get_response(request)Return an HttpResponseThe MIDDLEWARE list: top to bottom on the way in, bottom to top on the way out
OkHttp (client side)Interceptor.intercept(chain)chain.proceed(request)Return a response, e.g. from a cacheOrder of addInterceptor()

Chain, Decorator, Observer: how they differ

Chain of ResponsibilityDecoratorObserver
ShapeLinked handlers, each knowing the nextWrappers, each wrapping one inner objectOne subject, a list of independent listeners
Can a link stop the flow?Yes: that's the point (handle it, or refuse it)No: a decorator always calls the inner objectNo: every observer is notified
Who gets the requestThe first handler that takes it (classic) or each in turn (pipeline)Every layer, alwaysEvery listener, independently
Same interface as the target?Not necessarilyYes: a decorated object is used like the originalNo
ExampleApproval limits; auth middleware returning 401A BufferedInputStream around a FileInputStreamEmail and analytics both reacting to "order placed"

Middleware sits between the first two: structurally each layer wraps the next (decorator-like), but because any layer may refuse to call inward, it is usually described as a chain.

When not to use it

Where you meet it in real code

  • Web servers: servlet filters, Spring Security's filter chain, Express, Koa, ASP.NET Core and Django middleware.
  • HTTP clients: OkHttp interceptors (auth headers, retries, caching, logging), Axios interceptors.
  • Browsers: DOM events bubble from the clicked element up through its parents; any listener can call stopPropagation() to stop the chain.
  • Logging: in Python's logging, and similarly java.util.logging, a record is handled by a logger's handlers and then propagates to its parent logger's handlers unless propagate is false.
  • Netty: a ChannelPipeline of inbound and outbound handlers for network protocols.

In the interview

Your turn: order validation

Before an order is accepted, it must pass: a format check (non-empty cart, valid address), a stock check, a fraud score check (score above 80 rejects; 50–80 sends the order to manual review instead of rejecting), and a payment authorisation. The fraud rules change monthly and some countries skip the fraud check. Design the chain: the interface, the result type, one handler, and how the chain is built.

Compare with our answer
sealed interface Verdict permits Accept, Reject, Review {}
record Accept() implements Verdict {}
record Reject(String reason) implements Verdict {}
record Review(String reason) implements Verdict {}

interface OrderCheck { Verdict check(Order o, Function<Order, Verdict> next); }

final class FraudCheck implements OrderCheck {
    private final FraudScorer scorer;
    FraudCheck(FraudScorer scorer) { this.scorer = scorer; }
    public Verdict check(Order o, Function<Order, Verdict> next) {
        int score = scorer.score(o);
        if (score > 80) return new Reject("fraud score " + score);
        if (score >= 50) return new Review("fraud score " + score);   // stop, but not a rejection
        return next.apply(o);
    }
}

// built in one place, per country, from configuration
List<OrderCheck> checks = new ArrayList<>(List.of(new FormatCheck(), new StockCheck()));
if (!config.skipsFraud(country)) checks.add(new FraudCheck(scorer));
checks.add(new PaymentAuth(gateway));                                 // last: the expensive, side-effecting step

A strong answer mentions: a pipeline-style chain where each check can stop with a reason · a result type richer than true/false (accept, reject, review) · cheap checks first and payment authorisation last, because it has side effects and costs money · the chain assembled in one place from per-country configuration · a final "accept" when every check passes, so nothing falls off the end · each check testable alone by passing a fake next.

Chain of Responsibility on one page
  • Intent: decouple the sender from the receivers; pass a request along handlers that each know only the next.
  • Two flavours: classic (first handler that can, does) and pipeline (each does its part; any may stop).
  • Pass along vs stop: call next, or return a result without calling it.
  • End of the chain: always decide what happens when nobody handles it (a catch-all or an explicit reject).
  • Build the chain in one place, ideally from configuration; the client knows only the head.
  • Order matters: logging outermost, error handling inside it, CORS before auth, per-user limits after auth, side effects last.
  • Not Decorator: decorators always delegate; chain handlers may refuse.
  • In the wild: servlet filters, Express and Django middleware, OkHttp interceptors, DOM event bubbling, logger propagation.
Your turn: the requirement changes

The API team wants two changes to the middleware pipeline above: unauthenticated clients must be limited to 10 requests a minute per IP address (to protect the login service), and a new response compression middleware must gzip large JSON responses. Where does each go in the chain, and why?

Compare with our answer

A strong answer mentions: an IP-based limiter placed before auth, so floods are rejected cheaply before any token lookup · keeping the per-user limiter after auth, since it needs the user · compression placed outside the endpoint but inside logging (or logging records the uncompressed size, decided on purpose), and only for responses above a size threshold and when the client sent Accept-Encoding: gzip · the error handler still producing a response that compression and logging can see · a test per ordering rule (an unauthenticated flood gets 429 before auth runs) · both limiters needing shared storage such as Redis once there is more than one server, because an in-memory counter is per process.

Interactive labPractise it: route expense claims and add a fraud checkOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. An Express API logs every request with a logging middleware registered after the authentication middleware. The security team notices that failed login attempts never appear in the logs. What is the cause?

2. What is the key difference between a Chain of Responsibility handler and a Decorator?

3. An approval chain has team lead ($500), manager ($5,000) and director ($50,000). A $90,000 claim is submitted and nothing happens: no approval, no error. What is the best fix?

4. A Spring Boot API has a CORS filter after its JWT authentication filter. The browser app on another domain fails on every POST, although the same calls work from curl. Why?

5. A team wants a per-user rate limit of 100 requests a minute. Where should the limiter go in the middleware chain?

6. Which situation is the weakest case for a Chain of Responsibility?

7. In Django, AuthenticationMiddleware is listed above SessionMiddleware in MIDDLEWARE. What happens?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.