Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 57 ยท Behavioral Patterns

Chain of Responsibility

Learn the Chain of Responsibility design pattern: pass a request along a chain of handlers. Covers approval workflows, middleware pipelines and logging levels.

The Chain of Responsibility pattern passes a request along a line of handlers. Each handler looks at the request and either deals with it or hands it on to the next one. The sender does not know which handler will end up doing the work, and no handler needs to know about any handler except its successor.

Customer support works this way. You call the help line and the first agent tries to solve your problem. If it is beyond them, they pass you to a specialist, who may pass you to a manager. You never had to know who could approve a refund of that size; you only started the chain. The same idea runs through expense approvals, event bubbling in the browser, exception handling (catch blocks are tried one after another) and the middleware in web frameworks.

Pass it along

Handlers Each one links to the next.
Decide Handle the request, or pass it on.
Sender Sends to the first and does not care who answers.

Adding a handler never changes the sender.

1 / 2

The structure

Every handler has the same interface, usually one method, and a link to its successor. In the first-match variant, a handler that can deal with the request stops the chain. In the pipeline variant, every handler runs and decides whether to call the next one.

flowchart LR
    C["Client"] --> A["Handler A"]
    A -->|"cannot handle"| B["Handler B"]
    B -->|"cannot handle"| D["Handler C"]
    D -->|"cannot handle"| E["Unhandled"]
    A -->|"handled"| R["Result"]
    B -->|"handled"| R
    D -->|"handled"| R

The request travels until a handler takes it; if none does, the chain ends and the sender must cope.

An approval workflow

An expense report needs an approver whose limit is high enough. A team lead can approve up to 500, a manager up to 5,000, a director up to 50,000. Anything above needs a board vote. The sender just submits to the lead.

JS Expense approvals: first match wins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each approver knows its own limit and its successor, and nothing else. To insert a "vice president" level, you create one object and link it in. The sender code, lead.approve(request), does not change.

Logging levels

The same idea appears in logging frameworks, where a message with a level (debug, info, warn, error) can be written by several destinations. Here every handler in the chain may handle a message and pass it on, so a single error goes to the console and to an alert list. A handler that only cares about higher levels ignores lower messages.

JS A logger chain where several handlers act

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sender calls log once. Which destinations act depends on each handler's own threshold. Because each handler always forwards, you can reorder the chain or drop a handler without breaking the others.

Middleware pipelines

Web frameworks (Express, Koa, Laravel, ASP.NET Core) are built from this pattern. A request passes through middleware functions such as logging, authentication, parsing and finally the route handler. Each middleware receives the request and a next function. It can do work before calling next(), do work after next() returns (on the way back out), or stop the chain by responding without calling next() at all.

JS A tiny middleware pipeline with next()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For the anonymous user, auth replies and never calls next(), so the handler never runs, yet timing still sees the response on the way back because it wraps the rest of the chain. This "onion" shape is what makes middleware so useful for cross-cutting concerns.

Design notes and pitfalls

  • Unhandled requests. In first-match chains, a request can fall off the end. Decide what that means: an error, a default handler at the end, or a clear result as above.
  • Order matters. Authentication must come before authorization; a catch-all handler must come last. Document the intended order or build the chain in a single function.
  • Ownership of passing on. Either the base class forwards automatically (as in the logger) or each handler calls next() itself (as in middleware). Forgetting to forward is the classic bug, as is calling next() twice.
  • Hard to debug. It can be unclear which handler dealt with a request. Log the path or keep a trace, as the middleware example does.
  • Performance. A long chain adds a call per handler. Keep chains short on hot paths.

Chain of Responsibility looks like Decorator, since both link objects with the same interface, but a decorator always delegates and adds behavior, while a handler may stop the chain. It is closely related to Composite, where a parent passes requests to children, and to Command, because the request is often a command object. When many listeners react to one event rather than one handler taking the request, you want Observer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the sender know in Chain of Responsibility?

    The sender starts the request at the head of the chain. It does not know, and does not need to know, which handler will eventually act.
  2. 2. In the first-match variant, what happens when a handler can deal with the request?

    The first handler that can handle the request does so and stops the chain; others are never consulted.
  3. 3. In a middleware pipeline, what does a middleware do to short-circuit the chain?

    Handlers further down only run if next() is called. Responding without calling it ends the chain early, for example when authentication fails.
  4. 4. How does Chain of Responsibility differ from Decorator?

    Both link objects with a common interface, but a decorator enriches a call it always forwards, while a handler decides whether the request goes any further.
  5. 5. Which is a common bug in handler chains?

    A missing forward silently drops the request, and a double call to next runs the rest of the chain twice. Guard against both.

Summary

  • Chain of Responsibility sends a request through a line of handlers; each handles it or passes it on.
  • The sender knows only the first handler, and each handler knows only its successor.
  • First-match chains (approvals) stop at the first capable handler; pipelines (logging, middleware) let several handlers act.
  • Middleware adds next(), which allows work before and after the rest of the chain and early exit.
  • Plan for unhandled requests, document the order, and watch for missing or duplicate forwarding.
  • It resembles Decorator in structure, but a handler can stop the chain.

Next lesson: Mediator and Memento.