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 폴더 제거.
This commit is contained in:
Antigravity Agent
2026-07-05 00:33:48 +09:00
parent 1cfd3bbb56
commit 9148c358d0
6455 changed files with 1 additions and 86875 deletions
@@ -0,0 +1,140 @@
---
id: db-read-replica-patterns
title: Read Replica — Replication Lag / 일관성
category: Coding
status: draft
source_trust_level: B
verification_status: conceptual
created_at: 2026-05-09
updated_at: 2026-05-09
tags: [database, replication, read-replica, consistency, vibe-coding]
tech_stack: { language: "SQL / Postgres / MySQL", applicable_to: ["Backend"] }
applied_in: []
aliases: [replication lag, eventual consistency, write-then-read, read-your-writes]
---
# Read Replica
> Primary 1대 + Replica N대. Read 분산 → Primary 부하↓. **Replication lag (보통 ms~s) 이 함정**. 방금 쓴 데이터 즉시 read 시 미반영 가능 — read-your-writes 패턴 필요.
## 📖 핵심 개념
- Async replication (보통): primary 가 commit 후 replica 로 stream.
- Replication lag: primary→replica 도달 시간.
- Read-your-writes: 자기가 쓴 건 자기가 읽을 때 보여야.
- Strong vs eventual: 모든 쿼리가 강할 필요 없음.
## 💻 코드 패턴
### 라우팅 — Prisma
```ts
import { PrismaClient } from '@prisma/client';
const writer = new PrismaClient({ datasources: { db: { url: process.env.PRIMARY_URL } } });
const reader = new PrismaClient({ datasources: { db: { url: process.env.REPLICA_URL } } });
async function getUserPosts(userId: string) {
return reader.post.findMany({ where: { userId } }); // read = replica
}
async function createPost(input: NewPost) {
return writer.post.create({ data: input }); // write = primary
}
```
### Read-your-writes — sticky after write
```ts
class DbRouter {
private lastWriteAt = 0;
reader() {
if (Date.now() - this.lastWriteAt < 2000) return writer; // 최근 2초 = primary
return reader;
}
async write(fn: (db) => Promise<void>) {
await fn(writer);
this.lastWriteAt = Date.now();
}
}
```
### 좀 더 정확 — LSN tracking (Postgres)
```sql
-- Primary 에서 commit 후 LSN 받음
SELECT pg_current_wal_lsn();
-- Replica 에서 검사
SELECT pg_last_wal_replay_lsn() >= 'X/Y'::pg_lsn AS caught_up;
```
```ts
async function readAfterWrite(query: () => Promise<R>): Promise<R> {
const lsn = await writer.queryRaw('SELECT pg_current_wal_lsn() AS lsn');
for (let i = 0; i < 10; i++) {
const caught = await reader.queryRaw(
`SELECT pg_last_wal_replay_lsn() >= '${lsn}'::pg_lsn AS ok`
);
if (caught.ok) return query.call(reader);
await sleep(50);
}
return query.call(writer); // fallback
}
```
### 라우팅 — request scope
```ts
// Express middleware
app.use((req, res, next) => {
req.db = req.method === 'GET' ? reader : writer;
next();
});
```
### 트랜잭션 안 — primary 만
```ts
// 트랜잭션 내 read 도 primary — replica 는 다른 view 가능
await writer.$transaction(async (tx) => {
const user = await tx.user.findUnique(...); // primary
await tx.post.create({ data: { userId: user.id, ...} });
});
```
### Replication lag 모니터링
```sql
-- Postgres
SELECT now() - pg_last_xact_replay_timestamp() AS lag;
-- MySQL
SHOW REPLICA STATUS\G
-- Seconds_Behind_Source
```
알람: lag > 5s.
## 🤔 의사결정 기준
| 상황 | 라우팅 |
|---|---|
| Write | Primary |
| 즉시 read after write | Primary (2초 sticky) |
| 일반 list / detail | Replica |
| 분석 / 리포트 | Replica (분리된 분석용) |
| 트랜잭션 내 read | Primary (같은 connection) |
| Cache 가능 | Cache 우선, 미스 시 replica |
## ❌ 안티패턴
- **모든 read 를 무조건 replica**: read-after-write 깨짐.
- **트랜잭션 안 read 를 replica**: stale.
- **Lag 모니터링 없음**: 100s lag 도 모름.
- **Replica failover 안 함**: replica 1대 죽으면 모두 실패. health check + 다음 replica.
- **Primary write 성공 → 그 자리에서 replica read**: 거의 무조건 stale.
- **GROUP BY count 같은 무거운 쿼리 primary**: primary 부하. analytic replica 분리.
## 🤖 LLM 활용 힌트
- 기본 read = replica, write = primary.
- Read-your-writes = 2초 sticky 또는 LSN.
- Lag 모니터링 + alarm 필수.
## 🔗 관련 문서
- [[DB_Connection_Pooling_Patterns]]
- [[DB_Sharding_Strategies]]