[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+212 -103
View File
@@ -2,132 +2,241 @@
id: wiki-2026-0508-mediator-topology
title: Mediator Topology
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-C4E95109]
aliases: [Event Mediator Topology, Mediator-Based Event-Driven Architecture]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [mediator-topology, event-driven-architecture-(eda), broker-topology, event-mediator, business-process-execution-language-(bpel), architecture-principles]
confidence_score: 0.9
verification_status: applied
tags: [event-driven, architecture-topology, orchestration]
raw_sources: []
last_reinforced: 2026-05-02
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: temporal
---
# [[Mediator Topology]]
# Mediator Topology
## 📌 한 줄 통찰 (The Karpathy Summary)
**Mediator Topology**(메디에이터 토폴로지)는 이벤트 기반 아키텍처(Event-Driven Architecture, EDA)에서 다중 단계의 비즈니스 프로세스나 복잡한 이벤트 조율이 필요할 때 사용되는 핵심 아키텍처 토폴로지입니다 [1, 2]. 중앙의 이벤트 메디에이터(Event Mediator)가 워크플로우의 상태를 유지하고, 각 단계에 맞는 처리 명령을 지정된 채널로 디스패치하여 오케스트레이션(Orchestration) 방식으로 시스템 흐름을 중앙 제어합니다 [2, 3]. 전체 시스템에 이벤트를 브로드캐스팅하는 브로커(Broker) 토폴로지와 달리, 프로세스 제어, 분산된 오류 처리, 그리고 향상된 데이터 일관성을 제공하는 것이 특징입니다 [3].
## 한 줄
> **"매 central orchestrator 가 매 multi-step event flow 를 직접 지휘"**. Mark Richards, *Software Architecture Patterns* — Event-Driven Architecture 의 두 topology 중 하나 (다른 하나는 Broker). Mediator 는 매 sequence + error handling + transactional rollback 이 필요한 매 complex workflow 에 적합. 2026 의 modern 구현: Temporal, AWS Step Functions, Camunda 8, Netflix Conductor.
## 📖 구조화된 지식 (Synthesized Content)
메디에이터 토폴로지는 복잡한 비즈니스 로직과 워크플로우를 체계적으로 관리하기 위해 여러 구성 요소가 유기적으로 협력하는 구조입니다.
## 매 핵심
* **주요 구성 요소**: 시작 이벤트(Initiating Event), 이벤트 큐(Event Queue), 이벤트 메디에이터(Event Mediator), 이벤트 채널(Event Channel), 이벤트 프로세서/핸들러(Event Processor/Handler)로 구성됩니다 [4, 5].
* **오케스트레이션 기반의 워크플로우**: 클라이언트로부터 발생한 이벤트가 큐를 거쳐 메디에이터로 전달되면, 메디에이터는 전체 비즈니스 프로세스의 다음 단계를 결정하여 적절한 이벤트 채널로 비동기 명령(Processing Event)을 보냅니다 [5, 6]. 각 이벤트 프로세서는 이 이벤트를 수신하여 실제 비즈니스 로직을 수행하며, 메디에이터 자체는 비즈니스 로직을 수행하지 않고 오직 프로세서들에게 처리 지침만을 제공합니다 [7]. 이후 프로세서는 처리가 완료되었음을 비동기 메시지로 메디에이터에 알립니다 [6].
* **이벤트의 성격**: 브로커 토폴로지에서의 이벤트가 "이미 발생한 사실(Things that happened)"이라면, 메디에이터 토폴로지에서의 이벤트는 비즈니스 프로세스의 다음 단계를 실행하도록 지시하는 "명령(Command)"의 성격을 띠며 반드시 실행되어야 합니다 [8]. (예: '경매 입찰 발생' 대신 '입찰자들에게 알림', '아이템 결제' 등 [8])
* **다중 메디에이터 및 구현 도구**: 엔터프라이즈 환경에서는 도메인(예: 고객 이벤트, 주문 이벤트, 재고 이벤트 등)별로 다수의 이벤트 메디에이터를 구현하여 부하를 분산시키고 신뢰성을 높일 수 있습니다 [6]. 이벤트 조율 및 에러 처리가 비교적 단순할 때는 Apache Camel이나 Spring Integration 같은 라이브러리를 사용하며, 장기 실행 프로세스나 고도로 복잡한 동적 경로 결정이 필요할 때는 BPEL(Business Process Execution Language)이나 BPM(Business Process Management) 실행 엔진을 활용할 수 있습니다 [9].
### 매 Mediator vs Broker (Richards 의 dichotomy)
- **Broker**: 매 chain of events, decentralized, 매 service 가 매 다음 step 결정. Pub/sub. 매 simple, fast, hard-to-orchestrate complex workflow.
- **Mediator**: 매 central event mediator 가 매 process 를 orchestrate. 매 sequence 명시, 매 error handling 중앙화. 매 complex but observable.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
메디에이터 토폴로지는 강력한 제어력을 제공하지만, 구조적 특성상 뚜렷한 한계와 반대급부(Trade-off)를 수반합니다.
### 매 Mediator components
1. **Event Queue**: incoming initial events.
2. **Event Mediator**: 매 process orchestrator (workflow engine).
3. **Event Channel**: mediator → processor 의 dispatch.
4. **Event Processor**: 매 single step 실행 (idempotent worker).
* **장점 (이점)**:
* **복잡한 워크플로우 및 에러 제어**: 프로세스의 상태를 저장하고 유지할 수 있으므로, 에러 발생 시 트랜잭션을 재시작하거나 복구하는 등 복잡한 에러 처리가 매우 용이합니다 [2, 3, 10].
* **데이터 일관성**: 워크플로우가 중앙에서 관리되므로 잠재적으로 더 나은 데이터 일관성을 제공할 수 있습니다 [3].
* **단점 (제약 사항 및 부작용)**:
* **단일 장애점 및 성능 병목(Bottleneck)**: 모든 이벤트 흐름이 중앙 메디에이터를 거치기 때문에, 트래픽이 급증할 경우 메디에이터가 성능 병목이 되거나 단일 장애점(Single Point of Failure)으로 전락할 위험이 큽니다 [2, 3].
* **결합도(Coupling) 증가**: 처리기(Processor)들이 중앙의 메디에이터를 인지하고 상호작용해야 하므로 브로커 토폴로지에 비해 컴포넌트 간의 결합도가 높아집니다 [2, 3]. 이로 인해 극단적인 수평적 확장성(Scalability)을 달성하는 데에는 브로커 모델보다 불리할 수 있습니다 [2, 10].
### 매 응용 (when to use mediator)
1. Order fulfillment (validate → pay → reserve → ship → notify).
2. Loan approval (multi-stage with human-in-loop).
3. Subscription onboarding.
4. ETL/data pipeline with retries and DLQ.
5. SAGA pattern compensation orchestration.
## 🔗 지식 연결 (Graph)
### Related Concepts
### 매 trade-off vs Broker
- **More observable**: 매 mediator 의 single source of truth for workflow state.
- **More coupled**: 매 mediator 의 process knowledge — 매 evolution 시 central change.
- **Lower throughput**: 매 mediator 의 single point.
- **Easier to reason**: 매 sequence 가 명시 — debugging.
#### [관계 유형 A: 아키텍처/기반 기술]
* **[[Event-Driven Architecture (EDA)]]**
* 연결 이유: 메디에이터 토폴로지가 속한 상위 아키텍처 스타일입니다.
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 상태 변경(이벤트)을 비동기적으로 감지하고 반응하여 시스템의 확장성 및 응답성을 극대화하는 전반적인 메커니즘을 이해할 수 있습니다 [11-13].
* **[[Broker Topology]]**
* 연결 이유: 중앙 제어가 있는 메디에이터 토폴로지와 대비되는 무중앙(Choreography) 방식의 토폴로지입니다.
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 중앙 조정자 없이 컴포넌트 간 높은 디커플링(Decoupling)과 확장성을 달성하는 방식을 통해 메디에이터 도입 시 포기해야 하는 트레이드오프를 명확히 이해할 수 있습니다 [2, 3, 14].
## 💻 패턴
#### [관계 유형 B: 구현/활용 도구]
* **[[Event Mediator]]**
* 연결 이유: 메디에이터 토폴로지의 두뇌 역할을 하는 가장 핵심적인 중앙 조정 컴포넌트입니다.
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 프로세스 상태 저장, 분산된 오류의 복구 및 재시작 논리가 중앙에서 어떻게 조율(Orchestration)되는지 파악할 수 있습니다 [3, 4].
* **[[Business Process Execution Language (BPEL)]] / [[BPM]]**
* 연결 이유: 복잡한 이벤트 조율, 다중 캐스팅, 동적 경로 결정, 예외 처리 등을 메디에이터에 구현하기 위해 사용되는 선언적 언어 및 관리 엔진입니다.
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 단순한 코드로 처리하기 어려운 장기 실행(Long-running) 비즈니스 트랜잭션과 인간의 개입이 필요한 워크플로우를 시스템이 어떻게 자동화하는지 실무적 관점에서 배울 수 있습니다 [9].
### 1. Temporal workflow (mediator, 2026 standard)
```typescript
// activities.ts (event processors)
export async function validateOrder(o: Order) { /* ... */ }
export async function chargePayment(o: Order) { /* ... */ }
export async function reserveInventory(o: Order) { /* ... */ }
export async function ship(o: Order) { /* ... */ }
export async function notify(userId: string) { /* ... */ }
### Deeper Research Questions
- 메디에이터 토폴로지 내에서 메디에이터 자체의 성능 병목 및 단일 장애점(SPOF) 위험을 완화하기 위해 어떤 분산 및 고가용성 설계 전략이 사용될 수 있는가?
- 단일 시스템 내에서 단순한 이벤트는 브로커 토폴로지로, 복잡한 트랜잭션은 메디에이터 토폴로지로 처리하는 하이브리드 아키텍처는 어떻게 구현되며, 두 토폴로지 간의 통신은 어떻게 제어되는가?
- 마이크로서비스 아키텍처(MSA) 환경에서 메디에이터 토폴로지(오케스트레이션)를 적용할 때 필연적으로 발생하는 서비스 간 결합도 증가 문제를 설계 단계에서 어떻게 최소화할 수 있는가?
- 중앙 메디에이터가 각 이벤트 처리기(Processor)에 비동기 명령(Processing Event)을 디스패치할 때, 메시지 유실이나 순서 역전을 방지하기 위한 기술적 메커니즘(예: Guaranteed Delivery 등)은 무엇인가?
- 메디에이터가 프로세스 상태를 추적하고 실패 시 트랜잭션을 재시작/복구하는 과정에서 보상 트랜잭션(Compensating Transaction)은 어떻게 실행되며 데이터 일관성은 어떻게 보장되는가?
// workflow.ts (mediator)
import { proxyActivities } from "@temporalio/workflow";
import type * as activities from "./activities";
### Practical Application Contexts
* **Implementation:** 복잡한 이벤트 코디네이션이 필요한 도메인에서 Apache Camel이나 Spring Integration 같은 메시징 인프라를 활용해 메디에이터를 프로그래밍하거나, 복잡도에 따라 jBPM 같은 BPM 실행 엔진을 도입하여 워크플로우를 선언적으로 구현합니다 [9].
* **System Design:** 전자상거래 시스템이나 보험 청구 처리처럼 사용자 상호작용 후 주문, 재고 확인, 결제, 배송 등 일련의 다단계 후속 작업이 반드시 정해진 순서와 규칙에 따라 진행되고, 중간에 에러가 났을 때 전체를 취소(Rollback)하거나 재시도해야 하는 시스템 설계 시 채택됩니다 [6, 8].
* **Operation / Maintenance:** 메디에이터가 전체 비즈니스 흐름의 생살여탈권을 쥐고 있으므로 운영 팀은 중앙 메디에이터와 연결된 채널(메시지 큐)의 병목 여부, 큐 지연 시간(Latency) 등을 집중 모니터링해야 합니다 [2, 3].
* **Learning Path:** 이벤트 기반 아키텍처의 기본 개념 습득 -> 브로커 방식과 메디에이터 방식의 장단점 비교 -> 비동기 메시지 채널(RabbitMQ, Kafka 등) 실습 -> Saga 패턴 및 오케스트레이션 프레임워크 학습 순으로 지식을 확장합니다.
* **My Project Relevance:** 여러 마이크로서비스를 넘나드는 비즈니스 프로세스(예: 주문 처리 워크플로우)에서 트랜잭션의 상태 관리가 복잡해져 디버깅과 에러 복구에 어려움을 겪고 있다면, 중앙에서 흐름을 통제하는 메디에이터 패턴 도입을 검토하여 시스템의 안정성과 제어력을 높일 수 있습니다.
const acts = proxyActivities<typeof activities>({
startToCloseTimeout: "1 minute",
retry: { maximumAttempts: 5 },
});
### Adjacent Topics
* **[[Saga Pattern (Orchestration)]]**
* 확장 방향: 마이크로서비스 환경에서 중앙 오케스트레이터(메디에이터와 유사한 역할)를 두고 분산 트랜잭션을 관리하며, 실패 시 보상 트랜잭션(Compensating Transaction)을 통해 데이터의 최종 일관성을 달성하는 방법론으로 학습을 확장합니다 [13, 15].
* **[[Microservices Architecture (MSA)]]**
* 확장 방향: 도메인별로 작고 독립적인 서비스로 분할된 환경에서, 각 서비스 간의 효율적인 상호작용 및 오케스트레이션을 위해 이벤트 기반 아키텍처(메디에이터 포함)가 어떻게 MSA의 한계를 보완하고 복잡성을 제어하는지 분석합니다 [3, 16, 17].
---
*Last updated: 2026-05-02*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(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
export async function orderWorkflow(order: Order) {
await acts.validateOrder(order);
try {
await acts.chargePayment(order);
await acts.reserveInventory(order);
await acts.ship(order);
} catch (err) {
// SAGA compensation
await acts.refundPayment(order).catch(() => {});
await acts.releaseInventory(order).catch(() => {});
throw err;
}
await acts.notify(order.userId);
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. AWS Step Functions (managed mediator)
```json
{
"StartAt": "Validate",
"States": {
"Validate": { "Type": "Task", "Resource": "...:validate", "Next": "Charge" },
"Charge": { "Type": "Task", "Resource": "...:charge",
"Catch": [{ "ErrorEquals": ["PaymentError"], "Next": "Refund" }],
"Next": "Reserve" },
"Reserve": { "Type": "Task", "Resource": "...:reserve", "Next": "Ship" },
"Ship": { "Type": "Task", "Resource": "...:ship", "Next": "Notify" },
"Notify": { "Type": "Task", "Resource": "...:notify", "End": true },
"Refund": { "Type": "Task", "Resource": "...:refund", "Next": "Fail" },
"Fail": { "Type": "Fail" }
}
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Camunda 8 (BPMN mediator)
```xml
<!-- order.bpmn (visual model, executable) -->
<bpmn:process id="orderProcess">
<bpmn:startEvent id="OrderReceived" />
<bpmn:serviceTask id="Validate" zeebe:type="validate-order" />
<bpmn:serviceTask id="Charge" zeebe:type="charge-payment" />
<bpmn:exclusiveGateway id="ChargeOk?" />
<bpmn:serviceTask id="Reserve" zeebe:type="reserve-inventory" />
<!-- ... compensation events for SAGA -->
</bpmn:process>
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. Custom mediator (lightweight)
```typescript
type Step<S> = { name: string; run: (s: S) => Promise<S>; compensate?: (s: S) => Promise<void> };
**기본값:**
> *(TODO)*
class Mediator<S> {
constructor(private steps: Step<S>[]) {}
## ❌ 안티패턴 (Anti-Patterns)
async execute(initial: S): Promise<S> {
const completed: Step<S>[] = [];
let state = initial;
try {
for (const step of this.steps) {
state = await step.run(state);
completed.push(step);
}
return state;
} catch (err) {
// SAGA compensate in reverse
for (const step of completed.reverse()) {
await step.compensate?.(state).catch(() => {});
}
throw err;
}
}
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const orderMediator = new Mediator<Order>([
{ name: "validate", run: validateOrder },
{ name: "charge", run: chargePayment, compensate: refundPayment },
{ name: "reserve", run: reserveInventory, compensate: releaseInventory },
{ name: "ship", run: ship },
]);
```
### 5. Broker (contrast — for comparison)
```typescript
// No central mediator. Each service publishes its own next event.
// order-service: emits "order.validated"
// payment-service: subscribes "order.validated" → publishes "order.paid"
// inventory-service: subscribes "order.paid" → publishes "inventory.reserved"
// shipping-service: subscribes "inventory.reserved" → publishes "order.shipped"
//
// Pros: decoupled, scalable
// Cons: workflow knowledge scattered, hard to add/reorder steps
```
### 6. Compensation pattern (SAGA)
```typescript
// Within mediator, each step has forward + compensating action
const steps = [
{ do: chargePayment, undo: refundPayment },
{ do: reserveInventory, undo: releaseInventory },
{ do: scheduleShipment, undo: cancelShipment },
];
async function saga<S>(state: S) {
const done: typeof steps = [];
for (const s of steps) {
try { await s.do(state); done.push(s); }
catch {
for (const d of done.reverse()) await d.undo(state).catch(() => {});
throw new Error("saga compensated");
}
}
}
```
### 7. Idempotency (essential for mediator workers)
```typescript
async function chargePayment(order: Order) {
const idempotencyKey = `charge:${order.id}`;
const existing = await db.idempotency.findOne(idempotencyKey);
if (existing) return existing.result;
const result = await stripe.charges.create({
amount: order.amount,
customer: order.customerId,
idempotency_key: idempotencyKey,
});
await db.idempotency.put(idempotencyKey, result);
return result;
}
// Mediator may retry → worker MUST be idempotent.
```
## 매 결정 기준
| 상황 | Topology |
|---|---|
| <5 step linear flow, simple notify | Broker (pub/sub). |
| Multi-step with rollback / SAGA | Mediator. |
| Long-running (hours/days) workflow | Mediator (Temporal/Step Functions). |
| Human approval steps | Mediator (BPMN — Camunda). |
| High-throughput stream (>10k/s) | Broker (Kafka). |
| Audit + visibility critical | Mediator. |
| Loose coupling priority | Broker. |
**기본값**: complex business process 는 매 Mediator (Temporal). Simple notification/log 는 매 Broker (Kafka/SNS).
## 🔗 Graph
- 부모: [[Event-Driven Architecture]] · [[Workflow Orchestration]]
- 변형: [[Broker Topology]] · [[Choreography vs Orchestration]]
- 응용: [[Temporal]] · [[AWS Step Functions]] · [[Camunda]] · [[Netflix Conductor]]
- Adjacent: [[SAGA Pattern]] · [[Idempotency]] · [[BPMN]]
## 🤖 LLM 활용
**언제**: workflow architecture choice, SAGA design, multi-step business process modeling, retry/compensation strategy.
**언제 X**: 매 simple fire-and-forget event, 매 high-throughput streaming (broker preferred).
## ❌ 안티패턴
- **God mediator**: 매 매 모든 process 가 매 single mediator 에 — 매 monolith of orchestration. 매 domain 별 분리.
- **Non-idempotent worker**: 매 mediator retry → 매 double-charge / double-ship. 매 idempotency key 필수.
- **Mediator knows business rules**: 매 if/else 분기 가 매 mediator 에 — workflow engine 의 limit. 매 decision 은 activity 로 push.
- **Sync mediator for slow steps**: 매 mediator 가 매 slow IO 의 inline wait — 매 timeout. 매 async + signal/callback.
- **No timeout/retry policy**: 매 hung workflow 의 매 stuck instance.
- **Compensation 누락**: 매 SAGA 의 매 partial commit 의 매 inconsistent state.
## 🧪 검증 / 중복
- Verified (Richards, *Software Architecture Patterns* O'Reilly 2015; Temporal docs; Hohpe & Woolf, *Enterprise Integration Patterns* — Process Manager).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Mediator vs Broker + Temporal/Step Functions/Camunda 2026 implementations |