Lesson 8 of 17 2 min

LLD Lesson: The Chain of Responsibility Pattern

Learn how to decouple request senders from receivers using a chain of handlers. Perfect for middleware, logging, and validation pipelines.

1. The Problem: The Large Validation Method

Imagine a login request that needs to pass through:

  1. Auth Check (Is the user in the DB?)
  2. Rate Limit Check (Has the user tried 10 times in 1 min?)
  3. Role Check (Is the user an Admin?)
  4. Logging (Record the attempt).

If you put this all in one method, it becomes a "Monster Method" that is impossible to unit test and modify.

2. The Solution: Chain of Responsibility

We break each check into a separate Handler class. Each handler has a reference to the Next handler in the chain.

Step 1: The Handler Base

public abstract class Handler {
    private Handler next;

    public void setNext(Handler next) { this.next = next; }

    public void handle(Request req) {
        if (process(req) && next != null) {
            next.handle(req);
        }
    }

    protected abstract boolean process(Request req);
}

Step 2: Concrete Handlers

public class AuthHandler extends Handler {
    protected boolean process(Request req) {
        // Logic...
        return true; // Pass to next
    }
}

3. Real-world Intuition: The Support Call

  • Level 1: Basic reset password? (Handled).
  • Level 2: Bug in the app? (Forwarded to Level 2).
  • Level 3: Server down? (Forwarded to Level 3).

4. Interview Discussion

  • Pros: Follows SRP and OCP. You can add or reorder handlers without changing client code.
  • Cons: A request might reach the end of the chain without being handled (always have a "Default Handler").

Final Takeaway

The Chain of Responsibility is about Pipeline Processing. Use it when you have a sequence of logic that could vary in order or complexity.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.