An employee submits a taxi bill for $120 with no receipt, and it is rejected straight away. A $35 lunch goes to their team lead, who approves it. A $6,000 laptop goes past the team lead and the manager, and the director approves it. A $9,000 course is above everyone's limit, so finance looks at it by hand.
Every claim walks down the same line of people and checks. Each one either decides, or says "not mine" and hands it to the next. The claim never needs to know who will decide it. It only needs to enter the line at the front.
The Chain of Responsibility pattern turns that line into code. Each check becomes a small object, the objects are linked in order, and a request travels along the links until one object decides. The same shape shows up in support tickets that escalate from a bot to an agent to an engineer. A related shape, where every handler does its part and passes the request on, runs web request filters, level-based loggers and an ATM handing out notes of each size.
In this article we build the expense approval flow twice. The first version is one method with a long if-else ladder. The second uses the Chain of Responsibility pattern. Then we look at what the pattern costs, when a plain loop is enough, how it differs from Decorator, and how it comes up in interviews.
All the code is Java, and all of it compiles and runs. Every snippet is cut from the finished project, and the Open file button on a snippet shows the whole file in a code browser.
The approval flow we are building
An expense claim has an id, the employee's name, a category (travel, meals, equipment, training or gifts), an amount in dollars, and a receipt number if the employee has a receipt. The company's rules, checked in this order:
- Receipt check. A claim above $50 with no receipt is rejected.
- Policy check. Some categories are never paid back. Here, gifts are rejected.
- Duplicate check. A receipt can be claimed only once. A claim that reuses one is rejected.
- Approval limits. A team lead approves up to $500, a manager up to $2,500, and a director up to $7,500. The claim goes to the lowest role whose limit covers it.
- Finance review. A claim above every limit is sent to finance to look at by hand.
Every decision must say who decided and why, so the employee knows what happened. Finance also changes the limits a few times a year, and must be able to add a role, such as a department head, by changing the policy, without a new class or any change to the approval code.
This drawing is the design. Two questions come straight out of it: what happens to a claim that reaches the end of the line, and who decides the order? We answer both below.
The first version: one long if-else
The obvious way to write this is one method that checks each rule in turn and returns at the first one that decides:
public class ApprovalService { private final Set<String> usedReceipts = ConcurrentHashMap.newKeySet(); public Decision review(ExpenseClaim claim) { if (claim.amount() > 50 && !claim.hasReceipt()) { return Decision.rejected("Receipt check", "a receipt is needed above $50"); } if (claim.category() == Category.GIFTS) { return Decision.rejected("Policy check", "GIFTS claims are not reimbursed"); } if (claim.hasReceipt() && !usedReceipts.add(claim.receiptNumber())) { return Decision.rejected("Duplicate check", "receipt " + claim.receiptNumber() + " was already claimed"); } if (claim.amount() <= 500) { return Decision.approved("Team lead", "within the $500 limit"); } if (claim.amount() <= 2_500) { return Decision.approved("Manager", "within the $2,500 limit"); } if (claim.amount() <= 7_500) { return Decision.approved("Director", "within the $7,500 limit"); } return Decision.sentForReview("Finance review", "above every approval limit"); }}This code works, and it is easy to read. If the rules were fixed forever, it would be a fine answer. The trouble comes from how expense rules actually change.
The limits are written into the code. When finance raises the manager's limit to $4,000, a developer has to edit this method and ship a release.
Every rule lives in one method and one class. The duplicate check needs a set of used receipts, so ApprovalService holds one (line 5), even though no other rule uses it. A rule that needs a database, a currency converter or a budget service brings that dependency into the same class too.
Adding a rule means editing the middle of the ladder. A department head between the manager and the director is a new if between lines 22 and 23. The other branches must be read and re-tested, because one wrong comparison sends claims to the wrong person.
No rule can be tested alone. To test the duplicate check, a test has to build a claim that gets past the receipt and policy checks first.
The idea
The pattern works like this:
- Each rule becomes a handler: a small class with one job, which looks at a claim and either decides or passes.
- Every handler holds a reference to the next handler. Linked together, they form the chain.
- The client gives the claim to the first handler and gets a decision back. It never knows which handler decided.
- When a handler passes, the claim goes to the next one. The first handler that decides ends the walk.
The rules are the same five as before. What changes is where they live: each in its own class, with its own data, joined in an order that is set in one place.
Building it, step by step
Step 1: one base class that decides or passes on
Every handler needs the same two things: a link to the next handler, and the rule "if I decide, return my decision, otherwise ask the next one". That belongs in a base class:
public abstract class ClaimHandler { private ClaimHandler next; // Package-private and once only: ApprovalChain links the handlers, and nothing relinks a live chain. // Returns the handler it was given, so a chain can be linked in one line: a.linkTo(b).linkTo(c). ClaimHandler linkTo(ClaimHandler next) { if (this.next != null) { throw new IllegalStateException(getClass().getSimpleName() + " is already linked"); } for (ClaimHandler handler = next; handler != null; handler = handler.next) { if (handler == this) { throw new IllegalStateException("Linking " + getClass().getSimpleName() + " here would make a loop"); } } this.next = next; return next; } public final Decision handle(ExpenseClaim claim) { Optional<Decision> decision = decide(claim); if (decision.isPresent()) { return decision.get(); } if (next == null) { throw new IllegalStateException(getClass().getSimpleName() + " is the last handler and did not decide " + claim.id()); } return next.handle(claim); } protected abstract Optional<Decision> decide(ExpenseClaim claim);}A handler subclass writes only decide. It returns Optional.of(decision) when it decides, and Optional.empty() when it passes. The base class's handle does the walking: it returns the decision if there is one (line 28), and otherwise hands the claim to next (line 33).
handle is final, so no subclass can change the walking. linkTo returns the handler it was given, which lets a chain be linked in one line: a.linkTo(b).linkTo(c). It is package-private and works only once, so only ApprovalChain links handlers, and nothing can relink a chain that is in use. It also refuses any link that would make a loop, such as a handler linked to itself. A loop would call handle over and over until the stack overflows.
Who passes the claim to the next handler?
Each handler calls next itself
This is the common version. Each handler's handle method ends with next.handle(claim). It works, but every handler repeats the same lines, and a handler that forgets them silently drops the claim. A handler can also call next and then change the answer that comes back. That makes the chain hard to follow.
The base class passes on, and handlers only decideOur pick
A handler answers one question: "do I decide this?". The walking is written once, in ClaimHandler.handle, and no handler can forget it or bend it. The cost is less freedom: a handler cannot do work after the next one answers. Our approval rules do not need that.
Step 2: one class per kind of rule
Each rule is now a short class. Here is the receipt check:
public class ReceiptCheck extends ClaimHandler { private final long receiptRequiredAbove; public ReceiptCheck(long receiptRequiredAbove) { this.receiptRequiredAbove = receiptRequiredAbove; } @Override protected Optional<Decision> decide(ExpenseClaim claim) { if (claim.amount() > receiptRequiredAbove && !claim.hasReceipt()) { return Optional.of(Decision.rejected("Receipt check", "a receipt is needed above " + Money.dollars(receiptRequiredAbove))); } return Optional.empty(); }}It decides only to reject. A claim with a receipt, or at $50 or below, passes untouched.
The duplicate check needs the record of used receipts, and now it is the only class that has it:
public class DuplicateReceiptCheck extends ClaimHandler { private final ReceiptLedger ledger; public DuplicateReceiptCheck(ReceiptLedger ledger) { this.ledger = ledger; } @Override protected Optional<Decision> decide(ExpenseClaim claim) { if (claim.hasReceipt() && !ledger.record(claim)) { return Optional.of(Decision.rejected("Duplicate check", "receipt " + claim.receiptNumber() + " was already claimed")); } return Optional.empty(); }}The record itself is a ReceiptLedger. It wraps a map built for many threads, from each receipt number to the claim that holds it. Its record method records a receipt for a claim and says whether that was allowed, in one step. It compares whole claims, so a reused claim id with a different amount or employee is still a duplicate. The methods are package-private, so only the handlers and the chain can touch the ledger:
public class ReceiptLedger { private final Map<String, ExpenseClaim> claimByReceipt = new ConcurrentHashMap<>(); private final Set<String> claimsInReview = ConcurrentHashMap.newKeySet(); // Records the receipt for this claim in one step. True if the receipt was free, or this same claim already holds it. boolean record(ExpenseClaim claim) { ExpenseClaim holder = claimByReceipt.putIfAbsent(claim.receiptNumber(), claim); return holder == null || holder.equals(claim); } boolean isHeldBy(ExpenseClaim claim) { return claim.equals(claimByReceipt.get(claim.receiptNumber())); } // Frees the receipt, but only if this claim holds it. void release(ExpenseClaim claim) { claimByReceipt.remove(claim.receiptNumber(), claim); } // One review of a claim at a time, across every chain that shares this ledger. boolean startReview(ExpenseClaim claim) { return claimsInReview.add(claim.id()); } void endReview(ExpenseClaim claim) { claimsInReview.remove(claim.id()); }}The one-step putIfAbsent matters. If two different claims with the same receipt arrive on two threads at the same moment, checking "is it used?" and then recording it in two steps could let both through. With putIfAbsent, exactly one of them gets true.
The ledger is passed in, not created inside the check. When finance changes the limits, we build a new chain, and the new chain must still remember every receipt the old one saw. The ledger belongs to the company, not to one chain. For a short time both chains run at once: the old one finishes the claims it started while the new one takes new claims, and both write to the same ledger.
The approval limits are all the same kind of rule, so they share one class:
public class RoleApprover extends ClaimHandler { private final String role; private final long limit; public RoleApprover(String role, long limit) { this.role = role; this.limit = limit; } @Override protected Optional<Decision> decide(ExpenseClaim claim) { if (claim.amount() <= limit) { return Optional.of(Decision.approved(role, "within the " + Money.dollars(limit) + " limit")); } return Optional.empty(); }}In this design an approver decides at once. In a real company, the chain decides who must approve, and the claim then waits in that person's queue until they act. We would model that with a fourth outcome, ROUTED, that names the person, and a separate step that records their answer later. We keep the instant version so the pattern stays in view.
One class per role, or one class with the role as data?
TeamLeadApprover, ManagerApprover and DirectorApprover classes
This reads naturally, and many answers draw it. But the three classes would be the same code with a different number in each. Adding a department head would mean writing a new class, which is exactly what finance wanted to avoid.
One RoleApprover, made once per role from the policyOur pick
The role's name and limit are data, so they are constructor arguments. A new role is a new line in the policy, with no new class. If a role ever needs different behaviour, for example a director who must approve anything in the equipment category, that role gets its own class then.
May a handler act and then pass the claim on?
Yes: every handler does its part and passes on
This is the other common shape of the pattern, used by web request filters and middleware. Every handler runs. One logs the request, the next checks a login, the next adds a header. It suits work that every request needs.
No: a handler either decides or passes, never bothOur pick
An approval is one decision by one handler. If a handler could also change a claim and pass it on, the outcome would depend on everything before it, and the "decided by" field would hide half the story. Work that every claim needs, such as logging, belongs outside the chain.
The duplicate check bends this rule a little. It never changes the claim, but it does write to the ledger and then pass the claim on. It is the one handler with a side effect. If a later handler fails, for example an approver that calls a budget service that is down, the claim gets no decision, but its receipt is already recorded. The employee's retry would then be rejected as a duplicate of itself.
The duplicate check writes to the ledger. What if a later handler fails?
Record the receipt only after the chain decides
The check would only ask "is it used?", and ApprovalChain would record the receipt once a decision comes back. That brings back the race above: two claims with the same receipt can both see "not used" before either is recorded.
Record it in the check, keyed by claim id, and undo it if the chain failsOur pick
The ledger stores which claim holds each receipt, so the same claim asking again is not a duplicate. If anything after the check throws, ApprovalChain.review releases the receipt, but only if the claim did not hold it before this try began. The ledger also allows only one try of a claim at a time, across every chain, so "not held before this try" means "recorded by this try". The cost is a few lines in the ledger and the chain.
review first asks the ledger to start the claim's review, and refuses a second try while one is still running. Then walk notes whether the claim held its receipt before the walk, and its catch releases the receipt only if it did not:
public Decision review(ExpenseClaim claim) { if (!ledger.startReview(claim)) { throw new IllegalStateException("Claim " + claim.id() + " is already being reviewed"); } try { return walk(claim); } finally { ledger.endReview(claim); } } private Decision walk(ExpenseClaim claim) { // Only one try of a claim runs at a time, so a receipt the claim did not hold before the walk was recorded by this try. boolean heldBefore = claim.hasReceipt() && ledger.isHeldBy(claim); try { return first.handle(claim); } catch (RuntimeException e) { if (claim.hasReceipt() && !heldBefore) { ledger.release(claim); } throw e; } }Step 3: a last handler that always decides
A claim of $9,000 passes every approver. Something must still answer it. The last handler in every chain is ManualReview, which always decides:
public class ManualReview extends ClaimHandler { @Override protected Optional<Decision> decide(ExpenseClaim claim) { return Optional.of(Decision.sentForReview("Finance review", "above every approval limit")); }}What happens when no handler decides?
Return null, or an empty Optional, to the caller
The chain looks complete, but every caller now has to remember the "nobody decided" case. One that forgets crashes later, far from the cause. For an expense claim, "nobody decided" is not a real answer anyway.
An explicit last handler that always decidesOur pick
The business already has an answer for "above every limit": send it to finance. Writing that answer as a handler makes it visible in the chain and in the class diagram. A chain built without it is a programming mistake, so ClaimHandler.handle throws an IllegalStateException rather than return nothing (line 31).
Step 4: build the chain in one place, from a policy
The order matters, and the limits change, so both live in one place. The policy is a record holding the receipt threshold, the categories that are not paid back, and the approval limits in order:
public record ApprovalPolicy(long receiptRequiredAbove, Set<Category> notReimbursed, List<Limit> limits) { public record Limit(String role, long amount) { public Limit { if (role == null || role.isBlank()) { throw new IllegalArgumentException("A limit needs a role"); } if (amount <= 0) { throw new IllegalArgumentException(role + " needs a positive limit, got " + amount); } } } public ApprovalPolicy { if (receiptRequiredAbove < 0) { throw new IllegalArgumentException("The receipt threshold cannot be negative, got " + receiptRequiredAbove); } notReimbursed = Set.copyOf(notReimbursed); limits = List.copyOf(limits); if (limits.isEmpty()) { throw new IllegalArgumentException("A policy needs at least one approval limit"); } for (int i = 1; i < limits.size(); i++) { Limit previous = limits.get(i - 1); Limit current = limits.get(i); if (current.amount() <= previous.amount()) { throw new IllegalArgumentException(current.role() + " must have a higher limit than " + previous.role() + ", or no claim will ever be approved by " + current.role()); } } }}The constructor checks that each limit is higher than the one before it. Limits in the wrong order would not crash anything. They would quietly send claims to the wrong person, which is worse, so the policy refuses them. It also copies the lists, so a caller who changes a list later cannot change the policy.
The records also refuse values that make no sense. The policy refuses a negative threshold, and a limit with no role or a limit of zero or less. ExpenseClaim refuses an amount of zero or less, a missing category and a blank receipt number. These checks are a last guard. The form in front of the system shows the employee a message for an empty field or a negative amount. A bad value that still reaches these records is a bug in the code that built them, so they throw IllegalArgumentException.
ApprovalChain turns a policy into linked handlers:
public class ApprovalChain { private final ClaimHandler first; private final ReceiptLedger ledger; public ApprovalChain(ApprovalPolicy policy, ReceiptLedger ledger) { this(build(policy, ledger), ledger); } private static ClaimHandler build(ApprovalPolicy policy, ReceiptLedger ledger) { ClaimHandler first = new ReceiptCheck(policy.receiptRequiredAbove()); ClaimHandler last = first .linkTo(new PolicyCheck(policy.notReimbursed())) .linkTo(new DuplicateReceiptCheck(ledger)); for (ApprovalPolicy.Limit limit : policy.limits()) { last = last.linkTo(new RoleApprover(limit.role(), limit.amount())); } last.linkTo(new ManualReview()); return first; }The checks go first, then one approver per limit in the policy's order, then ManualReview. The client calls review and gets a decision. It never sees a handler.
The order of the checks is deliberate too. The duplicate check comes after the policy check, so a gift that policy rejects does not use up its receipt.
Who decides the order of the chain?
The calling code links the handlers itself
This is flexible, and every caller can build the chain it likes. But each caller can also get the order wrong, or forget ManualReview, and the mistake shows up only as a wrong decision on some claims.
ApprovalChain builds it from a checked policyOur pick
The order is written in exactly one place, and the limits are checked before any chain is built. Changing a limit means building a new ApprovalChain from a new policy, with no change to any handler or to the chain. In a real system the policy would be read from a config file or a database; the demo builds it in Java to stay short. The service that reviews claims holds the current chain in an atomic reference to an ApprovalChain, so a new chain replaces the old one in a single write, and every review runs on one whole chain or the other. The cost is that a caller cannot build an unusual chain, such as one without the duplicate check. If a team ever needs one, it can get its own builder.
The finished design
Here is one claim, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package approval; import java.util.Optional; import claim.ExpenseClaim; public abstract class ClaimHandler { private ClaimHandler next; // Package-private and once only: ApprovalChain links the handlers, and nothing relinks a live chain. // Returns the handler it was given, so a chain can be linked in one line: a.linkTo(b).linkTo(c). ClaimHandler linkTo(ClaimHandler next) { if (this.next != null) { throw new IllegalStateException(getClass().getSimpleName() + " is already linked"); } for (ClaimHandler handler = next; handler != null; handler = handler.next) { if (handler == this) { throw new IllegalStateException("Linking " + getClass().getSimpleName() + " here would make a loop"); } } this.next = next; return next; } public final Decision handle(ExpenseClaim claim) { Optional<Decision> decision = decide(claim); if (decision.isPresent()) { return decision.get(); } if (next == null) { throw new IllegalStateException(getClass().getSimpleName() + " is the last handler and did not decide " + claim.id()); } return next.handle(claim); } protected abstract Optional<Decision> decide(ExpenseClaim claim);}The demo in demo/Main.java sends ten claims through two policies:
C-1 Asha MEALS $35 -> APPROVED by Team lead (within the $500 limit) C-2 Ravi TRAVEL $120 -> REJECTED by Receipt check (a receipt is needed above $50) C-3 Meera GIFTS $200 -> REJECTED by Policy check (GIFTS claims are not reimbursed) C-4 Kabir TRAVEL $1,800 -> APPROVED by Manager (within the $2,500 limit) C-5 Kabir TRAVEL $1,800 -> REJECTED by Duplicate check (receipt R-402 was already claimed) C-6 Neha EQUIPMENT $6,000 -> APPROVED by Director (within the $7,500 limit) C-7 Arjun TRAINING $9,000 -> SENT_FOR_REVIEW by Finance review (above every approval limit) New policy: Manager up to $4,000, and a Department head up to $6,000 C-8 Kabir TRAVEL $3,200 -> APPROVED by Manager (within the $4,000 limit) C-9 Neha EQUIPMENT $6,000 -> APPROVED by Department head (within the $6,000 limit) C-10 Neha EQUIPMENT $6,000 -> REJECTED by Duplicate check (receipt R-517 was already claimed) Rejected policy: Team lead must have a higher limit than Manager, or no claim will ever be approved by Team lead
C-1 is $35 with no receipt, which is under the $50 threshold, so the team lead approves it. C-2 and C-3 stop at the receipt and policy checks. C-5 reuses receipt R-402 from C-4 and is rejected. C-7 is above every limit and goes to finance.
The second block uses a new policy with a $4,000 manager limit and a department head at $6,000. Only the policy changed, and C-9 now goes to the new department head. C-10 reuses receipt R-517 from C-6 under the old policy, and it is still rejected, because both chains share one ledger. The last line is a policy with its limits in the wrong order, which the policy refuses.
What it costs
Adding, removing or reordering a rule is cheap. A new rule is one new class and one new link. A new limit is one line of policy. No existing handler changes.
A decision that needs several rules at once is awkward. Each handler sees the claim alone and decides alone. A rule such as "reject if the claim has no receipt and the employee had two rejected claims this month" does not fit one handler, and two handlers cannot easily combine their answers. When decisions combine many rules, a list of rules that all run, followed by one step that weighs their results, is a better shape.
The order becomes a source of bugs. In the ladder, the order is visible in one method. In a chain, it is spread across links, unless one builder owns it, as ApprovalChain does. A wrong order still runs.
There are smaller costs. Five classes replace one method, and following one claim means stepping through several files.
When a plain loop is better
The three approvers are the same kind of rule with different numbers. If approval limits were the only rules, a loop over the sorted limits would be the whole design:
for (ApprovalPolicy.Limit limit : policy.limits()) { if (claim.amount() <= limit.amount()) { return Decision.approved(limit.role(), "within the limit"); }}return Decision.sentForReview("Finance review", "above every approval limit");The chain earns its place because our rules are of different kinds: a receipt rule, a category rule, a rule with its own memory, limits, and a fallback. If every handler would be the same class with different numbers, use a sorted list and a loop.
Two more cases where we would not use the pattern:
- Two or three fixed rules. The
if-elseversion is shorter and just as clear. - Every rule must run. If all the checks must run and report, such as a form that lists every invalid field at once, the chain is the wrong shape. Run a list of validators and collect their results.
Chain of Responsibility or Decorator?
The two are easy to confuse, because they look alike. In both, objects hold a reference to another object of the same type, and a request passes from one to the next.
| Chain of Responsibility | Decorator | |
|---|---|---|
| How far a request goes | Until one handler decides, and usually no further | Through every layer, every time |
| What each object does | Decides, or passes untouched | Adds behaviour, then calls the object inside |
| Who does the real work | Whichever handler decides | The object at the centre, with the layers around it |
| Example | Expense approval: the manager approves, the director never sees it | A data client with logging, retries and caching, each a layer |
A short way to remember it: a chain looks for one handler that answers. Decorators add something at every layer. The Decorator pattern page covers decorators in full.
The middleware shape from Step 2, where every handler acts and passes on, sits between the two. It is still called Chain of Responsibility, and it behaves much like a stack of decorators. In an interview, say which shape you mean.
In an interview
The first-handler-decides shape appears inside these common low-level design questions:
- a support ticket escalating from a bot to an agent to an engineer
- an approval or escalation flow with limits, like this one
- discount or pricing rules where the first rule that applies sets the price. The Parking Lot design mentions it for stacked fee rules.
The related shape, where every handler acts and passes on, appears in these:
- an ATM handing out notes of each size in turn
- a logger that sends each message to the handlers for its level
- request validation or middleware in a web framework
A good order for presenting it:
- Draw the line of handlers first, in order, with what each one decides. Ask the interviewer whether one handler decides or every handler acts. The answer picks the shape.
- Say what happens at the end of the chain. "A claim above every limit goes to finance" is a design decision. Say it early.
- Then write the base class and one or two handlers. The base class shows the pattern, and one real handler shows you can use it.
Common mistakes:
- No answer for the end of the chain. A request that falls off the end returns
null, and the caller crashes somewhere else. - A class per role that differs only in a number.
ManagerApproverandDirectorApproverare one class with two configurations. - A shared check-then-act on state. Two claims with the same receipt on two threads both pass if "is it used?" and "mark it used" are separate steps.
- A handler with a side effect and no undo. If a later handler fails, the side effect stays, and the retry is judged against it.
Summary
- Use Chain of Responsibility when a request goes through a line of handlers of different kinds, and the first one that can decide, does.
- Put the walking in one base class with a
finalmethod, so handlers only decide or pass. - End every chain with a handler that always decides, and treat a chain without one as a bug.
- Build the chain in one place from data, and check the order before building it.
- If every handler would be the same class with different numbers, a sorted list and a loop are enough.
- A chain stops at one handler. Decorators run every layer.