Programming Search⌘K

Patterncore

Chain of Responsibility pattern

Also called Chain of Responsibility, CoR, handler chain, middleware chain.

A request passes along a chain of handler objects. Each handler either handles it or passes it to the next one, so the sender does not know which object will handle it.

Family
behavioral-design
Intent
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Intent

Avoid coupling the sender of a request to its receiver, by giving more than one object a chance to handle the request. Chain the receiving objects, and pass the request along the chain until an object handles it.1 The sender knows only the first link. Each link knows only the next one.

Problem

Design Patterns starts from context-sensitive help in a graphical user interface.1 A user asks for help on a part of the screen, such as a button. The button may have its own help text. If it does not, the dialog box that holds the button may have help text. If the dialog has none, the application gives a general answer. The object that gets the request is the button, but the object that answers may be any object above it.

The forces are these. The sender does not know which object will answer, and it should not need to know. The set of objects that can answer changes while the program runs, as windows open and close. And the rule for choosing one should not be a long conditional in the sender, because each change to the set of handlers would then change the sender. Design Patterns gives three cases where the pattern applies: more than one object may handle a request and the handler is not known in advance, the sender should not name the receiver, and the set of handlers should be specified at run time.1

Solution

Design Patterns names three participants.1

  • Handler defines the interface for handling requests. It may also hold the link to the successor.
  • ConcreteHandler handles the requests that it is responsible for. If it cannot handle a request, it passes it to its successor.
  • Client sends the request to the first handler in the chain.

A handler that cannot answer a request passes it on. The request moves along the chain until one handler answers it. If no handler answers, the request falls off the end of the chain with no answer:

This code runs but gives a wrong answer on purpose.

class Handler:
    def __init__(self, successor=None):
        self.successor = successor

    def help(self, topic):
        if self.successor is not None:
            return self.successor.help(topic)
        # No successor: the request falls off the end, and help returns None.


class Button(Handler):
    def help(self, topic):
        if topic == "print":
            return "button: prints the page"
        return super().help(topic)


class Dialog(Handler):
    def help(self, topic):
        if topic == "margins":
            return "dialog: sets the page margins"
        return super().help(topic)


button = Button(successor=Dialog())
for topic in ["print", "margins", "shortcuts"]:
    print(f"{topic}: {button.help(topic)}")
Output
print: button: prints the page
margins: dialog: sets the page margins
shortcuts: None

Design Patterns calls this a consequence of the pattern: receipt is not guaranteed.1 The sender cannot tell that no handler took the request, and Python gives back None with no error. Put a handler at the end that answers every request, such as an application object with general help, or make the last link raise an error. The Java example answers 404 when no handler is left. The TypeScript example makes the last link a different type from the other links, so it cannot pass a request on.

Design Patterns gives two ways to build the chain.1 Each handler can hold a field for its successor, as Handler does above. Or the chain can use links that the objects already have. In a user interface, each widget already knows its parent, so the parent is the successor. This is why the pattern is often used with Composite. See Composite pattern.

A third form keeps the handlers in a list, and a loop asks each one in turn. No handler knows the next one. The OpenerDirector in Python's urllib.request works this way. Its _call_chain method calls each handler for a kind of request. A handler returns None when it cannot answer and another handler could, and the loop returns the first answer that is not None.3 The handlers are sorted, and the stage of opening a URL ends when a handler returns a response or raises an exception.4

Representing requests

Design Patterns lists three ways to represent a request.1 Each kind of request can be a separate method of the handler, as help is above. A single method can take a code that names the kind of request. Or the request can be an object, so that handlers can pass any data along with it. The examples in this node use a request object with a user and a path. A request object is close to a command. See Command pattern.

Middleware

In the form from Design Patterns, one handler answers and the others only pass the request on. Web servers use a related form, called middleware. Each link can do work before it calls the next link, and work after the next link returns. A link can also answer at once and not call the next link.

ASP.NET Core describes its request pipeline in this way. Calls to Use chain the request delegates together, and a parameter next represents the next delegate in the pipeline. A delegate that does not pass the request to next short-circuits the pipeline.9 The documentation also says that the order of the middleware in the program is the order in which they run on a request, the reverse order for the response, and that this order can be critical for security, performance and functionality.10

The order is a dependency that the type system does not check. Here a shared cache, keyed only by the path, runs before the check that the user signed in:

This code runs but gives a wrong answer on purpose.

def chain(handlers, last):
    call = last
    for handler in reversed(handlers):
        call = lambda request, handler=handler, next=call: handler(request, next)
    return call


def auth(request, next):
    if request["user"] is None:
        return 401, "sign in first"
    return next(request)


saved = {}


def cache(request, next):
    # A shared cache, keyed by the path only.
    if request["path"] not in saved:
        saved[request["path"]] = next(request)
    return saved[request["path"]]


def app(request):
    return 200, f"report for {request['user']}"


serve = chain([cache, auth], app)
print(serve({"user": "ada", "path": "/report"}))
print(serve({"user": None, "path": "/report"}))
Output
(200, 'report for ada')
(200, 'report for ada')

The second request has no user, but it gets the report for ada. The cache answered it, so auth never saw it. With the chain [auth, cache], the second request gets 401. The examples put the authentication check before the cache, and also key the cache by the user.

Middleware and Decorator

A link that always calls the next link, and only adds work before or after the call, is a decorator: it has the same interface as the object it wraps and adds behaviour to it. The decorator node shows middleware as a chain of decorators. See Decorator pattern. A link that may answer and not call the next link is a handler in a chain of responsibility. Most middleware stacks hold both kinds. In the examples, log is a decorator, and auth and cache can end the chain.

Functions in place of handler classes

Norvig lists Chain of Responsibility as one of six patterns of Design Patterns that first-class types make invisible or less complex.2 In the languages of the examples, first-class functions do most of this work:

  • A handler is a function that takes the request and next, the rest of the chain. The chain is a list of these functions, folded from the end. This replaces the abstract class and the successor field. The Python, JavaScript, TypeScript and C++ examples use this form. See Higher-order function.
  • State that a handler needs, such as the map of the cache, lives in a closure. See Closure.
  • In Go, http.Handler is an interface with one method, ServeHTTP.11 A link is a function that takes the next http.Handler and returns an http.Handler. The standard library has links of this shape: StripPrefix returns a handler that removes a prefix from the path and calls the handler it was given, and it answers 404 itself when the path does not have the prefix.12
  • In C#, DelegatingHandler is a handler that passes the processing of HTTP response messages to another handler, called the inner handler.13 The C# example builds the chain from it.

Exceptions are a chain of responsibility that the language runs. A raised exception moves from a function to its caller, and to the caller of that function, until a try block with a matching handler takes it. A handler can also raise it again, to pass it on. See Exception.

Example

All the example files run the same chain on three requests. The chain logs each request, rejects a request with no user, and caches answers by user and path. The first request goes to the application. The second request stops at the check for a user. The third request gets the answer from the cache.

Language Chain
Python functions of the request and next, folded into a chain
JavaScript functions of the request and next, folded with reduceRight
TypeScript the same, with types for Handler and Next
Java an abstract Handler with a successor field, as in Design Patterns
C# DelegatingHandler subclasses, sent through HttpMessageInvoker
Go net/http middleware of type func(http.Handler) http.Handler
Rust trait objects in a Vec, and a Next that holds the rest of the slice
C++ a std::vector of std::function, with an index for the next link
PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class Request:
    user: str | None
    path: str


# Each handler takes the request and the rest of the chain. It answers, or it calls next.
def log(request, next):
    print(f"log: {request.path} from {request.user or 'nobody'}")
    return next(request)


def auth(request, next):
    if request.user is None:
        return 401, "sign in first"
    return next(request)


def make_cache():
    saved = {}

    def cache(request, next):
        key = (request.user, request.path)
        if key in saved:
            status, body = saved[key]
            return status, body + " (cached)"
        saved[key] = next(request)
        return saved[key]

    return cache


def app(request):
    return 200, f"report for {request.user}"


def chain(handlers, last):
    # Build the chain from the end: each link holds the handler and the link after it.
    call = last
    for handler in reversed(handlers):
        call = lambda request, handler=handler, next=call: handler(request, next)
    return call


serve = chain([log, auth, make_cache()], app)
for request in [Request("ada", "/report"), Request(None, "/report"), Request("ada", "/report")]:
    status, body = serve(request)
    print(status, body)
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. Each handler is a function that takes the request and next, the rest of the chain. This is the middleware form used by web frameworks.
  • chain builds the links from the end. The default arguments handler=handler, next=call bind the values of this pass of the loop, because a closure reads a variable when it runs, not when it is made.
  • A handler that returns without calling next ends the chain. auth does this for a request with no user, so the cache and the application never see it.
  • The cache holds its dictionary in a closure, so each chain made with make_cache() has its own cache.
#include <cstddef>
#include <functional>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <utility>
#include <vector>

struct Request {
    std::optional<std::string> user;
    std::string path;
};

struct Response {
    int status;
    std::string body;
};

using Next = std::function<Response(const Request&)>;
using Handler = std::function<Response(const Request&, const Next&)>;

// run calls handler i, and gives it a Next that calls handler i + 1.
Response run(const std::vector<Handler>& handlers, const Next& last, std::size_t i, const Request& request) {
    if (i == handlers.size()) {
        return last(request);
    }
    Next next = [&](const Request& r) { return run(handlers, last, i + 1, r); };
    return handlers[i](request, next);
}

int main() {
    Handler log = [](const Request& request, const Next& next) {
        std::cout << "log: " << request.path << " from " << request.user.value_or("nobody") << "\n";
        return next(request);
    };
    Handler auth = [](const Request& request, const Next& next) {
        if (!request.user) {
            return Response{401, "sign in first"};
        }
        return next(request);
    };
    std::map<std::pair<std::string, std::string>, Response> saved;
    Handler cache = [&saved](const Request& request, const Next& next) {
        auto key = std::pair{request.user.value_or(""), request.path};
        if (auto hit = saved.find(key); hit != saved.end()) {
            return Response{hit->second.status, hit->second.body + " (cached)"};
        }
        Response response = next(request);
        saved.emplace(key, response);
        return response;
    };
    Next app = [](const Request& request) { return Response{200, "report for " + request.user.value_or("")}; };

    std::vector<Handler> handlers{log, auth, cache};
    for (auto user : {std::optional<std::string>{"ada"}, std::optional<std::string>{}, std::optional<std::string>{"ada"}}) {
        Response response = run(handlers, app, 0, Request{user, "/report"});
        std::cout << response.status << " " << response.body << "\n";
    }
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. Each handler is a std::function that takes the request and next. run makes next for handler i as a lambda that calls run for handler i + 1.
  • The lambda for next captures by reference. This is safe because next does not outlive the call of run that made it.
  • The cache lambda captures the map saved by reference, so the map must outlive the chain. Here both live in main.
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
    record Request(String user, String path) {}

    record Response(int status, String body) {}

    // The classic form: each handler holds a reference to its successor.
    abstract static class Handler {
        private Handler next;

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

        Response handle(Request request) {
            if (next == null) {
                return new Response(404, "no handler for " + request.path());
            }
            return next.handle(request);
        }
    }

    static class Log extends Handler {
        @Override
        Response handle(Request request) {
            String user = request.user() == null ? "nobody" : request.user();
            System.out.println("log: " + request.path() + " from " + user);
            return super.handle(request);
        }
    }

    static class Auth extends Handler {
        @Override
        Response handle(Request request) {
            if (request.user() == null) {
                return new Response(401, "sign in first");
            }
            return super.handle(request);
        }
    }

    static class Cache extends Handler {
        private final Map<Request, Response> saved = new HashMap<>();

        @Override
        Response handle(Request request) {
            Response hit = saved.get(request);
            if (hit != null) {
                return new Response(hit.status(), hit.body() + " (cached)");
            }
            Response response = super.handle(request);
            saved.put(request, response);
            return response;
        }
    }

    static class App extends Handler {
        @Override
        Response handle(Request request) {
            return new Response(200, "report for " + request.user());
        }
    }

    public static void main(String[] args) {
        Handler first = new Log();
        first.then(new Auth()).then(new Cache()).then(new App());

        Request[] requests = {
            new Request("ada", "/report"), new Request(null, "/report"), new Request("ada", "/report"),
        };
        for (Request request : requests) {
            Response response = first.handle(request);
            System.out.println(response.status() + " " + response.body());
        }
    }
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. This is the structure from Design Patterns: an abstract Handler with a successor field, and concrete handlers that override handle.
  • The default handle in the base class passes the request to the successor. A concrete handler calls super.handle to pass it on, and returns its own Response to stop.
  • then returns its argument, so the calls chain in the order that the requests flow.
  • The base class answers 404 when there is no successor. Without this default, a request that no handler takes would fall off the end with no answer.
  • A record has equals and hashCode from its components, so Request works as a key of the cache.
  • The Servlet API has the same shape in Filter and FilterChain, but it is not part of the Java SE standard library.
using System.Net;
using static Shared;

// DelegatingHandler is the standard library's chain of responsibility for HTTP clients.
// Each handler has an InnerHandler, and base.SendAsync passes the request to it.
var app = new AppHandler();
var cache = new CacheHandler { InnerHandler = app };
var auth = new AuthHandler { InnerHandler = cache };
var log = new LogHandler { InnerHandler = auth };
using var invoker = new HttpMessageInvoker(log);

string?[] users = ["ada", null, "ada"];
foreach (var user in users)
{
    var request = new HttpRequestMessage(HttpMethod.Get, "http://shop.example/report");
    if (user is not null)
    {
        request.Headers.Add("X-User", user);
    }
    var response = await invoker.SendAsync(request, CancellationToken.None);
    var body = await response.Content.ReadAsStringAsync();
    Console.WriteLine($"{(int)response.StatusCode} {body}");
}

static class Shared
{
    public static string? UserOf(HttpRequestMessage request) =>
        request.Headers.TryGetValues("X-User", out var values) ? values.First() : null;

    public static HttpResponseMessage Reply(HttpStatusCode status, string body) =>
        new(status) { Content = new StringContent(body) };
}

class LogHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
    {
        Console.WriteLine($"log: {request.RequestUri!.AbsolutePath} from {UserOf(request) ?? "nobody"}");
        return base.SendAsync(request, token);
    }
}

class AuthHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) =>
        UserOf(request) is null
            ? Task.FromResult(Reply(HttpStatusCode.Unauthorized, "sign in first"))
            : base.SendAsync(request, token);
}

class CacheHandler : DelegatingHandler
{
    private readonly Dictionary<(string?, string), (HttpStatusCode, string)> saved = [];

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
    {
        var key = (UserOf(request), request.RequestUri!.AbsolutePath);
        if (saved.TryGetValue(key, out var hit))
        {
            return Reply(hit.Item1, hit.Item2 + " (cached)");
        }
        var response = await base.SendAsync(request, token);
        saved[key] = (response.StatusCode, await response.Content.ReadAsStringAsync(token));
        return response;
    }
}

// The last link is a plain HttpMessageHandler. It has no inner handler, so it must answer.
class AppHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) =>
        Task.FromResult(Reply(HttpStatusCode.OK, $"report for {UserOf(request)}"));
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: stdlib. System.Net.Http.DelegatingHandler is a handler with a successor, the InnerHandler property. base.SendAsync passes the request on. HttpMessageInvoker sends a request into the first handler.
  • No request goes to the network. AppHandler is the last link and answers every request itself.
  • HttpClient takes the same chain in its constructor. Libraries add retries, logging and authentication to outgoing requests in this way.
  • The helpers UserOf and Reply live in a static class. Local functions of the top-level statements cannot be used inside other classes, so using static Shared brings the helpers into scope instead.
JavaScriptGitHub
// Each handler takes the request and next, the rest of the chain.
const log = (request, next) => {
  console.log(`log: ${request.path} from ${request.user ?? "nobody"}`);
  return next(request);
};

const auth = (request, next) => (request.user ? next(request) : [401, "sign in first"]);

function makeCache() {
  const saved = new Map();
  return (request, next) => {
    const key = `${request.user} ${request.path}`;
    if (saved.has(key)) {
      const [status, body] = saved.get(key);
      return [status, `${body} (cached)`];
    }
    const response = next(request);
    saved.set(key, response);
    return response;
  };
}

const app = (request) => [200, `report for ${request.user}`];

// reduceRight builds the chain from the end, so the first handler runs first.
const chain = (handlers, last) =>
  handlers.reduceRight((next, handler) => (request) => handler(request, next), last);

const serve = chain([log, auth, makeCache()], app);
for (const request of [
  { user: "ada", path: "/report" },
  { user: null, path: "/report" },
  { user: "ada", path: "/report" },
]) {
  const [status, body] = serve(request);
  console.log(status, body);
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. A handler is a function of the request and next. Express and Koa use this shape for middleware, with a response object or a context in place of the return value.
  • reduceRight folds the list from the end. Each step wraps the chain so far in one more handler.
  • Each call of the arrow function in reduceRight has its own next and handler parameters, so the links do not share a variable. The Python example needs default arguments to get the same effect.
TypeScriptGitHub
type Request = { user: string | null; path: string };
type Response = { status: number; body: string };
type Next = (request: Request) => Response;
type Handler = (request: Request, next: Next) => Response;

const log: Handler = (request, next) => {
  console.log(`log: ${request.path} from ${request.user ?? "nobody"}`);
  return next(request);
};

const auth: Handler = (request, next) =>
  request.user === null ? { status: 401, body: "sign in first" } : next(request);

function makeCache(): Handler {
  const saved = new Map<string, Response>();
  return (request, next) => {
    const key = `${request.user} ${request.path}`;
    const hit = saved.get(key);
    if (hit !== undefined) {
      return { ...hit, body: `${hit.body} (cached)` };
    }
    const response = next(request);
    saved.set(key, response);
    return response;
  };
}

const app: Next = (request) => ({ status: 200, body: `report for ${request.user}` });

function chain(handlers: Handler[], last: Next): Next {
  return handlers.reduceRight<Next>((next, handler) => (request) => handler(request, next), last);
}

const serve = chain([log, auth, makeCache()], app);
const requests: Request[] = [
  { user: "ada", path: "/report" },
  { user: null, path: "/report" },
  { user: "ada", path: "/report" },
];
for (const request of requests) {
  const { status, body } = serve(request);
  console.log(status, body);
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. The types Handler and Next say what a link is: a function that receives the request and the rest of the chain, and must return a Response.
  • The last link is a Next, not a Handler. It takes no successor, so it must answer, and a request cannot fall off the end of the chain.
  • reduceRight<Next> names the type of the value that the fold builds: at each step, the rest of the chain is a Next.
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

// Middleware is the usual Go form of a link: it takes the rest of the chain
// and returns a handler that does its own work and then may call next.
type Middleware func(next http.Handler) http.Handler

func logRequests(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user := r.Header.Get("X-User")
		if user == "" {
			user = "nobody"
		}
		fmt.Printf("log: %s from %s\n", r.URL.Path, user)
		next.ServeHTTP(w, r)
	})
}

func requireUser(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-User") == "" {
			http.Error(w, "sign in first", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func cache(next http.Handler) http.Handler {
	saved := map[string]string{}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := r.Header.Get("X-User") + " " + r.URL.Path
		if body, ok := saved[key]; ok {
			fmt.Fprint(w, body+" (cached)")
			return
		}
		record := httptest.NewRecorder()
		next.ServeHTTP(record, r)
		saved[key] = record.Body.String()
		w.WriteHeader(record.Code)
		fmt.Fprint(w, record.Body.String())
	})
}

func app(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "report for %s", r.Header.Get("X-User"))
}

// chain wraps from the last middleware to the first, so the first one runs first.
func chain(last http.Handler, middleware ...Middleware) http.Handler {
	for i := len(middleware) - 1; i >= 0; i-- {
		last = middleware[i](last)
	}
	return last
}

func main() {
	serve := chain(http.HandlerFunc(app), logRequests, requireUser, cache)
	for _, user := range []string{"ada", "", "ada"} {
		r := httptest.NewRequest(http.MethodGet, "/report", nil)
		if user != "" {
			r.Header.Set("X-User", user)
		}
		w := httptest.NewRecorder()
		serve.ServeHTTP(w, r)
		fmt.Println(w.Code, strings.TrimSpace(w.Body.String()))
	}
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: stdlib. net/http has no chain type, but http.Handler and http.HandlerFunc make a link a function of type func(http.Handler) http.Handler. Go web code calls this middleware.
  • httptest.NewRequest and httptest.NewRecorder drive the chain without a network. The cache also uses a recorder to capture the answer of the rest of the chain.
  • http.Error ends its body with a newline, so main trims the body before it prints it.
  • The cache map has no lock. A real server calls handlers from many goroutines, so it needs a sync.Mutex around the map.
RustGitHub
use std::cell::RefCell;
use std::collections::HashMap;

#[derive(Clone, PartialEq, Eq, Hash)]
struct Request {
    user: Option<String>,
    path: String,
}

type Response = (u16, String);

trait Handler {
    fn handle(&self, request: &Request, next: Next) -> Response;
}

// Next is the rest of the chain: the handlers that are left, and the last step.
#[derive(Clone, Copy)]
struct Next<'a> {
    rest: &'a [Box<dyn Handler>],
    last: &'a dyn Fn(&Request) -> Response,
}

impl Next<'_> {
    fn run(self, request: &Request) -> Response {
        match self.rest.split_first() {
            Some((first, rest)) => first.handle(request, Next { rest, last: self.last }),
            None => (self.last)(request),
        }
    }
}

struct Log;
impl Handler for Log {
    fn handle(&self, request: &Request, next: Next) -> Response {
        let user = request.user.as_deref().unwrap_or("nobody");
        println!("log: {} from {}", request.path, user);
        next.run(request)
    }
}

struct Auth;
impl Handler for Auth {
    fn handle(&self, request: &Request, next: Next) -> Response {
        match request.user {
            None => (401, "sign in first".to_string()),
            Some(_) => next.run(request),
        }
    }
}

#[derive(Default)]
struct Cache {
    saved: RefCell<HashMap<Request, Response>>,
}
impl Handler for Cache {
    fn handle(&self, request: &Request, next: Next) -> Response {
        if let Some((status, body)) = self.saved.borrow().get(request) {
            return (*status, format!("{body} (cached)"));
        }
        let response = next.run(request);
        self.saved.borrow_mut().insert(request.clone(), response.clone());
        response
    }
}

fn app(request: &Request) -> Response {
    (200, format!("report for {}", request.user.as_deref().unwrap_or("")))
}

fn main() {
    let handlers: Vec<Box<dyn Handler>> = vec![Box::new(Log), Box::new(Auth), Box::new(Cache::default())];
    let serve = Next { rest: &handlers, last: &app };
    for user in [Some("ada"), None, Some("ada")] {
        let request = Request { user: user.map(String::from), path: "/report".to_string() };
        let (status, body) = serve.run(&request);
        println!("{status} {body}");
    }
}
Output
log: /report from ada
200 report for ada
log: /report from nobody
401 sign in first
log: /report from ada
200 report for ada (cached)
  • Verdict: idiom. The handlers live in a Vec, and Next is a view of the rest of the chain: a slice of the handlers that are left and the last step. A handler calls next.run to pass the request on.
  • Next is Copy, because it holds only two references. No handler owns its successor, so the chain needs no Rc and no Option<Box<...>> field. See ownership.
  • handle takes &self, so the cache keeps its map in a RefCell to change it. The borrow() in the if let ends before next.run, so the borrow_mut() later does not panic.
  • Outside the standard library, the tower crate defines middleware as a Layer that wraps a Service. That is the shape of the Go example.

Consequences

Design Patterns lists three consequences.1 The pattern reduces coupling: the sender and the receiver do not know each other, and a handler knows only its successor, not the whole chain. It gives flexibility in assigning responsibilities: a program can add or change handlers at run time. And receipt is not guaranteed: a request can reach the end of the chain with no handler.

There are other costs. The path of a request is set at run time, so a reader cannot see from the sender which code will answer it. A debugger shows a deep stack of calls through each link. Each request walks the chain until a link answers, so a long chain adds a cost to every request. And the order of the links matters, as the cache before the check shows, but nothing in the code of a link states the order that it needs.

When not to use it

Do not use a chain when the sender knows the receiver. Call the receiver directly.

Do not use a chain to choose a handler by a key, such as a path or a message type, when each key has one handler. A dictionary from key to handler, or a match on the key, finds the handler in one step and shows all the choices in one place. See The match statement.

Do not use a chain when every handler must see each request. That is the Observer pattern. See Observer pattern. Python's logging module shows the difference. A record logged to a logger goes to the handlers of that logger and then to the handlers of each ancestor logger. It does not stop at the first handler. Only a logger with propagate set to false stops it.5

Do not build a chain of classes with a successor field in a language with first-class functions, unless the handlers need more than one method. A list of functions holds the same chain.

Composite. The parent of a component can act as its successor.1 Event bubbling in the DOM is this form. The dispatch algorithm builds a path from the target of an event through each of its parents, and calls the listeners on each object in the path.8 A listener that calls stopPropagation() sets a flag on the event. The listeners on the current object still run, but the algorithm calls no listeners on the objects later in the path.78 See Composite pattern.

Decorator. A decorator always passes the call to the object it wraps. A handler may stop the request. See the section on middleware above, and Decorator pattern.

Command. A request can be a command object, which the handlers pass along the chain. See Command pattern.

Observer. An observer gets every notification. A handler in a chain may stop the request before later handlers see it. See Observer pattern.

Parent first. A chain can ask the successor first and answer only when the successor cannot. A Java ClassLoader has a parent class loader. When it is asked to find a class or a resource, it usually asks its parent before it tries to find the class or resource itself.6

Known uses

  • Python: urllib.request.OpenerDirector asks its handlers in order, and a handler returns None to pass a request to the next one. See the method _call_chain at v3.14.0.34
  • Go: net/http handlers such as StripPrefix take the next handler as an argument.12
  • .NET: DelegatingHandler chains for HttpClient, and the middleware pipeline of ASP.NET Core.139
  • Java: class loaders delegate to a parent class loader.6
  • Web browsers: DOM events bubble from the target to its ancestors, until a listener stops them.8

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Chain of Responsibility (Intent, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
  2. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (Chain-Of-Responsibility is one of the six patterns affected by first-class types)
  3. CPython v3.14.0 source, Lib/urllib/request.py, method OpenerDirector._call_chain, lines 457 to 466
  4. The Python Standard Library, urllib.request, Python 3.14, OpenerDirector Objects
  5. The Python Standard Library, logging, Python 3.14, Logger.propagate
  6. Java SE 25 API, java.lang.ClassLoader, class description, the delegation model
  7. DOM Living Standard, WHATWG, 2.2 Interface Event, the stopPropagation() method steps
  8. DOM Living Standard, WHATWG, 2.9 Dispatching events, the dispatch and invoke algorithms
  9. ASP.NET Core Middleware, Microsoft Learn, Create a middleware pipeline with WebApplication
  10. ASP.NET Core Middleware, Microsoft Learn, Middleware order
  11. Go standard library, package net/http, type Handler
  12. Go standard library, package net/http, func StripPrefix
  13. .NET API reference, System.Net.Http.DelegatingHandler, class description and InnerHandler property

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B7VZ5Z/text.yaml