November 24, 202614 minutes
Who signs a 3,000 expense? Learn how the Chain of Responsibility pattern lets a request find its own handler, with diagrams, Java code, servlet filters, and a narrated video.
You’ve just booked a flight to a conference in Lisbon. It cost 3,000, and now someone has to approve the expense. But who? Your team lead can sign anything up to 1,000, your manager up to 5,000, the director up to 25,000. You shouldn’t have to know any of that: you want to press Submit and have the request find the right person on its own. That’s exactly what the Chain of Responsibility pattern does, and its whole idea fits in five words: handle it, or hand it on.
Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.
One request, several possible receivers, each with different powers:
The person who submits the expense shouldn’t need a map of the org chart and everyone’s signing limits. The request should find its own handler.
You already know this pattern from calling customer support. You dial one number, and the front desk picks up. Your app crashes on login. The front desk can reset passwords, but not this, so they pass you on to a specialist. The specialist handles billing, but this is a real bug, so it goes one step further, to an engineer, who fixes it.
Notice what you did: you dialed one number, and you never chose who would answer. That gives us the pattern’s four words:
| Word | Meaning | In the support call |
|---|---|---|
| Request | the thing that travels along the chain | the ticket “app crashes on login” |
| Handler | deals with the request, or passes it on | front desk, specialist, engineer |
| Next (successor) | the handler a handler passes to | front desk → specialist → engineer |
| Sender (client) | sends the request; knows only the first handler | you, dialing one number |
Back to expenses. The obvious first version is one method in an expense service, with a ladder of
if and else: up to 1,000, call the team lead; up to 5,000, the manager; up to 25,000, the
director. Anything bigger throws an exception, because nobody can approve it.
class ExpenseService {
void approve(Expense e) {
if (e.amount() <= 1_000) {
teamLead.approve(e);
} else if (e.amount() <= 5_000) {
manager.approve(e);
} else if (e.amount() <= 25_000) {
director.approve(e);
} else {
throw new IllegalStateException("nobody can approve " + e);
}
}
}It’s short, it’s readable, and it works. For now. It’s the right first version, the way a receptionist’s cheat sheet of who handles what is fine on day one.
Then the rules start arriving. Finance wants a fraud check that runs before anyone signs. Trips under 2,000 should go to the travel desk. And when the manager is on vacation, the director signs instead. Each rule is another rung on the same ladder, in the same method:
void approve(Expense e) {
if (fraudCheck.looksSuspicious(e)) {
fraudTeam.review(e);
} else if (e.isTravel() && e.amount() <= 2_000) {
travelDesk.approve(e);
} else if (e.amount() <= 1_000) {
teamLead.approve(e);
} else if (e.amount() <= 5_000 && !manager.onVacation()) {
manager.approve(e);
} else if (e.amount() <= 25_000) {
director.approve(e);
} else {
throw new IllegalStateException("nobody can approve " + e);
}
}And the order of the rungs matters. Move the fraud check down one line, and suspicious trips get approved by the travel desk before anyone looks at them. Look at what the sender knows now: every approver, every limit, and the exact order to ask them in.
And when another department wants a different order? You copy the whole ladder, and now two copies drift apart. None of these rules can be tested on its own, either: to test the travel-desk rule you have to get past the fraud check first. (When one rule change means editing several copies like this, you’re looking at Shotgun Surgery; a method that keeps growing rungs is on its way to a Long Method.)
The problem isn’t the
ifstatements. The sender knows too much.
Here’s the key insight. Give every approver the same small job: look at the request, and handle it, or hand it on to the next one. Each handler knows only its own rule and one neighbor, and the sender knows only the first link in the chain.
Watch the flight travel. The team lead looks at 3,000: too big for me, so it goes on. The manager looks: that’s mine. Signed, and the request stops there.
And because the chain is built from the outside, you can change its shape. Put a fraud check at the front, and nobody else changes: not the sender, and not the other handlers.
Handle it, or hand it on.
We start with an abstract class, ExpenseHandler. It holds one field: the next handler in the
chain. A method called linkTo sets that field and returns the handler you just linked, so you
can chain the calls. Then the heart of the pattern, handle: if I can handle it, I process it.
Otherwise, if there is a next handler, I pass it on. And if there’s nobody left, fail loudly.
abstract class ExpenseHandler {
private ExpenseHandler next;
ExpenseHandler linkTo(ExpenseHandler next) {
this.next = next;
return next;
}
final void handle(Expense e) {
if (canHandle(e)) {
process(e);
} else if (next != null) {
next.handle(e);
} else {
throw new IllegalStateException("nobody can approve " + e);
}
}
abstract boolean canHandle(Expense e);
abstract void process(Expense e);
}handle is final, so no subclass can break the passing rule. Each handler only fills in two
small methods: canHandle (“is this mine?”) and process (“what do I do with it?”). A fixed
skeleton in the base class with steps the subclasses fill in is itself a pattern, the
Template Method.
The team lead can handle anything up to 1,000, the manager up to 5,000, the director up to 25,000. Each class is two lines, and knows nothing about the others:
class TeamLead extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 1_000; }
void process(Expense e) { /* the team lead signs */ }
}
class Manager extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 5_000; }
void process(Expense e) { /* the manager signs */ }
}
class Director extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 25_000; }
void process(Expense e) { /* the director signs */ }
}Now the client builds the chain: a team lead, linked to a manager, linked to a director. Then it sends the flight to the first link:
ExpenseHandler chain = new TeamLead();
chain.linkTo(new Manager())
.linkTo(new Director());
chain.handle(new Expense("flight to Lisbon", 3_000)); // the manager signsThe team lead says no, and passes it on. The manager says yes, and signs. The director never even sees it:
| Role | In this example | Responsibility |
|---|---|---|
| Handler | ExpenseHandler | holds next; the fixed “handle it, or hand it on” rule |
| Concrete handlers | TeamLead, Manager, Director | one rule each (canHandle) and the work (process) |
| Client | the code that wires and submits | builds the chain, sends to the first link |
| Request | Expense | the thing that travels |
A variant you’ll also see: an interface ExpenseHandler { void handle(Expense e); } where each
class stores its own next and decides itself when to forward. It’s more flexible (a handler can
do some work and forward), but every class must remember to forward; the abstract base class
makes forgetting impossible.
Now the new rules from before are easy. The fraud check becomes a handler, and goes first. The travel desk goes second. The existing handlers don’t change at all:
class FraudCheck extends ExpenseHandler {
boolean canHandle(Expense e) { return looksSuspicious(e); }
void process(Expense e) { /* send it to the fraud team, and stop */ }
}
class Cfo extends ExpenseHandler {
boolean canHandle(Expense e) { return true; } // catches everything that's left
void process(Expense e) { /* approve or reject, but always answer */ }
}ExpenseHandler chain = new FraudCheck();
chain.linkTo(new TravelDesk())
.linkTo(new TeamLead())
.linkTo(new Manager())
.linkTo(new Director())
.linkTo(new Cfo()); // the end of the chain always decidesThe order of the chain is now configuration. A different department can build a different
chain from the same pieces, and each rule can be unit-tested on its own:
new TravelDesk().canHandle(trip) needs no other handler.
Watch the end of the chain. Send 40,000 down the old chain (team lead, manager, director), and it runs past the director, and off the end. Our base class throws. But a careless version would simply do nothing, and the request would vanish without a trace. That’s the classic pitfall: the request nobody handles.
The fix is a last link that always answers. Here, the Cfo catches everything that’s left,
and either approves it or rejects it. But it always answers.
Another design choice: does the request stop at the first handler? In the classic pattern, it does: exactly one link handles it. In the pipeline variant, every link does a bit of work and then passes it on. That’s how web middleware works (logging, compression, authentication all run for the same request).
And one warning. You can’t see the path in the code any more: the order lives in the wiring, not
in an if ladder you can read top to bottom. So log each hop (a line like TeamLead: pass,
Manager: handled in the base class’s handle costs nothing), and keep your chains short.
You use this pattern every time a Java web app handles a request. Before the request reaches your servlet, it passes through a chain of filters. Here: a timing filter, then an auth filter, then the reports servlet. A request comes in from someone who isn’t logged in. The auth filter stops it right there and sends back an unauthorized error (401). The servlet never runs.
In code, each filter gets the request, and the filter chain. If the user isn’t logged in, it
sends the error and returns: that’s handling it. Otherwise, it calls doFilter on the chain:
that’s handing it on.
class AuthFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
if (!isLoggedIn(req)) {
((HttpServletResponse) res).sendError(401); // handled: the chain stops here
return;
}
chain.doFilter(req, res); // not mine: hand it on
}
}A filter can even work on both sides. The timing filter notes the start time, lets the rest of the chain run, and then logs how long it took:
class TimingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
long start = System.nanoTime();
chain.doFilter(req, res); // the rest of the chain runs here
log.info("took " + (System.nanoTime() - start) + " ns");
}
}And the servlet never knows that the filters exist. They’re listed in configuration (web.xml,
@WebFilter, or your framework’s registration), and you can add or reorder them without touching
it. Spring Security works the same way: its SecurityFilterChain is a list of filters, and the
middleware of most web frameworks (and the handler pipelines of HTTP clients) follow the same
shape. Note that filters are the pipeline variant: most of them do a little work and hand the
request on, and only some, like the auth filter, stop it.
Other places you’ll find a chain: GUI event bubbling (a click goes to the button, then its panel,
then the window, until someone handles it), java.util.logging handlers passing records to their
parent loggers, and exception handling itself (the call stack is searched, frame by frame, for a
catch that can handle the exception).
Chain of Responsibility is often confused with the Decorator pattern. Both wrap another object and forward calls to it, so in code they can look alike. Here are Java’s input streams: a buffered stream, around a zip stream, around a file stream.
InputStream in = new BufferedInputStream(
new GZIPInputStream(
new FileInputStream("report.gz")));Every read() goes all the way through. Each layer adds something (buffering, unzipping), but it
always forwards. In a chain, any link can stop the request. Usually exactly one of them
handles it, and the rest never see it.
| Decorator | Chain of Responsibility | |
|---|---|---|
| Does every layer forward? | always | only if it doesn’t handle it |
| Does the core object run? | always | maybe nobody handles it |
| Purpose | add behavior around an object | find the object that handles a request |
| Typical count of “doers” | all of them | usually exactly one |
Middleware sits in between: most filters forward like decorators, but some stop the request like a chain.
And the Command pattern? That’s a different question. Command turns a request into an object. Chain of Responsibility decides who handles it. They work well together: a command object can travel down a chain, and the first handler that knows how to run it does.
A decorator always passes it on. A chain decides who stops it.
Use it when:
Skip it when:
Map,And watch out for long chains: they’re hard to debug, and every request pays for every hop.
An if/else ladder makes the sender know every receiver. Instead, give every handler one job,
and one neighbor. Build the chain from outside, and make sure its end always answers.
Handle it, or hand it on.
For reference, the whole expense chain, written out so it compiles:
record Expense(String description, int amount, boolean isTravel) {
Expense(String description, int amount) { this(description, amount, false); }
}
abstract class ExpenseHandler {
private ExpenseHandler next;
ExpenseHandler linkTo(ExpenseHandler next) {
this.next = next;
return next;
}
final void handle(Expense e) {
if (canHandle(e)) {
System.out.println(getClass().getSimpleName() + ": handled " + e.description());
process(e);
} else if (next != null) {
System.out.println(getClass().getSimpleName() + ": pass");
next.handle(e);
} else {
throw new IllegalStateException("nobody can approve " + e);
}
}
abstract boolean canHandle(Expense e);
abstract void process(Expense e);
}
class FraudCheck extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() % 1_000 == 999; } // a toy rule
void process(Expense e) { System.out.println(" sent to the fraud team"); }
}
class TravelDesk extends ExpenseHandler {
boolean canHandle(Expense e) { return e.isTravel() && e.amount() <= 2_000; }
void process(Expense e) { System.out.println(" booked through the travel desk"); }
}
class TeamLead extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 1_000; }
void process(Expense e) { System.out.println(" signed by the team lead"); }
}
class Manager extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 5_000; }
void process(Expense e) { System.out.println(" signed by the manager"); }
}
class Director extends ExpenseHandler {
boolean canHandle(Expense e) { return e.amount() <= 25_000; }
void process(Expense e) { System.out.println(" signed by the director"); }
}
class Cfo extends ExpenseHandler {
boolean canHandle(Expense e) { return true; }
void process(Expense e) { System.out.println(" decided by the CFO"); }
}
public class Expenses {
public static void main(String[] args) {
ExpenseHandler chain = new FraudCheck();
chain.linkTo(new TravelDesk())
.linkTo(new TeamLead())
.linkTo(new Manager())
.linkTo(new Director())
.linkTo(new Cfo());
chain.handle(new Expense("flight to Lisbon", 3_000, true)); // Manager
chain.handle(new Expense("new office", 40_000)); // Cfo
}
}