Avoid coupling the sender of a request to its receiver by giving several objects a chance to handle it. Link the receivers into a chain and pass the request along until one of them handles it.
Chain of Responsibility lets you send a request into a line of handler objects without knowing in advance which one will deal with it. Each handler either handles the request or passes it to the next one. The sender only knows the head of the chain. This guide follows one scenario throughout: a returns warehouse that has to decide what to do with every parcel customers send back. You will see why a growing if/else block turns painful, how a chain of small handlers replaces it, and how to explain the trade-offs in an interview. The code is in TypeScript, Python and PHP, and all three versions behave the same way.
The problem
A situation where the obvious design starts to hurt.
Parcelbay is a mid-sized online retailer. Its returns warehouse receives roughly 4,000 returned parcels a day, and for every one the system has to pick a disposition: put it back on the shelf, send it back to the supplier, refurbish it, donate it or recycle it.
All of that lives in one function, decideDisposition, which has grown to about 180 lines of nested conditionals. The rules depend on each other's order. Sealed items returned within 30 days go back to stock. Items from suppliers with a take-back contract go back to the supplier. Electronics whose repair costs no more than 40% of the price get refurbished. Apparel gets donated. Everything else is recycled.
The returns team changes these rules every few weeks. They want to add a take-back contract for a kettle supplier called Kettlecraft, try a seasonal donation rule for coats and switch off refurbishing during stocktake. Every change means editing the same function, rerunning its whole test suite and hoping the branch order still makes sense. Two engineers editing it in the same sprint almost always produce a merge conflict. There is also no way to run a different rule set for the smaller warehouse that does not refurbish at all.
The solution
What the pattern proposes.
Turn each rule into its own handler object with one method, handle(item). A handler checks whether the item matches its rule. If it does, it returns a decision and the chain stops. If it does not, it forwards the item to the next handler it holds a reference to.
A shared base class, BaseReturnHandler, stores the next reference and implements the default behaviour of forwarding. Concrete handlers such as RestockHandler, VendorTakeBackHandler, RefurbishHandler, DonateHandler and RecycleHandler only override handle with their own check and call the base version when they decline.
The intake code that receives the parcels never sees those classes. It gets the head of the chain and calls handle. The order of the rules is decided in one place, at wiring time: restock, then vendor take-back, then refurbish, then donate, then recycle as a catch-all at the end. Adding the Kettlecraft contract becomes a constructor argument. Removing refurbishing for the small warehouse means wiring a chain without that link. Each rule can be tested on its own with a single input.
An everyday analogy
The same idea, outside software.
Think of a jar with a stuck lid at a family dinner. The person who wants it open hands it to whoever is next to them. That person gives it one twist; if it opens, they hand it back open and that is the end of it. If not, they pass it on to the next person around the table. Nobody has to know in advance who has the strongest grip, and the person who asked does not care who opened it. At the end of the table sits whoever always manages it, with a rubber grip pad and a spoon, so the jar never comes back unopened. Swap the seating order and the same jar takes a different route, but the request is the same.
Structure
The pieces and how they relate.
Participants
- ReturnHandler (Handler interface)
- Declares the contract every link follows:
setNextto attach the following handler andhandleto process or forward a returned item. - BaseReturnHandler (Base handler)
- Holds the reference to the next handler and implements the default behaviour: forward the item, or return null if there is nobody left. Concrete handlers reuse this instead of repeating the forwarding code.
- RestockHandler, VendorTakeBackHandler, RefurbishHandler, DonateHandler (Concrete handlers)
- Each one owns a single business rule. If the item matches, it returns a Disposition and the chain stops; otherwise it calls the base
handleto pass the item on. - RecycleHandler (Terminal handler)
- Always handles the item. Placed last, it guarantees that no parcel leaves the chain without a decision.
- ReturnsIntake (Client)
- Builds or receives the chain and sends each ReturnedItem to its head. It does not know which handler will decide or how many handlers exist.
Pseudocode
The solution to the scenario, language-neutral.
interface ReturnHandler
method setNext(next: ReturnHandler): ReturnHandler
method handle(item: ReturnedItem): Disposition or null
abstract class BaseReturnHandler implements ReturnHandler
field next: ReturnHandler or null = null
method setNext(next)
this.next = next
return next // lets you write a.setNext(b).setNext(c)
method handle(item)
if next is not null
return next.handle(item)
return null
class RestockHandler extends BaseReturnHandler
method handle(item)
if item.sealed and item.daysSincePurchase <= 30
return Disposition("restock")
return parent.handle(item)
class VendorTakeBackHandler extends BaseReturnHandler
field vendors: set of names
method handle(item)
if item.vendor in vendors
return Disposition("return-to-vendor")
return parent.handle(item)
class RefurbishHandler extends BaseReturnHandler
method handle(item)
if item.category == "electronics" and item.repairCost <= item.price * 0.4
return Disposition("refurbish")
return parent.handle(item)
class DonateHandler extends BaseReturnHandler
method handle(item)
if item.category == "apparel"
return Disposition("donate")
return parent.handle(item)
class RecycleHandler extends BaseReturnHandler
method handle(item)
return Disposition("recycle") // terminal: never forwards
// wiring, done once
head = new RestockHandler()
head.setNext(new VendorTakeBackHandler({"Kettlecraft"}))
.setNext(new RefurbishHandler())
.setNext(new DonateHandler())
.setNext(new RecycleHandler())
// client
for each item in todaysReturns
decision = head.handle(item)
record(item, decision)The code
The same solution in TypeScript, Python and PHP.
type Category = "electronics" | "apparel" | "home";
interface ReturnedItem {
sku: string;
category: Category;
vendor: string;
sealed: boolean;
daysSincePurchase: number;
price: number;
repairCost: number;
}
interface Disposition {
action: string;
decidedBy: string;
}
interface ReturnHandler {
setNext(next: ReturnHandler): ReturnHandler;
handle(item: ReturnedItem): Disposition | null;
}
abstract class BaseReturnHandler implements ReturnHandler {
private next: ReturnHandler | null = null;
setNext(next: ReturnHandler): ReturnHandler {
this.next = next;
return next;
}
handle(item: ReturnedItem): Disposition | null {
return this.next ? this.next.handle(item) : null;
}
}
class RestockHandler extends BaseReturnHandler {
handle(item: ReturnedItem): Disposition | null {
if (item.sealed && item.daysSincePurchase <= 30) {
return { action: "restock", decidedBy: "RestockHandler" };
}
return super.handle(item);
}
}
class VendorTakeBackHandler extends BaseReturnHandler {
constructor(private readonly vendors: Set<string>) {
super();
}
handle(item: ReturnedItem): Disposition | null {
if (this.vendors.has(item.vendor)) {
return { action: "return-to-vendor", decidedBy: "VendorTakeBackHandler" };
}
return super.handle(item);
}
}
class RefurbishHandler extends BaseReturnHandler {
private static readonly MAX_REPAIR_RATIO = 0.4;
handle(item: ReturnedItem): Disposition | null {
if (
item.category === "electronics" &&
item.repairCost <= item.price * RefurbishHandler.MAX_REPAIR_RATIO
) {
return { action: "refurbish", decidedBy: "RefurbishHandler" };
}
return super.handle(item);
}
}
class DonateHandler extends BaseReturnHandler {
handle(item: ReturnedItem): Disposition | null {
if (item.category === "apparel") {
return { action: "donate", decidedBy: "DonateHandler" };
}
return super.handle(item);
}
}
class RecycleHandler extends BaseReturnHandler {
handle(_item: ReturnedItem): Disposition | null {
return { action: "recycle", decidedBy: "RecycleHandler" };
}
}
function buildChain(): ReturnHandler {
const head = new RestockHandler();
head
.setNext(new VendorTakeBackHandler(new Set(["Kettlecraft"])))
.setNext(new RefurbishHandler())
.setNext(new DonateHandler())
.setNext(new RecycleHandler());
return head;
}
const returns: ReturnedItem[] = [
{ sku: "HP-100", category: "electronics", vendor: "Soundwell", sealed: true, daysSincePurchase: 12, price: 89, repairCost: 0 },
{ sku: "KT-220", category: "home", vendor: "Kettlecraft", sealed: false, daysSincePurchase: 45, price: 39, repairCost: 20 },
{ sku: "TB-310", category: "electronics", vendor: "Tabula", sealed: false, daysSincePurchase: 60, price: 249, repairCost: 70 },
{ sku: "JK-415", category: "apparel", vendor: "Northline", sealed: false, daysSincePurchase: 40, price: 120, repairCost: 0 },
{ sku: "LP-520", category: "home", vendor: "Glowhaus", sealed: false, daysSincePurchase: 90, price: 25, repairCost: 18 },
];
const chain = buildChain();
for (const item of returns) {
const result = chain.handle(item);
console.log(
result ? `${item.sku} -> ${result.action} (${result.decidedBy})` : `${item.sku} -> unhandled`
);
}
// HP-100 -> restock (RestockHandler)
// KT-220 -> return-to-vendor (VendorTakeBackHandler)
// TB-310 -> refurbish (RefurbishHandler)
// JK-415 -> donate (DonateHandler)
// LP-520 -> recycle (RecycleHandler)from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class ReturnedItem:
sku: str
category: str
vendor: str
sealed: bool
days_since_purchase: int
price: float
repair_cost: float
@dataclass(frozen=True)
class Disposition:
action: str
decided_by: str
class BaseReturnHandler:
def __init__(self) -> None:
self._next: Optional[BaseReturnHandler] = None
def set_next(self, nxt: BaseReturnHandler) -> BaseReturnHandler:
self._next = nxt
return nxt
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
return self._next.handle(item) if self._next else None
class RestockHandler(BaseReturnHandler):
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
if item.sealed and item.days_since_purchase <= 30:
return Disposition("restock", "RestockHandler")
return super().handle(item)
class VendorTakeBackHandler(BaseReturnHandler):
def __init__(self, vendors: set[str]) -> None:
super().__init__()
self._vendors = frozenset(vendors)
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
if item.vendor in self._vendors:
return Disposition("return-to-vendor", "VendorTakeBackHandler")
return super().handle(item)
class RefurbishHandler(BaseReturnHandler):
MAX_REPAIR_RATIO = 0.4
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
if (
item.category == "electronics"
and item.repair_cost <= item.price * self.MAX_REPAIR_RATIO
):
return Disposition("refurbish", "RefurbishHandler")
return super().handle(item)
class DonateHandler(BaseReturnHandler):
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
if item.category == "apparel":
return Disposition("donate", "DonateHandler")
return super().handle(item)
class RecycleHandler(BaseReturnHandler):
def handle(self, item: ReturnedItem) -> Optional[Disposition]:
return Disposition("recycle", "RecycleHandler")
def build_chain() -> BaseReturnHandler:
head = RestockHandler()
(
head.set_next(VendorTakeBackHandler({"Kettlecraft"}))
.set_next(RefurbishHandler())
.set_next(DonateHandler())
.set_next(RecycleHandler())
)
return head
RETURNS = [
ReturnedItem("HP-100", "electronics", "Soundwell", True, 12, 89, 0),
ReturnedItem("KT-220", "home", "Kettlecraft", False, 45, 39, 20),
ReturnedItem("TB-310", "electronics", "Tabula", False, 60, 249, 70),
ReturnedItem("JK-415", "apparel", "Northline", False, 40, 120, 0),
ReturnedItem("LP-520", "home", "Glowhaus", False, 90, 25, 18),
]
if __name__ == "__main__":
chain = build_chain()
for item in RETURNS:
result = chain.handle(item)
if result:
print(f"{item.sku} -> {result.action} ({result.decided_by})")
else:
print(f"{item.sku} -> unhandled")
# HP-100 -> restock (RestockHandler)
# KT-220 -> return-to-vendor (VendorTakeBackHandler)
# TB-310 -> refurbish (RefurbishHandler)
# JK-415 -> donate (DonateHandler)
# LP-520 -> recycle (RecycleHandler)<?php
declare(strict_types=1);
final class ReturnedItem
{
public function __construct(
public readonly string $sku,
public readonly string $category,
public readonly string $vendor,
public readonly bool $sealed,
public readonly int $daysSincePurchase,
public readonly float $price,
public readonly float $repairCost,
) {
}
}
final class Disposition
{
public function __construct(
public readonly string $action,
public readonly string $decidedBy,
) {
}
}
interface ReturnHandler
{
public function setNext(ReturnHandler $next): ReturnHandler;
public function handle(ReturnedItem $item): ?Disposition;
}
abstract class BaseReturnHandler implements ReturnHandler
{
private ?ReturnHandler $next = null;
public function setNext(ReturnHandler $next): ReturnHandler
{
$this->next = $next;
return $next;
}
public function handle(ReturnedItem $item): ?Disposition
{
return $this->next?->handle($item);
}
}
final class RestockHandler extends BaseReturnHandler
{
public function handle(ReturnedItem $item): ?Disposition
{
if ($item->sealed && $item->daysSincePurchase <= 30) {
return new Disposition('restock', 'RestockHandler');
}
return parent::handle($item);
}
}
final class VendorTakeBackHandler extends BaseReturnHandler
{
/** @param string[] $vendors */
public function __construct(private readonly array $vendors)
{
}
public function handle(ReturnedItem $item): ?Disposition
{
if (in_array($item->vendor, $this->vendors, true)) {
return new Disposition('return-to-vendor', 'VendorTakeBackHandler');
}
return parent::handle($item);
}
}
final class RefurbishHandler extends BaseReturnHandler
{
private const MAX_REPAIR_RATIO = 0.4;
public function handle(ReturnedItem $item): ?Disposition
{
if (
$item->category === 'electronics'
&& $item->repairCost <= $item->price * self::MAX_REPAIR_RATIO
) {
return new Disposition('refurbish', 'RefurbishHandler');
}
return parent::handle($item);
}
}
final class DonateHandler extends BaseReturnHandler
{
public function handle(ReturnedItem $item): ?Disposition
{
if ($item->category === 'apparel') {
return new Disposition('donate', 'DonateHandler');
}
return parent::handle($item);
}
}
final class RecycleHandler extends BaseReturnHandler
{
public function handle(ReturnedItem $item): ?Disposition
{
return new Disposition('recycle', 'RecycleHandler');
}
}
function buildChain(): ReturnHandler
{
$head = new RestockHandler();
$head
->setNext(new VendorTakeBackHandler(['Kettlecraft']))
->setNext(new RefurbishHandler())
->setNext(new DonateHandler())
->setNext(new RecycleHandler());
return $head;
}
$returns = [
new ReturnedItem('HP-100', 'electronics', 'Soundwell', true, 12, 89, 0),
new ReturnedItem('KT-220', 'home', 'Kettlecraft', false, 45, 39, 20),
new ReturnedItem('TB-310', 'electronics', 'Tabula', false, 60, 249, 70),
new ReturnedItem('JK-415', 'apparel', 'Northline', false, 40, 120, 0),
new ReturnedItem('LP-520', 'home', 'Glowhaus', false, 90, 25, 18),
];
$chain = buildChain();
foreach ($returns as $item) {
$result = $chain->handle($item);
echo $result
? sprintf('%s -> %s (%s)', $item->sku, $result->action, $result->decidedBy) . PHP_EOL
: sprintf('%s -> unhandled', $item->sku) . PHP_EOL;
}
// HP-100 -> restock (RestockHandler)
// KT-220 -> return-to-vendor (VendorTakeBackHandler)
// TB-310 -> refurbish (RefurbishHandler)
// JK-415 -> donate (DonateHandler)
// LP-520 -> recycle (RecycleHandler)When to use it
Situations where it pays off.
More than one object may handle a request and you do not know which one until runtime, as with a parcel whose disposition depends on its condition, category and supplier.
The chain tries candidates in order and stops at the first match, so the sender never has to encode the selection logic itself.
You want to issue a request to one of several handlers without naming the receiver explicitly.
The client only depends on the handler interface and the head of the chain. New handlers can be added without touching the client.
The set of handlers or their order must change by configuration, environment or season, such as a small warehouse that does not refurbish.
Links are wired at runtime, so you can build different chains from the same handler classes instead of adding flags to one big conditional.
A request must pass through several processing steps in a fixed order, each of which may stop it, like checks in an HTTP middleware pipeline.
A variant of the pattern lets every handler do some work and then decide whether to continue, which keeps each step small and independently testable.
A long conditional keeps growing because each new business rule is another branch.
Moving each branch into its own handler turns a change to one rule into a change to one class, which cuts merge conflicts and regression risk.
How to implement it
Steps to introduce it in existing code.
Define the handler interface with a method that takes the request, here
handle(item). Decide what it returns: a result, a boolean, or nothing if handlers act through side effects.Write a base handler that stores a reference to the next handler and implements the default behaviour of forwarding. Have
setNextreturn the handler it received so you can chain the wiring calls.Move each branch of the old conditional into its own concrete handler. In
handle, check whether the request matches; if it does, process it and return; if not, call the base implementation to forward.Decide what happens when nobody handles the request. Either add a terminal catch-all handler, as
RecycleHandlerdoes here, or let the base return null and have the client deal with it explicitly.Wire the chain in one place, such as a factory function or the composition root, so the order of the rules is visible and easy to change.
Give the client only the head of the chain and replace the old conditional call with
head.handle(request).Test each handler in isolation with one matching and one non-matching input, then add a small set of end-to-end tests for the wired chain to lock in the order.
Pros and cons
What you gain and what you pay.
Pros
- The sender is decoupled from the receivers. The intake code does not change when rules are added, removed or reordered.
- Each handler has a single responsibility, which makes rules easy to read, review and unit test.
- New rules are added by writing a new class and linking it in, without editing existing handlers, which follows the open/closed principle.
- Chains can be assembled differently per environment, tenant or warehouse from the same building blocks.
Cons
- There is no guarantee a request gets handled. Without a terminal handler or an explicit null check, a request can fall off the end silently.
- Behaviour depends on order, and that order lives in the wiring code rather than in the handlers, so a wrong ordering can be a subtle bug.
- Debugging is harder because you have to follow the request across several objects to see who decided and why.
- Each request may walk the whole chain, so cost is O(n) in the number of handlers. That is fine for a handful of rules but worth noticing for long chains on hot paths.
Relations with other guides
Patterns it's often confused or combined with.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
Both link objects that share an interface and forward calls. A decorator always delegates and adds behaviour around the call; a chain handler may stop the request and never forward it.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Requests passed down a chain are often packaged as command objects, so handlers can inspect, queue or log them in a uniform way.
- Composite Pattern: Treat Single Items and Groups Through One Interface
In a composite tree, a child can pass a request to its parent, which forms a natural chain from leaf to root, as in event bubbling in UI component trees.
- Mediator: Route Component Chatter Through One Coordinator
A mediator centralises who talks to whom, while a chain spreads the decision across a sequence of handlers that each decide for themselves whether to act.
- Observer Pattern: Notify Subscribers Without Coupling to Them
Observer delivers an event to every subscriber. Chain of Responsibility typically delivers a request to one handler, the first that accepts it.
- Replace Conditional with Polymorphism: One Class per Case
Turning a long if/else chain of rules into handler classes is a close cousin of this refactoring: each branch becomes a type that owns its own decision.
Common questions
Short answers to the usual doubts.
How is Chain of Responsibility different from Decorator?
The structure looks similar: objects with the same interface, each holding a reference to the next. The difference is intent and control flow. A decorator always calls the wrapped object and adds behaviour before or after. A chain handler decides whether to handle the request, and if it does, it usually stops the request there. In an interview, say that a decorator enriches every call while a chain picks one receiver, or lets any step cut the request short.
What happens if no handler accepts the request?
With the plain base class, the last handler forwards to nothing and the chain returns null, so the request is effectively dropped. You have two clean options: put a terminal catch-all handler at the end, as RecycleHandler does here, or have the client check for null and treat it as an error. Pick one deliberately; silently losing requests is the most common bug with this pattern.
Is HTTP middleware an example of Chain of Responsibility?
Yes, it is a common variant. In middleware pipelines each handler usually does some work and then calls the next one, and any of them can stop the request by returning a response early, for example when authentication fails. The classic form stops at the first handler that accepts the request; the pipeline form lets several handlers act on it. Both share the key idea that the sender does not know which handlers will run.
Why not keep the rules in a list and loop over them?
That is a perfectly good implementation. A loop over a list of rule objects, returning the first non-null result, gives you the same decoupling without linked next references and makes the order explicit in one array. Linked handlers are more useful when a handler needs to run code after the next one returns, or wrap it in something like a try/catch or timer. Mentioning both shows the interviewer you understand the pattern rather than its textbook shape.
What is the performance cost of a chain?
In the worst case a request visits every handler once, so handling is O(n) in the number of handlers, plus whatever each check costs. For a handful of business rules like the five here, that is negligible. With linked handlers each hop also adds a stack frame, so a very long chain processed recursively can be a concern; a loop-based version avoids that.
Where should the chain be wired?
In one place, such as a factory function or the application's composition root, not inside the handlers. Handlers should not know which handler follows them. Keeping the wiring central makes the order of rules visible, lets you build different chains per environment, and keeps every handler testable on its own.