Files
2nd/10_Wiki/Topics/Architecture/Architecture_Refactor.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

6.6 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-architecture-refactor Architecture Refactor 10_Wiki/Topics verified self
strangler-fig
big-bang-rewrite
modernization
none A 0.9 applied
architecture
refactor
strangler-fig
modernization
2026-05-10 pending
language framework
polyglot strangler-fig

Architecture Refactor

매 한 줄

"매 incremental 의 always wins". 매 architecture refactor 의 default approach 의 Martin Fowler 의 Strangler Fig (2004) — 매 old system 의 around 의 new system 의 gradual 의 grow. 매 big-bang rewrite 의 historically failure rate >70% (Ousterhout, Brooks). 매 2026 의 typical pattern: 매 monolith → modular monolith → selective service extraction.

매 핵심

매 refactor strategies

  • Strangler Fig: 매 facade 의 routing — 매 traffic 의 incrementally 의 new system 의 redirect.
  • Branch by Abstraction: 매 abstraction layer 의 introduce — 매 dual 의 implementation — 매 old 의 remove.
  • Parallel Run: 매 old + new 의 동시 실행 — 매 output 의 compare.
  • Big Bang Rewrite: 매 last resort — 매 only 매 system 의 small + scope 의 frozen 의 가능.

매 refactor 의 prerequisite

  • Test coverage: 매 characterization tests (Feathers) 의 minimum.
  • Observability: 매 metrics + traces 의 before/after diff.
  • Feature flag: 매 reversibility 의 prerequisite.
  • ADR: 매 decision rationale 의 documented.

매 응용

  1. Monolith → modular monolith — 매 module boundary 의 enforce (ArchUnit).
  2. Service extraction — 매 bounded context 의 따라.
  3. Database split — 매 most expensive — 매 last 의 do.
  4. Framework upgrade — 매 incremental migration.

💻 패턴

Strangler Fig — Nginx routing facade

upstream legacy { server legacy.internal:8080; }
upstream new    { server new.internal:8080; }

server {
  listen 443 ssl;

  # New endpoints — gradual rollout
  location /api/v2/orders { proxy_pass http://new; }
  location /api/v2/users  { proxy_pass http://new; }

  # Everything else still legacy
  location / { proxy_pass http://legacy; }
}

Branch by Abstraction (Java)

// Step 1 — extract interface
interface PaymentGateway {
  Receipt charge(Order o);
}

// Step 2 — wrap legacy
class LegacyStripeGateway implements PaymentGateway { /* ... */ }

// Step 3 — new impl behind flag
class AdyenGateway implements PaymentGateway { /* ... */ }

// Step 4 — feature-flag pick
class GatewayFactory {
  PaymentGateway pick(String tenant) {
    return flags.isOn("adyen", tenant)
      ? new AdyenGateway()
      : new LegacyStripeGateway();
  }
}
// Step 5 — once 100% rollout, delete LegacyStripeGateway

Parallel Run (shadow traffic)

async function chargeShadow(order: Order): Promise<Receipt> {
  const [primary, shadow] = await Promise.allSettled([
    legacy.charge(order),
    newImpl.charge(order)  // never persists, just observes
  ]);
  if (shadow.status === 'fulfilled' && primary.status === 'fulfilled') {
    diff.record('charge', primary.value, shadow.value);
  }
  return primary.status === 'fulfilled' ? primary.value : Promise.reject(primary.reason);
}

Database Strangling — dual write + read switch

# Phase 1: dual write
def save_order(o: Order):
    legacy_db.insert(o)
    try:
        new_db.insert(o)
    except Exception as e:
        log.warn("shadow write failed", e=e)

# Phase 2: dual read + diff
def get_order(id: str):
    a = legacy_db.get(id)
    b = new_db.get(id)
    if a != b: metrics.increment("order.read.diverge")
    return a  # legacy still source of truth

# Phase 3: flip read source
def get_order(id: str):
    return new_db.get(id)

# Phase 4: stop legacy write, decommission

Module extraction (modular monolith → service)

# 1. Codify module boundary first (ArchUnit)
# 2. Replace direct calls with in-process interface
# 3. Add feature flag: in-process vs HTTP/gRPC
# 4. Deploy as separate process behind flag
# 5. Remove in-process path

Characterization test (Feathers)

import json, pytest

@pytest.mark.parametrize("fixture", load_fixtures("legacy_outputs/*.json"))
def test_legacy_behavior_preserved(fixture):
    inputs = fixture["input"]
    expected = fixture["legacy_output"]
    actual = new_impl.run(**inputs)
    assert actual == expected, f"divergence: {fixture['id']}"

Refactor scoreboard (CI)

# refactor-progress.yml — auto-generated dashboard
metrics:
  - name: legacy-endpoints-remaining
    cmd: grep -r "@legacy" src/ | wc -l
  - name: new-coverage
    cmd: jacoco --module=new-impl
  - name: traffic-on-new
    promql: sum(rate(http_requests_total{service="new"}[5m]))
                / sum(rate(http_requests_total[5m]))

매 결정 기준

상황 Strategy
Active legacy + traffic Strangler Fig
Library/abstraction swap Branch by Abstraction
Risk-critical (payment, billing) Parallel Run
DB schema change Dual-write + flip read
Tiny system, frozen scope Big Bang (rare)
Distributed monolith Reverse first → modular monolith → extract

기본값: Strangler Fig + feature flag + parallel-run on critical paths.

🔗 Graph

🤖 LLM 활용

언제: 매 legacy code → modern equivalent translation, 매 codemod plan generation, 매 ADR draft. 언제 X: 매 production cutover decision — 매 human + traffic data 의 필수.

안티패턴

  • Big bang rewrite: 매 70%+ failure rate — 매 last resort.
  • Refactor without tests: 매 silent regression 의 guarantee.
  • No flag, no rollback: 매 forward-only deploy — 매 incident magnification.
  • Premature service extraction: 매 distributed monolith 의 worst-of-both.
  • Stop midway: 매 두 system 의 forever maintain — 매 cost 의 doubled.

🧪 검증 / 중복

  • Verified (Fowler — StranglerFigApplication; Feathers — Working Effectively with Legacy Code; Newman — Monolith to Microservices).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — Strangler Fig + Branch-by-Abstraction + parallel-run patterns