Lesson 8 of 28Keeping code healthy
Technical Debt
Treat debt as a financial decision: find where the interest is paid, choose what to fix, and win the time to fix it in business terms.
In your second month, sprint planning stalls on one ticket. Product wants a new refund rule. The lead says it is three days of work, "because refunds touch the old billing module". Product asks why a rule change costs three days when a new page cost one. Someone says "tech debt", everyone nods, and nothing changes. Six months later the same module causes two incidents and a new hire spends a week understanding it. Every team has this conversation. The engineers who move it forward are the ones who can say where the debt is, what it costs each month, and what fixing it would buy, in words a product manager can put in a roadmap.
Code Smells and Refactoring taught you how to change messy code safely. This lesson is about the decision that comes before that: which mess is worth your team's time, which is not, and how to get the time.
The metaphor, done right
Ward Cunningham coined the term in 1992, in an experience report about a financial system called WyCash. He was explaining to his managers why the team kept reworking code that already worked. His point was financial: shipping before you fully understand a problem is like borrowing money. It lets you move faster now. But until you go back and fold what you have learned into the code, you pay interest on every change.
The two parts of the metaphor do real work:
- Principal is the cost of fixing the problem: the days to restructure the billing module so it matches how billing actually works today.
- Interest is the extra cost you pay every time you work around it: the two extra days on each refund ticket, the incident caused by a hidden coupling, the week a new hire spends confused.
Cunningham later stressed that he never meant "writing bad code on purpose". Debt, in his sense, is the gap between the code and your current understanding of the problem. You wrote the order model when you thought every order had one shipment. Now you know orders can split. The code was fine when written. It is debt now, because the world it models has moved.
This framing has a practical consequence that most teams miss. Interest is only paid when you touch the code. A tangled module nobody has changed in three years charges nothing. A slightly awkward module that every feature goes through charges you every sprint. Ugliness and debt are not the same thing, and the size of the mess tells you nothing about the size of the bill.
What does this print?
principal = 40 # hours to fix the module properly interest = 6 # extra hours per change while it stays messy changes_per_month = 4 saved, months = 0, 0 while saved < principal: saved += interest * changes_per_month months += 1 print(months)
The four kinds of borrowing
Martin Fowler's technical debt quadrant (2009) sorts debt along two axes. Was it deliberate or inadvertent? Was it prudent or reckless? The quadrant matters because the right response is different in each corner.
| Reckless | Prudent | |
|---|---|---|
| Deliberate | "No time for tests on the payment code, just ship it." | "We launch on one database region and write down the plan for when traffic needs a second." |
| Inadvertent | "What is a transaction?" The team did not know enough to see the problem. | "Now that we have run it for a year, we know how it should have been built." |
Prudent deliberate debt is a real business tool. A startup that ships a simple design to hit a launch date, knowing what it will cost later, is borrowing sensibly. The key word is knowing: it is written down, with the trigger for paying it back ("when we pass 10,000 orders a day").
Prudent inadvertent debt is unavoidable. You learn the domain by building in it, so some of your early design will always be wrong in hindsight. That is not a failure. Failing to update the code once you know better is.
Reckless debt, in either form, is the expensive kind. Reckless deliberate debt is usually a pressure problem: deadlines treated as more important than correctness in code where correctness is the product. Reckless inadvertent debt is a skills and review problem. You fix it with mentoring, code review and design discussions, not with a refactoring sprint, or the team will rebuild the same mess.
Match each situation to its corner of the debt quadrant.
Debt is not only in the code
When people say "tech debt" they usually mean messy functions. Real teams carry several kinds, and some of the most expensive never show up in a linter.
| Kind | What it looks like | How the interest shows up |
|---|---|---|
| Code | Long functions, duplicated rules, primitive obsession | Slow changes, bugs in edge cases |
| Architecture | A cycle between orders and billing, one database shared by four services | Changes need several teams, deploys must be coordinated |
| Test | No tests on billing, a flaky suite people rerun until green | Fear of change, slow merges, escaped bugs |
| Dependency | Two majors behind on the web framework, an unmaintained library | Security patches you cannot apply, upgrades that grow harder every month |
| Infrastructure | Hand-built servers, a deploy that only one person can run | Slow recovery, risky releases |
| Documentation | No runbook for the nightly job, a README that lies | Long incidents, slow onboarding |
| Knowledge | One engineer understands the pricing engine | The bus factor: if they leave, the team stalls |
Dependency debt compounds in a way code debt often does not. One major version behind is a weekend. Three majors behind, with breaking changes stacked on breaking changes and libraries that dropped support for your version, is a quarter. The interest rate rises the longer you wait, which is why teams that use Renovate or Dependabot and take small upgrades often rarely face the big ones.
Knowledge debt is the one managers feel most, because it shows up as risk. It is also cheap to pay down: pairing, rotating who takes tickets in that area, and writing the three-page doc the expert has in their head.
Find it with data, not opinions
Ask five engineers where the debt is and you get five answers, each shaped by the code that annoyed them last week. A better start is the version history you already have. Adam Tornhill's idea of hotspots (from Your Code as a Crime Scene) is simple: debt matters where complex code is also frequently changed. Complexity alone is not enough, because complex code nobody touches charges no interest. Churn alone is not enough, because a simple config file can change daily at no cost.
Run these in any repo:
# Churn: how many commits touched each file in the last yeargit log --since="12 months ago" --format=format: --name-only \ | grep -v '^$' | sort | uniq -c | sort -rn | head -20# Complexity: cyclomatic complexity per function (Python)radon cc -s -a src/# Who knows this code? Commits per author for one areagit shortlog -sn --no-merges --since="12 months ago" -- src/billing/For TypeScript, the ESLint complexity rule reports the same idea per function, and lizard works across many languages. Exclude generated files, lockfiles and migrations from the churn list, or they will crowd out the real signal.
Then combine the two. Here is a small hotspot scorer working on the exact text git log --name-only prints, with complexity numbers like a tool would give you.
Press Run (⌘ Enter) to see what happens.Look at legacy/fax_gateway.py. It is the most complex file by far, and the one every engineer complains about. It also changed once in a year. billing/invoice.py is half as complex and changed seven times, so it scores more than three times higher. That is where the next refund ticket will hurt, and where a refactor pays back fastest. Try changing the fax gateway's complexity to 300 and run it again: it still ranks well below invoicing.
Two cautions. A hotspot list is a starting point for a conversation, not a verdict. Ask the people who work in the top files whether the pain is real. And the git shortlog output adds the knowledge dimension: if one person wrote 90% of the commits to your top hotspot, you have code debt and knowledge debt in the same place, and that is the riskiest spot in the codebase.
Paying it down without a rewrite
There is no one method. Strong teams combine several, matched to the size of the debt.
The boy-scout rule. Leave the code a little better than you found it. When a ticket takes you into a messy function, rename the confusing variable, extract the block you had to read three times, add the test you wished existed. This handles small debt for free, and because it follows feature work, it automatically lands in the hotspots. Keep those cleanups in their own commits, as you saw in Code Smells and Refactoring.
Tie debt to feature work in the same area. The cheapest moment to restructure the billing module is when you are about to change it anyway. You already have the context loaded, the reviewer is already looking at it, and the business is already waiting on that area. "The refund rule is 3 days, or 5 days with the restructure, and then the next three billing tickets drop from 3 days to 1" is an easy conversation.
A standing capacity allocation. Many teams reserve a slice of every sprint, often somewhere around 10 to 20%, for debt and platform work the team chooses. It is a heuristic, not a law. The value is predictability: you do not have to win a fight every sprint, and product can plan around a known number.
Deprecation with a removal date. For dependency and architecture debt, the move is parallel change at team scale: announce the replacement, give a date, track who still uses the old path, and delete it. A deprecation without a date is a second permanent API.
Week 0
Announce with a date
The new `/v2/reports` is live. The old endpoint logs a warning and returns a `Deprecation` header. The removal date goes in the changelog and the team channel.
Weeks 1-6
Track remaining callers
A dashboard counts calls to the old path by client. Each owning team gets a ticket with the date on it.
Week 7
Brownout
The old endpoint fails for one hour on a quiet day. Anyone still calling it finds out now, not on removal day.
Week 8
Delete
The calls are at zero. The code, the tests and the feature flag are deleted in one small PR. The interest stops.
Big debt gets planned like a feature. Architecture debt, like splitting a shared database, will not fit in a boy-scout cleanup or a 15% slice. It needs a design doc, a sequence of releasable steps (strangler fig, branch by abstraction) and a place on the roadmap with an owner.
Deciding what not to pay
Saying no to debt work is as important as saying yes. Leave debt alone when:
- The code rarely changes. As the hotspot run showed, interest is near zero.
- The code is going away. If the feature is being sunset next quarter, polishing it is waste.
- The fix costs more than years of interest. Run the break-even sum. A 3-month restructure to save one hour a month does not pay back.
- You do not yet understand the domain. Restructuring around your current guess can create new prudent-inadvertent debt. Sometimes the right move is to wait one more feature and learn.
Cost of delay sharpens the decision. Some debt has a flat interest rate. Other debt has a deadline: a framework version losing security support in June, a database nearing its storage limit, a single expert going on parental leave. That debt jumps up the list even if today's interest is low, because waiting gets more expensive on a known date.
Making the business case
"We need to refactor because the code is messy" loses to any feature request, because it describes engineering's feelings, not the business's costs. Translate debt into things a product manager or director already tracks:
- Lead time. "Billing changes take 3x longer than other areas: median 9 days from first commit to production, against 3 elsewhere."
- Incidents. "4 of last quarter's 7 incidents started in the billing module."
- Change failure rate. "1 in 4 billing deploys needs a hotfix."
- Onboarding. "New engineers take 3 weeks before their first billing PR."
- Risk. "Our web framework version stops getting security patches in 5 months."
Lead time and change failure rate come from the DORA research on software delivery, so many leaders already know and trust them. You can usually pull them from your issue tracker, Git history and incident log in an afternoon.
Then write it down on one page. A short proposal travels further than a meeting, because your manager can forward it.
# Proposal: restructure refund handling in billing
## Problem (in business terms)
Refund and billing changes take a median 9 days to ship, against 3 days
elsewhere. 4 of 7 incidents last quarter started in this module.
## Evidence
- Hotspot analysis: billing/invoice.py is the top file by churn x complexity.
- 3 of the next 5 roadmap items touch refunds.
- One engineer has 80% of commits here (knowledge risk).
## Proposal
Split refund rules out of invoice.py behind an interface, with
characterization tests first. Done in 4 releasable steps.
## Cost
About 8 engineer-days, alongside the Q3 refund-rule ticket.
## Expected payoff
Refund tickets from ~3 days to ~1. Payback within the next 3 roadmap items.
## How we will know
Track median lead time for billing PRs and billing incidents for 2 quarters.
## Risk of doing nothing
Lead time keeps rising as rules pile up; the knowledge risk stays.The last two sections matter most. "How we will know" makes it a bet that can be checked, which builds trust for the next proposal. "Risk of doing nothing" makes inaction a choice someone has to own.
It starts as a feeling. Feelings are a good signal and a weak argument.
Keep a debt register, but keep it small
A debt register is a list of known debt the team has decided to track. It turns hallway complaints into something you can prioritize. Most teams keep it as labelled tickets in the normal tracker, so debt competes in the same backlog as features instead of living in a forgotten document.
Record, for each item:
- Area: the module or system, ideally matching your hotspot names.
- Impact: the interest in concrete terms ("adds ~2 days to each refund change").
- Cost to fix: a rough size, not a precise estimate.
- Cost of delay: any deadline, such as an end-of-support date.
- Trigger: when it should be paid ("before the EU launch", "next time we touch refunds").
- Owner: who decides, not necessarily who does the work.
What not to record: every smell, every TODO, every function someone dislikes. A register with 400 entries is noise nobody reads, and it hides the six items that matter. Small debt goes to the boy-scout rule. Only debt that needs a decision goes on the list. Review it once a quarter and close items that no longer matter. Deleting stale entries is part of keeping it useful.
Put the steps of getting a debt fix funded in order.
- Tap the steps below in the right order.
For the structure behind answers like this, see Behavioral Interviews and STAR. The pattern that makes debt stories land: specific evidence, a small and safe plan, a business result, and something you learned.
- technical debt
- The gap between the code and your current understanding of the problem, which makes every change in that area cost extra.
- principal
- The one-time cost of fixing a piece of debt properly.
- interest
- The recurring extra cost of working around debt, paid each time you change the affected code.
- debt quadrant
- Fowler's grid sorting debt as deliberate or inadvertent and prudent or reckless.
- hotspot
- Code that is both complex and frequently changed, where debt costs the most.
- bus factor
- How many people would have to leave before nobody understands an area of the code.
- debt register
- A short, reviewed list of known debt items with impact, cost, cost of delay and owner.