Before you start
SGLang changes fast. Flags get renamed, defaults move, and new options appear in most releases. Every command below matches the current server arguments documentation. Before you copy a flag into a manifest, check it against your installed version:
python -m sglang.launch_server --help | less
python -c "import sglang; print(sglang.__version__)"
The default port is 30000 and the default host is 127.0.0.1. In a container you nearly always need --host 0.0.0.0.
Launch
python -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-70B-Instruct \
--served-model-name llama-70b \
--tp-size 4 \
--host 0.0.0.0 --port 30000 \
--context-length 32768 \
--mem-fraction-static 0.85 \
--enable-metrics \
--api-key "$SGLANG_API_KEY"
| Flag | What it controls | Notes |
|---|---|---|
--model-path (--model) | HF repo ID or local folder | Pin a revision when you mirror the weights |
--served-model-name | Name returned by /v1/models and expected in model | Keep it stable across weight upgrades |
--tp-size (--tp) | Tensor parallel degree across GPUs | Keep it within one node unless you have NVLink/InfiniBand |
--dp-size (--dp) | Data-parallel replicas in one server | Throughput, not capacity |
--context-length | Max tokens per request | Defaults to the model's config.json |
--quantization | fp8, awq, gptq and others | Must match how the checkpoint was produced |
--kv-cache-dtype | auto, fp8_e5m2, fp8_e4m3 and others | FP8 KV roughly doubles the token pool; check quality |
--api-key | Bearer key for the OpenAI-compatible API | Does not unlock admin endpoints |
--admin-api-key / SGLANG_ADMIN_API_KEY | Key for admin endpoints such as weight updates | Admin calls return 403 without it |
Memory and scheduling
SGLang reserves a static pool for weights and the KV cache up front. When you leave --mem-fraction-static unset, SGLang computes it from free GPU memory. The flags below are the ones you tune.
| Flag | Default | Turn it down when | Turn it up when |
|---|---|---|---|
--mem-fraction-static | auto | OOM at start-up, or OOM from CUDA graphs and activations | The token pool is too small and requests queue |
--max-running-requests | auto | OOM during decode under high concurrency | GPU is idle while num_queue_reqs > 0 |
--max-total-tokens | auto (pool size) | You want to cap the pool explicitly | Rarely set by hand |
--chunked-prefill-size | auto; -1 disables | OOM during prefill of long prompts | Long prompts starve decode less with smaller chunks |
--schedule-policy | fcfs | — | lpm (longest prefix match) favours cache reuse for shared prefixes |
--disable-radix-cache | off | You need strict per-request isolation or are debugging cache bugs | — |
--watchdog-timeout | 300 s | — | A legitimately slow forward batch kills the server |
Warning
Lowering
--mem-fraction-staticto stop a start-up OOM also shrinks the KV pool. If you lower it from 0.88 to 0.75 without touching--max-running-requests, you can trade a crash for heavy queueing at peak. Load test after every memory change.
Typical OOM fixes, in this order:
- OOM during prefill of long prompts: lower
--chunked-prefill-size(for example 4096 or 2048). - OOM during decode with many requests: lower
--max-running-requests. - OOM at start-up or in CUDA graph capture: lower
--mem-fraction-staticby 0.03–0.05 at a time.
Check what the server actually allocated:
curl -s localhost:30000/server_info | jq '{max_total_num_tokens, max_running_requests, mem_fraction_static, chunked_prefill_size, context_length}'
The exact field names in /server_info vary by version. Dump the whole object once and note which fields your build returns.
Calling it
OpenAI-compatible chat:
curl -s localhost:30000/v1/chat/completions \
-H "Authorization: Bearer $SGLANG_API_KEY" -H "Content-Type: application/json" \
-d '{"model":"llama-70b","messages":[{"role":"user","content":"Say OK"}],"max_tokens":8}'
Native generate (handy for testing raw prompts and sampling params):
curl -s localhost:30000/generate -H "Content-Type: application/json" \
-d '{"text":"The capital of France is","sampling_params":{"max_new_tokens":8,"temperature":0}}'
Native endpoints
| Endpoint | Method | Use |
|---|---|---|
/health | GET | Liveness. The process is up |
/health_generate | GET | Readiness. Runs a one-token generation through the scheduler |
/get_model_info | GET | model_path, tokenizer_path, is_generation, architectures |
/server_info | GET | Effective server args, token limits, memory pool sizes |
/v1/models | GET | What clients should put in model |
/flush_cache | POST | Empties the radix (prefix) cache |
/tokenize, /detokenize | POST | Check token counts against the server's tokenizer |
/update_weights_from_disk | POST | Hot-swap weights; admin key required |
Probe split for Kubernetes:
livenessProbe:
httpGet: { path: /health, port: 30000 }
periodSeconds: 10
failureThreshold: 6
readinessProbe:
httpGet: { path: /health_generate, port: 30000 }
periodSeconds: 15
timeoutSeconds: 10
startupProbe:
httpGet: { path: /health, port: 30000 }
periodSeconds: 10
failureThreshold: 120 # large models can take 15+ minutes to load
Caution
Don't use
/health_generateas a liveness probe with a short timeout. Under heavy load the probe request waits in the same queue as user traffic. The kubelet then restarts a pod that was merely busy, and the restart drops every in-flight stream on it.
Flush the prefix cache after you change weights or the chat template outside a restart:
curl -s -X POST "localhost:30000/flush_cache" -H "Authorization: Bearer $SGLANG_ADMIN_API_KEY"
Metrics
Metrics are only exposed on /metrics (same port) when you start with --enable-metrics. Each series carries a model_name label.
| Metric | Type | Read it as |
|---|---|---|
sglang:num_running_reqs | gauge | Requests currently decoding |
sglang:num_queue_reqs | gauge | Waiting requests; sustained > 0 means saturated |
sglang:token_usage | gauge | Fraction of the KV token pool in use |
sglang:cache_hit_rate | gauge | Radix cache prefix hit rate |
sglang:gen_throughput | gauge | Generated tokens per second |
sglang:time_to_first_token_seconds | histogram | TTFT |
sglang:e2e_request_latency_seconds | histogram | Full request latency |
sglang:request_time_per_output_token_seconds | histogram | Per-request TPOT |
sglang:prompt_tokens_total, sglang:generation_tokens_total | counter | Token volume for chargeback |
Metric names have changed between releases. Run curl -s localhost:30000/metrics | grep '^sglang:' on your build before you write alerts.
PromQL starting points:
# p95 TTFT per model
histogram_quantile(0.95, sum by (le, model_name) (rate(sglang:time_to_first_token_seconds_bucket[5m])))
# Saturation: queue building for 10 minutes
avg_over_time(sglang:num_queue_reqs[10m]) > 5
# KV pool nearly full (precedes retractions and latency spikes)
max_over_time(sglang:token_usage[5m]) > 0.95
# Prefix cache hit rate dropped (routing or prompt change broke reuse)
avg_over_time(sglang:cache_hit_rate[30m]) < 0.2
With tensor parallelism, --enable-metrics-for-all-schedulers makes each rank report separately. Filter on tp_rank or your sums double.
Quick symptom map
| Symptom | Likely cause | First move |
|---|---|---|
| CUDA OOM during long prompts | Prefill chunk too large | Lower --chunked-prefill-size |
| Queue grows, GPU util low | --max-running-requests too low or pool too small | Check /server_info, raise carefully |
| Cache hit rate fell after a release | Prompt now starts with a per-request value | Move timestamps and user IDs after the stable prefix |
| 403 on weight update | Used --api-key, not the admin key | Set --admin-api-key |
| Server exits during a huge batch | Watchdog fired | Raise --watchdog-timeout and check for stuck NCCL |
model not found from clients | --served-model-name differs from client config | Compare /v1/models with the client |
Prevent it next time
- Pin the SGLang image tag and the model revision together, and keep them in the same manifest.
- After each upgrade, record the output of
/server_infoandgrep '^sglang:'from/metrics, so renamed flags and metrics show up in a diff. - Alert on
num_queue_reqsandtoken_usage, not only on GPU utilisation. - Load test with your real prompt-length distribution before changing any memory flag in production.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get