Refactor vs rewrite: How to decide for an existing codebase

Contents
Refactor by default. Rewrite only when the architecture or platform blocks what the business needs and replacing the system costs less than changing it step by step, and even then replace it in slices, not all at once.
That verdict holds for most slow, painful codebases because a rewrite must rediscover every undocumented behavior before it reaches parity. What changes the answer is where the pain sits, what the platform's support window says and whether the team can still hire for the stack. The scored checklist below turns those factors into a threshold you can test against your own system.
Should we refactor or rewrite? The short verdict
Refactor by default: a big-bang rewrite is justified only when the platform or architecture cannot support what the business needs and incremental change costs more than replacement. Even then, replace the system in slices with the strangler fig pattern Martin Fowler described, so the old code keeps serving users until each piece is proven.
Our replatforming and modernization teams follow the same default with existing codebases. We recommend refactoring first when the stack is still supported and you can hire for it, because it delivers value early and keeps working behavior intact. An end-of-life platform, or a data model that blocks core features, shifts the answer toward replacement.
What does it mean to refactor? Refactoring vs rewriting defined
Refactoring restructures code without changing what it does, and a rewrite replaces code with new code that may behave differently. Martin Fowler defines refactoring as changing internal structure to make software easier to understand and cheaper to modify while observable behavior stays the same. Our guide to refactoring covers the depth.
A rewrite scales from one module to the whole system. A big-bang rewrite replaces everything and moves users over on a single cutover date.
The boundary is fuzzy because teams often label a module swap a "refactor" to make it sound safer. Our rule: any change that alters observable behavior or replaces a module wholesale is a rewrite of that part, whatever the team calls it. Plan, test, and review it as one.
A quick check uses characterization tests, which pin down what the code does today. If you have to edit those tests to get a change through, behavior moved, and "rewrite" is the correct word for what you are doing.
Refactor vs rewrite side by side
Refactoring, the strangler fig pattern, and a big-bang rewrite differ most in how soon they deliver value and how much users notice. The table adds incremental replacement as a middle option. Time ranges are illustrative and vary with team size and system age.
| Refactor | Strangler fig / slice | Big-bang rewrite | |
|---|---|---|---|
| Scope | Internal structure of existing modules | One bounded capability at a time, routed through a seam | Whole system replaced |
| Risk | Low per change; characterization tests catch regressions | Moderate; two systems and a routing layer to operate | Concentrated at cutover, plus the feature parity trap |
| Time to first value | First merged change, often days to weeks | First slice live behind a feature flag, often weeks to months | Nothing ships until parity, so close to the full build time |
| Impact on users | Mostly invisible | Gradual, canaried per slice | One cutover, one migration |
| Team skills | Deep knowledge of the current code | Current code plus the target stack and an anti-corruption layer | Target stack; legacy knowledge fades as people leave |
| Cost profile | Small and continuous | Higher total than refactoring, spread across slices while the old system keeps running | Front-loaded, with the roadmap frozen |
| Early failure sign | Single changes keep growing past what a reviewer can hold in mind | Slices go live but the legacy path is never switched off | The parity checklist grows as undocumented behavior surfaces |
Decision rule
We recommend choosing by two conditions: whether the platform can support what the business needs, and whether a seam exists.
- Refactor when the platform is adequate and the pain sits in module structure. Tests must exist or be writable around current behavior.
- Slice when the platform can't support the business and a seam exists, such as an API gateway, a message queue, or a UI route.
- Bounded big-bang when no seam exists, the system is small, and the platform is past end-of-life.
The strangler fig pattern lets each slice earn its place in production before the next begins, so a wrong turn costs one slice, not the whole build.
Slicing breaks down when nothing can intercept calls between old and new, because every slice then needs a seam built first. Watch the failure signs in the last table row. A legacy path that stays live after its slice ships means you are paying for two systems with no end date.
Is the pain local or structural?
Pain is local when it concentrates in a few hot-spot modules that have testable seams, and structural when it follows every feature across layers. Each symptom below feeds one input of the scoring checklist.
Start with data. Mine version control and the issue tracker for code churn and defect hot spots: files that change most often and also collect the most bug-fix commits. Then look at the last ten features shipped and count the layers each one touched.
| Symptom | How to check | Checklist input | Reads as |
|---|---|---|---|
| Churn and bug fixes cluster in a few modules | Rank files by commits times fix commits | Defect hot spots, change frequency | Local |
| A hot-spot module has a clean boundary | Can a test call it through an interface or seam? | Test coverage | Local |
| One feature edit touches UI, services, and schema | Layers touched per feature, last ten features | Change frequency, business goals | Structural |
| Hot spots spread evenly, and no seams exist | Count modules reachable only through shared state | Defect hot spots | Structural |
| One or two people understand the affected code | Bus factor per module | Team knowledge | Raises cost of either path |
The seam test decides the borderline cases. If you can pin a module's current behavior with characterization tests, the pain is local and refactoring is feasible. If you cannot find a place to write one, the coupling is structural.
Two caveats apply. High churn alone is not a defect signal, because a healthy core module under active development also changes often. And structural pain does not by itself justify a rewrite. It means the platform and data-model inputs need scoring, and any replacement should still proceed in slices.
Signals that favor refactoring
Refactoring is the better bet when pain is local, the architecture still supports the roadmap, and the code has seams where tests can attach. Four signals point that way:
- Concentrated hot spots. Churn and bug-fix commits cluster in a few modules, and the rest of the codebase ships without incident.
- Sound structure. The platform and architecture can carry the planned features, and slow delivery traces to tangled code inside that structure.
- Usable seams and interfaces. In Working Effectively with Legacy Code, Michael Feathers defines a seam as a place where you can change behavior without editing in that place. Characterization tests attach there, so you can pin current behavior before touching it.
- Steady feature demand. The business cannot accept a frozen roadmap, and refactoring ships alongside feature work.
Each signal can be misread, so check for these failure modes and their early signs before committing to a refactoring plan:
- Local pain that is spread across modules. The early sign is that every fix, whatever the ticket, touches the same five files (an illustrative threshold). Those files act as a shared dependency that no single-module cleanup removes, so each refactor ends with the next bug in the same place.
- Seams that exist only on paper. The early sign is that the first characterization test needs production code edits or heavy mocking to run at all. The work then starts with creating seams, and the size of that job tells you whether refactoring is still cheap.
- Structure that cannot carry the roadmap. The early sign is that planned features require changes to the data model or service boundaries. Cleaner code inside the same structure leaves those changes blocked.
If the first pattern shows up, stop scoping the work as a refactor and treat it as a structural signal.
When to rewrite code: Signs that favor a rewrite
A rewrite is justified when the platform is end-of-life, security findings trace to the architecture, or the stack can't be staffed. Each of these can be checked against a date, a finding, or a hiring number before the team debates code quality.
- End-of-life platform. Find the vendor's published end-of-life date for the runtime, framework, or database version, and compare it with your realistic migration lead time. If support ends before an upgrade can finish and no paid extended support exists, refactoring adds nothing to safety. A version that is old but still supported is an upgrade task.
- Security findings rooted in architecture. Triage each audit or pentest finding by asking whether a patch or dependency bump closes it. If so, it belongs in the backlog. If closing it means redrawing trust boundaries, such as authorization scattered across every module or tenants sharing tables without isolation, the finding is structural. Several open at once favor replacement.
- A data model that blocks core features. Check whether the next two roadmap items each need a schema change that reaches most of the codebase. If they do, no amount of local restructuring will unblock them.
- Hiring time for the stack. Track time-to-fill for engineers in the language or framework across your last few postings. As an illustrative trigger, not a benchmark, roles open for two quarters while one or two people hold all the knowledge of the legacy modules (a bus factor of 1-2) means the stack is itself a delivery risk.
Two or more of these firing together makes the case for replacement, but not for a big-bang cutover. Put an anti-corruption layer between old and new so the legacy data model doesn't leak into new services, then move one slice at a time. The cost side of that call is covered in when is it worth rewriting a legacy app.
Why big-bang rewrites fail
A big-bang rewrite fails because the team must rediscover every behavior the old system accumulated before the new one can replace it, while the roadmap stays frozen.

Joel Spolsky made the classic case in "Things You Should Never Do, Part I" (2000). He called Netscape's decision to rewrite Netscape Navigator from scratch "the single worst strategic mistake that any software company can make." His mechanism is that old code looks ugly because it carries bug fixes, and each fix records something learned in production.
Three things compound from there:
- The feature parity trap. Nobody holds a complete list of what the old system does. Pricing edge cases, timezone handling and partner quirks live in code and in user habits. Without characterization tests that pin current behavior first, parity is reached one escaped defect at a time, and the finish line moves with each discovery.
- A frozen roadmap. Product keeps requesting features. Either they are built twice, once in the old system and once in the new, or they wait. Value arrives only at cutover, so the team gets no early signal on whether the estimate holds.
- The second-system effect. In The Mythical Man-Month, Fred Brooks describes how designers of a second system tend to load it with the ideas they set aside the first time. A rewrite meant to fix everything (new framework, new data model, new deployment model) invites the same pressure, and scope grows.
All three trace to one decision: cutover happens once, at the end. Spolsky's essay concerns shipped commercial software, so weigh it against your own situation. An internal system on an end-of-life platform may still need replacing, and the guide to rebuilding legacy web apps covers how to do that in slices.
The middle path: Replace the system one slice at a time
The strangler fig pattern replaces a system one slice at a time: new code takes over one capability behind a routing seam while the legacy system keeps serving everything else. Martin Fowler's StranglerFigApplication page describes growing the new system around the old one until the old one can be retired. Each slice ships on its own, so the roadmap never freezes.

Pick the first slice by two properties: low coupling and high change frequency. Low coupling means few inbound callers and few tables shared with other modules, so the seam is cheap to cut. High change frequency, visible in version-control history, means the team feels the payoff early. Notifications, search, and document generation usually qualify. The billing core, which everything joins against, does not.
The seam depends on where the slice lives. The options side by side:
| Seam | Use when | Cutover control |
|---|---|---|
| Reverse proxy or API gateway | The slice is reachable through its own route | Route rules per path |
| Branch by abstraction | The slice is called in-process inside the codebase | Interface with old and new implementations |
In both cases, put the switch behind feature flags. Per-tenant or percentage-based flags give you a canary and a rollback that takes seconds. Before cutover, run a parallel run: send shadow traffic to the new slice and diff its output against the old one. Write characterization tests around the slice first, so the diff has a baseline.
Data consistency is where first slices tend to stall. An anti-corruption layer translates between the legacy schema and the new model, so legacy naming and quirks stay out of the new code. Keep one system of record per entity. If both systems must write, dual write needs a reconciliation job, because the two stores drift without one.
The pattern has limits. If the system is a single binary with shared global state and no interception point, the first slice is a refactor that creates the seam. Set an end-of-life date for each replaced slice and delete the old code, or you will end up maintaining two systems indefinitely.
Rewrite or refactor checklist: Score your codebase
Score refactor vs rewrite by rating five weighted criteria from 0 to 5, where 5 means refactoring cannot fix the problem; a weighted total of 65 or more out of 100 means replacement is worth considering.
The scorecard is our own, and the weights and thresholds are illustrative starting points to tune to your context. Rate each criterion from evidence, using code quality metrics such as code churn and defect hot spots pulled from version control and the issue tracker, not from opinion.
The worked example below assumes a 12-year-old order-management monolith maintained by eight engineers.
| Criterion | Weight | Score (0-5) | Points | Basis in the sample system |
|---|---|---|---|---|
| Business goals the architecture can't support | 30 | 4 | 24 | Multi-tenant isolation is on the roadmap, and the shared schema blocks it |
| Code churn and defect hot spots | 20 | 3 | 12 | Most bugs and edits cluster in two modules |
| Test coverage and testability | 15 | 2 | 6 | Coverage is low, but seams exist, so characterization tests can pin current behavior |
| Team knowledge | 20 | 3 | 12 | Two engineers understand billing; the bus factor is low |
| Budget and runway | 15 | 2 | 6 | Funding covers a multi-quarter program, not a frozen roadmap |
| Total | 100 | 60 |
Points are weight times score divided by 5. The thresholds:
- Below 40: refactor, and keep shipping features.
- 40-64: refactor by default, and replace the single worst slice using the strangler fig pattern.
- 65 and above: consider replacement, still delivered in slices behind feature flags.
The sample system lands at 60. The call is to write characterization tests around the two hot-spot modules, refactor the rest, and strangle the data-model slice that blocks multi-tenancy. No score justifies a big-bang rewrite on its own, because the scorecard says what to replace first, not whether to stop shipping.
Re-score each quarter, since test coverage and team knowledge move.
Refactor or rewrite a mobile app from scratch?
Refactor a mobile app by default, and rewrite from scratch only when its framework is an end-of-life platform; otherwise replace it module by module behind feature flags.
A hard cutover is a poor fit for mobile for two reasons. Store review sits between every merge and every user, so a bad release can't be hotfixed in minutes. Users also stay on old binaries for months, so the backend must serve the old app and the new one at the same time.
The strangler fig pattern fits these constraints. Ship the first module in the new framework (onboarding is a common candidate) inside the existing app, route to it with a remote feature flag, and ramp it up by cohort.
Both code paths ship in the binary, so flipping the flag rolls back without waiting for review. Check the new stack's minimum OS version against your install base before committing.
The exception is a framework past end of support. Microsoft ended Xamarin support on May 1, 2024 (Xamarin support policy). Without security patches or support for new OS SDKs, and with store SDK requirements that keep moving, migration has a deadline, so start slicing now.
If the existing code is too rigid for the features you need, a rewrite of one slice is a fresh start. A rewrite of the whole app is not.
How to run either path safely
Run a refactor or a rewrite in reversible slices: characterization tests pin current behavior, feature flags control exposure, and a parallel run compares old and new output. Each of the three has a failure mode that needs a guard.
Characterization tests can lock in bugs. They record what the code does today, not what it should do, and that includes wrong behavior. Have someone who knows the domain review each recorded assertion and tag it "intended" or "suspected bug". Fix suspected bugs in a separate commit, never inside the refactor.
Parallel runs break in three places. Dual writes double side effects such as emails and payments, so run the new path in shadow mode with writes stubbed. Async ordering makes outputs differ even when the logic matches. Timestamps, generated IDs, and now() calls produce diffs on every request. Normalize those fields, or replay recorded traffic with a frozen clock.
Part-time legacy knowledge raises bus factor. If the only person who understands the pricing rules works two days a week, or has already left for a contractor role, their availability limits slice size. Record walkthroughs of the rules before the slice starts, and pair that person with the slice owner so the knowledge survives the rewrite.
Write exit and abort criteria before each slice begins. Illustrative examples, to be tuned per system:
- Exit: zero unexplained mismatches in the parallel run across one full business cycle, including month-end. The flag then stays at 100% for an agreed soak period, and the old code path is deleted.
- Abort: the unexplained mismatch rate has not fallen across two consecutive sprints, the slice has overrun its estimate by half, or the one person who knows the rules is no longer available.
An aborted slice goes back to the backlog with its findings, and the flag returns traffic to the old path. Incremental replacement keeps that option open, and a big-bang cutover does not.
What each path costs
A big-bang rewrite costs more than a refactor because you pay for two systems, a frozen roadmap, and the feature parity trap before any user sees a benefit. Refactoring spreads a smaller bill across normal delivery, and each slice can ship on its own.
The cost drivers side by side:
| Cost driver | Refactor | Big-bang rewrite |
|---|---|---|
| Running two systems | None, one codebase | Old system in production while the new one is built |
| Roadmap impact | Lower velocity per sprint, features keep shipping | Feature freeze on the old system, or every feature built twice |
| Scope pressure | Bounded by the module being changed | Feature parity trap: undocumented behavior users rely on has to be found and rebuilt |
| First value | The first merged slice | Cutover day |
| Shape of the bill | Steady and easy to pause | Front-loaded and hard to stop midway |
Refactoring's cost is a velocity tax. Characterization tests have to exist before you touch the code, and some changes, such as small performance tweaks, return only modest gains. In exchange, you can stop after any slice and keep what you built.
A rewrite's largest line item is the parallel run: two sets of infrastructure, two on-call rotations, and a reconciliation process for every output that differs. That bill stays open until the old system's end-of-life.
If the code is too rigid to add the features the business needs, a rewrite can give you a fresh start. We recommend paying for that start one slice at a time, using the strangler fig pattern, so the parallel run covers a single capability. Sliced application modernization keeps the roadmap moving while the replacement grows.
FAQ
How long does a rewrite take?
What is the strangler fig pattern vs a full rewrite?
Decision rule
The decision rule: refactor by default, and rewrite only when the platform or architecture cannot support what the business needs and incremental change costs more than replacement.
If you reach that point, replace the system in slices with the strangler fig pattern. A big-bang rewrite freezes the roadmap until the new system reaches feature parity, and few teams can afford that.
Your next step is to write characterization tests around the module that slows delivery most. Then score it on change frequency, defect hot spots, and team knowledge. If the score points to replacement and you want a second opinion on where the first seam goes, get an estimate for your project.
