[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
@@ -1,89 +1,183 @@
---
id: wiki-2026-0508-real-time-data-streaming
title: Real time Data Streaming
title: Real-time Data Streaming
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [SYS-STREAM-001]
aliases: [Stream Processing, Event Streaming, Real-time Pipelines]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [infrastructure, _systems, streaming, real-time, kafka, flink, data-engineering, event-driven]
confidence_score: 0.95
verification_status: applied
tags: [streaming, kafka, pulsar, flink, data-engineering]
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: python
framework: kafka-flink-pulsar
---
# Real-time Data Streaming (실시간 데이터 스트리밍)
# Real-time Data Streaming
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터를 거대한 호수에 가두어 썩게 두지 말고, 쉼 없이 흐르는 강물처럼 실시간으로 분석하여 찰나의 가치를 통찰로 포착하라" — 끊임없이 생성되는 데이터([[Events|Events]])를 지연 시간(Latency) 없이 실시간으로 수집, 처리, 분석하는 컴퓨팅 아키텍처.
## 한 줄
> **"매 batch ETL 의 X — 매 unbounded events 매 milliseconds latency 매 process"**. Kafka (LinkedIn 2010) → Flink / Spark Structured Streaming / Pulsar / Materialize / RisingWave 매 modern stack. 매 2026 매 sub-second analytics 매 default.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Event-driven Orchestration and Continuous Aggregation" — 데이터가 발생하는 즉시 이벤트로 발행하고, 이를 스트림 처리 엔진이 구독하여 윈도우(Windowing) 연산이나 상태([[State|State]]) 관리를 통해 실시간 집계 결과를 산출하는 패턴.
- **핵심 기술 구성:**
- **Message Broker (Kafka):** 대량의 스트림 데이터를 유실 없이 전달하는 파이프라인.
- **Stream [[Processing|Processing]] (Flink, Spark Streaming):** 흐르는 데이터에 대한 필터링, 조인, 집계 수행.
- **Time Handling:** 이벤트 발생 시간(Event Time)과 처리 시간(Processing Time)의 구분 관리.
- **의의:** 금융권의 실시간 사기 탐지(FDS), 이커머스의 실시간 개인화 추천, 자율주행 센서 데이터의 즉각적 반응 등 '시간이 곧 가치'인 모든 현대적 시스템의 중추.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 하루 한 번 모아서 처리하던 배치(Batch) 처리 방식에서 벗어나, 이제는 모든 데이터를 스트림으로 보고 배치를 스트림의 특수한 경우(Bounded Stream)로 취급하는 '통합 데이터 처리' 패러다임이 확산됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 실시간 모니터링 로그 및 사용자 인터랙션 데이터를 스트리밍 방식으로 처리하여, 즉각적인 성능 대시보드 업데이트와 이상 징후 감지를 수행함.
### 매 layers
- **Ingest**: Kafka, Pulsar, Kinesis, Redpanda — 매 durable log.
- **Process**: Flink, Spark Streaming, Kafka Streams, Bytewax, Arroyo.
- **Serve**: Materialize, RisingWave, Pinot, Druid, ClickHouse.
## 🔗 지식 연결 (Graph)
- Queue-Management-Systems, System-Design-for-AI-Scale, [[High-Availability-Systems|High-Availability-Systems]], [[Predictive-Analytics|Predictive-Analytics]]
- **Raw Source:** 10_Wiki/Topics/AI/Real-time-Data-Streaming.md
### 매 windowing
- **Tumbling**: fixed, non-overlapping (1-min buckets).
- **Sliding**: overlapping (5-min, slide 1-min).
- **Session**: gap-based (user activity until 30s inactivity).
- **Hopping**: same as sliding (different name).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 time semantics
- **Event time**: 매 actual occurrence — 매 correctness 위해 default.
- **Processing time**: 매 broker arrival — 매 latency 측정.
- **Ingestion time**: 매 broker append.
- **Watermarks**: 매 lateness threshold — Flink/Beam 핵심.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Fraud detection — 매 payment stream + ML inference.
2. Real-time dashboards — Materialize + Grafana.
3. CDC pipelines — Debezium → Kafka → warehouse.
4. IoT telemetry — MQTT → Kafka → anomaly detection.
5. Personalization — clickstream → feature store → model.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Kafka Streams (Python via Faust / Bytewax)
```python
import bytewax.operators as op
from bytewax.dataflow import Dataflow
from bytewax.connectors.kafka import KafkaSource, KafkaSink
- **정보 상태:** 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
flow = Dataflow("fraud")
src = op.input("in", flow, KafkaSource(["localhost:9092"], ["payments"]))
parsed = op.map("parse", src, lambda kv: json.loads(kv.value))
flagged = op.filter("flag", parsed, lambda p: p["amount"] > 10000)
op.output("out", flagged, KafkaSink(["localhost:9092"], "alerts"))
```
## 🤔 의사결정 기준 (Decision Criteria)
### Flink SQL (windowed aggregation)
```sql
CREATE TABLE clicks (
user_id STRING, ts TIMESTAMP(3),
WATERMARK FOR ts AS ts - INTERVAL '5' SECOND
) WITH ('connector' = 'kafka', ...);
**선택 A를 써야 할 때:**
- *(TODO)*
SELECT
user_id,
TUMBLE_START(ts, INTERVAL '1' MINUTE) AS w_start,
COUNT(*) AS clicks
FROM clicks
GROUP BY user_id, TUMBLE(ts, INTERVAL '1' MINUTE);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Materialize (streaming SQL view)
```sql
CREATE SOURCE orders FROM KAFKA BROKER 'kafka:9092' TOPIC 'orders'
FORMAT AVRO USING SCHEMA REGISTRY 'http://sr:8081';
**기본값:**
> *(TODO)*
CREATE MATERIALIZED VIEW revenue_5min AS
SELECT
date_trunc('minute', ts) AS minute,
SUM(amount) AS revenue
FROM orders
WHERE ts > now() - INTERVAL '5 minutes'
GROUP BY 1;
## ❌ 안티패턴 (Anti-Patterns)
-- Subscribe to changes
SUBSCRIBE TO revenue_5min;
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Spark Structured Streaming
```python
df = (spark.readStream.format("kafka")
.option("subscribe", "events")
.load())
agg = (df.selectExpr("CAST(value AS STRING) as json")
.select(from_json("json", schema).alias("e"))
.withWatermark("e.ts", "10 minutes")
.groupBy(window("e.ts", "1 minute"), "e.user")
.count())
agg.writeStream.format("delta").outputMode("append").start("/lake/agg")
```
### Pulsar Functions (lightweight processing)
```python
from pulsar import Function
class EnrichOrder(Function):
def process(self, msg, ctx):
order = json.loads(msg)
order["region"] = lookup_region(order["zip"])
ctx.publish("orders.enriched", json.dumps(order))
```
### Exactly-once with Kafka transactions
```python
producer = KafkaProducer(transactional_id="tx-1", enable_idempotence=True)
producer.init_transactions()
try:
producer.begin_transaction()
producer.send("out", value=processed)
producer.send_offsets_to_transaction(offsets, group_id)
producer.commit_transaction()
except:
producer.abort_transaction()
```
### CDC with Debezium
```yaml
# connector config
connector.class: io.debezium.connector.postgresql.PostgresConnector
database.hostname: pg
table.include.list: public.orders
plugin.name: pgoutput
# emits CDC events to Kafka topic "pg.public.orders"
```
## 매 결정 기준
| 상황 | Stack |
|---|---|
| 매 simple transform | Kafka Streams / Bytewax |
| 매 complex windowing, joins | Flink |
| 매 SQL-first analytics | Materialize / RisingWave |
| 매 batch+stream unified | Spark Structured / Beam |
| 매 lightweight, serverless | Pulsar Functions / AWS Lambda |
| 매 OLAP serving | Pinot / Druid / ClickHouse |
**기본값**: 매 2026 매 SQL-on-streams (Materialize/RisingWave) 매 default — DX 압도적.
## 🔗 Graph
- 부모: [[Data Engineering]] · [[Event Driven Architecture]]
- 변형: [[Stream Processing]] · [[CEP]] · [[Lambda Architecture]] · [[Kappa Architecture]]
- 응용: [[Fraud Detection]] · [[Real-time Analytics]] · [[CDC]]
- Adjacent: [[Kafka]] · [[Flink]] · [[Materialize]] · [[Pulsar]]
## 🤖 LLM 활용
**언제**: 매 SQL DDL/query generation, 매 schema evolution analysis, 매 anomaly investigation summarization.
**언제 X**: 매 latency-critical hot path — LLM inference 매 too slow. 매 trained ML model 사용.
## ❌ 안티패턴
- **Processing time everywhere**: 매 out-of-order events 매 wrong results — event time + watermarks 사용.
- **Unbounded state**: 매 keyed state 매 grows forever — TTL / windows 필수.
- **Tiny files**: 매 1 record / file → S3 explosion. 매 batching + compaction.
- **Sync external calls in pipeline**: 매 backpressure 폭발. 매 async + bulkhead.
- **No replay strategy**: 매 bad code → poisoned downstream. 매 reset offset + idempotent sinks.
## 🧪 검증 / 중복
- Verified (Akidau — "Streaming 101/102"; Kafka docs; Flink docs 1.18+).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full streaming entry with Materialize/RisingWave |