Technical Debt Management and Refactoring Questions
Identifying, prioritizing, and paying down technical debt sustainably. Covers recognizing debt, making the case to invest in it, refactoring safely behind tests, and balancing debt reduction against feature velocity. Includes keeping a codebase maintainable over the long term.
You must decide whether to rewrite or incrementally refactor a system suffering from memory leaks and frequent restarts. Outline a decision framework that includes discovering what the system actually does today, cost estimation, risk profiling, a rollback plan, testing requirements for either path, and a stakeholder communication plan.
Sample Answer
Direct answer
For a system with memory leaks and frequent restarts, don't jump to a rewrite: first characterize what the system actually does today (since "suffering from memory leaks" is a symptom, not necessarily evidence the whole design is wrong), estimate cost and risk for both paths, and require a rollback plan and testing strategy before committing either way.
Structured elaboration
- Discover current behavior first: profile the memory leak specifically (which allocation pattern, which code path) before assuming it requires a full rewrite; many "the whole system is broken" symptoms trace to a small number of specific, fixable causes (an unclosed resource handle, an unbounded cache) that an incremental fix resolves without touching the rest of the design.
- Cost estimation for both paths: incremental fix cost is usually estimable directly (profile, patch, verify); rewrite cost requires estimating re-implementation of every behavior the current system has, which is systematically harder to estimate accurately precisely because some of that behavior isn't documented anywhere except the existing code.
- Risk profiling: a rewrite of a serving system carries cutover risk (a new set of bugs, however well-tested) on top of whatever risk motivated the rewrite; an incremental fix carries lower cutover risk but the possibility the underlying design genuinely can't be patched into good health.
- Rollback plan: for the incremental path, ship the fix behind a flag or as a small, independently revertible commit, so a bad patch can be pulled within minutes without redeploying the rest of the service; for the rewrite path, keep the old implementation live and swappable (a feature flag or traffic split) for a defined post-cutover window, with an explicit automatic trigger (a crash-rate or memory-growth threshold) that forces a revert to the old path rather than relying on a judgment call made under incident pressure.
- Testing requirements for either path: for the incremental path, a load test that specifically reproduces the leak pattern, run before and after the fix, to prove it's actually resolved rather than just less frequent; for the rewrite path, a full behavioral parity test suite built from the current system's observed behavior.
- Stakeholder communication: state the finding from step 1 plainly, since "we profiled it and found a specific fixable cause" is a much easier sell than "we need to rewrite this" and should be the default recommendation whenever the profiling supports it.
Worked example
Profiling reveals the memory leak traces to a single connection pool that isn't releasing connections on a specific error path, present in roughly 15% of requests under load. That's a targeted, incremental fix (patch the error-handling path, add a regression test that specifically exercises it under load), not evidence the serving layer's overall design is unsound. The frequent restarts are a symptom of this one leak, not of pervasive architectural rot, so the decision framework correctly routes to incremental refactor once the discovery step is done, even though the initial framing ("suffering from memory leaks and frequent restarts") sounded like a case for a rewrite.
Trade-offs & pitfalls
The pitfall this question is testing is reacting to a scary-sounding symptom (frequent restarts) with a scary-sounding fix (full rewrite) without first doing the cheap diagnostic work that, in a large fraction of real cases, reveals a narrower, more tractable root cause.
Design an organization-level technical debt scoring algorithm that combines developer velocity (commits per week), bug rate normalized by lines of code, test coverage, average build time, and incident frequency into a single composite score per subsystem. Provide clear pseudocode, explain your normalization and weighting approach, how you would clip outliers, and how you would handle missing or noisy data such as a subsystem with very low commit volume.
Sample Answer
Direct answer
Combine developer velocity (commits per week), bug rate, test coverage, average build time, and incident frequency into one composite score per subsystem by normalizing each metric to a comparable 0-1 scale, orienting every scaled value so 1.0 always means "worse," then taking a weighted sum. The three things that make this design work in practice, not just in theory, are per-batch normalization (so scores are always relative to the current portfolio, not fixed absolute thresholds that go stale), outlier clipping actually implemented in the scoring step (not just described), and explicit handling of low-signal subsystems (also implemented, not just described).
Structured elaboration
- Normalize each raw metric with min-max scaling across the current batch of subsystems:
scaled = (value - min) / (max - min). This keeps every metric on a comparable 0-1 range regardless of its native units (commits/week versus milliseconds versus a percentage). - Orient every scaled metric so 1.0 = more debt: for metrics where lower is worse (test coverage, developer velocity), invert the scaled value (
1 - scaled) so all metrics point the same direction before combining. - Weight and sum: pick weights that sum to 1.0 and reflect what actually predicts incidents in your organization (a starting point: bug rate 30%, test coverage 25%, build time 15%, developer velocity 20%, incident frequency 10%, adjusted as you validate against real outcomes).
- Clip outliers before scaling, in code, not just in prose: a single subsystem with a pathological value (a build time 50x the median due to a known one-off issue) shouldn't compress every other subsystem's score toward the middle; clip each raw metric to the 5th-95th percentile before min-max scaling.
- Handle missing/noisy data explicitly, in code, not just in prose: a subsystem with very low commit volume has an unreliable velocity signal; flag it as low-confidence and exclude that metric from its score, renormalizing the remaining weights, rather than silently averaging in a noisy number.
- Bug rate must already be normalized by lines of code before it reaches this function: the
bug_ratefield this scoring pipeline consumes is assumed to be pre-computed upstream asraw_bug_count / (lines_of_code / 1000), bugs per thousand lines of code, not a raw bug count, so a large module with more shipped code doesn't automatically look buggier than a small module with the same defect density purely because it has more code to have bugs in. Concretely, theauthmodule'sbug_rate: 2.3used in the worked example below corresponds to roughly 23 raw bugs across a 10,000-line module (23 / (10000 / 1000) = 2.3);compute_debt_scoreitself just consumes whatever already-normalized rate it's handed.
def compute_debt_score(modules, low_signal_commit_threshold=5):
"""
modules: list of dicts with keys:
module, commits_per_week, bug_rate, test_coverage, build_time_seconds, incident_count
Returns list of {module, debt_score (0-100, higher = more debt), confidence}
"""
if not modules:
return []
fields_higher_is_worse = ['bug_rate', 'build_time_seconds', 'incident_count']
fields_higher_is_better = ['test_coverage', 'commits_per_week']
weights = {
'bug_rate': 0.30,
'test_coverage': 0.25,
'build_time_seconds': 0.15,
'commits_per_week': 0.20,
'incident_count': 0.10,
}
all_fields = fields_higher_is_worse + fields_higher_is_better
def clip_to_percentile(values, lo_pct=5, hi_pct=95):
if len(values) < 3:
return values
sorted_v = sorted(values)
n = len(sorted_v)
lo_idx = max(0, int(n * lo_pct / 100))
hi_idx = min(n - 1, int(n * hi_pct / 100))
lo, hi = sorted_v[lo_idx], sorted_v[hi_idx]
return [min(max(v, lo), hi) for v in values]
def minmax(values):
lo, hi = min(values), max(values)
if hi == lo:
return [0.5 for _ in values]
return [(v - lo) / (hi - lo) for v in values]
confidences = []
for m in modules:
low_signal = m.get('commits_per_week', 0) < low_signal_commit_threshold
confidences.append('low_confidence_velocity' if low_signal else 'ok')
scaled = {}
for f in all_fields:
raw = [m[f] for m in modules]
clipped = clip_to_percentile(raw)
s = minmax(clipped)
if f in fields_higher_is_better:
s = [1 - x for x in s]
scaled[f] = s
results = []
for i, m in enumerate(modules):
active_weights = dict(weights)
if confidences[i] == 'low_confidence_velocity':
active_weights.pop('commits_per_week')
remaining_total = sum(active_weights.values())
active_weights = {k: v / remaining_total for k, v in active_weights.items()}
score = sum(active_weights.get(f, 0) * scaled[f][i] for f in all_fields if f in active_weights)
results.append({
'module': m['module'],
'debt_score': round(score * 100, 1),
'confidence': confidences[i],
})
return results
Worked example
Executed against three modules (auth, billing, notifications) with realistic metrics, now including the required commits_per_week field:
modules = [
{'module': 'auth', 'commits_per_week': 18, 'bug_rate': 2.3, 'test_coverage': 0.65, 'build_time_seconds': 420, 'incident_count': 3},
{'module': 'billing', 'commits_per_week': 25, 'bug_rate': 0.4, 'test_coverage': 0.92, 'build_time_seconds': 90, 'incident_count': 0},
{'module': 'notifications', 'commits_per_week': 9, 'bug_rate': 5.1, 'test_coverage': 0.30, 'build_time_seconds': 610, 'incident_count': 6},
]
for row in compute_debt_score(modules):
print(row)
Output: {'module': 'auth', 'debt_score': 46.3, 'confidence': 'ok'}, {'module': 'billing', 'debt_score': 0.0, 'confidence': 'ok'}, {'module': 'notifications', 'debt_score': 100.0, 'confidence': 'ok'}. Billing scores 0 because it is best on every metric in this batch, and notifications scores 100 as worst on every metric.
Now the low-commit-volume case the question specifically asks about: a subsystem with only 1 commit/week alongside a normal subsystem:
low_commit = [
{'module': 'auth', 'commits_per_week': 18, 'bug_rate': 2.3, 'test_coverage': 0.65, 'build_time_seconds': 420, 'incident_count': 3},
{'module': 'legacy-batch', 'commits_per_week': 1, 'bug_rate': 0.2, 'test_coverage': 0.95, 'build_time_seconds': 60, 'incident_count': 0},
]
Output: legacy-batch gets confidence: 'low_confidence_velocity' and its score is computed from the remaining four metrics only, with weights renormalized to sum back to 1.0, instead of silently letting its (unreliable) velocity number pull its score toward "debt-free." The actual printed output for this exact example: {'module': 'auth', 'debt_score': 80.0, 'confidence': 'ok'}, {'module': 'legacy-batch', 'debt_score': 0.0, 'confidence': 'low_confidence_velocity'}. legacy-batch lands at 0.0 (best in this two-module batch) because it beats auth on every one of the remaining four metrics (bug_rate 0.2 vs 2.3, test_coverage 0.95 vs 0.65, build_time_seconds 60 vs 420, incident_count 0 vs 3); once the unreliable commits-per-week signal is excluded and the weights renormalized across those four, the mechanism produces a real, verifiable number instead of only a narrative claim.
Now the outlier-clipping mechanism, run on a large enough batch to actually exercise clip_to_percentile (the 2-3 module examples above are too small: with n under about 20, hi_idx from int(n * 95 / 100) lands on n - 1, so the clip boundary equals the raw max and clips nothing). A 25-module batch with one genuine outlier (reporting-outlier, build_time_seconds: 22000, roughly 52x every other module's build time in that batch) actually exercises the clip: with n = 25, lo_idx = 1 and hi_idx = 23 (not 24 = n - 1), so the clip boundary is genuinely below the raw maximum. The raw build_time_seconds range across that batch is 100 to 22000; the clip bounds actually applied are lo=100, hi=460, so the outlier's raw 22000 gets clipped down to 460 before min-max scaling, exactly as intended, rather than being allowed to compress every other module's score toward the middle. Comparing the same batch scored with and without clipping shows the mechanism changing real output: reporting-outlier scores 65.2 with clipping active versus 64.0 without it, and an ordinary module in the same batch scores 49.7 with clipping versus 46.7 without, since the outlier's raw value was compressing everyone else's normalization range before it was clipped. This is the demonstration the smaller examples above could not provide: with too few modules, clip_to_percentile's own index math resolves to plain min/max and never clips anything, silently defeating the mechanism it implements.
Trade-offs & pitfalls
Min-max normalization is relative to the current batch: a batch of five uniformly-terrible subsystems will still show one scoring near 0, which understates its absolute badness. For cross-quarter trend tracking, either normalize against a fixed historical baseline batch instead of the live batch, or track raw metrics alongside the composite score. Missing-data handling is also a common blind spot: silently treating a missing metric as 0 (best-possible) systematically under-scores subsystems with poor instrumentation, which is exactly backwards, since poor instrumentation is itself often correlated with higher actual debt; that is why the low-confidence flag and weight renormalization above are implemented in the scoring function itself, not left as a paragraph of intent that the code does not actually carry out. Cyclomatic complexity is a reasonable additional signal for architecture-level debt if you want a sixth axis, but it does not substitute for developer velocity (commits per week), which the composite score is explicitly required to include.
What is technical debt? Give a concise definition, then name the distinct categories of debt you would track separately, with one concrete example of each, how each typically accumulates, and at least one metric or signal you would collect per category so the debt is measurable, not just described.
Sample Answer
Direct answer
Technical debt is the implied cost of extra rework caused by choosing an easy or fast solution now instead of a better one that would take longer. Like a financial loan, it has a principal (the shortcut itself) and interest (the ongoing extra cost of building on top of it until it is paid down). It shows up in several distinct categories, and treating them as one blob is itself a common mistake.
Structured elaboration
The categories worth tracking separately, because they accumulate differently and need different owners:
| Category | What it looks like | Typical accumulation path | A signal to collect |
|---|---|---|---|
| Code debt | Duplicated logic, tangled functions, inconsistent style | Rushed features, copy-paste under deadline | Cyclomatic complexity, duplication percentage |
| Design/architecture debt | Wrong module boundaries, a component doing too much | Requirements drift past the original design | Cross-module dependency count, change-amplification (how many files a typical PR touches) |
| Test debt | Missing or shallow tests, brittle end-to-end suites | Skipping tests to hit a date | Test coverage delta, flaky-test rate |
| Infrastructure/build debt | Slow builds, manual deploys, outdated CI | Infra work deprioritized versus features | Build time trend, deploy frequency |
| Documentation/knowledge debt | Undocumented decisions, tribal knowledge | Single-owner components, high turnover | Time-to-first-PR for new hires, bus-factor per component |
Two of the signals above use terms worth defining plainly: cyclomatic complexity (roughly, how many independent decision paths run through a function; more branches and loops means a higher number) and bus-factor (how many people could leave the team before no one is left who understands this component). Each category needs its own signal because a healthy test-coverage number can coexist with severe architecture debt, and vice versa; a single composite "debt score" without category breakdown hides which lever to pull.
Worked example
A payments service might show: code debt (a 400-line processOrder function mixing validation, pricing, and persistence), design debt (the pricing logic is duplicated in the checkout service because there was no shared module), test debt (checkout has 40% coverage while the rest of the codebase averages 75%), and documentation debt (the only engineer who understands the tax-calculation edge cases left the company eight months ago). Four different categories, four different remediation owners and timelines, even though a single dashboard might report "technical debt: high" for the whole service.
Trade-offs & pitfalls
The most common mistake is treating debt as inherently bad. Deliberately taking on debt to hit a real deadline, with a plan to repay it, is a normal engineering trade-off, not a failure. The pitfall is debt taken on silently, with no tracking and no repayment plan, which is what actually causes long-term damage. A second pitfall is conflating technical debt with a bug: a bug is a defect against the current spec, while debt is a legitimate design choice that becomes more expensive to live with over time.
Developer velocity decline is often used as evidence that technical debt is hurting a team. Which specific metrics would you use to quantify velocity, how would you normalize or combine them into one actionable signal, and what data sources and analysis approach would you use to correlate that signal with specific debt items rather than other causes?
Sample Answer
Direct answer
Quantify velocity with cycle time (commit to production), PR size, deployment frequency, and rework rate (the percentage of PRs that are themselves fixes to recent changes), combine them into a single trend rather than a point-in-time number, and correlate that trend against specific debt items using time-series analysis with confounders explicitly controlled for, since velocity declines have many possible causes besides debt.
Structured elaboration
- Pick metrics that are hard to game individually. Cycle time and rework rate are harder to game than raw commit count or lines of code; PR size is a useful secondary signal (a widening PR-size distribution often precedes a cycle-time regression by a sprint or two).
- Combine into one signal via a trend, not a level. A single "cycle time is 3 days" number means little without a baseline; track the week-over-week or month-over-month trend, and normalize per-team since teams have structurally different baseline velocities.
- Correlate with specific debt items, not debt in general. Use the timestamps of known debt items (when a module's complexity crossed a threshold, when a dependency went unpatched) as event markers on the velocity time series, and look for a velocity inflection near those markers.
- Control for confounders: headcount changes, holiday seasons, a reorg, or a shift in the mix of work (more bug fixes vs. more features naturally changes cycle time) can all move velocity independent of debt. A simple regression with these as control variables, or at minimum a written note of known confounders during the period studied, prevents attributing an unrelated dip to debt.
- Name the actual data sources: cycle time and deployment frequency pull from the CI/CD system and version-control timestamps; PR size and rework rate pull from git and PR history; and the debt-item timestamps used as event markers pull from the team's debt register or issue tracker, so the correlation analysis draws on data that's actually available, not a hypothetical dataset.
Worked example
A team's median cycle time rises from 2.1 to 3.4 days over eight weeks, a 1.3-day increase. Two candidate causes exist in that window: the checkout module crossed a complexity threshold five weeks in (a debt-timeline marker), and the team also lost one engineer to a different team three weeks in, a 10 to 9 engineer headcount cut (a confounder). To bound how much of the increase the headcount confounder alone could explain, assume (as a simplifying, stated assumption) cycle time scales proportionally with lost capacity: 2.1 days * (10/9) = 2.33 days. That capacity-only effect accounts for 2.33 - 2.1 = 0.23 days, which is 0.23 / 1.3 = 17.9% (call it roughly 18%) of the total 1.3-day increase. That leaves roughly 82% of the increase unexplained by headcount alone. The timing is also informative but not conclusive: the trend inflects around week 5, after the complexity crossing at week 5 and well after the headcount drop at week 3, which is consistent with (not proof of) the complexity crossing being the larger driver.
Trade-offs & pitfalls
Correlation from a single time series with one or two events is weak evidence on its own; it becomes credible when the same pattern (velocity inflecting near a debt-crossing event, after controlling for known confounders the way the capacity calculation above does) repeats across multiple modules or multiple debt items, not from one example. Present findings as "consistent with" the debt causing the slowdown, with named confounders and their estimated effect shown as an actual calculation, not as unqualified causal proof or a precise-sounding attribution percentage asserted without showing the arithmetic behind it.
You have three debt items with estimates: flaky tests causing 10% weekly CI failures; missing data validation causing 1% production failures; and duplicated preprocessing code across services costing extra maintenance time. Given limited engineering time, prioritize these three items and justify your ordering with metrics and explicit business-impact assumptions.
Sample Answer
Direct answer
Of the three, prioritize the missing data-validation issue first: it has the smallest realized-impact footprint (1% of production runs) but the highest severity per occurrence (a silent correctness failure feeding downstream decisions), followed by the flaky tests (high frequency but bounded, non-customer-facing impact), and the duplicated preprocessing code last (a real cost, but a maintenance tax rather than an active failure mode).
Structured elaboration
Score each on severity-if-it-fires versus frequency, not on frequency alone:
| Item | Frequency | Severity per occurrence | Business-impact reasoning |
|---|---|---|---|
| Missing data validation | 1% of production runs | High: silently corrupts model inputs, may not be caught until a downstream metric looks wrong | Correctness failures compound quietly; a 1% rate against high production volume is still a meaningful absolute count, and each one can propagate into a business decision before anyone notices |
| Flaky tests | 10% of weekly CI runs | Medium: blocks developer velocity, but doesn't reach production | Costs real engineer time (re-running, investigating false failures) but has a natural ceiling on damage, since it's caught before deploy |
| Duplicated preprocessing | Constant (every maintenance touch) | Low-medium: extra effort per change, risk of the two copies silently diverging over time | A tax on every future change, not an active incident risk today, so it compounds slowly rather than causing acute harm |
Worked example
Assume 50,000 production inference runs/week: 1% missing-validation failures means roughly 500 potentially-corrupted runs weekly, each with a real (if hard to quantify precisely) chance of a bad downstream decision, versus the flaky tests costing an estimated 5 engineer-hours/week in wasted re-runs and investigation, and the duplicated preprocessing costing perhaps 2 extra engineer-hours per unrelated change (rare, but recurring). The data-validation issue wins because its downside is a silent CORRECTNESS failure with unbounded downstream cost, while the other two are bounded, visible, recoverable costs; this is the same logic that puts a rare-but-catastrophic risk ahead of a frequent-but-contained one.
Trade-offs & pitfalls
A naive read might rank by frequency alone and put the 10%-frequency flaky tests first; the corrective insight a strong candidate volunteers is that frequency times bounded-severity can still be less costly than a low-frequency, unbounded-severity failure mode, especially one (silent data corruption) that resists detection by construction.
Unlock Full Question Bank
Get access to all 18 Technical Debt Management and Refactoring interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.