LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 38 OF 48

Chain of Responsibility in Java: Handlers, Middleware, Approvals

The Chain of Responsibility pattern with a refund approval example: why one big if-else breaks down, handlers linked by a next reference, the two styles (first handler wins, or every handler processes and any may stop), the end of the chain, order and testing, how it differs from Decorator and Observer, servlet filters, and where it shows up in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 141 lines, with a small main() demo. Save it as RefundApprovalChain.java, then run javac RefundApprovalChain.java && java RefundApprovalChain.

import java.util.ArrayList;
import java.util.List;

/** Chain of Responsibility: a refund request travels along handlers until one decides. */
public class RefundApprovalChain {

    record RefundRequest(String orderId, int amount, int refundsThisMonth) {}

    record Decision(String outcome, String decidedBy) {
        static Decision approved(String by) { return new Decision("APPROVED", by); }

        static Decision rejected(String by, String why) { return new Decision("REJECTED (" + why + ")", by); }

        static Decision unhandled() { return new Decision("ESCALATED to a manager", "end of chain"); }
    }

    // ---------- 1. The problem: every rule and their order in one method ----------
    static Decision decideNaively(RefundRequest r) {
        System.out.println("  [naive] log " + r.orderId());
        if (r.refundsThisMonth() > 3) {
            return Decision.rejected("naive", "too many refunds");
        }
        if (r.amount() <= 500) {
            return Decision.approved("naive auto");
        }
        if (r.amount() <= 5_000) {
            return Decision.approved("naive agent");
        }
        // a new rule or a new order means editing this method again
        return r.amount() <= 50_000 ? Decision.approved("naive lead") : Decision.unhandled();
    }

    // ---------- 2. The chain ----------

    /** The base handler owns the next link and the end-of-chain rule. */
    abstract static class RefundHandler {
        private RefundHandler next;

        /** Sets the next handler and returns it, so a chain reads a.then(b).then(c). */
        RefundHandler then(RefundHandler nextHandler) {
            this.next = nextHandler;
            return nextHandler;
        }

        abstract Decision handle(RefundRequest r);

        /** Forward to the next handler; at the end, never return null. */
        protected Decision passOn(RefundRequest r) {
            return next == null ? Decision.unhandled() : next.handle(r);
        }
    }

    /** Pipeline style: always does its part, then passes on. */
    static final class AuditTrail extends RefundHandler {
        private final List<String> entries = new ArrayList<>();

        @Override
        Decision handle(RefundRequest r) {
            entries.add(r.orderId() + ":" + r.amount());
            return passOn(r);
        }

        List<String> entries() { return entries; }
    }

    /** May stop the request; otherwise passes it on. */
    static final class FraudScreen extends RefundHandler {
        @Override
        Decision handle(RefundRequest r) {
            if (r.refundsThisMonth() > 3) {
                return Decision.rejected("fraud screen", "too many refunds this month");
            }
            return passOn(r);
        }
    }

    /** First-one-wins style: approves within its limit, otherwise passes on. */
    static class LimitApprover extends RefundHandler {
        private final String name;
        private final int limit;

        LimitApprover(String name, int limit) {
            this.name = name;
            this.limit = limit;
        }

        @Override
        Decision handle(RefundRequest r) {
            return r.amount() <= limit ? Decision.approved(name) : passOn(r);
        }
    }

    static final class AutoApprover extends LimitApprover {
        AutoApprover() { super("auto approver", 500); }
    }

    static final class SupportAgent extends LimitApprover {
        SupportAgent() { super("support agent", 5_000); }
    }

    static final class FinanceLead extends LimitApprover {
        FinanceLead() { super("finance lead", 50_000); }
    }

    /** The client: builds the chain in one place and only talks to the first handler. */
    static final class RefundDesk {
        private final AuditTrail audit = new AuditTrail();

        RefundDesk() {
            audit.then(new FraudScreen())
                 .then(new AutoApprover())
                 .then(new SupportAgent())
                 .then(new FinanceLead());
        }

        Decision submit(RefundRequest r) { return audit.handle(r); }

        List<String> auditLog() { return audit.entries(); }
    }

    public static void main(String[] args) {
        System.out.println("Problem: one method with every rule");
        System.out.println("  " + decideNaively(new RefundRequest("ORD-1", 3_200, 1)));

        System.out.println();
        System.out.println("Chain: audit -> fraud -> auto -> agent -> lead");
        RefundDesk desk = new RefundDesk();
        List<RefundRequest> requests = List.of(
                new RefundRequest("ORD-11", 349, 0),      // auto approver
                new RefundRequest("ORD-12", 3_200, 1),    // support agent
                new RefundRequest("ORD-13", 18_000, 0),   // finance lead
                new RefundRequest("ORD-14", 250, 5),      // stopped by the fraud screen
                new RefundRequest("ORD-15", 90_000, 0));  // falls off the end: escalated
        for (RefundRequest r : requests) {
            Decision d = desk.submit(r);
            System.out.printf("  %-7s %6d -> %-42s by %s%n",
                    r.orderId(), r.amount(), d.outcome(), d.decidedBy());
        }
        System.out.println("audit log saw every request: " + desk.auditLog());
    }
}

Notes

The problem

Here is the naive version. One method logs the request, checks for fraud, then walks through amount limits to decide who approves. Every rule, and the order of the rules, is welded into this method. Adding a festival season rule, or letting premium customers skip the agent, means editing it again. You cannot test one rule alone, and you cannot reuse the same rules in a different order for another country.

The naive version
Decision decide(RefundRequest r) {
    log(r);
    if (r.refundsThisMonth() > 3)
        return reject("too many");
    if (r.amount() <= 500) return auto();
    if (r.amount() <= 5000) return agent();
    if (r.amount() <= 50000) return lead();
    return escalate();
}  // a new rule edits this method

The idea

The idea in one sentence: link a set of handlers in a line and send the request to the first one. Each handler looks at the request and decides: deal with it, stop it, or pass it to the next handler. The sender does not know which handler will finally deal with it. And because the chain is assembled outside the handlers, you can reorder it, add to it or remove from it without touching any handler.

In one sentence
  • link handlers in a line; send
  • the request to the first; each
  • one handles it, stops it, or
  • passes it to the next
  • the sender does not know which
  • handler will deal with it
  • the chain is built outside
  • the handlers, so it can change

The structure

The participants. RefundDesk is the client. It builds the chain and sends each refund request to the first handler. RefundHandler is the abstract handler: it holds a reference to the next handler and a helper to pass the request on. The concrete handlers are AuditTrail, FraudScreen, AutoApprover, SupportAgent and FinanceLead. RefundRequest is a simple record with the order, the amount and how many refunds the customer had this month.

The code: base class

The base class has three parts. A private next field. A method called then, which sets the next handler and returns it, so the chain can be built in one readable line. And a protected pass on method that forwards to the next handler, or, at the end of the chain, returns an unhandled decision. That last part matters: a request must never silently fall off the end of the chain.

RefundHandler
abstract class RefundHandler {
  private RefundHandler next;
  RefundHandler then(RefundHandler n) {
    next = n; return n; }
  abstract Decision handle(RefundRequest r);
  Decision passOn(RefundRequest r) {
    return next == null
        ? Decision.unhandled()
        : next.handle(r);
  }
}

The code: handlers

Each concrete handler is small and checks one thing. The fraud screen rejects the request if the customer already had more than three refunds this month, and otherwise passes it on. The auto approver approves anything up to five hundred, and otherwise passes it on. The support agent and finance lead look the same with bigger limits. Each handler can be tested alone, by giving it a request and checking the decision.

Two concrete handlers
class FraudScreen extends RefundHandler {
  Decision handle(RefundRequest r) {
    if (r.refundsThisMonth() > 3)
      return Decision.rejected(...);
    return passOn(r); } }

class AutoApprover extends RefundHandler {
  Decision handle(RefundRequest r) {
    if (r.amount() <= 500)
      return Decision.approved("auto");
    return passOn(r); } }

Run-through

Let us follow a refund of three thousand two hundred. The desk sends it to the audit trail, which logs it and passes it on. The fraud screen sees only one earlier refund this month, so it passes it on. The auto approver sees it is over five hundred and passes it on. The support agent's limit is five thousand, so the agent approves it and returns the decision. The finance lead never sees it. The desk only ever talked to the first handler.

Two styles

There are two flavours of this pattern. In the first, exactly one handler deals with the request, and the rest never see it. Our approval levels work like that, and so does an exception travelling up the call stack until a matching catch block handles it. In the second flavour, a pipeline, every handler does its part and passes it on, but any handler may stop early. Web middleware works like that: logging, authentication, rate limiting, then validation. Our chain mixes both.

Two flavours of chain
  • first one wins:
  • approvals, event bubbling,
  • catch blocks up a call stack
  • exactly one handler decides
  • pipeline (middleware):
  • every handler does its part
  • and any one may stop early
  • logging, auth, rate limits,
  • validation, compression

Ends, order, loops

Three things to get right. First, the end of the chain. Decide what happens when nobody handles the request: return an unhandled result, escalate to a person, or put a catch all handler at the end. Never return null. Second, order matters. Put cheap and strict checks first, so fraud is screened before anything is approved. Treat the order as configuration. Third, never let the chain point back to itself, and keep it short, because a long chain is hard to debug.

Get these right
  • the end: return unhandled,
  • escalate, or a default
  • handler; never return null
  • order matters: cheap and
  • strict checks first (fraud
  • before approval)
  • no loops: a chain that points
  • back to itself never ends
  • keep chains short: long ones
  • are hard to debug

When to use it

Use the pattern when several objects might handle a request and the sender should not choose between them, or when the handlers and their order change by configuration, customer type or country. Skip it when there are two fixed rules, because a plain if else is clearer. Be careful when every request must be handled, since a chain can let a request slip through. And remember that stepping through a long chain in a debugger is slower than reading one method.

Use it / skip it
  • use it when:
  • several objects may handle a
  • request and you do not want
  • the sender to pick one
  • the handlers or their order
  • change by config or country
  • skip it when:
  • two fixed rules: if-else is
  • clearer
  • every request must be handled

vs its neighbours

How does it differ from its neighbours? A decorator wraps one object, and every layer runs and adds behaviour. It normally does not stop the call. Observer tells every listener about an event, in no promised order, and no listener can stop the others. A chain is ordered, and one handler decides, or any handler may stop the request. Middleware sits between chain and decorator, which is why the two are often confused.

Do not mix them up
  • Decorator: wraps one object,
  • every layer runs and adds
  • behaviour, never stops it
  • Observer: every listener
  • hears the event, no order,
  • none can stop the others
  • Chain: ordered handlers, one
  • decides or any may stop

In Java

Java web code is full of this pattern. A servlet filter receives the request, the response and a filter chain object. It can stop the request, for example when the user is not authorised, or call do filter on the chain to pass it to the next filter and finally to the servlet. Spring Security is built as a chain of such filters. And in java dot util dot logging, a logger hands each log record to its parent logger's handlers too, unless you turn that off.

Where you have seen it
// a servlet filter
public void doFilter(ServletRequest req,
        ServletResponse res,
        FilterChain chain) ... {
    if (!authorised(req)) { deny(res);
        return; }       // stop here
    chain.doFilter(req, res); // pass on
}
// also: Spring Security filter chain,
// java.util.logging parent handlers

In LLD interviews

In machine coding rounds, listen for levels, escalation, approvals or middleware. A logger can route messages through handlers for each level. An A T M dispenser is a favourite: the two thousand note handler takes what it can and passes the rest to the five hundred handler, then to the one hundred handler. Leave and expense approvals, support ticket escalation and an A P I gateway with authentication, rate limiting and validation all fit naturally.

Where it fits
  • logger: handlers per level,
  • each decides to write or not
  • ATM: note dispensers 2000,
  • 500, 100 each take a share
  • and pass the rest on
  • leave or expense approvals
  • API gateway: auth, rate limit,
  • validation as middleware
  • support ticket escalation
  • vending machine coin checks

Mistakes to avoid

Common mistakes. A request that falls off the end of the chain with no answer. A handler that forgets to pass the request on and silently swallows it, which the template style base class helps prevent. Handlers that refer to each other by concrete class, so the chain cannot be rebuilt. An order that approves before checking for fraud. And a chain that accidentally loops back to an earlier handler. Mention each of these and you show real experience.

Common mistakes
  • request falls off the end
  • with no answer
  • handler forgets to call next
  • and silently swallows it
  • handlers know each other
  • by concrete class
  • wrong order: approve before
  • the fraud check
  • a loop in the chain

Interview questions

What is the Chain of Responsibility pattern?

Handlers are linked in a line and a request is sent to the first one. Each handler either deals with it, stops it, or passes it to the next, so the sender does not need to know which handler will finally respond.

What are the two common styles of chain?

In the first, exactly one handler handles the request and the rest never see it, as in approval levels or exception handling up a call stack. In the second, a pipeline, every handler does its part and any one may stop early, as in web middleware and servlet filters.

What happens if no handler handles the request?

You must decide explicitly: return an unhandled result, escalate, throw a clear exception, or place a catch-all handler at the end. Silently returning nothing is a common bug in interview solutions.

How is Chain of Responsibility different from Decorator?

Both link objects that forward calls. A decorator wraps one object and every layer runs to add behaviour, normally without stopping the call. A chain handler decides whether to handle, stop or forward, so a request may be handled early and later handlers never run.

Where is this pattern used in Java?

Servlet filters receive a FilterChain and either stop the request or call chain.doFilter to pass it on, and Spring Security is built as a chain of such filters. java.util.logging also forwards log records to parent loggers’ handlers by default.

How would you design an ATM cash dispenser with this pattern?

Create one handler per note value, ordered from largest to smallest. Each dispenses as many of its notes as it can for the remaining amount and passes the rest on; if anything is left at the end, the withdrawal is refused before any notes are released.

Why does the order of handlers matter?

Each handler sees only what earlier handlers passed on, so order changes behaviour. Cheap and strict checks such as fraud screening, authentication or rate limiting must run before approval or business logic, and the order should be visible in one place, the code that builds the chain.

What are the downsides of Chain of Responsibility?

A request may go unhandled, behaviour depends on order that is easy to get wrong, long chains are hard to debug and add a little overhead per handler, and a misconfigured chain can loop. For two or three fixed rules a plain if-else is clearer.