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.
On this page
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
- 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.
- 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:
| Flavour | What each handler does | Stops when | Examples |
|---|---|---|---|
| Classic (first one wins) | Handles the request or passes it on | One handler takes it | Approval limits, support escalation, event bubbling in a UI |
| Pipeline (everyone takes part) | Does its bit, then passes it on; any handler may stop early | A handler refuses, or the request reaches the end | Web middleware, servlet filters, HTTP client interceptors |
| Role | In the approval example | Responsibility |
|---|---|---|
| Handler (base class or interface) | Approver | Holds next; handle() either processes or forwards |
| Concrete handlers | FraudCheck, TeamLead, Manager, Director, Ceo | Decide whether they can handle it, and do so |
| Client | The submit code | Builds 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
- 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); } }from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class Claim:
what: str
dollars: int
flagged: bool = False
# ---------- The handler base class ----------
class Approver(ABC):
def __init__(self):
self._next = None
def set_next(self, nxt: "Approver") -> "Approver":
"""Returns the handler it was given, so calls can be chained."""
self._next = nxt
return nxt
def handle(self, c: Claim) -> None:
if self.can_handle(c):
self.process(c)
elif self._next is not None:
self._next.handle(c) # pass it along
else:
print(f"{c.what}: rejected, nobody could approve {c.dollars}")
@abstractmethod
def can_handle(self, c: Claim) -> bool: ...
@abstractmethod
def process(self, c: Claim) -> None: ...
# ---------- Concrete handlers ----------
class FraudCheck(Approver): # handles (stops) flagged claims only
def can_handle(self, c):
return c.flagged
def process(self, c):
print(f"{c.what}: blocked by fraud check")
class LimitApprover(Approver):
def __init__(self, role: str, limit: float):
super().__init__()
self.role, self.limit = role, limit
def can_handle(self, c):
return c.dollars <= self.limit
def process(self, c):
print(f"{c.what}: approved by {self.role}")
# ---------- Client ----------
if __name__ == "__main__":
chain = FraudCheck() # the sender only knows the first handler
(chain.set_next(LimitApprover("team lead", 500))
.set_next(LimitApprover("manager", 5_000))
.set_next(LimitApprover("director", 50_000))
.set_next(LimitApprover("CEO", float("inf"))))
chain.handle(Claim("taxi", 40))
chain.handle(Claim("conference", 3_000))
chain.handle(Claim("new office", 120_000))
chain.handle(Claim("gift cards", 450, flagged=True))
no_ceo = LimitApprover("team lead", 500) # a chain with no catch-all
no_ceo.set_next(LimitApprover("manager", 5_000))
no_ceo.handle(Claim("servers", 9_000))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
- 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
- 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);
}
}from dataclasses import dataclass, field
from functools import reduce
from typing import Callable, Optional
@dataclass
class Request:
method: str
path: str
token: Optional[str] = None
attrs: dict = field(default_factory=dict)
@dataclass
class Response:
status: int
body: str
Handler = Callable[[Request], Response]
Middleware = Callable[[Request, Handler], Response] # do your part, then call next or return
def build(endpoint: Handler, *chain: Middleware) -> Handler:
"""Wrap from the inside out, so the first middleware listed runs first."""
return reduce(lambda nxt, mw: (lambda req: mw(req, nxt)), reversed(chain), endpoint)
# ---------- Middlewares ----------
def error_handler(req, nxt):
try:
return nxt(req)
except Exception:
return Response(500, "internal error") # never leak the stack trace
def logging_mw(req, nxt):
res = nxt(req) # code after next() runs on the way out
print(f"{req.method} {req.path} -> {res.status}")
return res
TOKENS = {"token-ana": "ana", "token-bo": "bo"}
def auth(req, nxt):
user = TOKENS.get(req.token)
if user is None:
return Response(401, "log in first") # stop: next is never called
req.attrs["user"] = user # later handlers can rely on this
return nxt(req)
def rate_limit(per_window): # per user, so it must run after auth
counts = {} # a real one resets each window, and locks
def mw(req, nxt):
user = req.attrs["user"]
counts[user] = counts.get(user, 0) + 1
if counts[user] > per_window:
return Response(429, "slow down")
return nxt(req)
return mw
# ---------- Client ----------
def app(req): # the endpoint itself
if req.path == "/crash":
raise RuntimeError("bug")
return Response(200, f"orders for {req.attrs['user']}")
if __name__ == "__main__":
# Outermost first: logging sees every outcome, errors become 500s, auth before rate limit
server = build(app, logging_mw, error_handler, auth, rate_limit(2))
server(Request("GET", "/orders", "token-ana"))
server(Request("GET", "/orders")) # no token: stops at auth
server(Request("GET", "/orders", "token-ana"))
server(Request("GET", "/orders", "token-ana")) # third in the window: 429
server(Request("GET", "/crash", "token-bo")) # endpoint throws: 500
print("-- wrong order: Auth before Logging")
wrong = build(app, error_handler, auth, logging_mw, rate_limit(2))
wrong(Request("GET", "/orders")) # rejected, and nothing is loggedBoth 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
| Framework | A handler is | Pass along | Stop | Order set by |
|---|---|---|---|---|
| Java servlet filters | Filter.doFilter(req, res, chain) | chain.doFilter(req, res) | Write a response and return | web.xml order or @Order / FilterRegistrationBean in Spring |
| Spring Security | One of a dozen built-in filters | Same as servlet filters | e.g. return 401 or 403 | Fixed internal order; you insert with addFilterBefore |
| Express (Node.js) | (req, res, next) => … | next() | res.status(401).send() | Order of app.use() calls |
| Django | A class with __call__(request) | self.get_response(request) | Return an HttpResponse | The 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 cache | Order of addInterceptor() |
Chain, Decorator, Observer: how they differ
| Chain of Responsibility | Decorator | Observer | |
|---|---|---|---|
| Shape | Linked handlers, each knowing the next | Wrappers, each wrapping one inner object | One 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 object | No: every observer is notified |
| Who gets the request | The first handler that takes it (classic) or each in turn (pipeline) | Every layer, always | Every listener, independently |
| Same interface as the target? | Not necessarily | Yes: a decorated object is used like the original | No |
| Example | Approval limits; auth middleware returning 401 | A BufferedInputStream around a FileInputStream | Email 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 similarlyjava.util.logging, a record is handled by a logger's handlers and then propagates to its parent logger's handlers unlesspropagateis false. - Netty: a
ChannelPipelineof inbound and outbound handlers for network protocols.
In the interview
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 stepfrom dataclasses import dataclass
@dataclass
class Verdict:
kind: str # "accept", "reject" or "review"
reason: str = ""
def fraud_check(scorer):
def check(order, nxt):
score = scorer(order)
if score > 80:
return Verdict("reject", f"fraud score {score}")
if score >= 50:
return Verdict("review", f"fraud score {score}") # stop, but not a rejection
return nxt(order)
return check
# built in one place, per country, from configuration
checks = [format_check, stock_check]
if not config.skips_fraud(country):
checks.append(fraud_check(scorer))
checks.append(payment_auth(gateway)) # last: the expensive, side-effecting stepA 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.
- 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.
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.
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?
In a pipeline, a handler that stops the flow prevents every later handler from running. Register logging first (outermost) so it sees every request, including rejected ones.
2. What is the key difference between a Chain of Responsibility handler and a Decorator?
Decorators add behaviour and always call the wrapped object. A chain handler's defining freedom is to stop the flow, by handling the request or rejecting it.
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?
A request that falls off the end must be handled deliberately. Calling the director from the sender puts the policy back in the caller; raising the limit changes the business rule; retrying never helps.
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?
Browsers send a credential-less preflight for cross-origin requests with custom headers. If auth runs first it returns 401 and the browser blocks the real request; curl sends no preflight. Put CORS before auth.
5. A team wants a per-user rate limit of 100 requests a minute. Where should the limiter go in the middleware chain?
A per-user limit needs the identity that auth establishes. An IP-based limiter before auth is a separate, complementary control; counting after the endpoint lets every request through.
6. Which situation is the weakest case for a Chain of Responsibility?
A fixed lookup is clearer as a table and a loop. The chain pays off when handlers decide for themselves, can stop the flow, or the set and order change.
7. In Django, AuthenticationMiddleware is listed above SessionMiddleware in MIDDLEWARE. What happens?
Django runs the list top to bottom on the way in, and the auth middleware reads request.session to find the user. Django reports the misconfiguration and asks for SessionMiddleware to come first.
Score 60% or more and the lesson is marked complete.