找出延遲從何而來

閱讀約 51 分鐘,9 節 中共有 9 個範例。

版次 2026.11.2 範例於 2026年11 月 23 通過測試 80 個範例中有 80 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

Labs

透過實作學習本章

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。

在 Lab 中開啟,於新分頁開啟

正在檢查您的時數…

正在尋找您的 Lab…

於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。

讀完本章,你能說出在中位數與尾端兩種情況下,是哪一個步驟決定了一則訊息的耗時,並能印出每個數字,同時附上其樣本數與圍繞該數字的區間。Ambrewick 的助理回答每則訊息最多經過五個步驟。它的追蹤紀錄會列出一則訊息的每個步驟,卻看不出是哪一個步驟決定了這則訊息的結束時間。在基準日第 1 天,本章讀取的 200 則訊息中,訊息耗時的中位數為 8,099.3 ms,第 95 百分位數為 18,351.2 ms。這些時間是花在閱讀文章、撰寫回覆,還是等待工具?

本章所有的時間都來自同一台錄製機器,也就是 2.10 GHz 的 4 vCPU Intel Xeon,上面執行的是 Qwen3-4B-Instruct-2507(以下簡稱 4B)。每個時間不是某次呼叫的錄製時間,就是在 重播與虛擬時鐘 所述的虛擬時鐘上將這些時間加總的結果。本章所說的一則訊息的耗時,是在該時鐘上,把它所發出的每次呼叫的錄製時間、行程內工具的模擬時間,以及 contacts 呼叫的錄製時間相加而得。錄製器也記下了呼叫之間的間隔時間,而重播時會省略這段時間。整天下來,這段時間合計 651.4 ms,各節會說明其中的數字屬於這兩者中的哪一種。

本章依序建立決定一則訊息結束時間的呼叫鏈,把每次模型呼叫拆分為讀取與寫入兩部分,最後討論尾端,並為每條路徑列出百分位數及其區間。

關鍵路徑決定結束時間

一則訊息的追蹤(trace)是一棵帶有時間的 span 樹,根 span 在回覆送出時結束。多數 span 位於根 span 之內,其中大多數並不決定結束時間。要找出真正決定結束時間的 span,可以從根 span 的結束點往回走:先取最後結束的子 span,再取在該子 span 開始之前最後結束的子 span,如此持續,直到走回根 span 的開始點。關鍵路徑就是決定一則訊息結束時間的那條 span 鏈;縮短任何其他 span,都不會讓訊息更早結束。縮短鏈上的 span,訊息就會變短,直到另一條鏈變成較長的一條為止。

critical-path-one-message.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Replay the slowest message of baseline day 1 and list the chain of spans that sets its end time. The replay runs thecalls one after another, so every call is on the chain, and shortening any one of them shortens this message: the pointrests on the path lines and the assert that the path covers the whole message. The recorder's gaps between calls arenot in the replay; the day's total of them is printed beside it. The tool's time is modelled, a few microseconds, so itprints as 0.0 ms."""from lib.critical_path import critical_pathfrom lib.dayrun import DATA, run_day, run_day_tracedfrom lib.report import fmt_ms, fmt_shareimport jsonDAY = "2026-12-08"runs = run_day(DAY)                                                      # all 200 messages, in arrival orderslowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the longest of the day; no other message ties with ittraced = run_day_traced(DAY, [slowest.message.message_id], live=False)   # its spans, replayed the same wayby_id = {row["span_id"]: row for row in traced.spans}path = critical_path(traced.spans)                                       # root first, then the chain in time ordermessage = by_id[path[0]]message_time = message["end_ns"] - message["start_ns"]chain = [by_id[span_id] for span_id in path[1:]]covered = sum(row["end_ns"] - row["start_ns"] for row in chain)print("message:", slowest.message.message_id)print("route:", slowest.outcome.route)print("message time:", fmt_ms(message_time))for number, row in enumerate(chain, start=1):    # The inference spans carry their prompt's name, so the route call and the answer calls read apart.    name = row["attributes"].get("gen_ai.prompt.name", row["name"])    print(f"on the path, {number}: {name}, time: {fmt_ms(row['end_ns'] - row['start_ns'])}")print("share of the message time on the path:", fmt_share(covered, message_time))# The recorder's own offsets give the gaps the replay does not keep: each message's span minus its calls' times.rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]gap_ns = 0for message_id in sorted({row["message_id"] for row in rows}):    calls = [row for row in rows if row["message_id"] == message_id]    span = max(c["offset_ns"] + c["total_ns"] for c in calls) - min(c["offset_ns"] for c in calls)    gap_ns += span - sum(c["total_ns"] for c in calls)print("gaps between calls, recorded, all messages of the day:", fmt_ms(gap_ns))# A constructed tree, not the recording: two calls that overlap. The one that ends last sets the end, and the other# is off the path, since the walk back from the end reaches the later call's start before it reaches the earlier one.toy = [    {"span_id": "a", "parent_span_id": None, "start_ns": 0, "end_ns": 10, "span_seq": 1},    {"span_id": "b", "parent_span_id": "a", "start_ns": 0, "end_ns": 6, "span_seq": 2},    {"span_id": "c", "parent_span_id": "a", "start_ns": 2, "end_ns": 9, "span_seq": 3},]toy_covered = sum(row["end_ns"] - row["start_ns"] for row in toy if row["span_id"] in critical_path(toy)[1:])print("constructed overlap, span IDs on the path:", ", ".join(critical_path(toy)))print("constructed overlap, share of the root's time on the path:", fmt_share(toy_covered, toy[0]["end_ns"] - toy[0]["start_ns"]))assert critical_path(toy) == ["a", "c"]assert covered == message_time                 # the chain's calls cover the whole message, with no gapassert len(chain) == len(traced.spans) - 1     # every call of the message is on the path
輸出python critical-path-one-message.py
message: 7055
route: calendar
message time: 24,305.8 ms
on the path, 1: ambrewick.route, time: 1,666.5 ms
on the path, 2: ambrewick.answer, time: 14,993.5 ms
on the path, 3: execute_tool add_event, time: 0.0 ms
on the path, 4: ambrewick.answer, time: 7,645.8 ms
share of the message time on the path: 100.0%
gaps between calls, recorded, all messages of the day: 651.4 ms
constructed overlap, span IDs on the path: a, c
constructed overlap, share of the root's time on the path: 70.0%
習題 7.1

讓訊息自身的 span 不進入鏈中

+10 則證明

第 20 行以整條路徑建立鏈,因此訊息自身的根 span 被算成一個環節。請修改第 20 行,讓鏈只包含走訪時在根之下所到達的呼叫。

path = critical_path(traced.spans)                                       # root first, then the chain in time ordermessage = by_id[path[0]]message_time = message["end_ns"] - message["start_ns"]covered = sum(row["end_ns"] - row["start_ns"] for row in chain)print("message:", slowest.message.message_id)
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行

這次執行重播訊息 7055,也就是當天最長的訊息,走的是 calendar 路由,並保留了它的 span。這樣走下來得到四個環節:路由呼叫、一次回答呼叫、add_event 工具,以及第二次回答呼叫。輸出列出每個環節的時間,四者相加等於該訊息的 24,305.8 ms。路徑上的時間占訊息時間的比例為 100.0%,而這次執行斷言這條鏈涵蓋整則訊息。

重播之所以能顯示這個比例,是因為其中的呼叫一個接著一個執行,中間沒有任何空隙。記錄器的間隔本身沒有 span,所以由 span 建構的路徑會把它們略去,而這則訊息的重播沒有當天出現的那些間隔。路徑涵蓋的是模型呼叫、行程內(in-process)工具的建模時間,以及 contacts 呼叫的記錄時間,除此之外沒有別的。retrieve 步驟也不占任何時間,因為它的 span 在同一個時間點開始並結束。

重疊是重播無法呈現的情況。沒有任何一則已記錄的訊息同時有兩個呼叫在執行,所以這次執行以手工建構一棵小樹。Span a 是根,在 10 結束。Span b 從 0 執行到 6,span c 從 2 執行到 9。從結束點往回走時會先到達 c,而且不會再回到 b,所以路徑是 a, c。Span b 不在路徑上,縮短 b 並不會移動結束時間。這只在這棵樹上成立。路徑涵蓋根 span 時間的 70.0%,因此路徑上的 span 只解釋了那麼多的時間。這正是實用原則所警告的低占比。

實用原則: 調整追蹤之前,先走一遍關鍵路徑,而且只改動路徑上的 span。先看路徑占訊息時間的比例。比例偏低,代表你手上的 span 無法解釋這些時間,其餘的時間不屬於任何 span。重播的路徑一定涵蓋整則訊息,所以重播無法告訴你兩個重疊的呼叫中哪一個才重要。

首個資料塊時間

回答呼叫佔了路徑的大部分,因此接下來的問題是,時間在一次呼叫內部花在哪裡。首個資料塊時間(time to first chunk)是指從送出模型呼叫,到收到其回覆的第一個串流片段所經過的時間。標籤 0.1.0 的慣例以指標 gen_ai.client.inference.time_to_first_chunk 衡量這段等待,該指標是以秒為單位的直方圖,僅適用於串流呼叫,而且只在有資料塊抵達時才會記錄。span 屬性 gen_ai.response.time_to_first_chunk 則從邏輯操作開始時起算,也就是在驗證與第一次嘗試之前,因此託管用戶端的重試也會計入其中。第 3 章的名稱對照表將套件為該指標取的名稱對應到標準中的名稱。

本節的數字來自記錄器,而不是來自該指標,因為這些範例並未執行該指標。記錄器為每個串流回覆的第一個串流事件計時,而此執行環境會將這個事件與第一段內容一起送出。本地模型沒有驗證步驟需要額外計入。

本節的每個中位數都附有 95% 區間,其定義見含區間的尾端百分位數。

time-to-first-chunk-by-route.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Take each message's last answer call on baseline day 1, the one that writes the reply the user reads, and compare its timeto first chunk with its total time, by route. Fallback replies make no answer call, so they have no first chunk, and eachinterval resamples messages, not calls (PL-6)."""from lib.dayrun import DATA, run_dayfrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bootstrap_interval, nearest_rankimport jsonfrom collections import defaultdictruns = run_day("2026-12-08")routes = {run.message.message_id: run.outcome.route for run in runs}rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]# A first chunk comes before the call ends, and the recorder keeps both times for every call.assert all(row["ttfc_ns"] <= row["total_ns"] for row in rows)last_answer = {}for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made    if row["step"] == "answer":        last_answer[row["message_id"]] = row               # the later call overwrites the earlier oneby_route = defaultdict(list)for message_id, row in last_answer.items():    by_route[routes[message_id]].append(row)assert not any(routes[message_id] == "fallback" for message_id in last_answer)print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")for route in sorted(by_route):    calls = by_route[route]    ttfc = [call["ttfc_ns"] for call in calls]    total = [call["total_ns"] for call in calls]    low, high = bootstrap_interval(calls, lambda units: nearest_rank([u["ttfc_ns"] for u in units], 50))    print(f"{route}, messages with an answer call: {fmt_int(len(calls))}")    print(f"{route}, time to first chunk, median: {fmt_ms(nearest_rank(ttfc, 50))}")    print(f"{route}, time to first chunk, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{route}, total time of the answer call, median: {fmt_ms(nearest_rank(total, 50))}")    print(f"{route}, time to first chunk, share of the call's time: {fmt_share(sum(ttfc), sum(total))}")route_calls = [row for row in rows if row["step"] == "route"]print("route calls, time to first chunk, median, all messages:", fmt_ms(nearest_rank([c["ttfc_ns"] for c in route_calls], 50)))print("route calls, n:", fmt_int(len(route_calls)))print("messages with no answer call:", fmt_int(len(runs) - len(last_answer)))
輸出python time-to-first-chunk-by-route.py
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
alarms, messages with an answer call: 16
alarms, time to first chunk, median: 5,985.6 ms
alarms, time to first chunk, 95% interval: 1,514.8 ms to 6,456.4 ms
alarms, total time of the answer call, median: 9,744.4 ms
alarms, time to first chunk, share of the call's time: 49.6%
calendar, messages with an answer call: 27
calendar, time to first chunk, median: 6,818.8 ms
calendar, time to first chunk, 95% interval: 1,120.5 ms to 7,322.9 ms
calendar, total time of the answer call, median: 10,676.0 ms
calendar, time to first chunk, share of the call's time: 48.8%
devices, messages with an answer call: 17
devices, time to first chunk, median: 6,090.0 ms
devices, time to first chunk, 95% interval: 4,377.7 ms to 6,616.4 ms
devices, total time of the answer call, median: 11,326.7 ms
devices, time to first chunk, share of the call's time: 47.7%
lists, messages with an answer call: 13
lists, time to first chunk, median: 8,563.7 ms
lists, time to first chunk, 95% interval: 8,397.1 ms to 8,866.0 ms
lists, total time of the answer call, median: 12,256.8 ms
lists, time to first chunk, share of the call's time: 69.5%
media, messages with an answer call: 31
media, time to first chunk, median: 5,911.4 ms
media, time to first chunk, 95% interval: 5,663.0 ms to 6,128.4 ms
media, total time of the answer call, median: 11,073.2 ms
media, time to first chunk, share of the call's time: 49.8%
messages, messages with an answer call: 7
messages, time to first chunk, median: 9,289.0 ms
messages, time to first chunk, 95% interval: 485.7 ms to 12,842.8 ms
messages, total time of the answer call, median: 13,865.7 ms
messages, time to first chunk, share of the call's time: 59.4%
route calls, time to first chunk, median, all messages: 530.2 ms
route calls, n: 200
messages with no answer call: 89
習題 7.2

每則訊息保留最新的回答呼叫

+10 則證明

第 20 行對每則訊息只保留一個回答呼叫,但本節說明輸出使用的是某則訊息的回答呼叫中特定的一個。請修改第 20 行,讓每則訊息保留本節所指定的那個呼叫。

last_answer = {}for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made    if row["step"] == "answer":by_route = defaultdict(list)for message_id, row in last_answer.items():    by_route[routes[message_id]].append(row)
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行

輸出取每則訊息的最後一次回答呼叫,也就是寫出使用者所讀回覆的那一次,並依路由把它的首個資料塊時間與總時間並列。被導向備援回覆的訊息不會進行回答呼叫,這一點見第 1 章的說明,因此輸出將它們另外計數:共 89 則。負責挑選路由的 200 路由呼叫,其首個資料塊的中位數為 530.2 ms。

回答呼叫需要更長的時間才產生首個資料塊。撇開 messages 路由不談(其訊息數為 7),lists 的首個資料塊中位數最大,為 8,563.7 ms,來自 13 則訊息。其 95% 區間 8,397.1 ms to 8,866.0 ms 高於除 messages 之外的所有其他路由。

在 lists 上,首個資料塊佔該呼叫時間的 69.5%。在其他路由上,這個占比介於 47.7% 到 59.4% 之間。

messages 路由最需要留意。其首個資料塊中位數為 9,289.0 ms,來自 7 則訊息,而其 95% 區間 485.7 ms to 12,842.8 ms 是輸出中最寬的。

實用原則: 將首個資料塊時間與同一次呼叫的總時間並列印出,並將兩者一起判讀。首個資料塊出現得早,代表使用者較早看到輸出,並不代表這次呼叫的成本低。比較各路由時,應依據區間與占比,不要用少數幾則訊息就斷定某個路由的首個資料塊時間。

預填與生成

第一個區塊要等提示詞處理完才會出現,因此接下來的問題是:這段等待時間有多少花在讀取提示詞,又有多少花在其他地方。預填(prefill)是模型讀取提示詞;生成(generation)是模型逐個 token 寫出回覆。針對 GPU 的服務系統論文也做了同樣的劃分:預填會讓運算資源保持忙碌,而每一個解碼步驟則讓大部分運算資源閒置(Agrawal et al., Sarathi-Serve,OSDI 2024;每次迭代產生一個輸出 token 的做法,見 Yu et al., Orca,OSDI 2022)。

本節使用的計數不需要新的定義。第 6 章說明了輸入與輸出 token 的來源,其中的快取輸入一節則說明快取比例如何推導。已評估的 token,是輸入扣除已快取的前綴後所剩下的部分,也就是模型實際讀取的輸入。

這些計數器來自 llama-cpp-python,它提供了 llama.cpp 為每個情境(context)維護的計數器:已評估的提示詞 token 數及其耗時,以及已生成的 token 數及其耗時。計數器只會累加,因此記錄器在每次呼叫前後取其差值。每個程序在記錄第一則訊息之前,會先進行四次暖機呼叫,這些呼叫不計入劃分。

prefill-generation-split.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Split the recorded compute of each model call on baseline day 1 into prefill (the prompt the model read) and generation(the tokens it wrote), from llama.cpp's counters on the recording machine. The split is the method's output: the numbersbelong to that machine, and the method carries to other hardware. The recorder's warm-up call, made before eachprocess's first recorded message, is not recorded, so it is not in the split. Rates are computed from the recorded counts."""from lib.dayrun import DATAfrom lib.report import fmt_int, fmt_shareimport jsonrows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]for step in ("route", "answer"):    calls = [row for row in rows if row["step"] == step]    prefill = sum(call["prefill_ns"] for call in calls)    generation = sum(call["gen_ns"] for call in calls)    first_chunk = sum(call["ttfc_ns"] for call in calls)    evaluated = sum(call["tokens_evaluated"] for call in calls)   # the prompt's tokens the model read, minus cached ones    written = sum(call["completion_tokens"] for call in calls)    assert all(call["prefill_ns"] <= call["ttfc_ns"] for call in calls)   # the first chunk waits for the prompt    print(f"{step} calls: {fmt_int(len(calls))}")    print(f"{step}, prefill share of prefill plus generation: {fmt_share(prefill, prefill + generation)}")    print(f"{step}, prefill share of time to first chunk: {fmt_share(prefill, first_chunk)}")    print(f"{step}, prompt tokens evaluated per second of prefill, computed: {evaluated * 1e9 / prefill:.1f}")    print(f"{step}, tokens written per second of generation, computed: {written * 1e9 / generation:.1f}")
輸出python prefill-generation-split.py
route calls: 200
route, prefill share of prefill plus generation: 32.8%
route, prefill share of time to first chunk: 72.7%
route, prompt tokens evaluated per second of prefill, computed: 47.6
route, tokens written per second of generation, computed: 7.3
answer calls: 121
answer, prefill share of prefill plus generation: 54.1%
answer, prefill share of time to first chunk: 91.2%
answer, prompt tokens evaluated per second of prefill, computed: 62.3
answer, tokens written per second of generation, computed: 7.0

輸出把每個步驟的運算拆成這兩種工作,並先列出路由呼叫。路由呼叫讀取固定的指示與訊息,回答呼叫則讀取訊息以及路由所取回的內容。路由呼叫的第一個區塊要等它的提示詞:預填占該等待時間的 72.7%,但只占該呼叫運算量的 32.8%。回答呼叫等待提示詞的比重更大。預填占它們等待第一個區塊時間的 91.2%,所以回覆的第一個字,主要是在讀取提示詞。

回答呼叫的生成速度為每秒 7.0 個 token,預填則是每秒評估 62.3 個 token。這些速率由計數計算而得,只適用於這台機器,原因見小型開放模型:小型模型的速度是在一台指定機器上以錄製方式量測,絕不當作通則引用。預填是以已評估的 token 計算,而非以輸入 token 計算,下一節會說明這項選擇為何重要。

實用原則: 在更動模型呼叫的提示詞或回覆長度之前,先把該呼叫的時間分成預填與生成。劃分要取自計數器,並使用同一台機器與同樣的呼叫,再與總時間對照著看。當預填占第一個區塊時間的大部分時,等待的原因在提示詞。當生成占呼叫的大部分時,原因則在回覆的長度。

檢索內容與預填

檢索會把文章放進回答呼叫的提示中,因此檢索較多內容的版本,預填理應變長。針對該版本要問的是:長了多少,以及模型是否讀完了所有新增的輸入。在會檢索的路由上,基準版本最多給回答呼叫三篇文章,top-8 版本則最多給八篇。路由呼叫發生在檢索之前,因此兩個版本中,它們的提示都不含文章。

這項比較在兩個版本下使用相同的訊息,即配對的 60 則:基準第 1 天的訊息中,top-8 版本也有錄製到的那些。輸出中的 r0 是基準,r3 是 top-8 版本。輸出把每個版本在這些訊息上的回答呼叫加總,這只是加總,不是附有區間的比較。第 10 章同樣會配對相同的訊息,並給出差異的區間。

context-against-prefill.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Compare the same 60 messages under r0 (the baseline, on baseline day 1) and r3 (the top-8 release): the answer calls'prefill, tokens and cache, and the route calls' cache. More articles make the prompt longer, and prefill follows the tokens themodel had to evaluate, since a cached prefix is not read again while the cache holds it. The correlations are over all ofbaseline day 1's answer calls, computed; the paired interval belongs to chapter 10, so none is printed here."""from lib.case import load_messagesfrom lib.dayrun import DATAfrom lib.report import fmt_int, fmt_msimport jsonfrom collections import Counterfrom statistics import correlationdef load(folder):    return [json.loads(line) for line in (DATA / folder / "traces.jsonl").read_text(encoding="utf-8").splitlines()]def total(rows, step, field):    return sum(row[field] for row in rows if row["step"] == step)paired = {message.message_id for message in load_messages("2026-12-08-paired")}   # the 60 messages, same arrivalsbase = load("baseline-day-1")releases = {"r0": [row for row in base if row["message_id"] in paired], "r3": load("release-top-8")}assert {row["message_id"] for row in releases["r3"]} == paired     # r3 was recorded for exactly these messagesfor name, rows in releases.items():    print(f"{name}, prefill summed over the answer calls:", fmt_ms(total(rows, "answer", "prefill_ns")))    print(f"{name}, prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "prompt_tokens")))    print(f"{name}, prompt tokens evaluated summed over the answer calls:", fmt_int(total(rows, "answer", "tokens_evaluated")))    print(f"{name}, cached prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "cached_tokens_derived")))    print(f"{name}, prompt tokens evaluated summed over the route calls:", fmt_int(total(rows, "route", "tokens_evaluated")))print("prefill, r3 over r0, computed:", f"{total(releases['r3'], 'answer', 'prefill_ns') / total(releases['r0'], 'answer', 'prefill_ns'):.2f}")# The same answer calls under both releases: sorted by message, then by call, so each pair is one message's n-th answer.before = sorted((row for row in releases["r0"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))after = sorted((row for row in releases["r3"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))assert all(b["message_id"] == a["message_id"] and b["prompt_tokens"] <= a["prompt_tokens"] for b, a in zip(before, after))gained = sum(a["prompt_tokens"] > b["prompt_tokens"] for b, a in zip(before, after))   # the assert: none loses anyprint("paired answer calls, r3 with more prompt tokens than r0:", f"{gained} of {len(before)}")route = {name: {row["message_id"]: row for row in rows if row["step"] == "route"} for name, rows in releases.items()}assert all(route["r0"][m]["input_key"] == route["r3"][m]["input_key"]           and route["r0"][m]["prompt_tokens"] == route["r3"][m]["prompt_tokens"] for m in paired)   # identical route promptscached = {name: [row["cached_tokens_derived"] for row in rows if row["step"] == "route"] for name, rows in releases.items()}instruction = Counter(cached["r0"]).most_common(1)[0][0]        # the cached count most route calls get: the instructionprint("route instruction, cached tokens in most route calls:", fmt_int(instruction))for name in releases:    print(f"{name}, route calls that re-read most of the instruction:", sum(c < instruction for c in cached[name]))answer_calls = [row for row in base if row["step"] == "answer"]by_prompt = correlation([row["prompt_tokens"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])by_evaluated = correlation([row["tokens_evaluated"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])print("prefill against prompt tokens, correlation, computed:", f"{by_prompt:.2f}")print("prefill against tokens evaluated, correlation, computed:", f"{by_evaluated:.2f}")assert by_evaluated > 0.9 and by_evaluated > by_prompt   # the cached prefix adds to the prompt, not to the prefill
輸出python context-against-prefill.py
r0, prefill summed over the answer calls: 172,043.5 ms
r0, prompt tokens summed over the answer calls: 20,420
r0, prompt tokens evaluated summed over the answer calls: 10,855
r0, cached prompt tokens summed over the answer calls: 9,565
r0, prompt tokens evaluated summed over the route calls: 827
r3, prefill summed over the answer calls: 289,244.2 ms
r3, prompt tokens summed over the answer calls: 27,326
r3, prompt tokens evaluated summed over the answer calls: 17,813
r3, cached prompt tokens summed over the answer calls: 9,513
r3, prompt tokens evaluated summed over the route calls: 1,209
prefill, r3 over r0, computed: 1.68
paired answer calls, r3 with more prompt tokens than r0: 15 of 33
route instruction, cached tokens in most route calls: 133
r0, route calls that re-read most of the instruction: 1
r3, route calls that re-read most of the instruction: 4
prefill against prompt tokens, correlation, computed: 0.29
prefill against tokens evaluated, correlation, computed: 0.99

在配對的訊息上,回答呼叫在 top-8 版本下的預填為 289,244.2 ms,基準則為 172,043.5 ms:是基準的 1.68 倍。輸出另外給出基準第 1 天所有回答呼叫的兩項相關係數。

輸入隨文章增加而增長。輸入詞元從 20,420 上升到 27,326,而已評估詞元,也就是模型實際讀取的輸入,從 10,855 上升到 17,813。

兩個版本略過的快取前綴大致相同,基準為 9,565 個詞元,top-8 版本為 9,513 個,因此模型確實讀取了新增的輸入。在 top-8 版本下,有 15 of 33 個配對的回答呼叫增加了提示詞元,沒有任何一個減少。

路由呼叫的提示中沒有任何文章,卻仍出現差距。在 top-8 版本下,它們評估了 1,209 個詞元,基準則為 827 個,而範例斷言這些提示在兩個版本下完全相同。

原因在於錄製器的快取。該快取上限為 1 GiB,並先丟棄最舊的狀態,因此在足夠多的其他呼叫之後才執行的路由呼叫,會發現它的指令已被丟棄而必須重新讀取。錄製並未記錄快取命中,所以這個結論是從快取的規則推得,而不是來自日誌。多數路由呼叫的快取中保有該指令,共 133 個詞元。在 top-8 版本下,有 4 個路由呼叫重新讀取了其中大部分,基準則為 1 個。

預填跟隨的是已評估詞元,而非輸入。在基準第 1 天的所有回答呼叫中,預填與已評估詞元的相關係數為 0.99,與輸入的相關係數為 0.29。模型讀過的前綴,只要快取仍保有它,就不會再讀一次,所以輸入可以增加而工作量不變,而一次呼叫所評估的詞元數,取決於在它之前的那些呼叫。

實用原則: 要在與所改版本相同的訊息上,衡量提示額外增加的預填,並同時查看已評估詞元與輸入詞元。輸入詞元說明提示有多大,已評估詞元說明模型做了多少工作,而當前綴被快取時,這兩個數字就會分歧。應以工作量為依據採取行動。

此部分尚未翻譯,因此以英文呈現。

Tail percentiles with intervals

The medians so far leave out the messages that wait longest, and those are the ones a tail percentile is for. This book uses the nearest rank. The p-th percentile is the value at sorted position ceil(p/100 × n); the tail is the slowest few percent of messages. Sort the n values, count to position ceil(p/100 × n), and take the value there. It always returns a message that occurred.

Chapter 1 said that twenty messages cannot support a tail percentile. Two hundred can, with an interval beside it, and every percentile in this chapter states its count, n. A percentile of seven messages is a different kind of number from one of 200, and the output shows which.

The rule has a consequence at the top of the list. On 200 values the 99th percentile is the value at position 198, which is the third largest, not the second. The output prints the rule on the values 1 to 200 so that the position is visible.

Predict before you run it. How many messages does a route need before its 95th percentile is anything but its slowest message? Work it from ceil(0.95 × n), then check the output.

percentiles-by-route.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Print each route's median, p95 and p99 of message time on baseline day 1, every one with its message count n, and a 95%interval on each p95. Percentiles are nearest rank: the value at position ceil(p/100 x n). The interval is a bootstrap overmessages, 2,000 resamples, seed 20261207. A route with fewer than 20 messages has its p95 at its largest message, which theexample prints and asserts."""from lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_msfrom lib.stats import bootstrap_interval, nearest_rankfrom collections import defaultdictruns = run_day("2026-12-08")by_route = defaultdict(list)for run in runs:    by_route[run.outcome.route].append(run.replied_ns - run.arrived_ns)   # the message's time on the virtual clocktimes = [run.replied_ns - run.arrived_ns for run in runs]groups = {"all routes": times, **by_route}intervals = {}print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")print("p99 of the values 1 to 200 (n = 200), nearest rank:", nearest_rank(list(range(1, 201)), 99))assert nearest_rank(list(range(1, 201)), 99) == 198   # the 198th value, the third largest of 200print("fewest values before the p95 is not the largest, nearest rank:",      next(n for n in range(1, 201) if nearest_rank(list(range(1, n + 1)), 95) != n))for name in ["all routes"] + sorted(by_route):    values = groups[name]    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))    intervals[name] = (low, high)    print(f"{name}, messages (n): {fmt_int(len(values))}")    print(f"{name}, median: {fmt_ms(nearest_rank(values, 50))}")    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")small = [name for name in sorted(by_route) if len(by_route[name]) < 20]print("routes under 20 messages, count:", len(small))print("routes under 20 messages, p95 is their largest message:", ", ".join(small))for name in small:    assert nearest_rank(by_route[name], 95) == max(by_route[name])   # ceil(0.95 n) = n for every n up to 19assert len(times) == len(runs) == 200# Two routes' p95 intervals overlap, so the largest p95 cannot be told apart from the next one with this many messages.low_m, high_m = intervals["messages"]low_c, high_c = intervals["calendar"]assert low_m <= high_c and low_c <= high_m
輸出python percentiles-by-route.py
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
p99 of the values 1 to 200 (n = 200), nearest rank: 198
fewest values before the p95 is not the largest, nearest rank: 20
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms
all routes, p95, 95% interval: 16,452.7 ms to 20,909.8 ms
all routes, p99: 22,425.7 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms
alarms, p95, 95% interval: 15,757.0 ms to 22,425.7 ms
alarms, p99: 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms
calendar, p95, 95% interval: 14,623.8 ms to 24,305.8 ms
calendar, p99: 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms
devices, p95, 95% interval: 14,532.9 ms to 17,417.9 ms
devices, p99: 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms
fallback, p95, 95% interval: 1,636.7 ms to 3,108.1 ms
fallback, p99: 3,191.4 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms
lists, p95, 95% interval: 14,842.4 ms to 17,183.7 ms
lists, p99: 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms
media, p95, 95% interval: 14,786.5 ms to 18,351.2 ms
media, p99: 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms
messages, p95, 95% interval: 21,244.6 ms to 24,253.7 ms
messages, p99: 24,253.7 ms
routes under 20 messages, count: 4
routes under 20 messages, p95 is their largest message: alarms, devices, lists, messages
習題 7.3

找出 p95 等於其最大訊息的路由

+10 則證明

範例中的第 33 行是空白的。請填寫該行,使 small 存放訊息數少於第 23 行所求出之計數的路由,並依排序後的順序排列,也就是第 24 行所使用的相同順序。

    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")print("routes under 20 messages, count:", len(small))print("routes under 20 messages, p95 is their largest message:", ", ".join(small))for name in small:
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行
習題 7.4

Explain why a small route's interval tops out at its p95

+10 則證明

此部分尚未翻譯,因此以英文呈現。

The alarms route's 95% interval ends at the same value as its 95th percentile. Which explains that?

Explain why a small route's interval tops out at its p95:選出正確的說明
在 Python 3.13.16 上執行

The output gives each route's median, 95th and 99th percentile, each with its count, and a 95% interval on each 95th percentile. A route needs at least 20 messages before its 95th percentile is anything but its largest. 4 routes have fewer than 20 messages, alarms, devices, lists, messages, and for each one the 95th percentile is its slowest message.

The messages route's 95th percentile is 24,253.7 ms from 7 messages, with a 95% interval of 21,244.6 ms to 24,253.7 ms whose top is the same value. Its last answer calls are the longest of the answering routes at the median, at 13,865.7 ms. The output does not say why its tail is long.

The all-routes median, 8,099.3 ms, is lower than the median of every route that answered. The reason is the fallback route. 89 of the 200 messages took the fallback reply, which makes one route call and no answer call, and their median is 1,392.0 ms. The all-routes median is the middle value of all the messages, so those messages pull it down.

figure-latency-tail-by-route.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Draw each route's median and p95 of message time on baseline day 1, with a 95% interval on the p95, so the tail's placein each route shows at a glance. Every value the figure draws is printed first, with its message count n. The intervalis a bootstrap over messages (2,000 resamples, seed 20261207); the route is the one the assistant chose."""from lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_int, fmt_msfrom lib.stats import bootstrap_interval, nearest_rankfrom collections import defaultdictruns = run_day("2026-12-08")times = {"all routes": [run.replied_ns - run.arrived_ns for run in runs]}for run in runs:    times.setdefault(run.outcome.route, []).append(run.replied_ns - run.arrived_ns)names = ["all routes"] + sorted(name for name in times if name != "all routes")summary = []for name in names:    values = times[name]    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))    summary.append((name, len(values), nearest_rank(values, 50), nearest_rank(values, 95), low, high))    print(f"{name}, messages (n): {fmt_int(len(values))}")    print(f"{name}, median: {fmt_ms(summary[-1][2])}")    print(f"{name}, p95: {fmt_ms(summary[-1][3])}, interval: {fmt_ms(low)} to {fmt_ms(high)}")fig, ax = new_figure(height=3.8)rows = list(range(len(summary)))[::-1]                 # the first row, all routes, at the topfor row, (name, count, median, p95, low, high) in zip(rows, summary):    ax.hlines(row, low / 1e6, high / 1e6, color=MUTED, linewidth=3, label="95% interval of the p95" if row == rows[0] else None)    ax.scatter([median / 1e6], [row], facecolors="none", edgecolors=INK, linewidths=1.4, s=52, zorder=3,               label="median" if row == rows[0] else None)     # a hollow circle, so the two dots differ in shape as well as colour    ax.scatter([p95 / 1e6], [row], color=ACCENT, marker="D", s=44, zorder=3, label="p95" if row == rows[0] else None)ax.set_yticks(rows, [f"{name} (n = {count})" for name, count, *_ in summary])ax.set_xlabel("message time, milliseconds")ax.set_xlim(0, 30000)ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.22), ncol=3)   # below the axis, clear of every rowsave(fig, "latency-tail-by-route")
輸出python figure-latency-tail-by-route.py
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms, interval: 16,452.7 ms to 20,909.8 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms, interval: 15,757.0 ms to 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms, interval: 14,623.8 ms to 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms, interval: 14,532.9 ms to 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms, interval: 1,636.7 ms to 3,108.1 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms, interval: 14,842.4 ms to 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms, interval: 14,786.5 ms to 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms, interval: 21,244.6 ms to 24,253.7 ms
figure: figures/latency-tail-by-route.svg
050001000015000200002500030000message time, millisecondsall routes (n = 200)alarms (n = 16)calendar (n = 27)devices (n = 17)fallback (n = 89)lists (n = 13)media (n = 31)messages (n = 7)95% interval of the p95medianp95
圖 7.1 Each route's median and 95th percentile of message time on baseline day 1, with a 95% interval on the 95th percentile

圖 7.1 draws each route's median and 95th percentile, with the interval on the 95th percentile as a bar. The top row is all routes together. Read the answering routes' bars against one another. Most of their intervals overlap, and the messages interval overlaps calendar's, as the example asserts. The 4 routes under 20 messages have bars that end at their own largest message. The fallback bar is far shorter than the rest. So the tail depends on whether the route answers, and the count decides how sure the reader can be of where a route's tail sits.

The interval is a percentile bootstrap, and this is the one place the chapter builds it. An interval says how far a number would move had the day brought other messages drawn the same way; here, the middle 95% of 2,000 bootstrap resamples of messages. The question behind it is whether another day's 95th percentile would be the same. The interval answers that only for a day drawn the same way. A different day, a release or a load lies outside what it covers.

For each route, the code draws as many messages as the route has, with replacement, takes the 95th percentile of that resample, and repeats the draw 2,000 times with the seed 20261207. The interval is the 50th and the 1,950th of the 2,000 results, which bracket 95% of them. Efron introduced the bootstrap in 1979, and Evaluating LLM Applications uses the same method over items. Here the unit is the message, not the span, because the spans of one message are not independent of one another.

The same bootstrap applies to any statistic taken per message, such as the share of the day's cost that the most expensive messages carry in chapter 6. Under 20 messages, though, the 95th percentile of every resample is one of the route's own messages, and the largest of them is the top of the interval. The interval cannot reach past the messages it came from. So for each of the 4 routes under 20 messages, the upper end is its own largest message, the upper end and the point estimate are one value, and the interval's width measures the resampling, not what those few messages leave out.

Working rule: Print each percentile with its count and its interval, and rank two routes only when their intervals do not overlap. Collect more messages before you name a tail.

直方圖的桶與它們隱藏的資訊

直方圖不保存訊息,只保存計數。一個桶計算落在兩個邊界之間的值,因此從桶讀出的百分位數,只能確定到該桶的範圍之內。標籤 0.1.0 的 GenAI conventions 指出,其各項耗時直方圖(包含代理程式的 gen_ai.client.invoke_agent.duration)的桶邊界應當(SHOULD)如下,單位為秒。本書將這組邊界用於訊息時間,也就是本章所測量的耗時:0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92。服務匯出的是其設定所指定的邊界,可能與這組不同。

bucket-edges-hide-tail.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Count baseline day 1's message times into the buckets the GenAI conventions advise for the agent's duration histogram, thenestimate the p95 from the bucket counts and set it beside the nearest-rank p95 of the raw values. The estimate spreads eachbucket's values evenly across it, and the p95 falls in one bucket, so the buckets can only place the estimate inside it."""from lib import genaifrom lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bucket_counts, nearest_rankimport mathEDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]   # the conventions' advised upper bounds, in secondsprint("GenAI conventions version:", genai.REGISTRY_VERSION)print("bucket boundaries, GenAI conventions, seconds:", ", ".join(str(edge) for edge in EDGES_S))runs = run_day("2026-12-08")times = [run.replied_ns - run.arrived_ns for run in runs]n = len(times)edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here iscounts = bucket_counts(times, edges)                           # a value sits in the bucket whose upper edge it does not exceedprint("messages (n):", fmt_int(n))for index, count in enumerate(counts):    low = edges[index - 1] if index else 0                     # a bucket starts at the upper edge of the one before it    if index < len(edges):        print(f"bucket above {fmt_ms(low)} up to {fmt_ms(edges[index])}: {fmt_int(count)} messages, {fmt_share(count, n)}")    else:        print(f"bucket above {fmt_ms(low)}: {fmt_int(count)} messages, {fmt_share(count, n)}")exact = nearest_rank(times, 95)rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95index = next(i for i, edge in enumerate(edges) if exact <= edge)   # the bucket that holds the exact p95low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zerobelow = sum(counts[:index])                                    # messages in the buckets under itestimate = low + round((rank - below) * (edges[index] - low) / counts[index])print("bucket holding the p95, lower edge:", fmt_ms(low))print("bucket holding the p95, upper edge:", fmt_ms(edges[index]))print("messages in that bucket:", fmt_int(counts[index]))print("messages at or below its lower edge:", fmt_int(below))print("p95, nearest rank of the raw values:", fmt_ms(exact))print("p95, estimated from the bucket counts:", fmt_ms(estimate))print("estimate minus the nearest-rank p95:", fmt_ms(estimate - exact))assert low < exact <= edges[index]                             # the exact p95 lies in the bucket that holds itassert abs(estimate - exact) > 500_000_000                     # the bucket estimate is more than half a second off
輸出python bucket-edges-hide-tail.py
GenAI conventions version: 0.1.0
bucket boundaries, GenAI conventions, seconds: 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
bucket holding the p95, lower edge: 10,240.0 ms
bucket holding the p95, upper edge: 20,480.0 ms
messages in that bucket: 89
messages at or below its lower edge: 105
p95, nearest rank of the raw values: 18,351.2 ms
p95, estimated from the bucket counts: 20,019.8 ms
estimate minus the nearest-rank p95: 1,668.6 ms
習題 7.5

選出包含百分位數的桶

+10 則證明

在這份副本中,第 30 行是空白的。請寫出這一行,使 index 成為包含精確第 95 百分位數的桶,並採用第 19 行的註解所陳述的規則。

exact = nearest_rank(times, 95)rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zerobelow = sum(counts[:index])                                    # messages in the buckets under itestimate = low + round((rank - below) * (edges[index] - low) / counts[index])
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行

輸出把基準日 1 的相同訊息計入這些桶,由計數估計第 95 百分位數,並將估計值與原始訊息的最近排名(nearest-rank)值並列。包含第 95 百分位數的桶,範圍從 10,240.0 ms 到 20,480.0 ms。該桶內有 89 則訊息,而位於其下邊界或以下的訊息有 105 則。

桶只能把第 95 百分位數定位在這兩個邊界之間,無法更精確。這個估計假設桶內的訊息均勻分布於整個桶。這就是 Prometheus 由桶估計百分位數的規則,它假設桶內為線性分布。其他後端的內插方式可能不同,所以邊界一變,估計值也跟著改變。此處的估計值為 20,019.8 ms,原始訊息的最近排名值為 18,351.2 ms,因此這一天的估計值偏高 1,668.6 ms。

figure-bucket-hides-tail.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Draw baseline day 1's message times twice, on one millisecond scale: each message as a point in the upper panel, and thebucket counts for the same messages in the lower panel, each bucket drawn across the span it covers. The edges are the onesbucket-edges-hide-tail uses. Every value the figure shows is printed first, and the nearest-rank p95 is drawn as a line."""from lib import genaifrom lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bucket_counts, nearest_rankEDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]  # the conventions' advised upper bounds, in seconds, as thereruns = run_day("2026-12-08")times = sorted(run.replied_ns - run.arrived_ns for run in runs)n = len(times)edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here iscounts = bucket_counts(times, edges)exact = nearest_rank(times, 95)lows = [0] + edges                                             # each bucket starts at the edge before itprint("messages (n):", fmt_int(n))for number, count in enumerate(counts):    if number < len(edges):        print(f"bucket above {fmt_ms(lows[number])} up to {fmt_ms(edges[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")    else:        print(f"bucket above {fmt_ms(lows[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")print("p95, nearest rank of the raw values:", fmt_ms(exact))fig, (top, bottom) = new_figure(rows=2, height=4.6, sharex=True)top.scatter([t / 1e6 for t in times], [(i + 1) / n for i in range(n)], s=10, color=INK, label="each message")for edge in edges:    top.axvline(edge / 1e6, color=MUTED, linestyle=":", linewidth=0.8)top.axvline(exact / 1e6, color=ACCENT, linestyle="--", linewidth=1.2, label="p95, nearest rank")top.set_ylabel("share at or below")top.legend(loc="lower right")highs = edges + [edges[-1] + 10_000_000_000]                   # the last bucket is open; drawn 10 s wide, past the axiscentres = [(lo + hi) / 2 / 1e6 for lo, hi in zip(lows, highs)]widths = [(hi - lo) / 1e6 for lo, hi in zip(lows, highs)]bars = bottom.bar(centres, counts, width=widths, color=MUTED)bottom.bar_label(bars, labels=[fmt_int(c) if c else "" for c in counts], padding=2)   # empty buckets carry no labelbottom.set_xticks([e / 1e6 for e in edges], [f"{e / 1e6:,.0f}" if e >= 10_240_000_000 else "" for e in edges])   # the small edges crowd the leftbottom.set_ylabel("messages")bottom.set_xlim(0, 42000)                                      # set after the ticks, which would widen itbottom.set_ylim(0, max(counts) * 1.15)bottom.set_xlabel("message time, milliseconds; bucket edges as ticks")save(fig, "bucket-hides-tail")
輸出python figure-bucket-hides-tail.py
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
p95, nearest rank of the raw values: 18,351.2 ms
figure: figures/bucket-hides-tail.svg
0.00.20.40.60.81.0share at or beloweach messagep95, nearest rank10,24020,48040,960message time, milliseconds; bucket edges as ticks020406080100messages2165316896
圖 7.2 基準日 1 的訊息以點表示,並以桶計數表示,第 95 百分位數以虛線標示

圖 7.2以同一個毫秒刻度將相同的訊息繪製兩次。上方圖表將每則訊息繪於「小於或等於它的訊息所占比例」處,所以各點向上攀升。點線是桶的邊界,虛線是最近排名的第 95 百分位數。下方圖表顯示各桶的計數,並橫跨該桶所涵蓋的範圍繪製。第 95 百分位數的線落在一個寬桶之內,而下方圖表完全無法說明訊息位於該桶的哪個位置。這正是桶所損失的資訊,也是估計值有偏差的原因。

實用原則: 依據你將要提出的問題來設定桶邊界,並在每個告警門檻附近放置一個邊界。當百分位數落在寬桶之內時,應回報該桶及其計數,而不是精確到毫秒的估計值,並且盡可能保留原始值。由桶得到的估計值,是把一條規則套用在一組邊界上的結果,邊界一變,估計值也會改變。

以紀錄的服務時間進行排隊分析

一則訊息所花的時間,不只是它自身的處理工作。當訊息抵達時,若模型正忙於處理另一則訊息,它就必須等待,而這段等待也是使用者所看到的時間的一部分。排隊模型可以呈現這段等待如何隨負載增加。每個抵達者加入一條隊伍,伺服器一次處理一則訊息,而負載是指抵達者所要求的伺服器時間所占的比例。

本節的數字是計算而得,並非紀錄值。程式碼模擬的是單一伺服器。抵達是隨機發生的,其平均速率固定,由負載決定,這是一個 Poisson 過程:相鄰兩次抵達的間隔彼此獨立,並呈指數分布。每則訊息的服務時間,取自當天所紀錄的訊息時間之一,並採取放回抽樣。Little 定律指出,系統中的平均數量等於其抵達率乘以每個項目在系統中停留的平均時間,即 L = λW。Little 於 1961 年的證明確立了這項定律,而 MIT 關於 M/M/1 佇列的課程講義則以本節所用的形式陳述了它。

queue-on-service-times.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Queue baseline day 1's recorded message times behind one first-come, first-served server at three loads, with seeded Poissonarrivals and each message's service drawn from the recorded times. The number in system is walked from the queue's events andchecked against the arrival rate times the time in system, and the last check compares exponential service with the M/M/1 formula."""from lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_msfrom lib.stats import nearest_rankfrom fractions import Fractionimport numpy as npSEED, N, CHECK_N = 20261208, 50_000, 200_000                   # one seed; messages per run; the M/M/1 check's runrecorded = [run.replied_ns - run.arrived_ns for run in run_day("2026-12-08")]   # the day's 200 recorded message timesmean_service = sum(recorded) / len(recorded)recorded_services = lambda rng, n: rng.choice(np.asarray(recorded, dtype=np.int64), n)   # resampled with replacementexponential_services = lambda rng, n: rng.exponential(mean_service, n).round().astype(np.int64)def simulate(rng, rho, n, services):    """Serve n messages arriving at rate rho / mean_service. Returns arrivals, waits, times in system, the last finish    and the total service time, in ns."""    arrivals = np.cumsum(rng.exponential(mean_service / rho, n)).round().astype(np.int64).tolist()    finish, waits, sojourn, busy = 0, [], [], 0    for arrive, serve in zip(arrivals, services(rng, n).tolist()):        start = max(arrive, finish)          # the server finishes the message before it, then starts this one        finish = start + serve        waits.append(start - arrive)        sojourn.append(finish - arrive)        busy += serve    return arrivals, waits, sojourn, finish, busyprint("mean recorded message time:", fmt_ms(round(mean_service)))for rho in (0.5, 0.8, 0.9):    arrivals, waits, sojourn, finish, busy = simulate(np.random.Generator(np.random.PCG64(SEED)), rho, N, recorded_services)    span = finish - arrivals[0]                                # first arrival to last departure    # Each arrival adds one to the count in system and each departure takes one away; the area under the count is L times the span.    area, count, when = 0, 0, arrivals[0]    for moment, step in sorted([(a, 1) for a in arrivals] + [(a + s, -1) for a, s in zip(arrivals, sojourn)]):        area, count, when = area + count * (moment - when), count + step, moment    number, rate_times_time = Fraction(area, span), Fraction(N, span) * Fraction(sum(sojourn), N)   # L, and lambda W    print(f"load {rho}, utilisation, computed: {busy / span:.2f}")    print(f"load {rho}, wait before service, computed, p95 (n = {fmt_int(N)}):", fmt_ms(nearest_rank(waits, 95)))    print(f"load {rho}, number in system, time average, computed: {float(number):.2f}")    print(f"load {rho}, arrival rate times time in system, computed: {float(rate_times_time):.2f}")    assert number == rate_times_time     # exact, with no tolerance: the window starts at the first arrival and ends at the last departure# M/M/1: the mean time in system is 1 / (mu - lambda), which is mean_service / (1 - rho) for exponential service.sojourn = simulate(np.random.Generator(np.random.PCG64(SEED)), 0.8, CHECK_N, exponential_services)[2]simulated, formula = sum(sojourn) / CHECK_N, mean_service / (1 - 0.8)print(f"exponential service, load 0.8, mean time in system, simulated (n = {fmt_int(CHECK_N)}):", fmt_ms(round(simulated)))print("exponential service, load 0.8, mean time in system, formula:", fmt_ms(round(formula)))assert abs(simulated - formula) / formula < 0.02
輸出python queue-on-service-times.py
mean recorded message time: 8,019.0 ms
load 0.5, utilisation, computed: 0.50
load 0.5, wait before service, computed, p95 (n = 50,000): 27,983.0 ms
load 0.5, number in system, time average, computed: 0.91
load 0.5, arrival rate times time in system, computed: 0.91
load 0.8, utilisation, computed: 0.80
load 0.8, wait before service, computed, p95 (n = 50,000): 82,817.5 ms
load 0.8, number in system, time average, computed: 3.31
load 0.8, arrival rate times time in system, computed: 3.31
load 0.9, utilisation, computed: 0.90
load 0.9, wait before service, computed, p95 (n = 50,000): 179,463.5 ms
load 0.9, number in system, time average, computed: 7.26
load 0.9, arrival rate times time in system, computed: 7.26
exponential service, load 0.8, mean time in system, simulated (n = 200,000): 40,422.0 ms
exponential service, load 0.8, mean time in system, formula: 40,094.8 ms

輸出涵蓋 0.5、0.8 與 0.9 三種負載,每種都使用相同的種子,接著在有公式可用之處再做一項檢查。訊息時間紀錄的平均值為 8,019.0 ms,這是每則訊息平均所需的服務時間;在負載為 0.5 時,伺服器的使用率為 0.50。

開始服務前等待時間的第 95 百分位數,在負載 0.5 時為 27,983.0 ms,在 0.8 時為 82,817.5 ms,在 0.9 時為 179,463.5 ms。等待時間的攀升比負載更為陡峭。

系統中的數量也遵循同一條曲線。在負載 0.8 時,其平均為 3.31,而抵達率乘以系統中的時間得到 3.31。程式碼由佇列隨時間變化的事件求得前者,由抵達率與系統中的平均時間求得後者,並以斷言確認兩者在每種負載下都相等。在視窗從第一次抵達延續到最後一次離開的樣本路徑上,Little 定律精確成立,因此該斷言不容許任何誤差。

M/M/1 公式給出單一伺服器在指數服務下於系統中的平均時間,它只對指數分布的服務時間才是精確的,而紀錄的時間並非指數分布。因此程式碼先依模擬自身的條件加以檢驗。在負載 0.8、指數服務、共 200,000 則訊息的情況下,模擬得到的系統中平均時間為 40,422.0 ms,公式給出 40,094.8 ms。程式碼斷言兩者的差距在 2% 以內。M/G/1 是服務分布任意的單一伺服器,它有自己的平均值公式,本章不做該項檢查。

這是單一伺服器的模型,並非 Ambrewick 部署環境的模型。每則訊息的完整紀錄時間視為一次服務,這正是佇列處理訊息的方式,而它的抵達則忽略當天實際的抵達時間。因此,這些等待時間是一台伺服器處理這種訊息組合時會產生的結果,並不是當天實際發生的情形。

實用原則: 在接受某個尾端數值或增加容量之前,請同時在預期的負載與更高的負載下檢視佇列。手邊有紀錄的服務時間時就使用它,標示每個由模擬計算而得的數字,並且只在公式的假設成立之處,才以公式檢驗模擬。

正式環境中會出什麼問題

這些數字離開重播(replay)環境後,有三件事會改變。第一,正式環境的 span 會留下空隙。記錄器記下的呼叫間空隙,在一整天內合計為 651.4 ms。這些空隙是訊息中真實存在的時間,卻不屬於任何 span,因此由 span 建立的關鍵路徑,涵蓋的時間可能少於訊息的完整時間。請將路徑所占的比例與訊息時間並列閱讀,並把偏低的比例當作要向追蹤紀錄(trace)追問的問題,而不是當作答案。

第二,服務匯出的直方圖(histogram),其邊界由自身的設定決定,未必是慣例所建議的邊界。從桶(bucket)讀出的百分位數會帶有其邊界造成的誤差,這一天的訊息所呈現的桶估計值即是如此。第 9 章會依據這些延遲來訂定目標,因此在那項決定中也必須考量這些邊界。

第三,每天訊息很少的路由,其第 95 百分位數會有很寬的區間,而只顯示單一點的儀表板看起來卻像是精確的。請把數量與區間放在同一個面板上,否則就不要在面板上顯示該百分位數。

實用原則: 在你發布正式環境的延遲數字之前,請在旁邊印出它的數量與區間,並說明它屬於哪一種時間:span 的時間、桶的估計值,或重播的總和。當路徑所占的比例或桶的邊界不明時,請隨數字一併說明,而不要讓數字單獨存在。

本章所做的決定

以下每一項都是我們可能判斷錯誤之處。每一項都附上理由,以及用來檢驗它的範例。

  • 我們從 span 讀出關鍵路徑,並在一棵人為建構的樹上展示重疊的情況,因為沒有任何一則已記錄的訊息含有重疊的呼叫。critical-path-one-message 檢查該路徑涵蓋整則重播的訊息,並檢查建構出的樹中 span b 不在路徑上。
  • 我們把首個區塊時間與同一次呼叫的總時間並列呈報,並用計數器將它拆分,使首個區塊不會被單獨解讀。time-to-first-chunk-by-route 與 prefill-generation-split 在同樣的呼叫上印出兩者。
  • 我們印出最近秩(nearest-rank)百分位數及其計數,並以訊息為單位、用固定種子的自助重抽樣(bootstrap)為每個第 95 百分位數給出區間。percentiles-by-route 指出訊息數少於 20 的路由,其第 95 百分位數就是其最大的訊息,並檢查內文所依賴的那一處重疊。
  • 我們採用 GenAI 慣例建議的訊息時間邊界值,並明說這一點,因為服務自己的邊界值可能不同。bucket-edges-hide-tail 印出估計值在這一天的誤差,figure-bucket-hides-tail 則把原始數值與計數並排繪出。
  • 我們只在已記錄的服務時間上模擬佇列,並標示每個計算得出的佇列數字。queue-on-service-times 由佇列的事件求出系統內的數量,並在每種負載下,對照到達率乘以系統內時間來檢查;而 M/M/1 公式只在指數分布的服務下檢查。
  • 我們只在各路由尾端的區間不重疊時才為它們排序,因為一天的訊息無法將它們排出順序。在這一天,這使得多數有回應的路由仍無法排序,因此確切的差異在於路由是否有回應,而不在於哪一條有回應的路由尾端最差。

本章,於本版次中

版次 2026.11.2範例於 2026年11 月 23 通過測試9 of 9 個範例 in this chapter pass

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 7 章,共 12 章: 找出延遲從何而來

  1. 關鍵路徑決定結束時間
  2. 首個資料塊時間
  3. 預填與生成
  4. 檢索內容與預填
  5. Tail percentiles with intervals
  6. 直方圖的桶與它們隱藏的資訊
  7. 以紀錄的服務時間進行排隊分析
  8. 正式環境中會出什麼問題
  9. 本章所做的決定

返回頂端所有章節