Chain of Responsibility Pattern
Avoid coupling the sender of a request to its receiver — give more than one object a chance to handle the request.
📌 Key IdeaBuild a linked list (or ordered pipeline) of handlers. Each decides to process or forward. Used in servlet filters, middleware, approval workflows, logging pipelines.
Visual
⛓ Handler chain
Client ─▶ Auth ─▶ RateLimit ─▶ Cache ─▶ Controller
pass pass handle ✓Decouples client from which concrete handler applies.
When to Use
- More than one handler might satisfy — order matters (priority).
- You want handlers added/removed without editing core dispatcher.
- HTTP/JWT filter chains, Spring
HandlerInterceptor, AWS Lambda middleware.
When NOT to Use
- Exactly one responsible module — direct call is clearer.
- Chains grow unreadable without discipline — avoid 30-node chains.
Anti-Pattern (What NOT to Do)
One god method with stacked conditionalsBadjava
void handle(Request r) {
if (!authOk(r)) return;
if (rateLimited(r)) return;
if (cached(r)) return;
controller.exec(r); // order & duplication baked inHard to reorder, test pieces, or plug new stages.
The Right Way
Handlers linked — pass or forwardGoodjava
interface Handler { Handler next(Handler h); void handle(Request r); }
abstract class Base implements Handler {
private Handler next;
public Handler next(Handler h) { this.next = h; return this; }
protected void forward(Request r) { if (next != null) next.handle(r); }
}Servlet
FilterChain.doFilter is the same idea — ordered pipeline.Pros & Cons
👍 Pros
- Open/Closed — plug handlers without changing client.
- Single Responsibility per handler.
👎 Cons
- Hard to debug — flow implicit.
- Risk nobody handles → define fallback rules.
Common Confusions Cleared Up
Chain vs Decorator
Decorator always forwards inward eventually along one pipeline enhancing behaviour. Chain — any handler may terminate the chain; request might never reach the end.
Interview Q&A
Likely Follow-up Questions
- Pure functional middleware (
Req → Maybe Req) vs OO chain?
Quick Cheat Sheet
IntentPass request until someone handles it.
ExamplesServlet filters, Spring MVC interceptors.
RiskUnhandled fall-through.