Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Chapter mnemonic
Behavioural design patterns
Curious cats investigate missing milk. One spots squirrels towing vans.
Video lesson · Chapter 1 of 6
Make a prediction
Chain of responsibility
1:07Reel
Theory
Read or listen first. About 2 min.
What it is
Chain of responsibility is a behavioral design pattern. Objects that may be able to deal with a request are put in an order. The request goes to the first. Each object either deals with it or passes it on.
It is like a question in a classroom: you ask a friend, the friend does not know and asks another, who asks the teacher. The teacher answers, and you never had to know who would know.
Three flavours share the name. In dispatch one handler takes the request. In a filter each handler may refuse it. In a wrapping pipeline each handler works before and after the rest.
Why it exists
The sender is free of the receivers. It can be tested alone, and receivers can be added, removed and reordered without touching it.
Each rule lives in one class with one reason to change. The list of rules becomes a thing that can be built from configuration, printed, compared and reused.
Frameworks use it so that your code can stand in the middle of theirs: web middleware, interceptors, event handlers, log handlers.
A short history
1994
The book Design Patterns by Gamma, Helm, Johnson and Vlissides (published 31 October) describes the pattern under this name.
2000
DOM Level 2 Events becomes a W3C Recommendation on 13 November. It defines capturing and bubbling: an event travels along a chain of nodes, and a listener can stop it.
Servlet 2.3
The Java servlet API gains
FilterandFilterChain. The documentation of FilterChain marks it as present since version 2.3.
Words to know
- Handler
- An object that may take a request or pass it on.
- Successor
- The next handler in the order.
- Short circuit
- Stopping the chain early by not calling the next handler.
- Catch-all
- A last handler that takes everything.
- Middleware
- A link that receives the request and the rest of the chain as a function.
- Fail closed
- A link that cannot decide refuses. The opposite, fail open, lets the request through.
- Shadowed handler
- A handler that never gets a request because an earlier one takes all of them.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Request arrives. The sender gives it to the first handler
Understand it
Start here
Who should take this?
A request arrives. Several objects might be the right one to deal with it, and the sender does not know which. The pattern on this page lets the request travel past them, one after the other. Each one looks and decides: I take it, or I pass it on.
Each sieve knows one thing, the size of its holes. The sorting comes from the order in which they hang.
Four parts
Handler
The interface:
handle(request), and oftensetNext(handler). Examples:SupportHandler,Middleware,Validator,Approver.Base handler
Optional. It stores the next handler and passes on by default, so that the concrete classes hold only their rule.
Concrete handlers
One class per rule:
Level1,TokenCheck,ManagerApprover. Each decides alone.Client
Puts the chain together (or receives it) and sends requests to the first handler. It does not know who will answer.
Why
What goes wrong without it
An online shop checks every order before accepting it. The first version is one function, and it is fine. Then come gift orders, then retries after a failed payment, and each needs nearly the same checks.
BLOCKED = {"mallory"}def process_order(order): if not order["user"]: return "invalid user" if order["stock"] == 0: return "out of stock" if not order["card_ok"]: return "payment failed" if order["user"] in BLOCKED: # added last week return "fraud detected" return "order accepted"def process_gift_order(order): # copied last year if not order["user"]: return "invalid user" if order["stock"] == 0: return "out of stock" if not order["card_ok"]: return "payment failed" return "order accepted"order = {"user": "mallory", "stock": 3, "card_ok": True}print("normal:", process_order(order))print("gift: ", process_gift_order(order))Every rule is easy. The trouble is that the list of rules is not a thing. It exists only as the order of some if lines, copied into each function that needs it.
The design that hurts
1/3One method, two checks
It starts harmlessly. The service asks the user store and the stock.
uses
A chain
- One class per rule
- The list is data: it can be built, shown, changed and tested
- Two paths are two lists of the same handlers
- One rule, one small test
A list of ifs
- All rules live in one method
- Adding, removing or reordering a rule edits that method
- Another path means another copy
- One rule cannot be tested alone
The idea
Turn the list of ifs into a list of objects
Each handler holds a reference to the next one. handle does one of two things: answer, or call next.handle. Nobody sees the whole chain except the code that builds it.
The pattern in general
One critical ticket
Five tickets, one chain
| Ticket | Level 1 | Level 2 | Engineering | Triage | Handlers asked |
|---|---|---|---|---|---|
| LOW, password reset | takes it | 1 | |||
| MEDIUM, slow report | pass | takes it | 2 | ||
| HIGH, payments fail | pass | pass | takes it | 3 | |
| CRITICAL, server crash | pass | pass | takes it, pages someone | 3 | |
| UNKNOWN | pass | pass | pass | keeps it | 4 |
Two flavours
One takes it, or everybody does a bit
The classic form stops at the first handler that takes the request. Most chains in web frameworks are different: every handler does some work and then calls the next, unless it wants to stop. Both are called chain of responsibility, and an interviewer will ask which one you mean.
| Dispatch | Filter | Wrapping pipeline | |
|---|---|---|---|
| Question of each handler | Is it mine? | Is it all right? | What do I do before and after? |
| Usual result | One handler takes it | All pass, or the first refuses | All run, in and out again |
| Stops when | Somebody took it | Somebody refused | Somebody does not call next |
| End of the chain | Nobody wanted it: decide! | Accepted | The real work (endpoint) |
| Examples | Support desk, expense approval, event bubbling | Order validation, access checks | Django middleware, OkHttp interceptors |
Which flavour is it?
The order checks as a chain
1/3The service holds one check
It asks the first one and gets either a refusal or nothing. It no longer knows users, stock or payment.
usesextends (is a)
Building
A bug in nearly every fluent example
setNext often returns the handler it received, so that calls can be written one after the other. That makes one mistake very easy.
class Check: def __init__(self, name, ok): self.name, self.ok, self.next = name, ok, None def set_next(self, other): self.next = other return other # the new one, not self def handle(self, order): if not self.ok(order): return "refused by " + self.name return self.next.handle(order) if self.next else "accepted"def user(): return Check("user", lambda o: o["user"] != "")def stock(): return Check("stock", lambda o: o["stock"] > 0)def fraud(): return Check("fraud", lambda o: o["total"] < 5000)order = {"user": "", "stock": 1, "total": 10}chain = user().set_next(stock()).set_next(fraud()) # chain is the fraud check!print("wrong:", chain.handle(order))first = user()first.set_next(stock()).set_next(fraud())print("right:", first.handle(order))Who should know what comes next?
BreaksEach handler creates its successor
- How
Level1containsnew Level2().- Limit
- The order is welded into the classes. No second chain, no test alone, no removal.
- Choose when
- Never.
WorksLinked handlers with set_next
- How
- The client links objects that each hold
next. - Limit
- A handler object can be in one chain only. Relinking while requests are running is a race. Cycles are possible.
- Choose when
- Classic form, few handlers, built once at start.
StrongA list outside the handlers
- How
- A runner loops over an unchangeable list, or composes functions. Handlers do not know that they are in a chain.
- Limit
- Work after the next handler needs the composed form.
- Choose when
- The default in production: easy to print, share, swap and test.
Order
Order is behaviour
Two handlers may swap places only if no request could be taken by both. A catch-all in front takes everything. A cheap check should come before an expensive one. A check that protects something must come before the thing it protects.
| Rule | Good order | What the other order does |
|---|---|---|
| Special before general | Critical, then AnyTicket | The general one takes every critical ticket |
| Catch-all last | ... then Triage | Triage keeps everything, the others never run |
| Cheap before expensive | format check, then fraud service | You pay for a remote call to reject an empty form |
| Protection before work | rate limit, then login | An attacker makes you compute password hashes |
| Errors outermost | catch errors, then logging | An exception in logging escapes as a raw crash |
| Frequent first, if exclusive | Level1 for 70 percent | More handlers asked on average |
How many handlers are asked on average
Everyday code
Chains you already use
app.use(logger); // handler 1app.use(auth); // handler 2app.use(validate); // handler 3app.get("/api", handler); // the endpointfunction auth(req, res, next) { if (req.headers.authorization) { next(); // pass it on } else { res.status(401).send("Unauthorized"); // stop here }}next. The Express guide warns: if it does neither, the request is left hanging.Real authentication must of course verify the header, not only notice that it exists. The example shows the two exits.
A click climbs up
Where the shape appears
| Chain | Handlers | Stops when |
|---|---|---|
| Help desk | call centre, supervisor, manager, director | someone can help |
| Expense approval | manager, director, VP, CEO | the limit is high enough |
| Access | token, account, permission | a check refuses |
| Exceptions | catch blocks up the call stack | a type matches |
| Log records | logger, its parents | propagation is switched off |
| Class loading | parent loaders first | one finds the class |
Choosing
When to use it and when not
Use it when
- Several objects may handle a request and the right one is known only at run time
- You want to send without naming the receiver
- The set or the order of handlers is configured or changes
- Different paths need different selections of the same rules
Leave it when
- You know exactly who handles it: call them
- A key decides: a map from key to handler is direct and has no order
- Every rule must always run: use a plain loop and collect results
- Three ifs that never change and exist once
Chain, map or ifs?
The price
It may fall off the end
Nothing in the structure guarantees an answer. A last handler or an exception does.
Hard to follow
The code does not show who answers. Log the name of the handler that took it, and print the chain at start.
Order hides in wiring
Swapping two lines in a configuration changes behaviour without touching a class.
Linear and deep
n handlers mean up to n calls, and n frames on the stack. Fine for ten, wrong for ten thousand.
Summary
The whole topic in one minute.
Put the rules into handlers and the order into one place. Each handler takes the request or passes it on, and the sender knows only the first. Keep that first one: a fluent setNext returns the last.
Decide what the end means. In dispatch it is a problem and needs a catch-all or an exception. In a filter it means accepted. In a pipeline it is the endpoint.
In production: order is declared and checked at start, a running chain is replaced as a whole, security links fail closed, the trail names every handler asked, and thousands of rules get an index that keeps their order.
- Each handler takes the request or passes it on. The sender knows only the first.
- Name the flavour: dispatch, filter or wrapping pipeline.
- Decide and test what happens at the end of the chain.
- Order is behaviour: special first, catch-all last, protection before work.
- Build the chain in one place and keep the first handler, not what setNext returns.
- If one key decides, use a map.