Coding

Chain of Responsibility Pattern Explained, With Code

The chain of responsibility pattern passes a request along a line of handlers, and each handler either processes the request or hands it to the next one. The sender only talks to the first handler and does not need to know which one finally does the work.

It is one of the classic behavioral design patterns. You will recognise it in approval workflows, event bubbling, logging levels and web server middleware, even when the code never uses the pattern's name.

What is the chain of responsibility pattern?

The pattern turns a set of checks or processing steps into separate objects (or functions) that are linked together. A request enters at the head of the chain. Each handler looks at it and makes one of two decisions: handle it, or forward it. Refactoring Guru describes the intent as letting you pass requests along a chain of handlers, where each handler decides either to process the request or to pass it to the next handler in the chain.

The problem it solves is a growing pile of conditional logic. Imagine an order system that has to authenticate the caller, check permissions, sanitize input, apply rate limiting and look in a cache, in that order. If all of that lives in one function, every new check makes the function longer, and one change can break another check. Splitting each check into its own handler keeps each piece small and lets you reuse a check somewhere else without copying it.

The parts of the pattern

PartRole
HandlerThe shared interface: a method that takes a request, and usually a way to set the next handler.
Base handler (optional)Stores the reference to the next handler and holds the default "forward it" behavior.
Concrete handlersThe classes with the real logic. Each decides whether to process the request and whether to pass it on.
ClientBuilds the chain, once or dynamically, and sends the request into it.

Per the same source, the client can send a request to any handler in the chain, not only the first one. That is useful when you want to start partway down the line.

Chain of responsibility example in Python

This example models an expense approval. A team lead can approve up to 1,000, a manager up to 10,000, and a director up to 100,000. Anything above that is not approved by anyone in the chain. The amounts are made up for the demonstration.

from __future__ import annotations


class Approver:
    """Base handler: stores the next link and forwards by default."""

    def __init__(self, title: str, limit: int) -> None:
        self.title = title
        self.limit = limit
        self.next_approver: Approver | None = None

    def set_next(self, approver: Approver) -> Approver:
        self.next_approver = approver
        return approver  # lets you chain set_next calls

    def handle(self, amount: int) -> str:
        if amount <= self.limit:
            return f"{self.title} approved {amount}"
        if self.next_approver is not None:
            return self.next_approver.handle(amount)
        return f"Unhandled: {amount}"


team_lead = Approver("TeamLead", 1_000)
manager = Approver("Manager", 10_000)
director = Approver("Director", 100_000)

team_lead.set_next(manager).set_next(director)

for amount in (500, 5_000, 50_000, 500_000):
    print(team_lead.handle(amount))

Example output, worked out from the code above:

TeamLead approved 500
Manager approved 5000
Director approved 50000
Unhandled: 500000

The client only ever calls team_lead.handle(...). Adding a new level, say a vice president at 1,000,000, means creating one more Approver and linking it after the director. Nothing else changes. That is the Open/Closed benefit the pattern is known for: new handlers can be added without breaking the existing client code.

The last line of handle shows the pattern's weak spot. When the request reaches the end of the chain, the code has to decide what an unhandled request means. Here it returns a string. In real code you would more likely raise an exception or return a result type that the caller must check.

Chain of responsibility in Express middleware

Web frameworks are where most developers meet this shape every day. In Express, the third argument passed to a middleware function is next. The Express documentation describes it as a function that, when invoked, executes the middleware succeeding the current middleware. Middleware functions run in the order they are loaded, so registration order is chain order.

const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('LOGGED');
  next();            // pass control to the next handler
});

app.get('/', (req, res) => {
  res.send('Hello World!');   // ends the cycle, no next() needed
});

app.listen(3000);

Two rules from the Express documentation map directly onto the pattern:

  • A handler must either end the request or forward it. If a middleware function does not end the request-response cycle, it must call next(). Otherwise the request is left hanging. This is the "forgot to forward" bug, and it is the most common mistake with chains of any kind.
  • Order decides who sees the request. If a logging middleware is registered after a route that already sends a response, the request never reaches it, because the route handler terminates the cycle.

Express also adds a twist the textbook pattern lacks. If you pass anything to next() other than the strings 'route' or 'router', Express treats the request as an error and skips the remaining non-error handlers. In effect there is a second chain, made of error-handling middleware, that the request jumps to.

Note the difference from the approval example. There, exactly one handler acts and the chain stops. In middleware, most handlers do a small piece of work (log, parse, authenticate) and forward, and the last one responds. Both are legitimate uses of the same structure.

When to use it

Refactoring Guru lists three situations where the pattern fits:

  • Your program handles different kinds of requests in different ways, and the types and sequences are not known in advance.
  • Several handlers must run in a specific order.
  • The set of handlers and their order may change at runtime.

The same source lists the benefits as control over processing order, single responsibility (the classes that invoke operations are separated from those that perform them) and the open/closed property described above.

Drawbacks and pitfalls

  • Unhandled requests. The source names this as the one downside: a request can reach the end without anyone processing it. Add a default handler at the tail, or make the end of the chain an explicit error.
  • Silent hangs. A handler that neither responds nor forwards stops the chain without any error. Test each handler for both paths.
  • Hard-to-follow flow. The behavior depends on how the chain was assembled, so reading one handler tells you little about what runs before or after it. Build the chain in one place and keep it short.
  • Wrong order. Putting an expensive check before a cheap rejecting check wastes work, and putting authentication after a handler that serves data is a security bug. Treat the order as part of the design.

If you only have a few steps

A chain is not always worth it. If you have two or three fixed checks that never change order, a plain function with early returns is simpler and easier to read. Reach for the pattern when handlers are added, removed or reordered often, or when different callers need different chains built from the same pieces.

Frequently asked questions

What is the chain of responsibility pattern in simple terms?
It is a behavioral design pattern where a request is passed along a line of handlers. Each handler either processes the request or forwards it to the next handler, so the sender does not need to know which handler will end up doing the work.
Does exactly one handler have to process the request?
No. In the classic form one handler processes the request and stops the chain. In other variants, such as web middleware, every handler does a little work and passes the request on, and only the last one produces the final response.
What happens if no handler can process the request?
The request falls off the end of the chain unhandled. This is the main drawback of the pattern, so add a final default handler or have the client check the result and report an error.
Is Express middleware an example of chain of responsibility?
It has the same shape: functions run in the order they were registered, and each one either ends the request or calls next() to pass control on. Express documents this behavior but does not itself use the pattern's name, so treat it as a close analogy.

Sources