Skip to content

Chain of Responsibility

Difficulty: Intermediate

Key concepts

  • chain of responsibility pattern
  • handler
  • successor
  • guaranteed handling
  • vector of handlers
  • What Chain of Responsibility is for: sending a request to a sequence of handlers, where the first one able to deal with it does, and the sender does not know or care which one that is.
  • How to write it in C++ with explicit ownership: each handler owns the next, and a non-virtual function walks the chain so that no handler can forget to pass a request on.
  • The simpler alternative, a list of handlers tried in order, and how to choose between the two.
  • How to make sure every request is handled, or at least that an unhandled one is noticed, instead of falling silently off the end.

A help desk receives tickets. Each ticket has a category (account, billing, technical, legal), a severity, a topic, and sometimes a refund request. There are several levels of support, from cheapest to most expensive:

  • a help bot that answers known questions with an article;
  • a billing agent who answers billing questions and can refund up to $50;
  • an engineer who takes technical problems that are not critical;
  • a manager who can refund up to $500 and takes every critical ticket.
  1. FR-1 Each ticket goes to the first level, in order, that can resolve it.
  2. FR-2 Different teams have different levels, in different orders: a small team has no billing agent and no engineer; another team may put the manager first. This is set when the desk is set up, without editing the code of any level.
  3. FR-3 Every ticket gets a response. A ticket that no level can resolve goes to a triage queue, where a person picks it up, and is counted.
  4. FR-4 The response says who resolved the ticket and what they did.

One function decides, with a flag for each optional level:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

ticket.hpp
// What a ticket is about, and how urgent it is. `enum class` keeps the
// names inside the type (Category::billing, Severity::critical) and stops
// them from being mixed up with plain ints.
enum class Category { account, billing, technical, legal };
enum class Severity { low, high, critical };
// One customer request: the data that every level looks at to decide
// whether to take it. A plain struct with a default for each field, so a
// ticket can be written as a brace list in field order, such as
// {2, Category::billing, Severity::low, "charged twice", 1999}.
struct Ticket {
int id = 0;
Category category = Category::account;
Severity severity = Severity::low;
std::string topic;
// Money is a whole number of cents (1999 is $19.99), so there are no
// rounding errors from floating-point numbers.
int refund_cents = 0; // 0: no refund asked for
};
// The answer the customer gets (FR-4): who dealt with the ticket, such as
// "billing agent" or "triage queue", and what they did, in plain words.
struct Resolution {
std::string handled_by;
std::string action;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
namespace before {
// The settings a team can change: a flag to switch the bot or the engineer
// off, and the largest refund, in cents, that the agent and the manager
// may approve. There is no flag for the billing agent or the manager, and
// no setting for the order: both are fixed inside route().
struct Levels {
bool faq_bot = true;
bool engineer = true;
// The ' is a digit separator: the compiler ignores it, and it is there
// only for the reader. 50'00 is 5000 cents ($50.00); 500'00 is $500.00.
int agent_limit_cents = 50'00;
int manager_limit_cents = 500'00;
};
// Decides who resolves the ticket, in one function. The ticket and the
// levels are borrowed by const reference: route reads them and changes
// neither. It always returns an answer: a ticket that no level takes gets
// the triage queue.
Resolution route(const Ticket& ticket, const Levels& levels);
} // namespace before

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Each `if` is one level, tried from top to bottom, and the first one that
// matches returns at once. So the order of the ifs is the escalation
// order. `return {"faq bot", "..."};` builds the Resolution from a brace
// list: handled_by first, then action.
Resolution route(const Ticket& ticket, const Levels& levels) {
// Level 1, the bot: only the one topic it has an article for, and only
// when no money is involved. The topic and the article are written into
// the code, so a new article means editing this function.
if (levels.faq_bot && ticket.topic == "password reset" && ticket.refund_cents == 0) {
return {"faq bot", "sent the article help/reset-password"};
}
// Level 2, the billing agent: any billing ticket whose refund is within
// the agent's limit, including a plain question with no refund at all.
if (ticket.category == Category::billing && ticket.refund_cents <= levels.agent_limit_cents) {
if (ticket.refund_cents == 0) {
return {"billing agent", "answered the question"};
}
// format_cents turns cents into dollars for people: 1999 -> "$19.99".
return {"billing agent", "refunded " + format_cents(ticket.refund_cents)};
}
// Level 3, the engineer: technical tickets, except critical ones, which
// fall through to the manager below.
if (levels.engineer && ticket.category == Category::technical && ticket.severity != Severity::critical) {
return {"engineer", "opened a bug report"};
}
// Level 4, the manager, in two parts: any critical ticket, whatever its
// category; then billing refunds above the agent's limit (smaller ones
// were taken above) and up to the manager's own.
if (ticket.severity == Severity::critical) {
return {"manager", "started an incident"};
}
if (ticket.category == Category::billing && ticket.refund_cents > 0 &&
ticket.refund_cents <= levels.manager_limit_cents) {
return {"manager", "approved a refund of " + format_cents(ticket.refund_cents)};
}
// Nobody matched (a legal ticket, or a refund over every limit): the
// ticket waits for a person, so every ticket still gets a response.
return {"triage queue", "waiting for a person"};
}

This is short, and for one team with fixed levels it is the right design: everything is in one place and easy to read. It meets FR-1 and FR-4, and the response part of FR-3 (a caller could count the triage results). It fails FR-2:

  • The order is fixed in the code. A team that wants the manager first needs a new flag, and a new path through the function.
  • Every level lives in one function. A new level (say, a security team for account takeovers) means editing route, and every team’s routing changes with it.
  • The flags grow with the teams. Each team’s needs become another bool in Levels, and the function must handle every combination. Here the small team can turn off the engineer, but not the billing agent, except by a trick such as a negative limit, because nobody added a flag for it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_chain.cpp
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)
// records a failure, printing both values, if they are not equal. They come
// from the site's small test header, lld_test.hpp. billing(cents) is a
// helper earlier in this file (not shown): a low-severity billing ticket,
// topic "refund", asking for that many cents back.
// std::string{"..."} makes the expected value a std::string, so the
// comparison is between two strings, not a string and a char pointer.
LLD_TEST(before_routes_in_one_fixed_order) {
// $19.99 is within the agent's $50.00 limit; $120.00 is not, but is
// within the manager's $500.00, so it goes one level further.
LLD_CHECK_EQ(before::route(billing(1999), before::Levels{}).handled_by, std::string{"billing agent"});
LLD_CHECK_EQ(before::route(billing(12000), before::Levels{}).handled_by, std::string{"manager"});
// Levels can be switched off, but not reordered or added without
// editing route().
// With the engineer off, a high-severity bug matches no other level
// (only critical tickets go to the manager), so it reaches triage.
before::Levels no_engineer;
no_engineer.engineer = false;
const Ticket bug{11, Category::technical, Severity::high, "export fails", 0};
LLD_CHECK_EQ(before::route(bug, no_engineer).handled_by, std::string{"triage queue"});
}

Chain of Responsibility gives each level its own handler object and links the handlers into a sequence. A request goes to the first handler; each handler either deals with it or passes it on to the next one, its successor. The sender sees only the start of the chain.

Its participants:

  • The handler interface: a way to offer a request, and a link to the next handler. Here, Handler.
  • The concrete handlers: each decides whether to take a request, using only its own rule. Here, FaqBot, BillingAgent, Engineer, and Manager.
  • The client: builds the chain and sends requests to its first handler. Here, SupportDesk, which also deals with requests that nobody takes.

A handler knows nothing about the others, only that there may be a next one. That is what makes FR-2 possible: the levels and their order are decided by whoever builds the chain.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handler.hpp
// The base of every level in the chain. It does two jobs: it holds the
// link to the next handler, and it walks the chain (handle). Each concrete
// handler adds only its own rule, by overriding try_handle. A Handler
// cannot be created on its own: try_handle is pure virtual (= 0), and the
// constructor is protected.
class Handler {
public:
// No copying (= delete): a copy would have to share the rest of the
// chain, which a unique_ptr cannot do, or copy all of it. Declaring
// these also means the compiler writes no move operations, so a
// handler cannot be moved either; it is always reached by pointer or
// reference.
Handler(const Handler&) = delete;
Handler& operator=(const Handler&) = delete;
// Virtual, because the chain deletes handlers through a
// unique_ptr<Handler>: this makes sure a Manager's own destructor runs.
virtual ~Handler() = default;
// Links `next` after this handler and returns it, so links can be
// written one after another. Throws if `next` is null or this handler
// already has a next one.
// `next` is taken by value: the caller hands over ownership with a
// temporary from std::make_unique, or with std::move.
Handler& then(std::unique_ptr<Handler> next);
// Offers the ticket to this handler, then to each one after it, and
// returns the first resolution; nothing if no handler takes it.
// Not virtual: this one loop is the only passing-on code, so no
// handler can forget to pass a ticket along. [[nodiscard]] makes the
// compiler warn if a caller drops the answer, and with it the chance
// to notice "nobody took it".
[[nodiscard]] std::optional<Resolution> handle(const Ticket& ticket) const;
protected:
// Protected: only derived classes (FaqBot, Manager, ...) can call it.
Handler() = default;
// One handler's own decision: a resolution, or nothing to pass it on.
// Returning std::nullopt means "not mine"; it is not an error.
virtual std::optional<Resolution> try_handle(const Ticket& ticket) const = 0;
private:
// Null for the last handler. Each handler owns the one after it, so
// the first handler owns, and in the end destroys, the whole chain.
std::unique_ptr<Handler> next_; // owns the rest of the chain
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handler.cpp
// Adds one link: `next` becomes the handler after this one. Two refusals,
// in this order: a null `next` throws std::invalid_argument; a handler
// that is already linked throws std::logic_error, because replacing
// next_ would silently destroy the rest of the chain. On either throw,
// nothing is linked, and the refused handler is destroyed with the
// parameter that owns it.
Handler& Handler::then(std::unique_ptr<Handler> next) {
if (!next) {
throw std::invalid_argument("the next handler must not be null");
}
if (next_) {
throw std::logic_error("this handler already has a next handler");
}
// std::move hands ownership from the parameter to next_; afterwards
// `next` is null and next_ owns the new handler.
next_ = std::move(next);
// Return the handler just linked (not this one), so that
// a.then(b).then(c) links c after b, building a -> b -> c.
return *next_;
}
// Walks the chain from this handler to the end and returns the first
// answer. `current` is a plain, non-owning pointer: it only visits the
// handlers, which the chain still owns. next_.get() reads the raw pointer
// inside a unique_ptr without taking ownership; it is nullptr after the
// last handler, which ends the loop.
std::optional<Resolution> Handler::handle(const Ticket& ticket) const {
for (const Handler* current = this; current != nullptr; current = current->next_.get()) {
// An if with a declaration: call this handler's own rule and keep
// the result. An optional converts to true only if it holds a
// Resolution, so the first handler that takes the ticket ends the
// walk, and the handlers after it are never asked.
if (auto resolution = current->try_handle(ticket)) {
return resolution;
}
}
// Every handler said "not mine": tell the caller nobody took it.
return std::nullopt;
}
How this code works: Handler::then and Handler::handle

Building the chain with then. main below builds the standard chain in one statement: chain->then(agent).then(engineer).then(manager), where chain owns the bot. It runs left to right:

  1. chain->then(agent) is called on the bot. agent is not null and the bot has no next_ yet, so both checks pass. std::move hands the agent to the bot’s next_, and then returns a reference to the agent, not to the bot.
  2. .then(engineer) is therefore called on the agent: the engineer becomes the agent’s next_, and the engineer is returned.
  3. .then(manager) is called on the engineer: the manager becomes the engineer’s next_. The manager’s own next_ stays null, which marks the end of the chain.

The result is bot, then agent, then engineer, then manager. Each one owns the next through its unique_ptr, and chain owns the bot, so one owner at the front holds the whole chain.

Walking it with handle. handle runs on the first handler and moves a plain pointer, current, along the links. It never takes ownership; it only visits. Here is ticket 4, a billing ticket about “order cancelled” asking for a refund of 12000 cents ($120.00):

Step current Its try_handle returns Then
1 FaqBot nothing: “order cancelled” is not in its map current moves to the agent
2 BillingAgent nothing: 12000 is more than its limit of 5000 current moves to the engineer
3 Engineer nothing: the ticket is billing, not technical current moves to the manager
4 Manager “approved a refund of $120.00” handle returns that resolution

For ticket 6, a legal request, all four return nothing. After step 4, current becomes the manager’s next_.get(), which is nullptr, so the loop ends and handle returns std::nullopt: nobody took it.

  • handle is public and not virtual; try_handle is protected and virtual. Each concrete handler answers one question, “will you take this?”, by returning a resolution or nothing. The passing-on is done once, in the base, so a handler cannot forget it. (This is the Template Method shape: the base fixes the steps, and subclasses fill in one.)
  • handle walks the chain in a loop, not by each handler calling the next. A loop does not grow the call stack with the length of the chain. It can reach current->try_handle and current->next_ on another handler because they are members of the same class (access in C++ is checked per class, not per object).
  • std::optional<Resolution> says “taken, or not” without a special value. An empty optional from the end of the chain means nobody took the request; the caller must decide what that means.
  • Each handler owns the next one through std::unique_ptr. The first handler owns the whole chain, and destroying it destroys every handler after it.
  • then refuses a second link. Replacing next_ would destroy the rest of the chain without warning, so it throws instead. It returns the new handler, so the links can be written one after another, as in main below.
  • Copying is deleted. A copy would either share the rest of the chain (which a unique_ptr cannot do) or copy it all; neither is what a caller would expect.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handlers.hpp
// The four levels. Each one derives from Handler and overrides only
// try_handle, its own "is this mine?" rule; none of them knows which
// handlers come before or after it. `final` says no class may derive from
// these in turn. Each try_handle is private: only Handler::handle calls
// it, through the base class.
// Answers known questions with a help article.
// Takes a ticket whose topic is in its map and that asks for no refund.
class FaqBot final : public Handler {
public:
// The map is taken by value and moved into the bot, so the bot keeps
// its own copy of the articles. `explicit` stops a map from turning
// into a FaqBot by accident.
explicit FaqBot(std::map<std::string, std::string> articles); // topic -> article
private:
std::optional<Resolution> try_handle(const Ticket& ticket) const override;
std::map<std::string, std::string> articles_;
};
// Answers billing tickets, refunding up to a limit.
// Takes any billing ticket with refund_cents <= its limit; a refund of 0
// is a plain question, which it answers.
class BillingAgent final : public Handler {
public:
explicit BillingAgent(int refund_limit_cents); // throws if negative
private:
std::optional<Resolution> try_handle(const Ticket& ticket) const override;
int refund_limit_cents_;
};
// Takes technical tickets that are not critical.
// No settings, so no constructor is written: the compiler's default one is
// public, which is why a test can write `Engineer engineer;`.
class Engineer final : public Handler {
private:
std::optional<Resolution> try_handle(const Ticket& ticket) const override;
};
// Approves larger refunds, up to a higher limit, and takes critical tickets.
// It takes any billing refund from 1 cent up to its limit; the refunds it
// sees are "larger" only because, in the standard chain, the billing agent
// before it has already taken the small ones. It does not answer billing
// questions with no refund.
class Manager final : public Handler {
public:
explicit Manager(int refund_limit_cents); // throws if negative
private:
std::optional<Resolution> try_handle(const Ticket& ticket) const override;
int refund_limit_cents_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

handlers.cpp
// std::move hands the map's contents to the member instead of copying
// them a second time.
FaqBot::FaqBot(std::map<std::string, std::string> articles) : articles_{std::move(articles)} {}
// Takes the ticket only if there is an article for its topic and it asks
// for no money; anything else goes on down the chain.
std::optional<Resolution> FaqBot::try_handle(const Ticket& ticket) const {
// find returns an iterator to the matching (topic, article) pair, or
// articles_.end() if the topic is not in the map.
const auto found = articles_.find(ticket.topic);
if (found == articles_.end() || ticket.refund_cents > 0) {
return std::nullopt; // not mine: pass it on
}
// found->second is the article, the value half of the pair.
return Resolution{"faq bot", "sent the article " + found->second};
}
// checked_limit is a small helper earlier in this file (not shown): it
// returns the limit unchanged, or throws std::invalid_argument if it is
// negative. Calling it in the member initialiser means a BillingAgent with
// a bad limit is never created.
BillingAgent::BillingAgent(int refund_limit_cents) : refund_limit_cents_{checked_limit(refund_limit_cents)} {}
std::optional<Resolution> BillingAgent::try_handle(const Ticket& ticket) const {
// Not billing, or more money than this agent may give: not mine. The
// limit itself is allowed, because the test is `>`, not `>=`.
if (ticket.category != Category::billing || ticket.refund_cents > refund_limit_cents_) {
return std::nullopt;
}
if (ticket.refund_cents == 0) {
return Resolution{"billing agent", "answered the question"};
}
return Resolution{"billing agent", "refunded " + format_cents(ticket.refund_cents)};
}
// A critical technical ticket is declined here, so that it reaches the
// manager later in the chain.
std::optional<Resolution> Engineer::try_handle(const Ticket& ticket) const {
if (ticket.category != Category::technical || ticket.severity == Severity::critical) {
return std::nullopt;
}
return Resolution{"engineer", "opened a bug report"};
}
Manager::Manager(int refund_limit_cents) : refund_limit_cents_{checked_limit(refund_limit_cents)} {}
// Two rules, checked in order: any critical ticket, of any category,
// starts an incident; otherwise a billing refund above 0 and within the
// limit is approved. Everything else, including a billing question with no
// refund, is passed on.
std::optional<Resolution> Manager::try_handle(const Ticket& ticket) const {
if (ticket.severity == Severity::critical) {
return Resolution{"manager", "started an incident"};
}
if (ticket.category == Category::billing && ticket.refund_cents > 0 && ticket.refund_cents <= refund_limit_cents_) {
return Resolution{"manager", "approved a refund of " + format_cents(ticket.refund_cents)};
}
return std::nullopt;
}
How this code works: Which handler takes each sample ticket

In the standard chain, each ticket is offered to the bot, the agent ($50.00 limit), the engineer, and the manager ($500.00 limit), in that order, and stops at the first one that takes it. A dash means that handler is never asked, because an earlier one took the ticket.

Ticket FaqBot BillingAgent Engineer Manager
1: account, “password reset”, no refund takes: has an article - - -
2: billing, “charged twice”, 1999 cents declines: no article takes: 1999 is within 5000 - -
3: technical, high, “export fails” declines declines: not billing takes: technical, not critical -
4: billing, “order cancelled”, 12000 cents declines declines: over 5000 declines: not technical takes: within 50000
5: technical, critical, “site down” declines declines declines: critical takes: critical
6: legal, “copy of my data” declines declines declines declines: not critical, not billing

Ticket 6 falls off the end, so handle returns nothing, and the SupportDesk below sends it to the triage queue. Notice that ticket 5 is technical, but the engineer declines it on purpose, so that a critical ticket always reaches the manager.

  • Each handler’s rule is self-contained. BillingAgent does not know that an engineer or a manager exists; it declines anything over its limit, and the chain does the rest.
  • The state that differs between teams is in the constructor: the bot’s articles and each person’s refund limit. A team with a $100 agent limit builds BillingAgent{100'00}; no code changes.
  • try_handle is private in the concrete classes. Only the base calls it, through handle. (C++ lets an override have different access from the function it overrides; the base’s access is what counts when it is called through the base.)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

desk.hpp
// Routes every ticket through one chain. A ticket that no handler takes
// goes to the triage queue, so every ticket gets a response.
// This is the client of the chain: it knows only the first handler, and
// it is the one place where "nobody took it" becomes an answer (FR-3).
class SupportDesk {
public:
// Takes ownership of the whole chain: the caller passes its
// unique_ptr with std::move and no longer has it afterwards.
explicit SupportDesk(std::unique_ptr<Handler> chain); // throws if null
// Not const: a ticket that reaches triage adds one to unhandled_.
Resolution route(const Ticket& ticket);
// How many tickets so far went to the triage queue.
int unhandled() const { return unhandled_; }
private:
std::unique_ptr<Handler> chain_; // owns the first handler, which owns the rest
int unhandled_ = 0;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

desk.cpp
// The chain is moved into chain_ first, then checked. Throwing
// std::invalid_argument for a null chain means a SupportDesk that exists
// always has a first handler, so route can call chain_->handle without
// checking for null.
SupportDesk::SupportDesk(std::unique_ptr<Handler> chain) : chain_{std::move(chain)} {
if (!chain_) {
throw std::invalid_argument("a support desk needs at least one handler");
}
}
Resolution SupportDesk::route(const Ticket& ticket) {
// Ask the chain. If some handler took the ticket, the optional holds
// its answer; *resolution copies that Resolution out of the optional.
if (auto resolution = chain_->handle(ticket)) {
return *resolution;
}
// Nobody took it: count it, so someone can watch the number, and send
// it to a person instead of dropping it.
++unhandled_;
return Resolution{"triage queue", "waiting for a person"};
}

The desk owns the first handler, and so the whole chain. It is the one place where “nobody took it” is turned into a response (FR-3): the triage queue, plus a count that someone can watch. The constructor refuses an empty chain, so route never needs a null check.

class Handler

the handler interface; not copyable

Data members

  • std::unique_ptr<Handler> next_; owns the rest of the chain

Member functions

  • Handler& then(std::unique_ptr<Handler> next); throws if null or already linked
  • std::optional<Resolution> handle(const Ticket& ticket) const; tries each handler in turn
  • virtual std::optional<Resolution> try_handle(const Ticket& ticket) const = 0; protected

class FaqBot final

a concrete handler: known topics

Data members

  • std::map<std::string, std::string> articles_;

Member functions

  • std::optional<Resolution> try_handle(const Ticket& ticket) const override; private: called only by Handler::handle

class BillingAgent final

a concrete handler: billing, refunds up to a limit

Data members

  • int refund_limit_cents_;

Member functions

  • std::optional<Resolution> try_handle(const Ticket& ticket) const override; private: called only by Handler::handle

class Engineer final

a concrete handler: technical, not critical

Member functions

  • std::optional<Resolution> try_handle(const Ticket& ticket) const override; private: called only by Handler::handle

class Manager final

a concrete handler: critical tickets, larger refunds

Data members

  • int refund_limit_cents_;

Member functions

  • std::optional<Resolution> try_handle(const Ticket& ticket) const override; private: called only by Handler::handle

class SupportDesk

the client: owns the chain, handles what nobody takes

Data members

  • std::unique_ptr<Handler> chain_; the first handler
  • int unhandled_;

Member functions

  • explicit SupportDesk(std::unique_ptr<Handler> chain); throws if null
  • Resolution route(const Ticket& ticket); the triage queue if nobody takes it
  • int unhandled() const;
The support chain: the Handler base, the four levels, and the SupportDesk that owns the chain

The outline leaves out the handlers’ constructors and the Ticket and Resolution structs shown above.

Ticket 4 asks for a $120 refund. The bot does not know the topic, the agent’s limit is $50, and the engineer does not take billing, so it reaches the manager:

Ticket 4, a $120 refund, passes the bot, the agent, and the engineer, and is resolved by the manager
Text description of the diagram

A sequence diagram with five participants: SupportDesk, FaqBot (the first handler), BillingAgent, Engineer, and Manager. The desk calls handle with ticket 4 on the bot. The loop in handle, running on the bot, first calls the bot’s own try_handle, which returns nothing because the topic is unknown. It then calls try_handle on the billing agent, which returns nothing because the refund is over its $50 limit, and on the engineer, which returns nothing because the ticket is not technical. Finally it calls try_handle on the manager, which returns “approved a refund of $120.00”. handle returns the manager’s resolution to the desk.

Diagram source (Mermaid)
sequenceDiagram
participant Desk as SupportDesk
participant Bot as FaqBot (first)
participant Agent as BillingAgent
participant Eng as Engineer
participant Mgr as Manager
Desk->>Bot: handle(ticket 4)
Bot->>Bot: try_handle: unknown topic, nothing
Bot->>Agent: try_handle(ticket 4)
Agent-->>Bot: nothing (over the $50 limit)
Bot->>Eng: try_handle(ticket 4)
Eng-->>Bot: nothing (not technical)
Bot->>Mgr: try_handle(ticket 4)
Mgr-->>Bot: approved a refund of $120.00
Bot-->>Desk: the manager's resolution

The calls go out from the bot because the loop runs inside the first handler’s handle; no handler calls another.

  • The desk owns the first handler; each handler owns the next. The chain is a singly linked list of unique_ptrs, and it is destroyed from the front when the desk is.
  • Destruction is recursive. Destroying a handler destroys its next_, which destroys its own, and so on. For chains of a few or a few dozen handlers, as here, that is harmless; a chain of many thousands could exhaust the stack on destruction. If chains can be that long, use the list form below, or give Handler a destructor that unlinks next_ in a loop.
  • The reference that then returns is to a handler owned by the chain. It is valid while the chain lives; use it for linking, not to keep.
  • A ticket is borrowed by const& for the length of the call. No handler keeps it.
  • Threads: these handlers only read their own state, so once the chain is built it can be shared by many threads. const alone does not promise that (a handler could have mutable members or use globals), and linking with then must finish before any routing. SupportDesk::route changes unhandled_, so a desk shared between threads needs a lock, or a std::atomic<int> counter.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// `tickets` holds the six sample tickets. print is a small helper above
// main (not shown) that writes one line: "#id topic -> who: what".
// before::Levels{} is the default settings: every level on, the agent's
// limit $50.00 and the manager's $500.00.
std::cout << "before:\n";
for (const Ticket& ticket : tickets) {
print(ticket, before::route(ticket, before::Levels{}));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Build the standard chain: bot -> billing agent -> engineer -> manager.
// std::make_unique creates the bot on the heap and returns the
// unique_ptr that owns it. The map is the bot's articles, topic first.
auto chain = std::make_unique<FaqBot>(std::map<std::string, std::string>{
{"password reset", "help/reset-password"},
});
// Each then() links a new handler after the previous one and returns a
// reference to the new one, so the next .then() links after it. The
// bot owns the agent, the agent owns the engineer, and so on. The
// limits are in cents: 50'00 is $50.00, 500'00 is $500.00.
chain->then(std::make_unique<BillingAgent>(50'00))
.then(std::make_unique<Engineer>())
.then(std::make_unique<Manager>(500'00));
// Hand the whole chain to the desk. std::move is needed because a
// unique_ptr cannot be copied; afterwards `chain` is null, and the
// unique_ptr<FaqBot> has become the desk's unique_ptr<Handler>.
SupportDesk desk{std::move(chain)};
std::cout << "chain:\n";
// Keep each answer, so the rule list below can be compared with it.
std::vector<Resolution> chain_results;
for (const Ticket& ticket : tickets) {
chain_results.push_back(desk.route(ticket));
print(ticket, chain_results.back()); // back(): the answer just added
}
std::cout << "unhandled: " << desk.unhandled() << '\n';
// A small team: no billing agent, no engineer.
// The same handler classes, a shorter chain: bot -> manager. Nothing in
// the handlers changes; only the building code does (FR-2).
auto small_chain = std::make_unique<FaqBot>(std::map<std::string, std::string>{
{"password reset", "help/reset-password"},
});
small_chain->then(std::make_unique<Manager>(500'00));
SupportDesk small_desk{std::move(small_chain)};
std::cout << "small team:\n";
for (const Ticket& ticket : tickets) {
print(ticket, small_desk.route(ticket));
}
std::cout << "unhandled: " << small_desk.unhandled() << '\n';
Expected output
before:
#1 password reset -> faq bot: sent the article help/reset-password
#2 charged twice -> billing agent: refunded $19.99
#3 export fails -> engineer: opened a bug report
#4 order cancelled -> manager: approved a refund of $120.00
#5 site down -> manager: started an incident
#6 copy of my data -> triage queue: waiting for a person
chain:
#1 password reset -> faq bot: sent the article help/reset-password
#2 charged twice -> billing agent: refunded $19.99
#3 export fails -> engineer: opened a bug report
#4 order cancelled -> manager: approved a refund of $120.00
#5 site down -> manager: started an incident
#6 copy of my data -> triage queue: waiting for a person
unhandled: 1
small team:
#1 password reset -> faq bot: sent the article help/reset-password
#2 charged twice -> manager: approved a refund of $19.99
#3 export fails -> triage queue: waiting for a person
#4 order cancelled -> manager: approved a refund of $120.00
#5 site down -> manager: started an incident
#6 copy of my data -> triage queue: waiting for a person
unhandled: 2
rule list: same as the chain for 6 of 6 tickets; unhandled: 1

Read the output against the requirements:

  • The chain gives the same answers as the before-version for the standard team (FR-1, FR-4): the first level that can resolve each ticket does.
  • Ticket 6, a legal request, goes to the triage queue and is counted (FR-3). No level takes legal tickets.
  • The small team’s chain has only two levels, and nothing in the handlers changed to build it (FR-2). Ticket 2 now goes to the manager, the first level left that can refund it; ticket 3 has no engineer to go to and reaches triage, so this team’s count is 2.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_chain.cpp
// standard_chain() is a helper earlier in this file (not shown) that builds
// the same chain as main: bot -> billing agent ($50.00) -> engineer ->
// manager ($500.00), and returns it as a std::unique_ptr<Handler>.
// Checked when the file is compiled, not when the tests run: the build
// fails if Handler ever becomes copyable.
static_assert(!std::is_copy_constructible_v<Handler>);
// The agent's limit, at the edge: $19.99 and exactly $50.00 are the
// agent's (its test is `>`, so the limit itself is allowed); one cent more
// and the agent passes it on, and the manager is the next that takes it.
LLD_TEST(the_first_handler_that_can_resolve_a_ticket_resolves_it) {
SupportDesk desk{standard_chain()};
LLD_CHECK_EQ(desk.route(billing(1999)).handled_by, std::string{"billing agent"});
LLD_CHECK_EQ(desk.route(billing(5000)).handled_by, std::string{"billing agent"});
LLD_CHECK_EQ(desk.route(billing(5001)).handled_by, std::string{"manager"});
}
// $900.00 is over every limit, so every handler declines; the desk turns
// "nothing" into the triage queue and counts it once.
LLD_TEST(a_ticket_no_handler_takes_goes_to_triage_and_is_counted) {
SupportDesk desk{standard_chain()};
const Resolution resolution = desk.route(billing(900'00));
LLD_CHECK_EQ(resolution.handled_by, std::string{"triage queue"});
LLD_CHECK_EQ(desk.unhandled(), 1);
}
// A chain of one: just a manager. A billing question with no refund
// (0 cents) is not the manager's, so it reaches triage; a $1.00 refund is.
LLD_TEST(a_manager_does_not_answer_plain_billing_questions) {
auto chain = std::make_unique<Manager>(500'00);
SupportDesk desk{std::move(chain)};
LLD_CHECK_EQ(desk.route(billing(0)).handled_by, std::string{"triage queue"});
LLD_CHECK_EQ(desk.route(billing(100)).handled_by, std::string{"manager"});
}
// The same two handler classes in the other order: manager -> agent. A
// $19.99 refund, which the agent would take, now goes to the manager,
// because the manager is asked first and takes any refund up to $500.00.
LLD_TEST(the_order_of_the_chain_decides_who_resolves) {
auto manager_first = std::make_unique<Manager>(500'00);
manager_first->then(std::make_unique<BillingAgent>(50'00));
SupportDesk desk{std::move(manager_first)};
LLD_CHECK_EQ(desk.route(billing(1999)).handled_by, std::string{"manager"});
}
// Every refusal in the design. LLD_CHECK_THROWS(expression, type) runs the
// expression and records a failure unless it throws that type of exception
// (or a type derived from it).
LLD_TEST(a_chain_cannot_be_relinked_or_given_a_null_link) {
// A handler can live on the stack too; this one gets one link, to a
// manager with a limit of 0 (allowed: only a negative limit throws).
Engineer engineer;
engineer.then(std::make_unique<Manager>(0));
// A second link is refused with std::logic_error, because replacing
// next_ would destroy the first manager.
LLD_CHECK_THROWS(engineer.then(std::make_unique<Manager>(0)), std::logic_error);
// then() checks for null before "already linked", so this is
// std::invalid_argument even though `engineer` is linked. (A check for
// std::logic_error would accept it too, because std::invalid_argument
// derives from std::logic_error.)
LLD_CHECK_THROWS(engineer.then(nullptr), std::invalid_argument);
LLD_CHECK_THROWS(SupportDesk{nullptr}, std::invalid_argument); // no first handler
LLD_CHECK_THROWS(BillingAgent{-1}, std::invalid_argument); // a negative limit
}
// The alternative gives the same answer, in both who and what, for each of
// the six sample tickets, and refuses an empty rule: Rule{} is a
// std::function that holds nothing.
LLD_TEST(the_rule_list_routes_like_the_chain) {
SupportDesk desk{standard_chain()};
RuleDesk rules = make_standard_rule_desk();
for (const Ticket& ticket : sample_tickets()) {
const Resolution from_chain = desk.route(ticket);
const Resolution from_rules = rules.route(ticket);
LLD_CHECK_EQ(from_rules.handled_by, from_chain.handled_by);
LLD_CHECK_EQ(from_rules.action, from_chain.action);
}
LLD_CHECK_THROWS(rules.add(Rule{}), std::invalid_argument);
}
  • the_first_handler_that_can_resolve_a_ticket_resolves_it checks the limit at $50.00 exactly and one cent over it.
  • the_order_of_the_chain_decides_who_resolves puts the manager first; the manager then takes a refund the agent would have taken.
  • the_rule_list_routes_like_the_chain checks the alternative below against the chain, ticket by ticket.

A chain can end without anyone taking the request. That is the pattern’s main risk: a request silently dropped. There are four common ways to deal with it, and a design should choose one on purpose:

Approach Good when
The caller turns “nothing” into a fallback, as SupportDesk does there is one sensible default, and the caller is the right place to count it
A last handler that always takes the request, such as a TriageHandler the fallback is itself a level, and teams should be able to choose it
Return “nothing” and make the caller handle it (std::optional, marked [[nodiscard]] as Handler::handle is) callers differ in what they do with an unhandled request
Throw an exception an unhandled request is a bug, such as an event type nobody registered

What to avoid is a chain that returns a default the caller cannot tell from a real answer, such as an empty Resolution. Then nobody notices when a request falls off the end.

The handlers in the chain above only decide, and the base does all the passing. So the links do not need to live in the handlers at all. A list, tried in order, does the same job:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

rule_desk.hpp
// The same routing as a list of functions, tried in order.
// `using Rule = ...` gives a short name to a long type. std::function<R(A)>
// can hold any callable (a lambda, a plain function, an object with an
// operator()) that takes an A and returns an R. Here: it takes a ticket
// and returns a resolution, or nothing for "not mine", exactly like
// Handler::try_handle.
using Rule = std::function<std::optional<Resolution>(const Ticket&)>;
// Holds the rules in one vector, in the order they were added, and owns
// them by value: there are no links between rules, so the order is in one
// place and there is no recursive destruction.
class RuleDesk {
public:
void add(Rule rule); // throws if empty
// Tries each rule in order; the triage queue if none takes the ticket.
Resolution route(const Ticket& ticket);
int unhandled() const { return unhandled_; }
private:
std::vector<Rule> rules_;
int unhandled_ = 0;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

rule_desk.cpp
// A default-constructed std::function holds nothing, and calling it would
// throw std::bad_function_call later, in the middle of routing. So an
// empty rule is refused here, at once: `!rule` is true when it is empty.
void RuleDesk::add(Rule rule) {
if (!rule) {
throw std::invalid_argument("a rule must not be empty");
}
rules_.push_back(std::move(rule)); // move the callable in, not copy it
}
// The same loop as Handler::handle, over a vector instead of links: the
// first rule whose answer holds a Resolution wins, and later rules are not
// called. rule(ticket) calls whatever the std::function holds.
Resolution RuleDesk::route(const Ticket& ticket) {
for (const Rule& rule : rules_) {
if (auto resolution = rule(ticket)) {
return *resolution;
}
}
++unhandled_;
return Resolution{"triage queue", "waiting for a person"};
}

Here the rules are std::functions, so each level can be a lambda that captures its own settings, such as a refund limit:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

rule_desk.cpp
// Builds the standard team's routing as four lambdas, one per level, in the
// same order and with the same rules as the standard chain in main.cpp.
// Each lambda states its return type, `-> std::optional<Resolution>`,
// because it returns both a Resolution and std::nullopt; with no stated
// type, the compiler could not pick one from two different kinds of value.
RuleDesk make_standard_rule_desk() {
RuleDesk desk;
// The bot. Captures nothing (`[]`); its one topic and article are
// written into the lambda, where the FaqBot class takes a map.
desk.add([](const Ticket& t) -> std::optional<Resolution> {
if (t.topic == "password reset" && t.refund_cents == 0) {
return Resolution{"faq bot", "sent the article help/reset-password"};
}
return std::nullopt;
});
// The billing agent. `[limit = 50'00]` is an init-capture: the lambda
// gets its own int named `limit`, set to 5000 cents ($50.00), stored
// inside it like the refund_limit_cents_ member of BillingAgent.
desk.add([limit = 50'00](const Ticket& t) -> std::optional<Resolution> {
if (t.category != Category::billing || t.refund_cents > limit) {
return std::nullopt;
}
if (t.refund_cents == 0) {
return Resolution{"billing agent", "answered the question"};
}
return Resolution{"billing agent", "refunded " + format_cents(t.refund_cents)};
});
// The engineer: technical tickets that are not critical.
desk.add([](const Ticket& t) -> std::optional<Resolution> {
if (t.category != Category::technical || t.severity == Severity::critical) {
return std::nullopt;
}
return Resolution{"engineer", "opened a bug report"};
});
// The manager, with its own captured limit of $500.00.
desk.add([limit = 500'00](const Ticket& t) -> std::optional<Resolution> {
if (t.severity == Severity::critical) {
return Resolution{"manager", "started an incident"};
}
if (t.category == Category::billing && t.refund_cents > 0 && t.refund_cents <= limit) {
return Resolution{"manager", "approved a refund of " + format_cents(t.refund_cents)};
}
return std::nullopt;
});
// Returned by value: the vector of rules goes to the caller without a
// copy (the compiler moves it, or builds it in place).
return desk;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Route the same six tickets through the rule list, and count how many
// answers match the chain's, in both who and what. Ticket i's chain
// answer is chain_results[i], because both were filled in ticket order.
// std::size_t is the unsigned type that sizes and indexes use, so `i`
// compares with tickets.size() without a signed/unsigned warning.
RuleDesk rules = make_standard_rule_desk();
std::size_t same = 0;
for (std::size_t i = 0; i < tickets.size(); ++i) {
const Resolution resolution = rules.route(tickets[i]);
if (resolution.handled_by == chain_results[i].handled_by && resolution.action == chain_results[i].action) {
++same;
}
}
std::cout << "rule list: same as the chain for " << same << " of " << tickets.size()
<< " tickets; unhandled: " << rules.unhandled() << '\n';

The output’s last line shows the list routing all six tickets as the chain did. This is still Chain of Responsibility, the same idea held in a different structure. The list could equally hold std::unique_ptr<RoutingRule>, where RoutingRule is an interface with a virtual try_handle, if the rules need names, state, or their own tests.

Question Linked handlers A list of handlers
Who holds the order? spread over the links one container; with named rule objects, it can be printed and inspected
Insert or remove a level later relink by hand (here, not allowed after linking) insert or erase in the vector (given an API for it)
Can a handler do work before and after the rest? only in the classic form, where each handler calls the next (not this page’s Handler) no: the loop decides; use Decorator for that
Long chains recursive destruction no recursion
A level with its own type, state, and tests a class a class behind an interface, or a lambda

For this desk, either is sound. The list is simpler when levels are plain rules and the order is configuration, which is the common case. The linked form is worth it when a handler must control what happens to the rest of the chain, which the classic form allows and the base class here deliberately does not.

  • GUI events. A click goes to the widget under the mouse; if it does not handle it, the event goes to its parent, and on up to the window. The “next” link is the parent pointer of a Composite tree.
  • Middleware and filters. A request passes through a sequence of steps (authentication, rate limits, logging) before it reaches the code that answers it. When each step can also act on the way back, that is closer to Decorator than to a plain chain.
  • Choosing a parser, a codec, or a file loader. “Try each loader in order until one recognises the file” is a list of handlers.
  • Exceptions follow a similar idea: a thrown exception goes up the call stack to the first catch that matches. That is a language feature, not this pattern, but the “first one that can handles it” rule is the same.
  • More than one object may handle a request, and which one should is decided at run time, by the request.
  • The set of handlers or their order changes between configurations, teams, or over time (FR-2).
  • The sender should not depend on the handlers. It hands the request to the chain and gets an answer.
  • Each rule can be decided on its own, without knowing which other rules exist.
  • There is one handler, or always the same one: call it.
  • Every handler must see every request. That is broadcasting; see Observer.
  • The choice is a lookup by a key, such as a category. A std::map<Category, std::function<Resolution(const Ticket&)>> or a switch is clearer and says that exactly one applies.
  • The rules depend on each other, such as “the engineer takes it only if the bot already tried a different article”. Rules that need shared state or each other’s results are a single decision, better kept in one place.
  • The order is fixed and short. The before-version, a few ifs in one function, is easier to read than a chain. Move to a chain when FR-2-style requirements appear, not before.
  • Where a request ends up is not visible in one place. To know who handles a ticket, you must know the chain’s order, which is set at run time. Logging which handler took each request helps.
  • A request can fall off the end unless the design handles that (see Guaranteed handling).
  • Each request may visit every handler. For a few levels that is nothing; for hundreds of rules on a hot path, a lookup is faster.
  • The order matters, and is easy to get wrong. Put the manager first, and every refund costs a manager’s time. Tests should check the order a team actually uses.
  • Handlers that know about each other. A BillingAgent that calls Manager directly for large refunds hard-codes the order the chain exists to make configurable.
  • Using a chain to broadcast. If every handler acts and passes the request on, that is a list of observers or a pipeline, and its name should say so.
  • Ignoring the end. A chain with no fallback and no check for “nothing” drops requests silently.
  • “A new security level, first, for account takeovers.” A new handler class; teams that want it put it at the front. No existing handler changes.
  • “Log which level handled each ticket.” One change in SupportDesk::route (or in Handler::handle), not in every handler.
  • “Refunds over $500 need a director.” A new Director handler at the end of the chain, for the teams that have one.
  • “Show each team’s routing in the admin screen.” Easier with a list of named rule objects (each with a name()), which can be read in order. std::function rules would need names added, and the linked form would need a way to walk the links from outside.

Exercise: Handle an unhandled request

A customer asks for a $900 refund. No level in the standard chain can approve more than $500, so the chain returns nothing, and the desk sends the ticket to triage.

  1. A product owner says: “large refunds should not wait in triage with everything else; they should go to the finance team’s queue, and finance should be told how much.” Change the design so that happens, without changing any existing handler. Sketch the C++.
  2. Another team wants a guarantee that their chain can never return nothing. Design a way to build a chain whose last handler always takes the request, so that a builder cannot forget it.
  3. Which of the two changes would you make for the help desk, and why?
Show the explained answer

1. Add a handler at the end of the standard chain, after the manager, that takes billing tickets with large refunds:

// A new level, written like the four existing ones: it overrides only
// try_handle, and Handler::handle still does the passing-on. It takes
// billing tickets whose refund is more than `above_cents`.
class FinanceQueue final : public Handler {
public:
explicit FinanceQueue(int above_cents) : above_cents_{above_cents} {}
private:
std::optional<Resolution> try_handle(const Ticket& ticket) const override {
// Not billing, or a refund of at most the threshold: not mine.
// With a threshold of 500'00, a refund of exactly $500.00 is left
// to the manager, whose limit includes it.
if (ticket.category != Category::billing || ticket.refund_cents <= above_cents_) {
return std::nullopt;
}
// The amount goes into the action, so finance is told how much.
return Resolution{"finance queue",
"waiting for finance: refund of " + format_cents(ticket.refund_cents)};
}
int above_cents_;
};
// When building the chain (last, after the manager, and with the
// manager's limit as the threshold, so no refund falls between the two):
// ...then(std::make_unique<Manager>(500'00))
// .then(std::make_unique<FinanceQueue>(500'00));

No other handler changes, and teams without a finance team leave it out. Legal tickets still reach triage. Placed after the manager, it sees only what the manager declined; its threshold must not be above the manager’s limit, or refunds in between fall through to triage. Placed before the manager, its threshold must not be below the manager’s limit, or it takes refunds the manager could approve. Either way the two numbers are linked, so set them from one constant.

2. Make the last handler a separate type, and require it where the chain is built:

// The last resort. It is not a Handler: take returns a Resolution, not an
// optional, so "this one always answers" is written into its type.
class Fallback { // always takes the request
public:
virtual ~Fallback() = default;
virtual Resolution take(const Ticket& ticket) = 0;
};
// Like SupportDesk, but the team chooses the fallback, and must: the only
// constructor needs both parts, and refuses a null one, so a desk without
// a fallback cannot be built.
class GuaranteedDesk {
public:
// Owns both: the chain (first handler, which owns the rest) and the
// fallback. Only declared here; its body would move them into the
// members and throw std::invalid_argument if either is null.
GuaranteedDesk(std::unique_ptr<Handler> chain, std::unique_ptr<Fallback> last); // throws if either is null
// Try the chain first; if it returns nothing, the fallback answers.
// Either way a Resolution comes back.
Resolution route(const Ticket& ticket) {
if (auto resolution = chain_->handle(ticket)) {
return *resolution;
}
return last_->take(ticket);
}
private:
std::unique_ptr<Handler> chain_;
std::unique_ptr<Fallback> last_;
};

Fallback::take returns a Resolution, not an optional, so the type says that it always handles. A desk cannot be built without one. This is SupportDesk’s approach with the fallback made a choice of each team instead of fixed in the desk.

3. For the help desk, part 1: the requirement is about one kind of ticket going somewhere specific, which is what adding a level is for. SupportDesk already guarantees a response (the triage queue), so part 2 is only worth it if teams need different fallbacks.

  • Decorator also links objects that each own the next one. A decorator always passes on and adds behaviour around the call; a chain handler usually stops at the first one that handles. See Decorator.
  • Command turns a request into an object, which can then be passed along a chain. See Command.
  • Composite trees often supply the chain: a request goes from a child to its parent. See Composite.
  • Observer sends an event to every subscriber, not to the first that takes it. See Observer.
  • Template Method is how this page’s Handler keeps the passing-on in one place. See Template Method.
  • Chain of Responsibility sends a request along a sequence of handlers; the first one that can deal with it does, and the sender does not know which.
  • Each handler decides alone. Who is in the chain, and in what order, is set by whoever builds it, so it can differ between configurations.
  • In C++, a non-virtual handle that loops over the handlers stops any handler from forgetting to pass a request on; std::unique_ptr links make the chain’s ownership explicit.
  • A list of handlers is the same idea, often simpler: the order is in one container you can inspect and change.
  • Decide what happens when nobody handles a request: a fallback, a final handler, an explicit “nothing”, or an exception. Never let it fall off the end unnoticed.