Chain of Responsibility
Intent
Pass a request along a chain of handlers until one of them handles it, so the sender never picks the receiver directly.
Motivation
A help desk gets tickets with severity 1, 2, or 3. Level 1 staff solve easy tickets, level 2 takes harder ones, and the manager takes the rest. Hard-coding “if severity then route” in the ticket form means every staffing change edits the form. Chaining handlers instead lets each level either resolve the ticket or forward it, and the form just hands the ticket to the head of the chain.
Structure
flowchart LR Client[Client Ticket Form] --> L1[Level1 Handler] L1 --> L2[Level2 Handler] L2 --> Mgr[Manager Handler]
- Client — submits the request to the head of the chain only.
- Handler (Level1, Level2, Manager) — checks whether it can handle the request; handles it or forwards to the next link.
- Successor link — each handler holds the next handler; the tail either handles everything or reports failure.
Consequences
- Benefit: sender and receivers stay decoupled; the chain can be reordered or extended without touching the sender.
- Cost: a request can fall off the end unhandled, and long chains are harder to trace when debugging.
Basic Recap
Chain of Responsibility passes a request along a sequence of handlers, allowing one to handle it, transform it, or forward it. The sender knows the entry point rather than the eventual handler, and the chain can be assembled for a context. Handlers share a contract but retain independent decisions. The design needs a clear termination rule and a defined outcome when nobody accepts the request.
Complex Scenario
A content publishing platform runs submitted posts through moderation handlers for malformed input, spam scoring, privacy checks, legal holds, and final acceptance. Each handler can reject, annotate and forward, or escalate for human review. Editorial teams configure different chains for comments and long-form articles without teaching the upload endpoint about every rule. The request carries a submission identifier and collected findings so later handlers can make decisions without repeating earlier work.
Edge cases
- Ordering: Running privacy redaction after spam analysis may be intentional, but reversing legal escalation and acceptance could publish held content; chain order must be validated and visible.
- Retries: Re-entering the chain after a transient model failure must not duplicate audit events or charge twice for completed external checks.
- Partial failure: If an optional spam provider is unavailable but legal screening is mandatory, each handler needs an explicit fail-open or fail-closed policy rather than one chain-wide guess.
An unhandled or exhausted chain should return a typed outcome, not silently accept the content by falling off the end.
Sketch (illustrative pseudocode, not runnable):
ModerationChain.submit(post):
context = ModerationContext(post, findings = {})
outcome = firstHandler.handle(context)
return outcome # Accepted, Rejected, or NeedsReview; never implicit null
Handler.handle(context):
checkpoint = journal.completed(context.submissionId, this.name)
if not checkpoint:
checkpoint = this.evaluate(context)
journal.record(context.submissionId, this.name, checkpoint)
return route(checkpoint, nextHandler, terminalPolicy)
When to Use / When Not to Use
Use when:
- More than one unit could handle a request and the right one depends on runtime data like severity.
- The set or order of handlers changes often.
Avoid when:
- Exactly one receiver is known at send time, or every request must be guaranteed handled by a specific unit.
Examples
examples/elixir/chain-of-responsibility/examples/dart/chain-of-responsibility/examples/go/chain-of-responsibility/examples/rust/chain-of-responsibility/
Expected outcome: a severity-2 ticket passes Level1 and is handled at Level2, printing two lines.
Anti-pattern / Failure Mode
-
Misuse: A chain where no handler claims the request and the drop is silent.
-
Review signal: Requests falling through with no observability on who saw them.
-
Misuse symptom: A fixed routing table is turned into a long mutable chain, and developers must debug every handler to discover why a request disappeared. Handlers that both perform business side effects and secretly rebuild their successors make behavior depend on invocation history.
-
Review signal: Look for handlers returning null when they decline, missing terminal handlers, runtime link mutation, and no tests for exhausted chains. Dashboards should expose the last completed handler and final outcome; a spike in requests with neither indicates that flexibility has removed accountability.
Related
- Command — pass along vs package as an object.
- Mediator — chain vs hub routing.
- Complete Mediation — check on every access in the chain.
Exercise
Add a severity-3 ticket that reaches the manager. Then add a severity-9 ticket and decide: should the tail print “unhandled”, or should the manager handle anything? Document your choice.
Self-check
- Who picks the final handler?
Answer
No one up front — each handler decides locally to handle or forward, so the receiver emerges from the chain walk. - What happens with no willing handler?
Answer
The request exits the tail unhandled unless you add a default handler or an explicit failure report. - Chain vs Strategy: what differs?
Answer
Strategy picks one variant up front; Chain tries handlers in order until one claims the request.