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,111 @@
---
id: db-connection-pool
title: DB Connection Pool — 사이즈와 누수
category: Coding
status: draft
source_trust_level: B
verification_status: conceptual
created_at: 2026-05-09
updated_at: 2026-05-09
tags: [database, connection-pool, postgres, vibe-coding]
tech_stack: { language: "Postgres / pgbouncer / Prisma", applicable_to: ["Backend"] }
applied_in: []
aliases: [pool size, max_connections, pgbouncer, transaction mode]
---
# DB Connection Pool
> "pool size = CPU 코어수 × 2" 가 좋은 출발점. 수백으로 키우면 DB 가 죽는다. **누수 패턴**(connection 안 반환)이 throughput 폭발 원인의 90%.
## 📖 핵심 개념
- DB 한 connection = 메모리 ~10MB (Postgres) + 한 backend process. 수천이면 OOM.
- App pool 사이즈 vs DB max_connections 균형.
- 분산 환경: pgbouncer / RDS Proxy 로 multiplex.
## 💻 코드 패턴
### node-postgres 기본
```ts
import { Pool } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // pool size
idleTimeoutMillis: 30_000,// idle 30s 후 닫음
connectionTimeoutMillis: 5_000, // pool 가득이면 5s 대기 후 throw
statement_timeout: 30_000, // 쿼리 자체 30s
});
export async function withTx<T>(op: (c: Client) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query('BEGIN');
const r = await op(client);
await client.query('COMMIT');
return r;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release(); // 누수 방지
}
}
```
### Pool size 계산
```
pool_size = ((core_count * 2) + effective_spindle_count)
// 8코어 SSD: 16~20
```
HikariCP / pg / mysql2 모두 비슷한 휴리스틱.
### pgbouncer transaction mode
```ini
[databases]
mydb = host=postgres dbname=mydb pool_size=100
[pgbouncer]
pool_mode = transaction # 트랜잭션 끝나면 즉시 반환
default_pool_size = 25 # backend 1개당 25 connection
max_client_conn = 1000 # 클라이언트 측 1000 가능
```
client 1000개 → backend 25개. 단 `LISTEN/NOTIFY`, prepared statement 일부 호환 X.
### 누수 감지
```ts
pool.on('connect', () => log.debug('connect'));
pool.on('remove', () => log.debug('remove'));
setInterval(() => {
log.info('pool stats', { total: pool.totalCount, idle: pool.idleCount, waiting: pool.waitingCount });
}, 10_000);
```
`waitingCount > 0` 이 지속되면 pool 부족 또는 누수.
## 🤔 의사결정 기준
| 환경 | 설정 |
|---|---|
| 단일 인스턴스 + 가벼운 트래픽 | max=20, no pgbouncer |
| 다중 인스턴스 / 서버리스 | pgbouncer transaction mode 또는 RDS Proxy |
| Lambda / Edge | RDS Proxy 또는 Hyperdrive — 매 cold start 새 connection 안 만들기 |
| Long-running job | 별도 pool / 별도 user (격리) |
| Read replica 사용 | 읽기/쓰기 분리 pool |
## ❌ 안티패턴
- **release() 누락**: 매 요청 connection 누수 → 곧 모두 점유 → 새 요청 timeout. try/finally.
- **트랜잭션 안에서 외부 API 호출**: connection 묶임. 외부 latency = pool 점유 시간. API 먼저, 그 후 트랜잭션.
- **pool size 1000**: DB 다운. 코어수 × 2~4 권장.
- **prepared statement 캐시 + pgbouncer transaction mode**: 다른 connection 으로 가서 statement 못 찾음. session mode 또는 disable cache.
- **idleTimeout 너무 김**: 사용 안 하는 connection 점유.
- **statement_timeout 미설정**: 한 슬로우 쿼리가 connection 영구 점유.
- **connection 재시도 무한**: DB 다운 시 폭주.
## 🤖 LLM 활용 힌트
- pool size = 코어수 × 2 출발.
- 트랜잭션은 withTx wrapper 패턴 + finally release.
- pgbouncer 면 prepared statement 정책 확인.
## 🔗 관련 문서
- [[DB_Migration_Safety]]
- [[DB_Transaction_Isolation]]