Skip to content
Back to blog
Design Patterns

Chain of Responsibility: Building Composable Processing Pipelines

Updated 16 min read

The Chain of Responsibility Pattern lets you compose independent handlers into a processing pipeline. Learn how to implement it in TypeScript, control execution order, handle failures, and decide when a reusable pipeline is better than a simple sequence of function calls.

Table of Contents

Introduction

Many applications process requests through a series of steps.

An HTTP request may need authentication, authorization, validation, rate limiting, and business processing. A payment request may require input validation, fraud checks, risk assessment, and provider selection. A document processing system may need to parse content, normalize data, detect sensitive information, and apply business rules.

At first, implementing these steps in a single function seems reasonable.

As requirements grow, however, the function becomes harder to understand. Each new rule introduces more conditional logic, and changing the execution order can affect unrelated behavior.

A common response is to extract methods. This improves readability, but it does not necessarily solve the underlying design problem: the processing steps may still be tightly coupled to one fixed implementation.

The Chain of Responsibility Pattern provides another approach. It organizes processing logic into a sequence of independent handlers, allowing each handler to perform its responsibility and decide whether processing should continue.

The pattern is useful when a request must pass through several possible checks or processing stages. But it is not always the right abstraction. A simple sequence of function calls may be clearer when the workflow is fixed and unlikely to change.

The design challenge is to make processing steps composable without making execution unpredictable.

1. The Problem: Processing Logic Becomes a Long Sequence of Conditions

Imagine an API that processes a request to create an order.

Before the application creates the order, it must:

  1. Authenticate the user.
  2. Check whether the user is allowed to create orders.
  3. Validate the request.
  4. Check whether the user has exceeded a rate limit.
  5. Execute the business operation.

A straightforward implementation might look like this:

typescript
async function createOrder(
  request: CreateOrderRequest,
  user: User | null,
) {
  if (!user) {
    throw new UnauthorizedError();
  }

  if (!user.permissions.includes("order:create")) {
    throw new ForbiddenError();
  }

  if (!isValidOrder(request)) {
    throw new ValidationError();
  }

  if (await isRateLimited(user.id)) {
    throw new TooManyRequestsError();
  }

  return orderService.create(request, user);
}

This code is not inherently bad. It is explicit, readable, and easy to understand when the number of steps is small.

The difficulty appears when the processing rules grow.

Different endpoints may need different combinations of checks. Some checks may be shared across routes, while others are specific to one operation. A new security requirement may need to be inserted before existing logic. Testing every combination can become increasingly cumbersome.

Developers may respond by introducing flags, nested conditions, or helper functions that still depend on the same execution structure.

The problem is not simply that the function is long. It is that the processing steps are difficult to compose independently.

We want each step to own a focused responsibility and allow the application to assemble the steps required for a particular workflow.

2. The Core Idea Behind Chain of Responsibility

Chain of Responsibility organizes processing into individual handlers connected by a common contract.

Each handler receives a request or context and can:

  • Process or validate the input.
  • Modify the context when appropriate.
  • Stop the chain when a condition fails.
  • Delegate execution to the next handler.

A simplified structure looks like this:

text
Request
   |
   v
Authentication Handler
   |
   v
Authorization Handler
   |
   v
Validation Handler
   |
   v
Rate Limit Handler
   |
   v
Business Handler
   |
   v
Response

The important design choice is that each handler does not need to know the internal implementation of every other handler.

It only needs to follow the chain's contract.

There are two common forms of this pattern.

Classic handler chain: Each handler decides whether it can handle a request. It may process the request or pass it to the next handler. This is useful when different handlers may handle different requests.

Processing pipeline: Every handler performs one stage of a workflow and passes the result to the next stage. Middleware and request-processing pipelines commonly use this form.

These forms are related, but they are not identical. A pipeline generally expects a sequence of stages, while a classic handler chain may stop as soon as one handler handles the request.

For the API example, a pipeline is a natural fit because every required check must run in a specific order unless a check rejects the request.

3. Implementing a Processing Pipeline in TypeScript

Let's build a small pipeline that can be reused across application workflows.

Step 1: Define the handler contract

A handler receives a context and a function representing the next stage.

typescript
type Next<T> = () => Promise<T>;

interface Handler<T> {
  handle(context: T, next: Next<T>): Promise<T>;
}

This contract is intentionally small.

A handler can inspect or update the context, then call next() to continue. If it throws an error or returns without calling next(), the downstream handlers will not execute.

The example uses a promise-based interface because many application steps involve asynchronous work, such as database queries or external API calls.

Step 2: Implement individual handlers

First, define a context that carries the information needed by the pipeline:

typescript
interface OrderContext {
  user: User | null;
  request: CreateOrderRequest;
  orderId?: string;
}

The User and CreateOrderRequest types represent application-specific models.

An authentication handler can check whether the request has an authenticated user:

typescript
class AuthenticationHandler
  implements Handler<OrderContext>
{
  async handle(
    context: OrderContext,
    next: Next<OrderContext>,
  ): Promise<OrderContext> {
    if (!context.user) {
      throw new UnauthorizedError();
    }

    return next();
  }
}

Authorization becomes a separate responsibility:

typescript
class AuthorizationHandler
  implements Handler<OrderContext>
{
  async handle(
    context: OrderContext,
    next: Next<OrderContext>,
  ): Promise<OrderContext> {
    if (
      !context.user?.permissions.includes("order:create")
    ) {
      throw new ForbiddenError();
    }

    return next();
  }
}

Validation is independent of authentication and authorization:

typescript
class OrderValidationHandler
  implements Handler<OrderContext>
{
  async handle(
    context: OrderContext,
    next: Next<OrderContext>,
  ): Promise<OrderContext> {
    if (!isValidOrder(context.request)) {
      throw new ValidationError();
    }

    return next();
  }
}

Each handler has one main responsibility. It does not need to know which concrete handlers come before or after it.

Step 3: Build the pipeline

Now we need a component that connects the handlers in order.

typescript
class Pipeline<T> {
  constructor(
    private readonly handlers: Handler<T>[],
  ) {}

  execute(context: T): Promise<T> {
    const dispatch = (
      index: number,
    ): Promise<T> => {
      const handler = this.handlers[index];

      if (!handler) {
        return Promise.resolve(context);
      }

      return handler.handle(
        context,
        () => dispatch(index + 1),
      );
    };

    return dispatch(0);
  }
}

This implementation creates the chain by passing each handler a next() function that invokes the following handler.

The terminal condition returns the context after all handlers have completed.

Notice that the pipeline does not know anything about orders, authentication, or validation. It only coordinates handlers that implement the same contract.

Step 4: Assemble the workflow

The application decides which handlers to use and in what order:

typescript
const orderPipeline = new Pipeline<OrderContext>([
  new AuthenticationHandler(),
  new AuthorizationHandler(),
  new OrderValidationHandler(),
  new OrderCreationHandler(),
]);

Execution becomes:

typescript
const context: OrderContext = {
  user,
  request,
};

const result = await orderPipeline.execute(context);

OrderCreationHandler represents the final business operation and should be implemented to create the order and return the resulting context.

The same pipeline infrastructure could support another workflow with a different handler sequence.

For example, an administrative endpoint might use additional authorization checks, while a public endpoint might use a different validation strategy.

The important point is that the pipeline's structure is configurable without changing its orchestration implementation.

Step 5: Keep the contract appropriate for the workflow

A generic pipeline is not always the best starting point.

For a small, fixed workflow, direct function composition may be easier to maintain:

typescript
async function createOrderWorkflow(
  context: OrderContext,
) {
  await authenticate(context);
  await authorize(context);
  await validateOrder(context);

  return createOrder(context);
}

This is explicit and requires no handler infrastructure.

A reusable pipeline becomes more valuable when handlers need to be reordered, combined across workflows, or extended independently.

Start with the simplest structure that accommodates the actual variation in your system.

4. Understanding Execution Order and Failure Handling

A chain is not merely a list of functions. Its execution semantics determine whether it remains predictable and safe.

4.1. Order is part of the contract

Consider these steps:

text
Authentication -> Authorization -> Validation -> Execution

Reordering them can change behavior.

Authorization usually depends on an established identity. Business execution must not occur before required security checks. In some systems, inexpensive validation can occur before authentication, but that decision should be deliberate and must not leak sensitive information.

Do not assume handlers are interchangeable simply because they implement the same interface.

A pipeline should document which steps must precede others and which steps may be safely reordered.

4.2. Stopping the chain

A handler should not call next() when it rejects the request.

In the earlier example, authentication throws an error if no user exists. The downstream handlers never run.

This is an example of fail-fast behavior.

The pipeline itself does not need to understand every possible business error. It can allow exceptions to propagate to the application boundary, where they are converted into appropriate HTTP responses or other application-level results.

4.3. Errors before and after next()

Handlers can perform work before and after downstream execution.

typescript
class TimingHandler<T> implements Handler<T> {
  async handle(
    context: T,
    next: Next<T>,
  ): Promise<T> {
    const startedAt = Date.now();

    try {
      return await next();
    } finally {
      recordDuration(Date.now() - startedAt);
    }
  }
}

The finally block runs whether the downstream chain succeeds or throws.

This makes the handler useful for timing, tracing, and cleanup.

The use of await next() is important. Without await, the handler may return before downstream processing finishes, so its finally block would not measure the complete operation.

4.4. Avoid calling next() more than once

A middleware-style pipeline generally expects each handler to call next() at most once.

Calling it twice can execute downstream business operations twice. That can be dangerous for operations such as charging a payment or creating an order.

If the pipeline is used for critical operations, its contract should explicitly prohibit multiple calls to next(). A more defensive implementation can also track whether the continuation has already been invoked.

Do not rely on convention alone when duplicate execution could cause side effects.

4.5. Separate rejection from recovery

A handler that catches an error and silently continues can accidentally bypass an important failure.

For example, a rate-limit handler must not allow a request through merely because the rate-limit service is unavailable, unless that fail-open behavior is an intentional, documented policy.

Likewise, a logging handler should normally record an error and rethrow it rather than turn a failed operation into a successful result.

Each handler should have a clear failure policy: reject, propagate, recover, or deliberately continue under a defined condition.

5. Real-World Applications

5.1. HTTP middleware

HTTP frameworks commonly implement middleware chains.

A request may pass through request ID generation, logging, authentication, authorization, validation, and route execution.

Each middleware can perform work before the next stage and optionally perform cleanup or response processing afterward.

This is one of the most familiar applications of chain-based processing.

However, use the framework's native middleware conventions where possible. Building a second generic middleware engine on top of an existing one often adds unnecessary complexity.

5.2. Document and data processing

Consider an ingestion system that processes uploaded documents.

text
Read File
   |
   v
Detect Format
   |
   v
Extract Text
   |
   v
Normalize Content
   |
   v
Validate Metadata
   |
   v
Store Document

Each stage can have a clear contract and can be tested independently.

Different workflows can share normalization and validation while using different extraction handlers for PDFs, spreadsheets, or plain text.

A pipeline is especially useful when new processing stages are expected to be added over time.

If the stages have substantially different input and output types, however, a single mutable context may become difficult to reason about. In that case, model the pipeline as typed transformations where each stage receives one type and returns another.

5.3. Business rules and risk checks

A financial or commerce application may evaluate a transaction through fraud checks, account restrictions, limits, and compliance rules.

Each rule can produce an explicit decision such as allow, reject, or require further review.

For these workflows, it is often better to model the decision directly than to rely on exceptions for ordinary outcomes:

typescript
type RuleDecision =
  | { type: "allow" }
  | { type: "reject"; reason: string }
  | { type: "review"; reason: string };

The orchestrator can then decide whether to continue, reject, or route the request for manual review.

Not every rule engine is a Chain of Responsibility implementation. Some systems need all rules to run and combine their results, while others stop at the first rejection. Choose the execution model that matches the business requirements.

5.4. Request enrichment

A request may need contextual information before business logic runs:

  • Load the account.
  • Resolve tenant configuration.
  • Attach feature flags.
  • Retrieve permissions.
  • Add tracing metadata.

A chain can make these steps reusable across routes.

Be careful, however, not to turn the context into an unstructured container that every handler modifies freely. Define which fields each stage may populate and which stages are allowed to depend on them.

6. Chain of Responsibility vs. Middleware, Decorator, and Strategy

These patterns are related, but they answer different design questions.

PatternMain questionTypical use
Chain of ResponsibilityWhich handler should process this request, and should it continue?Validation chains, request pipelines
MiddlewareHow should cross-cutting behavior wrap request processing?HTTP logging, authentication, tracing
DecoratorHow can an object's behavior be extended while preserving its interface?Caching, retries, metrics
StrategyWhich interchangeable algorithm should perform this operation?Pricing, payment selection, ranking

Middleware is often implemented using a chain-like structure, so the two concepts overlap. Middleware is commonly associated with request/response processing and the ability to run logic before and after downstream handlers.

Decorator focuses on adding behavior around an object while preserving its contract. A decorator may itself use a chain-like composition, but its central purpose is to extend behavior.

Strategy chooses among alternative implementations of an operation. A processing chain, by contrast, typically coordinates multiple steps that may all need to execute.

These patterns can work together. For example, a request pipeline could use a Strategy to select a fraud detection algorithm and a Decorator to add timing to the selected implementation.

The distinction is useful because it helps you choose a pattern based on the responsibility you need to model, rather than the structure of the code alone.

7. Common Design Mistakes

7.1. Introducing a generic framework too early

A handful of sequential functions does not automatically justify a pipeline abstraction.

If the workflow is stable, a normal function with clear steps may be easier to read and debug.

Introduce a chain when composition, reuse, or independent extension provides a concrete benefit.

7.2. Hiding execution order

A pipeline that loads handlers dynamically from configuration can make the system harder to understand if the execution order is not visible or validated.

For security-sensitive workflows, make required ordering constraints explicit. Authentication, authorization, validation, and execution should not be freely rearrangeable without considering their dependencies.

7.3. Making handlers responsible for unrelated concerns

A single handler that authenticates users, queries a database, modifies the request, sends notifications, and creates an order is not a well-separated handler.

The chain does not automatically create good architecture. Each handler still needs a cohesive responsibility.

7.4. Using shared mutable context without rules

A shared context is convenient, but uncontrolled mutation creates hidden dependencies between handlers.

For example, one handler may assume that another has populated context.account, even though the pipeline does not guarantee that ordering.

Keep the context small, define its lifecycle, and make required data dependencies explicit.

For complex workflows, typed stage outputs or immutable context updates may be safer.

7.5. Ignoring observability

When execution spans many handlers, debugging can become harder if logs do not reveal which stages ran.

Useful observability includes stage names, durations, failures, and correlation identifiers.

Avoid logging secrets or sensitive request contents. Observability should help explain execution without exposing protected data.

7.6. Treating every failure as a rejection

Some handlers perform checks that may fail because a dependency is unavailable. Whether the request should fail, retry, or continue depends on the specific operation and its risk.

A missing optional enrichment field may be acceptable. A failed authorization check usually is not.

Make failure behavior an explicit part of each handler's contract.

8. When Should You Use Chain of Responsibility?

Use the pattern when:

  • A request passes through multiple independent processing stages.
  • Handlers need to be reused or assembled into different workflows.
  • Processing must stop when a handler rejects or handles the request.
  • New steps are expected to be introduced without rewriting a large central function.
  • Cross-cutting behavior needs a consistent, composable execution model.

Avoid introducing it when:

  • The workflow has only a few stable steps.
  • A simple function or ordinary sequence of calls is clearer.
  • Dynamic composition makes execution order difficult to reason about.
  • Handlers have incompatible semantics that cannot be represented by a clear contract.
  • The abstraction would require more infrastructure than the workflow itself.

Before implementing the pattern, answer three questions:

  1. Who decides whether processing continues? Each handler, a central orchestrator, or a rule engine?
  2. What happens when a handler fails? Stop, propagate, retry, recover, or continue under a documented policy?
  3. How is execution order controlled? Fixed in code, assembled by the application, or configured dynamically?

If these questions have clear answers, the pattern can make a complex workflow easier to extend. If they do not, adding handlers may only move complexity from one large function into several smaller, less predictable components.

Summary

The Chain of Responsibility Pattern organizes processing into independent handlers that can process, reject, or pass a request to the next stage.

Its main benefit is composability. Instead of concentrating every rule in one central function, the application can assemble focused handlers into a workflow that is easier to extend and test.

A good implementation makes execution order, continuation rules, error handling, and context ownership explicit.

But a chain is not automatically better than ordinary function composition. For a small, stable workflow, direct calls are often simpler. For complex or evolving workflows, a well-defined pipeline can provide a valuable structure.

The goal is not to turn every operation into a handler. It is to make changing the processing flow easier without making the flow itself harder to understand.

  • Design Patterns
  • Chain of Responsibility Pattern
  • OOP
  • Programing
  • Software Architecture
  • Chain of Responsibility vs Middleware
  • Request Pipeline
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.