지연 시간이 어디에서 오는지 찾기

읽는 데 약 36분, 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)을 실행했다. 각 시간은 호출 하나의 기록된 시간이거나, Replay and the virtual clock에서 설명하는 가상 시계 위에서 그 시간들을 합한 값이다. 여기서 메시지의 시간은 메시지가 낸 각 호출의 기록된 시간에, 프로세스 내부 도구의 모델링된 시간과 contacts 호출의 기록된 시간을 더해 그 시계 위에서 합산한 값이다. 기록기는 호출 사이의 시간도 남겼으며, 재생에서는 그 시간을 제외한다. 하루 전체에서 그 시간은 합계 651.4 ms이며, 각 절은 자신의 수치가 둘 중 어느 쪽인지 밝힌다.

이 장은 먼저 메시지의 끝을 정하는 호출의 연쇄를 만들고, 다음으로 각 모델 호출을 읽기와 쓰기로 나누며, 마지막으로 꼬리 구간을 경로별 백분위수와 그 구간과 함께 살펴본다.

임계 경로가 종료 시각을 정한다

메시지의 트레이스는 시간이 기록된 스팬의 트리이며, 루트 스팬은 응답이 나가는 시점에 끝난다. 대부분의 스팬은 루트 안에 들어 있으며, 그중 대부분은 그 종료 시각을 정하지 않는다. 종료 시각을 정하는 스팬을 찾으려면 루트의 끝에서 거꾸로 따라간다. 가장 늦게 끝나는 자식 스팬을 고르고, 그다음에는 그 스팬이 시작하기 전에 가장 늦게 끝나는 자식 스팬을 고르는 식으로, 루트의 시작에 닿을 때까지 계속한다. 임계 경로는 메시지의 종료 시각을 정하는 스팬의 연쇄이다. 경로에 없는 다른 스팬을 줄여도 메시지는 더 빨리 끝나지 않는다. 경로 위의 스팬을 줄이면 다른 연쇄가 더 길어지기 전까지는 메시지가 짧아진다.

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

메시지 자체의 스팬을 체인에서 제외한다

+10 증명

20행은 전체 경로로 체인을 만들기 때문에, 메시지 자체의 루트 스팬이 링크 하나로 계산된다. 체인이 루트 아래에서 탐색이 도달하는 호출만 담도록 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 라우트에서 스팬을 보존한 채 다시 재생한다. 따라가 보면 연결 고리가 네 개 나온다. 라우트 호출, 응답 호출, add_event 도구, 두 번째 응답 호출이다. 출력은 각 고리의 시간을 보여 주며, 네 시간을 더하면 메시지의 24,305.8 ms가 된다. 경로가 차지하는 메시지 시간의 비율은 100.0%이며, 실행은 이 연쇄가 메시지 전체를 덮는다고 단언한다.

재생에서 이 비율을 볼 수 있는 이유는 호출이 사이에 아무것도 없이 차례로 실행되기 때문이다. 기록기의 공백에는 자체 스팬이 없으므로, 스팬으로 만든 경로에서는 그 공백이 빠진다. 이 메시지의 재생에는 그날의 공백이 없다. 경로가 덮는 것은 모델 호출, 프로세스 내부 도구의 모델링된 시간, contacts 호출의 기록된 시간이며, 그 밖의 것은 없다. retrieve 단계는 스팬의 시작과 끝이 한 시점이므로 시간을 차지하지 않는다.

겹침은 재생이 보여 줄 수 없는 경우이다. 기록된 메시지 중에는 두 호출이 동시에 실행된 것이 없으므로, 실행은 작은 트리를 직접 만든다. 스팬 a는 루트이며 10에서 끝난다. 스팬 b는 0에서 6까지, 스팬 c는 2에서 9까지 실행된다. 끝에서부터 따라가면 c에 먼저 닿고 b로는 돌아가지 않으므로 경로는 a, c이다. 스팬 b는 경로 밖에 있으며, b를 줄여도 종료 시각은 움직이지 않는다. 이는 이 트리에서만 성립한다. 경로는 루트 시간의 70.0%를 덮으므로, 경로 위의 스팬은 시간의 그만큼만 설명한다. 작업 규칙이 경고하는 낮은 비율이 바로 이것이다.

작업 규칙: 트레이스를 조정하기 전에 임계 경로를 따라가 보고, 경로 위의 스팬만 바꾼다. 먼저 메시지 시간에서 경로가 차지하는 비율을 읽는다. 비율이 낮다면 가지고 있는 스팬이 시간을 설명하지 못한다는 뜻이며, 나머지는 어느 스팬에도 속하지 않는다. 재생의 경로는 항상 그 메시지를 모두 덮으므로, 재생만으로는 겹치는 두 호출 중 어느 것이 중요한지 알 수 없다.

첫 청크까지의 시간

응답 호출이 경로의 대부분을 차지하므로, 다음 질문은 호출 안에서 시간이 어디에 쓰이는가이다. 첫 청크까지의 시간은 모델 호출을 보낸 시점부터 그 응답의 첫 스트리밍 조각을 받기까지 걸린 시간이다. 태그 0.1.0의 규약은 이 대기 시간을 메트릭 gen_ai.client.inference.time_to_first_chunk로 측정한다. 이 메트릭은 초 단위의 히스토그램이며, 스트리밍 호출에서만, 그리고 청크가 도착했을 때만 기록된다. 스팬 속성 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개의 route 호출은 중앙값 530.2 ms에 첫 청크에 도달한다.

응답 호출은 그 첫 청크를 내는 데 더 오래 걸린다. 7을 가진 messages 경로를 제외하면, 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은 출력에서 가장 넓다.

작업 규칙: 첫 청크까지의 시간을 같은 호출의 전체 시간과 나란히 출력하고, 두 값을 함께 읽는다. 첫 청크가 이르다는 것은 사용자가 출력을 일찍 본다는 뜻이다. 호출의 비용이 적다는 뜻은 아니다. 경로는 구간과 비율로 비교하고, 소수의 메시지만으로 한 경로의 첫 청크를 단정하지 않는다.

프리필과 생성의 비교

첫 번째 청크는 프롬프트를 기다리므로, 다음 질문은 그 대기 시간 가운데 얼마가 프롬프트를 읽는 데 쓰이고 얼마가 다른 일에 쓰이는가이다. 프리필은 모델이 프롬프트를 읽는 단계이고, 생성은 모델이 응답을 한 번에 토큰 하나씩 쓰는 단계이다. GPU용 서빙 논문들도 같은 구분을 한다. 프리필은 연산 자원을 계속 바쁘게 하고, 디코딩의 각 단계는 그 대부분을 놀게 한다(Agrawal et al., Sarathi-Serve, OSDI 2024; 반복마다 출력 토큰 하나를 다루는 방식은 Yu et al., Orca, OSDI 2022).

이 절에서 쓰는 개수에는 새로운 정의가 필요하지 않다. 6장은 입력 토큰과 출력 토큰이 어디에서 오는지 설명하고, 캐시된 입력을 다루는 절은 캐시된 비율을 어떻게 구하는지 설명한다. 평가된 토큰은 입력에서 캐시된 접두부를 뺀 나머지이며, 모델이 실제로 읽은 입력이다.

카운터는 llama-cpp-python에서 가져온다. llama-cpp-python은 llama.cpp가 컨텍스트마다 유지하는 카운터를 노출한다. 평가된 프롬프트 토큰과 그에 걸린 시간, 생성된 토큰과 그에 걸린 시간이 그것이다. 카운터는 누적만 되므로 기록기는 호출 전후의 차이를 구한다. 각 프로세스에서 첫 번째로 기록되는 메시지 전에 수행하는 네 번의 워밍업 호출은 이 구분에 포함하지 않는다.

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 토큰으로 진행되고, 프리필은 초당 62.3 토큰을 평가하며 읽는다. 이 속도는 개수로부터 계산한 값이며 이 기계에서만 성립한다. 그 이유는 소형 오픈 모델이 설명하는 바와 같다. 소형 모델의 속도는 이름이 밝혀진 한 기계의 기록에서 측정하며, 규칙으로 인용하지 않는다. 프리필은 입력 토큰이 아니라 평가된 토큰으로 센다. 이 선택이 왜 중요한지는 다음 절에서 보인다.

작업 규칙: 모델 호출의 프롬프트나 응답 길이를 바꾸기 전에, 호출 시간을 프리필과 생성으로 나눈다. 구분은 같은 기계와 같은 호출에서 카운터로 구하고, 전체 시간과 나란히 놓고 읽는다. 프리필이 첫 청크까지 걸리는 시간의 대부분이면 대기는 프롬프트에 있다. 생성이 호출의 대부분이면 대기는 응답의 길이에 있다.

검색된 컨텍스트와 프리필

검색은 답변 호출의 프롬프트에 기사를 넣으므로, 더 많이 검색하는 릴리스는 프리필이 더 길어질 것이다. 이 릴리스에서 물어야 할 것은 프리필이 얼마나 더 길어지는지, 그리고 모델이 추가된 입력을 모두 읽는지다. top-8 릴리스는 검색을 수행하는 경로에서 답변 호출에 기사를 최대 8개까지 주며, 기준 릴리스는 최대 3개까지 준다. 경로 호출은 검색보다 앞서 일어나므로, 어느 릴리스에서든 경로 호출의 프롬프트에는 기사가 들어 있지 않다.

비교에는 두 릴리스에서 같은 메시지를 사용한다. 짝지은 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번 줄은 비어 있다. 23번 줄이 찾아내는 개수보다 메시지 수가 적은 경로를 small이 담도록 33번 줄을 작성한다. 경로는 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

작은 경로의 구간 상한이 p95에서 멈추는 이유를 설명하기

+10 증명

alarms 경로의 95% 구간은 95번째 백분위수와 같은 값에서 끝난다. 이를 설명하는 것은 무엇인가?

작은 경로의 구간 상한이 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 규약은 에이전트의 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행이 비어 있다. 19행의 주석이 밝히는 규칙을 사용해, index가 정확한 95번째 백분위수를 담고 있는 버킷이 되도록 30행을 작성하라.

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번째 백분위수를 추정한 다음, 추정값을 원본 메시지의 최근접 순위 값과 나란히 놓는다. 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번째 백분위수 선은 넓은 버킷 안에 놓이며, 아래쪽 패널에는 메시지가 그 버킷의 어디에 있는지 알려 주는 것이 없다. 이것이 버킷이 잃는 정보이며, 추정값이 어긋나는 이유이다.

작업 규칙: 앞으로 던질 질문에 맞추어 버킷 경계를 정하고, 경보를 거는 각 임계값 근처에 경계를 하나씩 둔다. 백분위수가 넓은 버킷 안에 놓이면 밀리초 단위의 추정값 대신 그 버킷과 개수를 보고하고, 가능하면 원본 값을 계속 보관한다. 버킷에서 얻은 추정값은 하나의 규칙을 하나의 경계 집합에 적용한 결과이며, 경계가 달라지면 달라진다.

기록된 서비스 시간에 대한 대기열 분석

메시지의 처리 시간은 그 메시지 자체의 작업 시간만이 아니다. 모델이 다른 메시지를 처리하는 중에 메시지가 도착하면 그 메시지는 기다려야 하고, 이 대기 시간은 사용자가 보는 시간에 포함된다. 대기열을 사용하면 부하에 따라 이 대기 시간이 어떻게 늘어나는지 볼 수 있다. 도착한 메시지는 각각 줄에 들어가고, 서버는 한 번에 메시지 하나를 처리하며, 부하는 도착한 메시지가 요구하는 서버 시간의 비율이다.

이 절의 수치는 기록된 값이 아니라 계산된 값이다. 코드는 서버 하나를 모델로 삼는다. 도착은 부하로 정해지는 고정된 평균 속도로 무작위로 일어나며, 이는 포아송 과정이다. 도착 간격은 서로 독립이고 지수 분포를 따른다. 각 메시지의 서비스 시간은 그날 기록된 메시지 시간 중 하나를 복원 추출한 값이다. 리틀의 법칙에 따르면 시스템 안에 있는 평균 개수는 도착률에 각 항목이 시스템에 머무는 평균 시간을 곱한 값과 같으며, 이는 L = λW로 쓴다. Little의 1961년 증명이 이를 입증하며, M/M/1 대기열에 관한 MIT 강의 노트는 여기서 쓰는 형태로 이를 서술한다.

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이 된다. 코드는 앞의 값을 시간에 따른 대기열의 사건에서 구하고 뒤의 값을 도착률과 평균 시스템 내 시간에서 구한 다음, 모든 부하에서 두 값이 같다고 단언한다. 첫 도착부터 마지막 출발까지를 구간으로 하는 표본 경로에서는 리틀의 법칙이 정확히 성립하므로, 이 단언은 허용 오차를 두지 않는다.

M/M/1 공식은 서버 하나와 지수 서비스에서의 평균 시스템 내 시간을 주며, 서비스 시간이 지수 분포일 때만 정확하다. 기록된 시간은 지수 분포가 아니다. 그래서 코드는 먼저 시뮬레이션 자체를 기준으로 검증한다. 부하 0.8에서 지수 서비스로 메시지 200,000개를 시뮬레이션하면 평균 시스템 내 시간은 40,422.0 ms이고, 공식은 40,094.8 ms을 준다. 코드는 두 값이 2% 이내에서 일치한다고 단언한다. 서비스 분포가 임의인 단일 서버인 M/G/1에는 고유한 평균 공식이 있으나, 이 장은 그 검증을 다루지 않는다.

이것은 서버 하나의 모델이며 Ambrewick의 배포 환경에 대한 모델이 아니다. 각 메시지의 기록된 전체 시간을 하나의 서비스로 보는데, 이는 대기열이 메시지를 다루는 방식이며, 도착은 그날의 실제 도착 시각을 무시한다. 따라서 대기 시간은 이런 메시지 구성을 가진 서버 하나가 보였을 값이지, 그날 실제로 일어난 값이 아니다.

작업 규칙: 꼬리 구간을 받아들이거나 용량을 늘리기 전에, 예상하는 부하와 그보다 높은 부하에서 대기열을 읽어라. 기록된 서비스 시간이 있으면 그것을 사용하고, 시뮬레이션이 계산한 모든 수치에 계산된 값이라고 표시하며, 공식의 가정이 성립하는 경우에만 시뮬레이션을 공식과 대조하라.

운영 환경에서 잘못되는 것

이 수치들이 리플레이를 벗어나면 세 가지가 달라진다. 첫째, 운영 환경의 스팬에는 빈틈이 생긴다. 기록기가 측정한 호출 사이의 간격은 하루 동안 모두 651.4 ms이다. 이 간격은 메시지 안에서 실제로 흐른 시간이지만 어느 스팬에도 속하지 않는다. 그래서 스팬으로 만든 크리티컬 패스는 메시지의 전체 시간보다 적은 시간만 덮을 수 있다. 경로의 비율은 메시지 시간과 함께 읽고, 비율이 낮으면 답이 아니라 트레이스에 던질 질문으로 다룬다.

둘째, 서비스가 내보내는 히스토그램의 경계는 그 서비스의 설정이 정한 값이며, 관례가 권하는 경계와 다를 수 있다. 버킷에서 읽은 백분위수는 경계가 만드는 오차를 그대로 지닌다. 이날의 메시지에 대한 버킷 추정이 이를 보여 준다. 9장은 이 지연 시간을 기준으로 목표를 정하므로, 경계도 그 결정에 포함된다.

셋째, 하루에 메시지가 적은 경로의 95번째 백분위수는 구간이 넓다. 점 값만 보여 주는 대시보드는 실제보다 정확해 보인다. 개수와 구간을 같은 패널에 놓거나, 백분위수를 패널에서 뺀다.

작업 규칙: 운영 환경의 지연 시간 수치를 공개하기 전에, 그 옆에 개수와 구간을 출력하고 어떤 종류의 시간인지 밝힌다. 스팬의 시간인지, 버킷의 추정인지, 리플레이의 합인지를 적는다. 경로의 비율이나 버킷의 경계를 알 수 없다면, 수치만 홀로 두지 말고 그 사실을 수치와 함께 적는다.

이 장이 내린 결정

이 결정들은 각각 우리가 틀릴 수 있는 판단이다. 각 항목은 그 이유와 그 판단을 시험하는 예제를 함께 제시한다.

  • 우리는 스팬에서 임계 경로를 읽고, 겹치는 호출이 있는 경우는 구성한 트리로 보인다. 기록된 메시지 중에는 호출이 겹치는 것이 없기 때문이다. critical-path-one-message은 그 경로가 재생한 메시지 전체를 덮는지, 그리고 구성한 트리의 스팬 b가 경로 밖에 있는지 확인한다.
  • 우리는 첫 청크까지의 시간을 같은 호출의 전체 시간과 나란히 보고하고, 카운터로 그 시간을 나눈다. 첫 청크를 단독으로 읽는 일이 없게 하기 위해서다. time-to-first-chunk-by-route와 prefill-generation-split은 같은 호출에 대해 둘을 모두 출력한다.
  • 우리는 최근접 순위 백분위수를 개수와 함께 출력하고, 각 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월 239 of 9개 예제 in this chapter pass

영어판 2026.11.2판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 7장: 지연 시간이 어디에서 오는지 찾기

  1. 임계 경로가 종료 시각을 정한다
  2. 첫 청크까지의 시간
  3. 프리필과 생성의 비교
  4. 검색된 컨텍스트와 프리필
  5. Tail percentiles with intervals
  6. 히스토그램 버킷과 버킷이 감추는 것
  7. 기록된 서비스 시간에 대한 대기열 분석
  8. 운영 환경에서 잘못되는 것
  9. 이 장이 내린 결정

맨 위로 돌아가기전체 장