콘텐츠로 이동

LLM 비용과 지연

분류: Layer 12 - AI 시스템 & LLM 애플리케이션 | 선수지식: L11-50 (트랜스포머), L12-10 (LLM API)

LLM 비용과 지연 — 비용 모델, Latency, 모델 라우팅, Self-Hosting

섹션 제목: “LLM 비용과 지연 — 비용 모델, Latency, 모델 라우팅, Self-Hosting”

LLM 비용·지연은 input/output 토큰·prefill/decode·prompt caching·batch·모델 라우팅·self-hosting의 다축 함수이며, 운영자가 1만1억 호출에서 단가를 2100배 줄이는 표준 패턴들이 정착해 있다.

  • 운영 비용의 80%가 inference: pretraining·fine-tuning은 일회성, inference는 매 호출 누적
  • UX 직결: TTFT 1초 이상이면 챗봇 이탈
  • 모델 라우팅 ROI: 작업·모델 매칭만으로 비용 5~50× 절감 가능
  • Self-hosting trade-off: API vs 자체 호스팅의 손익분기 이해
  • Reasoning 모델 시대: token 비용 5~20× 차이로 운영 결정 더 어려워짐

등장 배경 — per-token 가격은 떨어지는데 inference 부담은 누적된다

섹션 제목: “등장 배경 — per-token 가격은 떨어지는데 inference 부담은 누적된다”

L12-10에서 본 “LLM API = per-token 단가 × 호출 수” 단순 모델이 운영에서 깨지는 지점이 이 토픽의 존재 이유다. 두 곡선이 반대 방향이라 단가 인하만 기다리는 운영은 매년 손해를 본다.

가격 곡선 — 떨어진다:

  • GPT-4 launch (2023.03): output $60/M tokens
  • GPT-4o (2024.05) → 2024.10 인하: output $10/M (input -92%, output -83% TokenMix, AI Pricing History)
  • “good enough” tier는 GPT-3.5 $1.50/M → DeepSeek 계열 $0.50/M으로 약 50~100× 하락
  • 3년 만에 frontier output 가격 4×, 보급형은 100× 인하

부담 곡선 — 누적된다:

  • pretraining은 일회성(GPT-3 1회 ≈ $5M+), inference는 매 호출 누적 — 운영 lifespan 동안 inference 비용이 training을 압도 (Sandgarden, Real Costs of LLMs)
  • 2025 Anthropic 보고치: 인프라 비용이 매출의 약 85% 차지(서빙 burn rate $2.7M/day 추정, Introl, Inference Unit Economics) — premium 가격에도 inference가 마진을 갉아먹는다
  • 사용 패턴이 single-shot → multi-turn(긴 history)·tool-call(중첩 호출)·reasoning(긴 출력)으로 이동하면서 호출당 토큰 수 증가 — 단가 인하분을 호출 패턴 변화가 상쇄

해소 메커니즘 — 단순 per-token 모델의 세 break point에서 별도 기법이 등장:

  1. 같은 prefix를 매번 재계산 지불 → prompt caching (§3.3, cache hit 시 input의 10~50%로 회수)
  2. cheap 모델이 충분한 query까지 frontier로 전송 → 모델 라우팅 (§3.5, RouteLLM 기준 MT Bench 비용 85% 절감 with 95% GPT-4 품질 유지 LMSYS RouteLLM)
  3. 실시간이 필요 없는 호출도 실시간 가격 → Batch API (§3.4, 50% 할인)

이 토픽이 사라지면 깨지는 것: 단가 인하만 기다리는 운영. caching·routing·batch 중 하나라도 빠지면 같은 워크로드에서 단가 인하분의 2~10×를 잃는다(예: 50% 단가 인하가 있어도 caching 미적용 시 입력 비용에서만 -55%p를 놓침; §3.3 hit ratio 50%+ 기준).

Total cost = Σ (input_tokens × price_in + output_tokens × price_out)
- Σ cache_hit_savings
- Σ batch_discount
+ tool_costs (검색·벡터·외부 API)
+ infra_costs (자체 호스팅 시)

Input vs Output 가격 비대칭 (L12-10 §3.7)

섹션 제목: “Input vs Output 가격 비대칭 (L12-10 §3.7)”

거의 모든 provider에서 output이 input보다 4~5× 비쌈. 이유:

  • Prefill (input 처리): 병렬 가능, GPU 활용률 높음 → cheap
  • Decode (output 생성): 토큰 1개씩 순차, memory-bound → expensive
  • o3, Claude extended thinking, R1 등은 reasoning token을 별도 카운트 (출력 전 사고)
  • 같은 답변에 reasoning 모델이 일반 모델보다 5~20× 비용
  • 단 step 수 적어 multi-step 작업에선 합산이 더 쌈 가능
Total latency = TTFT + (output_tokens × ITL) + tool_latency
TTFT (Time To First Token) = network + queue + prefill
ITL (Inter-Token Latency) = decode 한 토큰당 시간
  • TTFT: 첫 토큰 — 사용자 체감 가장 큼 (target: <1s)
  • TPOT (Time Per Output Token): 토큰당 시간 (target: 30~50ms for 30 tok/s)
  • End-to-end latency: 전체 응답 시간
  • Throughput: 동시 처리 가능 요청 수
  • input length (prefill 비례)
  • 모델 크기
  • 서버 큐 depth (P99에 영향 큼)
  • prompt caching 여부
  • 모델 크기
  • batch size (continuous batching)
  • KV cache 메모리·대역폭
  • speculative decoding 사용 여부

3.3 Prompt Caching — 비용 절감 1순위

섹션 제목: “3.3 Prompt Caching — 비용 절감 1순위”

같은 prefix를 재사용해 prefill 비용 절감.

Provider캐싱 방식가격 (cache hit)TTL
Anthropic명시적 (cache_control)input의 10%5분 (write 1.25×) 또는 1시간 (write 2×)
OpenAIAutomatic prefix caching (1024 토큰 이상 자동)input의 50%5~10분
GoogleContext caching (수동)input의 ~25%1시간 default
  • 시스템 프롬프트·few-shot: 항상 caching 대상
  • RAG context: 자주 쓰이는 문서는 caching (예: 사내 정책)
  • 긴 대화 history: 누적 대화는 prefix이므로 자연스럽게 cache hit
  • Hit ratio 모니터링: 50%+ 목표. 낮으면 prompt 구조 점검
[OpenAI / Anthropic / Google Batch API]
요청들을 jsonl 파일로 업로드 → 24시간 내 처리 → 결과 다운로드
  • 할인: input·output 모두 50%
  • 사용처: 비실시간 작업 (데이터 분석, eval, 콘텐츠 생성, 분류)
  • 불용처: 채팅·실시간 agent

3.5 Modal Routing — 작업·모델 매칭

섹션 제목: “3.5 Modal Routing — 작업·모델 매칭”

가장 큰 ROI 절감 도구.

1. Cheap 모델 (예: Haiku 4.5)이 답변 시도
2. confidence 점수 또는 별도 verifier로 평가
3. 부족하면 Sonnet 4.6, 또 부족하면 Opus 4.7
  • 단순 질문은 cheap에서 끝, 복잡한 것만 비싼 모델
  • 공개 벤치마크 수치 (RouteLLM, 95% GPT-4 품질 유지 조건, LMSYS RouteLLM):
    • MT Bench(대화형): 비용 85% 절감 (GPT-4 호출 26%만)
    • MMLU(지식 객관식): 45% 절감 (GPT-4 호출 54%)
    • GSM8K(수학 reasoning): 35% 절감 — 절감폭이 낮아 cascade보다 reasoning 모델 single-step(§3.8)이 합산 더 쌀 수 있음
  • FrugalGPT은 cascade + prompt adaptation + LLM approximation 결합으로 GPT-4 동등 성능에 최대 98% 비용 절감 보고 (Chen et al., arXiv:2305.05176)
  • 다만 위 수치는 router를 본인 traffic으로 tuning한 결과 — 운영 현장에서 quality 모니터링·threshold 튜닝 없이는 30~60% 절감이 현실적 (§3.13의 threshold 튜닝 필수)

작은 LLM(혹은 분류기)이 query를 분류 → 적절한 모델 선택.

query → Router (작은 모델 또는 BERT 분류기)
├─ 일반 chat → GPT-4o-mini
├─ 코드 → Claude Sonnet
├─ 복잡 reasoning → o3
└─ 한국어 도메인 → 자체 fine-tune

query 임베딩 → 미리 만든 카테고리 임베딩과 비교 → 가장 가까운 카테고리의 모델.

  • OpenRouter: 100+ 모델 통합 라우팅 + fallback
  • LiteLLM Router: provider 추상화 + 라우팅 정책
  • Portkey: API gateway + 라우팅 + observability
  • NotDiamond: 자동 모델 선택

API 호출 비용이 일정 규모 이상이면 self-hosting이 더 쌈.

Inference 엔진 (open-weight 모델 호스팅)

섹션 제목: “Inference 엔진 (open-weight 모델 호스팅)”
  • vLLM: PagedAttention, continuous batching, 가장 널리 쓰임
  • TGI (HuggingFace Text Generation Inference): production-ready, k8s 친화
  • SGLang: structured generation 강력
  • TensorRT-LLM (NVIDIA): NVIDIA GPU 최적화 극단
  • llama.cpp: CPU·소형 GPU. edge·local
  • Ollama: 개발용 로컬
~1M 호출/월 미만: API가 거의 항상 쌈
1M~10M 호출/월: 사례별. 한국어·도메인 fine-tune 필요면 self-host
10M+/월: 보통 self-host가 절반 미만 비용
  • GPU: H100 시간당 $23 (Lambda, RunPod), $58 (AWS·Azure 정가)
  • 운영: 모니터링·autoscaling·장애 대응 인력
  • 최적화: vLLM·FlashAttention·speculative decoding 도입에 엔지니어 시간

3.7 Inference 최적화 기법 (L11-50 §3.10·3.11 재방문)

섹션 제목: “3.7 Inference 최적화 기법 (L11-50 §3.10·3.11 재방문)”
기법효과비고
FlashAttention 2/3메모리 O(n) + 속도 2~4×seq_len 길수록 효과 큼
Continuous batchingthroughput 2~4×vLLM 표준. dynamic batch
PagedAttentionKV cache 단편화 60~80% → <4%vLLM, throughput 2~4× ↑
Speculative decodingoutput latency 2~3× ↓EAGLE-3, draft model + target 검증
Prefix cachingTTFT 큰 폭 ↓자주 쓰는 prefix
Quantization (INT8/INT4)메모리 2~4× ↓, 속도 ↑품질 약간 손실 (1~3%)
GQA / MQAKV cache num_heads배 ↓모델 자체 architecture
MoEactive < total params같은 메모리에 더 큰 total
일반 모델 multi-step:
N step × LLM 호출 × (input + output) = 누적 비용
Reasoning 모델 single-step:
reasoning_tokens + output_tokens = 단발 비용 (5~20× 비쌈)
  • 단순 작업 (분류, 추출): 일반 모델 cheap
  • 다단계 reasoning이 필요 (수학, 코드 디버깅): reasoning 모델이 합산 더 쌈
  • 비용 민감 + 정확도 보통: 일반 모델 + self-consistency
  • 정확도 절대 우선: reasoning 모델 + best-of-N

production 운영의 표준.

  • 호출당 input/output 토큰 분포
  • model별 호출 수·비용
  • 사용자/feature/route별 비용 attribution
  • cache hit ratio
  • 평균 latency P50/P95/P99
  • 시간대별 비용 추이
  • Helicone: API gateway + cost dashboard
  • Langfuse: LLM observability + cost tracking
  • LangSmith: trace·cost
  • Portkey: gateway + observability + 라우팅
  • OpenAI usage dashboard: 기본 제공
  • 일/시간당 비용 임계 초과
  • cache hit ratio 폭락
  • TTFT P99 임계 초과
  • 특정 사용자/route 비용 폭증
  • Cache miss explosion: prompt 구조 변경으로 cache hit ratio 폭락
  • Prompt 누적: 대화 history가 무한 증가 → context·비용 폭증 (sliding window 또는 summarize)
  • Tool 안의 LLM 호출: tool이 내부적으로 LLM 호출 → 보이지 않는 비용
  • Reasoning 폭주: reasoning 모델이 너무 길게 생각 → reasoning_budget 제한
  • Stale routing: 라우팅 분류기가 옛 모델 가격으로 결정 → 주기적 재학습
  • Sandbox 폭주: code execution sandbox가 무한 루프 → timeout·max compute
  • Latency p99 무시: 평균은 좋은데 p99가 30초 — UX 핵심 신호

3.11 깨지는 조건 정량 표 (운영 결정용)

섹션 제목: “3.11 깨지는 조건 정량 표 (운영 결정용)”
기법효과 발휘 범위깨지는 조건
Prompt caching같은 prefix 재사용 (>50%)prompt 자주 변경 → cache miss로 비용↑
Batch API비실시간, 24h OK채팅·실시간 agent 부적합
Cascade routingcheap이 70%+ 처리 가능 작업모든 query가 어려운 도메인 → escalation 비율 ↑
Classifier routingquery 카테고리 명확overlap 多 → semantic router 또는 cascade로 fallback
vLLM self-host>5M 호출/월, 한국어·도메인<1M 호출/월은 API가 더 쌈
Speculative decodingoutput 多 (>50 tokens)짧은 output엔 오버헤드
Reasoning model복잡 reasoning단순 작업 비용 5~20× 무의미
Continuous batchinghigh concurrency (>10 req)단발 요청엔 효과 미미
INT8 quantization메모리 절감정확도 critical 작업엔 위험
API 월비용 = (호출 수) × (평균 input + output × 4) × ($per token)
Self-host 월비용 = (GPU 시간) × ($/h) + (운영 인력 비용) + (개발·튜닝 시간)
GPU 시간 = (호출 수 × output token) / (throughput tok/s × 3600)

경험적 break-even:

호출 수/월API ($/월)Self-host (H100×1)권장
1M$1k5k~$2k+ 운영 XAPI
10M$10k50k~$5k+ 운영사례별
100M+$100k500k$1030k + 운영self-host 우위

(input·output 평균 토큰·도메인·모델에 따라 ±50%)

cheap 모델 답변 → confidence·verifier 점수 평가 → threshold 미달 시 escalate
  • threshold 0.8: 너무 보수적 (escalation 비율 ↑) — 비용 절감 효과 적음
  • threshold 0.6: 표준 — 대화형 traffic 기준 escalation 3050%, 평균 비용 510× ↓
  • threshold 0.4: 너무 공격적 — 품질 폭락 위험
  • escalation 비율 모니터링: production traffic의 30~50% 권장. 70%+ → cheap 모델 변경 또는 라우팅 재학습

Task 난이도가 threshold를 결정한다

섹션 제목: “Task 난이도가 threshold를 결정한다”

“threshold 0.6 = 표준”은 대화형 traffic 가정이다. RouteLLM 측정(LMSYS)은 같은 95% GPT-4 품질 조건에서 task별로 cheap 처리 가능 비율이 2× 가까이 차이남을 보여준다:

TaskGPT-4 호출 필요권장 threshold비용 절감
MT Bench(대화)26%0.5~0.6 (공격적)85%
MMLU(지식 QA)54%0.7+ (보수적)45%
GSM8K(수학 추론)cascade↓, §3.8 우선35%

운영 절차 — 새 워크로드는 routing 도입 전에 200~500 query offline replay → cheap-vs-frontier 정답 일치율 분포를 측정 → 그 분포의 ~70 percentile을 threshold 초기값으로 설정. 분포가 dual-peak(쉬운 query / 어려운 query 양극화)이면 cascade보다 classifier routing이 적합.

실패 모드 연결: cascade 도입 후 escalation 비율이 70%+로 오르면 §3.14의 “Stale routing”으로 진단. 흔한 원인은 cheap 모델 신버전(예: Haiku 4.5 → 5.0)이 풀린 뒤 router 분류기를 재학습하지 않아 옛 모델 capability·가격을 기준으로 escalate하는 경우. 분기마다 router 재학습 + cheap 모델 버전 업데이트 동기화.

증상정량 신호원인복구
Cache hit ratio 폭락hit ratio <30%prompt 구조 변경고정 prefix + 동적 suffix 분리
Prompt 누적input 토큰 시간당 2×↑대화 history 무한 증가sliding window 또는 summarize
Tool 안의 LLM 호출tool 호출당 비용 10×↑보이지 않는 비용tool별 budget cap, alert
Reasoning 폭주reasoning_tokens 100k+사고 무한 길어짐reasoning_budget 제한
Stale routingcascade escalation 70%+router 분류기 옛 모델 가격주기적 재학습
Sandbox 폭주timeout 빈발code 무한 루프timeout·max compute 강제
Latency p99 무시평균 OK·p99 30s+큐 depth, hot pathprovider 라우팅 fallback, off-peak 분배

Cache hit ratio 폭락 — 감지·alert·rollback 단위

섹션 제목: “Cache hit ratio 폭락 — 감지·alert·rollback 단위”

위 표는 증상 매트릭스이고, 가장 흔한 1번 항목(Cache hit ratio 폭락)을 명령 단위로 풀어둔다. 나머지 6 항목도 같은 패턴(메트릭 노출 → 임계 alert → 즉시 점검 → revert)으로 적용한다.

감지 — Anthropic 공식 필드(cache_read_input_tokens, cache_creation_input_tokens)로 5분 sliding window hit ratio 계산:

# 풀 스크립트. gateway response hook에서 record(resp) 호출 후
# 모니터링 루프가 hit_ratio_5min()을 주기적으로 평가
import time, anthropic
from collections import deque
client = anthropic.Anthropic()
window = deque(maxlen=600)
def record(resp):
u = resp.usage
window.append((time.time(), u.cache_read_input_tokens,
u.cache_creation_input_tokens))
def hit_ratio_5min():
cutoff = time.time() - 300
recent = [(r, w) for t, r, w in window if t >= cutoff]
reads = sum(r for r, _ in recent)
writes = sum(w for _, w in recent)
if reads + writes == 0:
return None # 캐시 자체가 적용 안 됨 — 별도 신호
return reads / (reads + writes)

Alert 임계 (Prometheus·Datadog rule도 동일 표현):

  • WARNING: hit_ratio_5min < 0.50 5분 지속 — 목표 미달, prompt diff 점검
  • CRITICAL: hit_ratio_5min < 0.30 5분 지속 — rollback 후보
  • 별도 신호: 한 호출에서 cache_read_input_tokens == 0 AND cache_creation_input_tokens == 0인 비율이 10%↑ — 캐시가 아예 적용 안 됨 (모델별 최소 길이 Haiku 2048 / Sonnet·Opus 1024 미달, 또는 cache_control 미부착). hit_ratio 분모 0이라 위 두 alert에 안 잡힘 — 별도 alert 필수 (Anthropic docs: length-based failure는 silent).

Rollback 절차 (CRITICAL alert 후 5분 안에):

Terminal window
# 1) 직전 prompt 변경 식별
git log --since='15 minutes ago' --name-only -- content/prompts/
# 2) prefix를 깬 커밋만 revert (다른 변경 보존)
git revert --no-edit <commit-sha>
# 3) 재배포 + 회복 확인
kubectl rollout status deploy/llm-gateway -n production --timeout=180s
# 이후 hit_ratio_5min()이 0.50+로 복귀하는지 5분 후 재평가

미회복 시: prefix에 timestamp·request_id·user 이름 같은 동적 값이 섞였는지 점검 — 이런 값은 cache_control breakpoint 다음으로 옮겨 고정 prefix와 분리한다.

3.15 LLM 비용·지연의 일반 매핑 (Transferable Pattern)

섹션 제목: “3.15 LLM 비용·지연의 일반 매핑 (Transferable Pattern)”

LLM 비용·지연 = “통신·연산·캐시” 의 trade-off. 분산 시스템과 같은 패턴.

LLM 비용·지연 구성요소일반 시스템 매핑
Input vs Output 비대칭DB read vs write, 압축 vs 압축 해제
Prefill (병렬) vs Decode (순차)batch processing vs streaming
Prompt cachingHTTP cache, CDN, redis 정적 자원
Batch API (24h)spot instance, off-peak processing
Cascade routingDB query plan optimizer, hot/cold tier
Self-host vs APIon-prem vs cloud, build vs buy
Continuous batchingrequest coalescing, queue-based ETL
Speculative decodingbranch prediction in CPU, prefetch
Quantization (INT8/INT4)columnar compression (Parquet, ORC)

일반 공식: “비용·지연 = 자원 × 가격 - 캐시 - 압축”. 3차원 trade-off가 모든 분산 시스템 운영에 공통이며, LLM은 토큰 비용과 비결정성이 추가된 사례.

운영 시나리오 — 사내 챗봇 비용 50% 절감 사례 (예시)

섹션 제목: “운영 시나리오 — 사내 챗봇 비용 50% 절감 사례 (예시)”
상황: 사내 챗봇 GPT-4o, 월 $15k. P95 TTFT 1.5s.
선택지:
A. Anthropic prompt caching (시스템 prompt 2k 토큰):
- cache hit 70%+ → input 비용 -63%
B. Cascade routing (Haiku → Sonnet → Opus):
- Haiku에서 60% 처리, Sonnet 30%, Opus 10%
- 평균 비용 5~10× ↓
C. Self-host (Llama-3-8B + vLLM + 4090):
- 운영 부담 ↑, 한국어 fine-tune 필요
- 손익분기 5M+ 호출/월
D. Batch API (비실시간 작업 30%):
- 50% 할인
선택: A + B + D 결합 (self-host는 운영 부담).
대안 비선택: C는 호출량 부족, D 단독은 caching 효과 X.
결과 (가상): $15k → $4.5k (~70% ↓), P95 TTFT 1.5s → 600ms.
silent failure (§3.14):
- cache miss 폭증 → prompt 구조 점검
- cascade escalation 70%+ → cheap 모델 변경
- reasoning 폭주 → reasoning_budget 제한

§3.3 caching + §3.5 routing + §3.11 깨지는 조건 + §3.14 silent failure + §3.15 일반 매핑 모두 적용.

같은 시나리오를 일반 공식 “자원 × 가격 − 캐시 − 압축”으로 재분해

섹션 제목: “같은 시나리오를 일반 공식 “자원 × 가격 − 캐시 − 압축”으로 재분해”

위 시나리오에서 채택한 A·B·D가 어느 항을 건드리는지 분해하면 결정의 직교성이 명확해진다:

  • A. Prompt caching−캐시 항. 자원·가격은 그대로, prefix 80%를 cache 가격(input의 10%)으로 회수 → input 비용 -63%
  • B. Cascade routing자원 × 가격 항을 직접 줄임 (cheap 모델은 토큰 처리 비용 자체가 작은 자원 × 낮은 가격). 캐시·압축 항이 아니다
  • D. Batch API−압축 항 (시간 차원 압축: 24h 지연 허용 → 50% 가격으로 환원)
  • C. Self-host (비채택) → 항 구조 자체를 교체 (per-token × 호출 수per-GPU-hour × 시간). 호출량이 손익분기 미달이면 새 항 합계가 더 큼

A·B·D가 서로 다른 항을 건드려서 효과가 곱으로 누적된 반면, “Anthropic caching + 같은 prefix를 자체 redis로 또 캐시”처럼 같은 항(−캐시)을 두 번 건드리면 ROI가 잠식된다 — 이게 새 절감 제안을 평가할 때 먼저 봐야 할 축.

같은 공식을 LLM 밖 시스템에 적용하면 진단 절차가 동형이다:

  • CDN edge: 자원=오리진 요청 수×응답 크기, 가격=오리진 단가, −캐시=edge hit ratio, −압축=Brotli/gzip — “edge hit ratio 폭락” 진단은 §3.14 cache hit 폭락과 같은 패턴(prefix가 깨졌나 → URL/Vary 헤더가 변동했나)
  • DB read replica + Redis: 자원=쿼리 수×row 크기, 가격=IO·CPU, −캐시=Redis hit, −압축=columnar(Parquet) — 부하 절감 제안의 항 매핑이 LLM과 같음
  • Spark batch ETL: 자원=레코드×스키마, 가격=executor-hour, −캐시=데이터셋 cache, −압축=Snappy/ZSTD + spot instance(시간 압축, batch API와 동일 메커니즘)
  • 모든 LLM 운영 (cost·UX 직결)
  • 모델 선택·교체 결정
  • Self-host vs API 결정
  • Prompt 구조 최적화 (caching 친화적)
  • Reasoning 모델 도입 결정
  • Capacity planning (예측 비용·자원)

플랫폼 엔지니어가 LLM 비용·지연을 운영할 때 다음에 도움된다.

  • 모델 라우팅 도입: cascade(Haiku → Sonnet → Opus) 또는 classifier로 평균 비용 5~20× 절감
  • Prompt caching 패턴: 시스템 prompt·RAG context·few-shot은 모두 caching 대상. 50%+ hit 목표
  • Batch API 활용: 비실시간 작업 (eval·요약·분류)은 50% 할인
  • TTFT P99 SLO: 챗봇은 1초 이내, 그 외 2~3초 이내. streaming + caching이 핵심
  • Self-host 손익분기: 1M+/월 + 한국어·도메인 fine-tune 필요면 vLLM 도입 검토
  • Reasoning 모델 cost guard: reasoning_budget·tier 분리로 비용 폭주 방어
개념 A개념 B차이점
Input priceOutput price4~5× 차이. output은 decode (sequential)
PrefillDecode입력 병렬 vs 출력 sequential. cost·latency 다름
TTFTTPOT첫 토큰 vs 토큰당. 둘 다 UX 중요
Prompt cachingBatch API즉시 5090% ↓ vs 24h 비동기 50% ↓
Cascade routingClassifier routeconfidence 기반 단계 vs 사전 분류
APISelf-hostper-token vs per-GPU-hour. 호출량에 따라 손익분기
QuantizationDistillation같은 모델 압축 vs 작은 모델 학습
Speculative decContinuous batchoutput latency vs throughput
Reasoning 모델일반 + multi-step단발 5~20× 비싸지만 step ↓ vs 다단계 누적
  • Input·Output 가격 4~5× 차이의 이유(prefill 병렬 vs decode sequential)를 설명할 수 있다
  • TTFT·TPOT·throughput을 운영 SLO 관점에서 정의할 수 있다
  • Anthropic vs OpenAI prompt caching 동작 차이를 비교할 수 있다 (명시 vs automatic, 가격 10% vs 50%)
  • Cascade·Classifier·Semantic 3가지 모델 라우팅 패턴을 적용할 수 있다
  • vLLM의 PagedAttention·continuous batching이 throughput을 늘리는 메커니즘을 설명할 수 있다
  • API vs Self-host의 손익분기 휴리스틱(1M/월·10M/월)을 설명할 수 있다
  • Reasoning 모델 vs 일반 모델 multi-step의 비용 결정 프레임을 적용할 수 있다
  • Cache miss explosion·prompt 누적·tool 안의 LLM 호출 등 silent failure를 진단할 수 있다
  • 비용: input/output, prompt caching, batch API, reasoning tokens, prompt token reuse
  • Latency: TTFT, TPOT, prefill/decode, queue depth, p50/p95/p99
  • Routing: cascade, classifier, semantic router, OpenRouter, LiteLLM Router, NotDiamond, Portkey
  • Inference 엔진: vLLM, TGI, SGLang, TensorRT-LLM, llama.cpp, Ollama, MLC-LLM
  • 최적화: PagedAttention, continuous batching, speculative decoding, EAGLE-3, FlashAttention 3, FlashDecoding
  • Quantization: INT8/INT4, AWQ, GPTQ, GGUF, ExLlamaV2, bitsandbytes
  • 모니터링: Helicone, Langfuse, LangSmith, Portkey, OpenAI usage, custom OpenLLMetry

prompt caching 효과 측정 (풀 실행 가능, Anthropic SDK):

# requirements: pip install "anthropic>=0.40.0"
# env: export ANTHROPIC_API_KEY=...
import os, time
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
LONG_SYSTEM = "당신은 사내 정책 도우미입니다.\n" + ("정책 본문 " * 600) # ≈2k 토큰
def call(use_cache: bool):
sys_block = [{
"type": "text",
"text": LONG_SYSTEM,
**({"cache_control": {"type": "ephemeral"}} if use_cache else {}),
}]
r = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=200,
system=sys_block,
messages=[{"role": "user", "content": "휴가 정책 요약해줘"}],
)
u = r.usage
return u.cache_creation_input_tokens, u.cache_read_input_tokens
call(True); time.sleep(2) # warm-up: 첫 호출은 cache write
reads = creates = silent = 0
for _ in range(100):
cw, cr = call(True)
creates += cw; reads += cr
if cw == 0 and cr == 0:
silent += 1
if reads + creates == 0:
print("⚠️ silent failure: 캐시 미적용 (prompt가 모델별 최소 길이 미달?)")
else:
print(f"cache_read={reads} cache_creation={creates} "
f"hit_ratio={reads/(reads+creates):.1%} silent_count={silent}/100")

예상 출력 (Haiku 4.5, system prompt ≈2k 토큰, 2026-04 측정 기준):

cache_read=198400 cache_creation=2000 hit_ratio=99.0% silent_count=0/100

해석:

  • 첫 호출만 cache write(2000), 99회 read → hit ratio 99%
  • input 비용 = (1×100% + 99×10%) / 100 = ≈10.9% (≈ -89% 절감, Anthropic Prompt Caching docs — cache hit는 input의 10%)
  • silent_count > 0이면 일부 호출이 임계 미달 — Haiku는 2048, Sonnet/Opus는 1024 토큰 이상이어야 캐시
  • hit_ratio가 50% 아래로 떨어지면 prefix에 동적 값(timestamp·user_id 등)이 섞였는지 점검

다음 단계: OpenAI usage dashboard 1주일 export → input/output 토큰 비율 확인 (보통 input 70~90%) → 같은 prompt를 OpenAI automatic prefix caching(1024+ 자동, 50% 할인)로도 재측정.

  • streaming on/off로 같은 prompt의 TTFT 측정 (time.perf_counter로 첫 청크 시점)
  • OpenAI vs Anthropic vs Gemini의 TTFT 분포 P50/P95/P99 비교
  • LiteLLM Router로 cascade 패턴 (Haiku → Sonnet → Opus) 구현 — 평균 비용 측정
  • OpenRouter API로 동일 prompt를 5개 모델에 송출 — 가격·latency·품질 dashboard

vLLM 서버 기동 + 동시 부하 throughput 측정 (H100 80GB 1장 가정):

Terminal window
# 1) vLLM OpenAI-compatible 서버 기동
pip install "vllm==0.6.4"
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--tensor-parallel-size 1 \
--max-num-seqs 256 \
--gpu-memory-utilization 0.90 \
--port 8000 &
# 2) 별도 터미널에서 동시 100 요청 부하
python -m vllm.entrypoints.cli.main bench serve \
--backend openai \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--base-url http://localhost:8000 \
--dataset-name sharegpt \
--num-prompts 1000 \
--max-concurrency 100

예상 출력 (입력 평균 200 / 출력 평균 200 토큰):

============ Serving Benchmark Result ============
Successful requests: 1000
Request throughput (req/s): 18.4
Output token throughput (tok/s): 3680
Total Token throughput (tok/s): 7360
----------- Time to First Token ----------------
Mean TTFT (ms): 120
P50 TTFT (ms): 98
P99 TTFT (ms): 380
----------- Time Per Output Token --------------
Mean TPOT (ms): 22
P50 TPOT (ms): 20
P99 TPOT (ms): 45
==================================================

해석:

  • 공식 보고치: Llama 3.1 8B BF16 / H100 1장 ≈ 12.5k tok/s 합산 throughput (Microsoft ND-H100-v5 측정). 본 예시 7.4k는 sharegpt + max-concurrency 100 기준의 보수적 측정
  • TTFT p99 380ms = §3.2 target <1s 충족
  • --max-num-seqs 1로 같은 부하 재실행 시 throughput 3~4× 하락 — continuous batching 기여도 직접 확인 가능

다음 단계: 동일 모델·워크로드를 SGLang으로 재측정 — H100 1장에서 16.2k tok/s 보고가 있어 (SitePoint 2026 비교) vLLM 대비 +29% 이득이 본인 환경에서 재현되는지 확인.

  • 같은 수학 문제를 GPT-4o + multi-step CoT vs o3 single-step — 비용·정확도·시간 비교
  • reasoning_budget 1k/4k/16k로 sweep — 정확도 vs 비용 곡선
  • cache hit ratio 낮음 → prompt 구조 점검 (caching 단위 prefix가 변경 안 됨?)
  • TTFT P99 폭증 → 서버 큐 depth, model 사용률, 시간대별 패턴
  • self-host throughput 낮음 → GPU 활용률, batch size, FlashAttention 적용 여부
  • 라우팅 비용 절감 안 됨 → cheap 모델 fallback 비율 점검 (너무 많이 escalation?)
  1. LLM 비용은 input/output·prefill/decode 비대칭과 prompt caching·batch API·모델 라우팅으로 5~50× 절감 가능.
  2. TTFT (target <1s)·TPOT (30~50ms) 두 SLO가 챗봇 UX 핵심이고, streaming·caching·speculative decoding이 표준 도구.
  3. Cascade·Classifier·Semantic routing이 평균 비용 5~20× 절감의 가장 큰 ROI 도구.
  4. vLLM·TGI·SGLang이 self-host 표준 (PagedAttention·continuous batching). API 손익분기는 보통 1M~10M/월.
  5. Reasoning 모델은 token 5~20× 비싸지만 step 수 적어 다단계 작업에서 합산 더 싼 경우 多 — 작업별 결정.

최종 수정: 2026-04-26