Chain of Responsibility Design Pattern in Java
The chain of responsibility design pattern in Java passes a request along a line of handler objects until one of them deals with it, or until every handler has had its turn. Each handler knows only its own rule and the next handler, so the sender does not need to know which object will finally process the request.
It matters because approval rules, validations and request filters tend to grow into one long if-else method that every team edits. A chain splits that method into small, reorderable steps. It is a behavioral design pattern, and you meet it daily in Java web development: servlet filters and Spring Security's filter chain work this way.
1. What Is the Chain of Responsibility Design Pattern?
The GoF intent is: "Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it."
Each handler implements the same interface and holds a reference to the next handler. When a request arrives, the handler decides: handle it and stop, or pass it on. The client only talks to the first handler.
In practice, Java code uses two flavours:
- Find a handler: the first handler that can deal with the request handles it, and the rest never see it. Refund approval by amount works like this.
- Pipeline: every handler processes the request in turn, and any one of them may stop it. Validations and web filters work like this.
Both apply the Single Responsibility Principle (one rule per handler) and the Open/Closed Principle (new rules are new handlers inserted into the chain, not edits to existing code).
2. Key Components
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Handler | Declares the handling method and holds the link to the next handler | RefundApprover |
| Concrete Handlers | Decide whether to handle the request or forward it | AutoApproval, SupportAgent, TeamLead, FinanceManager |
| Client | Builds the chain once and sends requests to its head | main |
The client sends the request to the first handler. Each handler checks its own condition and either returns a result or calls the next handler. The client receives the result without knowing which handler produced it.
3. When Is the Pattern Useful?
- Approval levels: refunds approved by the lowest role whose limit covers the amount.
- Validation pipelines: a payment checked for amount, currency, country and card velocity, stopping at the first failure.
- Request processing: an API gateway that adds a correlation ID, authenticates and rate-limits before reaching the endpoint.
4. UML Class Diagram
The diagram shows the Basic Example.
RefundApproveris the handler. The arrow that loops back to it is thenextfield: each approver may point to zero or one further approver.handle()holds the shared "approve or forward" logic;canApprove()is abstract (italic), so each subclass supplies its own rule.- The four concrete approvers extend the handler (solid lines, hollow triangle).
- The client depends only on the abstract handler, so it never knows how many approvers exist.
5. Step-by-Step Execution Flow
- The client creates the four approvers and links them: auto-approval, support agent, team lead, finance manager.
- It calls
chain.handle(refund)with a refund of Rs. 18,000. AutoApprovalcannot approve more than 500, sohandle()callsnext.handle(refund).SupportAgentcannot approve more than 5,000 and forwards it again.TeamLeadcan approve up to 50,000, so it returns "approved by team lead". The finance manager is never called.- The result travels back through the call stack to the client. If no handler accepts, the last one reports that the refund was escalated.
6. Real-World Use Cases
- E-commerce: refund, return and price-override approvals by role; discount rules applied in order.
- Payments and banking: transaction validation and fraud screening pipelines, and loan approvals by amount.
- Notifications and support: routing a ticket to the bot, then tier 1, then tier 2 support.
- Java EE / Jakarta Servlet: each
Filterreceives aFilterChainand callschain.doFilter()to pass the request on, or stops by not calling it. - Spring: Spring Security runs requests through a
SecurityFilterChain, Spring MVC'sHandlerInterceptor.preHandle()stops processing by returningfalse, and Spring Cloud Gateway applies a chain of gateway filters to every route.
7. Problem Without the Pattern
All refund rules in one method:
public class RefundsWithoutChain {
record Refund(String orderId, int amountInRupees, boolean flaggedByFraudModel) { }
// Every rule lives in one method, in one fixed order
static String approve(Refund refund) {
if (refund.flaggedByFraudModel()) {
return refund.orderId() + ": held for fraud review";
}
if (refund.amountInRupees() <= 500) {
return refund.orderId() + ": auto-approved";
} else if (refund.amountInRupees() <= 5_000) {
return refund.orderId() + ": approved by support agent";
} else if (refund.amountInRupees() <= 50_000) {
return refund.orderId() + ": approved by team lead";
} else if (refund.amountInRupees() <= 200_000) {
return refund.orderId() + ": approved by finance manager";
}
return refund.orderId() + ": no one can approve this";
}
public static void main(String[] args) {
System.out.println(approve(new Refund("ORD-1", 349, false)));
System.out.println(approve(new Refund("ORD-2", 18_000, false)));
System.out.println(approve(new Refund("ORD-3", 900, true)));
}
}
ORD-1: auto-approved
ORD-2: approved by team lead
ORD-3: held for fraud review
- One method, many owners: risk, support and finance all edit the same
if-elseladder. - Hard-coded order: moving the fraud check or adding a "VIP customer" rule means rewriting the method.
- No reuse: the same limits cannot be shared by the returns flow without copying.
- Hard to test: each rule can only be tested through the whole method.
8. Solution Using the Pattern
Turn each rule into a handler with one decision, and link them in the order you want. The client sends every refund to the first handler.
Each team owns its handler. Adding a fraud check or a VIP rule means writing one class and inserting it in the chain where it belongs; other handlers do not change. Each handler can be unit-tested alone, and the same handlers can be assembled into different chains for refunds and returns.
9. Chain of Responsibility Design Pattern in Java: Code Examples
Each example is a single file that runs on Java 21 with java FileName.java.
Basic Example: Refund Approval Levels
Problem: route each refund to the lowest role allowed to approve it, and report refunds no one can approve.
public class RefundApprovalChainDemo {
record Refund(String orderId, int amountInRupees) { }
// Handler: knows its own limit and the next handler, nothing else
abstract static class RefundApprover {
private RefundApprover next;
RefundApprover linkWith(RefundApprover next) { // returns next, so links can be chained fluently
this.next = next;
return next;
}
final String handle(Refund refund) {
if (canApprove(refund)) {
return refund.orderId() + " (Rs. " + refund.amountInRupees() + "): approved by " + name();
}
if (next == null) {
return refund.orderId() + " (Rs. " + refund.amountInRupees() + "): escalated, no approver in the chain";
}
return next.handle(refund); // pass it along
}
protected abstract boolean canApprove(Refund refund);
protected abstract String name();
}
// Concrete handlers
static final class AutoApproval extends RefundApprover {
protected boolean canApprove(Refund r) { return r.amountInRupees() <= 500; }
protected String name() { return "auto-approval"; }
}
static final class SupportAgent extends RefundApprover {
protected boolean canApprove(Refund r) { return r.amountInRupees() <= 5_000; }
protected String name() { return "support agent"; }
}
static final class TeamLead extends RefundApprover {
protected boolean canApprove(Refund r) { return r.amountInRupees() <= 50_000; }
protected String name() { return "team lead"; }
}
static final class FinanceManager extends RefundApprover {
protected boolean canApprove(Refund r) { return r.amountInRupees() <= 200_000; }
protected String name() { return "finance manager"; }
}
public static void main(String[] args) {
RefundApprover chain = new AutoApproval();
chain.linkWith(new SupportAgent())
.linkWith(new TeamLead())
.linkWith(new FinanceManager());
for (int amount : new int[] {349, 2_400, 18_000, 120_000, 750_000}) {
System.out.println(chain.handle(new Refund("ORD-" + amount, amount)));
}
}
}
Important classes and methods
handle()isfinal: the forwarding logic is written once in the base class, and subclasses supply onlycanApprove()andname().linkWith()returns the handler it was given, so links read left to right.- The end of the chain is handled explicitly instead of returning
null.
Expected output
ORD-349 (Rs. 349): approved by auto-approval
ORD-2400 (Rs. 2400): approved by support agent
ORD-18000 (Rs. 18000): approved by team lead
ORD-120000 (Rs. 120000): approved by finance manager
ORD-750000 (Rs. 750000): escalated, no approver in the chain
How it runs
- Each amount starts at auto-approval and moves along until a limit covers it.
- Rs. 750,000 passes every handler; the last one has no successor, so it reports an escalation.
Practical Example: Payment Validation Pipeline
Problem: every payment must pass several independent checks, the first failure must stop processing with a clear reason, and the order of checks must be easy to change.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class PaymentValidationChainDemo {
record Payment(String id, String cardId, long amountInRupees, String currency, String country) { }
// Handler: returns a rejection reason, or empty to let the payment continue
@FunctionalInterface
interface PaymentCheck {
Optional<String> check(Payment payment);
}
// Concrete handlers
static PaymentCheck amountLimit(long max) {
return p -> p.amountInRupees() <= 0 || p.amountInRupees() > max
? Optional.of("amount " + p.amountInRupees() + " outside 1.." + max) : Optional.empty();
}
static PaymentCheck supportedCurrency(Set<String> currencies) {
return p -> currencies.contains(p.currency()) ? Optional.empty() : Optional.of("currency " + p.currency() + " not supported");
}
static PaymentCheck blockedCountry(Set<String> blocked) {
return p -> blocked.contains(p.country()) ? Optional.of("country " + p.country() + " is blocked") : Optional.empty();
}
// Stateful handler: shared by all requests, so its counters are thread-safe
static final class VelocityCheck implements PaymentCheck {
private final int maxPerCard;
private final Map<String, AtomicInteger> attempts = new ConcurrentHashMap<>();
VelocityCheck(int maxPerCard) { this.maxPerCard = maxPerCard; }
public Optional<String> check(Payment p) {
int count = attempts.computeIfAbsent(p.cardId(), k -> new AtomicInteger()).incrementAndGet();
return count > maxPerCard ? Optional.of("card " + p.cardId() + " used " + count + " times") : Optional.empty();
}
}
// The chain: runs checks in order and stops at the first rejection
static final class ValidationChain {
private final List<PaymentCheck> checks;
private ValidationChain(List<PaymentCheck> checks) { this.checks = List.copyOf(checks); }
static Builder builder() { return new Builder(); }
String validate(Payment payment) {
for (PaymentCheck check : checks) {
Optional<String> rejection = check.check(payment);
if (rejection.isPresent()) {
return payment.id() + " REJECTED: " + rejection.get();
}
}
return payment.id() + " ACCEPTED";
}
static final class Builder {
private final List<PaymentCheck> checks = new ArrayList<>();
Builder then(PaymentCheck check) { checks.add(check); return this; }
ValidationChain build() { return new ValidationChain(checks); }
}
}
public static void main(String[] args) {
ValidationChain chain = ValidationChain.builder()
.then(amountLimit(200_000)) // cheap checks first
.then(supportedCurrency(Set.of("INR", "USD")))
.then(blockedCountry(Set.of("XX")))
.then(new VelocityCheck(2)) // stateful check last
.build();
List<Payment> payments = List.of(
new Payment("P-1", "card-9", 2_499, "INR", "IN"),
new Payment("P-2", "card-9", 350_000, "INR", "IN"),
new Payment("P-3", "card-4", 120, "JPY", "IN"),
new Payment("P-4", "card-7", 999, "USD", "XX"),
new Payment("P-5", "card-9", 640, "INR", "IN"),
new Payment("P-6", "card-9", 210, "INR", "IN"));
payments.forEach(p -> System.out.println(chain.validate(p)));
}
}
Important classes and methods
PaymentCheckis a functional interface, so simple handlers are lambdas from small factory methods.ValidationChainkeeps handlers in an immutable list and loops over them. A loop instead of recursion means no stack growth for long chains.VelocityCheckis stateful and shared, so it usesConcurrentHashMapandAtomicInteger.
Expected output
P-1 ACCEPTED
P-2 REJECTED: amount 350000 outside 1..200000
P-3 REJECTED: currency JPY not supported
P-4 REJECTED: country XX is blocked
P-5 ACCEPTED
P-6 REJECTED: card card-9 used 3 times
How it runs
- P-2, P-3 and P-4 each stop at the first check they fail; later checks never run.
- Because P-2 stopped early, it did not count towards the card's velocity.
- card-9 reaches the velocity check three times (P-1, P-5, P-6), so the third attempt is rejected.
Real-World Enterprise Example: API Gateway Filter Chain
Problem: every API call needs a correlation ID, authentication and rate limiting before it reaches the endpoint, and logging must happen after the response is known, even when a filter rejects the call.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class ApiFilterChainDemo {
// A tiny request/response model
record Request(String path, Map<String, String> headers) { }
static final class Response {
int status = 200;
String body = "";
final Map<String, String> headers = new HashMap<>();
}
// Handler interface: a filter can act before and after the rest of the chain
interface Filter {
void doFilter(Request request, Response response, Chain chain);
}
// Per-request cursor over an immutable list of filters
static final class Chain {
private final List<Filter> filters;
private final Endpoint endpoint;
private int position = 0;
Chain(List<Filter> filters, Endpoint endpoint) { this.filters = filters; this.endpoint = endpoint; }
void proceed(Request request, Response response) {
if (position < filters.size()) {
filters.get(position++).doFilter(request, response, this); // next filter
} else {
endpoint.handle(request, response); // end of chain
}
}
}
interface Endpoint {
void handle(Request request, Response response);
}
// Concrete filters
static final class CorrelationIdFilter implements Filter {
private final AtomicInteger sequence = new AtomicInteger();
public void doFilter(Request request, Response response, Chain chain) {
String id = request.headers().get("X-Correlation-Id");
if (id == null) {
id = "gen-" + sequence.incrementAndGet(); // only generate when the caller sent none
}
response.headers.put("X-Correlation-Id", id);
chain.proceed(request, response);
System.out.println(" [log] " + id + " " + request.path() + " -> " + response.status); // after the rest of the chain
}
}
static final class AuthFilter implements Filter {
private final Map<String, String> tokens;
AuthFilter(Map<String, String> tokens) { this.tokens = Map.copyOf(tokens); }
public void doFilter(Request request, Response response, Chain chain) {
String client = tokens.get(request.headers().getOrDefault("Authorization", ""));
if (client == null) {
response.status = 401;
response.body = "missing or invalid token";
return; // short-circuit: the chain stops here
}
response.headers.put("X-Client", client);
chain.proceed(request, response);
}
}
static final class RateLimitFilter implements Filter {
private final int maxRequests;
private final Map<String, AtomicInteger> counts = new ConcurrentHashMap<>();
RateLimitFilter(int maxRequests) { this.maxRequests = maxRequests; }
public void doFilter(Request request, Response response, Chain chain) {
String client = response.headers.get("X-Client");
if (counts.computeIfAbsent(client, c -> new AtomicInteger()).incrementAndGet() > maxRequests) {
response.status = 429;
response.body = "rate limit exceeded for " + client;
return;
}
chain.proceed(request, response);
}
}
// The filter list is immutable and shared; each request gets its own Chain cursor
static final class Gateway {
private final List<Filter> filters;
private final Endpoint endpoint;
Gateway(List<Filter> filters, Endpoint endpoint) { this.filters = List.copyOf(filters); this.endpoint = endpoint; }
Response handle(Request request) {
Response response = new Response();
new Chain(filters, endpoint).proceed(request, response);
return response;
}
}
public static void main(String[] args) {
Gateway gateway = new Gateway(
List.of(new CorrelationIdFilter(), new AuthFilter(Map.of("Bearer t-123", "mobile-app")), new RateLimitFilter(2)),
(request, response) -> response.body = "orders for " + response.headers.get("X-Client"));
List<Request> requests = List.of(
new Request("/orders", Map.of("Authorization", "Bearer t-123", "X-Correlation-Id", "abc-1")),
new Request("/orders", Map.of()),
new Request("/orders", Map.of("Authorization", "Bearer t-123")),
new Request("/orders", Map.of("Authorization", "Bearer t-123")));
for (Request request : requests) {
Response response = gateway.handle(request);
System.out.println(response.status + " " + response.body);
}
}
}
Important classes and methods
Filter.doFilter(request, response, chain)mirrors the servlet API: a filter callschain.proceed()to continue, or returns to stop.- Code after
chain.proceed()runs on the way back, which is howCorrelationIdFilterlogs the final status. - The filter list is immutable and shared, while each request gets a fresh
Chaincursor, so concurrent requests never share a position.
Expected output
[log] abc-1 /orders -> 200
200 orders for mobile-app
[log] gen-1 /orders -> 401
401 missing or invalid token
[log] gen-2 /orders -> 200
200 orders for mobile-app
[log] gen-3 /orders -> 429
429 rate limit exceeded for mobile-app
How it runs
- The first call keeps the caller's correlation ID and reaches the endpoint.
- The second has no token, so
AuthFiltersets 401 and stops; the log line still appears. - The fourth call is the client's third, so
RateLimitFilterreturns 429.
10. Best Practices and Common Mistakes
Best practices
- Give each handler one rule, and put cheap checks before expensive ones.
- Decide explicitly what happens at the end of the chain: a default handler, an exception or a clear result.
- Build chains in one place (a builder or configuration) and make them immutable.
- Thread safety: chains are usually shared by all requests. Keep per-request data in the request or a per-request cursor, and make stateful handlers use concurrent types.
Common mistakes
- Silent drops: a request falls off the end and nothing reports it.
- Hidden ordering dependencies, such as a rate limiter that needs the client ID set by authentication.
- Very deep recursive chains that grow the call stack.
- Overengineering: a chain for two fixed rules that a simple method expresses clearly.
11. When to Use and When Not to Use
Use it when the set or order of processing steps changes, when different teams own different steps, or when the same steps must be combined differently for different flows.
Avoid it when exactly one well-known object should always handle the request, when every step must always run and none can stop the flow, where a plain loop is clearer, or when debugging "who handled this?" across many handlers would be harder than reading one method.
12. Advantages and Disadvantages
Advantages
- Decouples the sender from the receivers.
- Small, testable handlers with one responsibility each.
- Reorder, add or remove steps without touching others.
- Reusable handlers across several chains.
Disadvantages
- No guarantee that a request is handled.
- Harder to trace which handler acted.
- Order-sensitive, and long chains add latency.
13. Comparison with Similar Patterns
| Aspect | Chain of Responsibility | Decorator | Observer | Command |
|---|---|---|---|---|
| Intent | Find or run the right handlers for a request | Add behaviour to an object | Notify every interested listener | Turn a request into an object |
| Can stop the flow | Yes, any handler | Normally no; it always delegates | No | Not applicable |
| Receivers | One, or each in turn until one stops | The wrapped object | All subscribers | The command's receiver |
| Structure | Linked handlers or an ordered list | Nested wrappers | Subject with a list | Command objects |
A filter chain and a decorator stack look similar in code. The difference is intent: a chain handler may decide to stop the request, while a decorator adds to it and always delegates. Choose Observer when every listener must receive the event, and Command when you need to queue, log or undo requests; commands are often what travels along a chain.
14. Summary
- The chain of responsibility design pattern in Java passes a request along linked handlers until one handles it or a handler stops it.
- Purpose: decouple senders from receivers and split large conditional logic into small steps.
- Components: Handler, Concrete Handlers, Client.
- Each handler handles, forwards or stops; the client only knows the head of the chain.
- Used for approvals, validation pipelines, servlet filters and Spring Security.
- Benefits: flexible ordering, testable handlers and reuse.
- Handle the end of the chain, watch ordering dependencies, and keep shared chains thread-safe.
15. Java Design Pattern Interview Questions and Answers
Q1. How do you define the order of handlers in a Spring Boot application?
Make each handler a bean that implements a common interface and annotate it with @Order (or implement Ordered). When Spring injects a List of that interface, it sorts the beans by that order, so the list is your chain.
@Component @Order(1) class AmountCheck implements PaymentCheck { ... }
@Component @Order(2) class CurrencyCheck implements PaymentCheck { ... }
@Service
class PaymentValidator {
private final List<PaymentCheck> checks; // injected in @Order sequence
PaymentValidator(List<PaymentCheck> checks) { this.checks = checks; }
}Q2. Why might a chain built from linked objects cause a StackOverflowError, and how do you avoid it?
If each handler calls next.handle(), every link adds a stack frame, so a chain of thousands of handlers, or one accidentally linked into a loop, can overflow the stack. Store handlers in a list and iterate, as the Practical Example does, and validate at build time that no handler appears twice.
Q3. One handler calls a slow external fraud service. How do you keep the chain fast?
Place cheap, local checks first so most invalid requests stop before the slow call. Give the external call a strict timeout and a defined fallback, such as "hold for manual review". If the result is not needed to answer the user, move that handler out of the synchronous chain into an asynchronous step after the response.
Q4. How do you unit-test a single handler?
Test it with a stub or mock next handler. For a request it should handle, assert the result and verify that the next handler was not called. For a request it should forward, verify that the next handler received exactly that request. This tests each rule without building the full chain.
Q5. In a servlet filter, what happens if you forget to call chain.doFilter()?
The request stops at that filter: later filters and the servlet never run, and the client receives whatever the filter wrote, often an empty 200 response. Stopping is sometimes intended, for example when authentication fails, but then the filter must set a proper status such as 401 itself.