AlgoViz

Chain of responsibility

medium 45 min

A 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

0:00 / 4:36

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

  1. 1994

    The book Design Patterns by Gamma, Helm, Johnson and Vlissides (published 31 October) describes the pattern under this name.

  2. 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.

  3. Servlet 2.3

    The Java servlet API gains Filter and FilterChain. 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.

Step 1 of 3

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.

The mountain of sieves
5030hole 40hole 20hole 5

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 often setNext(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.

Python
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))
Run it. The fraud check was added to one path and forgotten in the other. The second order goes through.
Edit and run it in your browser

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

OrderService+ process(): 4 ifs+ processGift(): 3 ifs+ processRetry(): 2 ifsUserStore+ exists(user)Stock+ available(items)

1/3One method, two checks

It starts harmlessly. The service asks the user store and the stock.

uses

The smell: a sequence of unrelated checks in one method, and a second method with nearly the same sequence.

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

firstClient+ sends request«interface»Handler+ setNext(h): Handler+ handle(request)

1/3Sender and contract

The client holds one reference, of the interface type: the first handler.

usesimplementshas (lives on)extends (is a)

Is a and has a on the same interface: remember this shape. Decorator and Composite share it with other intentions.

One critical ticket

The answer walks back the same way. Each handler is still on the call stack until the last one has finished.

Five tickets, one chain

TicketLevel 1Level 2EngineeringTriageHandlers asked
LOW, password resettakes it1
MEDIUM, slow reportpasstakes it2
HIGH, payments failpasspasstakes it3
CRITICAL, server crashpasspasstakes it, pages someone3
UNKNOWNpasspasspasskeeps it4
Without the triage handler the last row ends in an exception. That is a decision too, and it has to be written down.

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.

DispatchFilterWrapping pipeline
Question of each handlerIs it mine?Is it all right?What do I do before and after?
Usual resultOne handler takes itAll pass, or the first refusesAll run, in and out again
Stops whenSomebody took itSomebody refusedSomebody does not call next
End of the chainNobody wanted it: decide!AcceptedThe real work (endpoint)
ExamplesSupport desk, expense approval, event bubblingOrder validation, access checksDjango middleware, OkHttp interceptors
Reaching the end is bad news in the first column and good news in the second.

Which flavour is it?

The order checks as a chain

firstOrderService+ process(order)«abstract»OrderCheck- next: OrderCheck+ check(o): Refusal?# refuse(o): Refusal?

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)

Gift orders use the same handlers in another list. The forgotten check is now a visible line in a list.

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.

Python
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))
Run it. The variable holds the last check, so a user without a name gets through. Keep the first handler, or use a function that builds the chain and returns the first.
Edit and run it in your browser

Who should know what comes next?

BreaksEach handler creates its successor
How
Level1 contains new 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.

RuleGood orderWhat the other order does
Special before generalCritical, then AnyTicketThe general one takes every critical ticket
Catch-all last... then TriageTriage keeps everything, the others never run
Cheap before expensiveformat check, then fraud serviceYou pay for a remote call to reject an empty form
Protection before workrate limit, then loginAn attacker makes you compute password hashes
Errors outermostcatch errors, then loggingAn exception in logging escapes as a raw crash
Frequent first, if exclusiveLevel1 for 70 percentMore handlers asked on average

How many handlers are asked on average

0.70⋅1+0.20⋅2+0.09⋅3+0.01⋅4=1.410.70 \cdot 1 + 0.20 \cdot 2 + 0.09 \cdot 3 + 0.01 \cdot 4 = 1.41
Assumed mix: 70 percent LOW, 20 MEDIUM, 9 HIGH or CRITICAL, 1 unknown. With Engineering first and Level 1 third it would be 0.09 x 1 + 0.20 x 2 + 0.70 x 3 + 0.01 x 4 = 2.63.

Everyday code

Chains you already use

TypeScript
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  }}
Express middleware. Each function either ends the answer or calls 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

Event bubbling: the chain is the tree of parents, nobody had to build it. By default bubbling continues after a listener ran, so it is closer to the pipeline flavour.

Where the shape appears

ChainHandlersStops when
Help deskcall centre, supervisor, manager, directorsomeone can help
Expense approvalmanager, director, VP, CEOthe limit is high enough
Accesstoken, account, permissiona check refuses
Exceptionscatch blocks up the call stacka type matches
Log recordslogger, its parentspropagation is switched off
Class loadingparent loaders firstone 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 support desk of this page has a key, the priority. With nothing else it should be a map. It earns the chain when a rule looks at more than the priority.

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.

Sources