Skip to main content

Chapter 40 — Working in Existing & Brownfield Systems

Part VIII · Synthesis | Prerequisites: Ch 39 | Builds: a brownfield exercise — inherit and safely extend Pulsely's monolithic billing/claims module

Earlier you learned to draw boundaries — where to put seams so the cost of change stays bounded as the system grows. This chapter is about the other ninety percent of your career: living inside boundaries someone else drew, often badly, in code with no tests, no docs, and no surviving author. Greenfield — the empty repo, the clean slate, the architecture you get to choose — is a thin slice at the very start of a system's life. Everything after that is brownfield: a working, load-bearing, money-handling tangle that you must understand, extend, and migrate without breaking the people depending on it right now.

This is the chapter where seniority is actually tested. Not "can you write clean code from scratch" — most candidates can. The real test is "can you reduce the blast radius of a change in a system you don't fully understand." That skill is teachable, repeatable, and almost nobody teaches it. We will. The running example is a deliberately ugly corner of Pulsely — a 1,400-line ClaimService, the monolithic billing/claims module at the heart of revenue-cycle — and a feature you must add to it without a single regression.


1. The problem: most senior work is brownfield​

It's your second week. A Sev-2 fires at 4 p.m.: claims are double-billing — the same claim is going out to the payer twice, and the second submission is either paying twice or generating a denial that a biller has to chase. The endpoint is POST /claims, and the code that handles it is ClaimService.submitClaim — fourteen hundred lines, mixed concerns top to bottom, magic numbers nobody can explain, a module-level mutable cache, and exactly zero tests. git blame points at a contractor who rolled off eight months ago. The one engineer who "kind of understood it" left in April. There is a README, but it documents an architecture that was replaced a year ago. You have a production incident, a pager, and a codebase that is, functionally, a black box.

This is not an unlucky edge case. This is the median experience of a working backend engineer. By any honest accounting, the large majority of a senior engineer's career is spent modifying code they did not write. A successful system spends a few months greenfield and then years in production accreting features, fixes, and consumers. The empty repo is the exception; the inherited tangle is the rule.

And here is the part that surprises people pivoting in from frontend or from school projects: brownfield is harder than greenfield, not easier. On a blank page there are no invariants to violate, because there's nothing there yet. In a live system you are surrounded by invisible invariants — undocumented callers, downstream consumers, behavior that other systems already depend on including the bugs. A billing dashboard that rounds an allowed amount a particular way, a clearinghouse integration that parses a specific date format, a compliance report that reads a column you were about to rename. You can't see any of it from the code. You only find out when you break it.

The risk is asymmetric, too. A bug in greenfield code breaks nothing — there are no users yet. A bug in brownfield code breaks revenue, corrupts a patient record, and can take down a dozen consumers you didn't know existed, in production, today. The downside is real and immediate; the code is unfamiliar; the safety net is missing. That combination is exactly why this work is hard and exactly why it pays.

There's a cultural trap layered on top of the technical one. Pivoting developers — and bootcamp grads, and CS students — are trained almost entirely on greenfield: every assignment starts from npx create-…. So the instinct, on meeting a mess, is to treat it as someone else's failure to be corrected rather than as the normal state of a system that survived long enough to matter. The most valuable mental shift in this chapter is to stop reading the tangle as incompetence and start reading it as history — every ugly branch is a scar from a real wound. You don't heal a system by being offended by its scars. You heal it by understanding what cut it.

The seductive wrong answer, which we'll demolish in §7, is "this is a mess, let me just rewrite it." Hold that thought. For now, internalize the reframe: your job in a brownfield system is not to write beautiful code. It is to make a correct, valuable change while keeping the blast radius small — in a system you only partly understand and cannot afford to break.

🧭 A useful distinction. Greenfield asks "what should this do?" Brownfield asks "what does this currently do, and what depends on that?" The first is a design question; the second is an archaeology question. Most engineers are trained only for the first and then spend their careers doing the second untrained. This chapter is the missing training.


2. The mental model: black box, three-layer map, two-phase change​

Hold three pictures.

A legacy system is a black box wrapped around accumulated business truth. The messy ClaimService is not just bad code — it is a compressed, lossy record of every edge case production ever threw at it. That weird if (claim.modifierId && claim.serviceDate < contractEnd && !patient.isSelfPay) branch looks like noise. It is almost certainly a fix for a real incident: a payer that denied a whole batch until a specific modifier was suppressed, a contract that expired mid-quarter, a self-pay patient who got billed the contracted rate by mistake. The mess encodes knowledge. Respect it before you delete it — that respect is the entire difference between a strangler and a disaster.

You build a three-layer map of any unfamiliar codebase, in this order:

(1) SEAMS where can I observe or alter behavior
WITHOUT editing the scary code in place?
(2) REQUEST SPINE one end-to-end trace: the request spine, made concrete
controller → service → repo/DB → external calls
(3) CHANGE SURFACE the minimal set of files THIS task actually touches

You do not try to understand the whole system — that way lies weeks of reading and no shipped change. You understand one request path deeply (the request spine, now traced through real code), you find the seams where you can attach a test or a new path without surgery, and you scope ruthlessly to the change surface. Everything else stays a black box on purpose.

Legacy code is code without tests. That's Michael Feathers' definition, and it's the most useful one you'll ever adopt. It says nothing about age. A service written last Tuesday with no tests is legacy; a twelve-year-old module with a thorough suite is not. The thing that makes code dangerous to touch is not that it's old — it's that you have no way to know if you broke it. The absence of the safety net is the danger.

Which gives you the load-bearing rule of this whole chapter — change is a two-phase operation:

PHASE 1: make the change SAFE (add a net: pin behavior, find a seam)
PHASE 2: make the change (sprout new behavior behind the seam)

── never do both at once ──

🧭 Mental model. First make it safe to change, then change it. Beginners do the two phases simultaneously — they "fix and improve" in one pass — and that's how an undocumented edge case dies silently. Seniors split them. Phase 1 produces no behavior change at all; it just makes regressions detectable. Only then does Phase 2 begin. If you remember one sentence from this chapter, it's this one.

For migrations — the large-scale version of the same idea — the organizing metaphor is the strangler fig. The fig seeds in the canopy, sends roots down around an existing tree along its real structure, and slowly takes over until the original trunk is dead and can be cut. You don't fell the tree and rebuild; you grow the new system around the old along real call paths until the old one is load-free. We make this concrete in §3 and §5.

Last, the right frame for tech debt: it's a financial position, not a moral failing. Debt has principal (the wrong design that's baked in) and interest (the recurring tax you pay every time you touch it). Some debt is fine to carry — a high-principal, zero-interest mess in code nobody ever opens costs you nothing. You manage debt like a portfolio: you pay down the high-interest items, you record the rest, and you stop feeling guilty about code that works. The corollary that surprises perfectionists: not all debt should be paid down, and a senior who tries to fix every mess they pass is as junior, in their own way, as one who fixes none — both have failed to prioritize, which is the actual skill.


3. Theory & invariants​

A mental model tells you how to picture the work. Invariants tell you what must stay true while you do it. These are the load-bearing rules.

🔑 The safety-net invariant. Before you change behavior B, you must be able to detect a change in B. If you cannot observe B — capture it, assert on it, see it move when you break it — you cannot safely change it. "Safe to change" is defined entirely by "regression is detectable," not by "I read it carefully and I'm confident." Confidence is not a safety net.

The tool that satisfies that invariant in legacy code is the characterization test (also called a golden-master or pinning test). Here is the mind-bending part that trips everyone up the first time: a characterization test asserts what the code currently does, not what it should do. Its job is to detect change, not to verify correctness. If the legacy code computes an allowed amount wrong, your characterization test asserts the wrong value — on purpose — because right now your goal is "don't change behavior I didn't mean to change." A wrong-looking assertion is still a correct pin. You write the test by running the code and recording what comes out, then freezing it. In a claims module, this discipline is doubly important: you're about to touch code that computes money and moves PHI, so pinning the current behavior first is what keeps a "small cleanup" from silently changing what a payer gets billed.

🔑 The behavior-preservation invariant (the real definition of refactoring). Refactoring means changing internal structure while keeping observable behavior identical. That is the whole definition. If observable behavior changes — even a little, even an improvement — it is not refactoring. It's a feature or a bugfix, and it needs its own test and its own scrutiny. The industry uses "refactor" loosely to mean "I messed with the code"; you will use it precisely, because mixing structural change and behavior change is how regressions hide.

To attach a test or a new path without editing the scary code in place, you need a seam — Feathers' term for a place where you can alter behavior without editing in that place. Three kinds, each anchored to a tool you already use:

  • Object seam — inject a dependency instead of constructing it inline. If ClaimService does new FeeScheduleClient(), you can't substitute it; if it takes a pricing collaborator in its constructor, you can pass a fake. In plain terms: constructor injection — the DI you already do. (This is dependency injection, which you've already met, repurposed as a testability tool.)
  • Link seam — swap the module that resolves at import/link time. In plain terms: jest.mock('./fee-schedule') — you replace the whole module the importer pulls in, without touching the importer's code at all.
  • Preprocessing seam — change behavior via config or environment before the code runs. In plain terms: a process.env.FLAG or LaunchDarkly check that selects the code path before it executes — a feature flag.

Seams are where both your tests and your strangler attach. Finding them is the first creative act of brownfield work.

Two small surgical techniques for adding behavior without cutting into the mess:

  • Sprout — write the new logic in a fresh, fully-tested unit (a new method or class), and call into it from one line in the legacy code. The scary method gains one clean call; all the new logic lives in tested code you control.
  • Wrap — interpose around an existing call: rename the old method, write a new one with the old name that does your new thing and then delegates. The new behavior brackets the old without touching its body.

Finally, the invariant that governs every migration:

🔑 The expand/contract (parallel-change) invariant. Never hard-swap. You expand (add the new path alongside the old), run both, route traffic over gradually, and only then contract (remove the old path). And before you route real traffic, the new path must be observably equivalent to the old for the same inputs — which is the formal basis for the shadow/dual-run comparison — running both paths on real traffic and diffing their outputs, detailed in §5. "Equivalent" means: same outputs, same side effects, same errors, for the same inputs, proven on real traffic — not asserted in a design doc.


4. Under the hood: reading a large codebase you didn't write​

You've cloned the repo. It's 200k lines. Where do you even start? Not at the top of a file — start at the entry points, because every request enters somewhere, and the request spine is your through-line.

Find the entry points (Node/TS). The real start path is in package.json scripts — follow start/dev to main.ts, server.ts, or index.ts. From there, the HTTP surface is wherever routes register: Express app.use(...) / router.get(...), or NestJS @Controller/@Module decorators feeding the module graph. But HTTP is not the only door — grep for the other entry points that beginners forget:

grep -rn "listen(" src/ # the http server bootstrap
grep -rnE "@(Controller|Get|Post|Put)" src/ # nest route decorators
grep -rnE "\.process\(|consume\(|subscribe\(" src/ # queue/broker consumers
grep -rnE "cron|schedule|setInterval" src/ # timers and cron workers

A cron job or a queue consumer — say the nightly job that resubmits denied claims, or the worker that ingests inbound 835 remits — can be the thing calling your "dead" code. Enumerate every door before you assume you know who calls what.

Trace one request — and run it, don't just read it. Pick POST /claims and follow controller → service → repository/DB → external calls (the clearinghouse, the eligibility service). But your read of the path will be wrong wherever there's dynamic dispatch, DI, or metaprogramming, because the code that runs isn't lexically obvious. So get ground truth: fire a real request carrying a correlation id and read the structured logs. Or, faster for a local trace, drop a one-liner where you're unsure:

console.log(new Error('trace').stack); // prints the real call tree to here

or attach with node --inspect and set a breakpoint. The actual call stack beats the call stack you imagined every single time.

Build the map cheaply with tooling, not heroics. Generate the import/dependency graph to find god-modules and cycles:

npx madge --circular --extensions ts src/ # cycles = coupling smells
npx dependency-cruiser --output-type dot src/ | dot -Tsvg > deps.svg

The five most-imported files are the load-bearing walls — break one and the building shakes. Cross that with churn (how often a file changes) and you've found the danger zone:

git log --pretty=format: --name-only | sort | uniq -c | sort -rn | head -20

🏭 High churn × high coupling = the danger zone. A file that everything imports and that changes constantly is where your incidents come from and where your refactoring time pays off most. A messy file nobody touches (high principal, zero interest) can be left alone. This 2×2 — churn against coupling — is how you triage a whole codebase in an afternoon. We turn it into the tech-debt quadrant in §5.

Mine git history as documentation — because in a system with no docs, the commit log is the docs:

git log -p -- src/ClaimService.ts # WHY the code looks the way it does
git log -S "* 0.029" # the "pickaxe": when did this magic number appear?
git blame -w -C src/ClaimService.ts # authorship through reformat/move noise (-w -C)

git log -S (the pickaxe) finds the commit that introduced a string or constant — invaluable for the unexplained * 0.029 in the claim-pricing math. git blame -w -C ignores whitespace and tracks code moved between files, so you blame the author of the logic, not whoever last ran the formatter. The commit message, and the PR or Jira id it references, is how you recover the intent that the code itself lost.

Read tests and docs as a map, even when they're sparse. An existing *.spec.ts next to a file is the original author telling you which cases they thought mattered — it's a partial spec for free. A stale README still reveals the original module boundaries and intent, even if the implementation drifted. Don't dismiss old docs as worthless; read them as historical evidence.

🏭 The enterprise (JVM/Spring) lens. In Spring, entry points are @RestController/@Component classes discovered by classpath scanning and wired by the bean container. There are no explicit imports tying caller to callee, so "find who calls this" is harder than in import-explicit Node — you lean on the IDE's call-hierarchy view and the Spring bean graph instead of grep. In plain terms: Spring wires objects together automatically at startup by scanning the codebase, so unlike Node there's no import line connecting caller to callee — you can't grep the wiring, you ask the IDE for it. (Skip this box if you're not on the JVM; the principle — make invisible wiring visible before you touch it — is all you need.) The transferable principle is identical: make the implicit wiring explicit before you change anything.

The mechanics of a characterization test in TS. Capture current outputs into a golden file and assert future runs match. The only real difficulty is nondeterminism — timestamps, generated ids, map ordering — which makes the pin flap. The fix is to inject the sources of nondeterminism (a clock, a uuid factory — an object seam) or scrub those fields before comparing:

// Pin what submitClaim DOES today, scrubbing the non-deterministic bits.
function scrub(c: Claim) {
return { ...c, id: '<id>', submittedAt: '<ts>' }; // freeze the volatile fields
}

test('characterization: submitClaim totals & side effects (CURRENT behavior)', async () => {
const submitted: Submission[] = [];
const svc = new ClaimService({
pricing: legacyPricing, // real legacy collaborators
clearinghouse: { submit: s => { submitted.push(s); return ok(); } }, // capture side effects
clock: () => new Date('2026-01-01T00:00:00Z'), // seam: deterministic time
});

const claim = await svc.submitClaim(FIXTURE_CLAIM);

// We assert what it CURRENTLY produces — even the weird 0.029 adjustment — to detect drift.
expect(scrub(claim)).toMatchSnapshot();
expect(submitted).toMatchSnapshot(); // side effects are behavior too
});

Note that the test captures side effects (what got sent to the clearinghouse) as well as the return value. In a brownfield claims path, the side effect — the 837 that goes out the door — is usually the part that matters most.


5. In production: the brownfield change recipe and the strangler​

Here is the recipe tutorials skip — the actual sequence a senior follows to land a feature in scary code:

1. Reproduce current behavior locally ┐
2. Pin it with characterization tests │ PHASE 1: make it safe
3. Find or insert a seam ┘
4. Sprout the new behavior in a tested unit ┐
5. Wire it behind a feature flag │
6. Ship dark (flag off in prod) │ PHASE 2: make the change
7. Compare new vs old (shadow / dual-run) │
8. Flip the flag — gradually │
9. Delete the old path — as a SEPARATE PR ┘

Steps 1–3 are Phase 1; nothing user-visible changes. Steps 4–9 are Phase 2. Step 9 is its own pull request, never bundled with the feature — so that if anything regresses, the revert is clean.

The strangler fig in practice. For anything bigger than a method — extracting a whole capability, like pulling claim-pricing out of the monolith — you put a routing layer in front of the legacy capability (a façade/adapter, a feature flag, or a proxy), implement the new path beside it, and then earn trust before trusting it:

Frame 1 (shadow) Frame 2 (50%) Frame 3 (cut)
┌────────────┐ ┌────────────┐ ┌────────────┐
│ façade │ │ façade │ │ façade │
└─────┬──────┘ └──┬──────┬──┘ └─────┬──────┘
100% │ │shadow 50%│ │50% │ 100%
▼ ▼ (compare) ▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────┐ ┌──────┐ ┌──────────┐
│ legacy │ │ new │ │legacy│ │ new │ │ new │
└────────┘ └────────┘ └──────┘ └──────┘ └──────────┘
new runs no-op for diff stays clean → legacy trunk cut
writes; outputs diffed ramp traffic (separate PR)

In Frame 1 you dual-run / shadow: the new path executes on real production traffic but its writes are no-ops — it computes the answer, you diff it against the legacy answer, and you log the mismatches. This is the expand/contract invariant from §3 made operational: you prove observable equivalence on real traffic before a single claim is routed to the new path. Then you ramp — 1%, 10%, 50%, 100% — watching the diff and your error budget. Throughout, you track a burn-down of call sites still on the old path, so "are we done" has a number, not a vibe.

The routing layer itself is just a thin façade — exactly the seam from §3, now load-bearing in production — and it doubles as an anti-corruption layer: it translates between the legacy claim shape and the clean domain model the new service speaks, so the mess on one side never leaks into the new code on the other.

// The façade decides, per call, who prices the claim — and whether to shadow.
async function priceClaim(claim: Claim, ctx: Ctx): Promise<Money> {
const legacy = await legacyPricing.price(claim); // still the source of truth
if (flags.shadowFeeSchedule(ctx)) {
queueMicrotask(async () => { // off the hot path
const next = await feeScheduleService.price(claim); // NEW path, write-free
if (!next.equals(legacy)) metrics.diff('fee-schedule', scrubForLog(claim), legacy, next);
});
}
return flags.serveFeeSchedule(ctx) ? await feeScheduleService.price(claim) : legacy;
}

Two flags, not one: shadowFeeSchedule controls comparison (the no-op diff) and serveFeeSchedule controls who actually serves (the ramp). Decoupling them lets you shadow at 100% while serving at 0% — you collect a full traffic sample of diffs before you trust the new path with a single real claim. When serveFeeSchedule reaches 100% and the diff rate has been zero for your agreed window, the legacy branch is dead weight, and that is when step 9 — delete-the-old-path — becomes a safe, separate PR.

Record tech debt deliberately. Debt you don't write down isn't managed — it's just forgotten until it bites. Keep a debt register: an issue (labeled tech-debt) with a short ADR-style note — what's wrong, why it exists, the interest rate (how often it hurts), and a cost-to-fix estimate. Make it discoverable from the code itself:

// TODO(DEBT-417): the 0.029 factor is a hardcoded legacy payer contractual-adjustment rate.
// Interest: every fee-schedule change risks it; Fix-cost: ~1d once FeeScheduleService lands.

The ticket id in the comment links code to context, so the next engineer finds the why without re-running git archaeology.

Pay it down where it's cheapest. The boy-scout rule — leave the campsite cleaner than you found it — but scoped to your change footprint. Tidy the files you already had to touch; do not gold-plate untouched files (that's the scope-creep pitfall in §6). Attach paydown to features that already require opening that code — touching it is the expensive part, so amortize the cleanup against work you're doing anyway. And allocate a fixed, defended slice of each sprint to debt, or "later" never comes.

Refactor under constraints. Small, reviewable, behavior-preserving commits, separated from feature commits. Never mix a rename/move PR with a logic PR — keep them apart so review stays comprehensible and git bisect stays useful when you hunt the regression later. Keep the build green at every commit, not just the last one, so any commit is a safe place to bisect to.

Work within the team's process — and match conventions you dislike. Read CONTRIBUTING.md, the lint and format config, the PR template. Then match the existing conventions even where your taste disagrees — in shared code, consistency beats personal preference, because the next reader pays for every local exception. If you genuinely think a convention is wrong, raise it as a separate proposal (an ADR, an RFC), team-wide, not as a silent unilateral change smuggled into a feature PR. (Distinguish conventions from defects: you match the team's style; you do not adopt the legacy code's anti-patterns "for consistency" — see §6.)

Use code review as a brownfield tool. Your PR description does real work: narrate the seam you inserted, the characterization coverage you added, and the rollback plan. Then tag the original author or the git blame owner as a reviewer — they carry tribal knowledge no document captured, and a review request is the cheapest way to extract it. Building on the testing discipline you've already met, your characterization tests are now the artifact that makes the review believable: "here's proof I didn't change what I didn't mean to."

🛑 What we deliberately did not explain. How to write the ADR/design-doc format itself (that's Ch 39). How feature flags are implemented and operated at scale, and the deploy/rollback machinery behind a percentage rollout — that's the delivery and reliability material in Ch 33 and Ch 38. The general theory of consistency during dual-writes lives in Part V. Here we use those as tools to land a brownfield change; we don't re-derive them.


6. Common pitfalls​

Each is signature → fix: the symptom you'll observe, then the rule that resolves it.

Refactor-and-feature in one PR. Signature: a reviewer can't tell which diff lines are behavior changes and which are cleanup; six months later git bisect lands on a 600-line commit and tells you nothing. Fix: split into three PRs — pin, then refactor (behavior-preserving), then feature. Each is reviewable on its own and bisectable later.

Changing behavior before pinning it. Signature: a silent regression in an undocumented edge case that nobody notices for three weeks, until a payer's denial rate spikes and finance comes asking. Fix: characterization test first — always. And a corollary worth tattooing on your wrist: if you can't write a test that pins the current behavior, you don't understand the code well enough to change it. The struggle to pin it is the understanding.

"Improving" code you didn't need to touch. Signature: a 4-file feature becomes a 40-file PR; review stalls for a week; an unrelated module breaks because you "cleaned it up." Fix: scope discipline. The campsite rule applies to your change footprint, not the whole campground. See debt you didn't plan to fix? Log it (TODO(DEBT-…)), don't fix it now.

Trusting reading over running. Signature: your carefully-reasoned mental trace is simply wrong, because a DI container, a dynamic dispatch, or some metaprogramming sends the call somewhere your eyes never followed. Fix: confirm the real call path with a breakpoint, a log line, or new Error().stack. Reading proposes; running confirms.

Hard cutover on a migration. Signature: you deploy the new version, it's subtly wrong under real traffic, there's no flag and no shadow data, and you're now in an incident with no fast rollback. Fix: expand/contract — shadow-diff, percentage rollout, flag-based instant rollback. Never a flip with no path back.

Deleting "dead" code that wasn't dead. Signature: you remove an unreferenced function; a quarterly cron or another service was calling it; the failure surfaces at quarter-end. Fix: "nothing references it in the IDE" is not proof in a system with reflection, cron, queues, and other services. Verify with runtime usage logs/metrics across a full business cycle before deleting — and delete in a separate, easily-reverted PR.

Snapshot tests as a crutch. Signature: giant, unreadable golden files that every teammate reflexively --updates on any diff; the safety net catches nothing because nobody reads it. Fix: keep pins narrow and assertive — assert the few values that matter, not a 5,000-line blob. Treat an unexpected snapshot diff as a stop-the-line event, not a rubber-stamp.

Adopting the mess's anti-patterns "for consistency." Signature: you copy the legacy module's global mutable cache and 200-line method "to match the surrounding style," and the debt compounds. Fix: match conventions (naming, formatting, file layout), never defects. New code can be clean behind a seam even when the code around it isn't — that's how a codebase gets better one change at a time instead of worse.


7. Tradeoffs​

Senior judgment is naming the spectrum and saying why you stand where you stand.

Strangle ↔ rewrite from scratch. The strangler keeps the system shippable and de-risks each step, but it's slower and forces you to live with two systems coexisting for a while. A full rewrite is faster on paper and routinely fails in practice — Netscape's rewrite is the canonical corpse, and the "second-system effect" the canonical diagnosis. Why rewrites fail: the mess you're replacing encodes years of hard-won edge-case knowledge and bug fixes, and a rewrite throws all of it away, re-discovering each fix as a fresh production incident. Meanwhile the old system keeps moving, so you're chasing a target that never stops. You reverse toward a rewrite only in the narrow case where the old system genuinely cannot be incrementally extended — a dead platform with no path forward, a runtime with no build, a language nobody can hire for. Even then you strangle if you possibly can.

🚫 A framing this book rejects. "This code is ugly, so the responsible thing is to rewrite it cleanly." Ugliness is not a business case. The code is ugly and it works and it encodes truth you can't see. "Clean" is a property you value; "correct in production" is a property your users value, and a rewrite trades the second for the first on a promise it usually can't keep. Replace "let's rewrite it" with "let's strangle it," and you'll be right far more often than the engineer who reaches for the blank page.

Refactor now ↔ log as debt. Refactoring while you're already in the file is the cheapest it will ever be — but it expands the scope and risk of this change. Logging it keeps your PR small but risks "later" never arriving. Decide by one question: does the mess actively block this task? If you can't add the feature cleanly without it, refactor (in a separate prior PR). If you can route around it via a seam, log the debt and move on.

Characterization test ↔ "I read it carefully." Pinning costs time and ossifies the current, possibly-buggy behavior (a real cost — you're freezing bugs). Reading is faster but unsafe. The rule: pin anything that touches money, persistent state, or an external contract. For a pure read of a cosmetic, side-effect-free helper, careful reading may genuinely be enough. For submitClaim — which prices money, writes state, and hits an external clearinghouse — it never is.

Match existing convention ↔ introduce the better one. Consistency lowers cognitive load and review friction across the whole team; a unilateral "better" pattern fragments the codebase into dialects. Introduce new conventions deliberately and team-wide (an RFC, a lint rule everyone adopts at once) — never by smuggling your preference into a feature PR where it reads as noise and invites bikeshedding.

Shadow/dual-run ↔ direct cutover. Running both paths doubles the compute for that capability and adds diffing complexity and a comparison harness to build. But for a money or claims path, dual-running is the only way to earn trust before flipping — the cost is cheap insurance against a double-billing incident. You skip it only for genuinely low-risk, trivially-reversible changes where the worst case is a quick revert, not a wave of denied claims.

Tag the original author ↔ review it solo. Pulling the git blame owner onto your PR recovers tribal knowledge no document captured — but it costs their time, and on a long-departed contractor it costs you nothing because there's nobody to tag. The senior calibration: spend a reviewer's attention proportional to the blast radius of the change. A pin-only PR can go to anyone; the flag-flip PR that re-routes live claim pricing should pull in whoever last touched it and whoever owns the consumers downstream. Treat the reviewer list as a knowledge-recovery budget, not a formality.


8. Security & scale notes​

Legacy code predates your current security conventions. Tracing a request through old code routinely surfaces an internal endpoint with no auth, a raw string-concatenated SQL query (Ch 31), or secrets sitting in a checked-in config file. The brownfield rule: map authorization at each seam — do not assume the edge already enforced it (Ch 32). An internal service you're extending may have been written in an era when "internal means trusted," an assumption that's false the moment anything reaches it from outside — and in a PHI system the stakes are not abstract: a broken access check that lets one clinician read another patient's claim or chart is a reportable HIPAA breach, not a bug ticket. Minimum-necessary access is an invariant here, not a nice-to-have.

Characterization tests can pin a vulnerability. This is the subtle one. If you golden-master "current behavior" indiscriminately, you may freeze an insecure default — pinning, say, that the endpoint currently returns another patient's PHI, and then "protecting" that bug forever. So tag security-relevant behavior explicitly: "pin to detect change, but intend to change" — kept separate from the pins whose whole purpose is preservation. Preserve behavior by default; flag the behavior you're preserving only long enough to fix it safely. In a claims/EHR module, the behavior most worth flagging this way is anything that returns data across a patient or tenant boundary — freezing that is freezing a breach.

Migration data integrity at scale. When you dual-run a claim/authorization path, the cardinal sin is double side effects — two prior-auth reservations, two claim submissions to the clearinghouse. This is why the new path runs in shadow / no-op for writes until it's verified: it computes, you diff, it touches nothing. And when you do flip, an in-flight request must not double-execute, so you lean on idempotency keys (Ch 25): a flag flipped mid-flight, or a retried request, resolves to a single effect because the key dedupes it. Idempotency is what makes a percentage rollout safe rather than exciting — and it's the same mechanism that keeps the original Sev-2, a claim submitted twice, from ever recurring.

Behavior under load during cutover. Percentage rollout interacts with caches and connection pools in ways a staging test never shows. The Pulsely legacy module's global mutable cache is both a correctness bug and a scaling cliff. It never evicts, so it grows forever — a memory leak waiting for the right traffic. It's shared across every request, so one patient's claim data can bleed into another's — and in a PHI system that isn't a glitch, it's a reportable breach where the wrong chart reaches the wrong clinician. And because Node interleaves many requests, two of them can touch the same cache entry mid-update and corrupt it — a race condition (Ch 4 on why shared mutable state and concurrency don't mix). Call it out the moment you insert the seam, because the strangler will route traffic in ways that expose it.

Shadow traffic isn't free. Comparing old vs new on live traffic adds latency and compute, and — easy to miss — the diff logs can capture PHI (diagnosis codes, patient identifiers, the whole claim). So sample (compare 1% of traffic, not 100%), scrub the diff payloads before they hit the log, and time-box the comparison window so you're not shadow-running forever, quietly doubling cost and leaking protected health information into a logging system that was never threat-modeled for it. The scrubForLog in the §5 façade isn't cosmetic — it's the control that keeps a debugging aid from becoming a reportable breach. And a subtler scaling trap: the shadow path issues the same downstream calls as the real path (an extra fee-schedule lookup, an extra DB read per shadowed request), so at 100% shadow you've silently doubled load on every dependency the new path touches — which is the other reason you sample rather than shadow everything.


9. Interview lens & exercises​

Interview questions​

Brownfield questions are where interviewers separate people who've shipped into real systems from people who've only built toy projects. The tell is whether you reach for a safety net by reflex.

"You inherit a 1,500-line claims service with no tests and must add a feature — walk me through your first day."

  • Junior answer: "I'd read through the service top to bottom to understand it, then add my feature where it fits." Reads and edits in place — no net, no seam, no blast-radius thinking.
  • Senior answer: "I find the entry point and trace one real request to confirm the path by running it, not just reading. I pin the current behavior — especially the money and side effects — with characterization tests. I find a seam, sprout the new feature in a tested unit, wire it behind a flag, ship dark, and only then flip. The first day's deliverable isn't the feature; it's the safety net that makes the feature safe to add."

"What's a characterization test, and when would you write a deliberately 'wrong' assertion?"

  • Junior: describes a normal unit test that checks correctness.
  • Senior: "It asserts what the code currently does, to detect change — so when the legacy code prices a claim wrong, I pin the wrong value on purpose, because right now my job is preventing unintended drift, not fixing the bug. I handle nondeterminism by injecting clocks and id factories, and I pin money and external-contract behavior first."

"Your team wants to rewrite a working-but-ugly service. Argue for or against."

  • Junior: "It's messy and hard to work in — a clean rewrite would be better."
  • Senior: "I default to strangler-fig. A rewrite throws away years of encoded edge-case fixes and chases a moving target — it's the canonical way these projects fail. I'd extract one capability behind a façade, shadow-diff it, and ramp. I'd only argue for a rewrite if the old system truly can't be incrementally extended — dead platform, no build, unhirable stack."

"How do you migrate a critical path with zero downtime and a rollback?"

  • Junior: "Deploy the new version and watch the dashboards."
  • Senior: "Expand/contract. Add the new path, shadow-run it with writes no-op'd, diff against the old on real traffic, make every write idempotent so a mid-flight flip can't double-submit a claim, then ramp by percentage behind a flag so rollback is instant. Delete the old path as a separate PR once the burn-down hits zero."

"How do you tell which code is safe to delete?"

  • Junior: "If nothing references it in the IDE, it's dead."
  • Senior: "Static reference search is necessary but not sufficient — reflection, cron, queues, and other services don't show up there. I confirm with runtime usage logs/metrics over a full business cycle, then delete in a small, easily-reverted PR so an unexpected caller is a one-click recovery, not an incident."

Exercises & the Pulsely increment​

Do these on the real Pulsely repo. The goal is fluency under realistic mess.

  1. Map drill. On the Pulsely repo, produce a dependency graph (dependency-cruiser or madge), find the top-3 files by churn × coupling (git log churn crossed with import count), and hand-draw the request spine for POST /claims: controller → ClaimService → repository/DB → external clearinghouse/eligibility calls, marking every seam where a test or the strangler could attach. Plot the modules on a tech-debt quadrant (churn on x, coupling on y) and circle the high/high danger zone.

  2. Git-archaeology drill. Use git log -S "* 0.029" and git blame -w -C to reconstruct why that magic adjustment factor exists in the claim-pricing math — who added it, in what commit, referencing what ticket (a payer contract? a one-off fee-schedule tweak?). Write the one-line TODO(DEBT-…) note that captures the what / why / interest-rate / fix-cost so the next engineer never has to repeat your dig.

  3. The Pulsely increment — inherit and extend the mess. You're handed the deliberately ugly ClaimService: ~1,400 lines, mixed concerns, magic numbers, a global mutable cache, no tests. Your task: add "reserve a prior-authorization unit on claim submission" (decrement the patient's remaining authorized visits — a finite resource with a real side effect) without changing any existing behavior. Execute Phase 1 / Phase 2 in order — (a) write characterization tests that pin the current claim totals and side effects (the clearinghouse submission), handling nondeterminism by injecting a clock and a uuid factory; (b) insert an object seam for the prior-authorization collaborator; (c) sprout the reservation logic in a fresh, fully-tested unit; (d) wire it behind a feature flag and ship dark; (e) verify the legacy method's pinned behavior is byte-for-byte unchanged. The deliverable is the safety net plus the feature behind a flag — not a refactor of the legacy method.

  4. Strangler ADR. Author the migration plan to extract the claim-pricing / fee-schedule logic out of the monolithic ClaimService into a new FeeScheduleService. In full Context → Decision → Alternatives → Consequences form (Ch 39), specify: the routing façade that fronts both paths (doubling as an anti-corruption layer that translates the legacy claim shape to the new service's domain model); the shadow/dual-run comparison (writes no-op, outputs diffed on sampled live traffic, PHI scrubbed); idempotency keys so a mid-flight flag flip can't double-submit a claim; the percentage-rollout ramp; and — the part juniors omit — an explicit exit criterion for deleting the old code path (burn-down of legacy call sites hits zero, diff mismatch rate under threshold for N days), executed as its own revertable PR. An ADR without a kill-the-old-path criterion is a plan to run two systems forever.


Key takeaways​

  • Brownfield is the job. The large majority of senior backend work is modifying code you didn't write — and it's harder than greenfield, because invisible invariants and live consumers make the downside immediate and the safety net absent.
  • Legacy code is code without tests (Feathers). Danger is the missing net, not the age. Add the net before you touch anything.
  • Change is two phases: make it safe (pin behavior with characterization tests, find a seam), then make the change (sprout behind a flag). Never both at once.
  • A characterization test asserts what the code currently does, to detect change — not what it should do. Pin the bug on purpose; fix it deliberately and separately.
  • Read a codebase by entry points → one traced (and run) request → the minimal change surface. Mine git history as docs; cross churn with coupling to find the danger zone.
  • Migrate with the strangler fig and expand/contract: add the new path, shadow-diff it on real traffic with writes no-op'd, make it idempotent, ramp by percentage, delete the old path as a separate PR.
  • Manage tech debt as a portfolio (principal vs interest): record it, prioritize by interest, pay it down within your change footprint — don't gold-plate, don't moralize.
  • Don't rewrite. The mess encodes edge-case truth; rewrites discard it and chase a moving target. Strangle unless the old system genuinely can't be extended.

← Previous: Ch 39 — Software Architecture & Service Boundaries · Up: Part VIII overview · Master TOC · Next: Ch 41 — System Design Mastery →