7

生產環境

把推論營運成可靠、可觀測且具成本意識的服務。

12 分鐘閱讀

印刷頁: 177–208

在 GitHub 加星

一口氣讀懂

一個很快的 GPU process 還不是正式服務。先封裝可重現的 runtime,量出 concurrency envelope,用有限 queue 保留超額工作,在延遲失守之前增加 replica,依可用狀態把請求送到正確目的地,並讓 cold start 足夠短,使 scaling policy 能及時反應。容量與 failure domain 要刻意配置,上線要依 live evidence 逐步推進,資料與 weights 要受到保護,成本要算入 total cost of ownership(TCO),觀測則要涵蓋整個請求。time to first token(TTFT)和 tokens per second(TPS)固然重要,但 client setup、network、queue 與 protocol 也會消耗 service-level agreement(SLA)的預算。

為何重要

  • 正式流量會驗證 benchmark 固定不變的假設。抵達突波、超長輸入、cache locality、使用者地理位置與下游變慢,都可能把一個很快的 replica 變成不可靠的產品。只有把這些變動納入容量與延遲設計,實驗室成果才會在真實世界成立。
  • 容量會隨時間改變。Concurrency、batch size、queue depth、replica count 與 cold-start time 其實是同一個 control problem;單獨調整任何一個數字,都可能把 idle cost 換成 latency miss,或把短暫尖峰換成系統 overload。
  • 規模放大之後,硬體與 provider 故障是正常營運的一部分。可靠度來自快速辨識 unhealthy node、隔離 failure domain、準備替代容量,並在事故前演練 failover,而不是期待昂貴 GPU 永遠不壞。
  • 使用者感受到的是 client 到 server 的完整路徑,不是 kernel time。Connection reuse、鄰近 workload、短 queue、提早開始 streaming 或改成 async job,都可能比再提高一次模型局部速度更直接改善產品。

心智模型

先建立 immutable serving artifact。Container image 由經過驗證的 base、精確的 application 與 system dependency、configuration,以及執行時才出現的 ephemeral layer 疊成。鎖定版本並刪除未使用套件,讓 image 可重現、更小、更快搬移,也更容易 audit。大型 model weights 如果遠大於 image,就應分開存放;compiled engine 只能搭配它所要求的完全相同硬體與軟體 identity 來 cache 和重用。

2026 年 1 月版快照:NVIDIA Inference Microservices(NIMs)把受支援的 model 與 GPU 組合封裝成現成 container,包含較彈性的模型家族 image,以及針對特定模型高度最佳化的 image。它可以直接成為服務、reference implementation 或 base layer。經過測試的 opinionated configuration 若符合需求,可以縮短上線時間;若產品限制需要更深控制,從較低階 base 開始通常比硬改既定方案清楚。

生產環境是一個可量測的控制迴圈

Queue depth 流向 Concurrency budget;容量飽和時會觸發 Scaling policy,再啟動 Cold-start path。就緒的 replica 進入 Routing,Routing 的結果流向 Observability;Observability 對照需求、延遲、utilization、錯誤與 replica 狀態,再把修正訊號送回 Scaling policy。

  1. Queue depth有限度保留超額工作,並呈現等待中的需求
  2. Concurrency budget讓 scheduler 容量與每個 replica 相符
  3. Scaling policy把 traffic、utilization、delay 與上下限一起判斷
  4. Cold-start path取得硬體、載入 image 與 weights,最後啟動 engine
  5. Routing依容量、sequence、cache 與 adapter 狀態配置工作
  6. Observability串連延遲、錯誤、需求、utilization 與 replica 狀態
  • Queue depthConcurrency budget: 等待中的工作
  • Concurrency budgetScaling policy: 容量飽和或閒置
  • Scaling policyCold-start path: 增加或替換 replica
  • Cold-start pathRouting: Replica 進入 ready 狀態
  • RoutingObservability: 請求與結果
  • ObservabilityScaling policy: 修正訊號

設定 autoscaling 前先量出 replica envelope。Continuous batching 會在 slot 釋出時加入新 sequence;較大的 active batch 能增加 aggregate throughput,也會讓每個請求變慢。Engine batch limit 與 autoscaler concurrency target 必須來自同一組測試。Traffic signal 能提前預測需求,GPU utilization 則能揭露昂貴 sequence shape,兩者要一起使用;再加上 measurement window、最小與最大 replica、cooldown,以及對 forecast error 的 headroom,policy 才不會對短暫雜訊過度反應。

Scale-up decision 只有在 replica ready 之後才產生價值。把 cold start 拆成 hardware allocation、image transfer、weight transfer 與 engine startup;縮小 bytes、把 cache 放在靠近 GPU 的位置,並在相容條件下安全重用 compiled artifact。容量到達前,用有限的 first-in-first-out 或 priority queue 保留工作。Replica ready 後,依 load、sequence length、key-value prefix state 或 low-rank adaptation(LoRA)weights routing,並立刻把 queued work 填到新 replica 的 concurrency limit。

跨出單一 cluster 後,要把 global control plane 與能獨立持續服務的 workload plane 分開。Reserved capacity 承接 baseline demand,on-demand 或可中斷資源處理 peak;workload 要靠近使用者,同一個 multi-stage request 內則避免 cross-cluster hop。Active-active region 平時就承載 live traffic,故障時能平順切換;active-passive 降低常態使用量,但 standby readiness 必須反覆驗證。Security policy 要涵蓋 user data、model weights、infrastructure access、encryption、isolation、retention 與 geographic processing constraint。

Deployment 本身就是 capacity event。先做 manual test 與 load test,再 shadow 一部分真實 traffic。Canary 讓新版本從很小的 live volume 開始,觀察 correctness、latency、error、quality 與 scaling,再依 guardrail 分段增加流量。Rollback 要隨時可用,每一步也要先 warm 足夠 replica;否則量到的會是 cold queue,而不是新服務。這種方法不需要像 blue-green cutover 一樣先準備完整的雙倍 GPU fleet。

成本應至少用具有代表性的一週來估算。先依 input、output 與 cache behavior 計算 application programming interface(API)帳單,再與 dedicated hardware 在真實 utilization、batch 與 sequence distribution 下的成本比較,並把工程與維運工時納入 TCO。觀測時要把 request volume、sequence size、response code、percentile latency、replica state、host 與 accelerator utilization、queue depth 放在一起;server log 與 change audit 才能解釋這些數值為何同時移動,並支援快速 rollback。

Client 也是 inference 的一部分。重用 transport layer security(TLS)session,避免每個請求重付 setup;若 P95 端到端延遲目標是 300 毫秒,TLS handshake 就可能占掉至少一成預算。有限時間的呼叫使用同步 Hypertext Transfer Protocol(HTTP);重視 throughput 的長工作用 async job 與 webhook;連續、較少結構的雙向 stream 用 WebSocket;具有固定 schema 的 service communication 則用 gRPC。WebSocket 適合未結構化即時資料;gRPC 則以預先定義的 schema 與 validation 支援結構化雙向 stream。

想像一次 traffic burst 正好發生在 scale-down 之後,所有 replica 很快到達 concurrency limit。Queue 能保存已被接受的工作,但 oldest age 會開始消耗 SLA;它不是可以無限延長的倉庫,而是一個正在倒數的 deadline buffer。Traffic rate 與 active concurrency 應比單看 utilization 更早觸發 scale-up,controller 同時用實測 cold-start distribution 推估新 replica 能否在 deadline 前 ready。若 max replica 仍不足,admission policy 必須拒絕、降級或延後低優先工作,不能接受明知無法及時完成的請求。新 replica ready 後要立刻被 router 發現,但只能接收到它實測 envelope 允許的 queued work,否則剛啟動就再次 overload。需求下降後,cooldown 要跨過常見的第二波,而不是看到瞬間空檔就縮容。這個 scenario 同時測試 queue、concurrency、autoscaling、cold start、routing 與 admission;steady-state throughput test 只證明 engine 在流量穩定時能跑多快,無法證明整個 feedback loop 在突波時會保住使用者延遲。

接著在持續流量下移除一個 GPU node,再讓一個 region 失聯。Health automation 必須停止新 placement、cordon 有問題的 node、替換受影響 replica,並把 regional demand 移往其他 capacity,同時遵守 data-location policy,不能為了快速 failover 把受限制資料送到錯誤國家。即使 global controller 暫時不可用,既有 workload plane 仍應繼續接受並處理本地流量;這是 control plane 與 workload plane 分離真正要保護的能力。Active capacity 要能吸收轉移,standby capacity 則要用演練證明它真的載有正確 image、weights、keys、network policy 與 routing rule,而不是只存在於 inventory。Operator 透過 audit log 追蹤 interrupted request、deployment change、access 與可能的 model-state exposure。Recovery 不能只以 replacement process 啟動為終點;必須確認 latency、error rate、queue age、capacity margin、replica health 與 security control 全部回到明定範圍,並保存 timeline 供後續修正 runbook。

Incident timeline 要把 product、system 與 cost signal 串在一起。某次 deployment 可能讓 input sequence 變長,接著提高 prefill utilization、加深 queue、觸發更多 replica;大量 replica 同時啟動又會競爭 image 與 weight bandwidth,讓 cold start 變慢,最後同時推高 latency 和 spend。只看其中任何一張圖,都可能得到錯誤修法,例如盲目增加 max replica,反而讓啟動競爭更嚴重。應在同一個 request identity 與 time window 下連結 release identity、request shape、routing choice、cache behavior、queue age、replica lifecycle、client timing、response code 與 cost allocation。Operator 先判斷 causal chain,再選擇 rollback、限制輸入、調整 routing、增加 bandwidth 或擴容,並觀察下游 signal 是否按預期恢復。同一份 record 也能在事後回答 economics:把 idle headroom、failover reserve、測試 GPU、transfer 與 engineering labor 納入 TCO 後,dedicated capacity 是否仍優於 API;若答案只在理想 utilization 下成立,就還不是可持續的 production decision。

Data handling 要直接寫進 serving contract。若 request input 與 model output 在工作完成後沒有用途,最安全也最省事的做法就是不保存,從源頭縮小 attack surface;不能因為 logging 預設方便,就長期留下使用者內容。若 quality review、audit 或 future training 確實需要 retention,收集之前要先定義 purpose、允許 region、保存時間、encryption、access role、deletion workflow、使用者約定與 incident evidence,並確認 provider 也能執行相同要求。規則不能只套用 primary database;model weights、server log、prompt cache、queue payload、object storage、debug dump、temporary file 與備份都可能殘留敏感內容,也要有相同 inventory、access control 與清除期限。多個 cloud provider 之間的 portability 只有在每個 destination 都維持同等 control、compliance 與 geographic restriction 時才有價值;若 failover 會把資料送出允許範圍,可靠度設計本身就製造了 security incident。

核心概念

Known-good artifact

Container 能跨環境保存脆弱的 dependency chain。Exact version、最小化 filesystem、architecture-aware build、image registry 與 immutable release identity,讓 deployment 可以重複,也讓 rollback 回到已知狀態,而不是臨時重新解 dependency。

Autoscaling 是 feedback loop

Traffic 預測需求,utilization 顯示工作強度,concurrency 與 queue 揭露飽和,cold-start delay 決定必須提前多久動作。穩定 policy 會把所有 signal 與明確上下限、measurement window 和 cooldown 一起判斷。

Placement 跟著可用狀態

平均分配 load 只是起點,不是完整 policy。Sequence cost、prefix cache、adapter residency、region 與 replica readiness,都可能讓其中一個 destination 明顯優於其他選項;router 必須理解這些狀態。

各階段獨立擴縮

Compound workload 應讓 detector、model 與 decoder 各自取得適合的硬體和 replica policy。緊密耦合的階段仍應放在同一 cluster,避免 cross-cluster network time 吃掉端到端 latency budget。

容量需要 failure domain

Multi-cloud 不是把幾個彼此孤立的帳號排在一起。Global scheduling 必須看見可以互換使用的 capacity pool,同時讓每個 workload plane 在 global controller 或其他 region 故障時仍能獨立服務。

先串連,再下結論

Latency 上升可能來自 demand、input length、queueing、error 或 resource pressure。Inference metric 要和 application telemetry、deployment event 放在同一時間軸,operator 才能區分 root cause 與 symptom。

Protocol 跟著 interaction

短 request-response、數小時 job、token stream、live audio 與內部 typed service,需要不同的 connection lifetime、acknowledgement、schema 與 backpressure behavior。選 protocol 是產品行為與 failure handling 的決策,不只是序列化格式。

運作機制

  1. 以可信的 engine base 建立最小 image,鎖定所有 runtime 與 system dependency,完成 security scan,附上 immutable release identity,並證明同一 artifact 能在目標 GPU architecture 啟動。
  2. 使用具代表性的 sequence,在多個 concurrency level 下 load test。選出仍能滿足 tail latency 與 memory limit 的最高 per-replica concurrency,再讓 engine batch 與 autoscaler target 對齊。
  3. 合併 arrival rate、queue depth、active concurrency、compute 與 memory signal。Scale-up 要提早涵蓋實測 cold-start delay;scale-down 則等 cooldown 跨過正常 traffic gap,避免剛縮容就再次啟動。
  4. 分別計時 hardware allocation、image loading、weight loading 與 engine initialization。縮小資料、提高 local bandwidth、cache 相容 build,並在任何階段 regression 時發出 alert,而不是只看總時間。
  5. 宣告 ready 後才能接收 routing。Queue 必須有界,priority 要刻意設計,工作依 load 與 reusable state 配置;到達 max capacity 時,要以可預測方式停止 admission 或 shed load,不能讓等待無限增長。
  6. 注入 node loss、region loss、control-plane interruption、slow downstream 與 preemption。用接近正式的負載驗證 health detection、isolation、rerouting、queue behavior、data policy 與 recovery objective。
  7. 先 shadow 一部分流量,再以預先 warm 的最低容量啟動 canary;依明確 gate 推進 traffic,當 correctness、quality、latency、error 或 cost 超出界線時,自動 rollback 到舊版本。
  8. 從 client send 到 useful output 完整計時。重用 session,依 interaction 選擇 sync、async 或 streaming transport,傳遞 cancellation 與 backpressure,並把 network 和 client parsing 放入 latency trace。

關鍵指標

需求

requests/s 與 tokens/s

依 input、output length、region、model、cache status、adapter 與 customer class 切分,才能看出昂貴流量。

端到端延遲

P50、P90、P99

拆成 client setup、network、queue、prefill、decode 或 model work,以及 response delivery。

Queue health

depth 與 wait age

追蹤 oldest request、admission rejection、priority mix,以及 replica ready 後的 drain rate。

Replica capacity

active concurrency

Batch occupancy 與 throughput 要連同 latency、accelerator memory、compute 與 half-full replica count 報告。

Cold start

各階段秒數

分別報告 hardware、image、weights、engine、readiness,以及 scale-up 期間使用者實際承受的 queue delay。

可靠度

success 與 recovery

監控 response-code rate、node health、failover time、interrupted request 與故障後剩餘 capacity。

經濟性

每個可接受 workload 的成本

在代表性期間納入 reserved 與 burst GPU、idle share、transfer、storage、testing 與 engineering time。

Streaming

連線與首個有用輸出

追蹤 active session、setup 與 reuse、backpressure、disconnect、bytes、underrun 與 reconnect success。

取捨

現成或可控的 image

2026 年 1 月版快照:受支援的 NIM 或 engine image 能減少 setup,並保存已知相容組合。較少 opinion 的 base 能深入控制 kernel、dependency、security 與 startup,代價是團隊必須長期維護這些責任。

吞吐量或個別延遲

增加 concurrent work 會提高 utilization 和總輸出,直到 contention 成為主因;同時每個請求會等更久。選定的 operating point 必須在正式 sequence distribution 下仍滿足 SLA。

Warm capacity 或 cold cost

較高 minimum replica 和較長 scale-down delay 能快速吸收 spike,也會為 idle GPU 付費。Scale to zero 適合間歇性工作,但每個 first request 都依賴 queue durability 與 cold-start speed。

單一 cloud 或 pooled capacity

單一 provider 較容易營運。多個 provider 增加 capacity、locality、redundancy 與 compliance 選擇,也同時增加 global scheduler、portability work 與新的 failure mode。

Blue-green 或 canary

Blue-green 提供完整平行 rollback environment,卻可能讓稀缺 GPU 容量加倍。Canary 用較少 spare hardware 逐步暴露問題,但必須有強 gate 和快速 reversal。

彈性 stream 或 typed stream

WebSocket 適合 continuous unstructured payload,由 application 自行 parsing;gRPC 為 service-to-service work 加上 predefined schema 與 validation,也帶來少量額外 overhead。

工程檢查表

  • 採用前重新驗證每一項 2026 年 1 月版 vendor、engine、client、cloud、price、availability、compliance 與 protocol 敘述。
  • 鎖定並 scan 完整 dependency tree,縮小 image,分離大型 weights,並記錄與硬體相容的 engine cache identity。
  • 設定 autoscaling target 前,在 production-shaped traffic 上一起量測 concurrency、batch、latency、throughput、memory 與 quality。
  • 限制每個 queue,定義 priority 與 admission policy,並測試 overflow、cancellation、retry storm 和 replica discovery。
  • 替每個 cold-start stage 設定 budget 與 alert,確保 scale-up 在 queue 吃完 latency headroom 之前開始。
  • 測試 node、cluster、region、provider 與 control-plane failure,驗證 isolation、failover capacity、request recovery 與 health automation。
  • 減少 retained user data,保護 weights,加密 traffic 與 storage,隔離 workload,限制 access,audit change,並強制執行 residency policy。
  • Shadow 真實流量、prewarm canary、逐步套用 gate、維持可用 rollback,並把 autoscaling behavior 納入 deployment approval。
  • 在同一個 incident view 串連 demand、sequence shape、latency、code、queue、replica、utilization、log、client timing、deployment event 與 cost。

術語

Container image
包含 application 與必要 runtime file 的 immutable layered package。
Continuous batching
Token-level slot 釋出時,就讓新 request 加入的 scheduler。
Cold start
從要求 capacity 到新 model replica 能接收 traffic 的完整延遲。
Router
替單一 request 選擇最合適 serving destination 的元件。
Workload plane
能獨立處理 inference 與 local scaling 的 regional 或 clustered serving plane。
Canary deployment
透過受監控階段,逐步增加新 release 所承接 live traffic 的 rollout。
Observability
用來解釋 system state 的相關 metric、log、alert 與 change history。
Asynchronous inference
提交時先確認接收,之後通常透過 webhook 傳回結果的 job pattern。

原書索引

  • 第 177-183 頁

    Production framing、container layer、dependency discipline、prerelease 與 NIMs。

  • 第 183-192 頁

    Autoscaling、batching、concurrency、cold start、routing、queue、scale to zero 與 stage scaling。

  • 第 193-196 頁

    Multi-cloud plane、GPU supply mechanism、capacity blending 與 geographic routing。

  • 第 196-199 頁

    Hardware failure、high-availability posture、security、compliance 與 data location。

  • 第 199-203 頁

    Testing、canary rollout、API 與 dedicated cost 比較,以及 total ownership cost。

  • 第 203-204 頁

    Metric、log、alert,以及和其他 application context 的 correlation。

  • 第 204-207 頁

    Client overhead、session reuse、async work、streaming、WebSocket 與 gRPC。

  • 第 208 頁

    該版 Baseten 結尾案例,以及書中列出的四項 operating pillar。

Production framing, containers, image layers, dependencies, release pinning, and NIMs
印刷頁: 177–183; PDF 頁: 179–185
Kubernetes, autoscaling signals, concurrency, batching, cold starts, routing, queues, scale to zero, and component scaling
印刷頁: 183–192; PDF 頁: 185–194
Multi-cloud control and workload planes, GPU procurement, capacity mix, and geographic routing
印刷頁: 193–196; PDF 頁: 195–198
Hardware failure, active-active and active-passive designs, security, compliance, and data residency
印刷頁: 196–199; PDF 頁: 198–201
Testing, zero-downtime rollout, canaries, cost estimation, and total cost of ownership
印刷頁: 199–203; PDF 頁: 201–205
Metrics, logs, alerts, causal diagnosis, and integration with application observability
印刷頁: 203–204; PDF 頁: 205–206
Client overhead, connection reuse, asynchronous inference, streaming, HTTP, WebSockets, and gRPC
印刷頁: 204–207; PDF 頁: 206–209
Edition-specific Baseten closing example and its stated operating pillars
印刷頁: 208–208; PDF 頁: 210–210