Design Patterns

Pattern 13 of 23, Behavioral family

Chain of Responsibility

Pass a request along a chain of handlers: each one handles it, stops it, or forwards it to the next.

The problem

A request has to go through authentication, rate limiting, validationโ€ฆ Piling everything into the controller creates a monolithic block of ifs that is impossible to reorder or reuse.

The solution

Turn each check into a standalone handler that holds a reference to the next one. The chain is assembled freely; each link decides whether to cut it short or carry on.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The request enters the first link.
  2. Valid token โ†’ forwarded to the next link.
  3. 12 req/min < 60 โ†’ next.
  4. Invalid body: Validation responds and cuts the chain. The Controller is never reached.
  5. New request, valid this time.
  6. Auth โ†’ RateLimit: next()
  7. RateLimit โ†’ Validation: next()
  8. Every link has approved: the Controller handles the request.

An analogy

Tech support: level 1, then level 2, then the expert. Each one solves the issue or escalates to the next.

When to use it

  • HTTP middlewares (Laravel, Express, ASP.NET, Go)
  • Validation pipelines / filters
  • Event handling (DOM bubbling)

Pros and cons

Pros

  • Configurable processing order
  • Single Responsibility per link
  • Add / remove links without touching the others

Cons

  • A request can go through the chain without being handled
  • Flow is less straightforward to debug

Implementations

The same example, written idiomatically in each language.

Chain of Responsibility in Python

chain-of-responsibility.py 30 lines
class Handler:
    def __init__(self):
        self._next: "Handler | None" = None

    def then(self, nxt: "Handler") -> "Handler":
        self._next = nxt
        return nxt

    def handle(self, req: dict) -> str:
        return self._next.handle(req) if self._next else "200 OK"


class Auth(Handler):
    def handle(self, req):
        return "401" if not req.get("token") else super().handle(req)

class RateLimit(Handler):
    def handle(self, req):
        return "429" if req.get("rpm", 0) > 60 else super().handle(req)

class Validation(Handler):
    def handle(self, req):
        return "422" if "body" not in req else super().handle(req)


chain = Auth()
chain.then(RateLimit()).then(Validation())

print(chain.handle({"token": "x", "rpm": 12}))               # 422
print(chain.handle({"token": "x", "rpm": 12, "body": {}}))   # 200 OK

Chain of Responsibility in TypeScript

chain-of-responsibility.ts 16 lines
type Req = { token?: string; rpm: number; body?: unknown };
type Middleware = (req: Req, next: () => string) => string;

const auth: Middleware = (r, next) => (r.token ? next() : "401");
const rateLimit: Middleware = (r, next) => (r.rpm > 60 ? "429" : next());
const validate: Middleware = (r, next) => (r.body ? next() : "422");
const controller = () => "200 OK";

function chain(mws: Middleware[], final: () => string) {
  return (req: Req): string =>
    mws.reduceRight<() => string>((next, mw) => () => mw(req, next), final)();
}

const handle = chain([auth, rateLimit, validate], controller);
handle({ token: "x", rpm: 12 });           // "422"
handle({ token: "x", rpm: 12, body: {} }); // "200 OK"

Chain of Responsibility in Java

chain-of-responsibility.java 28 lines
abstract class Handler {
    private Handler next;

    Handler then(Handler next) {
        this.next = next;
        return next;
    }

    String handle(Request r) {
        return next == null ? "200 OK" : next.handle(r);
    }
}

class Auth extends Handler {
    String handle(Request r) { return r.token() == null ? "401" : super.handle(r); }
}
class RateLimit extends Handler {
    String handle(Request r) { return r.rpm() > 60 ? "429" : super.handle(r); }
}
class Validation extends Handler {
    String handle(Request r) { return r.body() == null ? "422" : super.handle(r); }
}

record Request(String token, int rpm, String body) {}

Handler chain = new Auth();
chain.then(new RateLimit()).then(new Validation());
chain.handle(new Request("tok", 12, null)); // 422

Chain of Responsibility in C#

chain-of-responsibility.cs 25 lines
abstract class Handler
{
    private Handler? _next;

    public Handler Then(Handler next) { _next = next; return next; }

    public virtual string Handle(Request r) => _next?.Handle(r) ?? "200 OK";
}

class Auth : Handler
{
    public override string Handle(Request r) => r.Token is null ? "401" : base.Handle(r);
}
class RateLimit : Handler
{
    public override string Handle(Request r) => r.Rpm > 60 ? "429" : base.Handle(r);
}

record Request(string? Token, int Rpm);

var chain = new Auth();
chain.Then(new RateLimit());
Console.WriteLine(chain.Handle(new Request("tok", 12)));   // 200 OK

// ASP.NET Core: app.Use(async (ctx, next) => { โ€ฆ; await next(); });

Chain of Responsibility in PHP

chain-of-responsibility.php 36 lines
abstract class Handler
{
    private ?Handler $next = null;

    public function then(Handler $next): Handler
    {
        $this->next = $next;
        return $next;
    }

    public function handle(array $req): string
    {
        return $this->next?->handle($req) ?? '200 OK';
    }
}

class Auth extends Handler
{
    public function handle(array $req): string
    {
        return empty($req['token']) ? '401' : parent::handle($req);
    }
}

class RateLimit extends Handler
{
    public function handle(array $req): string
    {
        return ($req['rpm'] ?? 0) > 60 ? '429' : parent::handle($req);
    }
}

$chain = new Auth();
$chain->then(new RateLimit());
echo $chain->handle(['token' => 'x', 'rpm' => 12]); // 200 OK
// This is exactly how Laravel's middleware pipeline works

Chain of Responsibility in Go

chain-of-responsibility.go 20 lines
type Middleware func(next http.Handler) http.Handler

func Auth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Authorization") == "" {
            http.Error(w, "unauthorized", http.StatusUnauthorized)
            return // the chain stops here
        }
        next.ServeHTTP(w, r) // otherwise move on to the next link
    })
}

func Chain(h http.Handler, mws ...Middleware) http.Handler {
    for i := len(mws) - 1; i >= 0; i-- {
        h = mws[i](h)
    }
    return h
}

http.Handle("/api", Chain(controller, Auth, RateLimit, Validate))

Frequently asked questions

What is the Chain of Responsibility design pattern?

Pass a request along a chain of handlers: each one handles it, stops it, or forwards it to the next. Turn each check into a standalone handler that holds a reference to the next one. The chain is assembled freely; each link decides whether to cut it short or carry on.

When should you use the Chain of Responsibility pattern?

HTTP middlewares (Laravel, Express, ASP.NET, Go); Validation pipelines / filters; Event handling (DOM bubbling).

What are the pros and cons of the Chain of Responsibility pattern?

Pros: Configurable processing order; Single Responsibility per link; Add / remove links without touching the others. Cons: A request can go through the chain without being handled; Flow is less straightforward to debug.