Skip to content

API contracts and validation placement

Difficulty: Intermediate

Key concepts

  • validation
  • syntactic validation
  • semantic validation
  • API contract
  • error reporting
  • invariant
  • boundary
  • The difference between syntactic checks (is the request well formed?) and semantic checks (does it make sense, given the rules and what is stored?).
  • A simple way to place each check: by what it needs to know.
  • How a C++ boundary turns request text into a command holding domain values, so later code cannot receive a malformed id.
  • Why the domain still enforces its invariants when the boundary already checked them.
  • How to write an error-reporting contract: stable codes, one status per outcome, every field problem at once, and no internal details.

The registrar’s web service gains two requests: create a course, and enroll a student. Each can be wrong in many ways. A field may be missing, a capacity may be two, a course code may be cs101, the course may already exist, or the student may already take three courses.

Without a plan, each check lands wherever its author happened to be working.

Step 1: classify each check by what it needs

Section titled “Step 1: classify each check by what it needs”
Check Kind Needs Where it goes Reported as
field present, not repeated, known syntactic the request alone boundary 400, field problem
capacity is a whole number syntactic the request alone boundary 400, field problem
title at most 60 bytes syntactic the request and the API’s limits boundary 400, field problem
CS101 is a well-formed code syntactic the value’s format value object, asked by the boundary 400, field problem
capacity is at least 1 semantic the domain’s rule, no stored data domain; pre-checked by the boundary 400, field problem
the course code is free semantic stored data application service 409, refused
the course and the student exist semantic stored data application service 404, not found
at most three courses per student semantic stored data and the domain’s rule domain, called by the service 409, refused

Syntactic checks ask whether the request is well formed: the right fields, the right types, sensible lengths. They need only the request, so they run first, at the boundary, before anything else is touched.

Semantic checks ask whether the request makes sense. Some need only a rule (“capacity is at least 1”); most also need stored data (“is CS101 taken?”). They run where that knowledge lives: in the domain for rules, and in the application service for questions about what exists.

The “Needs” column is the placement rule. A check’s home is the first place that has everything it needs; checking only later lets bad data travel further than it must. A rule that needs no stored data may also be pre-checked earlier, at the boundary, so the client hears about it as a field problem. The capacity rule is the example: its home is the domain, and the boundary keeps a copy.

The status follows the same line. A request that is wrong in itself, whether malformed or against a rule that needs no stored data, is a 400 with field problems: the client can fix it from the request alone. A request that is fine in itself but refused given what is stored is a 409. An id that names nothing stored is a 404.

Where checks happen for one create-course request: the boundary checks the shape and asks the value object about the code, the service checks stored data, and the Course constructor enforces its own rule
Text description of the diagram

A sequence diagram with six participants: client, handler, boundary, CourseCode parse, service, and Course. The client sends POST /courses with a code, a title, and a capacity. The handler calls check_create_course on the boundary. Check 1: the boundary checks that every field name is known and none is repeated. Check 2: it checks that the code is present, and asks CourseCode parse whether it is well formed, getting back a CourseCode or nothing. Check 3: it checks that the title is present and short enough, and that the capacity is present, a whole number, and at least 1. The boundary returns every problem found, or a command. If there are problems, the handler replies 400 with them. Otherwise the handler calls create_course on the service with the command. Check 4: the service checks whether the code is free among the stored courses, and replies 409 course_exists if it is taken. Check 5: the service constructs a Course, whose constructor enforces a capacity of at least 1 and throws std::invalid_argument otherwise. The service returns created, and the handler replies 201 created, or 500 if anything threw.

Diagram source (Mermaid)
sequenceDiagram
participant C as client
participant H as handler
participant B as boundary
participant V as CourseCode parse
participant S as service
participant D as Course
C->>H: POST /courses with code, title, capacity
H->>B: check_create_course
B->>B: 1 field names known, none repeated
B->>V: 2 code present, and is it well formed
V-->>B: a CourseCode, or nothing
B->>B: 3 title present and short enough, capacity present, a whole number, at least 1
B-->>H: every problem found, or a command
H-->>C: 400 with the problems, if any
H->>S: create_course with the command
S->>S: 4 is the code free in the stored courses
S-->>H: 409 course_exists, if taken
S->>D: 5 construct, enforcing capacity of at least 1
D-->>S: a Course, or std::invalid_argument
S-->>H: created
H-->>C: 201 created, or 500 if anything threw

Before writing any check, decide what a failure looks like to the client. This is the error-reporting contract, and clients will write code against it.

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

contract.hpp
// The error-reporting contract: what every reply can say, in a form a
// client program can act on. Codes are stable names; nothing here comes
// from an exception's message.
// This header is the whole promise to clients: every reply is one Reply,
// its outcome picks the HTTP-style status number, and to_json writes it.
// A client program tests the outcome name and the field problems, never
// a sentence, so the wording of a message can change without breaking it.
// The six kinds of answer. The numbers in the comments are what
// status_code returns for each one.
enum class Outcome {
created, // 201: the thing now exists
ok, // 200: done; detail says how
invalid_request, // 400: wrong in itself, without looking at stored data; lists every problem
not_found, // 404: an id names nothing stored; detail says which
refused, // 409: fine in itself, but refused given what is stored
internal_error, // 500: our fault; no details
};
// One thing wrong with one field of the request, such as
// {"capacity", "not_a_whole_number"}. An invalid request carries a list
// of these, so the client hears every problem in one reply.
struct FieldProblem {
std::string field; // the field's name as the client sent it
std::string problem; // "missing", "empty", "bad_format", "too_long", ...
};
// One reply. Which members matter depends on the outcome: detail for
// ok, not_found, and refused; problems for invalid_request; neither for
// created and internal_error. The builder functions below fill in the
// right ones, so callers do not have to remember this.
struct Reply {
Outcome outcome = Outcome::ok;
std::string detail; // for ok, not_found, and refused
std::vector<FieldProblem> problems; // for invalid_request
};
// One function per outcome, so every reply is built the same way.
// The strings and the list are taken by value and moved into the Reply,
// so a caller that passes a temporary pays for no extra copy.
// internal_error() takes nothing on purpose: there is no way to attach
// an exception's message to it, so none can reach the client.
Reply created();
Reply ok(std::string detail);
Reply invalid_request(std::vector<FieldProblem> problems);
Reply not_found(std::string what);
Reply refused(std::string why);
Reply internal_error();
// 201, 200, 400, 404, 409, or 500, as listed on the enum.
int status_code(Outcome outcome);
// {"result":"created"}, {"result":"seated"}, or an error object such as
// {"error":"refused","detail":"course_exists"}. Every string is escaped,
// because field names in problems can come straight from the client.
std::string to_json(const Reply& reply);

The contract makes four promises:

  • One status code per outcome. A client can branch on 400, 404, 409, or 500 without reading text. Here, a request refused given what is stored is 409 Conflict; some APIs use 422 for that, and some use 422 for an id in the request body that names nothing, keeping 404 for an address that does not exist. Each choice is defensible. What matters is that the contract says which, and keeps saying it.
  • Stable codes, not sentences. course_exists and bad_format are names a client program can compare. A sentence for people can be added, but the code is what programs rely on.
  • Every field problem at once. A 400 lists all the problems found, so a form can mark every wrong field in one round trip.
  • No internal details. internal_error carries nothing: the client cannot fix our bug, and the message of an exception may reveal how the program works inside.

The boundary’s job is to turn request text into a command, a struct that has passed every check the request alone allows, or into a list of problems:

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

requests.hpp
// What the boundary hands to the application: requests that have passed
// every check that needs no stored data. The ids are domain values, so
// a command cannot hold a malformed one; the other fields are plain
// values, which anyone can set, so the domain checks them again.
// A checked "create a course" request. code is a domain::CourseCode, so
// it can only hold a well-formed code (parse is the only way to make
// one). title and capacity were checked by the boundary, but nothing in
// the type stops other code from building a CreateCourse with capacity 0,
// which is why the Course constructor checks again.
struct CreateCourse {
domain::CourseCode code;
std::string title;
int capacity = 0;
};
// A checked "enroll" request: both ids are domain values. Whether the
// student and the course exist is not known yet; that needs stored data,
// so the application answers it.
struct Enroll {
domain::StudentId student;
domain::CourseCode course;
};
// Either the command, or every problem found in the request.
// std::variant holds exactly one of the types listed, here a Command or a
// list of problems, never both and never neither. The `template` and
// `using` make Checked a short name for any command: Checked<Enroll> is
// std::variant<Enroll, std::vector<api::FieldProblem>>. The caller must
// look at which one it got (handler.cpp does, with std::get_if) before
// using it, so an unchecked request cannot be used by mistake.
template <typename Command>
using Checked = std::variant<Command, std::vector<api::FieldProblem>>;
// The API's own limit, from what the website can show; not a domain rule.
// Counted in bytes: a title with accented letters fits fewer characters.
// `inline constexpr` gives one constant, fixed at compile time, that any
// file including this header can use without a duplicate definition.
inline constexpr std::size_t max_title_length = 60;
// Request text such as "code=CS101&title=Software Design&capacity=30".
// Each runs every check that needs only the text, collects every problem
// instead of stopping at the first, and returns the command only if the
// list stayed empty. Neither throws for a bad request: problems are an
// expected answer, returned as a value.
// check_enroll takes "student=S1&course=CS101".
Checked<CreateCourse> check_create_course(std::string_view query);
Checked<Enroll> check_enroll(std::string_view query);

CreateCourse holds a domain::CourseCode, not a string. Since a CourseCode can only be made by parse, a command that exists holds a well-formed code, and the service never checks the format again. Only the ids are guaranteed by their types, though: capacity and title are plain values that any caller can set, which is why the domain checks the capacity again. This idea is often summed up by the phrase “parse, don’t validate”, the title of a 2019 essay by Alexis King: instead of checking text and passing the same text on, turn it into a type that cannot hold a bad value.

Checked<Command> is a std::variant of the command and the list of problems. A bad request is expected now and then, so it is a value, not an exception, as the errors and contracts page recommends for expected failures.

The first step splits the text into fields, refusing names the request type does not have:

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

requests.cpp
// Splits "a=1&b=2" into named fields. A name the request type does not
// have, or a name given twice, is a problem: the contract says which
// fields exist, and a typo should not be silently ignored.
// Inputs: the query text, the field names this request type allows (a
// brace list such as {"code", "title", "capacity"}), and the list to add
// problems to, passed by reference so the caller sees what was added.
// Result: a map from name to value text, with each allowed name at most
// once. Values are not checked here; the functions below do that.
Fields split_fields(std::string_view query, std::initializer_list<std::string_view> names,
Problems& problems) {
Fields fields;
// Each turn cuts one "name=value" part off the front of query, until
// nothing is left. query is a string_view, so cutting only moves the
// view's start; the caller's text is never copied or changed.
while (!query.empty()) {
// find gives std::string_view::npos (a huge number) when there is
// no '&'; std::min turns that into "the rest of the text".
const std::size_t end = std::min(query.find('&'), query.size());
const std::string_view part = query.substr(0, end);
// Drop the part and its '&'. On the last part there is no '&', and
// end + 1 would be one past the end, so std::min stops at the end.
query.remove_prefix(std::min(end + 1, query.size()));
// The same trick for '=': a part with no '=', such as "title",
// gets the whole part as its name and an empty value.
const std::size_t equals = std::min(part.find('='), part.size());
// Copies, because the map keeps them after query is gone.
const std::string name{part.substr(0, equals)};
const std::string value{part.substr(std::min(equals + 1, part.size()))};
if (std::find(names.begin(), names.end(), name) == names.end()) {
// Not a field of this request: "room", a typo such as "cours",
// or "" from an empty part between two '&'.
problems.push_back({name, "unknown_field"});
} else if (!fields.emplace(name, value).second) {
// emplace adds the pair only if the name is not in the map yet,
// and returns a pair whose .second says whether it did. false
// means a second value for the same name: the first one is
// kept, and the repeat is reported.
problems.push_back({name, "repeated"});
}
}
return fields;
}
// The field's text, or nullptr after recording why there is none.
// A field that is absent is "missing"; one given as "title=" is "empty".
// The pointer points into `fields`: it is valid only while that map
// exists and that entry is not erased, which holds in the callers below, where the
// map is a const local that outlives every use of the pointer. A pointer
// (not a copy) is returned so a field is never copied just to be read.
const std::string* required(const Fields& fields, std::string_view name, Problems& problems) {
const auto found = fields.find(name); // an iterator to the entry, or fields.end()
// `||` stops early: found->second is only read when found is a real entry.
if (found == fields.end() || found->second.empty()) {
problems.push_back({std::string{name}, found == fields.end() ? "missing" : "empty"});
return nullptr;
}
return &found->second; // the address of the value text inside the map
}

Refusing unknown fields is a contract decision. If a client sends capasity=30 and unknown fields were ignored, the reply would say that capacity is missing, although the client believes it sent it; for an optional field, the typo would be dropped without any error at all. Naming the unknown field tells the client exactly what went wrong. Some APIs ignore unknown fields instead, so that old servers accept requests from newer clients. That is also a valid contract, but it should be chosen, not fallen into.

Two helpers read single fields. Each records a problem and returns nothing when the field is missing or wrong:

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

requests.cpp
// A whole number that uses all of the text: "12abc", "1.5", " 7", and
// "+7" are refused; "-1" is read, and left to the range checks.
// Result: the number, or std::nullopt after adding exactly one problem
// (missing, empty, out_of_range, or not_a_whole_number) for this field.
std::optional<int> int_field(const Fields& fields, std::string_view name, Problems& problems) {
const std::string* text = required(fields, name, problems);
if (text == nullptr) return std::nullopt; // required already said why
int value = 0;
const char* last = text->data() + text->size(); // one past the last character
// std::from_chars reads digits (and a leading '-') from the start and
// never throws. It returns where it stopped and an error code;
// `const auto [end, error]` names the two (a structured binding).
const auto [end, error] = std::from_chars(text->data(), last, value);
// A number too big for an int, such as "99999999999".
if (error == std::errc::result_out_of_range) {
problems.push_back({std::string{name}, "out_of_range"});
return std::nullopt;
}
// No number at the start ("two", " 7", "+7"), or text left over after
// it ("12abc" stops at 'a', "1.5" at '.'). std::errc{} means no error.
if (error != std::errc{} || end != last) {
problems.push_back({std::string{name}, "not_a_whole_number"});
return std::nullopt;
}
return value;
}
// The value object owns its format; the boundary asks it, rather than
// keeping a second copy of the rule.
// A template, so one function serves both id types: the caller names the
// type, as in id_field<domain::CourseCode>(...), and Id::parse becomes
// CourseCode::parse. Result: the id, or std::nullopt after adding one
// problem: missing, empty, or bad_format.
template <typename Id>
std::optional<Id> id_field(const Fields& fields, std::string_view name, Problems& problems) {
const std::string* text = required(fields, name, problems);
if (text == nullptr) return std::nullopt;
std::optional<Id> id = Id::parse(*text); // *text: the string the pointer points at
if (!id) problems.push_back({std::string{name}, "bad_format"});
return id; // empty or not, the caller gets parse's answer
}

Then each field is checked, and every problem is collected:

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

requests.cpp
// Every syntactic check for "create a course", in a fixed order: unknown
// and repeated fields first (split_fields), then code, title, and
// capacity. Each check adds to the same problems list and does not stop
// the others, so one reply can list every mistake.
Checked<CreateCourse> check_create_course(std::string_view query) {
Problems problems;
// fields is const and lives until the function returns, so the
// pointers that required hands out below stay valid.
const Fields fields = split_fields(query, {"code", "title", "capacity"}, problems);
const std::optional<domain::CourseCode> code =
id_field<domain::CourseCode>(fields, "code", problems);
const std::string* title = required(fields, "title", problems);
if (title != nullptr && title->size() > max_title_length) {
problems.push_back({"title", "too_long"});
}
const std::optional<int> capacity = int_field(fields, "capacity", problems);
if (capacity && *capacity < 1) {
// Course's own rule, pre-checked here so the client hears which
// field is wrong; the constructor still enforces it.
problems.push_back({"capacity", "below_1"});
}
// Every problem is reported at once, so the client can fix them all.
// The list becomes the variant's second kind of value.
if (!problems.empty()) return problems;
// No problems means every check above succeeded, and each one adds a
// problem whenever it fails, so code and capacity hold values and
// title is not nullptr. That is what makes the three `*` safe here.
// *title copies the title text into the command.
return CreateCourse{*code, *title, *capacity};
}
How this code works: check_create_course on a request with four mistakes

The second request in main is code=cs101&title=&capacity=two&room=B12. Every check adds to one problems list, and none of them stops the others.

1. split_fields cuts the text at each &, then each part at its first =:

Part Name Value What happens
code=cs101 code cs101 allowed, stored
title= title (empty) allowed, stored with an empty value
capacity=two capacity two allowed, stored
room=B12 room B12 not allowed: room:unknown_field

2. The code. id_field<domain::CourseCode> finds cs101, which is not empty, and asks CourseCode::parse. Small letters are refused, so it adds code:bad_format and returns an empty optional.

3. The title. required finds the field, but its value is empty, so it adds title:empty and returns nullptr. The length check is skipped, because title != nullptr is false.

4. The capacity. int_field gets the text two. std::from_chars finds no digit at the start and sets its error code, so it adds capacity:not_a_whole_number and returns an empty optional. The below_1 check is skipped, because the optional is empty.

5. The result. The list has four problems, in the order they were found: room, code, title, capacity. It is returned, and the variant holds the list instead of a command. The handler later writes exactly this list as a 400 reply, as the program output below shows.

Had the list been empty, every * in the last line would be safe: each check adds a problem whenever it fails, so an empty list means code and capacity hold values and title points at real text.

Three details:

  • The code’s format is not written here. id_field calls CourseCode::parse and turns std::nullopt into a bad_format problem. The value object is the one place that knows what a course code looks like.
  • int_field uses std::from_chars and requires it to use the whole text, so 12abc and 1.5 are refused, unlike with std::stoi. from_chars also refuses +7 and leading spaces, and reads -1, which the range check then reports as below_1. A number too large for an int is reported as out_of_range, not as “not a whole number”.
  • The title limit is the API’s, not the domain’s. A Course can hold any title; 60 is what the website can show. Keeping it in the boundary lets the domain stay free of display concerns. It counts bytes, so a title with accented letters fits fewer characters; real code would count characters or display width.

The capacity check appears twice: as below_1 in the boundary, and in the Course constructor, which throws std::invalid_argument. That looks like the duplication the flawed example was criticized for, but the two copies have different jobs.

  • The domain’s check is the guarantee. Every Course ever built has at least one seat, whoever builds it: this service, an import job, a test, or code written next year.
  • The boundary’s check is for the client. It turns a broken rule into a field problem with a name, instead of an exception that can only become a 500.

The cost is two copies that can drift apart. A test pins them together, as the testing section shows. If the rule were more complex, the domain could expose it once, for example as a static Course::valid_capacity(int) that both places call. The DDD page’s Course is reused unchanged here, so the example keeps the copy and the test.

Some questions cannot be answered from the request: whether CS101 is taken, or whether student S7 exists. They belong to the application service, which owns the stored data:

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

enrollment_service.hpp
// The application: takes checked commands and answers the questions that
// need stored data (does it exist? is it taken?), then lets the domain
// decide the rest. It never sees request text.
// It owns every course and every student's load, by value, in two maps.
// Its functions take boundary commands, never request text, so the ids
// they get are always well formed (they are domain values). In this
// program only the boundary builds commands, but CreateCourse is a plain
// struct that any code could fill in, so the Course constructor checks again.
class EnrollmentService {
public:
// Registers a student with no courses yet. Adding one twice changes
// nothing. This stands in for a real student store.
void add_student(const domain::StudentId& student);
// Semantic checks, which need stored data. create_course: refused if
// the code is taken, created otherwise. enroll: not_found for an
// unknown course or student; then the domain decides between seated,
// waitlisted, and two refusals. Neither returns invalid_request: a
// command that got here has already passed every syntactic check.
api::Reply create_course(const boundary::CreateCourse& command);
api::Reply enroll(const boundary::Enroll& command);
private:
// std::map keeps its keys sorted, using the ids' <=> comparison.
std::map<domain::CourseCode, domain::Course> courses_;
std::map<domain::StudentId, domain::StudentLoad> loads_; // a student's courses, and limit
};

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

enrollment_service.cpp
// Called with a command the boundary has already checked: a well-formed
// code, a title of at most 60 bytes, and a capacity of at least 1. The
// one question left needs the stored courses: is the code free?
api::Reply EnrollmentService::create_course(const boundary::CreateCourse& command) {
// Semantic: whether the code is free depends on what is stored.
// count is 1 if the map has the key and 0 if not. Checking first means
// an existing course is reported as refused, not silently kept.
if (courses_.count(command.code) != 0) return api::refused("course_exists");
// The constructor enforces capacity >= 1 whoever calls it; a command
// that skipped the boundary makes it throw std::invalid_argument.
// The Course is built first, from copies of the command's fields; if
// that throws, nothing is added, and the exception goes up to answer
// (in handler.hpp), which replies internal_error. Otherwise emplace
// moves the new Course into the map under its code.
courses_.emplace(command.code, domain::Course{command.code, command.title, command.capacity});
return api::created();
}

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

enrollment_service.cpp
// The ids in the command are well formed; whether they name anything is
// a semantic question, answered from the maps. Then the domain decides,
// and its answer is translated into the contract's words. A refusal
// leaves both maps exactly as they were.
api::Reply EnrollmentService::enroll(const boundary::Enroll& command) {
// find gives an iterator to the map entry (its ->second is the
// value), or end() when the key is not stored. The course is looked
// up first, so a request naming two unknown things gets "course".
const auto course = courses_.find(command.course);
if (course == courses_.end()) return api::not_found("course");
const auto load = loads_.find(command.student);
if (load == loads_.end()) return api::not_found("student");
// The domain decides, on copies, as on the DDD page; both are kept
// only if something changed.
// Copies of the stored values. domain::enroll changes the objects it
// is given, so it is handed these copies, not the stored originals.
domain::Course next_course = course->second;
domain::StudentLoad next_load = load->second;
const domain::EnrollDecision decision = domain::enroll(next_load, next_course);
// The two refusals return here; the copies are thrown away when the
// function ends, so nothing stored changes. seated and waitlisted
// fall through to `break` and go on to keep the changes. Listing
// every case lets the compiler warn if a new status is added.
switch (decision.status) {
case domain::EnrollStatus::already_in_course: return api::refused("already_in_course");
case domain::EnrollStatus::at_course_limit: return api::refused("at_course_limit");
case domain::EnrollStatus::seated:
case domain::EnrollStatus::waitlisted: break;
}
next_course.take_events(); // this example publishes no events
// Keep both changes. std::move lets each stored value take over the
// copy's contents (its lists) instead of copying them again; the
// copies are not used after this. Moving standard strings and
// containers does not throw, so the course and the load change together.
course->second = std::move(next_course);
load->second = std::move(next_load);
// `?:` picks the word: "seated" if the status is seated, else "waitlisted".
return api::ok(decision.status == domain::EnrollStatus::seated ? "seated" : "waitlisted");
}

The service checks existence, then hands the decision to the domain’s enroll, which applies the course’s seats and the student’s limit. The service does not repeat the limit: it translates the domain’s answer, such as at_course_limit, into the contract’s refused. The domain decides; the service reports.

A check that needs stored data, made at the boundary, would need the stored data there. That would make the boundary a second owner of the data, with all the risk of two places reading it at different moments.

The handler: one place turns failures into replies

Section titled “The handler: one place turns failures into replies”

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

handler.cpp
// The boundary checks the request; only a checked command reaches the
// service.
// run takes the boundary's answer (a command, or a list of problems) and
// `use`, the function to call with the command. Command and Use are
// template parameters: the compiler works them out from the arguments,
// so one run serves both CreateCourse and Enroll.
template <typename Command, typename Use>
api::Reply run(const boundary::Checked<Command>& checked, Use use) {
// std::get_if gives a pointer to the list of problems if that is what
// the variant holds, and nullptr if it holds the command. Declaring
// `problems` inside the if means it exists only where it is non-null.
if (const auto* problems = std::get_if<std::vector<api::FieldProblem>>(&checked)) {
return api::invalid_request(*problems); // 400, every problem; the service is not called
}
// Not problems, so it must be the command. std::get reads it; it
// would throw std::bad_variant_access for the wrong type, which the
// check above rules out.
return use(std::get<Command>(checked));
}
// Picks the request type from how the text starts, hands the rest to
// the matching boundary check, and, if that passes, to the service.
// Any other text, such as "DELETE /courses/CS101", is not_found("route").
api::Reply route(EnrollmentService& service, std::string_view request) {
constexpr std::string_view create = "POST /courses ";
constexpr std::string_view enroll = "POST /enroll ";
// substr(0, count) is the first count characters (or all of a shorter text),
// so this asks "does the request start with create?".
if (request.substr(0, create.size()) == create) {
// The query after the prefix goes to the boundary first. The
// lambda is the `use` step: [&] captures `service` by reference,
// so the lambda calls the real service, not a copy of it.
return run(boundary::check_create_course(request.substr(create.size())),
[&](const boundary::CreateCourse& command) {
return service.create_course(command);
});
}
if (request.substr(0, enroll.size()) == enroll) {
return run(boundary::check_enroll(request.substr(enroll.size())),
[&](const boundary::Enroll& command) { return service.enroll(command); });
}
return api::not_found("route");
}

run is the gate: only a checked command reaches the service. A list of problems goes straight back as a 400.

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

handler.hpp
// Runs one request's work and writes the reply as "STATUS JSON". Any
// exception is our fault, not the client's: the reply says only
// internal_error, and the details go to the log, never to the client.
// Work is any callable that takes nothing and returns an api::Reply,
// usually a lambda; `Work&&` accepts it whether it is a temporary or a
// named variable. The log stream is borrowed by reference: answer writes
// to it but does not own it. This is the one place exceptions are caught,
// so the code below it (route, the boundary, the service) never needs a
// try block of its own.
template <typename Work>
std::string answer(Work&& work, std::ostream& log) {
api::Reply reply; // default: outcome ok; always replaced below
try {
reply = work(); // the request's real work, which may throw
} catch (const std::exception& failure) {
// Every standard exception, and any derived from std::exception,
// lands here. what() is its message: written to the log only.
log << "internal error: " << failure.what() << '\n';
reply = api::internal_error();
} catch (...) {
// `...` catches anything else that was thrown, such as an int.
// There is no message to read, so the log says only that.
log << "internal error: an exception not derived from std::exception\n";
reply = api::internal_error();
}
// Writing the reply is outside the try: if even that throws, the
// caller's own handler, or std::terminate, has to deal with it.
// For example "409 {"error":"refused","detail":"course_exists"}".
return std::to_string(api::status_code(reply.outcome)) + ' ' + api::to_json(reply);
}
How this code works: One request through boundary, service, and domain

The sixth request in main is POST /enroll student=S2&course=CS101. By then CS101 exists with one seat, and S1 holds it.

  1. main calls app::handle(service, request, std::cerr). It passes the service and the log stream by reference: handle borrows them and owns neither.
  2. handle calls answer with a lambda that calls route(service, request). Everything from here on runs inside answer’s try.
  3. route sees that the text starts with POST /enroll , and passes the rest, student=S2&course=CS101, to boundary::check_enroll.
  4. The boundary splits the fields and parses both ids with StudentId::parse and CourseCode::parse. No problems, so the Checked<Enroll> holds an Enroll command made of two domain values. The request text is not used after this.
  5. run finds no problem list in the variant, so it calls the lambda with the command, and the lambda calls service.enroll.
  6. The service asks the stored-data questions: CS101 is in courses_, S2 is in loads_. It copies the stored Course and StudentLoad, and gives the copies to domain::enroll.
  7. The domain decides: S2 is not in the course, is under the three-course limit, and the one seat is taken, so S2 joins the waitlist and the answer is waitlisted.
  8. The service keeps the change by moving both copies back into its maps, and returns api::ok("waitlisted").
  9. answer turns the reply into 200 {"result":"waitlisted"}, which main prints.

The same path also shows where each refusal stops. A malformed id stops at step 4 (400) and the service is never called. An unknown course or student stops at step 6 (404). A domain refusal such as already_in_course stops at step 7 (409), and the copies are dropped, so the stored data is unchanged. An exception thrown anywhere in steps 3 to 8 is caught in answer and becomes 500 internal_error.

answer wraps every request’s work. An exception means something the contract did not foresee: a bug, or a failure such as running out of memory. The client gets 500 and internal_error; the details go to the log, where the people who can fix the bug will see them. The catch (...) covers exceptions not derived from std::exception. Writing the reply happens after the try, so a failure there, such as running out of memory while building the text, is left to the caller. The main program passes std::cerr as the log.

namespace api

the contract, no domain types

Functions

  • enum class Outcome { created, ok, invalid_request, not_found, refused, internal_error };
  • struct FieldProblem { std::string field; std::string problem; };
  • struct Reply { Outcome outcome; std::string detail; std::vector<FieldProblem> problems; };
  • int status_code(Outcome outcome);
  • Reply refused(std::string why); and one such function per outcome
  • std::string to_json(const Reply& reply);

namespace boundary

request text to commands

Functions

  • struct CreateCourse { domain::CourseCode code; std::string title; int capacity; };
  • struct Enroll { domain::StudentId student; domain::CourseCode course; };
  • Checked<CreateCourse> check_create_course(std::string_view query);
  • Checked<Enroll> check_enroll(std::string_view query);

class app::EnrollmentService

checks that need stored data

Data members

  • std::map<domain::CourseCode, domain::Course> courses_;
  • std::map<domain::StudentId, domain::StudentLoad> loads_;

Member functions

  • api::Reply create_course(const boundary::CreateCourse& command);
  • api::Reply enroll(const boundary::Enroll& command);

namespace app

the handler

Functions

  • std::string answer(Work&& work, std::ostream& log); template
  • std::string handle(EnrollmentService& service, std::string_view request, std::ostream& log);
The validation example's pieces: the contract, the boundary's commands and checks, the service, and the handler; members are summarized

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

main.cpp
int main() {
// The service owns all stored data. Two students exist; no courses
// yet. `*` takes the id out of the optional that parse returns.
app::EnrollmentService service;
service.add_student(*domain::StudentId::parse("S1"));
service.add_student(*domain::StudentId::parse("S2"));
// Request text is not URL-encoded here, so titles hold plain spaces.
// One request for each kind of answer: created, a 400 with four
// problems, a 400 for capacity 0, a 409 for a taken code, seated,
// waitlisted (CS101 has one seat), already_in_course, a 400 for a
// repeated and a missing field, two 404s, and an unknown route.
constexpr std::string_view requests[] = {
"POST /courses code=CS101&title=Software Design&capacity=1",
"POST /courses code=cs101&title=&capacity=two&room=B12",
"POST /courses code=MA101&title=Linear Algebra&capacity=0",
"POST /courses code=CS101&title=Software Design Again&capacity=30",
"POST /enroll student=S1&course=CS101",
"POST /enroll student=S2&course=CS101",
"POST /enroll student=S2&course=CS101",
"POST /enroll student=S2&student=S1",
"POST /enroll student=S7&course=CS101",
"POST /enroll student=S1&course=PH101",
"DELETE /courses/CS101",
};
// handle is the single entry point; the log goes to std::cerr, so the
// standard output shows only requests and replies.
for (const std::string_view request : requests) {
std::cout << "> " << request << '\n' << app::handle(service, request, std::cerr) << '\n';
}
}
Expected output
> POST /courses code=CS101&title=Software Design&capacity=1
201 {"result":"created"}
> POST /courses code=cs101&title=&capacity=two&room=B12
400 {"error":"invalid_request","problems":[{"field":"room","problem":"unknown_field"},{"field":"code","problem":"bad_format"},{"field":"title","problem":"empty"},{"field":"capacity","problem":"not_a_whole_number"}]}
> POST /courses code=MA101&title=Linear Algebra&capacity=0
400 {"error":"invalid_request","problems":[{"field":"capacity","problem":"below_1"}]}
> POST /courses code=CS101&title=Software Design Again&capacity=30
409 {"error":"refused","detail":"course_exists"}
> POST /enroll student=S1&course=CS101
200 {"result":"seated"}
> POST /enroll student=S2&course=CS101
200 {"result":"waitlisted"}
> POST /enroll student=S2&course=CS101
409 {"error":"refused","detail":"already_in_course"}
> POST /enroll student=S2&student=S1
400 {"error":"invalid_request","problems":[{"field":"student","problem":"repeated"},{"field":"course","problem":"missing"}]}
> POST /enroll student=S7&course=CS101
404 {"error":"not_found","detail":"student"}
> POST /enroll student=S1&course=PH101
404 {"error":"not_found","detail":"course"}
> DELETE /courses/CS101
404 {"error":"not_found","detail":"route"}

Reading the replies against the table in step 1:

  • The second request has four problems, and all four come back in one reply: an unknown field room, a badly formed code, an empty title, and a capacity that is not a number.
  • capacity=0 is a whole number, so it passes the syntactic check, but it breaks the course’s rule. That rule needs no stored data, so the request is wrong in itself: the boundary’s pre-check reports it as a 400 field problem, and the client knows which field to fix.
  • Creating CS101 again is well formed, so it reaches the service, which refuses it with course_exists: a 409, not a 400.
  • S1 takes CS101’s only seat and S2 is waitlisted. S2’s second attempt is refused by the domain as already_in_course.
  • student=S2&student=S1 repeats a field and lacks course; both are reported.
  • S7 and PH101 are well formed but do not exist: 404, with a detail saying which.
  • An unknown route is a 404 as well, with route as the detail.

No request reached a bug, so nothing was written to the log.

The boundary, alone, with no service: good requests become commands, every problem is reported, the title limit holds, and the boundary agrees with the domain about capacity:

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

test_requests.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) records a
// failure unless actual == expected, and prints both values when it does.
// They come from the site's small test header, lld_test.hpp.
// problems_of (a helper above) turns a Checked result into one string,
// such as "title:empty capacity:missing", or "" when it holds a command,
// so a whole list of problems can be compared in one line.
// These tests need no service and no stored data: the boundary alone.
// A valid request comes back as a CreateCourse holding the parsed values.
LLD_TEST(a_good_request_becomes_a_command_with_domain_values) {
const auto checked = boundary::check_create_course("code=CS101&title=Software Design&capacity=30");
// A pointer to the command if the variant holds one, else nullptr.
const auto* command = std::get_if<boundary::CreateCourse>(&checked);
LLD_CHECK(command != nullptr);
LLD_CHECK_EQ(command->code.text(), std::string{"CS101"});
LLD_CHECK_EQ(command->title, std::string{"Software Design"});
LLD_CHECK_EQ(command->capacity, 30);
}
// Five bad requests. Each expected string lists every problem, in the
// order the check finds them: unknown and repeated fields first, then
// each field in turn (code, title, capacity). Proves the boundary does not
// stop at the first mistake, and shows "S01x" (letters after the digits),
// a number too big for an int, and "+7" each being refused.
LLD_TEST(every_problem_is_reported_at_once) {
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=cs101&title=&capacity=two&room=B12")),
std::string{"room:unknown_field code:bad_format title:empty "
"capacity:not_a_whole_number"});
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=CS101&code=MA101")),
std::string{"code:repeated title:missing capacity:missing"});
LLD_CHECK_EQ(problems_of(boundary::check_enroll("student=S01x&course=CS101")),
std::string{"student:bad_format"});
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=CS101&title=T&capacity=99999999999")),
std::string{"capacity:out_of_range"});
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=CS101&title=T&capacity=+7")),
std::string{"capacity:not_a_whole_number"});
}
// A title of exactly 60 characters passes (an empty problem string); 61
// is too long. Proves the limit is inclusive and lives in the boundary.
LLD_TEST(the_title_limit_belongs_to_the_api) {
// std::string(count, character): 60 copies of 'x'.
const std::string longest(boundary::max_title_length, 'x');
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=CS101&capacity=5&title=" + longest)),
std::string{});
const std::string too_long = longest + 'x';
LLD_CHECK_EQ(problems_of(boundary::check_create_course("code=CS101&capacity=5&title=" + too_long)),
std::string{"title:too_long"});
}
LLD_TEST(the_boundary_and_the_domain_agree_on_capacity) {
// The rule is written in two places; this test keeps them in step.
// For capacities -1, 0, 1, and 2 it asks both: does the boundary
// report no problems, and does the Course constructor not throw? The
// answers must match each time: no, no, yes, yes.
for (int capacity = -1; capacity <= 2; ++capacity) {
const std::string query = "code=CS101&title=T&capacity=" + std::to_string(capacity);
const bool boundary_accepts = problems_of(boundary::check_create_course(query)).empty();
bool domain_accepts = true;
// Building a Course is the domain's check; the course itself is
// not needed and is destroyed at the end of the try block.
try {
const domain::Course course{*domain::CourseCode::parse("CS101"), "T", capacity};
} catch (const std::invalid_argument&) {
domain_accepts = false;
}
LLD_CHECK(boundary_accepts == domain_accepts);
}
}

The last test is the guard against drift. It tries capacities from −1 to 2, and checks that the boundary accepts exactly those the Course constructor accepts. If someone changes the domain’s minimum to 5, this test fails until the boundary agrees.

The service, with commands built directly: questions about stored data, the domain’s limit, and a command that skipped the boundary:

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

test_service.cpp
// student("S1") and code("CS101") are helpers above that parse known-good
// text into domain ids. Commands are written as brace lists, such as
// {code("CS101"), "Software Design", 1}, which fill a CreateCourse's
// fields in order: code, title, capacity. The service is called directly,
// with no request text and no boundary.
// LLD_CHECK_THROWS(expression, type), also from lld_test.hpp, fails
// unless the expression throws that type of exception.
// One student, one course. Proves the semantic answers come from the
// service: a taken code is refused, and an unknown student or course is
// not_found, with detail saying which.
LLD_TEST(questions_about_stored_data_are_answered_by_the_service) {
app::EnrollmentService service;
service.add_student(student("S1"));
LLD_CHECK(service.create_course({code("CS101"), "Software Design", 1}).outcome ==
api::Outcome::created);
LLD_CHECK_EQ(service.create_course({code("CS101"), "Again", 5}).detail,
std::string{"course_exists"});
LLD_CHECK_EQ(service.enroll({student("S9"), code("CS101")}).detail, std::string{"student"});
LLD_CHECK_EQ(service.enroll({student("S1"), code("PH101")}).detail, std::string{"course"});
}
// S1 joins three courses, the most StudentLoad allows (max_courses is
// 3), and is then refused a fourth. Proves the service passes the
// domain's refusal on as refused with detail at_course_limit.
LLD_TEST(the_domain_refuses_what_its_rules_forbid) {
app::EnrollmentService service;
service.add_student(student("S1"));
// The created replies are not checked here; only enrollment is tested.
for (const char* text : {"CS101", "MA101", "PH101", "EN101"}) {
service.create_course({code(text), "Course", 5});
}
for (const char* text : {"CS101", "MA101", "PH101"}) {
LLD_CHECK(service.enroll({student("S1"), code(text)}).outcome == api::Outcome::ok);
}
const api::Reply fourth = service.enroll({student("S1"), code("EN101")});
LLD_CHECK(fourth.outcome == api::Outcome::refused);
LLD_CHECK_EQ(fourth.detail, std::string{"at_course_limit"});
}
// A CreateCourse with capacity 0, built by hand, never checked by the
// boundary. Proves the Course constructor still refuses it, by throwing
// std::invalid_argument, and that no course was stored.
LLD_TEST(a_command_that_skipped_the_boundary_still_meets_the_invariant) {
app::EnrollmentService service;
service.add_student(student("S1"));
LLD_CHECK_THROWS(service.create_course({code("CS101"), "Software Design", 0}),
std::invalid_argument);
// Nothing was stored.
LLD_CHECK_EQ(service.enroll({student("S1"), code("CS101")}).detail, std::string{"course"});
}

The last test builds a CreateCourse with capacity 0, which the boundary would never produce. The constructor still refuses it, and nothing is stored. That is the domain’s guarantee, tested without the boundary.

The handler: an exception becomes a 500 with no details, each outcome has one status, and text from the client is escaped before it is echoed:

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

test_handler.cpp
// A work function that always throws, with a message no client should
// see. Proves the reply is a bare 500 internal_error and the message goes
// only to the log. std::ostringstream is an output stream that collects
// text in memory, so log.str() shows exactly what was logged.
// `[]() -> api::Reply { throw ...; }` is a lambda that captures nothing;
// `-> api::Reply` names its return type: a body with no return statement
// would otherwise make it void, and answer needs an api::Reply.
LLD_TEST(an_exception_becomes_internal_error_without_its_details) {
std::ostringstream log;
const std::string reply =
app::answer([]() -> api::Reply { throw std::logic_error{"seat index 7 out of range"}; }, log);
LLD_CHECK_EQ(reply, std::string{"500 {\"error\":\"internal_error\"}"});
LLD_CHECK_EQ(log.str(), std::string{"internal error: seat index 7 out of range\n"});
}
// Pins every outcome to its status number, so a change to the contract
// cannot slip through unnoticed.
LLD_TEST(each_outcome_has_one_status_code) {
LLD_CHECK_EQ(api::status_code(api::Outcome::created), 201);
LLD_CHECK_EQ(api::status_code(api::Outcome::ok), 200);
LLD_CHECK_EQ(api::status_code(api::Outcome::invalid_request), 400);
LLD_CHECK_EQ(api::status_code(api::Outcome::not_found), 404);
LLD_CHECK_EQ(api::status_code(api::Outcome::refused), 409);
LLD_CHECK_EQ(api::status_code(api::Outcome::internal_error), 500);
}
// The client sends a field named x"y (with a quote mark in it). It is
// reported as unknown_field, and in the JSON the quote is escaped as \"
// so the reply is still valid JSON. In the C++ string literal, each \"
// stands for one quote character and each \\ for one backslash.
LLD_TEST(text_from_the_client_is_escaped_in_the_reply) {
app::EnrollmentService service;
std::ostringstream log;
LLD_CHECK_EQ(app::handle(service, "POST /enroll student=S1&course=CS101&x\"y=1", log),
std::string{"400 {\"error\":\"invalid_request\",\"problems\":"
"[{\"field\":\"x\\\"y\",\"problem\":\"unknown_field\"}]}"});
}

The escaping test matters because the reply repeats an unknown field’s name, which the client chose. Without escaping, a name containing " would produce broken JSON. The escaping handles quotes, backslashes, and control characters; bytes that are not valid UTF-8 are still copied as they are, which a real service would refuse or replace. Echoing client text is always a place to be careful; Security-sensitive boundaries goes further.

  • Clients you do not control. Other teams, mobile apps, or the public depend on the replies, so the codes must be stable and the problems complete.
  • Several entry points into one domain. A web API, an import job, and an admin tool each have a boundary of their own, and the domain’s invariants protect all of them.
  • Forms. Reporting every problem at once is what lets a form mark every wrong field.

It is more than a small tool needs. A command-line program used by its own authors can parse its arguments, let the domain throw, and print the message. Even there, keep the domain’s invariants: they are what make the program’s data trustworthy, whoever calls it.

  • Validating only in the domain. Clients get one exception at a time, as a 500 or with internal text, and cannot tell a mistake from a bug.
  • Validating only at the boundary. Every other caller, such as an import job or a test, can build a course with no seats. The domain’s invariant is what all callers share.
  • Copying formats into the boundary. A regular expression for course codes in the handler drifts from CourseCode::parse. Ask the value object.
  • Stored-data checks at the boundary. Looking up whether a course exists before the service does reads the data twice, possibly with different answers.
  • Free-text errors. Clients end up matching sentences. Give each failure a stable code.
  • Passing exception messages to clients. They reveal internals and change when the code changes. Log them; reply internal_error.
  • Passing request text on after checking it. A std::string that was once checked looks the same as one that was not. Turn it into a domain value at the boundary.
  • A course code may now have five letters. Only CourseCode::parse changes; the boundary asks it, so it follows.
  • Courses may have at most 400 seats. If the limit is the university’s rule, it goes in the Course constructor, with the boundary’s pre-check and the agreement test updated alongside. If it is only what the website can display, it goes in the boundary, like the title limit.
  • A batch import of 500 courses. The import gets its own boundary, reading a file and producing the same CreateCourse commands. It might collect problems per line and report a summary, but the service and the domain do not change.
  • Clients want messages in their language. Add a message for people next to each stable code, chosen by the client’s language. Client programs keep relying on the codes.

Exercise: Place six checks

The registrar adds a request to book a room for a course’s exam: room=B12&course=CS101&date=2027-01-20&seats=120. Place each check: boundary, value object, domain, or application service. Say what each is reported as.

  1. date is a real calendar date in the form YYYY-MM-DD.
  2. seats is a whole number.
  3. Room B12 exists.
  4. The room has at least as many seats as requested.
  5. A room is never booked twice for the same date.
  6. The request has no more than the four fields.
Show the explained answer
  1. A value object, such as ExamDate::parse, asked by the boundary. The format and the calendar (no 30 February) are the value’s own rules. Reported as a 400 field problem, bad_format.
  2. The boundary. It needs only the text. A 400 field problem, not_a_whole_number.
  3. The application service. Whether B12 exists depends on stored data. A 404 with detail room.
  4. The domain, for example in a Room aggregate’s book, called by the service. It is a rule comparing two values, one of them stored. A 409 refusal, such as room_too_small. The boundary cannot check it: it does not know the room’s size.
  5. The domain, as an invariant of the room’s bookings, so it holds for every caller. The service loads the room and asks it to book; a clash is a 409 refusal, room_taken. With several clients at once, the check and the save must also be one transaction, or two bookings can both pass; Transaction and persistence boundaries covers that.
  6. The boundary, while splitting the fields. A 400 field problem, unknown_field for each extra name, and repeated for a name given twice.
  • Syntactic checks ask whether a request is well formed; semantic checks ask whether it makes sense, given rules and stored data.
  • Place each check at the first place that has what it needs: the boundary for the request alone, value objects for formats, the domain for rules, the service for stored data.
  • The boundary turns text into commands holding domain values, so later code cannot receive a malformed id.
  • The domain enforces its invariants for every caller. A boundary pre-check is for the client’s benefit; a test keeps the two in step.
  • The error contract gives one status per outcome, stable codes, every field problem at once, and no internal details.
  • An exception reaching the top is our fault: reply internal_error, and log the details.