Skip to main content

Chapter 35 — Testing & Quality Strategy for Backend Systems

Part VII · Delivery | Prerequisites: Ch 14, Ch 26–Ch 27 | Builds: Pulsely's test suite — unit, integration (Testcontainers), contract, queue-flow

You have spent six parts learning to build a backend that stays correct while parts of it fail. This part is about shipping that backend without breaking it — and the first thing you ship is not code, it's confidence. A test suite is the machine that lets you change a running system on a Tuesday afternoon and still go home on time. This chapter is about building that machine so it tells the truth, runs fast enough to use, and exercises the parts that actually break — which, for a backend, are almost never the parts a naïve suite covers. By the end you'll be able to place any behavior at the cheapest layer that can still catch its bugs, test asynchronous and eventually-consistent flows without sleep(), and explain to a skeptical staff engineer exactly what each test is worth and what it's lying about.

This is a dense chapter with real code, because testing async backends is where most "good test discipline" quietly falls apart, and the difference between a suite people trust and one they route around lives in details most tutorials skip.


1. The problem: a green suite that shipped a null​

Let me start with the kind of incident that gets a testing chapter written.

Pulsely has 2,400 tests. Coverage sits at 91%. The CI dashboard is a wall of green. On a Thursday, a claim is submitted with a null charge total — the payer rejects it at the clearinghouse, the practice's revenue reconciliation breaks, and the billing team spends a day untangling it. The post-mortem finds the cause in ninety seconds: every test that touched claim creation mocked the fee-schedule service to return a fixed 1499. The bug was in the real fee-schedule lookup — a charge lookup that returned null for a newly added CPT code under a newly contracted payer — and not one of 2,400 tests had ever called it. The mock was the bug's perfect hiding place. The suite wasn't wrong; it was blind in exactly the spot that mattered, and the coverage number counted the mocked-out lines as covered.

This is the trap the chapter exists to dismantle, and it has two walls. The first wall is the brittle suite: tests so coupled to implementation that every refactor turns the board red for reasons no user would ever notice, so the team starts disabling them, then stops trusting them, then stops reading them. The second wall is the slow suite: 22 minutes of CI that engineers route around with git commit --no-verify because waiting is worse than the small chance of a bug. Brittle and slow look like opposite failures, but they end in the identical place — tests stop gating change. And a test that doesn't gate change is pure cost: you pay to run it, pay to maintain it, and still re-verify the system by hand.

So reframe what a test is. A test is not a proof of correctness — you cannot test your way to "this is correct," only to "this specific regression won't recur silently." A test is a cost-of-change reducer: it earns its keep only if it would have caught a regression you'd otherwise have shipped. By that definition, the 2,400-test suite above had a large number of tests worth approximately zero, because the regression that actually shipped sailed straight through them.

There is a structural reason backends fall into this trap harder than frontends or libraries. A backend is mostly I/O and coordination — talking to a database, a cache, a queue, three other services, an outside clearinghouse or lab, and the wall clock — and that is precisely the part unit-with-mocks testing refuses to touch. The pure logic (a charge calculation, a worklist-ranking formula) is the easy 20% to test and the rarely-broken part; the glue (does the transaction commit, does the consumer dedupe, does the migration match the query) is the hard 80% to test and where the incidents live. A suite that's easy to write tests the safe code and leaves the dangerous code naked. "More tests" is the wrong reflex because it deepens that imbalance: a fourth test of the charge function and a tenth assertion on a mock's call count add count and coverage while the queue consumer remains untested.

🧭 The reframe. Tests are not proof; they are insurance against regression, priced per test. Coverage measures lines executed, not failures prevented — a line run by a test with no meaningful assertion, or run only against a mock, is "covered" and unprotected. Ask of every test you write: which regression, shippable by a real engineer, would this have caught? If you can't name one, you're writing cost.


2. The mental model: a confidence-per-second portfolio​

Stop thinking of tests as a checklist and start thinking of them as a portfolio. Each test buys you some quantity of confidence at some price — a price paid in run time (every CI cycle, forever) and in maintenance (every refactor that has to drag it along). Your job is not to maximize the count, the coverage, or any single layer's size. Your job is to maximize total confidence purchased per second of CI and per hour of upkeep. That single shift kills most bad testing arguments before they start.

Make the value concrete. A test's worth is roughly:

value ≈ P(it catches a real regression) × cost-if-that-regression-ships
─────────────────────────────────────────────────────────────────
run cost + maintenance cost

Run this formula over the mock-heavy unit test of claim creation from §1 and it scores terribly: the probability it catches a real regression in I/O-bound code is low (the I/O is mocked away), so the numerator collapses no matter how cheap it is to run. Run it over an integration test that drives a real Postgres and asserts the committed claim row, and the numerator jumps — it can catch the null charge, the missing migration, the broken ON CONFLICT, the wrong isolation level. Same feature, wildly different value, because the blast radius of the bugs each can catch differs by an order of magnitude — and a dropped claim or a leaked chart is a bug with real-world teeth.

The second dial is fidelity vs. feedback, and it is a genuine tradeoff you cannot wish away. The more real a test's collaborators are — real Postgres beats a fake beats a mock — the higher its fidelity (it tells the truth about more of the system) and the slower and more fragile its feedback (containers to boot, network to flake, more moving parts). You don't pick a single point on this dial for the whole suite. You place each behavior at the cheapest layer that still tells the truth about it. Charge arithmetic? Pure unit — a real database tells you nothing extra about multiplication. "Does the unique constraint reject a duplicate claim submission?" Integration against real Postgres — a mock or an in-memory fake will cheerfully accept the duplicate and lie to you.

🧭 Mental model. Picture every behavior as a point you must place on a fidelity-vs-speed plane. Push it as far toward cheap and fast as you can go without the test starting to lie about that behavior. The whole craft of backend testing is locating that line — and the line moves up (toward real infra) exactly when the behavior depends on something a double can't fake: SQL semantics, transaction visibility, message ordering, time.

Two more model pieces close the loop. First, test the contract, not the implementation: assert on observable behavior at a stable boundary — the HTTP response, the row in the database, the message published to the broker — not on the private steps inside. A test that asserts "the service called repo.save() with these arguments" breaks the day you rename save, even though no user-visible behavior changed; a test that asserts "after POST /claims, a row exists with status submitted" survives every refactor that preserves that truth. The boundary is what your callers depend on; everything inside it is yours to change.

Second, the async corollary, which is the spine of the hard half of this chapter. In an eventually-consistent system — the queues and event logs you've already built — the "result" of an operation is not a return value. POST /claims returns 202 Accepted (received, not yet finished) and the biller notification arrives later, the worklist fans out later still. The correct outcome is a state the system reaches within a bound, not a value a function hands back. So your assertion can't be expect(result).toEqual(x); it must be "the system converges to X within N seconds." That one reframing — from equality to bounded convergence — dictates every technique in the queue-flow section, and getting it wrong is the single largest source of flaky backend tests in the wild.


3. Theory & invariants: pyramids, doubles, and the things that must stay true​

Two famous pictures argue about the shape of a good suite, and you should understand both well enough to ignore the picture and reason about your own risk.

The test pyramid (Mike Cohn) says: many fast unit tests at the base, fewer integration tests in the middle, a sliver of end-to-end at the top. Its logic is speed and isolation — push tests down to where they run in milliseconds and pinpoint failures precisely. Its hidden assumption is that most of your risk lives in unit-testable logic. That assumption holds for a compiler, a spreadsheet engine, an eligibility-rules library — code that is rich logic over poor I/O.

The testing trophy (Kent Dodds) says: make integration the widest band. Its logic is that for systems which are thin logic over rich I/O — most backends, most chart-and-coordinate services — the bugs live in the glue between your code and its dependencies, so integration tests buy the most confidence per test. The base (static types, lint) and the e2e tip stay small.

Don't memorize a winner. The decision rule subsumes both:

🔑 The shape invariant. Shape your suite to where your risk and your actual bug history live, not to a diagram. A service that is a deep eligibility engine over a thin database earns a pyramid. A service that is thin glue over Postgres + Kafka earns a trophy. The right shape is an output of your system's logic-to-I/O ratio and your post-mortem record — read both before drawing either picture.

Now pin the vocabulary down, because loose definitions cause loose tests:

  • Unit — exercises one logical unit (a function, a small class) with no I/O and full determinism. Same input, same output, every time, in microseconds.
  • Integration — your code plus a real adjacent dependency (a database, a cache, a broker), running in-process in your test. This is where "does my SQL actually do what I think" gets answered.
  • End-to-end (e2e) — the deployed system exercised over its real external interfaces (HTTP in, message out), with no test reaching into internals. Highest fidelity, slowest, flakiest; you want very few.

Test doubles, and exactly how each one lies​

A double is any stand-in for a real collaborator. Gerard Meszaros named five, and the useful framing — the one that prevents the §1 incident — is to learn each by the specific lie it tells:

  • Dummy — pure filler passed to satisfy a signature, never actually used. Lies by omission only if you mistake "unused" for "irrelevant."
  • Stub — returns canned data on demand. Its lie: it answers only the cases you remembered to program, so it silently hides the variety and edge cases you forgot — the null-charge CPT code, the empty result set, the out-of-range vital.
  • Spy — records how it was called so you can assert on it afterward. Its lie: it tempts you to assert on implementation ("was save called twice with these args") instead of behavior, coupling your test to internals that aren't a contract.
  • Mock — a stub with pre-programmed expectations that fails if they aren't met. Its lie: it asserts against your belief about the collaborator's contract — and if the real collaborator's contract differs or drifts, the mock passes while production breaks. This is precisely the §1 null bug.
  • Fake — a real, working, lightweight implementation: an in-memory database, an in-memory queue. Its lie: it has different semantics from the real engine. Here is the intuition to hold onto: a fake reimplements the database in memory, so it re-guesses every rule the real engine enforces — and it guesses several of them wrong. Concretely, real Postgres will reject a duplicate key through a UNIQUE constraint; an in-memory fake happily accepts it, so your test goes green on a write production would refuse. The same gap hides in the dialect, the isolation level (the rule for what one transaction is allowed to see of another's uncommitted work), ON CONFLICT, JSONB operators, collation, and timezone handling — each subtly or completely wrong, so your test passes against a database you will never deploy.

🔑 The double invariant. A double can only be as correct as your understanding of the thing it replaces. Every double encodes an assumption about the real collaborator — and that assumption may already be false the moment you write it, and will drift as the real thing evolves. This is why mocks of other teams' services (or an outside clearinghouse or lab) and fakes of real databases are the two most dangerous doubles in a backend: in both cases the thing you're modeling is outside your control and free to surprise you.

Two more invariants govern whether a suite is even usable:

Determinism and independence. No shared mutable state across tests; no dependence on execution order; no reliance on the wall clock or the live network; fresh data per test. Every violation of these is a future flaky test — a test that fails not because the code broke but because two tests collided, the clock advanced, or a leftover row survived. Flakiness is not bad luck; it is determinism debt coming due.

The oracle problem. Every assertion needs a source of truth for what "correct" means — an oracle. For synchronous code the oracle is usually an expected value (expect(total).toBe(1499)). For async flows, the oracle is a converged state, and a converged state can't be checked with equality at an instant — it forces polling with a timeout ("does this predicate become true within N seconds?"). The shift from "assert a value" to "assert a predicate converges" is forced by the oracle problem, not chosen for convenience.

📎 Borrowed on credit: idempotency & delivery semantics. This chapter tests async flows; the properties it asserts about them — at-least-once delivery, why consumers must be idempotent, what redelivery and ordering actually guarantee — are owned by Chapter 25. Here we take them as given and build tests that prove a consumer honors them. If "at-least-once means your handler runs twice for one message" isn't yet reflexive, that's the chapter to revisit; we lean on it constantly below.


4. Under the hood: building the four layers in Node/TS​

Now we build, layer by layer, with the mechanics that tutorials skip and the traps that bite in week three.

The unit layer: design for zero doubles​

The cheapest, fastest, most stable test is one that needs no doubles at all — and you earn that by extracting pure logic out of I/O-bound code. Pulsely's claim charge, contractual-adjustment rules, and worklist-ranking score should be pure functions: data in, value out, no database, no clock.

// claim-charge.ts — pure. No I/O, so no doubles, so no lies.
export function claimCharge(lines: ChargeLine[], adjustment: Adjustment | null): Cents {
if (lines.some(l => l.units <= 0)) throw new InvalidClaim('units must be positive');
const gross = lines.reduce((s, l) => s + l.unitCharge * l.units, 0);
const off = adjustment ? applyAdjustment(gross, adjustment) : 0;
return gross - off;
}
// claim-charge.test.ts — edge cases are the point: adjustments, zero/negative units, ties.
import { describe, it, expect } from 'vitest';
test('rejects non-positive units', () => {
expect(() => claimCharge([{ unitCharge: 500, units: 0 }], null)).toThrow(InvalidClaim);
});
test('applies percentage contractual adjustment to gross charge', () => {
expect(claimCharge([{ unitCharge: 1000, units: 2 }], { kind: 'pct', value: 10 })).toBe(1800);
});

The mechanics worth knowing: Vitest and Jest both hoist vi.mock/jest.mock to the top of the module before imports run, which is why mocking a module sometimes "doesn't apply" — your import already resolved. This hoisting is exactly why dependency injection beats module monkey-patching: when a service receives its collaborators through its constructor or parameters — the case for dependency injection you've already seen — you hand it a test double explicitly and visibly, with no hoisting magic and no global module surgery. DI keeps tests honest because the seams are real seams in the code, not patched-over module internals — and the same seam that makes the code testable makes it composable in production.

Faking time deterministically is a unit-layer superpower and a footgun. Use vi.useFakeTimers() / jest.useFakeTimers() (or sinon's clock) to control setTimeout, Date.now, debounce windows, and retry backoff — so a test of "retry after 30s, then 60s" runs in zero real seconds by advancing a virtual clock. The trap: fake timers leak across tests if you don't restore them in teardown, and a leaked fake clock turns an unrelated later test into a mysterious hang. Always vi.useRealTimers() in afterEach.

The integration layer: real Postgres/Redis via Testcontainers​

The moment a behavior depends on database semantics, a fake lies and only the real engine tells the truth. Testcontainers boots a throwaway real Postgres (or Redis, or Kafka) in a Docker container, programmatically, for the duration of your tests, and tears it down after. You get production's exact engine with a test's disposability.

// claims.integration.test.ts
import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import { beforeAll, afterAll, beforeEach, it, expect } from 'vitest';

let pg: StartedPostgreSqlContainer;
let db: Pool;

beforeAll(async () => {
pg = await new PostgreSqlContainer('postgres:16') // pin the engine you deploy
.withDatabase('pulsely').start(); // waits until truly ready
db = new Pool({ connectionString: pg.getConnectionUri() }); // dynamic port → config
await runMigrations(db); // the PRODUCTION migrations, not a hand-built schema
}, 60_000);

afterAll(async () => { await db.end(); await pg.stop(); });

Three details carry the weight. Dynamic port mapping: the container's port is assigned at runtime and injected into your config via getConnectionUri() — never hardcode 5432, because parallel test workers each get their own. Wait strategy: Testcontainers blocks start() until the container is genuinely ready (Postgres's image signals readiness via a log line; for custom images you supply a log-regex or health-check waitStrategy), which kills an entire class of "connection refused" flakes. And run the real migrations against the throwaway database — the schema under test must be byte-identical to production's, or you're testing a schema you'll never ship. This is how the §1 bug gets caught: against real Postgres, the null-charge either violates a NOT NULL constraint at insert or surfaces in the asserted row.

Isolation between tests sharing one container is the design decision that determines both speed and truth:

  • Transaction-per-test rollback — open a transaction in beforeEach, run the test inside it, roll back in afterEach. Fast (no data ever commits), perfectly clean. But here is the catch, in plain terms: a rolled-back transaction is a private scratchpad — nothing you write in it is visible to any other database connection, and it never actually COMMITs. So any behavior that only happens on a real commit, or that a second connection needs to see, is invisible to this test. That rules out commit-time triggers (including the append-only audit trigger), multi-connection visibility, advisory locks, and code that opens its own connection (which won't see your uncommitted rows).
  • Truncate-between-tests — let writes commit, then truncate the touched tables in afterEach. Slower, but real: it tests true commit behavior and cross-connection visibility.
  • Schema-per-worker — each parallel worker owns a uniquely named schema/database, so workers never collide. The scaling answer for a large suite; combine with one of the above for within-worker isolation.

Choose by what the test asserts: rollback for pure repository logic, truncate the moment a test depends on a real commit.

Testing async/queue flows — the hard part​

This is the section that separates engineers who say they test backends from those who actually do. Submitting the claim in §1 doesn't just write a row — it publishes a claim.submitted event that a notifications consumer turns into a biller notification row, and a fan-out worker turns into worklist entries. The "result" is those downstream states arriving eventually. You test it by producing the trigger, then polling the eventual outcome under a bounded predicate — never by sleeping.

🛑 What we deliberately do not re-derive here. Why the system is eventually consistent, how the broker delivers at-least-once, and why the consumer must be idempotent are Chapter 25–27 material, taken as settled. This beat owns only the testing technique for such systems: how to assert bounded convergence, drain a real broker in a test, and prove idempotency under deliberate redelivery. We will not re-explain delivery semantics; we will test against them.

The load-bearing helper is awaitUntil — poll a predicate until it's true or a deadline passes. (If you've used React Query, this is the same instinct as polling a query until its data satisfies a condition, with a hard timeout so you never wait forever.)

// awaitUntil.ts — the eventual-assertion primitive. Imitates Java's awaitility.
export async function awaitUntil(
predicate: () => Promise<boolean>,
{ timeoutMs = 5_000, intervalMs = 50 } = {},
): Promise<void> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (await predicate()) return;
if (Date.now() > deadline) throw new Error('awaitUntil: predicate never became true');
await new Promise(r => setTimeout(r, intervalMs));
}
}
// claim-flow.integration.test.ts — real Postgres + real broker via Testcontainers.
it('claim submission fans out a biller notification', async () => {
const res = await api.post('/claims').send(validClaim).expect(202);

await awaitUntil(async () => {
const { rowCount } = await db.query(
'SELECT 1 FROM notifications WHERE claim_id = $1', [res.body.claimId]);
return rowCount === 1; // assert the CONVERGED STATE, within a bound
});
});

it('is idempotent under redelivery', async () => {
await broker.publish('claim.submitted', { claimId, dedupeKey });
await broker.publish('claim.submitted', { claimId, dedupeKey }); // deliberate duplicate
await awaitUntil(() => notificationCount(claimId).then(n => n >= 1));
await settle(); // let any second handler finish
expect(await notificationCount(claimId)).toBe(1); // EXACTLY one — proves dedup
});

🔑 The convergence invariant. Never assert an async outcome with await sleep(N) followed by a check. A fixed sleep is slow when N is generous and flaky when N is tight — and N is always both, because convergence time varies with load. Poll the actual converged state with a timeout. The timeout is a safety net you hope never to hit, not a guess at how long the work takes. sleep-then-assert is the #1 cause of flaky backend suites; banning it removes most of your flake.

To drive these, you consume from a real broker inside the test — a Kafka, Redis Streams, or localstack-SQS container — and you must read your own messages. First the picture: a broker topic is a shared log, and a consumer group is a bookmark into that log (the offset) that remembers how far it has read. If two parallel tests share one bookmark, each ends up reading the other's messages — the same way two React components sharing one React Query cache key each get served the other's data. So use a unique consumer group / unique topic / unique key per test, so a parallel test's messages don't bleed into yours and offsets start where you expect. Controlling offsets and consumer groups is not optional hygiene here; it is what makes a queue test deterministic instead of a race against whatever messages happen to be on the topic. The idempotency test above is the high-value one: it deliberately delivers twice (because the broker will — at-least-once delivery is a promise, not an accident) and asserts exactly one notification, proving the consumer dedupes. Assert ordering only where the system actually guarantees it (e.g. within a Kafka partition, never across partitions); asserting ordering on a system that doesn't promise it writes a test guaranteed to flake, because you've made your oracle a property the system never claimed to provide.

Contract testing across services​

When Pulsely's notifications consumer lives in a different service/repo than the claims producer, neither integration nor unit tests catch contract drift: the producer changes the claim.submitted shape, the consumer's stub still reflects the old shape, both repos are green, production breaks at the seam. Here is the intuition first, tools second: the consumer writes down the exact message shape it needs; that written-down expectation becomes a file the producer's CI must satisfy — so if the producer changes the shape, its own build fails before it ever ships. That is what consumer-driven contracts (CDC) mean, and Pact is the popular tool. Mechanically: the consumer's test declares the request/response (or message) shape it depends on; that expectation is published as a contract artifact; the provider's CI verifies independently that it can satisfy it. Two services, two pipelines, one shared truth — and no flaky shared integration env in the middle.

The same discipline extends past your own services to external partners, which is where healthcare lives or dies. The shape of an X12 837 claim you send a clearinghouse, the 835 remittance you parse back, an eligibility 270/271 exchange, an HL7/FHIR lab result — every one is a contract with a system you don't control. Pin each with a recorded fixture that the partner's real format must satisfy, run against a Testcontainers stand-in for the partner, so a silent format change fails your build instead of a live claim. For event buses, the analog is a schema-compatibility check: a schema registry that rejects a producer change that would break existing consumers (Avro or JSON-Schema is the format that fills it in).

Where the JVM teaches the pattern​

(Skippable if you don't work in Java — the payoff, not the vocabulary, is what transfers.) Two ideas move straight from the Spring/JVM world even though Pulsely is Node. First, Spring's test slices (@DataJpaTest, @WebMvcTest, @SpringBootTest) formalize "spin up only this layer" — a discipline TS lacks out of the box but should imitate by hand: a repository test wires only the database, not the HTTP server, so a failure points at one layer instead of the whole stack. The slice idea is worth internalizing even without the annotation — when a test boots more of the system than the behavior it asserts needs, it is slower and less diagnostic than it should be. Second, Testcontainers was born on the JVM, and @Testcontainers + @DynamicPropertySource is the cleanest expression of "inject real-infra connection details into config at runtime" — exactly what getConnectionUri() does above; the Node port copies the pattern, not the syntax. And awaitility's await().atMost(5, SECONDS).until(...) is the canonical eventual-assertion API our awaitUntil imitates beat for beat. The vocabulary is JVM; the technique is universal, and recognizing it across ecosystems is how you avoid re-inventing a flakier version of a solved problem.


5. In production: CI topology, isolation at scale, and gates​

A suite that's correct on your laptop and unusable in CI hasn't shipped. Production-grade testing is about topology and discipline.

Split CI jobs by layer, and fail fast. Units (sub-30 seconds) run on every push — if they're red, don't even boot containers. Integration (Testcontainers) runs on the pull request. Contract verification runs on the provider's build against the published contract. e2e and load run nightly or pre-deploy. The ordering is deliberate: cheap and high-signal first, so a typo never costs a Docker pull.

push ─▶ [lint + typecheck] ─▶ [unit <30s] ─▶ [integration: Testcontainers] ─▶ [contract verify]
│ red? stop │ red? stop │
▼ ▼ ▼
fail fast (gates the merge) (gates provider)

nightly / pre-deploy ─▶ [e2e] ─▶ [perf gate: k6 p95 vs baseline] ← does NOT gate every merge

📎 Borrowed on credit: wiring these jobs as CI gates. The diagram shows what runs when; the machinery that makes a red job actually block a merge or a deploy — branch protection, required checks, the promote-on-green pipeline — is Chapter 38's territory. This chapter owns the content of each lane (what each layer tests and why); Chapter 38 owns turning the lanes into enforced gates. Here we draw the lanes; there we arm them.

Containers in CI have sharp edges. Decide between Docker-in-Docker and mounting the host Docker socket (simpler, but the runner can see all containers and a leaked container can outlive a job). Pin base images by digest for reproducibility — an unpinned postgres:16 can silently become a different patch between Tuesday's green run and Thursday's red one — and cache the layers so every run doesn't re-pull gigabytes. Set resource limits so a dozen parallel Testcontainers don't OOM the runner; "passes locally, killed in CI" is almost always memory pressure from N containers the laptop had headroom for and the runner didn't.

Isolation at scale means data, not just containers. With parallel workers, use worker-scoped containers or schema-per-worker, and seed each test's data through factories (functions that mint a fresh, valid object — a synthetic patient, a synthetic claim — with a unique key) rather than shared fixtures — shared fixtures make tests fight over the same rows, which is order-dependence wearing a disguise.

Flakiness is an SLO, not an annoyance. Track a flake rate. Quarantine a flaky test into a non-gating lane — don't delete it (you lose the coverage) and don't ignore it (it rots) — and file it as a bug with a ticket, because a flaky test is a real race or a real shared-state leak that hasn't bitten production yet. Auto-retry only at the job level with visibility, never as a silent per-test retry: 3 that hides a genuine race behind a green checkmark.

Perf regression as a gate. Capture a baseline p95 and throughput for a critical endpoint — claim submission — as a checked-in artifact. CI runs a short k6 or Artillery scenario and fails the build if p95 regresses past a threshold. Performance becomes a tested invariant, not a quarterly surprise discovered by users. Keep the CI scenario small enough to finish in a couple of minutes (it's a regression tripwire, not a capacity study); full load tests stay out-of-band.

// k6 perf-gate scenario — short, on the bottleneck path, fails the build on regression.
import http from 'k6/http';
import { check } from 'k6';
export const options = {
vus: 20, duration: '60s',
thresholds: { http_req_duration: ['p(95)<350'] }, // baseline p95; CI fails if breached
};
export default function () {
const r = http.post(`${__ENV.API}/claims`, JSON.stringify(claim), jsonHeaders);
check(r, { 'accepted': (res) => res.status === 202 });
}

Test data and secrets: ephemeral, synthetic, never real patient data; seed deterministically with a fixed RNG seed so a failure reproduces instead of vanishing on re-run. A test that can't be reproduced can't be debugged, and a randomly-seeded factory is a flaky test waiting for an unlucky value. And use coverage correctly — as a ratchet (a gate that forbids coverage dropping below the current line) and a gap-finder (which branches in claims and PHI-access code are uncovered?), never as a target to hit, because a coverage target is gamed in minutes with assertion-free tests that execute lines and verify nothing. The ratchet is the honest version of the same number: it rewards adding protection to new code without ever rewarding the empty test that satisfies a quota.


6. Common pitfalls​

The eternal happy-path mock. Signature: a collaborator is stubbed to return the same valid value forever; production breaks on the case you never stubbed (the §1 null charge). Fix: test edge and error variety, prefer fakes or real infra for I/O, and bound every mock of an external service (fee schedule, clearinghouse, lab) with a contract test so the mock can't silently diverge from reality.

The in-memory database that lies. Signature: tests pass against an in-memory fake and fail against real Postgres — case sensitivity, transaction isolation, ON CONFLICT, JSONB, timezones. Fix: run integration tests against the real engine via Testcontainers; reserve fakes for pure logic, never for database semantics.

await sleep(N) for async outcomes. Signature: the suite is slow (N is generous) and flaky (N is occasionally too short under load). Fix: awaitUntil a predicate tied to the actual converged state, with the timeout as a safety net.

Order-dependent tests / leftover rows. Signature: green locally, red under CI parallelism; reordering tests changes the result. Fix: per-test isolation (transaction rollback or truncate), fresh factory data, zero shared globals.

Asserting on mock calls as the main assertion. Signature: expect(spy).toHaveBeenCalledWith(...) is the test's whole point; it breaks on every internal refactor. Fix: assert the observable outcome; use a spy only when the side effect is the contract (e.g. "a critical-value alert was enqueued" is a real, patient-safety obligation).

Leaked fake timers / global state. Signature: an unrelated later test hangs or fails spookily. Fix: restore mocks and timers in teardown; isolate per test.

Pyramid inversion — mostly e2e. Signature: a 40-minute, flaky, mostly-end-to-end suite no one trusts, justified as "it tests everything." Fix: push each behavior down to the cheapest layer that still tells its truth; keep e2e a thin smoke layer.

Testing the framework. Signature: tests assert that Express routes, that the ORM saves, that the JSON serializer serializes. Fix: delete them — they have maintenance cost and zero regression-catching value. Test your logic and your integration wiring, not the library's.

Contract drift between services. Signature: provider changes the response shape, the consumer's stub doesn't, both repos green, production broken at the seam. Fix: consumer-driven contract verification in the provider's CI against the published contract.


7. Tradeoffs​

Pyramid vs. trophy. More unit = fast, isolated, but blind to glue and I/O bugs. More integration = high confidence, slower, needs Docker. Lean unit-heavy when logic gets rich (a real eligibility engine); lean integration-heavy when the service is thin glue over DB and queue. You'd reverse a service's shape the day its logic-to-I/O ratio flips — extracting a fat rules engine out of a chart-and-store service is exactly such a day.

Mock vs. real infra. Mocks: fast, deterministic, low fidelity. Testcontainers: high fidelity, slower, Docker-dependent. Reverse toward mocks when the dependency is a flaky or expensive third party you can't run locally (a clearinghouse, a payer eligibility API, a lab interface) — but then back the mock with a contract test, or the mock will drift from the real thing and reintroduce the §1 failure under a different name.

Transaction-rollback vs. truncate isolation. Rollback is fastest and cleanest but cannot test commit-time triggers, cross-connection visibility, or anything COMMIT-dependent. Truncate is slower but real. Choose per what the test asserts, not per a global policy — a repository unit-of-work test wants rollback; a "does the audit trigger fire on commit" test demands truncate.

Contract testing vs. a shared integration environment. CDC is decoupled, fast, and only covers the interactions you wrote down. A live shared environment catches emergent cross-service issues but is slow, flaky, and a contended bottleneck the whole org queues behind. Most teams need both, weighted heavily toward CDC, with a thin shared-env smoke test as backstop.

Perf-gate strictness. A tight p95 threshold catches regressions early but flakes on noisy runners; a loose one is stable but lets slow creep through. Tune the threshold to your runner's observed variance, and gate on a trend across runs rather than a single noisy data point.

🚫 A framing this book rejects. "Get to 100% coverage and you're done." Coverage is lines executed, not failures prevented — 100% coverage with assertion-free or fully-mocked tests is a suite that proves nothing while costing everything to maintain. The §1 incident lived comfortably inside 91% coverage. Chase confidence per second on the code that can hurt you, and let coverage be a ratchet and a gap-finder on claims and PHI-access paths — never the goal itself.


8. Security & scale notes​

The threat surface mocks happily pass. Authorization boundaries are the sharpest example, and in healthcare they have teeth. The question is not "can user A read user B's order" — it is "can provider A pull up patient B's chart?", and a wrong answer is not a bug, it is a reportable HIPAA breach. This is the classic IDOR / BOLA hole: a chart is fetched by id, someone increments or guesses the id, and one patient's record is served to the wrong clinician. A mock will cheerfully return success for every such request and tell you nothing. The authz check that matters runs against real Postgres, with provider A's identity, and returns zero of patient B's rows — because the boundary is enforced by row-level security (RLS) and tenant scoping in the database (each clinic/org isolated, each role — provider vs. biller vs. front-desk — held to minimum-necessary access), and only the real engine exercises that policy. A mocked repository that returns a hand-picked list has decided the answer before the test ran. The injection check is the same shape: a parameterized query proven safe is one that ran a hostile string through the actual driver and engine and came back inert — a string-matching mock proves only that your assertion matches your own expectation. Put your security tests where the database actually runs, because the boundary you're defending is the one between your code and that database, not the one between your code and a stub.

Two healthcare invariants deserve their own integration tests, because a mock erases exactly what they assert:

  • Minimum-necessary & break-glass. A biller's identity must see the claim and its charge but not the clinical note; test the deny side, not just the allow. And an emergency break-glass access (a clinician overriding normal scope to reach a chart in an emergency) must succeed and force a written justification row — so test both halves: the access is granted and the mandatory reason is recorded.
  • The audit trail. HIPAA requires an immutable, append-only record of every chart view, not just every write — so "reading patient B's chart writes exactly one audit row naming the viewer, the record, and the time" is a first-class assertion. It can only be checked against the real database, where the append-only audit table and its commit-time trigger actually live (which is also why this test wants truncate isolation, not rollback — a rolled-back transaction never fires the trigger). A test that reads a chart and then asserts the audit row exists is guarding a compliance obligation, not a nicety.

Test infrastructure is itself a threat surface. Never seed real PHI into a test database — synthetic patients only; a leaked test dump of real charts is the same breach as a leaked production one, and "it's only test data" is how PHI ends up on an unmonitored box. Keep test infrastructure on HIPAA-eligible, BAA-covered services (encrypted stores with server-side encryption, private subnets, no PHI ever on a public endpoint) even for fixtures. Pin Testcontainers images by digest (an unpinned base image is a supply-chain hole that runs inside your CI with your secrets). Scope CI secrets tightly — test pipelines should never hold production credentials. And ensure ephemeral test databases are actually torn down, leaving no data and no open port behind.

Load tests reveal what unit and integration cannot. Lock contention (two front-desk staff grabbing the same appointment slot), connection-pool exhaustion, and queue backpressure are emergent under concurrency — invisible to any single-threaded test. So aim the CI perf gate at the bottleneck path (the claim write plus the queue publish), not at a trivial healthcheck that exercises nothing contended.

Flakiness scales superlinearly — the math demands an SLO. With N tests each flaking with independent probability p, the chance the whole suite is green is roughly (1−p)^N. A 0.1% per-test flake across 3,000 tests fails about 1 run in 20 — green suite, red CI, eroded trust, one in twenty pushes blocked for no real reason. This is precisely why flakiness is an SLO with a budget you drive toward zero, not an annoyance you retry away: at scale, small p is not small.

Eventual-consistency tests must be sized for load, not idle. A convergence window that comfortably passes on an idle CI box can fail under a busy runner where the broker and consumer are contended. Size your awaitUntil timeouts from observed p99 convergence under realistic load — the tail-latency thinking you've already seen applies directly — and assert that the bound is met, not merely that the state arrives "eventually," which is untestable.


9. Interview lens & exercises​

Interview questions​

"How would you test an endpoint that submits a claim and asynchronously fans out a biller notification?"

  • Junior answer: "Mock the queue and assert that publish was called." Stops at the boundary of the service and never touches the async outcome.
  • Senior answer: names two layers — a unit/contract check that publication happens with the right shape, plus an integration test that drives the real consumer via Testcontainers and awaitUntils the converged notification row — and explicitly adds a duplicate-delivery test for idempotency and asserts ordering only where the broker guarantees it. The phrase to listen for is "the result is a converged state within a bound, not a return value."

"Pyramid or trophy — which, and why?"

  • Junior: recites one as the universally correct shape.
  • Senior: "depends on where the risk lives," then sizes the layers to the service's logic-to-I/O ratio and its actual bug history, and names the cost of each layer rather than its dogma.

"When does a mock lie to you?"

  • Junior: "Mocks are just for replacing dependencies."
  • Senior: enumerates the contract-drift failure — the mock encodes your belief about a collaborator's contract, which drifts (especially for an outside clearinghouse or lab) — and pairs every external mock with a contract test or real-infra test to bound the lie.

"Your suite is green but flaky about 5% of runs — what do you do?"

  • Junior: "Add retries."
  • Senior: treats each flake as a bug with a ticket, quarantines it non-gating, root-causes it to time/order/async/shared-state, and frames the whole thing with (1−p)^N to explain why 5% is intolerable at the suite's size.

"What do you deliberately not test, and why?"

  • Junior: "Test everything."
  • Senior: the framework's own behavior, third-party internals, trivial getters, and over-specified mock interactions — because they carry maintenance cost and catch nothing, which is negative value.

Exercises & the Pulsely increment​

Build Pulsely's layered suite and the ADR that governs it. Each layer maps to a beat above.

  1. Unit (no doubles). Extract claim-charge/pricing and worklist-ranking into pure functions and unit-test the edges with zero doubles: percentage and fixed contractual adjustments, zero and negative units, ranking tie-breaks, an empty claim. If a test needs a mock, the function isn't pure yet — refactor until it is.

  2. Integration (Testcontainers). Stand up real Postgres + Redis, run the production migrations, and test the claim-creation repository path — including a uniqueness / ON CONFLICT case (a duplicate claim submission) that an in-memory fake would pass falsely. Add a PHI-boundary test (provider A's identity returns zero of patient B's rows under RLS) and an audit-on-view test (reading a chart writes exactly one append-only audit row). Pick and justify an isolation strategy (rollback vs. truncate) for each test by what it asserts.

  3. Queue-flow. Submit a claim through the API, consume from the real broker, and awaitUntil the notification row and the worklist fan-out appear; then redeliver the same message and assert exactly one notification (idempotency under at-least-once). No sleep anywhere — if you typed one, replace it with a predicate.

  4. Contract + ADR. Write a consumer-driven contract between the claims producer and the notifications consumer, plus a recorded clearinghouse 837/835 fixture the partner's real format must satisfy, and wire provider verification into CI. Then author the ADR — Test strategy & boundaries: for each layer state what it owns (which behaviors live there) and where the boundary sits (in-process unit vs. real-infra integration vs. cross-service contract); declare the isolation choice per layer; set a flakiness budget (a target flake rate and the quarantine policy); fix the perf-gate threshold (baseline p95 for claim submission and the allowed regression); and — the part most ADRs omit — list what is deliberately NOT tested (the framework, third-party internals, trivial accessors) and why. An ADR that can't say what it refuses to test hasn't made a strategy, only a wish.


Key takeaways​

  • A test is a cost-of-change reducer, not a proof. It earns its keep only by catching a regression you'd otherwise ship; coverage counts lines executed, not failures prevented — and counts mocked-out lines as "covered."
  • Treat your suite as a confidence-per-second portfolio. Place each behavior at the cheapest layer that still tells the truth about it; the layer rises toward real infra exactly when a double would lie (SQL semantics, transaction visibility, ordering, time).
  • Shape the suite to where your risk and bug history actually live (pyramid vs. trophy), not to a diagram. Backends are thin logic over thick I/O, so integration usually buys the most confidence.
  • Every double lies in a known way — stubs hide forgotten variety, mocks encode a drifting contract, fakes get engine semantics wrong. A double is only as correct as your understanding of what it replaces; bound external mocks (fee schedule, clearinghouse, lab) with contract tests.
  • For async flows, the result is a converged state within a bound, not a return value. Poll a predicate with awaitUntil; never sleep-then-assert. Prove idempotency by deliberately redelivering.
  • Use Testcontainers to test against the real engine with real migrations; choose transaction-rollback vs. truncate by what the test asserts; isolate parallel workers by schema.
  • Flakiness is an SLO: (1−p)^N makes tiny per-test flake fail whole suites at scale. Quarantine, ticket, root-cause — never silently retry.
  • Gate performance as an invariant with a short CI perf scenario on the bottleneck path. Test the security boundaries at the integration layer where mocks would wave them through — a broken PHI access check is a reportable HIPAA breach, and every chart view must leave an immutable audit row.

← Previous: Ch 34 — Observability & Debugging · Up: Part VII overview · Master TOC · Next: Ch 36 — Containers & the 12-Factor App →