Chain of Responsibility

Passes a request along a chain of handlers; each one either deals with it or passes it on to the next.

Why it matters

A request may need to pass several checks, or be handled by one of several handlers depending on its details. Hard-coding that sequence in one function makes it long and rigid.

The idea

Good for pipelines of checks or approvals: authentication → rate limit → validation → handler; or expense approval: a team lead up to £100, a manager up to £1,000, a director above that. Each handler is independent, and the chain can be reordered.

A customer-support line: first-line support, then a specialist, then a manager, each stepping in only if the one before can't solve it.

A support line always ends with someone. In code, a request can fall off the end with nobody handling it, so add a final default handler.

How it works

  1. Define a handler interface: handle(request).
  2. Each handler decides: deal with the request, or pass it to the next handler it holds.
  3. Link the handlers into a chain, in the order you want.
  4. Send the request to the first handler; it travels along until someone deals with it.
  5. End the chain with a default handler that rejects or logs anything unhandled.

Example

Web framework middleware, logging levels, and an ATM paying out £50 notes, then £20s, then £10s.

Key points

Common mistakes

Not true: A request that no handler accepts is reported as an error automatically.
In fact: Unless you add a default handler at the end, the request falls off the chain and disappears silently. Always handle the end of the chain.

In the interview

Chain of Responsibility passes a request through a sequence of handlers until one deals with it — like expense approvals by amount, or middleware for auth, rate limiting and validation. It keeps each handler small and lets me reorder the chain.

Part of Unit 6: Design patterns in the free System Design course.