On this page

Chain of Responsibility Pattern

Some requests don't have an obvious owner. An expense claim might be signed off by a team lead, a manager, a director or the CFO, depending on its size and type. A log line might go to the console, a file and a pager, depending on its severity. An HTTP request might be rejected by the rate limiter, the authentication check or the CSRF check before it ever reaches your controller. In each case the sender shouldn't have to know who will deal with it. It hands the request to the first candidate and lets the candidates sort it out among themselves.

That is Chain of Responsibility. The grouped behavioral patterns overview shows the middleware form briefly. This page goes further: the two flavours of the pattern (stop at the first handler, or let every handler have a turn), how to build and configure chains, what happens when nobody handles a request, how the pattern shows up in an ATM design, and the questions interviewers ask about it.

Intent

Decouple the sender of a request from its receivers by giving several objects a chance to handle it. Link the candidates into a chain and pass the request along until one of them handles it, or until the chain ends.

Three ideas sit inside that sentence:

  1. The sender knows only the head of the chain. It doesn't know how many handlers there are or in what order they run.
  2. Each handler decides for itself. "Can I deal with this?" is answered inside the handler, not by a central if/else ladder.
  3. The chain is assembled at runtime. You can reorder, insert or remove handlers without changing the sender or the other handlers.

The problem

Here is a typical expense approval routine. It starts small and grows one branch per policy change:

final class ExpenseApproval {
    private final java.util.List<String> notified = new java.util.ArrayList<>();

    String approve(String employee, long amountCents, String category) {
        if (amountCents <= 0) {
            return "REJECTED: amount must be positive";
        }
        if (category.equals("ALCOHOL") || category.equals("GIFTS")) {
            return "REJECTED: category not reimbursable";
        }
        if (amountCents <= 100_000) {
            notified.add("team-lead");
            return "APPROVED by team-lead";
        }
        if (amountCents <= 500_000) {
            notified.add("manager");
            return "APPROVED by manager";
        }
        if (amountCents <= 2_500_000 && category.equals("TRAVEL")) {
            notified.add("director");
            return "APPROVED by director";
        }
        if (amountCents <= 10_000_000) {
            notified.add("cfo");
            return "APPROVED by cfo";
        }
        return "REJECTED: needs board approval";
    }

    java.util.List<String> notified() { return notified; }
}

class BeforeDemo {
    public static void main(String[] args) {
        ExpenseApproval approval = new ExpenseApproval();
        assert approval.approve("asha", 45_000, "MEALS").equals("APPROVED by team-lead");
        assert approval.approve("ravi", 1_200_000, "TRAVEL").equals("APPROVED by director");
        assert approval.approve("ravi", 1_200_000, "HARDWARE").equals("APPROVED by cfo");
        assert approval.approve("li", 9_000, "ALCOHOL").startsWith("REJECTED");
        System.out.println("before: ok " + approval.notified());
    }
}

It works, and for four rules it's honestly fine. The trouble starts when the rules keep moving:

  • Every policy change edits the same method. Finance adds a "procurement desk" step for hardware. The Singapore office has no director level. A new rule says claims from contractors always go to their sponsor first. Each of these is another branch in the middle of the ladder, and the ordering of branches is the policy, so one misplaced if silently changes who approves what.
  • The order is hidden in code. You can't print "the current approval chain" or load it from config, because it isn't data. It's control flow.
  • Each rule can't be tested on its own. To test the director rule you have to make sure the claim passes the policy check and is above the manager limit, because every rule is entangled with the ones above it.
  • Different offices want different chains. With one method you end up with if (office.equals("SG")) inside the ladder, which doubles the paths to test.

The underlying issue is that there are several candidates for one request, the set of candidates and their order vary, and the sender (the claim submission code) shouldn't care which one says yes.

Structure

classDiagram
    class Client
    class Approver {
        <<abstract>>
        -next: Approver
        +linkTo(next: Approver) Approver
        +handle(claim: Claim) Decision
        #tryHandle(claim: Claim) Optional~Decision~
    }
    class PolicyCheck {
        -banned: Set~String~
        #tryHandle(claim: Claim) Optional~Decision~
    }
    class LimitApprover {
        -role: String
        -limitCents: long
        #tryHandle(claim: Claim) Optional~Decision~
    }
    class TravelDirector {
        -limitCents: long
        #tryHandle(claim: Claim) Optional~Decision~
    }
    class Claim {
        +employee: String
        +amountCents: long
        +category: String
    }
    Client --> Approver : sends claim to head
    Approver --> Approver : next
    Approver <|-- PolicyCheck
    Approver <|-- LimitApprover
    Approver <|-- TravelDirector
    Approver ..> Claim

At runtime the objects form a line. A claim for 12,000.00 of travel walks it like this:

sequenceDiagram
    participant C as Client
    participant P as PolicyCheck
    participant T as TeamLead
    participant M as Manager
    participant D as TravelDirector
    C->>P: handle(claim 12000.00 TRAVEL)
    P->>T: not banned, pass on
    T->>M: above my limit, pass on
    M->>D: above my limit, pass on
    D-->>C: APPROVED by director

Participants

ParticipantRole in the exampleResponsibility
HandlerApproverDeclares the handling operation and holds the link to the next handler. In the version below it also owns the "try me, else pass on" loop, so concrete handlers can't forget to forward.
Concrete handlerPolicyCheck, LimitApprover, TravelDirectorAnswers one question: can I handle this request? If yes, it returns a result. If not, it says so and the base class forwards.
Clientthe claim submission codeBuilds the chain (or receives it already built) and sends requests to its head. It never talks to the other handlers.
RequestClaimThe data travelling down the chain. Keep it immutable so one handler can't quietly change what the next one sees.

A useful refinement, used below, is to separate the two jobs of a handler: deciding (tryHandle, specific to each handler) and forwarding (handle, written once in the base class). The textbook version makes every concrete handler call next.handle(...) itself. That works, but it means every handler can forget to forward, forward twice, or forward to the wrong place. Putting the forwarding in a final method in the base class removes that whole class of bug. It's Template Method applied to the chain.

Implementation

The three versions below build the same approval chain: a policy check, then a team lead (up to 1,000.00), a manager (up to 5,000.00), a director who only approves travel (up to 25,000.00) and the CFO (up to 100,000.00). Money is held in integer cents. If nobody handles a claim, the chain returns an explicit rejection rather than null.

import java.util.Optional;
import java.util.Set;

record Claim(String employee, long amountCents, String category) {}

record Decision(boolean approved, String by, String reason) {
    static Decision approve(String by) { return new Decision(true, by, "within limit"); }
    static Decision reject(String by, String reason) { return new Decision(false, by, reason); }
}

abstract class Approver {
    private Approver next;

    /** Links this handler to the next one and returns that one, so calls can be chained. */
    Approver linkTo(Approver next) {
        this.next = next;
        return next;
    }

    /** Written once: try this handler, otherwise forward. Subclasses can't break forwarding. */
    final Decision handle(Claim claim) {
        Optional<Decision> mine = tryHandle(claim);
        if (mine.isPresent()) return mine.get();
        if (next == null) {
            return Decision.reject("chain", "no approver for " + claim.amountCents() + " cents");
        }
        return next.handle(claim);
    }

    /** Return a decision to stop the chain, or empty to pass the claim on. */
    protected abstract Optional<Decision> tryHandle(Claim claim);
}

final class PolicyCheck extends Approver {
    private final Set<String> banned;

    PolicyCheck(Set<String> banned) { this.banned = Set.copyOf(banned); }

    @Override
    protected Optional<Decision> tryHandle(Claim c) {
        if (c.amountCents() <= 0) return Optional.of(Decision.reject("policy", "amount must be positive"));
        if (banned.contains(c.category())) {
            return Optional.of(Decision.reject("policy", c.category() + " is not reimbursable"));
        }
        return Optional.empty();
    }
}

final class LimitApprover extends Approver {
    private final String role;
    private final long limitCents;

    LimitApprover(String role, long limitCents) {
        this.role = role;
        this.limitCents = limitCents;
    }

    @Override
    protected Optional<Decision> tryHandle(Claim c) {
        return c.amountCents() <= limitCents ? Optional.of(Decision.approve(role)) : Optional.empty();
    }
}

final class TravelDirector extends Approver {
    private final long limitCents;

    TravelDirector(long limitCents) { this.limitCents = limitCents; }

    @Override
    protected Optional<Decision> tryHandle(Claim c) {
        boolean mine = c.category().equals("TRAVEL") && c.amountCents() <= limitCents;
        return mine ? Optional.of(Decision.approve("director")) : Optional.empty();
    }
}

class ApprovalDemo {
    public static void main(String[] args) {
        Approver head = new PolicyCheck(Set.of("ALCOHOL", "GIFTS"));
        head.linkTo(new LimitApprover("team-lead", 100_000))
            .linkTo(new LimitApprover("manager", 500_000))
            .linkTo(new TravelDirector(2_500_000))
            .linkTo(new LimitApprover("cfo", 10_000_000));

        assert head.handle(new Claim("asha", 45_000, "MEALS")).by().equals("team-lead");
        assert head.handle(new Claim("ravi", 1_200_000, "TRAVEL")).by().equals("director");
        assert head.handle(new Claim("ravi", 1_200_000, "HARDWARE")).by().equals("cfo");

        Decision banned = head.handle(new Claim("li", 9_000, "ALCOHOL"));
        assert !banned.approved() && banned.by().equals("policy");

        Decision tooBig = head.handle(new Claim("li", 50_000_000, "HARDWARE"));
        assert !tooBig.approved() && tooBig.by().equals("chain");
        System.out.println("approval chain: ok");
    }
}
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass


@dataclass(frozen=True)
class Claim:
    employee: str
    amount_cents: int
    category: str


@dataclass(frozen=True)
class Decision:
    approved: bool
    by: str
    reason: str


class Approver(ABC):
    def __init__(self) -> None:
        self._next: Approver | None = None

    def link_to(self, nxt: Approver) -> Approver:
        """Link to the next handler and return it, so calls can be chained."""
        self._next = nxt
        return nxt

    def handle(self, claim: Claim) -> Decision:
        """Written once: try this handler, otherwise forward."""
        decision = self.try_handle(claim)
        if decision is not None:
            return decision
        if self._next is None:
            return Decision(False, "chain", f"no approver for {claim.amount_cents} cents")
        return self._next.handle(claim)

    @abstractmethod
    def try_handle(self, claim: Claim) -> Decision | None:
        """Return a Decision to stop the chain, or None to pass the claim on."""


class PolicyCheck(Approver):
    def __init__(self, banned: set[str]) -> None:
        super().__init__()
        self._banned = frozenset(banned)

    def try_handle(self, claim: Claim) -> Decision | None:
        if claim.amount_cents <= 0:
            return Decision(False, "policy", "amount must be positive")
        if claim.category in self._banned:
            return Decision(False, "policy", f"{claim.category} is not reimbursable")
        return None


class LimitApprover(Approver):
    def __init__(self, role: str, limit_cents: int) -> None:
        super().__init__()
        self._role, self._limit = role, limit_cents

    def try_handle(self, claim: Claim) -> Decision | None:
        if claim.amount_cents <= self._limit:
            return Decision(True, self._role, "within limit")
        return None


class TravelDirector(Approver):
    def __init__(self, limit_cents: int) -> None:
        super().__init__()
        self._limit = limit_cents

    def try_handle(self, claim: Claim) -> Decision | None:
        if claim.category == "TRAVEL" and claim.amount_cents <= self._limit:
            return Decision(True, "director", "within limit")
        return None


if __name__ == "__main__":
    head = PolicyCheck({"ALCOHOL", "GIFTS"})
    (head.link_to(LimitApprover("team-lead", 100_000))
         .link_to(LimitApprover("manager", 500_000))
         .link_to(TravelDirector(2_500_000))
         .link_to(LimitApprover("cfo", 10_000_000)))

    assert head.handle(Claim("asha", 45_000, "MEALS")).by == "team-lead"
    assert head.handle(Claim("ravi", 1_200_000, "TRAVEL")).by == "director"
    assert head.handle(Claim("ravi", 1_200_000, "HARDWARE")).by == "cfo"

    banned = head.handle(Claim("li", 9_000, "ALCOHOL"))
    assert not banned.approved and banned.by == "policy"

    too_big = head.handle(Claim("li", 50_000_000, "HARDWARE"))
    assert not too_big.approved and too_big.by == "chain"
    print("approval chain: ok")
interface Claim {
  readonly employee: string;
  readonly amountCents: number;
  readonly category: string;
}

interface Decision {
  readonly approved: boolean;
  readonly by: string;
  readonly reason: string;
}

abstract class Approver {
  private next: Approver | null = null;

  /** Link to the next handler and return it, so calls can be chained. */
  linkTo(next: Approver): Approver {
    this.next = next;
    return next;
  }

  /** Written once: try this handler, otherwise forward. */
  handle(claim: Claim): Decision {
    const mine = this.tryHandle(claim);
    if (mine !== null) return mine;
    if (this.next === null) {
      return { approved: false, by: "chain", reason: `no approver for ${claim.amountCents} cents` };
    }
    return this.next.handle(claim);
  }

  /** Return a decision to stop the chain, or null to pass the claim on. */
  protected abstract tryHandle(claim: Claim): Decision | null;
}

class PolicyCheck extends Approver {
  constructor(private readonly banned: ReadonlySet<string>) {
    super();
  }

  protected tryHandle(c: Claim): Decision | null {
    if (c.amountCents <= 0) return { approved: false, by: "policy", reason: "amount must be positive" };
    if (this.banned.has(c.category)) {
      return { approved: false, by: "policy", reason: `${c.category} is not reimbursable` };
    }
    return null;
  }
}

class LimitApprover extends Approver {
  constructor(private readonly role: string, private readonly limitCents: number) {
    super();
  }

  protected tryHandle(c: Claim): Decision | null {
    return c.amountCents <= this.limitCents
      ? { approved: true, by: this.role, reason: "within limit" }
      : null;
  }
}

class TravelDirector extends Approver {
  constructor(private readonly limitCents: number) {
    super();
  }

  protected tryHandle(c: Claim): Decision | null {
    return c.category === "TRAVEL" && c.amountCents <= this.limitCents
      ? { approved: true, by: "director", reason: "within limit" }
      : null;
  }
}

function check(condition: boolean, message: string): void {
  if (!condition) throw new Error(`check failed: ${message}`);
}

const head = new PolicyCheck(new Set(["ALCOHOL", "GIFTS"]));
head
  .linkTo(new LimitApprover("team-lead", 100_000))
  .linkTo(new LimitApprover("manager", 500_000))
  .linkTo(new TravelDirector(2_500_000))
  .linkTo(new LimitApprover("cfo", 10_000_000));

check(head.handle({ employee: "asha", amountCents: 45_000, category: "MEALS" }).by === "team-lead", "team lead");
check(head.handle({ employee: "ravi", amountCents: 1_200_000, category: "TRAVEL" }).by === "director", "director");
check(head.handle({ employee: "ravi", amountCents: 1_200_000, category: "HARDWARE" }).by === "cfo", "cfo");

const banned = head.handle({ employee: "li", amountCents: 9_000, category: "ALCOHOL" });
check(!banned.approved && banned.by === "policy", "policy rejects");

const tooBig = head.handle({ employee: "li", amountCents: 50_000_000, category: "HARDWARE" });
check(!tooBig.approved && tooBig.by === "chain", "end of chain rejects");
console.log("approval chain: ok");

A few details are worth pointing out because interviewers notice them.

  • The end of the chain is a decision, not an accident. When no handler takes the claim, handle returns a rejection from "chain". The alternatives are returning null (the caller then has to remember to check) or throwing (reasonable if an unhandled request is a bug). What you must not do is let the request vanish silently. If you prefer a handler object, put a terminal RejectAll handler at the end instead; the effect is the same and the chain stays uniform.
  • The director only approves travel. A hardware claim for 12,000.00 passes straight through the director to the CFO. This is the property the if ladder made awkward: a handler can be selective on any field, not just the amount, and it doesn't affect anyone else's logic.
  • Adding the procurement desk is one class and one linkTo call. Nothing else changes, which is the Open/Closed Principle working as intended.

Two flavours: stop at the first, or everyone gets a turn

The classic definition says the request travels until one handler handles it, and then it stops. The approval chain above is that flavour. In practice there is a second, equally common flavour where every handler gets the request and each decides whether to act on it, but forwarding always continues (unless a handler deliberately stops it). Logging, event bubbling and most middleware are this second kind.

Stop at first handlerEvery handler gets a turn
Typical useApprovals, cash dispensing, picking a parser for a file typeLogging, middleware, validation that collects all errors
A handler that acts...ends the chainusually forwards anyway
Resultexactly one handler's answer (or "unhandled")the combined effect of several handlers
Main riskrequests nobody handlesa handler that forgets to forward and silently cuts off the rest

Logger levels

A logging setup is the textbook "everyone gets a turn" chain. Each sink has a threshold. A DEBUG line should reach only the developer console, an INFO line also goes to the file, and an ERROR line goes to all of them and pages someone.

from __future__ import annotations

from enum import IntEnum


class Level(IntEnum):
    DEBUG = 10
    INFO = 20
    WARN = 30
    ERROR = 40


class LogHandler:
    """Each handler writes if the level is high enough, then always forwards."""

    def __init__(self, name: str, threshold: Level) -> None:
        self.name = name
        self.threshold = threshold
        self.lines: list[str] = []
        self._next: LogHandler | None = None

    def link_to(self, nxt: LogHandler) -> LogHandler:
        self._next = nxt
        return nxt

    def log(self, level: Level, message: str) -> None:
        if level >= self.threshold:
            self.write(level, message)
        if self._next is not None:
            self._next.log(level, message)

    def write(self, level: Level, message: str) -> None:
        self.lines.append(f"{level.name} {message}")


class DedupHandler(LogHandler):
    """A handler that may stop the chain: it swallows an exact repeat of the last message."""

    def __init__(self) -> None:
        super().__init__("dedup", Level.DEBUG)
        self._last: tuple[Level, str] | None = None

    def log(self, level: Level, message: str) -> None:
        if self._last == (level, message):
            return  # stop: nobody after us sees the duplicate
        self._last = (level, message)
        super().log(level, message)

    def write(self, level: Level, message: str) -> None:
        pass  # dedup only filters, it doesn't store anything


if __name__ == "__main__":
    dedup = DedupHandler()
    console = LogHandler("console", Level.DEBUG)
    file = LogHandler("file", Level.INFO)
    pager = LogHandler("pager", Level.ERROR)
    dedup.link_to(console).link_to(file).link_to(pager)

    dedup.log(Level.DEBUG, "cache miss for user 42")
    dedup.log(Level.INFO, "order 9 placed")
    dedup.log(Level.ERROR, "payment provider timed out")
    dedup.log(Level.ERROR, "payment provider timed out")  # duplicate, dropped

    assert console.lines == ["DEBUG cache miss for user 42", "INFO order 9 placed",
                             "ERROR payment provider timed out"]
    assert file.lines == ["INFO order 9 placed", "ERROR payment provider timed out"]
    assert pager.lines == ["ERROR payment provider timed out"]
    print("logger chain: ok")

The DedupHandler shows that "everyone gets a turn" is a default, not a law: any handler can still end the chain on purpose. Order also matters differently here. Put the dedup handler after the console and the console still sees duplicates. In a stop-at-first chain the order decides who handles; in a pass-it-on chain it decides who sees what.

Middleware: the chain as functions

Web frameworks are where most developers meet this pattern, often without the name. A middleware function receives the request and a next callback. It can:

  • short-circuit by returning a response without calling next (an auth check that returns 401);
  • pass through by calling next and returning what it gets;
  • wrap by doing work before and after calling next (timing, adding headers, catching errors).

That third capability is something the classic object chain doesn't give you. Because next(req) returns the downstream result, each middleware sees the response on the way back out. People call this the onion model: the request travels inward through the layers and the response travels back out through them in reverse.

type Req = { readonly path: string; readonly headers: Readonly<Record<string, string>>; readonly user?: string };
type Res = { readonly status: number; readonly body: string; readonly headers: Readonly<Record<string, string>> };
type Handler = (req: Req) => Res;
type Middleware = (req: Req, next: Handler) => Res;

/** Fold the list from the right so the first middleware is the outermost layer. */
function compose(middlewares: readonly Middleware[], endpoint: Handler): Handler {
  return middlewares.reduceRight<Handler>((next, mw) => (req) => mw(req, next), endpoint);
}

const trace: string[] = [];

const logging: Middleware = (req, next) => {
  trace.push(`-> ${req.path}`);
  const res = next(req);
  trace.push(`<- ${res.status}`);
  return res;
};

const poweredBy: Middleware = (req, next) => {
  const res = next(req);
  return { ...res, headers: { ...res.headers, "x-powered-by": "chain" } };
};

const auth: Middleware = (req, next) => {
  if (req.headers["authorization"] !== "Bearer good-token") {
    return { status: 401, body: "unauthorized", headers: {} }; // short-circuit: next is never called
  }
  return next({ ...req, user: "asha" });
};

const endpoint: Handler = (req) => ({ status: 200, body: `hello ${req.user ?? "?"}`, headers: {} });

const app = compose([logging, poweredBy, auth], endpoint);

function check(condition: boolean, message: string): void {
  if (!condition) throw new Error(`check failed: ${message}`);
}

const denied = app({ path: "/me", headers: {} });
check(denied.status === 401, "auth short-circuits");
check(denied.headers["x-powered-by"] === "chain", "outer layers still see the response");

const ok = app({ path: "/me", headers: { authorization: "Bearer good-token" } });
check(ok.status === 200 && ok.body === "hello asha", "request reaches endpoint with user attached");
check(trace.join(",") === "-> /me,<- 401,-> /me,<- 200", "logging wraps both requests");
console.log("middleware chain: ok");

The compose function is the whole framework. Express and Koa do essentially this, with asynchronous next and error handling added. A few rules carry over to any middleware stack:

  • Order is behaviour. Here poweredBy sits outside auth, so even the 401 gets the header. Swap them and it wouldn't. Put logging first so it sees everything, including rejected requests. Put authentication before anything that reads req.user.
  • Don't call next twice. Calling it twice runs the rest of the chain twice. Koa's compose detects this and throws an error. Your hand-rolled version should either do the same or be simple enough that it obviously can't happen.

Building and configuring the chain

The linked-list form (linkTo) is the classic shape, but it is not the only one and often not the best. If handlers don't need to wrap each other, a list of handlers plus a loop is simpler: the chain becomes plain data you can print, sort, load from configuration and test.

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

record Expense(long amountCents, String category) {}

/** The chain as data: an ordered list of steps and one loop. */
final class ListChain {
    private final List<Function<Expense, Optional<String>>> steps;

    ListChain(List<Function<Expense, Optional<String>>> steps) { this.steps = List.copyOf(steps); }

    String handle(Expense e) {
        for (Function<Expense, Optional<String>> step : steps) {
            Optional<String> result = step.apply(e);
            if (result.isPresent()) return result.get();
        }
        return "unhandled";
    }

    static Function<Expense, Optional<String>> limit(String role, long cents) {
        return e -> e.amountCents() <= cents ? Optional.of(role) : Optional.empty();
    }
}

class ListChainDemo {
    public static void main(String[] args) {
        // Two offices, two chains, same handler code. Singapore has no manager level.
        ListChain india = new ListChain(List.of(
            ListChain.limit("team-lead", 100_000),
            ListChain.limit("manager", 500_000),
            ListChain.limit("cfo", 10_000_000)));
        ListChain singapore = new ListChain(List.of(
            ListChain.limit("team-lead", 100_000),
            ListChain.limit("cfo", 10_000_000)));

        assert india.handle(new Expense(300_000, "MEALS")).equals("manager");
        assert singapore.handle(new Expense(300_000, "MEALS")).equals("cfo");
        assert india.handle(new Expense(99_000_000, "MEALS")).equals("unhandled");
        System.out.println("list chain: ok");
    }
}

Wherever the chain is built, build it in one place: a factory, a configuration class or the composition root. If linkTo calls are scattered across the codebase, nobody can answer "what is the chain right now?", which defeats much of the point.

Chain of Responsibility in an ATM

The ATM machine case study is built mostly around the State pattern, but cash dispensing is a natural chain and interviewers often ask for it as a follow-up. Each cassette holds one denomination. The highest denomination dispenses as many notes as it can, then passes the remainder to the next cassette.

import java.util.LinkedHashMap;
import java.util.Map;

final class Cassette {
    private final int denomination;
    private int notes;
    private Cassette next;

    Cassette(int denomination, int notes) {
        this.denomination = denomination;
        this.notes = notes;
    }

    Cassette linkTo(Cassette next) {
        this.next = next;
        return next;
    }

    /** Dry run: fill in how many notes each cassette would give. No state changes. */
    boolean plan(int amount, Map<Integer, Integer> out) {
        int use = Math.min(amount / denomination, notes);
        if (use > 0) out.put(denomination, use);
        int rest = amount - use * denomination;
        if (rest == 0) return true;
        return next != null && next.plan(rest, out);
    }

    /** Apply a plan that already succeeded. */
    void commit(Map<Integer, Integer> plan) {
        notes -= plan.getOrDefault(denomination, 0);
        if (next != null) next.commit(plan);
    }

    int notes() { return notes; }
}

final class CashDispenser {
    private final Cassette head;

    CashDispenser(Cassette head) { this.head = head; }

    synchronized Map<Integer, Integer> dispense(int amount) {
        Map<Integer, Integer> plan = new LinkedHashMap<>();
        if (amount <= 0 || !head.plan(amount, plan)) {
            throw new IllegalStateException("cannot dispense " + amount);
        }
        head.commit(plan); // only touch the cassettes once the whole amount is covered
        return plan;
    }
}

class DispenserDemo {
    public static void main(String[] args) {
        Cassette c2000 = new Cassette(2000, 2);
        Cassette c500 = new Cassette(500, 3);
        Cassette c100 = new Cassette(100, 10);
        c2000.linkTo(c500).linkTo(c100);
        CashDispenser atm = new CashDispenser(c2000);

        assert atm.dispense(3700).equals(Map.of(2000, 1, 500, 3, 100, 2));
        assert c2000.notes() == 1 && c500.notes() == 0 && c100.notes() == 8;

        // Failure leaves every cassette untouched.
        try { atm.dispense(100_000); assert false; } catch (IllegalStateException expected) { }
        assert c2000.notes() == 1 && c100.notes() == 8;

        // The greedy chain's known limit: 600 from {500 x1, 200 x3} is possible (3 x 200)
        // but the chain takes the 500 first and is left with 100 it can't make.
        Cassette a500 = new Cassette(500, 1);
        a500.linkTo(new Cassette(200, 3));
        try { new CashDispenser(a500).dispense(600); assert false; } catch (IllegalStateException expected) { }
        System.out.println("dispenser chain: ok");
    }
}

This example earns its place in an interview for three reasons:

  1. It's the "everyone contributes" flavour with a stop condition. Each cassette handles part of the request and forwards the rest. The chain ends when the remainder is zero.
  2. It separates planning from committing. A naive version decrements note counts as it goes, so a failed withdrawal leaves the machine believing it has fewer notes than it does. Planning first, then committing, keeps the cassettes consistent. synchronized on dispense stops two withdrawals from planning against the same counts. (A real ATM serves one customer at a time, but the dispenser is shared state and the habit is worth showing.)
  3. It has a known limit you should volunteer. Greedy works for currencies whose denominations are "canonical" (Indian rupee and US dollar note sets are), but with arbitrary counts and denominations it can fail when a solution exists, as the 600 case shows. If the interviewer pushes, the fix is to replace the chain with a small search over note counts; the chain is the right first answer because it is simple and correct for the usual case.

Real-world uses

These are places where the pattern is plainly visible in widely used APIs:

  • Java Servlet filters. A javax.servlet.Filter (now jakarta.servlet.Filter) receives the request, response and a FilterChain. It calls chain.doFilter(request, response) to pass control on, or doesn't call it to stop the request. Spring Security is built as a chain of such filters.
  • Express and Koa middleware. Each middleware receives next. In Express, not calling next() and not sending a response leaves the request hanging, which is the "forgot to forward" bug in its most visible form. Koa's middleware is the onion model with async/await.
  • OkHttp interceptors. An OkHttp Interceptor receives a Chain and calls chain.proceed(request) to continue. Retry, caching and header rewriting are all interceptors, and an interceptor can return a response without proceeding.
  • Netty's ChannelPipeline. Inbound and outbound events flow through an ordered list of channel handlers, each of which can handle, transform or pass the event to the next.
  • DOM event bubbling. A click on a button is offered to the button, then its parent element, then up to the document. Any listener can call stopPropagation() to end the journey. The chain here follows the element tree's parent links.
  • Python's logging propagation. Loggers form a dotted hierarchy (app.db is a child of app). A record is offered to the logger's own handlers, then to its ancestors' handlers while propagate is true, and each handler applies its own level threshold.

When NOT to use it

The pattern costs something: indirection, ordering bugs and requests that fall off the end. Skip it when:

  • There is one handler, or the set never changes. A three-branch if that matches a stable business rule is easier to read than three classes and a wiring step. Reach for the chain when the set of handlers or their order is a thing that changes.
  • You can compute the right handler directly. If the handler is determined by a key (paymentMethod → processor), a map lookup is clearer and faster. That's Strategy selected from a registry, not a chain. Chains are for when each candidate must inspect the request to know whether it applies.
  • Every handler must see every request and order doesn't matter. That's Observer. A chain implies order and the power to stop. If neither matters, don't pay for them.
  • Handling must be guaranteed. If a request that nobody handles is a correctness bug (a payment that's neither approved nor rejected), make sure the chain can't end silently. Add a terminal handler or throw, and test the empty and unmatched cases.
PatternHow it differs
DecoratorStructurally almost identical: each object wraps the next. A decorator always delegates and adds behaviour around it. A chain handler may decide not to delegate. Middleware sits right between the two, which is why people call it either.
CommandOften travels through a chain: the request object is a command, and the chain decides who executes it. Command is about packaging a request; the chain is about routing it.
CompositeChains often follow composite parent links. DOM bubbling walks from a child node to its parent, and a widget asks its container for help (the classic "context-sensitive help" example).
StrategyStrategy picks one algorithm up front, chosen by the client. A chain lets the candidates decide at request time, possibly several of them.
ObserverObserver broadcasts to all subscribers, unordered, and no subscriber can stop the others. A chain is ordered and any link can end it.
MediatorA mediator knows all the participants and routes centrally. In a chain, no one knows the whole route; each handler knows only its successor.
Template MethodUsed inside the handler base class above: handle is the fixed skeleton, tryHandle the step subclasses fill in.
SpecificationA handler's "can I handle this?" check is often a specification. Chains of specifications are how many rule engines pick the first matching rule.

The smell that suggests it

Look for these in code you're reviewing or in your own first draft:

  • An ordered ladder of "if it's mine, handle it" branches, where each branch tests a different condition (thresholds, categories, file types) and the order of the branches is itself the business rule.
  • The ladder differs between deployments, tenants or offices, so you see if (region == ...) threaded through it.
  • The same cross-cutting checks at the top of every endpoint: authenticate, check rate limit, log, validate. Each endpoint repeats them, and they drift apart. That's middleware waiting to be extracted.
  • A request that's tossed to whoever is "nearest" and escalated if they can't deal with it: support tiers, approval levels, fallback providers (try the primary payment gateway, then the backup).

Interview questions

  1. "What happens if no handler handles the request?" That's a design decision you should make explicitly. Options: return a typed "unhandled" result, throw (if it indicates a bug), or end the chain with a catch-all handler that applies a default. Never let it return null by accident. In the approval example the chain rejects with a reason, so callers can't mistake silence for approval.
  2. "How is Chain of Responsibility different from Decorator? The code looks the same." The structure is the same: each object holds a reference to the next. The intent differs. A decorator always forwards and adds something; the caller gets the wrapped object's behaviour plus extras. A chain handler may stop the request and answer itself. Middleware can do both, which is why the line blurs in practice.
  3. "Who builds the chain?" One place: a factory or the composition root at startup, often from configuration. Handlers shouldn't create their successors, or you've hard-coded the order inside the handlers and lost the main benefit.
  4. "Would you use a linked list of handlers or a list and a loop?" A list and a loop when handlers are independent checks and nobody needs to run code after the next handler finishes. It's easier to print, test and configure. Linked handlers (or composed functions) when handlers wrap each other, like timing or transaction middleware.
  5. "How do you test a chain?" Test each handler alone: give it a request it should take and one it should pass, and assert on the result (a fake "next" that records whether it was called works well). Then add a few tests on the assembled chain for ordering: the claim that both the manager and the CFO could approve must go to the manager.
  6. "How would you design ATM cash dispensing with this pattern, and what can go wrong?" One handler per cassette, highest denomination first, each dispensing what it can and passing the remainder on. Plan the whole withdrawal before changing any counts, so a failure leaves the cassettes untouched, and serialise withdrawals. Mention that greedy can fail for unusual stock levels (600 from one 500 and three 200s), and that a small search fixes it if the interviewer asks.
  7. "Can handlers modify the request?" They can, but prefer passing a new, enriched request to next (the auth middleware attaching a user) over mutating a shared object. Mutation hides ordering bugs: a later handler reads a value some earlier handler quietly changed.

Further reading