SGLang 모델 게이트웨이
SGLang 모델 게이트웨이 (SGLang Model Gateway)
SGLang Model Gateway는 대규모 LLM 배포를 위한 고성능 모델 라우팅 게이트웨이입니다. 워커 수명주기 관리를 중앙화하고, 이기종 프로토콜(HTTP, gRPC, OpenAI 호환) 전반의 트래픽을 균형 조정하며, 히스토리 저장소·MCP 도구·프라이버시 민감 워크플로우에 대한 엔터프라이즈급 제어를 제공합니다. SGLang 서빙 런타임에 깊게 최적화되어 있지만 어떤 OpenAI 호환 백엔드에도 라우팅할 수 있어요.
출처: 문서
본문
SGLang Model Gateway는 대규모 LLM 배포를 위한 고성능 모델 라우팅 게이트웨이입니다. 워커 수명주기 관리를 중앙화하고, 이기종 프로토콜(HTTP, gRPC, OpenAI 호환) 전반의 트래픽을 균형 조정하며, 히스토리 저장소·MCP 도구·프라이버시 민감 워크플로우에 대한 엔터프라이즈급 제어를 제공합니다. 게이트웨이는 SGLang 서빙 런타임에 깊게 최적화되어 있지만 어떤 OpenAI 호환 백엔드에도 라우팅할 수 있습니다.
개요 (Overview)
- 통합 컨트롤 플레인 (Unified control plane): 이기종 모델 팔리트(fleet) 전반에서 regular·prefill·decode 워커를 등록·모니터링·오케스트레이션.
- 멀티 프로토콜 데이터 플레인 (Multi-protocol data plane): HTTP, PD (prefill/decode), gRPC, OpenAI 호환 백엔드 전반에 트래픽을 라우팅하며 공유 신뢰성 프리미티브를 제공.
- 업계 최초 gRPC 파이프라인: 네이티브 Rust 토큰화·추론 파서·툴 호출 실행으로 높은 처리량의 OpenAI 호환 서빙 지원. 단일 스테이지와 PD 토폴로지 모두 지원.
- 추론 게이트웨이 모드 (
--enable-igw): 멀티 테넌트 배포를 위해 여러 라우터 스택(HTTP regular/PD, gRPC)을 동적으로 인스턴스화하고 모델별 정책을 적용. - 대화 및 응답 커넥터 (Conversation & responses connectors): 채팅 히스토리를 라우터 안에 중앙화해 같은 컨텍스트를 여러 모델·MCP 루프에서 데이터를 업스트림 벤더로 새지 않게 재사용(memory, none, Oracle ATP, PostgreSQL).
- 엔터프라이즈 프라이버시: 에이전트형 다중 턴
/v1/responses, 네이티브 MCP 클라이언트(STDIO/HTTP/SSE/Streamable), 히스토리 저장소가 모두 라우터 경계 안에서 동작. - 신뢰성 코어 (Reliability core): 지터(jitter) 포함 재시도, 워커 범위 서킷 브레이커, 토큰 버킷 속도 제한과 대기열, 백그라운드 헬스 체크, 캐시 인식 부하 모니터링.
- 종합적 관측성 (Comprehensive observability): 40+ Prometheus 메트릭, OpenTelemetry 분산 추적, 구조화 로깅, 요청 ID 전파.
아키텍처 (Architecture)
컨트롤 플레인 (Control Plane)
- Worker Manager: 능력(
/get_server_info,/get_model_info)을 발견하고, 부하를 추적하며, 공유 레지스트리에서 워커를 등록/제거. - Job Queue: 추가/제거 요청을 직렬화하고 상태(
/workers/{worker_id})를 노출해 클라이언트가 온보딩 진행 상황을 추적하게 함. - Load Monitor: 캐시 인식·power-of-two 정책에 실시간 워커 부하 통계를 공급.
- Health Checker: 워커를 지속적으로 프로브하고 준비 상태·서킷 브레이커 상태·라우터 메트릭을 업데이트.
- Tokenizer Registry: HuggingFace 또는 로컬 경로에서 비동기 로딩으로 동적으로 등록된 토크나이저를 관리.
데이터 플레인 (Data Plane)
- HTTP 라우터 (regular & PD):
/generate,/v1/chat/completions,/v1/completions,/v1/responses,/v1/embeddings,/v1/rerank,/v1/classify,/v1/tokenize,/v1/detokenize와 관련 admin 엔드포인트 구현. - gRPC 라우터: 토큰화된 요청을 SRT gRPC 워커로 직접 스트리밍하며 완전히 Rust에서 동작 — 토크나이저·추론 파서·툴 파서가 모두 프로세스 내에 상주. 단일 스테이지와 PD 라우팅, 임베딩·분류 포함 지원.
- OpenAI 라우터: OpenAI 호환 엔드포인트를 외부 벤더(OpenAI, xAI 등)로 프록시하면서 채팅 히스토리와 다중 턴 오케스트레이션은 로컬에 유지.
저장소와 프라이버시 (Storage and Privacy)
- 대화·응답 히스토리는 라우터 계층(memory, none, Oracle ATP, PostgreSQL)에 저장됩니다. 같은 히스토리가 여러 모델·MCP 루프를 지원할 수 있으며 데이터를 업스트림 벤더에 보내지 않습니다.
/v1/responses에이전트형 흐름, MCP 세션, 대화 API가 같은 저장소 계층을 공유해 규제 워크로드에 대한 컴플라이언스를 가능하게 합니다.
설치 (Installation)
Docker
Docker Hub에 다중 아키텍처(x86_64 및 ARM64)를 지원하는 미리 빌드된 Docker 이미지가 있습니다:
docker pull lmsysorg/sgl-model-gateway:latest
전제 조건 (Prerequisites)
- Rust와 Cargo
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source "$HOME/.cargo/env" rustc --version cargo --version - Python에
pip와 virtualenv 도구가 있어야 함.
Rust 바이너리 (Rust Binary)
cd sgl-model-gateway
cargo build --release
Python 패키지 (Python Package)
pip install maturin
# Fast development mode
cd sgl-model-gateway/bindings/python
maturin develop
# Production build
maturin build --release --out dist --features vendored-openssl
pip install --force-reinstall dist/*.whl
빠른 시작 (Quick Start)
일반 HTTP 라우팅 (Regular HTTP Routing)
# Rust binary
./target/release/sgl-model-gateway \
--worker-urls http://worker1:8000 http://worker2:8000 \
--policy cache_aware
# Python launcher
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 http://worker2:8000 \
--policy cache_aware
gRPC 라우팅 (gRPC Routing)
python -m sglang_router.launch_router \
--worker-urls grpc://127.0.0.1:20000 \
--model-path meta-llama/Llama-3.1-8B-Instruct \
--reasoning-parser deepseek-r1 \
--tool-call-parser json \
--host 0.0.0.0 --port 8080
배포 모드 (Deployment Modes)
라우터와 워커 함께 시작 (Co-launch Router and Workers)
하나의 프로세스에서 라우터와 SGLang 워커 팔리트를 시작합니다:
python -m sglang_router.launch_server \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--dp-size 4 \
--host 0.0.0.0 \
--port 30000
라우터 인자가 붙은 종합 예시(--router- 접두사):
python -m sglang_router.launch_server \
--host 0.0.0.0 \
--port 8080 \
--model meta-llama/Llama-3.1-8B-Instruct \
--tp-size 1 \
--dp-size 8 \
--grpc-mode \
--log-level debug \
--router-prometheus-port 10001 \
--router-tool-call-parser llama \
--router-model-path meta-llama/Llama-3.1-8B-Instruct \
--router-policy round_robin \
--router-log-level debug
별도 시작 (HTTP) (Separate Launch, HTTP)
워커를 독립적으로 실행하고 라우터가 HTTP 엔드포인트를 가리키게 합니다:
# Worker nodes
python -m sglang.launch_server --model meta-llama/Meta-Llama-3.1-8B-Instruct --port 8000
python -m sglang.launch_server --model meta-llama/Meta-Llama-3.1-8B-Instruct --port 8001
# Router node
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 http://worker2:8001 \
--policy cache_aware \
--host 0.0.0.0 --port 30000
gRPC 시작 (gRPC Launch)
SRT gRPC 워커를 사용해 최고 처리량과 네이티브 추론/툴 파이프라인을 사용합니다:
# Workers expose gRPC endpoints
python -m sglang.launch_server \
--model meta-llama/Llama-3.1-8B-Instruct \
--grpc-mode \
--port 20000
# Router
python -m sglang_router.launch_router \
--worker-urls grpc://127.0.0.1:20000 \
--model-path meta-llama/Llama-3.1-8B-Instruct \
--reasoning-parser deepseek-r1 \
--tool-call-parser json \
--host 0.0.0.0 --port 8080
gRPC 라우터는 일반 HTTP-등가 서빙과 PD(prefill/decode) 서빙을 모두 지원합니다. 연결 모드가 gRPC로 해석될 때마다 --tokenizer-path 또는 --model-path(HuggingFace ID 또는 로컬 디렉토리)를 제공하세요.
Prefill-Decode 분리 (Prefill-Decode Disaggregation)
PD 인식 캐싱·밸런싱을 위해 prefill과 decode 워커를 분리합니다:
python -m sglang_router.launch_router \
--pd-disaggregation \
--prefill http://prefill1:30001 9001 \
--decode http://decode1:30011 \
--prefill-policy cache_aware \
--decode-policy power_of_two
Prefill 항목은 선택적 bootstrap 포트를 받습니다. PD 모드는 prefill 메타데이터를 decode 출력과 병합하고 결과를 클라이언트로 스트리밍합니다.
OpenAI 백엔드 프록시 (OpenAI Backend Proxy)
히스토리와 MCP 세션은 로컬에 유지하면서 OpenAI 호환 엔드포인트를 프록시합니다:
python -m sglang_router.launch_router \
--backend openai \
--worker-urls https://api.openai.com \
--history-backend memory
OpenAI 백엔드 모드는 라우터 인스턴스당 정확히 하나의 --worker-urls 항목을 기대합니다.
멀티 모델 추론 게이트웨이 (Multi-Model Inference Gateway)
단일 라우터로 여러 모델을 라우팅하려면 IGW 모드를 활성화합니다:
./target/release/sgl-model-gateway \
--enable-igw \
--policy cache_aware \
--max-concurrent-requests 512
# Register workers dynamically
curl -X POST http://localhost:30000/workers \
-H "Content-Type: application/json" \
-d '{
"url": "http://worker-a:8000",
"model_id": "mistral",
"priority": 10,
"labels": {"tier": "gold"}
}'
API 참조 (API Reference)
추론 엔드포인트 (Inference Endpoints)
| Method | Path | Description |
|---|---|---|
POST |
/generate |
SGLang generate API |
POST |
/v1/chat/completions |
OpenAI 호환 채팅 완성 (streaming/tool calls) |
POST |
/v1/completions |
OpenAI 호환 텍스트 완성 |
POST |
/v1/embeddings |
임베딩 생성 (HTTP 및 gRPC) |
POST |
/v1/rerank, /rerank |
리랭킹 요청 |
POST |
/v1/classify |
텍스트 분류 |
토큰화 엔드포인트 (Tokenization Endpoints)
게이트웨이는 배치 지원과 함께 텍스트 토큰화용 HTTP 엔드포인트를 제공하며, SGLang Python 토큰화 API를 미러하도록 설계되었습니다.
| Method | Path | Description |
|---|---|---|
POST |
/v1/tokenize |
텍스트를 토큰 ID로 토큰화 (단일 또는 배치) |
POST |
/v1/detokenize |
토큰 ID를 텍스트로 변환 (단일 또는 배치) |
POST |
/v1/tokenizers |
새 토크나이저 등록 (비동기, 작업 상태 반환) |
GET |
/v1/tokenizers |
등록된 모든 토크나이저 나열 |
GET |
/v1/tokenizers/{id} |
UUID로 토크나이저 정보 조회 |
GET |
/v1/tokenizers/{id}/status |
비동기 토크나이저 로딩 상태 확인 |
DELETE |
/v1/tokenizers/{id} |
레지스트리에서 토크나이저 제거 |
토큰화 요청 (Tokenize Request)
{
"model": "meta-llama/Llama-3.1-8B-Instruct",
"prompt": "Hello, world!"
}
배치 토큰화 요청 (Batch Tokenize Request)
{
"model": "meta-llama/Llama-3.1-8B-Instruct",
"prompt": ["Hello", "World", "How are you?"]
}
토큰화 응답 (Tokenize Response)
{
"tokens": [15339, 11, 1917, 0],
"count": 4,
"char_count": 13
}
디토큰화 요청 (Detokenize Request)
{
"model": "meta-llama/Llama-3.1-8B-Instruct",
"tokens": [15339, 11, 1917, 0],
"skip_special_tokens": true
}
디토큰화 응답 (Detokenize Response)
{
"text": "Hello, world!"
}
토크나이저 추가 (비동기) (Add Tokenizer, Async)
curl -X POST http://localhost:30000/v1/tokenizers \
-H "Content-Type: application/json" \
-d '{"name": "llama3", "source": "meta-llama/Llama-3.1-8B-Instruct"}'
응답:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"status": "pending",
"message": "Tokenizer registration queued"
}
상태 확인:
curl http://localhost:30000/v1/tokenizers/550e8400-e29b-41d4-a716-446655440000/status
파서 엔드포인트 (Parser Endpoints)
게이트웨이는 LLM 출력에서 추론 콘텐츠와 함수 호출을 파싱하는 admin 엔드포인트를 제공합니다.
| Method | Path | Description |
|---|---|---|
POST |
/parse/reasoning |
추론(<think>)을 일반 텍스트에서 분리 |
POST |
/parse/function_call |
텍스트에서 함수/툴 호출 파싱 |
추론 분리 요청 (Separate Reasoning Request)
{
"text": "<think>Let me analyze this step by step...</think>The answer is 42.",
"parser": "deepseek-r1"
}
응답 (Response)
{
"normal_text": "The answer is 42.",
"reasoning_text": "Let me analyze this step by step..."
}
함수 호출 파싱 (Function Call Parsing)
{
"text": "{\"name\": \"get_weather\", \"arguments\": {\"city\": \"NYC\"}}",
"parser": "json"
}
분류 API (Classification API)
/v1/classify 엔드포인트는 시퀀스 분류 모델(예: Qwen2ForSequenceClassification, BertForSequenceClassification)을 사용한 텍스트 분류를 제공합니다.
요청 (Request)
curl http://localhost:30000/v1/classify \
-H "Content-Type: application/json" \
-d '{
"model": "jason9693/Qwen2.5-1.5B-apeach",
"input": "I love this product!"
}'
응답 (Response)
{
"id": "classify-a1b2c3d4-5678-90ab-cdef-1234567890ab",
"object": "list",
"created": 1767034308,
"model": "jason9693/Qwen2.5-1.5B-apeach",
"data": [
{
"index": 0,
"label": "positive",
"probs": [0.12, 0.88],
"num_classes": 2
}
],
"usage": {
"prompt_tokens": 6,
"completion_tokens": 0,
"total_tokens": 6
}
}
응답 필드 (Response Fields)
| Field | Description |
|---|---|
label |
예측 클래스 레이블 (모델의 id2label 설정에서, 또는 LABEL_N 폴백) |
probs |
모든 클래스에 대한 확률 분포 (logits의 softmax) |
num_classes |
분류 클래스 수 |
참고 (Notes)
- 분류는 임베딩 백엔드를 재사용합니다. 스케줄러가 logits를 반환하고 softmax로 확률로 변환됩니다.
- 레이블은 모델의 HuggingFace 설정(
id2label필드)에서 옵니다. 이 매핑이 없는 모델은 일반 레이블(LABEL_0,LABEL_1등)을 사용합니다. - HTTP와 gRPC 라우터 모두 분류를 지원합니다.
대화 및 응답 API (Conversation and Response APIs)
| Method | Path | Description |
|---|---|---|
POST |
/v1/responses |
백그라운드 응답 생성 (agentic loops) |
GET |
/v1/responses/{id} |
저장된 응답 검색 |
POST |
/v1/responses/{id}/cancel |
백그라운드 응답 취소 |
DELETE |
/v1/responses/{id} |
응답 삭제 |
GET |
/v1/responses/{id}/input_items |
응답 입력 항목 나열 |
POST |
/v1/conversations |
대화 생성 |
GET |
/v1/conversations/{id} |
대화 조회 |
POST |
/v1/conversations/{id} |
대화 업데이트 |
DELETE |
/v1/conversations/{id} |
대화 삭제 |
GET |
/v1/conversations/{id}/items |
대화 항목 나열 |
POST |
/v1/conversations/{id}/items |
대화에 항목 추가 |
GET |
/v1/conversations/{id}/items/{item_id} |
대화 항목 조회 |
DELETE |
/v1/conversations/{id}/items/{item_id} |
대화 항목 삭제 |
워커 관리 API (Worker Management APIs)
| Method | Path | Description |
|---|---|---|
POST |
/workers |
워커 등록 큐잉 (202 Accepted 반환) |
GET |
/workers |
헬스·부하·정책 메타데이터와 함께 워커 나열 |
GET |
/workers/{worker_id} |
특정 워커 또는 작업 큐 항목 검사 |
PUT |
/workers/{worker_id} |
워커 업데이트 큐잉 |
DELETE |
/workers/{worker_id} |
워커 제거 큐잉 |
워커 추가 (Add Worker)
curl -X POST http://localhost:30000/workers \
-H "Content-Type: application/json" \
-d '{"url":"grpc://0.0.0.0:31000","worker_type":"regular"}'
워커 나열 (List Workers)
curl http://localhost:30000/workers
응답:
{
"workers": [
{
"id": "2f3a0c3e-3a7b-4c3f-8c70-1b7d4c3a6e1f",
"url": "http://0.0.0.0:31378",
"model_id": "mistral",
"priority": 50,
"cost": 1.0,
"worker_type": "regular",
"is_healthy": true,
"load": 0,
"connection_mode": "Http"
}
],
"total": 1,
"stats": {
"prefill_count": 0,
"decode_count": 0,
"regular_count": 1
}
}
Admin 및 헬스 엔드포인트 (Admin and Health Endpoints)
| Method | Path | Description |
|---|---|---|
GET |
/liveness |
헬스 체크 (항상 OK 반환) |
GET |
/readiness |
준비 상태 체크 (건강한 워커 가용성 확인) |
GET |
/health |
liveness의 별칭 |
GET |
/health_generate |
헬스 generate 테스트 |
GET |
/engine_metrics |
워커의 엔진 수준 메트릭 |
GET |
/v1/models |
사용 가능한 모델 나열 |
GET |
/get_model_info |
모델 정보 조회 |
GET |
/get_server_info |
서버 정보 조회 |
POST |
/flush_cache |
모든 캐시 비우기 |
GET |
/get_loads |
모든 워커 부하 조회 |
POST |
/wasm |
WASM 모듈 업로드 |
GET |
/wasm |
WASM 모듈 나열 |
DELETE |
/wasm/{module_uuid} |
WASM 모듈 제거 |
로드 밸런싱 정책 (Load Balancing Policies)
| Policy | Description | Usage |
|---|---|---|
random |
균등 무작위 선택 | --policy random |
round_robin |
워커를 순서대로 순환 | --policy round_robin |
power_of_two |
워커 두 개를 샘플링해 더 가벼운 것 선택 | --policy power_of_two |
cache_aware |
캐시 지역성과 부하 밸런싱 결합 (기본) | --policy cache_aware |
bucket |
동적 경계로 워커를 부하 버킷으로 분할 | --policy bucket |
캐시 인식 정책 튜닝 (Cache-Aware Policy Tuning)
--cache-threshold 0.5 \
--balance-abs-threshold 32 \
--balance-rel-threshold 1.5 \
--eviction-interval-secs 120 \
--max-tree-size 67108864
| Parameter | Default | Description |
|---|---|---|
--cache-threshold |
0.3 | 캐시 적중을 위한 최소 프리픽스 매치 비율 |
--balance-abs-threshold |
64 | 재밸런싱 전 절대 부하 차이 |
--balance-rel-threshold |
1.5 | 재밸런싱 전 상대 부하 비율 |
--eviction-interval-secs |
120 | 초 단위 캐시 축출 주기 |
--max-tree-size |
67108864 | 캐시 트리 최대 노드 수 |
신뢰성과 흐름 제어 (Reliability and Flow Control)
HTTP 클라이언트 (HTTP Client)
업스트림 HTTP 클라이언트 연결 설정을 구성합니다:
| Parameter | Default | Description |
|---|---|---|
--pool-idle-timeout-secs |
50 | 풀링된 업스트림 HTTP 연결의 유휴 타임아웃(초). SMG_POOL_IDLE_TIMEOUT_SECS로도 설정 가능. |
--connect-timeout-secs |
10 | 새 업스트림 HTTP 연결의 타임아웃(초). SMG_CONNECT_TIMEOUT_SECS로도 설정 가능. |
--pool-max-idle-per-host |
500 | 호스트당 유지할 최대 유휴 업스트림 HTTP 연결. SMG_POOL_MAX_IDLE_PER_HOST로도 설정 가능. |
--tcp-keepalive-secs |
30 | 업스트림 HTTP 연결의 TCP keepalive 유휴 시간(초). SMG_TCP_KEEPALIVE_SECS로도 설정 가능. |
재시도 (Retries)
지수 백오프 재시도를 구성합니다:
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 http://worker2:8001 \
--retry-max-retries 5 \
--retry-initial-backoff-ms 50 \
--retry-max-backoff-ms 30000 \
--retry-backoff-multiplier 1.5 \
--retry-jitter-factor 0.2
| Parameter | Default | Description |
|---|---|---|
--retry-max-retries |
5 | 최대 재시도 횟수 |
--retry-initial-backoff-ms |
50 | 초기 백오프 시간(ms) |
--retry-max-backoff-ms |
5000 | 최대 백오프 시간(ms) |
--retry-backoff-multiplier |
2.0 | 지수 백오프 승수 |
--retry-jitter-factor |
0.1 | 랜덤 지터 계수 (0.0-1.0) |
--disable-retries |
false | 재시도를 완전히 비활성화 |
재시도 가능 상태 코드 (Retryable Status Codes): 408, 429, 500, 502, 503, 504
서킷 브레이커 (Circuit Breaker)
워커별 서킷 브레이커가 연쇄 실패(cascading failures)를 방지합니다:
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 http://worker2:8001 \
--cb-failure-threshold 5 \
--cb-success-threshold 2 \
--cb-timeout-duration-secs 30 \
--cb-window-duration-secs 60
| Parameter | Default | Description |
|---|---|---|
--cb-failure-threshold |
5 | 서킷을 열 연속 실패 횟수 |
--cb-success-threshold |
2 | half-open에서 닫을 성공 횟수 |
--cb-timeout-duration-secs |
30 | half-open 시도 전 시간 |
--cb-window-duration-secs |
60 | 실패 카운팅 윈도우 |
--disable-circuit-breaker |
false | 서킷 브레이커 비활성화 |
서킷 브레이커 상태 (Circuit Breaker States):
- Closed: 정상 동작, 요청 허용
- Open: 실패 중, 요청 즉시 거부
- Half-Open: 복구 테스트 중, 제한된 요청 허용
속도 제한과 대기열 (Rate Limiting and Queuing)
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 http://worker2:8001 \
--max-concurrent-requests 256 \
--rate-limit-tokens-per-second 512 \
--queue-size 128 \
--queue-timeout-secs 30
동시성 한도를 초과하는 요청은 FIFO 대기열에서 대기합니다. 반환:
- 대기열이 가득 차면
429 Too Many Requests - 대기열 타임아웃이 만료되면
408 Request Timeout
헬스 체크 (Health Checks)
--health-check-interval-secs 30 \
--health-check-timeout-secs 10 \
--health-success-threshold 2 \
--health-failure-threshold 3 \
--health-check-endpoint /health
추론 파서 통합 (Reasoning Parser Integration)
게이트웨이는 명시적 thinking 블록이 있는 CoT(Chain-of-Thought) 추론을 사용하는 모델용 내장 추론 파서를 포함합니다.
지원 파서 (Supported Parsers)
| Parser ID | Model Family | Think Tokens |
|---|---|---|
deepseek-r1 |
DeepSeek-R1 | <think>...</think> (초기 추론) |
qwen3 |
Qwen-3 | <think>...</think> |
qwen3-thinking |
Qwen-3 Thinking | <think>...</think> (초기 추론) |
kimi |
Kimi K2 | Unicode think 토큰 |
glm45 |
GLM-4.5/4.6/4.7 | <think>...</think> |
step3 |
Step-3 | <think>...</think> |
minimax |
MiniMax | <think>...</think> |
사용법 (Usage)
python -m sglang_router.launch_router \
--worker-urls grpc://127.0.0.1:20000 \
--model-path deepseek-ai/DeepSeek-R1 \
--reasoning-parser deepseek-r1
gRPC 라우터는 자동으로:
- 스트리밍 출력에서 추론 블록 탐지
- 추론 콘텐츠를 일반 텍스트에서 분리
- 버퍼 관리와 함께 증분 스트리밍 파싱 적용
- 올바른 스트리밍 동작을 위한 부분 토큰 탐지 처리
툴 호출 파싱 (Tool Call Parsing)
게이트웨이는 LLM 출력에서 함수/툴 호출을 여러 형식으로 파싱하는 것을 지원합니다.
지원 형식 (Supported Formats)
| Parser | Format | Description |
|---|---|---|
json |
JSON | 표준 JSON 툴 호출 |
python |
Pythonic | Python 함수 호출 구문 |
xml |
XML | XML 형식 툴 호출 |
사용법 (Usage)
python -m sglang_router.launch_router \
--worker-urls grpc://127.0.0.1:20000 \
--model-path meta-llama/Llama-3.1-8B-Instruct \
--tool-call-parser json
토크나이저 관리 (Tokenizer Management)
토크나이저 소스 (Tokenizer Sources)
게이트웨이는 여러 토크나이저 백엔드를 지원합니다:
- HuggingFace: 모델 ID로 HuggingFace Hub에서 로드
- Local: 로컬
tokenizer.json또는 디렉토리에서 로드 - Tiktoken: OpenAI GPT 모델(gpt-4, davinci 등) 자동 감지
설정 (Configuration)
# HuggingFace model
--model-path meta-llama/Llama-3.1-8B-Instruct
# Local tokenizer
--tokenizer-path /path/to/tokenizer.json
# With chat template override
--chat-template /path/to/template.jinja
토크나이저 캐싱 (Tokenizer Caching)
최적 성능을 위한 2단계 캐싱:
| Cache | Type | Description |
|---|---|---|
| L0 | Exact match | 반복 프롬프트용 전체 문자열 캐싱 |
| L1 | Prefix match | 증분 프롬프트용 프리픽스 경계 매칭 |
--enable-l0-cache \
--l0-max-entries 10000 \
--enable-l1-cache \
--l1-max-memory 52428800 # 50MB
MCP 통합 (MCP Integration)
게이트웨이는 툴 실행을 위한 네이티브 Model Context Protocol (MCP) 클라이언트 통합을 제공합니다.
지원 전송 (Supported Transports)
| Transport | Description |
|---|---|
| STDIO | 로컬 프로세스 실행 |
| SSE | Server-Sent Events (HTTP) |
| Streamable | 양방향 스트리밍 |
설정 (Configuration)
python -m sglang_router.launch_router \
--mcp-config-path /path/to/mcp-config.yaml \
--worker-urls http://worker1:8000
MCP 설정 파일 (MCP Configuration File)
servers:
- name: "filesystem"
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
protocol: "stdio"
required: false
- name: "github"
url: "https://api.github.com/mcp"
token: "ghp_xxxxx"
protocol: "sse"
required: false
- name: "custom-tools"
url: "https://tools.example.com/mcp"
protocol: "streamable"
required: true
pool:
max_connections: 100
idle_timeout: 300
proxy:
http: "http://proxy.internal:8080"
https: "https://proxy.internal:8443"
no_proxy: "localhost,127.0.0.1,*.internal"
inventory:
enable_refresh: true
tool_ttl: 300
refresh_interval: 300
서비스 디스커버리 (Kubernetes) (Service Discovery)
Kubernetes 파드 셀렉터로 자동 워커 디스커버리를 활성화합니다:
python -m sglang_router.launch_router \
--service-discovery \
--selector app=sglang-worker role=inference \
--service-discovery-namespace production \
--service-discovery-port 8000
PD 모드 디스커버리 (PD Mode Discovery)
--pd-disaggregation \
--prefill-selector app=sglang component=prefill \
--decode-selector app=sglang component=decode \
--service-discovery
Prefill 파드는 sglang.ai/bootstrap-port 어노테이션으로 bootstrap 포트를 노출할 수 있습니다. RBAC는 파드에 get, list, watch를 허용해야 합니다.
히스토리와 데이터 커넥터 (History and Data Connectors)
| Backend | Description | Usage |
|---|---|---|
memory |
인메모리 저장소 (기본) | --history-backend memory |
none |
지속성 없음 | --history-backend none |
oracle |
Oracle Autonomous Database | --history-backend oracle |
postgres |
PostgreSQL Database | --history-backend postgres |
redis |
Redis | --history-backend redis |
Oracle 설정 (Oracle Configuration)
# Connection descriptor
export ATP_DSN="(description=(address=(protocol=tcps)(port=1522)(host=adb.region.oraclecloud.com))(connect_data=(service_name=service_name)))"
# Or TNS alias (requires wallet)
export ATP_TNS_ALIAS="sglroutertestatp_high"
export ATP_WALLET_PATH="/path/to/wallet"
# Credentials
export ATP_USER="admin"
export ATP_PASSWORD="secret"
export ATP_POOL_MIN=4
export ATP_POOL_MAX=32
python -m sglang_router.launch_router \
--backend openai \
--worker-urls https://api.openai.com \
--history-backend oracle
PostgreSQL 설정 (PostgreSQL Configuration)
export POSTGRES_DB_URL="postgres://user:***@host:5432/dbname"
python -m sglang_router.launch_router \
--backend openai \
--worker-urls https://api.openai.com \
--history-backend postgres
Redis 설정 (Redis Configuration)
export REDIS_URL="redis://localhost:6379"
export REDIS_POOL_MAX=16
export REDIS_RETENTION_DAYS=30
python -m sglang_router.launch_router \
--backend openai \
--worker-urls https://api.openai.com \
--history-backend redis \
--redis-retention-days 30
영구 저장소에는 --redis-retention-days -1을 사용하세요(기본 30일).
WASM 미들웨어 (WASM Middleware)
게이트웨이는 커스텀 요청/응답 처리를 위한 WebAssembly (WASM) 미들웨어 모듈을 지원합니다. 이를 통해 게이트웨이를 수정·재컴파일하지 않고 인증, 속도 제한, 빌링, 로깅 등을 위한 조직별 로직이 가능해집니다.
개요 (Overview)
WASM 미들웨어는 메모리 격리, 네트워크/파일시스템 접근 없음, 구성 가능한 자원 제한을 갖춘 샌드박스 환경에서 실행됩니다.
| Attach Point | When Executed | Use Cases |
|---|---|---|
OnRequest |
워커로 전달하기 전 | Auth, 속도 제한, 요청 수정 |
OnResponse |
워커 응답 수신 후 | 로깅, 응답 수정, 오류 처리 |
| Action | Description |
|---|---|
Continue |
수정 없이 진행 |
Reject(status) |
HTTP 상태 코드로 요청 거부 |
Modify(...) |
헤더, 본문 또는 상태 수정 |
예시 (Examples)
완전한 동작 예시는 examples/wasm/에 있습니다:
| Example | Description |
|---|---|
auth/ |
보호된 경로용 API 키 인증 |
rate_limit/ |
클라이언트별 속도 제한 (requests/minute) |
logging/ |
요청 추적 헤더와 응답 수정 |
인터페이스 정의는 src/wasm/interface에 있습니다.
모듈 빌드 (Building Modules)
# Prerequisites
rustup target add wasm32-wasip2
cargo install wasm-tools
# Build
cargo build --target wasm32-wasip2 --release
# Convert to component format
wasm-tools component new \
target/wasm32-wasip2/release/my_middleware.wasm \
-o my_middleware.component.wasm
모듈 배포 (Deploying Modules)
# Enable WASM support
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 \
--enable-wasm
# Upload module
curl -X POST http://localhost:30000/wasm \
-H "Content-Type: application/json" \
-d '{
"modules": [{
"name": "auth-middleware",
"file_path": "/absolute/path/to/auth.component.wasm",
"module_type": "Middleware",
"attach_points": [{"Middleware": "OnRequest"}]
}]
}'
# List modules
curl http://localhost:30000/wasm
# Remove module
curl -X DELETE http://localhost:30000/wasm/{module_uuid}
런타임 설정 (Runtime Configuration)
| Parameter | Default | Description |
|---|---|---|
max_memory_pages |
1024 (64MB) | 최대 WASM 메모리 |
max_execution_time_ms |
1000 | 실행 타임아웃 |
max_stack_size |
1MB | 스택 크기 제한 |
module_cache_size |
10 | 워커당 캐시되는 모듈 수 |
참고: 속도 제한 상태는 워커 스레드별이며 게이트웨이 복제본 간에 공유되지 않습니다. 프로덕션에서는 공유 계층(예: Redis)에서 속도 제한을 구현하는 것을 고려하세요.
언어 바인딩 (Language Bindings)
SGLang Model Gateway는 Python과 Go의 공식 언어 바인딩을 제공해 서로 다른 기술 스택과 조직 요구사항과의 통합을 가능하게 합니다.
Python 바인딩 (Python Bindings)
Python 바인딩은 Rust 게이트웨이 라이브러리 주변의 PyO3 기반 래퍼를 제공합니다. 이는 Python에서 게이트웨이 서버를 시작하는 단순한 바인딩입니다.
설치 (Installation)
# From PyPI
pip install sglang-router
# Development build
cd sgl-model-gateway/bindings/python
pip install maturin && maturin develop --features vendored-openssl
사용법 (Usage)
Python 바인딩은 이 문서 전체에서 사용됩니다. 자세한 예시는 Quick Start와 Deployment Modes 섹션을 참고하세요.
핵심 컴포넌트:
- 50+ 설정 옵션이 있는
RouterArgsdataclass - 프로그래매틱 시작용
Router.from_args() - CLI 명령:
smg launch,smg server,python -m sglang_router.launch_router
Go 바인딩 (Go Bindings)
Go 바인딩은 Go 기반 인프라를 가진 조직을 위한 고성능 gRPC 클라이언트 라이브러리입니다. 다음과 같은 경우에 이상적입니다:
- 내부 Go 서비스·도구와의 통합
- 고성능 클라이언트 애플리케이션
- 커스텀 OpenAI 호환 프록시 서버 구축
아키텍처 (Architecture)
+-------------------------------------------+
| High-Level Go API |
| (client.go - OpenAI-style interface) |
+-------------------------------------------+
| gRPC Layer |
+-------------------------------------------+
| Rust FFI Layer |
| (Tokenization, Parsing, Conversion) |
+-------------------------------------------+
핵심 기능 (Key Features):
- FFI를 통한 네이티브 Rust 토크나이제이션 (thread-safe, lock-free)
- 컨텍스트 취소가 있는 전체 스트리밍 지원
- 고동시성을 위한 구성 가능한 채널 버퍼 크기
- 내장 툴 호출 파싱과 채팅 템플릿 적용
설치 (Installation)
# Build the FFI library first
cd sgl-model-gateway/bindings/golang
make build && make lib
# Then use in your Go project
go get github.com/sgl-project/sgl-go-sdk
요구사항: Go 1.24+, Rust 툴체인
예시 (Examples)
완전한 동작 예시는 bindings/golang/examples/에 있습니다:
| Example | Description |
|---|---|
simple/ |
비스트리밍 채팅 완성 |
streaming/ |
SSE가 포함된 스트리밍 채팅 완성 |
oai_server/ |
완전한 OpenAI 호환 HTTP 서버 |
# Run examples
cd sgl-model-gateway/bindings/golang/examples/simple && ./run.sh
cd sgl-model-gateway/bindings/golang/examples/streaming && ./run.sh
cd sgl-model-gateway/bindings/golang/examples/oai_server && ./run.sh
테스트 (Testing)
cd sgl-model-gateway/bindings/golang
# Unit tests
go test -v ./...
# Integration tests (requires running SGLang server)
export SGL_GRPC_ENDPOINT=grpc://localhost:20000
export SGL_TOKENIZER_PATH=/path/to/tokenizer
go test -tags=integration -v ./...
비교 (Comparison)
| Feature | Python | Go |
|---|---|---|
| Primary Use | 게이트웨이 서버 런처 | gRPC 클라이언트 라이브러리 |
| CLI Support | 전체 CLI (smg, sglang-router) | 라이브러리 전용 |
| K8s Discovery | 네이티브 지원 | N/A (클라이언트 라이브러리) |
| PD Mode | 내장 | N/A (클라이언트 라이브러리) |
Python을 사용할 때: 게이트웨이 서버 시작·관리, 서비스 디스커버리, PD 분리.
Go를 사용할 때: 커스텀 클라이언트 애플리케이션 구축, Go 마이크로서비스 통합, OpenAI 호환 프록시 서버.
보안과 인증 (Security and Authentication)
라우터 API 키 (Router API Key)
python -m sglang_router.launch_router \
--api-key "your-router-api-key" \
--worker-urls http://worker1:8000
클라이언트는 보호된 엔드포인트에 Authorization: Bearer <TOKEN>을 제공해야 합니다.
워커 API 키 (Worker API Keys)
# Add worker with explicit key
curl -H "Authorization: Bearer <TOKEN>" \
-X POST http://localhost:8080/workers \
-H "Content-Type: application/json" \
-d '{"url":"http://worker:8000","api_key":"worker-key"}'
보안 설정 (Security Configurations)
- 인증 없음 (No Authentication) (기본): 신뢰된 환경에서만 사용
- 라우터 전용 인증 (Router-only Authentication): 클라이언트가 라우터에 인증
- 워커 전용 인증 (Worker-only Authentication): 라우터는 개방, 워커는 키 필요
- 전체 인증 (Full Authentication): 라우터와 워커 모두 보호
게이트웨이 서버 TLS (HTTPS) (TLS for Gateway Server)
게이트웨이를 HTTPS로 서빙하려면 TLS를 활성화합니다:
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 \
--tls-cert-path /path/to/server.crt \
--tls-key-path /path/to/server.key
| Parameter | Description |
|---|---|
--tls-cert-path |
서버 인증서 경로 (PEM 형식) |
--tls-key-path |
서버 개인 키 경로 (PEM 형식) |
두 파라미터는 함께 제공해야 합니다. 게이트웨이는 TLS 종료에 ring 암호화 프로바이더를 사용한 rustls를 사용합니다. TLS가 구성되지 않으면 게이트웨이는 일반 HTTP로 폴백합니다.
워커 통신용 mTLS (mTLS for Worker Communication)
HTTP 모드에서 워커와의 보안 통신을 위해 상호 TLS (mTLS)를 활성화합니다:
python -m sglang_router.launch_router \
--worker-urls https://worker1:8443 https://worker2:8443 \
--client-cert-path /path/to/client.crt \
--client-key-path /path/to/client.key \
--ca-cert-path /path/to/ca.crt
| Parameter | Description |
|---|---|
--client-cert-path |
mTLS용 클라이언트 인증서 경로 (PEM 형식) |
--client-key-path |
mTLS용 클라이언트 개인 키 경로 (PEM 형식) |
--ca-cert-path |
워커 TLS 검증용 CA 인증서 경로 (PEM 형식, 반복 가능) |
핵심 사항 (Key Points):
- 클라이언트 인증서와 키는 함께 제공해야 함
- 여러
--ca-cert-path플래그로 여러 CA 인증서를 추가할 수 있음 - TLS가 구성되면 rustls 백엔드를 사용
- 모든 워커에 단일 HTTP 클라이언트 생성 (단일 보안 도메인 가정)
- 장기 연결에 TCP keepalive (30초) 활성화
전체 TLS 설정 예시 (Full TLS Configuration Example)
게이트웨이 HTTPS + 워커 mTLS + API 키 인증:
python -m sglang_router.launch_router \
--worker-urls https://worker1:8443 https://worker2:8443 \
--tls-cert-path /etc/certs/server.crt \
--tls-key-path /etc/certs/server.key \
--client-cert-path /etc/certs/client.crt \
--client-key-path /etc/certs/client.key \
--ca-cert-path /etc/certs/ca.crt \
--api-key "secure-api-key" \
--policy cache_aware
관측성 (Observability)
Prometheus 메트릭 (Prometheus Metrics)
--prometheus-host/--prometheus-port로 활성화합니다 (기본 0.0.0.0:29000).
메트릭 카테고리 (40+ 메트릭) (Metric Categories)
| Layer | Prefix | Metrics |
|---|---|---|
| HTTP | smg_http_* |
requests_total, request_duration_seconds, responses_total, connections_active, rate_limit_total |
| Router | smg_router_* |
requests_total, request_duration_seconds, request_errors_total, stage_duration_seconds, upstream_responses_total |
| Inference | smg_router_* |
ttft_seconds, tpot_seconds, tokens_total, generation_duration_seconds |
| Worker | smg_worker_* |
pool_size, connections_active, requests_active, health_checks_total, selection_total, errors_total |
| Circuit Breaker | smg_worker_cb_* |
state, transitions_total, outcomes_total, consecutive_failures, consecutive_successes |
| Retry | smg_worker_* |
retries_total, retries_exhausted_total, retry_backoff_seconds |
| Discovery | smg_discovery_* |
registrations_total, deregistrations_total, sync_duration_seconds, workers_discovered |
| MCP | smg_mcp_* |
tool_calls_total, tool_duration_seconds, servers_active, tool_iterations_total |
| Database | smg_db_* |
operations_total, operation_duration_seconds, connections_active, items_stored |
핵심 추론 메트릭 (gRPC 모드) (Key Inference Metrics)
| Metric | Type | Description |
|---|---|---|
smg_router_ttft_seconds |
Histogram | 첫 토큰까지 시간 |
smg_router_tpot_seconds |
Histogram | 출력 토큰당 시간 |
smg_router_tokens_total |
Counter | 총 토큰 (입력/출력) |
smg_router_generation_duration_seconds |
Histogram | 종단 간 생성 시간 |
지속 시간 버킷 (Duration Buckets)
1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s, 15s, 30s, 45s, 60s, 90s, 120s, 180s, 240s
OpenTelemetry 트레이싱 (OpenTelemetry Tracing)
OTLP 내보내기로 분산 추적을 활성화합니다:
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 \
--enable-trace \
--otlp-traces-endpoint localhost:4317
기능 (Features)
- OTLP/gRPC 익스포터 (기본 포트 4317)
- HTTP·gRPC용 W3C Trace Context 전파
- 배치 스팬 처리 (500ms 지연, 64 스팬 배치 크기)
- 노이즈를 줄이기 위한 커스텀 필터링
- 업스트림 워커 요청으로의 트레이스 컨텍스트 주입
- 서비스 이름:
sgl-router
로깅 (Logging)
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 \
--log-level debug \
--log-dir ./router_logs
선택적 파일 싱크가 있는 구조화 트레이싱. 로그 수준: debug, info, warn, error.
요청 ID 전파 (Request ID Propagation)
--request-id-headers x-request-id x-trace-id x-correlation-id
응답은 상관관계를 위해 x-request-id 헤더를 포함합니다.
프로덕션 권장사항 (Production Recommendations)
이 섹션은 프로덕션 환경에서 SGLang Model Gateway를 배포하기 위한 지침을 제공합니다.
보안 모범 사례 (Security Best Practices)
프로덕션에서 항상 TLS를 활성화하세요:
python -m sglang_router.launch_router \
--worker-urls https://worker1:8443 https://worker2:8443 \
--tls-cert-path /etc/certs/server.crt \
--tls-key-path /etc/certs/server.key \
--client-cert-path /etc/certs/client.crt \
--client-key-path /etc/certs/client.key \
--ca-cert-path /etc/certs/ca.crt \
--api-key "${ROUTER_API_KEY}"
보안 체크리스트 (Security Checklist):
- 게이트웨이 HTTPS 종료용 TLS 활성화
- 워커가 신뢰되지 않은 네트워크에 있을 때 워커 통신용 mTLS 활성화
- 라우터 엔드포인트 보호용
--api-key설정 - 자격 증명에 Kubernetes Secrets 또는 secrets manager 사용
- 인증서와 API 키를 주기적으로 교체
- 방화벽 또는 네트워크 정책으로 네트워크 접근 제한
고가용성 (High Availability)
스케일링 전략 (Scaling Strategy):
게이트웨이는 로드 밸런서 뒤에서 여러 복제본을 실행해 고가용성을 지원합니다. 그러나 중요한 고려사항이 있습니다:
| Component | Shared Across Replicas | Impact |
|---|---|---|
| Worker Registry | No (독립) | 각 복제본이 워커를 독립적으로 발견 |
| Radix Cache Tree | No (독립) | 캐시 적중이 10-20% 감소할 수 있음 |
| Circuit Breaker State | No (독립) | 각 복제본이 실패를 독립적으로 추적 |
| Rate Limiting | No (독립) | 한도가 전역이 아닌 복제본별 적용 |
권장사항 (Recommendations):
- 수직 스케일링보다 수평 스케일링 선호: 과도한 CPU·메모리를 가진 하나의 대형 인스턴스보다 여러 작은 게이트웨이 복제본을 배포. 이는 다음을 제공합니다:
- 더 나은 내결함성 (단일 복제본 실패가 게이트웨이를 죽이지 않음)
- 더 예측 가능한 자원 사용
- 더 쉬운 용량 계획
- Kubernetes 서비스 디스커버리 사용: 게이트웨이가 워커를 자동으로 발견·관리하게 하세요:
python -m sglang_router.launch_router \ --service-discovery \ --selector app=sglang-worker \ --service-discovery-namespace production - 캐시 효율 트레이드오프 수용: 여러 복제본에서 캐시 인식 라우팅 정책의 radix 트리는 복제본 간 동기화되지 않습니다. 이는 다음을 의미합니다:
- 각 복제본이 자체 캐시 트리를 구축
- 같은 사용자의 요청이 다른 복제본에 도달할 수 있음
- 예상 캐시 적중률 감소: 10-20%
- HA 이점을 고려하면 대개 허용 가능
- 세션 친화성 구성 (선택적): 캐시 효율이 중요하다면 요청(예: 사용자 ID 또는 API 키)의 일관된 해시를 기반으로 로드 밸런서에 세션 친화성을 구성하세요.
예시 HA 아키텍처 (Example HA Architecture):
+-------------------+
| Load Balancer |
| (L4/L7) |
+---------+---------+
|
+-------------------+-------------------+
| | |
v v v
+-----------+ +-----------+ +-----------+
| Gateway | | Gateway | | Gateway |
| Replica 1 | | Replica 2 | | Replica 3 |
+-----+-----+ +-----+-----+ +-----+-----+
| | |
+-------------------+-------------------+
|
+-------------------+-------------------+
| | |
v v v
+-----------+ +-----------+ +-----------+
| Worker | | Worker | | Worker |
| Pod 1 | | Pod 2 | | Pod N |
+-----------+ +-----------+ +-----------+
성능 (Performance)
높은 처리량용 gRPC 모드 사용 (Use gRPC mode for high throughput):
gRPC 모드는 SGLang 워커에 최고 성능을 제공합니다:
# Start workers in gRPC mode
python -m sglang.launch_server \
--model meta-llama/Llama-3.1-8B-Instruct \
--grpc-mode \
--port 20000
# Configure gateway for gRPC
python -m sglang_router.launch_router \
--worker-urls grpc://worker1:20000 grpc://worker2:20000 \
--model-path meta-llama/Llama-3.1-8B-Instruct \
--policy cache_aware
gRPC의 성능 이점 (Performance Benefits of gRPC):
- 네이티브 Rust 토크나이제이션 (Python 오버헤드 없음)
- 더 낮은 지연의 스트리밍
- 내장 추론 파서 실행
- 게이트웨이의 툴 호출 파싱
- 직렬화 오버헤드 감소
튜닝 권장사항 (Tuning Recommendations):
| Parameter | Recommendation | Reason |
|---|---|---|
--policy |
cache_aware |
반복 프롬프트에 최선, ~30% 지연 감소 |
--max-concurrent-requests |
2-4x 워커 수 | 처리량을 최대화하면서 과부하 방지 |
--queue-size |
2x max-concurrent | 버스트 트래픽 버퍼 |
--request-timeout-secs |
최대 생성 길이 기반 | 멈춘 요청 방지 |
Kubernetes 배포 (Kubernetes Deployment)
서비스 디스커버리용 파드 라벨링 (Pod Labeling for Service Discovery):
게이트웨이가 워커를 자동으로 발견하려면 워커 파드를 일관되게 라벨링하세요:
# Worker Deployment (Regular Mode)
apiVersion: apps/v1
kind: Deployment
metadata:
name: sglang-worker
namespace: production
spec:
replicas: 4
selector:
matchLabels:
app: sglang-worker
component: inference
template:
metadata:
labels:
app: sglang-worker
component: inference
model: llama-3-8b
spec:
containers:
- name: worker
image: lmsysorg/sglang:latest
ports:
- containerPort: 8000
name: http
- containerPort: 20000
name: grpc
디스커버리용 게이트웨이 설정:
python -m sglang_router.launch_router \
--service-discovery \
--selector app=sglang-worker component=inference \
--service-discovery-namespace production \
--service-discovery-port 8000
PD (Prefill/Decode) 모드 라벨링:
# Prefill Worker
metadata:
labels:
app: sglang-worker
component: prefill
annotations:
sglang.ai/bootstrap-port: "9001"
# Decode Worker
metadata:
labels:
app: sglang-worker
component: decode
PD 디스커버리용 게이트웨이 설정:
python -m sglang_router.launch_router \
--service-discovery \
--pd-disaggregation \
--prefill-selector app=sglang-worker component=prefill \
--decode-selector app=sglang-worker component=decode \
--service-discovery-namespace production
RBAC 요구사항 (RBAC Requirements):
게이트웨이는 파드를 감시할 권한이 필요합니다:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: sglang-gateway
namespace: production
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: sglang-gateway
namespace: production
subjects:
- kind: ServiceAccount
name: sglang-gateway
namespace: production
roleRef:
kind: Role
name: sglang-gateway
apiGroup: rbac.authorization.k8s.io
PromQL 모니터링 (Monitoring with PromQL)
게이트웨이 메트릭 엔드포인트(기본 :29000/metrics)를 스크레이프하도록 Prometheus를 구성하세요.
필수 대시보드 (Essential Dashboards):
1. 요청 속도와 지연:
# Request rate by endpoint
sum(rate(smg_http_requests_total[5m])) by (path, method)
# P50 latency
histogram_quantile(0.50, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le))
# P99 latency
histogram_quantile(0.99, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le))
# Error rate
sum(rate(smg_http_responses_total{status=~"5.."}[5m])) / sum(rate(smg_http_responses_total[5m]))
2. 워커 헬스:
# Healthy workers
sum(smg_worker_pool_size)
# Active connections per worker
smg_worker_connections_active
# Worker health check failures
sum(rate(smg_worker_health_checks_total{result="failure"}[5m])) by (worker_id)
3. 서킷 브레이커 상태
# Circuit breaker states (0=closed, 1=open, 2=half-open)
smg_worker_cb_state
# Circuit breaker transitions
sum(rate(smg_worker_cb_transitions_total[5m])) by (worker_id, from_state, to_state)
# Workers with open circuits
count(smg_worker_cb_state == 1)
4. 추론 성능 (gRPC 모드)
# Time to first token (P50)
histogram_quantile(0.50, sum(rate(smg_router_ttft_seconds_bucket[5m])) by (le, model))
# Time per output token (P99)
histogram_quantile(0.99, sum(rate(smg_router_tpot_seconds_bucket[5m])) by (le, model))
# Token throughput
sum(rate(smg_router_tokens_total[5m])) by (model, direction)
# Generation duration P95
histogram_quantile(0.95, sum(rate(smg_router_generation_duration_seconds_bucket[5m])) by (le))
5. 속도 제한과 대기열
# Rate limit rejections
sum(rate(smg_http_rate_limit_total{decision="rejected"}[5m]))
# Queue depth (if using concurrency limiting)
smg_worker_requests_active
# Retry attempts
sum(rate(smg_worker_retries_total[5m])) by (worker_id)
# Exhausted retries (failures after all retries)
sum(rate(smg_worker_retries_exhausted_total[5m]))
6. MCP 툴 실행
# Tool call rate
sum(rate(smg_mcp_tool_calls_total[5m])) by (server, tool)
# Tool latency P95
histogram_quantile(0.95, sum(rate(smg_mcp_tool_duration_seconds_bucket[5m])) by (le, tool))
# Active MCP server connections
smg_mcp_servers_active
얼러팅 규칙 예시 (Alerting Rules Example):
groups:
- name: sglang-gateway
rules:
- alert: HighErrorRate
expr: |
sum(rate(smg_http_responses_total{status=~"5.."}[5m]))
/ sum(rate(smg_http_responses_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "High error rate on SGLang Gateway"
- alert: CircuitBreakerOpen
expr: count(smg_worker_cb_state == 1) > 0
for: 2m
labels:
severity: warning
annotations:
summary: "Worker circuit breaker is open"
- alert: HighLatency
expr: |
histogram_quantile(0.99, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le)) > 30
for: 5m
labels:
severity: warning
annotations:
summary: "P99 latency exceeds 30 seconds"
- alert: NoHealthyWorkers
expr: sum(smg_worker_pool_size) == 0
for: 1m
labels:
severity: critical
annotations:
summary: "No healthy workers available"
설정 참조 (Configuration Reference)
핵심 설정 (Core Settings)
| Parameter | Type | Default | Description |
|---|---|---|---|
--host |
str | 127.0.0.1 | 라우터 호스트 |
--port |
int | 30000 | 라우터 포트 |
--worker-urls |
list | [] | 워커 URL (HTTP 또는 gRPC) |
--policy |
str | cache_aware | 라우팅 정책 |
--max-concurrent-requests |
int | -1 | 동시성 한도 (-1은 비활성화) |
--request-timeout-secs |
int | 600 | 요청 타임아웃 |
--max-payload-size |
int | 256MB | 최대 요청 페이로드 |
Prefill/Decode
| Parameter | Type | Default | Description |
|---|---|---|---|
--pd-disaggregation |
flag | false | PD 모드 활성화 |
--prefill |
list | [] | Prefill URL + 선택적 bootstrap 포트 |
--decode |
list | [] | Decode URL |
--prefill-policy |
str | None | prefill 노드용 정책 오버라이드 |
--decode-policy |
str | None | decode 노드용 정책 오버라이드 |
--worker-startup-timeout-secs |
int | 600 | 워커 초기화 타임아웃 |
Kubernetes 디스커버리 (Kubernetes Discovery)
| Parameter | Type | Description |
|---|---|---|
--service-discovery |
flag | 디스커버리 활성화 |
--selector |
list | 라벨 셀렉터 (key=value) |
--prefill-selector / --decode-selector |
list | PD 모드 셀렉터 |
--service-discovery-namespace |
str | 감시할 네임스페이스 |
--service-discovery-port |
int | 워커 포트 (기본 80) |
--bootstrap-port-annotation |
str | bootstrap 포트용 어노테이션 |
TLS 설정 (TLS Configuration)
| Parameter | Type | Description |
|---|---|---|
--tls-cert-path |
str | 게이트웨이 HTTPS용 서버 인증서 (PEM) |
--tls-key-path |
str | 게이트웨이 HTTPS용 서버 개인 키 (PEM) |
--client-cert-path |
str | 워커 mTLS용 클라이언트 인증서 (PEM) |
--client-key-path |
str | 워커 mTLS용 클라이언트 개인 키 (PEM) |
--ca-cert-path |
str | 워커 검증용 CA 인증서 (PEM, 반복 가능) |
문제 해결 (Troubleshooting)
워커가 준비되지 않음 (Workers Never Ready)
--worker-startup-timeout-secs를 늘리거나 라우터 시작 전에 헬스 프로브가 응답하는지 확인하세요.
부하 불균형 / 핫 워커 (Load Imbalance / Hot Workers)
워커별로 smg_router_requests_total을 확인하고 캐시 인식 임계값(--balance-*, --cache-threshold)을 조정하세요.
서킷 브레이커 플래핑 (Circuit Breaker Flapping)
--cb-failure-threshold를 늘리거나 타임아웃/윈도우 지속 시간을 연장하세요. 재시도를 임시로 비활성화하는 것을 고려하세요.
대기열 오버플로우 (429) (Queue Overflow)
--queue-size를 늘리거나 클라이언트 동시성을 줄이세요. --max-concurrent-requests가 다운스트림 용량과 일치하는지 확인하세요.
메모리 증가 (Memory Growth)
더 공격적인 캐시 정리를 위해 --max-tree-size를 줄이거나 --eviction-interval-secs를 낮추세요.
디버깅 (Debugging)
python -m sglang_router.launch_router \
--worker-urls http://worker1:8000 \
--log-level debug \
--log-dir ./router_logs
gRPC 연결 문제 (gRPC Connection Issues)
워커를 --grpc-mode로 시작했는지 확인하고 라우터에 --model-path 또는 --tokenizer-path가 제공됐는지 확인하세요.
토크나이저 로딩 실패 (Tokenizer Loading Failures)
비공개 모델의 경우 HuggingFace Hub 자격 증명(HF_TOKEN 환경 변수)을 확인하세요. 로컬 경로가 접근 가능한지 확인하세요.
SGLang Model Gateway는 SGLang 런타임과 함께 계속 진화합니다. 새 기능을 채택하거나 개선에 기여할 때 CLI 플래그, 통합, 문서를 정렬 상태로 유지하세요.