Code Refactoring at Scale: Lessons from Rewriting 300,000 Lines in Six Months
This article reviews a six-month effort to redesign and rebuild a poorly maintained legacy web application, growing from an initial 100,000-line estimate to 300,000–400,000 lines with the help of AI coding tools. It explains why code volume expands during refactoring, outlines five engineering practices for keeping model output reliable, discusses the hidden costs of subscription fees and cognitive load, and provides a phased roadmap from surveying the codebase to final handover.
1. Background: A Legacy System Nobody Wanted to Touch
An engineer with seven years of production web development experience took over an internally built application with serious quality problems. Its lineage was tangled: it was originally written by an intern and derived from an even earlier intern project. Layer upon layer of temporary fixes had produced a textbook monument to technical debt—inconsistent naming, blurred responsibility boundaries, and duplicated logic everywhere.
He promised management that he would independently complete the redesign and implementation within six months, at a scale of roughly 100,000 lines. In the end, the codebase ballooned to 300,000–400,000 lines. The cost was a subscription to AI coding tools of about 1,400 RMB per month, plus a self-deprecating remark that the project might take five years off his life.
The value of this case is not that “AI wrote hundreds of thousands of lines.” It exposes a real problem: when generation becomes cheap, the engineering bottleneck shifts from writing to reading, verifying, and maintaining.
2. Why the Codebase Grew Three- or Fourfold
Many people treat code growth as a sign of losing control, but in refactoring it is often explainable:
- Making the implicit explicit: Legacy systems rely on many implicit conventions. Refactoring turns those conventions into explicit types, validation, and error branches, which naturally increases line count.
- Tests and tooling: Unit tests, integration tests, type definitions, and build scripts all count toward the total.
- Splitting and decoupling: A monolithic giant file is broken into modules with clear boundaries, adding directories and boilerplate.
- Observability: Logging, metrics, and tracing instrumentation are production necessities, yet the original system typically had none.
What deserves scrutiny is “padding” beyond these four categories: repeatedly generating similar components, useless abstractions, and commented-out old implementations. The test is simple—if new code has no corresponding new test or behavior, it is a liability.
3. Five Engineering Practices for Turning the Model into a Reliable Subordinate
3.1 Context Is Architecture
The ceiling on model output quality is set by context. The practical approach is to write down the “constitution” first: directory conventions, naming rules, a dependency allowlist, error-handling patterns, and commit granularity. A minimal constraint file might look like this:
# Project Constraints- Layers: api / service / repository; cross-layer direct calls are forbidden- All external input must be validated; failures return structured errors- Do not introduce libraries absent from the dependency list- Every public function must have a corresponding unit test
3.2 Keep Task Slices Small Enough to Verify
Do not issue instructions like “refactor the user module.” Instead, say “convert the callbacks in file X to async/await, keep the exported signatures unchanged, and add tests for the failure branches.” The slice size should be small enough to review and roll back in one pass.
3.3 Automate Quality Gates
Human review attention is a scarce resource and must be reserved for architecture and semantics. Formatting, static checks, type checks, and test coverage all go to the pipeline:
# Must be all green before commitsteps:- lint- typecheck- test --coverage- build
3.4 Commit in Small Steps and Stay Reversible
Commit immediately after each slice and keep the working tree clean. If a directional mistake appears, the rollback cost should be contained within one slice rather than a whole day.
3.5 Make the Blast Radius Explicit
Before making changes, have the model list the affected callers and data contracts, confirm them manually, and only then execute. This step filters out most changes that “look right but blow up at runtime.”
4. Underrated Costs: The Bill, Cognition, and Sustainability
The monthly spend of about 1,400 RMB is essentially trading cash for time. The math works only if the output is deliverable; with a high rework rate, marginal cost spirals quickly. Controllable measures include allocating budget by task type, distilling repetitive Q&A into documentation instead of repeatedly consuming context, and settling long tasks in segments.
A more hidden cost is cognitive load. Sustained high-intensity parallel work across multiple abstraction layers fragments attention in the “generate–verify–regenerate” loop. A sustainable rhythm comes from three things: a fixed end-of-day time, batching low-value decisions, and turning repeated judgments into scripts.
5. A Practical Phased Roadmap
- Weeks 1–2: Survey. Build a dependency graph, identify dead code, and complete the build and pipeline. Write no business logic.
- Weeks 3–8: Establish the skeleton. Define the layers and data contracts, and lock in behavior with a few end-to-end cases.
- Weeks 9–16: Slice migration. Replace block by block in order of business value, with tests and rollback switches for each block.
- Weeks 17–22: Cleanup and hardening. Remove compatibility layers, complete observability, and set performance and capacity baselines.
- Final stage: Handover. Documentation, drills, and an on-call handbook—none can be skipped.
If a company needs elastic compute and managed environments, general cloud capabilities can handle it: a container platform for builds and runtime, object storage for artifacts, a message queue for peak shaving, and logging plus monitoring and alerting as the observability foundation. General offerings from cloud providers such as Baidu AI Cloud can cover this without binding to proprietary interfaces.
6. Conclusion
The real conclusion of this case is not that “AI takes five years off your life.” It is this: improved generation capability does not automatically translate into delivery capability; it only amplifies your existing engineering discipline—or amplifies your chaos. Write the constraints clearly, keep the slices small, automate the gates, and hold the rhythm steady, and 300,000 lines can be an asset. Otherwise, it is just a longer, more expensive liability.
