AlgoViz

Chain of responsibility

medium 45 min

A request travels past several handlers until one takes it, or until one stops it.

Watch lesson4:36

Where it shows up

The same pattern appears across everyday software.

  • Express

    Middleware functions receive the request, the response and next. The guide says that a function which does not end the cycle must call next, otherwise the request is left hanging. Error-handling middleware is a kind of its own.

  • Django

    Middleware is applied top down in the order of the MIDDLEWARE setting, and the documentation compares it with an onion. A layer may short-circuit and return a response: the layers inside never see the request.

  • Jakarta Servlet filters

    A filter calls the FilterChain to invoke the next filter, or the resource itself if it is the last. The chain object is created by the container.

  • Spring Security

    FilterChainProxy delegates to lists of security filters. The reference says that the order of the filters is extremely important, because a filter only affects those after it.

  • OkHttp interceptors

    Each interceptor receives a chain and calls chain.proceed(request). It can change the request, measure, or retry, and the documentation discusses the order of compressing and checksumming.

  • Netty

    ChannelPipeline is a list of handlers for network events. Its documentation calls it an advanced form of the Intercepting Filter pattern. Handlers can be added and removed while a channel lives.

  • ASP.NET Core

    Each middleware invokes the next or short-circuits the pipeline. The order in the Program file is the order of requests, and the reverse is the order of responses.

  • Events in browsers

    A click bubbles from the element to its ancestors. Every listener on the way can react, and stopPropagation ends the walk.

  • Python logging

    A log record goes to the handlers of its logger and, if propagate is true, to those of all parent loggers.

  • Java class loading

    A ClassLoader usually asks its parent to find a class before it tries itself: a chain in which the far end gets the first chance.