Files
2nd/10_Wiki/Topic_Programming/Architecture/Stream-Processing-Architectures.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

177 lines
5.3 KiB
Markdown

---
id: wiki-2026-0508-stream-processing-architectures
title: Stream Processing Architectures
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Stream Processing, Streaming Systems, Real-time Data Processing]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [stream-processing, kafka, flink, architecture]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: java
framework: kafka-streams-flink
---
# Stream Processing Architectures
## 매 한 줄
> **"매 unbounded data 의 continuous compute"**. 매 batch 의 finite data 의 처리와 달리 매 stream 의 무한 event flow 의 sub-second latency 의 처리. 2026 의 standard stack 의 Kafka + Flink + Iceberg 의 lakehouse streaming.
## 매 핵심
### 매 Stream vs Batch
- **Batch**: bounded, high throughput, hours latency (Spark, Hadoop).
- **Stream**: unbounded, lower throughput, ms-sec latency (Flink, Kafka Streams).
- **Unified**: 매 single API 의 batch + stream (Flink Table API, Beam).
### 매 Processing semantics
- **At-most-once**: drop on failure (low latency, lossy).
- **At-least-once**: retry (duplicates possible).
- **Exactly-once**: 매 idempotent + transactional (Kafka EOS, Flink checkpoints).
### 매 Time semantics
- **Event time**: 매 sensor emit 시각 (correct but late).
- **Processing time**: 매 system clock 시각 (fast but wrong on lag).
- **Watermark**: 매 event time 의 progress marker — 매 late event 의 cutoff.
### 매 응용
1. Real-time fraud detection (sub-100ms decision).
2. Trading / market data aggregation.
3. CDC pipelines (Debezium → Kafka → Flink → warehouse).
4. IoT telemetry (sensor → MQTT → stream proc).
## 💻 패턴
### Kafka Streams — windowed aggregation
```java
KStream<String, Order> orders = builder.stream("orders");
orders
.groupBy((k, v) -> v.getCustomerId())
.windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5)))
.aggregate(
() -> 0.0,
(k, order, total) -> total + order.getAmount(),
Materialized.as("customer-5min-total"))
.toStream()
.to("customer-totals");
```
### Flink — event-time + watermark
```java
DataStream<Event> stream = env
.fromSource(kafkaSource, WatermarkStrategy
.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(10))
.withTimestampAssigner((e, ts) -> e.getEventTime()),
"kafka");
stream
.keyBy(Event::getUserId)
.window(TumblingEventTimeWindows.of(Time.minutes(1)))
.aggregate(new CountAgg())
.sinkTo(icebergSink);
```
### Flink SQL — streaming join
```sql
SELECT o.order_id, o.amount, u.tier
FROM orders o
JOIN users FOR SYSTEM_TIME AS OF o.proc_time AS u
ON o.user_id = u.id
WHERE o.amount > 100;
```
### Stateful processing — Flink ProcessFunction
```java
public class FraudDetector extends KeyedProcessFunction<Long, Tx, Alert> {
private ValueState<Double> lastAmount;
@Override
public void open(Configuration cfg) {
lastAmount = getRuntimeContext().getState(
new ValueStateDescriptor<>("last", Double.class));
}
@Override
public void processElement(Tx tx, Context ctx, Collector<Alert> out) throws Exception {
Double prev = lastAmount.value();
if (prev != null && tx.amount > prev * 10) {
out.collect(new Alert(tx.id, "spike"));
}
lastAmount.update(tx.amount);
}
}
```
### Exactly-once with Kafka transactions
```java
producer.initTransactions();
try {
producer.beginTransaction();
producer.send(record1);
producer.send(record2);
producer.sendOffsetsToTransaction(offsets, consumerGroup);
producer.commitTransaction();
} catch (Exception e) {
producer.abortTransaction();
}
```
### Backpressure — Flink credit-based flow control
```java
// Flink auto-handles via network buffers + credit
env.setParallelism(8);
env.getConfig().setAutoWatermarkInterval(200);
env.enableCheckpointing(60_000, CheckpointingMode.EXACTLY_ONCE);
```
### Lakehouse streaming sink — Iceberg
```java
FlinkSink.forRowData(stream)
.table(icebergTable)
.tableLoader(loader)
.upsert(true)
.equalityFieldColumns(List.of("id"))
.append();
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Simple ETL, Kafka-native | Kafka Streams |
| Complex CEP, large state | Flink |
| Unified batch+stream | Flink / Beam |
| SQL-only team | Flink SQL / ksqlDB |
| Tiny scale | Single consumer + handler |
**기본값**: 매 Kafka + Flink — 매 production-grade exactly-once streaming.
## 🔗 Graph
- 부모: [[Distributed Systems]] · [[Event-Driven Architecture]]
- 변형: [[Apache Flink]]
## 🤖 LLM 활용
**언제**: continuous unbounded data, sub-second latency, stateful aggregation.
**언제 X**: hourly/daily batch (use Spark), tiny volumes (use cron).
## ❌ 안티패턴
- **Processing-time on lagged sources**: 매 watermark/event-time 의 사용.
- **Unbounded state**: 매 TTL 의 set — state 의 무한 grow 의 OOM.
- **Single-partition hot key**: 매 skew 의 partition rebalance.
- **Sync external call in operator**: 매 AsyncIO 의 사용.
## 🧪 검증 / 중복
- Verified (Apache Flink docs, Kafka Streams Developer Guide 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Kafka Streams + Flink patterns, EOS, watermarks |