--- id: wiki-2026-0508-large-scale-application-refactor title: Large-scale Application Refactoring category: 10_Wiki/Topics status: verified canonical_id: self aliases: [large refactor, monorepo refactor, architectural refactoring] duplicate_of: none source_trust_level: A confidence_score: 0.85 verification_status: applied tags: [refactoring, architecture, monorepo, frontend, migration] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: TypeScript framework: Monorepo --- # Large-scale Application Refactoring ## 매 한 줄 > **"매 large-scale refactor 의 성공은 incremental migration + automated codemod + tight feedback loop"**. 매 big-bang rewrite 는 매 90% fail. 매 strangler fig pattern, type-safe boundaries, CI-enforced invariants 가 정답. 2026 의 AI-assisted refactor (Claude, Cursor) 는 매 codemod 를 augment. ## 매 핵심 ### 매 전략 종류 - **Strangler Fig**: 매 old + new 동시 운영, gradual cutover. - **Branch by Abstraction**: 매 interface 추가 → impl 교체. - **Codemod**: 매 AST-based bulk rewrite (jscodeshift, ts-morph). - **Feature flag**: 매 new 코드 toggle, rollback 즉시. ### 매 사전 준비 - **Test coverage 가 안전망**: 매 critical path 80%+ 권장. - **Type system 활용**: 매 TS strict, branded types 로 invariant. - **Metrics baseline**: 매 perf, bundle size, error rate 의 before/after. - **Rollback plan**: 매 feature flag, blue-green deploy. ### 매 응용 1. JS → TS migration (Airbnb, Stripe). 2. Pages Router → App Router (Next.js). 3. Redux → Zustand / Jotai. 4. CRA → Vite. 5. Single repo → Turborepo / Nx monorepo. ## 💻 패턴 ### Strangler Fig — old/new gateway ```typescript // gateway.ts export async function fetchUser(id: string) { if (await flags.isEnabled("new-user-api", id)) { return newUserApi.get(id); // 매 new } return legacyUserApi.get(id); // 매 old fallback } // 매 traffic % gradually 100% ``` ### Codemod with ts-morph (rename API) ```typescript import { Project } from "ts-morph"; const project = new Project({ tsConfigFilePath: "./tsconfig.json" }); project.getSourceFiles().forEach((sf) => { sf.getDescendantsOfKind(SyntaxKind.CallExpression).forEach((call) => { const expr = call.getExpression(); if (expr.getText() === "oldFetch") { expr.replaceWithText("newFetch"); } }); }); await project.save(); // 매 매 file 수동 X — 매 1000 file 도 1초 ``` ### Branch by Abstraction ```typescript // 매 step 1: interface 도입 interface UserStore { get(id: string): Promise; save(u: User): Promise; } // 매 step 2: old impl 을 interface 뒤로 class ReduxUserStore implements UserStore { /* ... */ } // 매 step 3: 매 callsite 가 interface 사용 — 매 internal 구조 변경 가능 const store: UserStore = useFlag("zustand") ? new ZustandUserStore() : new ReduxUserStore(); ``` ### Type-driven migration (branded type) ```typescript type UserId = string & { __brand: "UserId" }; type LegacyUserId = string & { __brand: "LegacyUserId" }; function migrate(legacy: LegacyUserId): UserId { return `u_${legacy}` as UserId; } // 매 compiler 가 매 미migrate 사이트 catch ``` ### Dependency cruiser (architectural invariant) ```javascript // .dependency-cruiser.cjs module.exports = { forbidden: [ { name: "ui-no-import-server", severity: "error", from: { path: "^src/ui" }, to: { path: "^src/server" }, }, ], }; // 매 CI 에서 violation block — 매 layer 침범 방지 ``` ### Bundle size budget (CI enforce) ```json // package.json { "size-limit": [ { "path": "dist/main.js", "limit": "200 KB" }, { "path": "dist/vendor.js", "limit": "300 KB" } ] } ``` ### Mikado method (refactor 의 dependency tree) ``` Goal: Move auth from monolith to service ├── Pre: extract auth interface (BLOCKED by tight coupling) │ ├── Pre: extract user model (DONE) │ └── Pre: remove direct DB access from auth (DONE) └── Pre: setup auth service skeleton (DONE) ``` ### AI-assisted bulk refactor (2026) ```bash # 매 Cursor / Claude Code 에 codemod 보다 의도 기반 refactor # 매 "convert all class components to hooks" 같은 task 는 # AI 가 context 이해하며 수정 — 매 codemod 의 limit 넘음 # 매 검증: dry-run + diff review + test run ``` ## 매 결정 기준 | 변경 규모 | 전략 | |---|---| | 1-3 file | manual edit | | 10-100 file pattern | codemod (jscodeshift / ts-morph) | | Architectural | strangler fig + feature flag | | Cross-cutting (TS migration) | incremental + branded types | | Monorepo split | Nx / Turborepo migration | **기본값**: incremental + feature flag + CI invariant. Big-bang rewrite 의 X. ## 🔗 Graph - 부모: [[Software Architecture]] · [[Refactoring_Best_Practices|Refactoring]] - 변형: [[Feature Flag]] - 응용: [[Monorepo|Monorepo Setup]] - Adjacent: [[Dependency Cruiser]] ## 🤖 LLM 활용 **언제**: refactor 전략 설계, codemod 작성, dependency rule 작성. **언제 X**: 매 trivial change (3 line) — 매 manual 가 빠름. ## ❌ 안티패턴 - **Big-bang rewrite**: 매 6 month freeze, 매 ship 못 함, 매 abandon 률 높음. - **No baseline metrics**: 매 "더 좋아졌다" 증명 X. - **No rollback plan**: 매 prod 사고 시 panic. - **Codemod without test**: 매 silent regression. ## 🧪 검증 / 중복 - Verified (Martin Fowler "Refactoring", "Working Effectively with Legacy Code", Trunk-Based Dev). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — strangler fig + codemod + AI refactor |