00:00

Chain of Responsibility Design Pattern in Java

Last updated:

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

ComponentResponsibilityIn the Basic Example
HandlerDeclares the handling method and holds the link to the next handlerRefundApprover
Concrete HandlersDecide whether to handle the request or forward itAutoApproval, SupportAgent, TeamLead, FinanceManager
ClientBuilds the chain once and sends requests to its headmain

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.

Chain of Responsibility UML class diagram The Client uses the abstract RefundApprover, which holds an optional reference to the next RefundApprover. AutoApproval, SupportAgent, TeamLead and FinanceManager extend RefundApprover. Client uses «abstract» RefundApprover - next: RefundApprover + linkWith(next): RefundApprover + handle(refund): String # canApprove(refund): boolean next 0..1 extends AutoApproval SupportAgent TeamLead FinanceManager
Chain of Responsibility: each approver may hold one next approver, so the objects form a linked chain at runtime.
  1. RefundApprover is the handler. The arrow that loops back to it is the next field: each approver may point to zero or one further approver.
  2. handle() holds the shared "approve or forward" logic; canApprove() is abstract (italic), so each subclass supplies its own rule.
  3. The four concrete approvers extend the handler (solid lines, hollow triangle).
  4. The client depends only on the abstract handler, so it never knows how many approvers exist.

5. Step-by-Step Execution Flow

  1. The client creates the four approvers and links them: auto-approval, support agent, team lead, finance manager.
  2. It calls chain.handle(refund) with a refund of Rs. 18,000.
  3. AutoApproval cannot approve more than 500, so handle() calls next.handle(refund).
  4. SupportAgent cannot approve more than 5,000 and forwards it again.
  5. TeamLead can approve up to 50,000, so it returns "approved by team lead". The finance manager is never called.
  6. 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 Filter receives a FilterChain and calls chain.doFilter() to pass the request on, or stops by not calling it.
  • Spring: Spring Security runs requests through a SecurityFilterChain, Spring MVC's HandlerInterceptor.preHandle() stops processing by returning false, and Spring Cloud Gateway applies a chain of gateway filters to every route.

7. Problem Without the Pattern

All refund rules in one method:

RefundsWithoutChain.java
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)));
    }
}
Console
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-else ladder.
  • 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.

RefundApprovalChainDemo.java
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() is final: the forwarding logic is written once in the base class, and subclasses supply only canApprove() and name().
  • 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

Console
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

  1. Each amount starts at auto-approval and moves along until a limit covers it.
  2. Rs. 750,000 passes every handler; the last one has no successor, so it reports an escalation.

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

AspectChain of ResponsibilityDecoratorObserverCommand
IntentFind or run the right handlers for a requestAdd behaviour to an objectNotify every interested listenerTurn a request into an object
Can stop the flowYes, any handlerNormally no; it always delegatesNoNot applicable
ReceiversOne, or each in turn until one stopsThe wrapped objectAll subscribersThe command's receiver
StructureLinked handlers or an ordered listNested wrappersSubject with a listCommand 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.