Chain of Responsibility: request filters
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Before ShopLite accepts an order it must check stock, the cash-on-delivery limit, fraud risk and the pincode. Four checks in one method are hard to reorder, switch off or test. How can each check be its own piece?
The problem: one method with every order check
Chain of Responsibility is a design pattern where a request travels along a line of handler objects. Each handler either deals with the request or passes it to the next one, and the sender does not know which handler will act.
The problem first: all four ShopLite order checks sit in one validate method.
Example 1 · Before: every check in one validate method
import java.util.List;import java.util.Map;
record Order(String id, String sku, int qty, int amount, String payment, String pincode, int accountAgeDays) {}
class OrderValidator { private final Map<String, Integer> stock = Map.of("EAR-01", 3, "PEN-02", 50);
String validate(Order o) { int left = stock.getOrDefault(o.sku(), 0); if (o.qty() > left) { return "only " + left + " left"; } else if (o.payment().equals("COD") && o.amount() > 5000) { return "COD only up to Rs 5000"; } else if (o.accountAgeDays() < 2 && o.amount() > 10000) { return "new account, big order"; } else if (!o.pincode().matches("[1-9][0-9]{5}")) { return "bad pincode " + o.pincode(); } return "OK"; }}
public class OneMethodDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("A1", "EAR-01", 1, 1499, "UPI", "411001", 300), new Order("A2", "EAR-01", 5, 7495, "UPI", "411001", 300), new Order("A3", "PEN-02", 40, 6000, "COD", "560001", 90), new Order("A4", "PEN-02", 10, 12000, "CARD", "110001", 1), new Order("A5", "PEN-02", 1, 150, "UPI", "41100", 45)); OrderValidator validator = new OrderValidator(); for (Order o : orders) { System.out.println(o.id() + ": " + validator.validate(o)); } }}A1: OK A2: only 3 left A3: COD only up to Rs 5000 A4: new account, big order A5: bad pincode 41100
What this code does
- All four rules sit in one
if-elsechain. Reordering them, skipping one or adding a fifth means editing this method. [1-9][0-9]{5}is a regular expression for an Indian pincode: six digits, not starting with 0. A5's41100has only five.
Changing the order of the checks, switching one off for a festival sale, or adding a blacklist check all mean editing the same method. It also becomes hard to test one rule without the others.
Handler interface with a next handler
Handler is a small class with one method, here check(order), and a link to the next handler. It looks at the request and either answers it (for example, rejects the order) or calls the next handler.
Each check becomes a handler linked to the next one. The checkout code calls only the first handler.
Example 2 · Four handlers linked with next
import java.util.List;import java.util.Map;
record Order(String id, String sku, int qty, int amount, String payment, String pincode, int accountAgeDays) {}abstract class OrderCheck { // handler private OrderCheck next;
OrderCheck linkWith(OrderCheck next) { // returns next, so links can be chained this.next = next; return next; }
abstract String check(Order o);
protected String passToNext(Order o) { return next == null ? "OK" : next.check(o); }}
class StockCheck extends OrderCheck { private final Map<String, Integer> stock = Map.of("EAR-01", 3, "PEN-02", 50);
String check(Order o) { int left = stock.getOrDefault(o.sku(), 0); if (o.qty() > left) return "stock check: only " + left + " left"; return passToNext(o); }}
class LimitCheck extends OrderCheck { String check(Order o) { if (o.payment().equals("COD") && o.amount() > 5000) return "limit check: COD only up to Rs 5000"; return passToNext(o); }}
class FraudCheck extends OrderCheck { int apiCalls;
String check(Order o) { apiCalls++; // pretend this calls a slow fraud API if (o.accountAgeDays() < 2 && o.amount() > 10000) return "fraud check: new account, big order"; return passToNext(o); }}
class AddressCheck extends OrderCheck { String check(Order o) { if (!o.pincode().matches("[1-9][0-9]{5}")) return "address check: bad pincode " + o.pincode(); return passToNext(o); }}
public class ChainDemo { public static void main(String[] args) { StockCheck first = new StockCheck(); first.linkWith(new LimitCheck()).linkWith(new FraudCheck()).linkWith(new AddressCheck()); List<Order> orders = List.of( new Order("A1", "EAR-01", 1, 1499, "UPI", "411001", 300), new Order("A2", "EAR-01", 5, 7495, "UPI", "411001", 300), new Order("A3", "PEN-02", 40, 6000, "COD", "560001", 90), new Order("A4", "PEN-02", 10, 12000, "CARD", "110001", 1), new Order("A5", "PEN-02", 1, 150, "UPI", "41100", 45)); for (Order o : orders) { System.out.println(o.id() + ": " + first.check(o)); } }}A1: OK A2: stock check: only 3 left A3: limit check: COD only up to Rs 5000 A4: fraud check: new account, big order A5: address check: bad pincode 41100
What this code does
- Each handler checks one rule and either returns a rejection or calls
passToNext. Checkout talks only tofirst. - A2 stops at the stock check, so the limit, fraud and address handlers never see it. A5 passes three checks and is stopped by the last one.
The handlers are linked once, at start-up: stock, limit, fraud, address. The checkout code does not know how many checks there are or which one will speak.
The last handler's next is null, which ends the chain. Each concrete handler (StockCheck, FraudCheck) holds one rule.
Find the bug
Spot the chain bug
Each snippet has one wrong line. Tap it, then read the fix.
A valid order must reach the next check.
Round 1 of 2OK itself instead of calling the next one. The checks after it silently never run.Stop-on-failure vs pass-through chains
Stop-on-failure is a chain in which the first handler that answers ends the request's trip. Order validation works this way: once stock fails, the slow fraud check is never called.
A chain can stop at the first answer or let every handler act. Below, a refund goes to the first approver whose limit is high enough, and an address form collects every error.
Example 3 · Stop-on-failure: a refund approval chain
abstract class Approver { private final String name; private final int limit; private Approver next;
Approver(String name, int limit) { this.name = name; this.limit = limit; }
Approver then(Approver next) { this.next = next; return next; }
String approve(int amount) { if (amount <= limit) { return name + " approved Rs " + amount; // handled: the chain stops here } if (next == null) { return "Rs " + amount + ": nobody can approve, send to finance"; } return next.approve(amount); }}
class Bot extends Approver { Bot() { super("Refund bot", 500); } }class Agent extends Approver { Agent() { super("Support agent", 5000); } }class Manager extends Approver { Manager() { super("Store manager", 50000); } }
public class RefundChainDemo { public static void main(String[] args) { Approver chain = new Bot(); chain.then(new Agent()).then(new Manager());
for (int amount : new int[] {299, 1499, 24999, 80000}) { System.out.println(chain.approve(amount)); } }}Refund bot approved Rs 299 Support agent approved Rs 1499 Store manager approved Rs 24999 Rs 80000: nobody can approve, send to finance
What this code does
- Each approver handles the request if the amount is within its limit; otherwise it hands it up the line. The first approver that can say yes ends the chain.
- Rs 80,000 is above every limit, so it falls off the end. A chain should always say what happens then, here a message for finance.
Example 4 · Pass-through: collect every address error at once
import java.util.ArrayList;import java.util.List;
record Address(String name, String phone, String pincode, String city) {}
abstract class AddressRule { private AddressRule next;
AddressRule then(AddressRule next) { this.next = next; return next; }
void check(Address a, List<String> errors) { String problem = problem(a); if (problem != null) { errors.add(problem); // note it, but keep going } if (next != null) { next.check(a, errors); } }
abstract String problem(Address a);}
class NameRule extends AddressRule { String problem(Address a) { return a.name().isBlank() ? "name is empty" : null; }}
class PhoneRule extends AddressRule { String problem(Address a) { return a.phone().matches("[6-9][0-9]{9}") ? null : "phone must be 10 digits"; }}
class PincodeRule extends AddressRule { String problem(Address a) { return a.pincode().matches("[1-9][0-9]{5}") ? null : "pincode must be 6 digits"; }}
public class CollectErrorsDemo { public static void main(String[] args) { AddressRule rules = new NameRule(); rules.then(new PhoneRule()).then(new PincodeRule());
Address good = new Address("Riya", "9811100001", "411001", "Pune"); Address bad = new Address(" ", "98111", "41100", "Pune"); for (Address a : List.of(good, bad)) { List<String> errors = new ArrayList<>(); rules.check(a, errors); System.out.println(errors.isEmpty() ? "Address OK" : "Fix: " + errors); } }}Address OK Fix: [name is empty, phone must be 10 digits, pincode must be 6 digits]
What this code does
- Here every rule always passes the address on, and each one adds its own error to a shared list. The shopper sees all three problems at once instead of fixing them one by one.
- The structure is the same as the stop-on-failure chain; only the rule "answer or pass on" changed to "note and pass on".
Pass-through is the other kind: every handler runs and may add something before passing the request on. A form that should show all its errors at once collects them as the request passes every handler.
Decide which kind you need before you write the handlers.
Predict the output
Predict the approver
Read the code, then pick what it prints.
Three refund amounts go through the same chain.
Building the chain from a list, in order
Linking by hand gets fiddly. Put the handlers in a List in the order you want and link each one to the next in a loop.
Example 5 · Building the chain from a list, cheap checks first
import java.util.List;import java.util.Map;
record Order(String id, String sku, int qty, int amount, String payment, String pincode, int accountAgeDays) {}abstract class OrderCheck { // handler private OrderCheck next;
OrderCheck linkWith(OrderCheck next) { // returns next, so links can be chained this.next = next; return next; }
abstract String check(Order o);
protected String passToNext(Order o) { return next == null ? "OK" : next.check(o); }}
class StockCheck extends OrderCheck { private final Map<String, Integer> stock = Map.of("EAR-01", 3, "PEN-02", 50);
String check(Order o) { int left = stock.getOrDefault(o.sku(), 0); if (o.qty() > left) return "stock check: only " + left + " left"; return passToNext(o); }}
class LimitCheck extends OrderCheck { String check(Order o) { if (o.payment().equals("COD") && o.amount() > 5000) return "limit check: COD only up to Rs 5000"; return passToNext(o); }}
class FraudCheck extends OrderCheck { int apiCalls;
String check(Order o) { apiCalls++; // pretend this calls a slow fraud API if (o.accountAgeDays() < 2 && o.amount() > 10000) return "fraud check: new account, big order"; return passToNext(o); }}
class AddressCheck extends OrderCheck { String check(Order o) { if (!o.pincode().matches("[1-9][0-9]{5}")) return "address check: bad pincode " + o.pincode(); return passToNext(o); }}
public class ListChainDemo { static OrderCheck link(List<OrderCheck> checks) { for (int i = 0; i < checks.size() - 1; i++) { checks.get(i).linkWith(checks.get(i + 1)); } return checks.get(0); }
static int run(List<OrderCheck> checks, FraudCheck fraud, List<Order> orders) { OrderCheck first = link(checks); for (Order o : orders) { first.check(o); } return fraud.apiCalls; }
public static void main(String[] args) { List<Order> orders = List.of( new Order("A1", "EAR-01", 1, 1499, "UPI", "411001", 300), new Order("A2", "EAR-01", 5, 7495, "UPI", "411001", 300), new Order("A3", "PEN-02", 40, 6000, "COD", "560001", 90), new Order("A4", "PEN-02", 10, 12000, "CARD", "110001", 1), new Order("A5", "PEN-02", 1, 150, "UPI", "41100", 45)); FraudCheck f1 = new FraudCheck(); int fraudFirst = run(List.of(f1, new StockCheck(), new LimitCheck(), new AddressCheck()), f1, orders); FraudCheck f2 = new FraudCheck(); int fraudLast = run(List.of(new AddressCheck(), new StockCheck(), new LimitCheck(), f2), f2, orders);
System.out.println("Fraud API calls with fraud first: " + fraudFirst); System.out.println("Fraud API calls with fraud last: " + fraudLast); }}Fraud API calls with fraud first: 5 Fraud API calls with fraud last: 2
What this code does
linkconnects each handler to the one after it, so the chain's order is simply the list's order. Reordering is a one-line change.- With the slow fraud check last, orders already rejected for stock, limit or pincode never reach it: 2 API calls instead of 5 for the same results.
Changing the order, or reading it from configuration, is now a change to the list only. Order matters: put cheap checks that often fail first (pincode format, stock) and expensive ones last (a fraud API call).
The result is the same for a valid order, but bad orders are rejected sooner and the costly service is called less often.
Order of execution
Build the chain
Put the steps in the order you would do them.
Where chains appear: servlet filters and logging handlers
FilterChain.doFilter is the call a servlet filter makes to pass the request to the next filter and finally to the controller. A filter that does not call it stops the request there.
Every request to a Spring Boot application passes a chain of servlet filters before it reaches a controller. Below, one filter times the request.
@Componentpublic class RequestTimingFilter implements Filter { // jakarta.servlet.Filter @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long start = System.nanoTime(); chain.doFilter(request, response); // next filter, then the controller long ms = (System.nanoTime() - start) / 1_000_000; System.out.println(((HttpServletRequest) request).getRequestURI() + " took " + ms + " ms"); }}Example 6 · A mini servlet-style filter chain
import java.util.List;import java.util.function.Consumer;
interface Filter { void doFilter(String request, FilterChain chain);}
class FilterChain { private final List<Filter> filters; private final Consumer<String> controller; private int position = 0;
FilterChain(List<Filter> filters, Consumer<String> controller) { this.filters = filters; this.controller = controller; }
void doFilter(String request) { if (position < filters.size()) { filters.get(position++).doFilter(request, this); // next filter } else { controller.accept(request); // end of the chain } }}
class LoggingFilter implements Filter { public void doFilter(String request, FilterChain chain) { System.out.println("-> " + request); chain.doFilter(request); System.out.println("<- " + request); }}
class AuthFilter implements Filter { public void doFilter(String request, FilterChain chain) { if (!request.contains("token=")) { System.out.println(" 401 Unauthorized"); // stop: do not call the chain return; } chain.doFilter(request); }}
public class FilterChainDemo { public static void main(String[] args) { List<Filter> filters = List.of(new LoggingFilter(), new AuthFilter()); Consumer<String> controller = r -> System.out.println(" controller: orders listed");
new FilterChain(filters, controller).doFilter("GET /api/v1/me/orders?token=abc"); new FilterChain(filters, controller).doFilter("GET /api/v1/me/orders"); }}-> GET /api/v1/me/orders?token=abc controller: orders listed <- GET /api/v1/me/orders?token=abc -> GET /api/v1/me/orders 401 Unauthorized <- GET /api/v1/me/orders
What this code does
- Each filter decides by calling or not calling
chain.doFilter. The auth filter stops the second request, but the logging filter still prints its<-line because the call returns back through it. - This is how servlet filters and Spring Security work: code before
doFilterruns on the way in, code after it on the way out. Each request gets its own chain object, because the chain remembers its position.
A filter stops a request by returning without calling chain.doFilter, for example after writing a 401 error. Spring Security is itself a chain of such filters.
java.util.logging uses a chain too: a logger hands each log record to its own handlers and then to its parent logger's handlers, up to the root.
Next step
Check your understanding
12 quick questions