Invariants and failure scenarios
What you will learn on this page
Section titled “What you will learn on this page”- How to derive invariants from requirements, and decide which class (if any) can enforce each one.
- How to list failure scenarios by walking each step and each outside system.
- How to decide, for each failure, how it is detected, how it is handled, and what the user sees.
- How the decisions look in C++: refunds, keeping the unprinted rest of a job, and a boundary contract that says what each failure means.
Why the happy path is not the design
Section titled “Why the happy path is not the design”The use-case lesson’s example assumed that printing always succeeds. Flow 5a said: “The printer jams or goes offline during a job. The pages not printed must not be lost (FR-9). Designed in the invariants and failures lesson.” This is that lesson.
Most of the design work in a real service is in the failures. The happy path of a release is six lines. Deciding what happens when the printer stops after 4 of 10 pages raises questions about quotas, page numbers, expiry, and what the panel says. The way to answer them is to first write down what must always be true, and then check every failure against it.
The naive version
Section titled “The naive version”Here is the use-case example’s release loop, with a printer that can now jam:
Charge the job’s pages. Send the job to the print server. Remove the job.
When the printer jams after 4 of 10 pages, one of two things happens, depending on where the code stops:
- The job is removed anyway. Pages 5 to 10 are lost (breaking FR-9), and Robin has been charged for 10 pages but received 4.
- The job is kept, as it was. Robin releases it again at another printer. Pages 1 to 4 print a second time, and the quota is charged 10 pages again: 20 pages charged, 14 printed.
Neither is what anybody wants. Both are bugs a happy-path test would never find.
From requirements to invariants
Section titled “From requirements to invariants”An invariant is a statement that is true at every moment the system can be observed. To find them, read the requirements for words like always, never, only, must not, and each, and for numbers that must agree.
| ID | Invariant | From | Enforced by |
|---|---|---|---|
| I-1 | Every page of a submitted job is either printed, still held, or deleted by expiry. | FR-1, FR-7, FR-9 | the release logic (no page is dropped) |
| I-2 | No page of a job is printed twice. | G3, REQ-01 | the release logic, with HeldJobs keeping the next page number |
| I-3 | A user’s used pages equal the pages printed for them this month (under A3). | FR-4, G3 | the release logic, by refunding what did not print |
| I-4 | A user’s used pages are never negative and never more than their quota plus extra pages. | FR-4, FR-5 | QuotaAccount alone (it refuses any charge, refund, or grant that would break it) |
| I-5 | A job prints only on its owner’s badge. | FR-8, NFR-3 | the release logic, using only BadgeDirectory for identity |
| I-6 | Every held job has at least one page left, and is deleted 24 hours after it was first submitted. | FR-7, Q10 | HeldJobs (the page rule and the expiry rule), plus a timer that calls expire often enough |
The last column is the important design result. Some invariants belong to
one class: QuotaAccount can keep I-4 true by refusing a charge, refund,
or grant that would break it, exactly as the encapsulation lesson showed. Others
span several objects. I-3 links the quota (in Quotas) to what the printer
did (reported by PrintServer); no single class sees both. A
cross-object invariant has to be
kept by the code that coordinates the objects, here ReleaseStation, and
checked by tests that look at all of them.
Two more things to notice:
- I-6 contains a decision. When a jam leaves pages 5 to 10 held, is the 24-hour limit counted from the original submission, or from the jam? The security officer set the limit (Q10) to limit how long confidential jobs wait, so the original submission is the answer that serves the goal. That is worth confirming, and the example tests it.
- I-3 rests on an assumption. “Pages printed” can only be known if the printer reports it (assumption A2). If A2 is rejected, I-3 has to be weakened, as the assumptions lesson worked through.
Listing failure scenarios
Section titled “Listing failure scenarios”A failure scenario is one specific way something can go wrong, with its effect. To find them, walk two lists.
Each step of the use case. For UC-2: badge read, badge lookup, finding jobs, charging, printing, removing. For each, ask: what if it fails? What if it is slow? What if it gives a wrong answer?
Each outside system on the context diagram. The badge system, the print server, the printers, and the service’s own server. For each, ask: what if it is down? Slow? Sends something twice? Sends something impossible?
For the print-release service:
| ID | Failure | Detected by | Handling | User sees | Protects |
|---|---|---|---|---|---|
| F-1 | The badge system is down or does not answer in time | The lookup times out (NFR-1); BadgeSystemUnavailable |
Release nothing, change nothing (Q17: fail closed) | “Badge system unavailable. Try again later.” | I-5 |
| F-2 | The printer jams part-way through a job | The printer’s report: jammed after n pages | Keep pages n+1 onwards held; refund them; stop this release | “Printer problem: … still held; try another printer.” | I-1, I-2, I-3 |
| F-3 | The printer goes offline, before or during a job | The printer’s report: offline after n pages (maybe 0) | Same as F-2 | Same as F-2 | I-1, I-2, I-3 |
| F-4 | The print server cannot be reached | PrintServerUnavailable from the print call |
Refund the job; it is still held; stop this release | Same as F-2 | I-1, I-3 |
| F-5 | The service itself restarts during a release | On start-up | Needs saved state (NFR-4, A4); not in this example | Jobs still held after the restart | I-1 |
| F-6 | The same printer report arrives twice | A report ID seen before | Ignore the second (idempotency); not possible in this single-threaded example | Nothing | I-3 |
| F-7 | A report that is impossible (e.g. “jammed” after all pages) | HeldJobs::keep_unprinted checks the numbers |
Treated as a bug in the print-server code: throw before the job changes; log it | The release throws; the caller logs it (see below) | I-6 |
| F-8 | The user walks away while their pages print | Not detectable by the service | Accepted risk; the release records show who released them | n/a | (G2) |
Each row is a small design decision. A few of them are worth explaining.
F-1 fails closed. The security officer decided (Q17) that no badge system means no releases. The opposite choice, releasing to anyone when the badge system is down, would keep printing going but would break G2. Choosing between them was not the designer’s decision; finding the question was.
F-2 stops the release. Robin has two jobs; the first jams. Should the
service send the second job to the same printer? The printer has just jammed,
so it is likely to fail again, and Robin is about to walk to another printer.
The example stops: later jobs are not_attempted, not charged, and still
held. That is a design choice the facilities manager should see, and it is
written as a criterion so a test pins it.
F-7 is a bug, not a failure. The print server’s interface promises that a
“jammed” report has fewer pages than the job. A report that breaks that
promise means the code talking to the printers is wrong. There is no correct
way to handle it: the service does not know what printed. So it detects
the problem before changing the job, and lets the exception go up. The code
that calls release (the part that talks to the printers’ network, not shown
in the example) logs it and alerts IT. One more effect to know: if earlier
jobs in the same release had already printed, they have been removed and
charged correctly, but the ReleaseResult that would have reported them is
lost with the exception, so the panel cannot say so. The release records
(when built) are what would show it. The example’s
f7_an_impossible_report_through_the_station_keeps_the_full_charge test
checks this path through ReleaseStation.
The completed report is trusted: the station does not check that
pages_printed equals the job’s pages. That is a choice: the contract says
so, and a check would have no better answer than F-7’s. This is the difference between a failure the requirements
describe (handle it) and a broken
contract (detect it loudly).
F-8 is accepted. Not every failure can be handled. Writing it down still matters: it tells the security officer what the design does not protect, and the release records (the change scenario in REQ-01) are the mitigation.
Choosing how to handle a failure
Section titled “Choosing how to handle a failure”For each failure, the handling is usually one of a few choices:
- Refuse, changing nothing (F-1): when going on would break an invariant.
- Undo what was done (F-4’s refund): when a step was taken and the next one failed.
- Keep the rest for later (F-2, F-3): when part of the work succeeded.
- Retry: when the failure is likely to be brief, and repeating is safe (idempotent). The example does not retry printing: a jammed printer needs a person, and the user can move to another printer.
- Accept and record (F-8): when the system cannot detect or prevent it.
And for each, decide what the user sees. A panel that says “Error” after a jam leaves the user unsure whether their confidential pages are lying in the printer. “Printer problem: 2 job(s) still held; try another printer” tells them what happened and what to do.
The job’s states, with failures
Section titled “The job’s states, with failures”Text description of the diagram
A job starts in the Held state when the print server reports it. A release whose quota check fails leaves it Held and changes nothing. A release whose pages fit charges them and moves the job to Printing. From Printing: if the printer reports completed, the job is removed and becomes Printed, which is final. If the printer reports jammed or offline after n pages, the job goes back to Held, keeping the pages from n+1 onwards, and those pages are refunded. If the print server cannot be reached, the job goes back to Held and all its pages are refunded. A Held job becomes Expired 24 hours after it was first submitted, which is also final.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> Held: job reported
Held --> Held: release, does not fit / nothing changes
Held --> Printing: release, fits / charge its pages
Printing --> Printed: completed / remove the job
Printing --> Held: jammed or offline after n pages / keep pages from n+1, refund them
Printing --> Held: print server unreachable / refund all its pages
Held --> Expired: 24 hours after first submission
Printed --> [*]
Expired --> [*]The diagram shows one job. The rule “stop this release after a printer
problem” (F-2) is about the other jobs in the same release: they make no
transition at all. They stay Held, uncharged, marked not_attempted in the
result.
Compare this with the state-diagram lesson’s loan states. The new parts are
the two arrows from Printing back to Held, each with an action that keeps
I-3 true. Drawing them first makes the code obvious: each arrow is one branch
in print_one. In this single-threaded example, Printing lasts only for the
duration of the print call. In a concurrent service it is a stored state, so
that a second badge read cannot release a job that is printing (the quality
constraints lesson explains why).
The design in C++
Section titled “The design in C++”The example requirements/failures/printer-offline extends the use-case
example with the failure paths. First, the boundary now says what each
failure means:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thrown by a BadgeDirectory when the badge system does not answer in time.// Its own exception type, so the station can catch exactly this failure and// let any other exception pass. `using std::runtime_error::runtime_error;`// borrows the base class's constructors, so it can be built from a message:// BadgeSystemUnavailable("badge lookup timed out").class BadgeSystemUnavailable : public std::runtime_error {public: using std::runtime_error::runtime_error;};
// The badge system, seen from inside. Three possible answers: a user ID, an// empty std::optional for a badge it does not know, or an exception when it// cannot be asked at all. The first two are normal; the third is a failure.class BadgeDirectory {public: virtual ~BadgeDirectory() = default; // Throws BadgeSystemUnavailable if the badge system cannot be reached. [[nodiscard]] virtual std::optional<UserId> owner_of(const BadgeId& badge) const = 0;};
// How a print job ended at the printer.enum class PrintStatus { completed, jammed, offline };
// What the printer reports when a job ends: how it ended, and how many of// the pages sent actually came out (counted from job.first_page).struct PrintReport { PrintStatus status = PrintStatus::completed; int pages_printed = 0;};
// Thrown by a PrintServer when the job never reached the printer. That is a// different failure from a jam: no paper moved, so nothing was printed.class PrintServerUnavailable : public std::runtime_error {public: using std::runtime_error::runtime_error;};
// The print server, seen from inside. A job that reaches the printer// always ends with a PrintReport, even when it fails part-way; a job that// cannot be sent at all ends with an exception instead.class PrintServer {public: virtual ~PrintServer() = default; // Prints pages job.first_page onwards and waits for the printer's report. // Contract: if the status is jammed or offline, pages_printed is less // than job.pages (assumption A2: the printer can count them). Throws // PrintServerUnavailable only if no page was sent to the printer. virtual PrintReport print(const PrinterId& printer, const PrintJob& job) = 0;};The comments on PrintServer::print are a contract: they say what the
station may rely on. “Throws PrintServerUnavailable only if no page was
sent” is what makes the refund in F-4 correct. If the real print server
cannot promise that, the contract is wrong, and the failure table must
change. A contract on a boundary is where an assumption (here, A2) becomes
code.
The job now remembers where it got to:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One held document. New in this version: first_page, so that after a jam// the job can remember where to start again. A 10-page job jammed after 4// pages becomes first_page 5, pages 6: pages 5 to 10 are still to print.struct PrintJob { int id = 0; UserId owner; std::string document; int first_page = 1; // the next page to print; more than 1 after an interruption int pages = 0; // pages still to print Minutes submitted_at{0}; // never changed by a jam, so expiry counts from here};
// Jobs reported by the print server, held until released or expired.// Owns the jobs by value in one vector; callers only ever get copies.// Invariant I-6: every held job has at least one page left to print.// hold refuses pages < 1 and keep_unprinted refuses to leave 0 pages, so// no member function can break I-6.class HeldJobs {public: // 24 hours, stored as minutes (1440); std::chrono does the conversion. static constexpr Minutes hold_limit = std::chrono::hours{24};
// Holds a new job and returns its ID. Throws std::invalid_argument if // pages < 1. int hold(UserId owner, std::string document, int pages, Minutes now);
// The owner's held jobs, oldest first. [[nodiscard]] std::vector<PrintJob> jobs_for(const UserId& owner) const;
// Removes a job; returns false if no job has that ID. bool remove(int job_id);
// FR-9: the first `pages_printed` pages of the job came out; the rest stay // held. Throws std::logic_error, changing nothing, unless the job exists // and 0 <= pages_printed < its pages. void keep_unprinted(int job_id, int pages_printed);
// Deletes every job held for hold_limit or longer, counted from when it // was first submitted; returns how many. int expire(Minutes now);
[[nodiscard]] int count() const { return static_cast<int>(jobs_.size()); }
private: std::vector<PrintJob> jobs_; // in submission order int next_id_ = 1; // only goes up, so an ID is never reused};first_page and pages together say which pages are left. After a jam,
keep_unprinted moves the start forward:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// After a jam or an offline printer: the first `pages_printed` pages of the// job came out, so move the job's start forward past them and keep the rest// held. Throws std::logic_error, changing nothing, for an unknown job or an// impossible page count.void HeldJobs::keep_unprinted(int job_id, int pages_printed) { // std::ranges::find with a third argument, &PrintJob::id (a "pointer to // member"), compares each job's id with job_id, rather than comparing // whole jobs. It returns an iterator: a position in jobs_, which `->` // reads and writes through, or jobs_.end() if there is no match. const auto job = std::ranges::find(jobs_, job_id, &PrintJob::id); if (job == jobs_.end()) throw std::logic_error("no held job with that ID"); // Printing every page is not an interruption, and would leave a job with // no pages (breaking I-6). Checked before anything changes. if (pages_printed < 0 || pages_printed >= job->pages) { throw std::logic_error("impossible page count in a printer report"); } // Both checks passed, so 0 <= pages_printed < pages, and after these two // lines the job has at least one page left. The `const` on `job` only // stops it from being moved to another position; it is not a // const_iterator, so the job it points to can still be changed. // Example: first_page 1, pages 10, 4 printed gives first_page 5, pages 6. job->first_page += pages_printed; job->pages -= pages_printed;}It checks the report before changing anything. If the numbers are
impossible (F-7), it throws std::logic_error and the job is exactly as it
was. That is the strong guarantee for this function: it succeeds, or it
changes nothing. submitted_at is not touched, so the rest of the job still
expires 24 hours after the original submission (I-6).
The quota gains a refund, which keeps I-4 on its own:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Assumption A3 (Q8): a colour page counts the same as a black-and-white page.// job.pages is the pages still to print, so the rest of a jammed job costs// only what is left of it.[[nodiscard]] inline int pages_charged(const PrintJob& job) { return job.pages; }
// One user's pages for the current month.// Invariant I-4: 0 <= used pages <= monthly pages + extra pages.// Every member function that changes a number checks first and either// keeps I-4 or refuses, so remaining() can never be negative.class QuotaAccount {public: // Throws std::invalid_argument if monthly_pages < 0. explicit QuotaAccount(int monthly_pages);
// The allowance plus extra pages, minus what is used. Never negative, // because of I-4. [[nodiscard]] int remaining() const { return monthly_pages_ + extra_pages_ - used_pages_; }
// Charges the pages if they all fit; otherwise changes nothing. Returns // true if charged; a negative count is refused (false). [[nodiscard]] bool try_charge(int pages);
// Gives back pages that were charged but not printed. Throws // std::logic_error, changing nothing, unless 0 <= pages <= used pages. // A larger refund would make used pages negative and break I-4; that // can only come from a bug, so it is an exception, not a false. void refund(int pages);
// Throws std::invalid_argument, changing nothing, if pages < 0. void grant_extra(int pages);
private: int monthly_pages_; int extra_pages_ = 0; int used_pages_ = 0;};
// Every user's account; a new user gets the default quota.class Quotas {public: explicit Quotas(int default_monthly_pages) : default_pages_(default_monthly_pages) {}
// The user's account, created with the default allowance the first // time. A reference, so the caller changes the stored account. // The reference stays valid while this Quotas lives (std::map never // moves its elements when others are added). QuotaAccount& account_for(const UserId& user);
private: int default_pages_; std::map<UserId, QuotaAccount> accounts_;};The release loop now stops sending jobs after a printer problem:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// UC-2 with failures handled. Same shape as the acceptance example: find// the user, get their held jobs oldest first, charge and print each one.// What is new: the badge lookup can fail, and once the printer has a// problem, no later job is charged or sent.ReleaseResult ReleaseStation::release(const BadgeId& badge) { // Declared before the try block so it is still in scope after it. It // starts empty and is filled in only if the lookup answers. std::optional<UserId> user; try { user = badges_.owner_of(badge); // Only this one exception type is caught. Any other exception, from // a bug for example, is not hidden: it passes straight out of release. } catch (const BadgeSystemUnavailable&) { // F-1 (Q17): no badge system, no releases. Nothing has changed yet. return {ReleaseOutcome::badge_system_unavailable, {}}; } // The lookup answered: an empty optional means an unknown badge. if (!user) return {ReleaseOutcome::badge_not_recognised, {}};
// A copy of the user's jobs, oldest first. print_one changes or removes // the stored jobs in held_, but never this copy, so the loop is safe. const std::vector<PrintJob> jobs = held_.jobs_for(*user); if (jobs.empty()) return {ReleaseOutcome::no_jobs_waiting, {}};
QuotaAccount& quota = quotas_.account_for(*user); // the real account ReleaseResult result; // Starts true; turns false after the first job that was charged but did // not print completely (interrupted or not sent), and then stays false // for the rest of this release. An over-quota job does not change it. bool printer_ok = true; for (const PrintJob& job : jobs) { // After a printer problem, later jobs are not charged or sent; they // stay held for another printer. if (!printer_ok) { result.jobs.push_back({job.id, JobOutcome::not_attempted, 0}); continue; } // Charge first, all or nothing. A job over quota is not a printer // problem, so printer_ok stays true and the next job is still tried. if (!quota.try_charge(pages_charged(job))) { result.jobs.push_back({job.id, JobOutcome::over_quota, 0}); continue; } // Charged; print_one sends it and corrects the charge if not every // page came out. Any outcome but printed (interrupted or not_sent) // sets printer_ok to false. const JobResult printed = print_one(job, quota); printer_ok = printed.outcome == JobOutcome::printed; result.jobs.push_back(printed); } return result;}How this code works: ReleaseStation::release, with failures
- Ask the badge system, carefully.
useris declared before thetryblock, so it still exists after it. Ifowner_ofthrowsBadgeSystemUnavailable, thecatchblock returnsbadge_system_unavailable. Only that exception type is caught. - Unknown badge, or nothing held. Two early returns, exactly as in the use-case example.
- The loop, with one flag.
printer_okstartstrue. For each job:- if
printer_okis alreadyfalse, the job is recorded asnot_attempted: it is neither charged nor sent, and stays held for another printer; - otherwise
try_chargetries to charge the whole job. If it does not fit, it isover_quota, and the flag is left alone, because a full quota says nothing about the printer; - otherwise
print_onesends it and returns its result. Any result other thanprintedturns the flagfalse.
- if
A worked example. In the demonstration, Robin has 500 pages and two held jobs, and the printer at 2-East will jam after 4 pages.
| Job | printer_ok before |
What happens | Recorded as | Pages used after |
|---|---|---|---|---|
| 1, report.pdf, 10 pages | true |
charged 10; jams after page 4; pages 5 to 10 kept; 6 refunded | interrupted, 4 pages |
4 |
| 2, notes.txt, 2 pages | false |
skipped: not charged, not sent | not_attempted |
4 |
Both jobs are still held, so the panel says “Printer problem: 2 job(s) still held; try another printer.”, and Robin has 496 pages left.
F-1 is handled first, before anything has changed, so “refuse” needs no undo. The rest of the loop is the use-case version with one extra flag.
The failure decisions are in one function:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Called by release only after the whole job has been charged. Sends the// job, then makes the charge and the held job match what came out, so// that the user pays for exactly the pages printed (I-3). Three endings:// not sent, completed, or interrupted part-way.JobResult ReleaseStation::print_one(const PrintJob& job, QuotaAccount& quota) { // Declared outside the try block so it can be read after it. PrintReport report; try { report = server_.print(printer_, job); } catch (const PrintServerUnavailable&) { // F-4: no page was sent. Undo the charge; the job was never removed. // The refund cannot throw: these pages were charged a moment ago. quota.refund(pages_charged(job)); return {job.id, JobOutcome::not_sent, 0}; } // Every page came out: the charge was right, so only the held job // needs to go. if (report.status == PrintStatus::completed) { held_.remove(job.id); return {job.id, JobOutcome::printed, job.pages}; } // F-2, F-3 (FR-9): jammed or offline part-way. The printed pages stay // charged (I-3); the rest stay held, from the next page (I-2), and are // refunded until they print. keep_unprinted checks the report first, so // an impossible report (F-7) throws before the refund. // The order matters: if keep_unprinted throws, the exception leaves // print_one and release at once, the job is unchanged, and the full // charge stays. Example: 10 pages charged, jam after 4 gives // keep_unprinted(id, 4), then a refund of 10 - 4 = 6, so 4 stay charged. held_.keep_unprinted(job.id, report.pages_printed); quota.refund(job.pages - report.pages_printed); return {job.id, JobOutcome::interrupted, report.pages_printed};}How this code works: print_one
When print_one starts, the whole job has already been charged. Its job is
to make the charge and the held job match what really came out of the
printer. Here are its endings for a 10-page job starting at page 1. The
rows marked with a failure ID match the tests shown later on this page.
| Print server says | Held job afterwards | Refund | Charged in the end | Result |
|---|---|---|---|---|
throws PrintServerUnavailable (F-4) |
unchanged | 10 | 0 | not_sent |
completed, 10 pages |
removed | none | 10 | printed |
jammed, 4 pages (F-2) |
first page 5, 6 pages left | 10 - 4 = 6 | 4 | interrupted |
offline, 0 pages (F-3) |
unchanged: first page 1, 10 pages | 10 - 0 = 10 | 0 | interrupted |
jammed, 10 pages (F-7, impossible) |
unchanged: keep_unprinted throws |
never runs | 10 | std::logic_error thrown |
In every row but the last, the pages charged equal the pages printed
(I-3), and the pages not printed are still held, starting from the next
one (I-2). The last row is the contract being broken: the exception leaves
print_one and release before the refund line, so the job keeps its full
charge, as described below.
Read it against the state diagram: each return is one arrow out of
Printing. Two details:
- Catch only what the contract names.
print_onecatchesPrintServerUnavailable, not every exception. An unexpected exception means something the failure table does not describe; it is not safe to assume “nothing was sent”, so it is not caught here. - The order matters for F-7.
keep_unprintedruns beforerefund. If the report is impossible,keep_unprintedthrows, and the refund never happens. The job keeps its full charge and all its pages. That is not correct either, but it is the safer wrong: the user may be short of pages until the bug is fixed, but no page is lost and none is free. Since there is no correct answer, the service reports the bug loudly instead of hiding it.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A stand-in badge system that the demo can switch off. Setting reachable// to false makes owner_of throw BadgeSystemUnavailable, as a real lookup// that timed out would; otherwise it looks the badge up in a fixed map.class StaffBadges : public BadgeDirectory {public: bool reachable = true; std::optional<UserId> owner_of(const BadgeId& badge) const override { if (!reachable) throw BadgeSystemUnavailable("badge lookup timed out"); const auto found = owners_.find(badge); if (found == owners_.end()) return std::nullopt; return found->second; }
private: std::map<BadgeId, UserId> owners_{{"B-01", "robin"}, {"B-02", "kim"}};};
// Prints to the console, and can be told to fail the next job.// Each failure is one-shot: the setting is cleared as soon as it is used,// so only the next call to print fails and later calls print normally.// (Within one release, the station sends no more jobs after a failure.)class ConsolePrintServer : public PrintServer {public: std::optional<int> jam_after; // pages printed before the next job jams bool offline = false;
PrintReport print(const PrinterId& printer, const PrintJob& job) override { std::cout << " [" << printer << "] " << job.document; // Offline before the first page: report 0 pages printed. if (offline) { offline = false; std::cout << ": printer offline\n"; return {PrintStatus::offline, 0}; } // value_or: the jam count if one is set, otherwise every page. // The last page is first_page + printed - 1: pages 5 to 10 is 6 pages. const int printed = jam_after.value_or(job.pages); std::cout << " pages " << job.first_page << "-" << job.first_page + printed - 1; if (jam_after) { // reset() empties the optional, so the next job will not jam. jam_after.reset(); std::cout << ", then jammed\n"; return {PrintStatus::jammed, printed}; } std::cout << '\n'; return {PrintStatus::completed, printed}; }};
// Prints the badge and the panel text for one release.void show(const BadgeId& badge, const ReleaseResult& result) { std::cout << badge << ": " << panel_text(result) << '\n';}B-01: Badge system unavailable. Try again later. [2-East] report.pdf pages 1-4, then jammedB-01: Printer problem: 2 job(s) still held; try another printer.robin has 496 pages left [3-West] report.pdf pages 5-10 [3-West] notes.txt pages 1-2B-01: 2 job(s) printed.robin has 488 pages left [3-West] memo.docx: printer offlineB-02: Printer problem: 1 job(s) still held; try another printer.kim has 500 pages left [2-East] memo.docx pages 1-3B-02: 1 job(s) printed.held jobs: 0Reading the output against the failure table:
- The badge system is down: nothing happens (F-1).
- Robin’s report jams after 4 pages at 2-East. Robin is charged 4 pages (496 left), and both jobs stay held: the rest of the report, and the notes, which were not attempted (F-2).
- At 3-West, the report prints from page 5, then the notes. Robin has been charged 12 pages for 12 pages printed (I-2, I-3).
- 3-West goes offline before Kim’s memo starts: nothing is charged, and the memo stays held (F-3). At 2-East it prints.
Tests named after failures
Section titled “Tests named after failures”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, LLD_CHECK_EQ(actual, expected) records one if// the two differ (and prints both), and LLD_CHECK_THROWS(expression, type)// fails unless the expression throws that type. A failed check does not// stop the test. All four come from the site's test header, lld_test.hpp.
// A fake badge system: B-01 is robin's badge, and setting reachable to// false makes every lookup throw, like a badge system that timed out.class FakeBadges : public BadgeDirectory {public: std::map<BadgeId, UserId> owners{{"B-01", "robin"}}; bool reachable = true; std::optional<UserId> owner_of(const BadgeId& badge) const override { if (!reachable) throw BadgeSystemUnavailable("timed out"); const auto found = owners.find(badge); if (found == owners.end()) return std::nullopt; return found->second; }};
// Follows a script of reports, one per job; with no script left, every job// completes. Records each page that comes out, as (job ID, page number).// A test sets `script` to the reports it wants, for example// {{PrintStatus::jammed, 4}} for "the next job jams after 4 pages".// std::deque is used because reports are taken off the front.class ScriptedPrintServer : public PrintServer {public: std::deque<PrintReport> script; bool reachable = true; // false: every print throws PrintServerUnavailable std::vector<std::pair<int, int>> pages_out;
// The PrinterId parameter has no name because this fake does not use it. PrintReport print(const PrinterId&, const PrintJob& job) override { if (!reachable) throw PrintServerUnavailable("no connection"); // By default the job completes; a scripted report replaces that, // and is used up (pop_front) so the next job gets the next report. PrintReport report{PrintStatus::completed, job.pages}; if (!script.empty()) { report = script.front(); script.pop_front(); } // Record each page that came out, numbered from the job's first page. for (int i = 0; i < report.pages_printed; ++i) { pages_out.emplace_back(job.id, job.first_page + i); } return report; }
// I-2: no page of any job came out twice. // A std::set keeps only one copy of each (job, page) pair. If building // a set from the recorded pages loses nothing, no pair was repeated. [[nodiscard]] bool no_page_twice() const { const std::set<std::pair<int, int>> unique(pages_out.begin(), pages_out.end()); return unique.size() == pages_out.size(); }};
struct Office { FakeBadges badges; ScriptedPrintServer server; HeldJobs held; Quotas quotas{500}; ReleaseStation station{"2-East", badges, held, quotas, server};
Office() = default; // `station` refers to the other members; a copy would refer to the // original's members. Office(const Office&) = delete; Office& operator=(const Office&) = delete;
// Pages charged to the user so far: the 500 allowance minus what is // left. (No test here grants extra pages, so this is exact.) [[nodiscard]] int used(const UserId& user) { return 500 - quotas.account_for(user).remaining(); }};
const Minutes ten{std::chrono::hours{10}};
} // namespace
// F-1 The badge system does not answer: nothing prints, nothing is charged,// and the panel says to try again later.// Switches the badge system off, then checks that release reports it,// sends no page, charges nothing, and leaves the job held.LLD_TEST(f1_badge_system_down_prints_nothing_and_changes_nothing) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.badges.reachable = false;
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.outcome == ReleaseOutcome::badge_system_unavailable); LLD_CHECK(office.server.pages_out.empty()); LLD_CHECK_EQ(office.used("robin"), 0); LLD_CHECK_EQ(office.held.count(), 1);}
// F-2 The printer jams after 4 of 10 pages: 4 pages are charged, and pages// 5 to 10 stay held.// One 10-page job, scripted to jam after 4. The result says interrupted// with 4 pages, 4 are charged (10 charged, 6 refunded), and the held job// now starts at page 5 with 6 pages left. at(0) is like [0] but throws if// the vector is empty, so a missing result fails loudly. std::size_t{1}// matches the unsigned type that size() returns.LLD_TEST(f2_a_jam_keeps_the_unprinted_pages_and_charges_only_printed_ones) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.script = {{PrintStatus::jammed, 4}};
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.jobs.at(0).outcome == JobOutcome::interrupted); LLD_CHECK_EQ(result.jobs.at(0).pages_printed, 4); LLD_CHECK_EQ(office.used("robin"), 4); const std::vector<PrintJob> left = office.held.jobs_for("robin"); LLD_CHECK_EQ(left.size(), std::size_t{1}); LLD_CHECK_EQ(left.at(0).first_page, 5); LLD_CHECK_EQ(left.at(0).pages, 6);}
// F-2 After a jam, releasing again prints the rest, and no page twice.// The first release jams after 4 pages; `(void)` discards its result,// like static_cast<void>. The script is now empty, so the second release// completes pages 5 to 10: 10 pages out in total, none twice, 10 charged,// and nothing left held.LLD_TEST(f2_after_a_jam_the_rest_prints_without_repeating_a_page) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.script = {{PrintStatus::jammed, 4}}; (void)office.station.release("B-01");
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.jobs.at(0).outcome == JobOutcome::printed); LLD_CHECK_EQ(office.server.pages_out.size(), std::size_t{10}); LLD_CHECK(office.server.no_page_twice()); LLD_CHECK_EQ(office.used("robin"), 10); // I-3: charged = printed LLD_CHECK_EQ(office.held.count(), 0);}
// F-2 Jobs after the one that jammed are not sent and not charged.// Two jobs; the first jams after 4 pages. The second is marked// not_attempted and never charged, so only 4 pages are used, and both jobs// (the rest of the first, and all of the second) are still held.LLD_TEST(f2_jobs_after_a_jam_are_not_attempted_or_charged) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.held.hold("robin", "notes.txt", 2, ten); office.server.script = {{PrintStatus::jammed, 4}};
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.jobs.at(1).outcome == JobOutcome::not_attempted); LLD_CHECK_EQ(office.used("robin"), 4); LLD_CHECK_EQ(office.held.count(), 2); LLD_CHECK_EQ(panel_text(result), std::string("Printer problem: 2 job(s) still held; try another printer."));}
// F-3 The printer is offline before the first page: nothing is charged, and// the whole job stays held.// Offline with 0 pages printed: keep_unprinted(id, 0) changes nothing,// and the whole charge of 10 is refunded. The job still starts at page 1.LLD_TEST(f3_offline_before_the_first_page_refunds_everything) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.script = {{PrintStatus::offline, 0}};
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.jobs.at(0).outcome == JobOutcome::interrupted); LLD_CHECK_EQ(office.used("robin"), 0); const std::vector<PrintJob> left = office.held.jobs_for("robin"); LLD_CHECK_EQ(left.at(0).first_page, 1);}
// F-4 The print server cannot be reached: nothing is charged, and the job// stays held.// The print server throws PrintServerUnavailable. print_one catches it,// refunds the charge, and does not touch the held job.LLD_TEST(f4_print_server_unreachable_refunds_and_keeps_the_job) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.reachable = false;
const ReleaseResult result = office.station.release("B-01");
LLD_CHECK(result.jobs.at(0).outcome == JobOutcome::not_sent); LLD_CHECK_EQ(office.used("robin"), 0); LLD_CHECK_EQ(office.held.count(), 1);}
// I-6 What is left of an interrupted job is still deleted 24 hours after the// job was first submitted, not 24 hours after the jam.// The job was submitted at 10:00. keep_unprinted never changes// submitted_at, so exactly 24 hours after 10:00 the rest of it expires.LLD_TEST(i6_the_rest_of_a_job_expires_from_its_first_submission) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.script = {{PrintStatus::jammed, 4}}; (void)office.station.release("B-01"); // the jam is at 10:00
LLD_CHECK_EQ(office.held.expire(ten + HeldJobs::hold_limit), 1);}
// F-7 A report that claims all pages printed but says "jammed" breaks the// print server's contract. It is rejected before the job changes.// Uses HeldJobs on its own, with no station. 10 of 10 pages (that would// leave no pages) and -1 pages are both refused, and the job still has all// 10 pages afterwards, so the failed calls changed nothing.LLD_TEST(f7_an_impossible_report_is_rejected_before_the_job_changes) { HeldJobs held; const int id = held.hold("robin", "report.pdf", 10, ten);
LLD_CHECK_THROWS(held.keep_unprinted(id, 10), std::logic_error); LLD_CHECK_THROWS(held.keep_unprinted(id, -1), std::logic_error); const std::vector<PrintJob> left = held.jobs_for("robin"); LLD_CHECK_EQ(left.at(0).pages, 10);}
// F-7 through the station: the impossible report throws out of release, the// job keeps all its pages, and its full charge stays (the refund never runs).// The script says "jammed, 10 pages printed" for a 10-page job. The// logic_error from keep_unprinted escapes from release, which// LLD_CHECK_THROWS expects. The charge of 10 stays (the refund line never// ran), and the job is unchanged.LLD_TEST(f7_an_impossible_report_through_the_station_keeps_the_full_charge) { Office office; office.held.hold("robin", "report.pdf", 10, ten); office.server.script = {{PrintStatus::jammed, 10}};
LLD_CHECK_THROWS(office.station.release("B-01"), std::logic_error);
LLD_CHECK_EQ(office.used("robin"), 10); const std::vector<PrintJob> left = office.held.jobs_for("robin"); LLD_CHECK_EQ(left.at(0).first_page, 1); LLD_CHECK_EQ(left.at(0).pages, 10);}
// I-4 A refund can never make the used pages negative.// 3 pages charged, then a refund of 4 is refused with std::logic_error,// and 500 - 3 = 497 pages are still left: the failed refund changed nothing.LLD_TEST(i4_a_refund_larger_than_the_pages_used_is_rejected) { QuotaAccount account(500); LLD_CHECK(account.try_charge(3)); LLD_CHECK_THROWS(account.refund(4), std::logic_error); LLD_CHECK_EQ(account.remaining(), 497);}
// I-4 A negative grant, which could push the used pages over the limit, is// rejected.// All 500 pages used; a grant of -1 would leave -1 pages. It is refused,// and 0 pages are still left.LLD_TEST(i4_a_negative_grant_is_rejected) { QuotaAccount account(500); LLD_CHECK(account.try_charge(500)); LLD_CHECK_THROWS(account.grant_extra(-1), std::invalid_argument); LLD_CHECK_EQ(account.remaining(), 0);}The fake print server follows a script of reports, so each test can make
the printer fail at exactly the page it wants. It also records every page
that comes out, as a job ID and page number. That makes I-2 checkable
directly: no_page_twice turns the list into a set and compares sizes. Tests
of cross-object invariants need fakes that record, because the invariant
is about what happened outside the class under test.
The test names start with the failure or invariant they check. The traceability lesson connects them back to FR-9, NFR-3, and the rest.
What this example does not handle
Section titled “What this example does not handle”Being clear about the gaps is part of the design:
- F-5, restarts. Nothing is saved. NFR-4 (assumption A4) needs storage behind an interface, and a decision about jobs that were Printing at the moment of the restart: the service cannot know how many pages came out. That is a new question for IT and the printer supplier.
- F-6, duplicate reports. The print call returns its report directly, so a duplicate cannot arrive. A real printer sends reports over the network, and the service would need report IDs.
- Time limits. The example’s
BadgeDirectorythrows when told to; a real one would throw after a timeout. The interface does not change. - Concurrency. One thread, no locks.
When not to
Section titled “When not to”- Do not handle failures that cannot happen. If the print server is a library in the same process, “unreachable” is not a failure scenario. Each handler is code to test and maintain.
- Do not add retries everywhere. A retry is only safe when repeating the action is harmless. Retrying a print after a jam would print pages twice.
- Do not catch everything.
catch (...)that turns every exception into “printer problem” hides bugs like F-7 behind a message that sounds normal. - Do not make every invariant a runtime check. I-2 is guaranteed by the design (the next page number only moves forward) and checked by tests; a check on every page in production would add cost and no safety.
Trade-offs
Section titled “Trade-offs”A full failure table takes time, and some rows (F-5, F-6) lead to real work: storage, report IDs. Leaving them out keeps the first version small but leaves a known gap, which the table makes visible. Stopping a release after a printer problem is simple and safe but makes the user walk to another printer even if only one job failed. Keeping the full charge on an impossible report protects the quota but can leave one user short. Each choice is recorded with its reason, so that it can be revisited when a stakeholder disagrees.
Common mistakes
Section titled “Common mistakes”- Designing only the happy path, and discovering failures in testing or in use.
- Invariants that no code owns. If nobody can say which class or function keeps an invariant true, nothing does.
- Undoing in the wrong order, so that a second failure during the undo leaves the state worse than before.
- Treating every exception the same, so that bugs look like expected failures.
- Messages that do not tell the user what to do.
- Not writing down what is not handled.
When a requirement changes
Section titled “When a requirement changes”The facilities manager decides: “If a printer jams, the user should not be charged for that job at all. It was our printer’s fault.”
- Invariants: I-3 changes from “used pages equal pages printed” to “used pages equal pages printed, minus pages printed by jobs that jammed”. That is harder to state, which is a hint that the rule should be confirmed with finance (G3 is about cost).
- Failure table: F-2’s handling becomes “refund all the pages of this job, including the ones that printed”. When the rest prints later, is it charged? The new rule should say.
- Code: in
print_one, the jam branch refundsjob.pagesinstead ofjob.pages - report.pages_printed. One line, because the decision lives in one place. Since offline shares that branch, the same rule would apply to a printer going offline; facilities should confirm that too. - Tests:
f2_a_jam_keeps_the_unprinted_pages_and_charges_only_printed_ones,f2_after_a_jam_the_rest_prints_without_repeating_a_page, andf2_jobs_after_a_jam_are_not_attempted_or_chargedall check the used pages, so all three change; the first two need new names, since they now check a different rule. The example’s expected output changes too: Robin has 500 pages left after the jam, and 492 after the rest prints.
Exercise: Failure scenarios for a parcel locker
An office has a parcel locker. A courier puts a parcel in a free locker door and enters the recipient’s staff ID. The recipient gets an email with a six-digit code. At the locker, they type the code, and their door opens. Parcels not collected in 5 days are returned to the courier.
- Write three or four invariants, and say which object could enforce each.
- List at least six failure scenarios, by walking the steps and the outside systems (the email system, the door hardware, the courier).
- For each, say how it is detected, how it is handled, and what the user sees. Mark any decision that belongs to a stakeholder.
Show the explained answer
Invariants (one reasonable set):
- L-1 Each door holds at most one parcel. Enforced by a
Lockerobject that refuses to assign a parcel to an occupied door. - L-2 Each parcel is in exactly one place: in a door, collected, or returned. Kept by the code that coordinates deposits and collections.
- L-3 A door opens for collection only with the code of the parcel inside
it. Enforced by the
Locker(it compares the code with its door’s parcel). - L-4 A code works at most once. Enforced by the parcel record: a collected parcel has no valid code.
Failure scenarios:
| Failure | Detected by | Handling | User sees |
|---|---|---|---|
| The email system is down when the parcel arrives | The send fails or times out | Keep the parcel; retry the email later (an email sent twice is harmless) | The email arrives late |
| The recipient’s staff ID is wrong | The ID is not in the staff directory | Refuse the deposit; the courier keeps the parcel | Courier: “Unknown staff ID” |
| The door does not open when the code is right | The door’s sensor does not report “open” | Keep the parcel and its code valid (do not mark collected); alert facilities | “Door problem; facilities has been told” |
| The door opens but the recipient takes nothing | Cannot be detected without a sensor in the door | Accepted risk, or add a sensor (a stakeholder decision about cost) | n/a |
| Someone tries many codes | Repeated wrong codes at one locker | Lock the keypad for a while after five wrong codes (a security decision) | “Too many attempts; try again in 10 minutes” |
| The door is left open after collection | The sensor reports “open” for too long | Alarm; mark the door as not usable until checked | Alarm sound |
| The power fails during collection | On start-up, a door is recorded “opening” | Do not mark collected; facilities checks the door (a decision for facilities) | n/a |
| The 5-day return happens while the parcel is being collected | Collection and return at the same moment | Collection wins if the code was accepted first; do it under one lock | Normal collection |
What to check in your answer:
- Did you find the “door does not open” case, and keep the code valid? Marking the parcel collected when the door did not open breaks L-2: the system says it was collected but it is still inside.
- Did you separate detection from handling? “The door is broken” is not a detection; “the sensor does not report open” is.
- Did you mark the stakeholder decisions? How many wrong codes, whether a sensor is worth its cost, and what happens after a power failure are not the designer’s to choose.
- Did you note what cannot be detected? An empty door after collection is only detectable with extra hardware.
Summary
Section titled “Summary”- Derive invariants from the requirements’ always, never, and only, and from numbers that must agree. For each, name the class or function that keeps it true.
- Invariants inside one class are enforced by that class. Invariants across objects are kept by the code that coordinates them and checked by tests with recording fakes.
- List failure scenarios by walking each step and each outside system, asking what happens if it fails, is slow, repeats, or answers impossibly.
- For each failure, decide detection, handling (refuse, undo, keep for later, retry, accept), and what the user sees; mark the decisions that belong to stakeholders.
- Put the failure decisions in one place, matching the state diagram’s arrows; catch only the exceptions the boundary contract names; detect contract violations loudly.
- Write down what is not handled.