Refactoring Hundreds of Thousands of Lines in Six Months: How to Keep AI-Assisted Coding Under Control

    An individual developer recently reported refactoring a complex microservices project in six months with AI coding tools, growing the codebase from about 100,000 to 300,000–400,000 lines. This article uses that story as a starting point to examine what actually matters in AI-assisted large-scale refactoring: clarifying goals, building an engineering map, decomposing work into verifiable increments, preventing self-confirming test loops, handling data ownership in microservices, migrating incrementally, and managing the real costs of verification. The core conclusion: speed of code generation only translates into delivery capability when tasks have clear boundaries, behaviors have contracts, changes have tests, deployments have observability, and failures have rollback paths.

    1. The Real Difficulty of a Six-Month Refactor Is Not How Much Code You Write

    A reference case describes an intensive software overhaul: a developer committed to refactoring a complex microservices project within six months, using AI coding tools and paying roughly a modest monthly subscription fee for them. By his own account, the project grew from about 100,000 lines of code to somewhere between 300,000 and 400,000 lines.

    Individual experiences like this can serve as an entry point for discussion, but they cannot be used directly as a productivity benchmark. The account provides no independently verifiable test coverage, production incident rates, feature increments, code duplication ratios, or long-term maintenance costs. It is therefore impossible to judge success from timeline and line count alone, let alone extrapolate the results into general productivity gains.

    The question truly worth discussing is: when code generation gets faster and faster, how do developers ensure they still understand and control the system?

    The difficulty of large projects rarely lies at the syntax level. It lies in implicit business rules, complex dependencies, inconsistent historical data, and the compatibility obligations that must continue to be honored after go-live. AI coding can accelerate implementation, but it cannot assume these responsibilities on behalf of the team.

    1. Clarify the Goal First: Refactoring, Rewriting, and Expansion Are Not the Same Thing

    A refactor, in the strict sense, improves internal structure while keeping externally observable behavior essentially unchanged. A rewrite re-implements existing capabilities and usually carries higher compatibility risk. An expansion adds new business or infrastructure capabilities on top of the existing system.

    Real-world engineering often mixes all three. Without distinguishing them, teams easily mistake code growth from new features as proof of refactoring efficiency.

    At project kickoff, the goals should be split into three lists:

    First, behaviors that must be preserved: API inputs and outputs, error semantics, permission boundaries, data precision, and message handling rules.

    Second, problems that must be fixed: circular dependencies, duplicated business logic, hard-to-test modules, overly long deployment pipelines, and recurring failure patterns.

    Third, things explicitly out of scope: no business process changes for now, no expansion of service boundaries, no wholesale replacement of infrastructure “while we’re at it.”

    These three lists jointly constrain what AI coding tools are allowed to do. Otherwise, the tool may introduce new abstractions, dependencies, and directory structures for a local task, turning a small fix into a sweeping overhaul.

    1. Doubling the Codebase May Mean Better Structure—or More Burden

    More code is not inherently bad. Adding automated tests, splitting responsibilities, making data models explicit, and introducing migration scripts and observability can all legitimately expand a codebase.

    But another kind of growth should raise alarms: similar logic generated repeatedly; every module carrying its own near-identical exception handling; simple business logic wrapped in multiple layers of abstraction; old and new implementations coexisting indefinitely with no cleanup plan.

    Code size is therefore only an observational metric, not a value metric. A sounder evaluation should include:

    1. Behavioral correctness: Do critical business flows meet their contracts, and are historical defects protected by regression tests?
    2. Structural quality: Are dependency directions clear, is duplicated logic converging, and can modules be verified independently?
    3. Delivery efficiency: How long does it take from a proposed change to safe deployment, and is human review becoming the bottleneck?
    4. Runtime quality: Do error rates, latency, resource consumption, and recovery capability meet targets?
    5. Maintenance cost: Can the next developer understand the implementation and make changes within reasonable effort?

    These metrics need a pre-refactor baseline. Without a baseline, “things got better” is usually just a subjective impression.

    1. Build an Engineering Map Before Letting Tools Generate Implementations

    The context an AI coding tool receives is usually only part of the system. Even feeding it large numbers of files does not mean it understands all the implicit constraints.

    Before a large-scale overhaul, establish a concise, maintainable set of engineering documentation covering at least:

    Business map: core business objects, state transitions, role permissions, and exception paths.

    Service map: each service’s responsibility, call directions, data ownership, and deployment boundaries.

    Contract map: external APIs, internal messages, error meanings, timeout policies, and compatibility requirements.

    Risk map: highly sensitive paths involving money, inventory, permissions, and personal information, plus areas with concentrated historical incidents.

    This documentation should not degenerate into hundreds of pages nobody maintains. A more practical approach is “overview plus module notes”: the overview constrains common rules, while module notes record local behavior, known limitations, and verification entry points.

    Information that has not been confirmed should be explicitly marked as “to be verified,” rather than letting the tool fill in the gaps. A plausible explanation generated by a model is not the same as a real business rule.

    1. Break Large Tasks into Small Loops That Can Be Reviewed, Verified, and Rolled Back

    “Rewrite the entire service into a better architecture” is not a qualified execution task—it has no clear boundary and no way to tell when it is done.

    A task suitable for AI-assisted collaboration should at least specify:

    Purpose: which specific problem it solves.

    Modification boundary: which modules may be changed, and which interfaces and data structures must not change.

    Behavioral constraints: what semantics must be preserved, and which exceptions must be handled explicitly.

    Acceptance evidence: which tests, checks, and runtime observations prove the change works.

    Rollback method: how to recover if the change fails, and whether any irreversible data changes are involved.

    For example, instead of asking to “optimize message processing,” ask to “complete the duplicate-message handling path under the established business idempotency rules, keep the message format unchanged, and verify first-time processing, duplicate processing, and retry behavior after mid-flight failure.”

    A recommended loop:

    Understand the current state → propose a plan → human confirmation → small-scope implementation → automated verification → review the diff → integrate and run.

    Note that “propose a plan” cannot replace “understand the current state.” A plan must be able to point to the existing call chain, data write locations, and affected tests; otherwise it is likely just generic advice generated from common patterns.

    1. Tests Must Be Independent of the Implementation Logic to Avoid Self-Confirming Loops

    A subtle risk in AI coding is this: the tool generates an implementation, then generates tests based on the same misunderstanding—and all tests pass while the business logic is still wrong.

    To reduce this risk, establish independent behavioral evidence first wherever possible.

    For legacy systems, start by writing characterization tests that record current behavior under key inputs. But characterization tests only show “how it used to behave”—they do not automatically prove that behavior was correct. Where known defects or non-compliant behavior are involved, business and technical owners should jointly determine the target semantics.

    For cross-service calls, focus on contract tests that verify field meanings, optionality, error classification, and version compatibility.

    For complex business logic, add boundary and invariant tests. For example: monetary calculations must follow explicit precision and rounding rules; state transitions must not bypass authorization checks; duplicate requests must not produce duplicate, irreversible business effects.

    For failure paths, verify timeouts, partial success, retries, duplicate delivery, and dependency unavailability—not just the happy path.

    In addition, compilation checks, static analysis, and automated tests each cover only their own scope. They cannot fully replace human judgment on business correctness, security, and runtime behavior.

    1. The Core of Microservices Transformation Is Data and Boundaries, Not Directory Structure

    Splitting one large module into multiple services does not automatically yield better decoupling. If multiple services still directly read and write the same core data, or if every request requires chaining many synchronous calls, the complexity may simply have moved from inside the code to the network and operations layers.

    Service decomposition should prioritize clarifying data ownership: who owns writes, who may read, how data propagates across boundaries, and who fixes inconsistencies when they occur.

    For cross-service workflows, several concrete questions must be answered:

    When one step succeeds and another fails, how does the system converge?

    After a request times out, can the caller determine whether the operation actually completed?

    When messages are duplicated or arrive out of order, is the processing result still acceptable?

    When old and new versions run simultaneously, do both sides understand the same data?

    These questions typically require business-specific choices among idempotency controls, compensation mechanisms, status queries, or manual handling procedures—they cannot be solved by simply “adding retries.” Retries without boundary conditions can amplify failures and create duplicate side effects.

    1. Prefer Incremental Migration Over Replacing All Risk at Once

    Large-scale transformation works better when migrated in batches by business capability, rather than switching everything at once after all the code is written.

    A common path: first establish a stable boundary around the old implementation, then let the new implementation gradually take over portions of traffic, while keeping an explicit fallback path.

    When data structures change, follow an “expand, migrate, contract” approach: first add the compatible structure, then migrate data and read/write logic, confirm the old version no longer depends on the original structure, and only then clean up old fields or old paths.

    If you need to compare old and new results, pay special attention to side-effect isolation. Query results can be compared subject to privacy and resource constraints, but write operations—payments, deductions, notifications—must not be executed twice just for verification.

    Likewise, rolling back an application version does not roll back data. As long as new data or irreversible operations have been produced, a separate recovery plan is required—keeping the old code around is not enough.

    1. Beyond Subscription Fees, the Real Costs Are Verification and Human Load

    The monthly subscription is only a fraction of total cost. The full cost also includes requirement clarification, context preparation, code review, test maintenance, runtime resources, rework, and incident handling.

    When generation speed exceeds review capacity, unchecked code piles up quickly, forming “verification debt.” Tasks appear to complete faster and faster, while inadequately validated changes quietly accumulate.

    Therefore, limit parallel tasks and the size of individual changes, and prioritize finishing verification work already in progress over constantly launching new generation tasks. Where credentials, production data, or sensitive code are involved, clearly define what may be fed into tools, and enforce redaction, access control, and data usage review.

    Human condition is also an engineering constraint. Sustained overload degrades judgment, making developers more likely to accept implementations that look reasonable but are unverified. Part of the time saved by tools should be reinvested in testing, design, and recovery—not entirely converted into more aggressive delivery commitments.

    1. What Is Truly Worth Pursuing Is Sustainable Engineering Throughput

    Writing or modifying hundreds of thousands of lines of code in six months demonstrates intensity of effort, but says little about engineering quality. The more valuable questions for a team are: Is the critical business stable? Are changes easy to understand? Can failures be located and recovered from? Is ongoing maintenance more manageable?

    The reliable way to use AI coding is not to hand the entire system to a tool and wait for results, but to keep humans in charge of goals, constraints, evidence, and release decisions—while the tool handles execution work that is clearly bounded and verifiable.

    When tasks have boundaries, behaviors have contracts, changes have tests, deployments have observability, and failures have escape routes, generation speed can genuinely convert into delivery capability. Otherwise, writing faster simply means complexity accumulates faster.