Skip to content

Quality constraints: scale, consistency, concurrency, latency, security, reliability

Difficulty: Intermediate

Key concepts

  • order-of-magnitude estimate
  • scale
  • consistency
  • concurrency
  • latency
  • security
  • reliability
  • idempotency
  • premature distribution
  • How to make an order-of-magnitude estimate of load, memory, and storage from a few numbers.
  • How each of six qualities (scale, consistency, concurrency, latency, security, reliability) changes the local design: which classes exist, what they lock, what they check, and what they save.
  • How to tell when a quality really needs more than one process, and when it does not.

Qualities change the design, not just the test plan

Section titled “Qualities change the design, not just the test plan”

The requirements lesson wrote the print-release service’s non-functional requirements, NFR-1 to NFR-5. It is tempting to treat them as things to check at the end. They are not. Each one decides something about the code: whether a function may wait, what must happen under a lock, which inputs are trusted, and what is written to disk.

This lesson goes through six qualities in turn. For each: what to ask, how to estimate, and what changes in the C++ design. The running example is the same service, and its answers stay small on purpose. Most applications are small, and the most common design mistake with quality requirements is to design for a scale the system will never see.

“It must scale, be fast, be secure, and never lose data. So: a cluster of services behind a load balancer, a message queue between them, a replicated database, and a cache.”

Every word in that list is real technology, and none of it was derived from a number. Run the numbers for the print-release service (below), and the whole service fits in one small process on IT’s existing server (C-3). The cluster would add network failures, deployment work, and consistency problems that a single process does not have. This is premature distribution: paying for the problems of a distributed system before the requirements ask for one.

An order-of-magnitude estimate asks: is this number closer to 10, 1,000, or 1,000,000? That is usually enough to choose a design. Start from the numbers the requirements give, write down every step, and label assumptions.

For the print-release service, from Q12 (an assumption), Q1, and NFR-2. The last column says which rows grow if Q12’s estimate grows:

Quantity Working Result Grows with Q12?
Jobs per day Q12 estimate about 1,000 yes
Peak rate assume 60% of jobs arrive in the two peak hours: 600 jobs ÷ 120 minutes about 5 jobs a minute yes
Peak rate required NFR-2: 500 new jobs in one hour ÷ 60 minutes (a margin over the line above) about 8 jobs a minute no, it is a requirement
Releases per day at most one per job, usually fewer (several jobs per release) under 1,000 yes
Held jobs at once NFR-2, with margin 2,000 no, it is a requirement
Memory for held jobs 2,000 jobs × a few hundred bytes each (IDs, names, numbers); the pages stay on the print server (C-1) under 1 MB with held jobs
Quota accounts about 400 staff (Q1), a few numbers each a few kilobytes no (staff count)
Work per release, in memory scan up to 2,000 jobs for one owner a few thousand comparisons with held jobs

What the estimate tells you:

  • The data fits in memory many times over. No cache, no sharding, no database tuning.
  • The busiest minute has a handful of events. One process handles that without effort.
  • The in-memory work is tiny next to the calls outside. Scanning a few thousand jobs takes far less than a millisecond on a current computer; a network call to the badge system takes much longer. NFR-1 is measured up to the hand-over to the print server, so its 10 seconds depends on the badge lookup and the hand-over, not on the container choice.

Write the estimate down, with its assumptions. If Q12 turns out to be 10,000 jobs a day, the rows marked “yes” move by ten times, NFR-2 has to be restated (2,000 held jobs would no longer be a margin), and the conclusion is still the same. If it were 10,000,000, the conclusion would change, and you would know which line changed it.

Consistency asks: which pieces of data must always agree with each other, and how soon?

In the print-release service, the quota and the printing must agree: a user’s used pages must equal the pages printed for them (the invariants lesson calls this I-3). If the service charged the quota in one step and printed in another, and something failed between the two, they would disagree.

How this changes the local design:

  • Keep facts that must agree in one process, changed in one place. Here, ReleaseStation changes both the held jobs and the quota in a single function, in a fixed order, with an undo for each failure.
  • Order the steps so a failure leaves a known state. Charge, then print, then remove, with a refund on failure. Exception safety and failure atomicity treats this in depth.
  • Decide which facts may lag. A monthly page-count report for facilities can be a few minutes out of date; nobody is harmed. A quota balance used to refuse a job cannot.

If the quota were kept in one service and the held jobs in another, keeping them in agreement would need a protocol across the network. Not needing that is one of the strongest reasons to keep a small system in one process.

Concurrency: what happens at the same time

Section titled “Concurrency: what happens at the same time”

Concurrency asks: which events can happen at once, and what state do they share?

The print-release service has three sources of events:

  1. Badge reads from 12 printers (Q13). Two people can badge in at the same moment.
  2. New jobs from the print server, at any time.
  3. Expiry, which runs every so often on a timer.

All three read or change the same held jobs. If they run on different threads with no protection, that is a data race, which is undefined behaviour in C++. The design must choose how to prevent it. Two common choices:

  • One lock for the service’s state. A std::mutex guards the held jobs and the quotas. At about five events a minute, nobody waits on the lock.
  • One thread owns the state. Events go into a queue, and one worker thread applies them one at a time. The domain classes need no locks at all.

Both work at this scale. The detail that matters more is what happens while the lock is held. A release calls the badge system (up to seconds) and the printer (seconds to minutes). If the lock is held during those calls, every other printer waits: a user at 3-West cannot release while a 200-page job prints at 2-East. So the local design changes:

  • Claim under the lock, call outside it, finish under the lock. The release marks the user’s jobs as printing while holding the lock, releases the lock, talks to the printer, and takes the lock again to record the result.
  • A new state appears. “Printing” becomes a real state of a job, so that a second badge read (or a second user) cannot release the same job while it is printing, and so that expiry does not delete it half-way. The invariants lesson’s state diagram includes it.

This is how a quality requirement changes a class: HeldJobs gains a job state and a “claim” operation that a single-threaded design did not need.

Latency is the time between a request and its result. NFR-1 says 10 seconds for 95% of releases, never more than 30.

How this changes the local design:

  • Every call outside the process needs a time limit. If the badge system hangs, a release with no time limit hangs forever, and NFR-1 fails. The badge lookup gets a timeout of a few seconds, and a timeout is treated as “badge system unavailable” (Q17). The BadgeDirectory interface in the failures example says so: it throws BadgeSystemUnavailable.
  • Know where the time goes. From the estimate, the in-process work is negligible. The budget is spent on the badge system and the hand-over to the print server. Measure those two before optimising anything else.
  • Measure, do not guess. Log the time of each badge read and each hand-over. NFR-1 is checked by these measurements, not by a unit test.
  • Do not optimise code that is not on the slow path. Replacing the std::vector of held jobs with a hash map indexed by owner saves microseconds in a 10-second budget.

Security: who may do what, and what to trust

Section titled “Security: who may do what, and what to trust”

Security asks: what must never happen, and who might try to make it happen? NFR-3 says a held job can be released only by its owner’s badge at a printer.

How this changes the local design:

  • Know which inputs come from outside the trust boundary. The badge ID and printer ID arrive over the network from a printer. Treat them as untrusted: check that the printer ID is one of the 12 known printers, and that the badge ID is well formed, before using either.
  • Decide identity in one place. Only BadgeDirectory turns a badge into a user. No other code accepts a user name from outside. Then FR-8 (only the owner’s jobs) depends on one lookup, not on every caller being careful.
  • Do not keep what you do not need. The service stores job metadata, not the documents (C-1). Confidential pages never pass through it, which is one less thing to protect.
  • Fail closed. When the badge system is down, nobody can release (Q17). The alternative, “let anyone release when the badge system is down”, fails open, and breaks G2.
  • Record security-relevant events. Who released which job at which printer is what the security officer asked for in the release-records change (REQ-01).

The advanced section’s lesson on security-sensitive boundaries goes further: validating input, and keeping secrets out of logs.

Reliability asks: what can fail, what must survive it, and what should the user see? FR-9 (a jam must not lose pages) and NFR-4 (jobs survive a restart) are reliability requirements.

How this changes the local design:

  • Each outside call can fail, and each failure needs a decision. The invariants and failures lesson lists them and decides each one: retry, refund, keep, or refuse.
  • What must survive a restart is saved before it is acknowledged. For NFR-4, a new job is written to storage before the service tells the print server it is held. A quota charge is saved before the job is sent. The storage sits behind an interface, as the requirements lesson suggested, so the release logic does not change.
  • Messages may arrive twice. A printer that loses its network connection may send the same “jammed after 4 pages” report again when it reconnects. If the service refunds the remaining pages each time it receives the report, the user gets free pages. Handling the same report twice must have the same effect as handling it once. That property is called idempotency, and it is usually achieved by giving each report an ID and ignoring IDs already seen. The advanced section has a lesson on it.

The table collects the decisions. Each row is a quality, the requirement that asks for it, and what changes in the classes.

Quality Requirement What changes in the local design What it does not need
Scale NFR-2, Q12 A plain std::vector of held jobs; everything in one process A cache, sharding, a database cluster
Consistency I-3, FR-4, FR-9 Quota and held jobs changed by one function, in a fixed order, with an undo on each failure A distributed transaction
Concurrency Q13 (12 printers) One lock (or one owning thread); a “printing” state and a claim step so slow calls happen outside the lock A lock per job; lock-free structures
Latency NFR-1 A timeout on every outside call; time measured at the badge read and the hand-over Faster containers; a cache of badge lookups
Security NFR-3, G2, Q17 Printer and badge IDs validated at the boundary; identity decided only by BadgeDirectory; fail closed; release records Encrypting data the service never stores
Reliability FR-9, NFR-4 A decision per failure; storage behind an interface, written before acknowledging; duplicate reports ignored by ID Replicas of the service on several machines

The last column matters as much as the third. It records what was considered and judged unnecessary, with the number that justified it. When a number changes, that column says what to reconsider.

When the qualities pull against each other

Section titled “When the qualities pull against each other”
  • Durability against security. NFR-4 wants held jobs on disk; the security officer may not want document names stored at all. That is assumption A4’s conflict, resolved in the prioritization lesson.
  • Latency against reliability. Retrying a slow badge lookup improves the chance of success but uses up the 10-second budget. A single retry within the budget, then “badge system unavailable”, is a reasonable middle.
  • Simplicity against concurrency. One lock for everything is easy to get right, but at some larger number of printers, or with longer work under the lock, people would start to wait for it. At 12 printers and a few events a minute, the simple choice is the right one; if the numbers grow, measure how long releases wait for the lock before changing the design.
  • When no requirement asks for it and no number suggests it. “What if we have a million users?” is a question for the stakeholders, not a reason to add a cache.
  • When the cost of failure is low. A monthly report that is a minute out of date does not need the same consistency as a quota balance.
  • When an outside system already provides it. The print server already queues and spools pages. The service does not need its own print queue.
  • Designing for “scale” without a number. Estimate first; the estimate takes five minutes.
  • Holding a lock while calling a slow outside system, which turns 12 printers into one.
  • No time limit on outside calls, which makes every latency requirement depend on the slowest system.
  • Failing open when an identity or permission check cannot be made.
  • Assuming a message arrives exactly once. Reports, retries, and reconnections deliver some messages twice.
  • Treating qualities as a test-phase concern, so they are discovered when the design is finished.

New request: “The service should also run the print-release for our second building, with 3,000 staff and 60 printers.” (This would undo exclusion X7.)

Redo the estimate: jobs grow about 8.5 times (3,400 staff instead of 400), to about 8,500 a day; held jobs to about 17,000 if they grow the same way. Memory is still a few megabytes. The peak is about 40 jobs a minute. One process still handles it. NFR-2’s numbers (2,000 held, 500 an hour) have to be restated, and the storage for NFR-4 grows in proportion, which is still small.

What does change:

  • Concurrency: 72 printers, so more badge reads at once. One lock is still fine, because slow calls happen outside it. Without the claim step, this change would expose the problem.
  • Reliability: two buildings depend on one server. If the server is down, both buildings stop printing. Facilities should say whether that is acceptable, or whether each building needs its own copy of the service. That is an availability question, and it is the first one here that might really need a second machine.
  • Scale of the scan: finding one user’s jobs among 17,000 by scanning is still quick, but an index by owner (std::map<UserId, …> or std::unordered_map) is now a cheap, reasonable change, kept inside HeldJobs.

Exercise: Which qualities matter?

For each scenario, estimate the scale where you can, say which two or three qualities matter most, and name one change each makes to the local design. Also say what the scenario does not need.

  1. Meeting-room booking for one office: 20 rooms, 300 staff, bookings made from a web page.
  2. Concert ticket sales: 50,000 tickets for one show go on sale at 10:00; about 200,000 people try to buy in the first minutes. Each seat may be sold only once.
  3. A medicine cabinet in a hospital ward: a nurse scans their badge and a patient’s wristband, and one drawer opens. It must work when the hospital’s network is down.
Show the explained answer

1. Meeting-room booking.

  • Scale: tiny. 20 rooms × perhaps 10 bookings a day is 200 bookings a day. Everything fits in memory; one process is plenty.
  • Consistency and concurrency: two people may book the same room for the same time at the same moment. The check “is the room free?” and the booking must happen together, under one lock (or in one database transaction).
  • Security, lightly: only the person who booked (or an administrator) can cancel. Identity comes from the office login, decided in one place.
  • Does not need: caching, several servers, or a queue. The usual mistake is to add them.

2. Concert ticket sales.

  • Scale: 200,000 people in a few minutes is thousands of requests a second at the start. This is the first scenario where one process may not be enough, and where availability matters (a failure at 10:00 is a disaster). Write the estimate down and check it with the stakeholders.
  • Consistency: a seat is sold at most once. This is the invariant that shapes everything. Seats are often held for a few minutes while the buyer pays, and the hold expires: a state machine with a timeout, much like a held print job.
  • Concurrency: many buyers want the same seats at once. The seat check and the hold must be one atomic step.
  • Idempotency: a buyer who presses “Pay” twice, or whose connection drops, must not pay twice. Each payment request carries an ID.
  • Does not need: perfect fairness of who gets in first, unless the stakeholders ask for it. That would be an expensive requirement; ask before designing for it.

3. Hospital medicine cabinet.

  • Reliability: it must work when the network is down, so it must decide locally. That means a local copy of which nurse may open which drawer for which patient, and a way to update it when the network returns.
  • Security: a drawer opens only for the right nurse and the right patient. With the network down, it cannot check the latest permissions, so the stakeholders must decide: fail closed (nobody gets medicine) or fail open with records (open, and record every opening for review). In a hospital, “fail closed” may harm patients. This is a decision for clinical staff, not for the designer.
  • Consistency: records of openings made while offline are sent when the network returns, perhaps late. They must not be lost, and sending them twice must not count them twice (idempotency again).
  • Scale: small per cabinet. Does not need anything fast; does need careful storage.

What to compare with your answer: did you estimate before choosing, did you find the invariant that shapes the design (one seat, one sale), and did you notice where a decision belongs to a stakeholder, not to you?

  • Estimate scale to an order of magnitude, from the requirements’ numbers, with assumptions labelled. Most systems are small; the estimate shows it.
  • Consistency: keep facts that must agree in one process and change them in one place, in an order that survives failure.
  • Concurrency: find what happens at once and what it shares; protect it with one lock or one owning thread; never hold the lock during slow outside calls.
  • Latency: put a time limit on every outside call; measure where time goes.
  • Security: validate input at the boundary, decide identity in one place, fail closed, keep only what you need.
  • Reliability: decide each failure; save before acknowledging; expect messages to arrive twice.
  • Record what each quality does not need, and the number that says so.