Skip to content

Chain of Responsibility: Pass a Request Along Until One Handles It

Learn Chain of Responsibility by routing returned parcels through a chain of disposition handlers, with TypeScript, Python and PHP code.

14 min readDesign patternBehavioural

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.

Parcelbay returns: the intake calls the head of a chain of disposition handlers, each holding a reference to the next.ReturnsIntake calls ReturnHandler (handle(item)). ReturnsIntake creates ReturnedItem. BaseReturnHandler implements ReturnHandler. BaseReturnHandler has a ReturnHandler (next). RestockHandler inherits from BaseReturnHandler. VendorTakeBackHandler inherits from BaseReturnHandler. RefurbishHandler inherits from BaseReturnHandler. DonateHandler inherits from BaseReturnHandler. RecycleHandler inherits from BaseReturnHandler.ReturnsIntakecallschain.handle(item)«interface»ReturnHandlersetNext(),handle(item)Wiring orderrestock > vendor >refurbish > donate …«abstract»BaseReturnHandlernext: ReturnHandler;forwards by defaultReturnedItemsku, category,vendor, sealed…RestockHandlersealed and <= 30daysVendorTakeBackHandlervendor has atake-back contractRefurbishHandlerelectronics, repair<= 40% of priceDonateHandlerapparelRecycleHandlercatch-all, neverforwardshandle(item)next
Parcelbay returns: the intake calls the head of a chain of disposition handlers, each holding a reference to the next.

Participants

ReturnHandler (Handler interface)
Declares the contract every link follows: setNext to attach the following handler and handle to 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 handle to 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)

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.

  1. 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.

  2. Write a base handler that stores a reference to the next handler and implements the default behaviour of forwarding. Have setNext return the handler it received so you can chain the wiring calls.

  3. 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.

  4. Decide what happens when nobody handles the request. Either add a terminal catch-all handler, as RecycleHandler does here, or let the base return null and have the client deal with it explicitly.

  5. 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.

  6. Give the client only the head of the chain and replace the old conditional call with head.handle(request).

  7. 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.

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.

Next guide2 of 10 · Behavioral patternsCommand Pattern: Turn Requests into Objects You Can Queue and UndoRead the next one