[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,163 @@
|
||||
id: wiki-2026-0508-impedance-matching
|
||||
title: Impedance Matching
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [SYS-IMP-001]
|
||||
aliases: [Object-Relational Impedance Mismatch, API Impedance]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [system-design, engineering, impedance-matching, Optimization, Scalability]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [orm, api, architecture, integration]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: prisma
|
||||
---
|
||||
|
||||
# Impedance Matching in[[_system|system]]s (시스템 임피던스 매칭)
|
||||
# Impedance Matching
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "서로 다른 두 시스템이 만나는 경계에서 에너지와 데이터의 손실을 최소화하고, 흐름의 효율을 극대화하라" — 전기 회로의 개념을 소프트웨어 아키텍처로 확장하여, 서로 다른 처리 속도나 데이터 구조를 가진 컴포넌트 간의 결합을 최적화하는 설계 원리.
|
||||
## 매 한 줄
|
||||
> **"매 두 system 의 model / protocol 차이를 매 어디선가 흡수해야 한다 — 매 그 자리를 well-chosen 한 곳으로"**. 매 EE 의 source-load impedance match 의 metaphor — software 에서 매 OO ↔ relational, REST ↔ event, sync ↔ async, monolith ↔ microservice 사이의 mismatch 를 anti-corruption layer / DTO / ORM / adapter 로 매 흡수.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Interface [[Alignment|Alignment]]" — 데이터를 생산하는 속도(Producer)와 소비하는 속도(Consumer), 또는 객체 지향 코드와 관계형 데이터베이스(ORM) 사이의 간극을 메우기 위해 버퍼, 캐시, 변환 레이어를 배치하는 조율 패턴.
|
||||
- **주요 적용 사례:**
|
||||
- **Software Engineering:** 비동기 메시지 큐(Kafka, RabbitMQ)를 통한 처리 속도 차이 조율.
|
||||
- **Database (ORM):** 객체 모델과 테이블 모델 간의 구조적 불일치 해결.
|
||||
- **API Design:** 프론트엔드가 요구하는 데이터 형태와 백엔드가 제공하는 데이터 형태 사이의 변환 (BFF - [[Backend|Backend]] For [[Frontend|Frontend]]).
|
||||
- **의의:** 시스템 전체의 병목 현상을 방지하고, 구성 요소 간의 결합도(Coupling)를 낮추어 유지보수성과 확장성을 확보함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순히 연결만 하면 된다는 사고에서 벗어나, 연결 지점에서 발생하는 '에너지 손실(지연 시간, 리소스 낭비)'을 정량화하고 이를 최소화하는 것이 고성능 아키텍처의 핵심임을 인식.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 사고 속도와 UI 반영 속도 사이의 임피던스 매칭을 위해 '스트리밍 파싱'과 '상태 관리 최적화'를 필수 기술 표준으로 채택함.
|
||||
### 매 classic mismatches
|
||||
- **OO ↔ Relational**: object identity vs row, inheritance vs table, association vs FK.
|
||||
- **REST ↔ Event-driven**: request/response vs publish/subscribe, sync vs async.
|
||||
- **Internal model ↔ External API**: domain entity vs DTO/contract.
|
||||
- **Bounded context 간**: 매 같은 단어 ("Order") 가 매 다른 의미.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- System-Design-for-AI-Scale, [[High-Availability-Systems|High-Availability-Systems]], [[Frontend-Architecture|Frontend-Architecture]], [[Message-Queues-and-Event-Streams|Message-Queues-and-Event-Streams]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Impedance-Matching.md
|
||||
### 매 흡수 위치
|
||||
- **ORM** (Prisma, Drizzle, SQLAlchemy, Hibernate): OR mismatch.
|
||||
- **DTO / Schema** (Zod, Pydantic, Protobuf): API boundary.
|
||||
- **Anti-Corruption Layer (ACL)**: bounded context 간 (Evans DDD).
|
||||
- **Adapter / Port** (Hex / Clean architecture): 매 infra ↔ domain.
|
||||
- **Event envelope / outbox**: sync ↔ async.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. ORM choice / hand-rolled SQL trade-off.
|
||||
2. GraphQL / tRPC / gRPC 의 schema-first contract.
|
||||
3. CQRS — read model 과 write model 의 분리.
|
||||
4. Strangler fig — legacy ↔ new system migration.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Prisma — OR mismatch 흡수
|
||||
```ts
|
||||
// schema.prisma
|
||||
// model User { id Int @id @default(autoincrement()) email String @unique posts Post[] }
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
const prisma = new PrismaClient();
|
||||
const user = await prisma.user.findUnique({ where: { email }, include: { posts: true } });
|
||||
// 매 row → object graph (lazy/eager) automatic
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### DTO + Zod (API boundary)
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
export const CreateUserDTO = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1).max(100),
|
||||
});
|
||||
export type CreateUserDTO = z.infer<typeof CreateUserDTO>;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// route
|
||||
app.post("/users", async (req, res) => {
|
||||
const dto = CreateUserDTO.parse(req.body); // 매 invalid 면 throw
|
||||
const user = await userService.create(dto);
|
||||
res.json(toUserResponse(user)); // 매 entity → response DTO
|
||||
});
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Anti-Corruption Layer
|
||||
```ts
|
||||
// 매 legacy CRM 의 dirty model → 매 깨끗한 domain 으로
|
||||
class CrmAcl {
|
||||
toCustomer(raw: LegacyCrmRow): Customer {
|
||||
return {
|
||||
id: CustomerId.of(raw.cust_id_v2 ?? raw.cust_id),
|
||||
email: Email.of(raw.email_addr.trim().toLowerCase()),
|
||||
tier: raw.tier_code === "P" ? "premium" : "standard",
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Outbox (sync ↔ async)
|
||||
```ts
|
||||
await prisma.$transaction([
|
||||
prisma.order.create({ data: order }),
|
||||
prisma.outbox.create({ data: { topic: "order.created", payload: JSON.stringify(order) } }),
|
||||
]);
|
||||
// 매 별도 worker 가 outbox → Kafka publish (at-least-once)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Hexagonal port
|
||||
```ts
|
||||
// 매 domain side 의 port (interface)
|
||||
export interface PaymentGateway { charge(amount: Money, token: string): Promise<ChargeId>; }
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// 매 infra side 의 adapter
|
||||
export class StripeAdapter implements PaymentGateway {
|
||||
async charge(amount: Money, token: string): Promise<ChargeId> {
|
||||
const r = await stripe.paymentIntents.create({ amount: amount.cents, currency: amount.ccy, payment_method: token });
|
||||
return ChargeId.of(r.id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### gRPC / Protobuf contract
|
||||
```proto
|
||||
syntax = "proto3";
|
||||
message User { int64 id = 1; string email = 2; string name = 3; }
|
||||
service UserService { rpc GetUser(GetUserRequest) returns (User); }
|
||||
```
|
||||
|
||||
### CQRS — read model
|
||||
```ts
|
||||
// 매 write: domain entity → event
|
||||
// 매 read: denormalized view (materialized) → query
|
||||
const orders = await db.orderListView.where({ userId }).orderBy("createdAt", "desc");
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Simple CRUD + RDB | ORM (Prisma / Drizzle) |
|
||||
| Complex query / perf | hand-rolled SQL + thin mapper |
|
||||
| External legacy | ACL (변환 layer 명시) |
|
||||
| Polyglot service mesh | Protobuf + gRPC |
|
||||
| Sync write + async fanout | Outbox + event bus |
|
||||
| Read 많이, write 적게 | CQRS 의 separate read model |
|
||||
|
||||
**기본값**: TS + Postgres 조합은 Prisma/Drizzle + Zod DTO + outbox.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software Architecture]] · [[Integration]]
|
||||
- 변형: [[ORM]] · [[Anti-Corruption Layer]] · [[Hexagonal Architecture]] · [[CQRS]]
|
||||
- 응용: [[REST API]] · [[gRPC]] · [[GraphQL]] · [[Event-Driven Architecture]]
|
||||
- Adjacent: [[Bounded Context]] · [[DDD]] · [[Outbox Pattern]] · [[Strangler Fig]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: legacy 통합 설계, API contract 결정, ORM vs raw SQL trade-off reasoning.
|
||||
**언제 X**: 매 단일 monolith + 단일 DB 의 trivial app — 매 over-engineering.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Leaky ORM**: 매 ORM entity 를 그대로 API 응답 — 매 schema lock-in.
|
||||
- **N+1 query**: 매 ORM 의 lazy load loop — include / dataloader.
|
||||
- **Anemic ACL**: 매 변환만 하고 의미 보존 X — 매 그냥 DTO 와 다를 바 없음.
|
||||
- **Distributed monolith**: 매 microservice 인데 DB schema 공유 — 매 mismatch 흡수 실패.
|
||||
- **At-most-once event publish**: 매 outbox 없이 commit 후 publish → 매 lost message.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler *PoEAA* 2002, Evans *DDD* 2003, Vernon *IDDD* 2013, Prisma docs, microservices.io).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — OR mismatch + ACL + outbox + CQRS 정리 |
|
||||
|
||||
Reference in New Issue
Block a user