Bird
Raised Fist0
LLDsystem_design~7 mins

Chain of Responsibility pattern in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When a request needs to be handled by one of many possible handlers, hardcoding the logic to decide which handler processes it leads to rigid, hard-to-maintain code. Adding new handlers or changing the order requires modifying existing code, increasing the risk of bugs and reducing flexibility.
Solution
This pattern passes the request along a chain of handlers. Each handler decides if it can process the request; if not, it forwards the request to the next handler in the chain. This way, handlers are loosely coupled, and new handlers can be added without changing existing code.
Architecture
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│ Handler 1   │ →→→ │ Handler 2   │ →→→ │ Handler 3   │
└─────────────┘     └─────────────┘     └─────────────┘
       ↓                  ↓                  ↓
    Handles?           Handles?           Handles?
       ↓                  ↓                  ↓
    Process            Process            Process
       ↓                  ↓                  ↓
    Or pass            Or pass            Or pass

The diagram shows a sequence of handlers linked in a chain. Each handler receives the request, decides whether to process it or pass it to the next handler.

Trade-offs
✓ Pros
Decouples sender and receiver, allowing flexible assignment of responsibilities.
Easily extendable by adding new handlers without modifying existing ones.
Supports dynamic changes in the chain order or composition at runtime.
✗ Cons
Request may pass through many handlers, causing performance overhead.
No guarantee a request will be handled if no handler matches.
Debugging can be harder due to indirect flow of control.
Use when multiple handlers can process a request and the handler is not known in advance. Suitable for systems with dynamic or extensible processing rules, especially when the number of handlers is moderate (less than a few dozen).
Avoid when performance is critical and the chain length is very long, or when the request must be handled by a specific handler deterministically.
Real World Examples
Java Standard Library
The java.util.logging framework uses Chain of Responsibility to pass log messages through a chain of handlers that decide whether to log or filter messages.
Microsoft ASP.NET
ASP.NET uses this pattern in its HTTP pipeline where multiple middleware components process or pass on HTTP requests.
Apache Tomcat
Tomcat uses a chain of Valve components to process HTTP requests, each Valve deciding whether to handle or forward the request.
Code Example
The before code has client logic deciding which handler to call, causing tight coupling and duplication. The after code creates a chain where each handler tries to process the request and passes it on if it cannot. This decouples client from handler logic and allows easy extension.
LLD
### Before: tightly coupled handlers
class HandlerA:
    def handle(self, request):
        if request == 'A':
            return 'Handled by A'
        else:
            return None

class HandlerB:
    def handle(self, request):
        if request == 'B':
            return 'Handled by B'
        else:
            return None

# Client code
request = 'B'
handler_a = HandlerA()
handler_b = HandlerB()
result = handler_a.handle(request)
if result is None:
    result = handler_b.handle(request)
print(result)

### After: Chain of Responsibility pattern
class Handler:
    def __init__(self, successor=None):
        self.successor = successor

    def handle(self, request):
        handled = self.process_request(request)
        if handled is None and self.successor:
            return self.successor.handle(request)
        return handled

    def process_request(self, request):
        raise NotImplementedError('Must override')

class HandlerA(Handler):
    def process_request(self, request):
        if request == 'A':
            return 'Handled by A'
        return None

class HandlerB(Handler):
    def process_request(self, request):
        if request == 'B':
            return 'Handled by B'
        return None

# Client code
handler_chain = HandlerA(HandlerB())
result = handler_chain.handle('B')
print(result)
OutputSuccess
Alternatives
Observer pattern
Observer notifies multiple listeners simultaneously, while Chain of Responsibility passes a request along a single chain until handled.
Use when: Choose Observer when multiple components need to react to the same event independently.
Strategy pattern
Strategy selects one algorithm at runtime, Chain of Responsibility passes a request through multiple handlers until one processes it.
Use when: Choose Strategy when you want to swap entire algorithms dynamically.
Summary
Chain of Responsibility passes a request through a chain of handlers until one processes it.
It decouples sender and receiver, allowing flexible and extensible request handling.
This pattern is useful when multiple handlers can process a request but the handler is not known in advance.

Practice

(1/5)
1. What is the main purpose of the Chain of Responsibility pattern in system design?
easy
A. To pass a request along a chain of handlers until one handles it
B. To create multiple copies of an object
C. To ensure only one instance of a class exists
D. To define a family of algorithms and make them interchangeable

Solution

  1. Step 1: Understand the pattern's behavior

    The Chain of Responsibility pattern allows a request to be passed along a chain of objects until one can handle it.
  2. Step 2: Compare options with the pattern's purpose

    The options describing singleton (one instance), prototype (object copies), and strategy (interchangeable algorithms) refer to other design patterns, not Chain of Responsibility.
  3. Final Answer:

    To pass a request along a chain of handlers until one handles it -> Option A
  4. Quick Check:

    Chain of Responsibility = pass request along chain [OK]
Hint: Remember: Chain passes request until handled [OK]
Common Mistakes:
  • Confusing with Singleton or Strategy patterns
  • Thinking it creates object copies
  • Assuming it handles all requests at once
2. Which of the following is the correct way to link handlers in a Chain of Responsibility pattern?
easy
A. Handlers are linked using a global static list
B. Handlers are independent and do not reference each other
C. Handlers communicate through a shared database
D. Each handler holds a reference to the next handler in the chain

Solution

  1. Step 1: Recall how handlers are connected

    In Chain of Responsibility, each handler has a reference to the next handler to pass the request along.
  2. Step 2: Evaluate other options

    Global static lists, shared databases, and independent handlers describe unrelated or incorrect linking methods that contradict the chain concept.
  3. Final Answer:

    Each handler holds a reference to the next handler in the chain -> Option D
  4. Quick Check:

    Handler links = next handler reference [OK]
Hint: Handlers link by referencing the next handler [OK]
Common Mistakes:
  • Using global lists instead of direct references
  • Assuming handlers are independent
  • Confusing with event broadcasting
3. Consider this simplified handler chain code snippet:
class Handler:
    def __init__(self, successor=None):
        self.successor = successor
    def handle(self, request):
        if self.can_handle(request):
            return f"Handled {request}"
        elif self.successor:
            return self.successor.handle(request)
        else:
            return "Not handled"
    def can_handle(self, request):
        return False

class ConcreteHandlerA(Handler):
    def can_handle(self, request):
        return request == 'A'

class ConcreteHandlerB(Handler):
    def can_handle(self, request):
        return request == 'B'

chain = ConcreteHandlerA(ConcreteHandlerB())
print(chain.handle('B'))

What is the output of this code?
medium
A. Handled B
B. Handled A
C. Not handled
D. Error

Solution

  1. Step 1: Trace the request through the chain

    The request 'B' is first checked by ConcreteHandlerA, which returns False for can_handle('B'). It passes the request to ConcreteHandlerB.
  2. Step 2: ConcreteHandlerB handles the request

    ConcreteHandlerB's can_handle('B') returns True, so it returns "Handled B".
  3. Final Answer:

    Handled B -> Option A
  4. Quick Check:

    Request 'B' handled by second handler [OK]
Hint: Request passes chain until a handler returns true [OK]
Common Mistakes:
  • Assuming first handler handles all requests
  • Confusing return values
  • Missing the chain passing logic
4. Given the following code snippet, identify the bug that breaks the Chain of Responsibility pattern:
class Handler:
    def __init__(self, successor=None):
        self.successor = successor
    def handle(self, request):
        if self.can_handle(request):
            return f"Handled {request}"
        else:
            return "Not handled"
    def can_handle(self, request):
        return False

class ConcreteHandler(Handler):
    def can_handle(self, request):
        return request == 'X'

chain = ConcreteHandler()
print(chain.handle('Y'))

What is the main issue here?
medium
A. The successor is not initialized properly
B. The can_handle method always returns True
C. The handler does not pass the request to the successor
D. The handle method has a syntax error

Solution

  1. Step 1: Analyze the handle method logic

    The handle method checks can_handle; if False, it returns "Not handled" immediately without passing to successor.
  2. Step 2: Identify missing chain passing

    It should call self.successor.handle(request) if successor exists, but this is missing.
  3. Final Answer:

    The handler does not pass the request to the successor -> Option C
  4. Quick Check:

    Missing successor call breaks chain [OK]
Hint: Always pass request to successor if not handled [OK]
Common Mistakes:
  • Forgetting to call successor.handle()
  • Assuming can_handle always returns True
  • Ignoring successor initialization
5. You are designing a logging system using the Chain of Responsibility pattern. You want to handle logs of different severity: DEBUG, INFO, WARNING, ERROR. Each handler should process logs at its level and pass higher severity logs down the chain. Which design best fits this requirement?
hard
A. Each handler processes only its level and passes all logs to the next handler
B. Each handler processes logs at its level and passes only higher severity logs to the next handler
C. Each handler processes all logs regardless of severity and stops the chain
D. Each handler processes logs randomly without order

Solution

  1. Step 1: Understand the logging severity flow

    Logs should be handled at their level, and higher severity logs should continue down the chain for further handling.
  2. Step 2: Evaluate options for correct chain behavior

    Each handler processes logs at its level and passes only higher severity logs to the next handler matches this: handlers process their level and pass higher severity logs onward. Each handler processes only its level and passes all logs to the next handler passes all logs regardless, which is inefficient. Each handler processes all logs regardless of severity and stops the chain stops chain prematurely. Each handler processes logs randomly without order is random and incorrect.
  3. Final Answer:

    Each handler processes logs at its level and passes only higher severity logs to the next handler -> Option B
  4. Quick Check:

    Process level, pass higher severity [OK]
Hint: Process own level, pass higher severity logs down [OK]
Common Mistakes:
  • Passing all logs without filtering
  • Stopping chain too early
  • Ignoring severity order