These are the notes for Low-Level Design (LLD) episode 39, the sixth behavioural pattern (patterns about how objects share work and talk to each other). In a Chain of Responsibility, the sender hands a request to the first handler of a chain; each handler either handles it or passes it on to the next one. We start with a school leave application, watch an expense app crash on its biggest claim, and invent the pattern as the fix. Then we use the same idea for middleware pipelines, the way web servers use filters. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.
1. The real-life idea: a leave application
| At school | In code |
|---|---|
| The student hands the form to the class teacher, and only to her | The sender: knows only the first handler |
| Class teacher (1 day), principal (up to 7 days), management (longer) | Handlers: objects that may deal with the request |
| "Not mine, I'll pass it up": teacher → principal | The successor: the next handler in the chain |
| Whoever is allowed to, signs it | The request is handled; the passing stops |
The student never needed to know who would sign.
2. The problem: one method knows everyone
Expense limits at Asha's cafe company: team lead up to Rs 1,000, manager up to Rs 10,000, director up to Rs 1,00,000 (one lakh, which is a hundred thousand). Above that, nobody has been decided yet.
class ExpenseService {
String approver(int amount) { // knows EVERY approver and limit
if (amount <= 1000) return "Team lead";
if (amount <= 10000) return "Manager";
if (amount <= 100000) return "Director";
return null; // nobody... for now
}
}
public class Main {
public static void main(String[] args) {
ExpenseService s = new ExpenseService();
int[] claims = {500, 7500, 60000, 250000};
for (int amount : claims) {
System.out.println("Rs " + amount + " -> " + s.approver(amount).toUpperCase());
}
}
}
Rs 500 -> TEAM LEAD
Rs 7500 -> MANAGER
Rs 60000 -> DIRECTOR
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because the return value of "ExpenseService.approver(int)" is null
at Main.main(Main.java:14)
A NullPointerException (NPE) is thrown when code uses null as if it were an object: here, calling toUpperCase() on the null that approver() returned. Java's "helpful NPE" message even says which value was null.
Why it failed
- The sender goes through one method that knows every approver and limit.
- A new rule (a chief financial officer, a finance check before the manager) means editing that method again.
- "Nobody handled it" is a
nullthat crashes somewhere else, later. - Like the leave form: hand it to the first person; each one handles it or passes it on; the end of the line gives a clear answer.
3. The fix: a chain of handlers
abstract class Approver { // the handler
private Approver next; // the successor
Approver setNext(Approver next) { this.next = next; return next; }
void handle(int amount) {
if (canApprove(amount)) System.out.println("Rs " + amount + " approved by " + name());
else if (next != null) next.handle(amount); // pass it along
else System.out.println("Rs " + amount + " rejected: nobody can approve it");
}
abstract boolean canApprove(int amount);
abstract String name();
}
class TeamLead extends Approver { // concrete handlers
boolean canApprove(int a) { return a <= 1000; } String name() { return "Team lead"; }
}
class Manager extends Approver {
boolean canApprove(int a) { return a <= 10000; } String name() { return "Manager"; }
}
class Director extends Approver {
boolean canApprove(int a) { return a <= 100000; } String name() { return "Director"; }
}
public class Main {
public static void main(String[] args) {
Approver chain = new TeamLead();
chain.setNext(new Manager()).setNext(new Director()); // building the chain
for (int amount : new int[]{500, 7500, 60000, 250000}) chain.handle(amount);
}
}
Rs 500 approved by Team lead
Rs 7500 approved by Manager
Rs 60000 approved by Director
Rs 250000 rejected: nobody can approve it
Approveris the handler: an abstract class for anything that might deal with a claim. Its fieldnextis the successor.handle()is the heart: if I can, I handle it (and the request stops here); else if there is a next handler, I pass it along; else I'm last, so I reject it clearly. Nonull, no crash.TeamLead,Manager,Directorare concrete handlers. Each knows only its own limit, never who comes after it.- Building the chain:
setNext()stores the successor and returns it, so calls can be chained:lead.setNext(manager).setNext(director). This style, where each call returns an object to call the next method on, is a fluent interface (episode 25). - The sender (
Main) talks only to the first handler.
4. It has a name: Chain of Responsibility
+-------------------+ first handler +----------------------+
| Main |---------------->| Approver «handler» |----+ next (successor)
| «client · sender» | | - next: Approver |<---+
+-------------------+ | + setNext(a) |
| + handle(amount) |
+----------------------+
^ ^ ^
TeamLead Manager Director «concrete handlers»
request: TeamLead ──► Manager ──► Director ──► (end: reject)
The classic intent (SourceMaking): "Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request." and "Chain the receiving objects and pass the request along the chain until an object handles it." Coupling (episode 10) is how much one piece of code depends on another; here the sender depends on just one handler, not on all of them.
The chain is shaped like a linked list (from the DSA course): each handler points to the next one.
| Role | In our example | Job |
|---|---|---|
| Client / sender | Main |
Builds the chain, sends the request to the first handler |
| Handler | Approver |
Holds the successor; defines handle() |
| Concrete handler | TeamLead, Manager, Director |
Handles what it can, passes the rest on |
Adding a CFO is one new class and one more setNext (see the mini project). Main's other code and every other handler stay untouched.
5. The trap: a chain that loops
Chains are often built from configuration or by different people. One wrong link makes a circle:
abstract class Approver { // the handler
private Approver next; // the successor
Approver setNext(Approver next) { this.next = next; return next; }
void handle(int amount) {
if (canApprove(amount)) System.out.println("Rs " + amount + " approved by " + name());
else if (next != null) next.handle(amount); // pass it along
else System.out.println("Rs " + amount + " rejected: nobody can approve it");
}
abstract boolean canApprove(int amount);
abstract String name();
}
class TeamLead extends Approver { // concrete handlers
boolean canApprove(int a) { return a <= 1000; } String name() { return "Team lead"; }
}
class Manager extends Approver {
boolean canApprove(int a) { return a <= 10000; } String name() { return "Manager"; }
}
class Director extends Approver {
boolean canApprove(int a) { return a <= 100000; } String name() { return "Director"; }
}
public class Main {
public static void main(String[] args) {
Approver lead = new TeamLead(), manager = new Manager();
lead.setNext(manager);
manager.setNext(lead); // oops: back to the lead
lead.handle(250000);
}
}
Exception in thread "main" java.lang.StackOverflowError
at Approver.handle(Main.java:6)
at Approver.handle(Main.java:6)
... (the same lines repeat thousands of times)
Nobody can approve Rs 2,50,000, so the lead passes it to the manager, who passes it back to the lead, forever. Each pass is one more method call waiting on the call stack (the memory Java uses to remember unfinished method calls); when it runs out of room, Java throws StackOverflowError.
Fix: build the chain in one place, in one straight line, and make sure it ends: the last handler has no successor and gives the final answer. You can also check for a loop when the chain is built (practice 2).
5b. Order matters
The chain asks handlers one by one, so the order is part of the design. Built broadest-first:
abstract class Approver { // the handler
private Approver next; // the successor
Approver setNext(Approver next) { this.next = next; return next; }
void handle(int amount) {
if (canApprove(amount)) System.out.println("Rs " + amount + " approved by " + name());
else if (next != null) next.handle(amount); // pass it along
else System.out.println("Rs " + amount + " rejected: nobody can approve it");
}
abstract boolean canApprove(int amount);
abstract String name();
}
class TeamLead extends Approver { // concrete handlers
boolean canApprove(int a) { return a <= 1000; } String name() { return "Team lead"; }
}
class Manager extends Approver {
boolean canApprove(int a) { return a <= 10000; } String name() { return "Manager"; }
}
class Director extends Approver {
boolean canApprove(int a) { return a <= 100000; } String name() { return "Director"; }
}
public class Main {
public static void main(String[] args) {
Approver chain = new Director(); // broadest first!
chain.setNext(new Manager()).setNext(new TeamLead());
for (int amount : new int[]{500, 7500, 60000, 250000}) chain.handle(amount);
}
}
Rs 500 approved by Director
Rs 7500 approved by Director
Rs 60000 approved by Director
Rs 250000 rejected: nobody can approve it
No error, but the director approves even a Rs 500 chai bill, and the team lead and manager never see a claim. When handlers overlap, put the narrowest first and the broadest last, and build the chain in one place where everyone can see the order.
Chain vs Decorator (episode 28): decorators are linked too, but every decorator adds something and always passes the call on; a chain's handler may stop the request.
Testing: each handler can be tested alone: a Manager with no successor approves Rs 9,000 and rejects Rs 11,000.
6. Pass-through vs terminating handlers: middleware
Chains are also used so that every handler does a small job and then passes the request on. In web servers these handlers are called middleware: code that runs between a request arriving and the page being shown.
- A pass-through handler always continues (logging, timing, compression).
- A terminating handler may stop the request (login check, rate limit, input validation).
import java.util.*;
record Request(String user, String path) { }
interface Filter { void doFilter(Request r, Chain chain); } // a handler in a pipeline
class Chain {
private final List<Filter> filters; private final Runnable page; private int i = 0;
Chain(List<Filter> filters, Runnable page) { this.filters = filters; this.page = page; }
void next(Request r) { if (i < filters.size()) filters.get(i++).doFilter(r, this); else page.run(); }
}
class Logging implements Filter { // pass-through: always continues
public void doFilter(Request r, Chain c) {
System.out.println(" log: " + r.user() + " " + r.path()); c.next(r);
}
}
class Auth implements Filter { // may stop the request
public void doFilter(Request r, Chain c) {
if (r.user() != null) c.next(r); else System.out.println(" auth: 401, please log in");
}
}
public class Main {
public static void main(String[] args) {
List<Filter> filters = List.of(new Logging(), new Auth());
for (Request r : List.of(new Request("asha", "/orders"), new Request(null, "/orders"))) {
System.out.println(r.path() + " from " + r.user() + ":");
new Chain(filters, () -> System.out.println(" orders page shown")).next(r);
}
}
}
/orders from asha:
log: asha /orders
orders page shown
/orders from null:
log: null /orders
auth: 401, please log in
Requestis a record (episode 3): a small immutable data class withuser()andpath().Chain.next()calls the next filter, or, at the end, runs the page.Loggingis pass-through;Authstops a request with no user with 401 (the HTTP status code meaning "not authenticated: please log in").
Servlet filters. Java web servers work exactly like this. The Jakarta Servlet FilterChain javadoc: "Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain." A filter that doesn't call chain.doFilter(...) stops the request there.
7. When to use it (and when not)
| Use a chain for | Example |
|---|---|
| Approval workflows | Leave, expenses, refunds by amount or role |
| Middleware pipelines | Logging, login check, rate limits, compression |
| Support escalation | Bot → agent → supervisor |
| Handlers that change at runtime | Add or reorder handlers without touching the sender |
Risks: a request can fall off the end unhandled (always end with a clear default); long chains are harder to debug because the path isn't visible in one place; a loop crashes. Skip the chain when there's only one fixed receiver, or when a simple Map from key to handler is enough.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| One method knows every approver | java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because the return value of "ExpenseService.approver(int)" is null |
Nobody handled it: null |
A chain with a clear end |
| A chain that loops back | java.lang.StackOverflowError |
The request goes round in a circle | Build it in one straight line; detect loops |
| Handler neither handles nor forwards | No error: the request silently disappears | Forgot next.handle(...) / chain.next(...) |
Handle or call next, always |
| Wrong handler order | No error: the director approves a Rs 500 claim | Broad handler checked first | Order from narrow to broad |
| Sender builds and knows the whole chain everywhere | Coupling comes back | Chain built in many places | Build it once (a factory or config) |
Mini project: add a CFO
abstract class Approver { // the handler
private Approver next; // the successor
Approver setNext(Approver next) { this.next = next; return next; }
void handle(int amount) {
if (canApprove(amount)) System.out.println("Rs " + amount + " approved by " + name());
else if (next != null) next.handle(amount); // pass it along
else System.out.println("Rs " + amount + " rejected: nobody can approve it");
}
abstract boolean canApprove(int amount);
abstract String name();
}
class TeamLead extends Approver { // concrete handlers
boolean canApprove(int a) { return a <= 1000; } String name() { return "Team lead"; }
}
class Manager extends Approver {
boolean canApprove(int a) { return a <= 10000; } String name() { return "Manager"; }
}
class Director extends Approver {
boolean canApprove(int a) { return a <= 100000; } String name() { return "Director"; }
}
class Cfo extends Approver { // NEW: one class
boolean canApprove(int a) { return a <= 500000; } String name() { return "CFO"; }
}
public class Main {
public static void main(String[] args) {
Approver chain = new TeamLead();
chain.setNext(new Manager()).setNext(new Director()).setNext(new Cfo()); // one more link
for (int amount : new int[]{500, 7500, 60000, 250000, 900000}) chain.handle(amount);
}
}
Rs 500 approved by Team lead
Rs 7500 approved by Manager
Rs 60000 approved by Director
Rs 250000 approved by CFO
Rs 900000 rejected: nobody can approve it
One new class, one more setNext. Every existing handler is untouched (open-closed principle, episode 13).
Practice
1. Write a RateLimit filter that allows at most 3 requests per user, then answers 429.
Answer
import java.util.*;
record Request(String user, String path) { }
interface Filter { void doFilter(Request r, Chain chain); }
class Chain {
private final List<Filter> filters; private final Runnable page; private int i = 0;
Chain(List<Filter> filters, Runnable page) { this.filters = filters; this.page = page; }
void next(Request r) { if (i < filters.size()) filters.get(i++).doFilter(r, this); else page.run(); }
}
class RateLimit implements Filter { // terminating when over the limit
private final Map<String, Integer> count = new HashMap<>();
public void doFilter(Request r, Chain c) {
int n = count.merge(r.user(), 1, Integer::sum);
if (n > 3) System.out.println(" 429: too many requests from " + r.user());
else c.next(r);
}
}
public class Main {
public static void main(String[] args) {
List<Filter> filters = List.of(new RateLimit());
for (int i = 1; i <= 5; i++) {
System.out.print("request " + i + ":");
new Chain(filters, () -> System.out.println(" page shown")).next(new Request("asha", "/menu"));
}
}
}
request 1: page shown
request 2: page shown
request 3: page shown
request 4: 429: too many requests from asha
request 5: 429: too many requests from asha
Map.merge(key, 1, Integer::sum) adds 1 to the user's count (starting at 1). 429 is the HTTP status code for "too many requests". RateLimit is a terminating handler.
2. Make setNext refuse to create a loop.
Answer
abstract class Approver { // the handler
private Approver next; // the successor
Approver setNext(Approver next) {
for (Approver a = next; a != null; a = a.next) // walk the new tail
if (a == this) throw new IllegalArgumentException("loop: " + name() + " is already after " + next.name());
this.next = next; return next;
}
void handle(int amount) {
if (canApprove(amount)) System.out.println("Rs " + amount + " approved by " + name());
else if (next != null) next.handle(amount); // pass it along
else System.out.println("Rs " + amount + " rejected: nobody can approve it");
}
abstract boolean canApprove(int amount);
abstract String name();
}
class TeamLead extends Approver { // concrete handlers
boolean canApprove(int a) { return a <= 1000; } String name() { return "Team lead"; }
}
class Manager extends Approver {
boolean canApprove(int a) { return a <= 10000; } String name() { return "Manager"; }
}
class Director extends Approver {
boolean canApprove(int a) { return a <= 100000; } String name() { return "Director"; }
}
public class Main {
public static void main(String[] args) {
Approver lead = new TeamLead(), manager = new Manager();
lead.setNext(manager);
manager.setNext(lead); // caught when the chain is built
}
}
Exception in thread "main" java.lang.IllegalArgumentException: loop: Manager is already after Team lead
at Approver.setNext(Main.java:5)
at Main.main(Main.java:29)
Before linking, walk the chain that starts at the new successor; if we meet this, the link would make a circle. The bug is now caught when the chain is built, not when a big claim arrives.
3. Build a support chain: Bot answers "password" questions, Agent answers "refund" questions, Supervisor answers everything else. Which handler is terminating, and which order is right?
Answer
All three are terminating for the questions they answer; Supervisor is the default at the end. Order: Bot → Agent → Supervisor (narrow to broad). If Supervisor came first, it would answer every question and the others would never be used.
Quick quiz
Approver chain = new Manager();
chain.setNext(new TeamLead())
.setNext(new Director());
chain.handle(800);
Who approves it? (a) Team lead (b) Manager (c) Director (d) Rejected
Answer
(b) Manager. The manager is first and 800 ≤ 10,000, so he approves it and the chain stops. The team lead never sees it. Order matters.
Interview questions
- What is the Chain of Responsibility? A behavioural pattern that passes a request along a chain of handlers until one handles it, so the sender isn't coupled to the receiver.
- Participants? Client/sender, handler (with a successor), concrete handlers.
- What happens if no handler handles the request? It falls off the end; design a clear default (reject, log, or a catch-all handler).
- Terminating vs pass-through handlers? Terminating handlers may stop the request; pass-through handlers do their job and always continue (middleware).
- Where is it used in Java? Servlet
Filter/FilterChain, logging handler hierarchies, exception handling up the call stack (conceptually), security filter chains in web frameworks. - How do you build chains? Fluent
setNext()returning the successor, a list of handlers with an index (as inChain), or configuration. - Downsides? No guarantee of handling; harder debugging; order sensitivity; risk of loops.
- Chain vs Decorator? Both link objects. Decorators all add behaviour and always delegate; a chain's handlers may stop the request.
- Chain vs Command? Command turns a request into an object; Chain decides who handles a request. They combine well: a chain of handlers can receive command objects.
- How would you test a chain? Test each handler alone with a fake successor; then test the assembled chain with boundary values (1000, 1001, 10000, ...).
Glossary
| Term | Meaning, with an example |
|---|---|
| Behavioural pattern | A pattern about how objects share work and communicate |
| Chain of Responsibility | Pass a request along a chain of handlers until one handles it |
| Sender | The code that makes a request; knows only the first handler. Main |
| Handler | An object that may deal with a request. Approver |
| Concrete handler | One real handler with its own rule. Manager (≤ Rs 10,000) |
| Successor | The next handler in the chain. next |
| Passing a request along a chain | Calling next.handle(...) when you can't or don't want to handle it |
| Terminating handler | A handler that may stop the request. Auth, RateLimit |
| Pass-through handler | A handler that always continues. Logging |
| Building chains | Linking handlers in order. lead.setNext(manager).setNext(director) |
| Fluent interface | Methods that return an object so calls can be chained (episode 25) |
| Coupling | How much one piece of code depends on another (episode 10) |
| Middleware | Handlers that run between a request arriving and the response being produced |
| Middleware pipeline | A chain of middleware, each passing the request on |
| Servlet filter | Java web server middleware; calls FilterChain.doFilter to continue |
FilterChain |
The servlet object that invokes the next filter, or the resource at the end |
| Approval workflow | Routing a request to the person allowed to approve it |
NullPointerException |
Thrown when code uses null as an object |
| Call stack | The memory where Java remembers method calls that haven't finished |
StackOverflowError |
Thrown when the call stack runs out of room, e.g. endless passing in a loop |
| Record | A compact immutable data class. record Request(String user, String path) |
| HTTP 401 / 429 | Status codes: "not authenticated" / "too many requests" |
| Linked list | A chain of nodes, each pointing to the next |
| Lakh | Indian unit: 1,00,000 = one hundred thousand |
Summary
- One method that knows every approver breaks: a new limit means editing it, and "nobody" became a
nullthat crashed. - Chain of Responsibility: the sender hands the request to the first handler; each handler handles it or passes it to its successor; the end gives a clear default.
- Build chains in one straight line; a loop ends in
StackOverflowError. - Terminating handlers may stop a request; pass-through handlers always continue: that's middleware, and servlet filters work this way.
- Order handlers from narrow to broad.
Next episode: The Iterator pattern: one for-each loop for any collection, without knowing how it's stored.