Chain of Responsibility passes a request along a line of handler objects. Each handler either deals with the request or hands it to the next one, so the sender only talks to the first handler and never learns which one acted, or whether any did. Adding, removing or reordering handlers changes the chain, not the sender. It is the idea behind approval workflows, support escalation, event bubbling in UI trees and the middleware stacks of web servers.
Think of it like
Escalating a support call
You phone support and reach the first-line agent. If they can fix it from the script, they do. If not, they pass you to a specialist, who may pass you to an engineer. You never chose who would help you, and you did not need the org chart: you talked to whoever answered, and the request climbed until someone could handle it. Sometimes it reaches the top and the answer is "we cannot do that": the request fell off the end of the chain.
The problem
A company approves expenses by amount: a team lead signs up to 100, a manager up to 1000, a director up to 10000, and anything larger is not approved at this level. The first version is an ExpenseDesk that holds every approver and decides with an if/else ladder who signs. This is the Before version in the visualizer above.
class ExpenseDesk {
constructor(
private lead: TeamLead,
private mgr: Manager,
private dir: Director,
) {}
submit(amount: number): string {
// every limit, in a fixed order
if (amount <= 100) return this.lead.sign();
if (amount <= 1000) return this.mgr.sign();
if (amount <= 10000) return this.dir.sign();
return "unhandled";
}
}- The rules live in the wrong place. The approvers only know how to sign. The limits, which are really each approver's business, sit in the desk.
- The order is baked in. The checks only work in this order: put the 10000 test first and the director signs everything. Reordering, skipping a level for one department or adding one means editing
submit(). - Every new approver opens the hub. A department head means a new field, a new constructor parameter, a new rung in exactly the right place, and a change to every call that builds a desk.
- One class depends on everyone.
ExpenseDeskimports every approver class, so it changes whenever any of them does, and testing one rule means building the whole desk.
The pattern
Intent: avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle it. Chain the receiving objects and pass the request along the chain until an object handles it. The Gang of Four book introduced it with context-sensitive help in a user interface: a help request on a button goes to the dialog that contains it, then to the application, until some object has help to show.
- Handler (
Approver) - The common type every link shares. It holds the link to the next handler (
next), offers a way to set it (setNext()), and declares the request method (approve(amt)). - Concrete handler (
TeamLead,Manager,Director) - One class per rule. It checks whether the request is its own (here, whether the amount is within its limit). If so it handles it and stops; if not it passes the request to
next. - Successor link (
next) - A reference from one handler to the following one. The chain is just these references: an ordinary linked list of objects.
- Client
- Builds the chain (creates the handlers and links them in order) and sends every request to the first handler. It does not know which handler will act.
- Request
- Whatever travels down the chain: here a number, often an object carrying everything a handler needs to decide (an expense, an HTTP request, a UI event).
Two decisions move out of the old desk. Each handler now owns its own rule (is this mine?), and the client owns the order (who is asked next?). Neither the client nor any handler knows the whole chain: lead only knows mgr, and the client only knows lead. The visualizer at the top of the page runs exactly this code: press Play or step with the arrow buttons, and the caption under the stage explains every step.
What the visualizer shows
- Class diagram:
Approverhas a loop labelednexton its right side: a handler refers to another handler of the same abstract type. When a handler callsapprove()on itsnext, that loop lights up,Approverturns violet (the abstract class declares the method) and the class whose code actually runs is highlighted. - Objects at runtime: the chain is visible as fields,
lead.next = mgr,mgr.next = diranddir.next = null, with an arrow for each link. Watch the message travel down the column of handlers and the answer travel back up. - Sequence of calls: the strongest view. All four requests start with the same client call,
lead.approve(...), but the nested activation bars stop at different depths: 80 at the first lane, 700 at the second, 4000 at the third, and 25000 goes all the way down and comes back"unhandled". The Call stack panel lists the nested calls at each moment. - Before / With Chain of Responsibility and Add dept head: the toggle switches to the
ExpenseDeskversion, where every request is a single hop from the desk. Add dept head applies the change request to whichever version is shown; touched classes get a badge (new class, oredited +3 −0), and the Change request panel beside the code compares both versions. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create the handlers
With With Chain of Responsibility selected, the client creates
lead,mgranddir. Each starts withnext = null: a handler knows its own limit and nothing else. - 2
Link the chain
lead.setNext(mgr)storesmgrinlead.nextand returnsmgr, so the chained.setNext(dir)runs onmgr. The chain is nowlead → mgr → dir, and it was the client, not any handler, that chose this order. - 3
80: handled at the head
The client calls
lead.approve(80). 80 is within 100, soleadreturns"lead"at once. One call, one return;mgranddirnever see the request. - 4
700: one hop
leadcannot approve 700, so it callsmgr.approve(700)throughnext.mgrreturns"manager", andleadpasses that answer back to the client. Two activation bars deep. - 5
4000: two hops
leadpasses tomgr,mgrpasses todir, anddirreturns"director". The answer climbs back through both handlers. The client wrote exactly the same kind of call as for 80. - 6
25000: falls off the end
Every handler passes it on.
diris over its limit too and itsnextisnull, so it returns"unhandled", which travels back up to the client. Nothing threw an error; the client must check the result. - 7
Compare with Before
Switch to Before:
desk.submit()runs the ladder and calls exactly one approver'ssign(). The results are the same four answers, but every limit, and the order of the checks, is inExpenseDesk. - 8
Add dept head (change request)
With Add dept head applied to the chain version, the client creates
deptand the wiring line becomeslead.setNext(mgr).setNext(dept).setNext(dir). Now 4000 stops atdept(third link) anddiris never asked, while 25000 goes four links deep and still comes back"unhandled".
Before and after
Without the pattern
ExpenseDeskholds every approver and every limit- The order of the checks is fixed in one method
- A new approver edits the desk and its constructor
- Easy to read top to bottom while there are three rules
- Exactly one object is asked, after the desk decided
With Chain of Responsibility
- Each handler owns its rule; the client owns the order
- The order is data: the links between objects
- A new approver is a new class plus one wiring change
- To see the whole flow you have to follow the links
- The request visits handlers until one takes it, or none does
| Change request: add a department head (up to 5000) | Before | With Chain of Responsibility |
|---|---|---|
| Existing classes edited | 1 (ExpenseDesk) | 0 |
| New classes | 1 (DeptHead) | 1 (DeptHead) |
| Lines changed in existing classes | 3 (+3 −0) | 0 |
| Classes touched | 2 | 1 |
Both versions need a new class and both change the client: Before, the line that builds the desk; with the chain, the wiring line. The difference is the three lines inside ExpenseDesk: a field, a constructor parameter and a rung that must sit between the 1000 and 10000 checks. Put that rung one line lower and the department head never signs anything, with no error. With the chain, no existing handler is opened; the new class carries its own rule (which is why it is 9 lines against 5 in the Before version), and the place in the order is chosen where the chain is built.
Variations
Pure chain or pipeline
| Pure chain (GoF) | Pipeline or middleware | |
|---|---|---|
| Who acts | At most one handler: the first that can | Any number: each may do some work and pass the request on |
| Passing on | Only when the handler cannot help | The normal case; stopping is the exception (a short-circuit) |
| End of the chain | Reached only when nobody could handle it | Reached on every successful request: it is the real handler |
| Examples | Approvals, support escalation, GoF help handlers | Servlet filters, Express and Koa middleware, logging handlers |
A pipeline step that always calls the next one and adds work before or after it is structurally a Decorator. What makes a chain a chain is the ability to stop: a handler that answers itself and never calls next. That is why real middleware sits between the two patterns, as the Decorator lesson also points out. The second implementation below is such a pipeline: logging acts after the rest of the chain, authentication and Rate Limiting can short-circuit.
The chain does not have to be links inside the handlers. A dispatcher can hold an ordered list and ask each in turn: for (const h of handlers) if (h.canHandle(r)) return h.handle(r). Handlers stay unaware of each other and the list is easy to inspect, log and reorder. The price is that a handler can no longer do work around the rest of the chain (before and after calling next), which is what middleware relies on. The pipeline implementation below keeps an array and passes each handler a next function, which gives you both.
A base class with a default pass-through
In the visualizer every handler ends with the same forwarding line, return this.next?.approve(amt) ?? "unhandled". Real code moves that line into the base class as the default behavior, so a concrete handler only writes its own check and calls super for everything else. A handler that should never act (a logging or metrics step in a pure chain) then needs no approve() at all. The first implementation below is written this way.
abstract class Approver {
private next: Approver | null = null;
setNext(handler: Approver): Approver {
this.next = handler;
return handler;
}
// default: pass it on, or give up at the end
approve(amount: number): string | null {
return this.next ? this.next.approve(amount) : null;
}
}
class TeamLead extends Approver {
approve(amount: number): string | null {
if (amount <= 100) return "team lead";
return super.approve(amount); // not mine
}
}When nobody handles the request
- Return "nothing".
null, an emptyOptionalor a result type, as the visualizer and the implementations do. Cheap, but easy to ignore: the caller must check it. - Put a default handler at the end. A final handler that accepts everything ("send to the board", "404 Not Found", a generic help page) guarantees an answer. Web frameworks do this with a not-found handler after all the routes.
- Throw. If an unhandled request is a bug, fail loudly with an exception from the last link or from the client.
- Validate when building. If every request must be handled, check when the chain is assembled that some handler covers every case (here: that the last limit is high enough, or that a catch-all is present).
Order, cycles and building the chain from configuration
Order matters whenever two handlers could both accept a request: the first one wins. In the approval chain the limits are ascending, so a smaller approver must come first; reversed, the director would approve everything. Because the order is now data, it can come from configuration. When handlers differ only in data (a title and a limit) a single configurable class is enough, and the chain is built in a loop:
function buildChain(config: Array<[string, number]>): Approver {
if (config.length === 0) throw new Error("empty chain");
const handlers = config.map(([t, l]) => new LimitApprover(t, l));
for (let i = 0; i + 1 < handlers.length; i++) {
handlers[i].setNext(handlers[i + 1]);
}
return handlers[0];
}
const chain = buildChain([
["team lead", 100],
["manager", 1000],
["director", 10000],
["board", 1_000_000],
]);In real code
| Where | The chain | How a handler passes or stops |
|---|---|---|
| Java servlets | Filter objects in a FilterChain, ending at the servlet | A filter calls chain.doFilter(request, response) to pass on; not calling it (and writing a response instead) stops the request |
| Express and Koa (Node.js) | Middleware functions registered with app.use() | Express middleware calls next() to pass on or sends a response to stop; Koa middleware does await next() and can act before and after it |
| The DOM | An event's propagation path: the target, then each ancestor up to the document | Listeners on each ancestor see a bubbling event in turn; stopPropagation() ends the trip |
java.util.logging | Loggers named in a hierarchy (com.app.db has parent com.app) | A log record goes to the logger's own handlers, then up to its parent's, unless setUseParentHandlers(false) was called |
| Exceptions | The call stack | A thrown exception travels up through callers until one has a matching catch; uncaught, it reaches the top |
| Approval and escalation workflows | Levels of authority, support tiers | Each level approves within its limit or escalates; the top level may reject |
The DOM and logging examples are the pipeline flavor: every listener or handler on the path may act. Exceptions are the pure flavor: the first matching catch handles it and the search stops. Loggers that pass records along a chain are also the core of the Design a Logging Framework design exercise, and in a distributed system the same "pass it through a chain of checks" idea sits at the edge, in an API Gateway & Backend for Frontend that authenticates, rate-limits and routes before any service sees the request.
When to use it, and when not to
Reach for Chain of Responsibility when
- Several objects may handle a request, and which one is decided at runtime
- The set of handlers or their order should change without editing the sender
- You want to add cross-cutting steps (auth, logging, limits) to request processing
- Requests naturally escalate: levels of approval, support tiers, a UI tree
- The chain should be assembled from configuration
Think twice when
- Exactly one known object should handle each request: call it directly
- Handlers are chosen by a simple key: a map from key to handler is clearer and constant time
- Every request must be handled and a gap would be a silent bug, unless you add a catch-all
- The chain is long and hot, so visiting every link costs too much
- Every handler must receive the request: that is Observer, not a chain
- Harder to follow. No single method says who handles what; the answer depends on how the chain was built at runtime. Log the handler that acted (and, when debugging, each one that passed) so a request's path can be reconstructed.
- Long chains cost time. A request that matches late visits every earlier handler, so the cost is linear in the chain's length, and each link is a stack frame in the recursive form. For long chains with simple keys, a lookup table (a map from type to handler) may be the better design.
- Silent drops. A request that matches nothing produces no error unless you plan for it (see above).
Chain of Responsibility vs similar patterns
| Pattern | Structure | Who handles the request | The difference |
|---|---|---|---|
| Chain of Responsibility | A line of handlers, each with a next | Usually the first one that can (or each in turn, in a pipeline) | A handler may stop the chain; the request may go unhandled |
| Decorator | Wrappers, each holding one inner object | All of them: each adds behavior and always delegates | Same shape, but a decorator never swallows the call |
| Command | A request turned into an object | Whoever runs it | Often what travels down a chain: the request object a handler inspects |
| Observer | A subject with a list of subscribers | Every subscriber | Broadcast to all, not offered to each until one accepts |
| Composite | A tree of parts and wholes | The parent links form a chain upward | Requests often bubble from a child to its parents, as in the GoF help example and the DOM |
| Mediator | A hub that knows the participants | The mediator decides who acts | Central routing logic, instead of each handler deciding for itself |
Implementation
The scenario as a complete program, with the forwarding written once in the base class: Approver holds next, setNext returns its argument so links can be chained, and the default approve passes the request on or returns nothing at the end of the chain. TeamLead, Manager, DeptHead and Director each check their own limit and otherwise call the base version. The demo runs 80, 700, 4000 and 25000 through lead, manager and director, inserts a department head by changing only the wiring, and then builds the same kind of chain from a configuration list of titles and limits, with a board at the end so nothing falls off.
# Chain of Responsibility: expense approval by amount.
from __future__ import annotations
from typing import Optional
class Approver:
def __init__(self) -> None:
self._next: Optional[Approver] = None
def set_next(self, handler: Approver) -> Approver:
"""Links the next handler and returns it, so calls can chain."""
self._next = handler
return handler
def approve(self, amount: int) -> Optional[str]:
"""Default: pass the request on, or give up at the end."""
return self._next.approve(amount) if self._next else None
class TeamLead(Approver):
def approve(self, amount: int) -> Optional[str]:
if amount <= 100:
return "team lead"
return super().approve(amount) # not mine: pass it on
class Manager(Approver):
def approve(self, amount: int) -> Optional[str]:
if amount <= 1000:
return "manager"
return super().approve(amount)
class DeptHead(Approver):
def approve(self, amount: int) -> Optional[str]:
if amount <= 5000:
return "dept head"
return super().approve(amount)
class Director(Approver):
def approve(self, amount: int) -> Optional[str]:
if amount <= 10000:
return "director"
return super().approve(amount)
class LimitApprover(Approver):
"""One handler class configured with data: the chain from config."""
def __init__(self, title: str, limit: int) -> None:
super().__init__()
self.title = title
self.limit = limit
def approve(self, amount: int) -> Optional[str]:
if amount <= self.limit:
return self.title
return super().approve(amount)
def build_chain(config: list[tuple[str, int]]) -> Approver:
if not config:
raise ValueError("empty chain")
handlers = [LimitApprover(title, limit) for title, limit in config]
for current, following in zip(handlers, handlers[1:]):
current.set_next(following)
return handlers[0]
def submit(chain: Approver, amount: int) -> None:
who = chain.approve(amount)
if who:
print(f" {amount}: approved by {who}")
else:
print(f" {amount}: unhandled, send it to the board")
if __name__ == "__main__":
lead, mgr, director = TeamLead(), Manager(), Director()
lead.set_next(mgr).set_next(director)
print("team lead -> manager -> director")
for amount in (80, 700, 4000, 25000):
submit(lead, amount)
# Change request: insert a department head. Only the wiring changes.
mgr.set_next(DeptHead()).set_next(director)
print("team lead -> manager -> dept head -> director")
for amount in (4000, 25000):
submit(lead, amount)
# The same chain, read from configuration instead of code.
from_config = build_chain([
("team lead", 100),
("manager", 1000),
("director", 10000),
("board", 1_000_000),
])
print("built from config, with a board at the end")
for amount in (700, 25000):
submit(from_config, amount)Key takeaways
- Chain of Responsibility sends a request to the first of a line of handlers; each one handles it or passes it to
next, so the sender never knows which handler acted. - Each handler owns its own rule and the client owns the order. In the visualizer every request is the same call,
lead.approve(...), and only the depth of the nested calls changes. - A request can fall off the end unhandled. Plan for it: a result the caller must check, a catch-all handler at the end, or an exception.
- For the "add a department head" request, the chain adds one class and changes the wiring line; the if/else version also edits
ExpenseDesk(+3 lines), where a rung in the wrong place silently breaks the rules. - Pure chains stop at the first handler that acts; pipelines and middleware let every handler act and stop only to short-circuit, which puts them between this pattern and Decorator.
- Order matters, cycles loop forever, and long chains are slower and harder to debug: build the chain in one place, ideally from configuration, and log which handler acted.
Common pitfalls
- Ignoring the unhandled case: the request reaches the end,
nullcomes back, and the caller treats it as success or crashes later. Decide explicitly what the end of the chain means. - Putting handlers in the wrong order when their conditions overlap. With limits, a broad handler placed first (the director) takes every request meant for the narrower ones.
- A handler that forgets to forward (or forwards twice). In middleware, a missing
next()call leaves the request hanging, and calling it twice runs the rest of the chain twice. - Linking handlers into a cycle through scattered
setNext()calls, so an unhandled request never ends. - Using a chain where a lookup would do: if the handler is chosen by an exact key such as a message type, a map from key to handler is simpler, faster and easier to read.
Interview tips
- In LLD rounds with approvals, escalation, ATM cash dispensing (notes of each denomination as handlers) or request filtering, sketch an abstract handler with
next,setNext()andhandle(), then two or three concrete handlers and the client that wires them. - Say what happens when nobody handles the request, and how you would build the chain from configuration so a new level does not need code changes in the sender.
- Expect "how is this different from Decorator?" (a handler may stop the chain; a decorator always delegates) and from Observer (one handler versus every subscriber). Mention middleware as the real-world mix.
Real-world applications
- Approval workflows: purchase and expense approval by amount, leave requests, code review sign-offs by level.
- Support and incident escalation: first line, specialist, engineering, management.
- Web servers and frameworks: servlet filters, Express, Koa and ASP.NET Core middleware for authentication, logging, compression and error handling.
- UI event handling: events bubbling from a widget to its containers until one handles them, and context-sensitive help.
- Logging frameworks where records pass from a logger to its parents' handlers.
- Validation and fraud checks: a series of rules, each able to reject a transaction early.
Test yourself
In the visualizer, the client calls lead.approve(4000) on the chain lead → mgr → dir. What happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.