Chain of Responsibility Pattern
Chain of Responsibility links handlers into a sequence and hands a request to the first one. Each handler either deals with it or passes it to its successor, so the sender holds one reference – the head – and never learns which object did the work.
Why this matters: the handler classes are the easy part. What gets graded is where the chain is assembled, what happens when nobody handles the request, and whether a half-finished walk leaves the system broken.
Prerequisites
- Inheritance vs Composition – a handler holds the next by composition, which makes a chain reorderable
- Decorator Pattern – the same wrapping shape, and half of this lesson
- SOLID Principles – a new handler is a new class, not an edit
The Problem: the ATM dispenser as a cascade of if blocks
An ATM breaks a withdrawal into notes. Four denominations, four blocks, each running the same divide-remainder-decrement arithmetic with a different constant:
public class ATM {
private int count2000 = 10, count500 = 20, count200 = 25, count100 = 50;
public void withdraw(int amount) {
if (amount % 100 != 0) throw new InvalidAmountException(amount);
if (amount >= 2000) {
int notes = Math.min(amount / 2000, count2000);
count2000 -= notes; amount -= notes * 2000; // till already mutated
dispenseNotes(2000, notes);
}
if (amount >= 500) {
int notes = Math.min(amount / 500, count500);
count500 -= notes; amount -= notes * 500;
dispenseNotes(500, notes);
}
if (amount >= 200) {
int notes = Math.min(amount / 200, count200);
count200 -= notes; amount -= notes * 200;
dispenseNotes(200, notes);
}
if (amount >= 100) {
int notes = Math.min(amount / 100, count100);
count100 -= notes; amount -= notes * 100;
dispenseNotes(100, notes);
}
if (amount > 0) { // checked far too late
throw new InsufficientCashException(amount);
}
}
}
It works. It is also three separate problems:
- Adding a denomination means editing a working method. The ₹50 note returns and the diff lands among four blocks that already dispense correctly.
- The order is load-bearing and invisible. Largest-first is the requirement and nothing in the code says so. Move the ₹100 block up and withdrawals drain small notes.
- The failure check runs after the till is mutated. When
amount > 0throws, four counters are already decremented: the withdrawal failed and the books are wrong.
Class Diagram
classDiagram
class CashDispenser {
<<abstract>>
-CashDispenser next
#int denomination
#int available
+setNext(next) CashDispenser
+canDispense(amount) boolean
+dispense(amount, tally)
#notesToUse(amount) int
}
class Note2000Dispenser {
#notesToUse(amount) int
}
class Note500Dispenser
class ATM {
-CashDispenser head
+withdraw(amount) NoteTally
}
ATM --> CashDispenser : head
CashDispenser --> CashDispenser : next
CashDispenser <|-- Note2000Dispenser
CashDispenser <|-- Note500Dispenser
The self-loop is the pattern, and the only structural thing it adds over ordinary polymorphism. It is why ATM holds one reference and knows neither how many handlers exist nor in what order.
Real-World Example: ATM Cash Dispenser
The walk happens twice. A dry run asks the chain “between you, can you make this amount?” and touches nothing; only once that returns true does a second walk decrement tills, so a failed withdrawal leaves the machine unchanged.
💡 Two-phase here means ask-then-act in one process: a read-only canDispense walk, then a mutating dispense walk. Not distributed 2PC. Learn more →
// Abstract handler: owns the successor link and both walks.
public abstract class CashDispenser {
private CashDispenser next;
protected final int denomination;
protected int available;
protected CashDispenser(int denomination, int available) {
this.denomination = denomination;
this.available = available;
}
public CashDispenser setNext(CashDispenser next) {
this.next = next;
return next; // returning next lets a chain assemble fluently
}
// The only override point: sees the amount and its own till, never next.
protected int notesToUse(int amount) {
return Math.min(amount / denomination, available);
}
// Phase 1: dry run. Walks the chain and mutates nothing.
public final boolean canDispense(int amount) {
int remaining = amount - notesToUse(amount) * denomination;
if (remaining == 0) return true;
return next != null && next.canDispense(remaining);
}
// Phase 2: commit. Only called once canDispense returned true.
public final void dispense(int amount, Map<Integer, Integer> tally) {
int notes = notesToUse(amount);
available -= notes;
if (notes > 0) tally.put(denomination, notes);
int remaining = amount - notes * denomination;
if (remaining == 0) return;
if (next == null) throw new IllegalStateException("short " + remaining);
next.dispense(remaining, tally);
}
}
// A handler with a policy: hold large notes back for later customers.
public class Note2000Dispenser extends CashDispenser {
public Note2000Dispenser(int available) { super(2000, available); }
@Override
protected int notesToUse(int amount) {
return Math.min(super.notesToUse(amount), 5);
}
}
// No policy -- the entire cost of adding a denomination.
public class Note500Dispenser extends CashDispenser {
public Note500Dispenser(int available) { super(500, available); }
}
public class ATM {
private final CashDispenser head;
// Assembly in exactly one place, so largest-first is a fact you can read.
public ATM() {
head = new Note2000Dispenser(10);
head.setNext(new Note500Dispenser(20))
.setNext(new Note200Dispenser(25))
.setNext(new Note100Dispenser(50));
}
public Map<Integer, Integer> withdraw(int amount) {
if (amount <= 0 || amount % 100 != 0) throw new InvalidAmountException(amount);
if (!head.canDispense(amount)) {
throw new InsufficientCashException(amount); // tills untouched
}
Map<Integer, Integer> tally = new TreeMap<>(Comparator.reverseOrder());
head.dispense(amount, tally); // cannot fail now
return tally;
}
}
from abc import ABC
from typing import Optional
class CashDispenser(ABC):
"""Abstract handler: owns the successor link and both walks."""
def __init__(self, denomination: int, available: int) -> None:
self._denomination = denomination
self._available = available
self._next: Optional['CashDispenser'] = None
def set_next(self, nxt: 'CashDispenser') -> 'CashDispenser':
self._next = nxt
return nxt # returning next lets chains assemble fluently
def _notes_to_use(self, amount: int) -> int:
return min(amount // self._denomination, self._available)
def can_dispense(self, amount: int) -> bool:
remaining = amount - self._notes_to_use(amount) * self._denomination
if remaining == 0:
return True
return self._next is not None and self._next.can_dispense(remaining)
def dispense(self, amount: int, tally: dict[int, int]) -> None:
notes = self._notes_to_use(amount)
self._available -= notes
if notes:
tally[self._denomination] = notes
remaining = amount - notes * self._denomination
if remaining == 0:
return
if self._next is None:
raise RuntimeError(f"short {remaining}")
self._next.dispense(remaining, tally)
class PlainDispenser(CashDispenser):
"""Any denomination with no policy of its own."""
class Note2000Dispenser(PlainDispenser):
def _notes_to_use(self, amount: int) -> int:
return min(super()._notes_to_use(amount), 5) # hold large notes back
def withdraw(amount: int) -> dict[int, int]:
head = Note2000Dispenser(2000, 10) # assembled in one place
head.set_next(PlainDispenser(500, 20)) \
.set_next(PlainDispenser(200, 25)) \
.set_next(PlainDispenser(100, 50))
if not head.can_dispense(amount): # phase 1, tills untouched
raise InsufficientCashError(amount)
tally: dict[int, int] = {}
head.dispense(amount, tally) # phase 2, cannot fail now
return tally
#include <algorithm>
#include <map>
#include <memory>
// The request the chain walks. dryRun folds both phases into one method.
struct WithdrawalRequest {
int remaining;
std::map<int, int> tally;
bool dryRun;
};
class CashDispenser {
protected:
int denomination_;
int available_;
std::shared_ptr<CashDispenser> next_;
virtual int notesToUse(int amount) const {
return std::min(amount / denomination_, available_);
}
public:
CashDispenser(int denomination, int available)
: denomination_(denomination), available_(available) {}
virtual ~CashDispenser() = default;
std::shared_ptr<CashDispenser> setNext(std::shared_ptr<CashDispenser> next) {
next_ = std::move(next);
return next_;
}
/// True when this handler or a successor fully satisfies the request.
bool handle(WithdrawalRequest& request) {
const int notes = notesToUse(request.remaining);
if (!request.dryRun && notes > 0) {
available_ -= notes;
request.tally[denomination_] += notes;
}
request.remaining -= notes * denomination_;
if (request.remaining == 0) return true;
return next_ && next_->handle(request);
}
};
class Note2000Dispenser : public CashDispenser {
public:
explicit Note2000Dispenser(int available) : CashDispenser(2000, available) {}
protected:
int notesToUse(int amount) const override { // hold large notes back
return std::min(CashDispenser::notesToUse(amount), 5);
}
};
std::map<int, int> withdraw(const std::shared_ptr<CashDispenser>& head, int amount) {
WithdrawalRequest probe{amount, {}, true}; // phase 1: reads only
if (!head->handle(probe)) throw std::runtime_error("insufficient cash");
WithdrawalRequest commit{amount, {}, false}; // phase 2: writes
head->handle(commit);
return commit.tally;
}
The walk is greedy, which is worth saying before the interviewer does. ₹600 from a till holding one ₹500 and three ₹200 notes fails, because the ₹500 goes first and leaves ₹100 nothing can cover. The optimal split is a change-making problem for a solver the chain calls.
Two chains, and they are not the same
Two very different structures travel under this name, and conflating them is how candidates lose the follow-up.
The first-match chain. One handler deals with the request and the walk stops; nobody downstream sees it. The result is handled or not handled – exception handlers, ticket escalation from L1 to L2. The ATM is a hybrid, short-circuiting once the remainder hits zero yet letting several handlers contribute.
The pipeline chain. Every handler runs, each free to read, transform or veto, and the call to next is a statement the handler chooses to make. The result is a transformed request – servlet filters, middleware, validation chains, the logger-level chain.
GoF describes the first; almost every chain you have used in production is the second. And the second is a Decorator in different clothes, since each link implements the same interface as the thing it holds and always forwards. So the honest answer to “Chain vs Decorator” is that the distinction is real for first-match chains and cosmetic for pipelines.
The invariant that makes either safe: a handler decides using only the request and its own state, never knowledge of who comes after it. The moment Note500Dispenser contains “if the ₹200 till is low, take more here”, the chain stops being reorderable and the if-cascade is back, spread over four files.
Chain of Responsibility vs Decorator vs Command vs Strategy vs Specification
All five turn up around a request. Each answers a different question about it:
| Pattern | Intent | Tell |
|---|---|---|
| Chain of Responsibility | Decide who handles it | Sender holds one reference, cannot name who acts |
| Decorator | Add behavior, same interface | Every link runs and forwards; none short-circuits |
| Command | Package the request as an object | The interesting class is the request, not the handler |
| Strategy | Decide how a handler works | One implementation, chosen up front by the caller |
| Specification | Answer a boolean about it | Returns true or false, never acts |
They stack rather than compete: a pipeline often carries a Command as its request, each link consults a Specification to decide whether it applies, and the matching link delegates to a Strategy.
When to Use vs When to Avoid
| Use Chain of Responsibility When | Avoid When |
|---|---|
| The set of handlers grows over time | Two cases, where an if/else reads better |
| The sender must not know who will act | The caller already knows who should act |
| Handlers have a priority or fallback order | Order is irrelevant, so a loop is simpler |
| Each handler’s rule is testable alone | Handlers would have to coordinate |
| Cross-cutting steps compose per route | Dispatch is a lookup on a key the request carries |
The characteristic failure mode is the unterminated chain: the last handler’s next is null, nothing matched, the method returns, and no exception, log or metric records it. It surfaces weeks later as “some notifications never arrive”. Two fixes – a terminal handler that always matches and throws, logs or dead-letters the request (the Null Object trick), or a return type that carries the outcome, an Optional<Result> or an explicit Unhandled. The ATM takes the second, since canDispense returning false is the unhandled result. The other cost is debugging: nine handlers make nine near-identical stack frames and the one that mattered did nothing, which is the argument against a chain for two cases.
Interview Questions
-
“Chain of Responsibility vs Decorator?” – Intent and short-circuiting, since both hold a successor and both forward. A Decorator always forwards, so removing one changes how the call behaves rather than who answers it; a chain stops once a handler claims the request. A pipeline chain, though, is a Decorator with the field renamed, and admitting that beats defending a distinction that is not there.
-
“How do you keep the chain order correct and testable?” – Assemble it in one factory or builder, so there is a single file to open when the order is wrong, and never let a handler call
setNexton itself at runtime. Then stop treating construction sequence as the specification: give each handler an explicitorder()value and have the builder sort by it, which turns the constraint into data you can assert on. -
“Should a handler be able to re-enter or reorder the chain?” – No. A handler that reaches back up or re-dispatches to a named sibling needs the whole topology, and the chain’s one invariant goes with it. When the flow genuinely needs that, the right shape is a Mediator holding the routing rules or a state machine.
-
“How do you make a chain thread-safe when handlers hold mutable state like a cash till?” – Either make handlers stateless and push state outside, so the till becomes a repository with its own concurrency control, or keep state in the handler and take one lock at the chain entry. If you lock, it must span both phases: a dry run not held against the commit is a stale read and a check-then-act race. See Concurrency.
-
“When is a chain the wrong structure?” – Every request walks O(n) links, fine when n is small and each handler must evaluate a predicate to know whether it applies. It is wrong the moment dispatch is a lookup on a key the request already carries, since a
Map<Type, Handler>answers that in O(1) with no ordering question at all.
See It in Action
- ATM Machine – one
CashDispenserper denomination, two-phase dry run - Logging Framework – the level chain, a pipeline not a first-match
- Notification Service – channel fallback: push, SMS, email
- Discount Engine – stacked rules, each deciding if it applies