보존할 트레이스 선택하기

읽는 데 약 33분, 7절에 6개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 23 80개 예제 중 80개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 백엔드가 보존할 트레이스를 선택하고, 각 선택이 무엇을 버리는지 설명하며, 보존된 트레이스로부터 전체 합계를 추정하고 그 결과에 구간을 붙일 수 있다. 엔지니어에게 가장 필요한 트레이스를 보존하는 규칙을 작성하고, 장애 발생일의 데이터로 그 규칙을 검증한다.

Ambrewick은 메시지마다 트레이스를 하나씩 남기며, 1장에서는 그 트레이스를 모두 보존했다. 이 책의 규모인 하루 200개 메시지에서는 관리하기가 간단하다. 하루 종일 메시지에 응답하는 서비스는 훨씬 많은 트레이스를 기록하고, 트레이스를 1년 동안 모두 보관하는 백엔드는 그 하나하나에 비용을 치른다. 샘플러는 일부 트레이스를 보존하고 나머지는 버리므로, 중요한 결정은 어느 트레이스를 남기느냐이다. 장애 발생일이 이 문제를 보여 준다. 이날의 오류는 드물며, 경보가 울린 뒤 트레이스를 여는 엔지니어에게는 평범한 메시지보다 그 오류와 느린 메시지가 더 필요하다. 트레이스를 읽지 않고 고르는 샘플러는 드문 트레이스도 나머지와 같은 비율로만 보존한다.

이 장은 트레이스 샘플링이 내리는 세 가지 종류의 결정과, 일부 트레이스만 보존했을 때 합계를 구하는 데 필요한 추정을 다룬다. 여기서 트레이스 샘플링은 백엔드가 보존할 트레이스를 정하는 일을 뜻한다. 모델이 다음에 쓸 단어를 고르는 토큰 샘플링과는 관계가 없다. 예제는 기록된 이틀의 데이터로 실행한다. 하나는 주입된 결함이 없는 기준일 1이고, 다른 하나는 9장의 장애 발생일이다. 두 날 모두 4 vCPU Intel Xeon 2.10 GHz인 기록용 머신에서 기록했으며, 이 머신은 Qwen3-4B-Instruct-2507을 실행했다. 두 날 모두 가상 시계로 재생한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Head sampling decides before the trace runs

Head sampling decides whether to keep a trace when it starts, before any span has run. The kind this chapter uses keeps a fixed share by the trace ID, so it cannot know whether the message will fail and cannot aim at failures. The ratio is the share of traces kept, and the sample is keyed on the trace ID.

The SDK's ratio sampler compares the trace ID with the ratio. It reads the low 64 bits of the trace ID as a number, and it keeps the trace when that number falls below the ratio's share of the whole range (the sampler in the Python SDK, pinned here at 1.45.2). The decision depends on the ID alone, so every span of a trace agrees with the others, and the same trace gets the same answer on every run. The book's trace IDs count up from 1, and small counts all fall under any ratio above zero, so the book hashes each count to 128 bits before the sampler reads it. The specification deprecates TraceIdRatioBased in favour of ProbabilitySampler, which decides from the 56 bits of randomness that W3C Trace Context Level 2 specifies (the trace SDK specification at v1.50.0). The pinned SDK has no ProbabilitySampler, so the book uses the ratio sampler at the root.

The replay runs every message first and makes the head decision afterward. The decision is applied to the completed traces, and it is the same decision the assistant's own sampler would make at the source, because the trace ID alone settles it. The example's last lines check that claim: at each ratio it uses, a provider with the same sampler starts a root span for every trace ID of the day, and the example asserts that the two decisions agree.

head-sample-ratio.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 통과
"""Head sampling on baseline day 1: the share of messages each ratio keeps, and the rule that a larger ratio keeps everymessage a smaller one kept. The decision is the SDK's TraceIdRatioBased on each message's trace ID, as its root wouldmake it, so the same messages stay kept as the ratio grows. A live provider samples the same trace IDs at the source, andthe replayed and the live decisions must agree."""from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom lib.dayrun import run_day_tracedfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_sharefrom lib.sampling import head_ratio, head_sample, live_provider, message_traces, only_messagesMODEL = "Qwen3-4B-Instruct-2507"DAY = "2026-12-08"                                  # baseline day 1: no injected faultsRATIOS = (0.01, 0.1, 0.5, 1.0)                      # 1.0 keeps everything, the check that the ratio is read as a sharetraces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))print("messages on baseline day 1, of all messages:", fmt_int(len(traces)))kept = {}                                           # ratio -> the sequential trace IDs it keepsfor ratio in RATIOS:    kept[ratio] = {t.seq for t in head_sample(traces, ratio)}    print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(kept[ratio])))    print(f"share of messages kept at ratio {ratio}:", fmt_share(len(kept[ratio]), len(traces)))    # The source's own decision: a provider with the same sampler makes one root per trace ID, counting from 1.    provider = live_provider(head_ratio(ratio), InMemorySpanExporter())    tracer = provider.get_tracer("ambrewick.assistant")    live = set()    for seq in range(1, len(traces) + 1):        root = tracer.start_span("invoke_agent probe")        if root.is_recording():            live.add(seq)        root.end()    differ = len(live ^ kept[ratio])    print(f"trace IDs where the replayed and the live decision differ at ratio {ratio}, of {len(traces)}:", fmt_int(differ))    assert differ == 0# A trace kept at a small ratio is kept at every larger one: the decision compares one fixed value with the ratio.assert kept[0.01] <= kept[0.1] <= kept[0.5] <= kept[1.0]assert len(kept[1.0]) == len(traces)
출력python head-sample-ratio.py
messages on baseline day 1, of all messages: 200
messages kept at ratio 0.01, of 200: 5
share of messages kept at ratio 0.01: 2.5%
trace IDs where the replayed and the live decision differ at ratio 0.01, of 200: 0
messages kept at ratio 0.1, of 200: 21
share of messages kept at ratio 0.1: 10.5%
trace IDs where the replayed and the live decision differ at ratio 0.1, of 200: 0
messages kept at ratio 0.5, of 200: 96
share of messages kept at ratio 0.5: 48.0%
trace IDs where the replayed and the live decision differ at ratio 0.5, of 200: 0
messages kept at ratio 1.0, of 200: 200
share of messages kept at ratio 1.0: 100.0%
trace IDs where the replayed and the live decision differ at ratio 1.0, of 200: 0

A larger ratio keeps every message that a smaller one kept, and the example checks that first. At 0.1 the backend keeps 21 of the day's 200 messages. The ratio describes the share over many traces, and a single day can land a little above or below it, so the count is the day's and not the ratio's.

Working rule: Pick a head ratio only for traffic whose rare cases you can afford to lose. Run the ratio sampler at the root only, under ParentBased, and leave every other service on the default sampler or another parent-based one. The trace SDK specification recommends the ratio sampler "only for root spans", since different SDKs, and different versions of one SDK, can give inconsistent results for the same input. Print the kept share beside its count, as the example does, and never read the share as a count.

자식 스팬은 루트의 결정을 따른다

트레이스는 프로세스 경계를 넘나들며, 연락처 서버는 두 번째 프로세스다. 4장에서는 트레이스의 식별 정보를 traceparent로 각 요청에 담았으며, 이 헤더의 플래그 중 하나가 샘플링 플래그다(이 책이 기준으로 삼는 버전인 Trace Context Level 1). 부모 기반 샘플링은 각 스팬이 부모의 결정을 따르게 한다. 루트 스팬은 헤드 샘플러에 묻고, 그 아래의 모든 스팬은 자체 비율을 적용하는 대신 부모의 플래그를 읽는다. 서버는 어시스턴트의 비율을 알 수 없고 플래그만 보기 때문에, 이 방식은 프로세스 사이에서 중요하다.

연락처 서버는 자체 샘플러를 설정하지 않는다. 서버의 트레이서 프로바이더는 OTEL_TRACES_SAMPLER가 설정되지 않은 SDK 기본값을 사용하며, 이 기본값은 원격 부모의 샘플링 플래그를 따른다. 플래그가 설정되어 있으면 서버는 스팬을 샘플링하고, 설정되어 있지 않으면 버린다. 아래 프로브는 어시스턴트의 샘플러를 출발점에서 0.5의 비율로 켜고, 각 루트 아래에서 서버가 기록하는 스팬의 수를 센다.

parent-based-follows-root.py Python 3.13.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 통과
"""A parent-based sampler at the assistant decides each message's trace once, at its root, and the contacts server followsthat decision through the traceparent. The point rests on the server's count: no span reaches the receiver from atrace the assistant did not sample."""import jsonimport tempfilefrom collections import Counterfrom pathlib import Pathfrom opentelemetry import tracefrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterfrom lib.clock import VirtualClockfrom lib.report import fmt_int, fmt_sharefrom lib.sampling import head_ratio, live_providerfrom lib.tools import LiveContactsDAY, PROBES, RATIO = "2026-12-09", 40, 0.5exporter = InMemorySpanExporter()provider = live_provider(head_ratio(RATIO), exporter)  # the assistant's provider: its roots sampled at 0.5, children followtrace.set_tracer_provider(provider)                    # the MCP client span is made by the process's global providertracer = provider.get_tracer("ambrewick.assistant")recorded = {}                                          # trace ID -> whether the assistant's root was recordedwith tempfile.TemporaryDirectory() as folder:    spans_file = Path(folder) / "contacts-spans.jsonl"  # the server writes here, and the file is read after it exits    with LiveContacts(VirtualClock(DAY), spans_file) as contacts:        for number in range(PROBES):            with tracer.start_as_current_span(f"invoke_agent probe {number}") as root:                recorded[format(root.get_span_context().trace_id, "032x")] = root.is_recording()                contacts.find("U0028", "Ana")          # one tool call, inside this root, so its traceparent carries the root's flag    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]per_trace = Counter(row["trace_id"] for row in server)sampled = [t for t, yes in recorded.items() if yes]unsampled = [t for t, yes in recorded.items() if not yes]print("probes, one assistant root each:", fmt_int(PROBES))print(f"roots sampled at ratio {RATIO}, of {PROBES}:", fmt_int(len(sampled)))print(f"share of roots sampled at ratio {RATIO}:", fmt_share(len(sampled), PROBES))print("contacts server spans under sampled roots:", fmt_int(sum(per_trace[t] for t in sampled)))print("contacts server spans under unsampled roots:", fmt_int(sum(per_trace[t] for t in unsampled)))print("unsampled roots with any server span, of the unsampled:", fmt_int(sum(per_trace[t] > 0 for t in unsampled)))print("sampled roots with any server span, of the sampled:", fmt_int(sum(per_trace[t] > 0 for t in sampled)))assert all(t in recorded for t in per_trace)  # every server span belongs to a probe's traceassert not any(per_trace[t] for t in unsampled)     # the server records nothing for an unsampled traceassert all(per_trace[t] for t in sampled)           # and everything for a sampled one
출력python parent-based-follows-root.py
probes, one assistant root each: 40
roots sampled at ratio 0.5, of 40: 19
share of roots sampled at ratio 0.5: 47.5%
contacts server spans under sampled roots: 39
contacts server spans under unsampled roots: 0
unsampled roots with any server span, of the unsampled: 0
sampled roots with any server span, of the sampled: 19
연습문제 11.1

샘플링되지 않은 루트 아래에 서버 스팬이 나타나지 않는 이유

+10 증명

프로브가 "contacts server spans under unsampled roots: 0"을 출력한다. 이 결과를 설명하는 것은 어느 것인가?

샘플링되지 않은 루트 아래에 서버 스팬이 나타나지 않는 이유: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

연락처 서버는 스스로 결정을 내리지 않았으므로, 트레이스는 양쪽 모두에 기록되거나 양쪽 모두에 기록되지 않았다. 샘플링되지 않은 루트 아래에서 서버가 기록한 스팬은 0개였다. 프로브 루트 40개 중 어시스턴트가 샘플링한 루트는 19개였고, 그 루트 모두에 서버 스팬이 있었으며, 예제는 이를 단언한다.

작업 규칙: 샘플링은 루트에서만 하고, 다른 모든 서비스는 기본 샘플러나 다른 부모 기반 샘플러를 쓰게 둔다. 다른 서비스가 자체 비율, 알고리즘, SDK 버전을 쓰면 하나의 트레이스가 두 조각으로 갈라져 남을 수 있다. 같은 비율의 동일한 샘플러 두 개는 서로 결정이 일치하기 때문이다. 우리라면 서버에 자체 비율을 주지 않을 것이다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Tail sampling reads the whole trace

Head sampling decides before the message runs, and the failure happens while it runs. Tail sampling decides once the whole trace is in, by what it holds. The rule in this chapter keeps three kinds of trace, in this order. It keeps a trace whose message has an error, in the sense chapter 8 defines. It keeps a trace whose message ran past the latency objective from chapter 9, which is 20,000.0 ms. And it keeps a trace whose model calls cost more than the 99th percentile of baseline day 1, which is $0.000115 per message, the costly tail that chapter 6 counts. Each kept trace is kept whole, with every span from both processes, and the rule stops once its span budget is spent.

The rule is this book's own code, TailRule in lib/sampling.py, and it runs at the receiver once a trace's root has arrived. In every trace of the incident day the root is the last span to end, so a trace is whole when its root arrives. That is by end time. Spans can arrive over a network in another order, so a receiver should also wait.

The rule reads each whole trace, so the errors it keeps are the ones it found, not the ones a ratio happened to pick. The timeout window is part of this count. Chapter 9 showed that a lookup timeout writes ERROR attempts while the user still gets a reply, so those messages have an error in chapter 8's sense. The engineer needs their cause even though no user complained, and the rule keeps them for that reason.

Before the first run, make a prediction. The incident day has messages with an error, and a 10% head sample decides for each of them before anything runs. Predict how many of those messages the head sample keeps: all of them, about a tenth of them, or none. Write the number down, then run the example.

tail-rule-keeps-errors.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 통과
"""The incident day's failed messages, kept by a 10 percent head sample and by the tail rule. A message failed when a spanin its trace ends with ERROR (chapter 8). The head sample decides before anything runs, so the count it keeps is chance;the tail rule reads each whole trace and keeps every failed one. A detached root is judged as a trace of its own."""from lib.clock import NS_PER_SECONDfrom lib.dayrun import run_day_tracedfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_ms, fmt_share, fmt_usdfrom lib.sampling import TailRule, head_sample, message_traces, only_messagesfrom lib.stats import nearest_rankMODEL = "Qwen3-4B-Instruct-2507"BASE, INCIDENT = "2026-12-08", "2026-12-09"SLOW_NS = 20 * NS_PER_SECOND                        # chapter 9's latency objective: a message over 20 s is slowprice = PriceTable()# The expensive threshold is baseline day 1's 99th percentile of message cost (nearest rank, PL-5): the incident is# judged by the day before it, not by itself.expensive = nearest_rank([t.cost for t in only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))], 99)live = run_day_traced(INCIDENT)                     # live: the contacts server runs the injected faults over stdiotraces = message_traces(live.spans + live.server, INCIDENT, MODEL, price)  # each trace whole, the server's spans includedmessages = only_messages(traces)failed = [t for t in messages if t.error]head = head_sample(messages, 0.1)kept = TailRule(keep_error=True, slow_ns=SLOW_NS, expensive=expensive, budget=sum(len(t.rows) for t in traces)).keep(traces)print("latency threshold, the 20 s objective:", fmt_ms(SLOW_NS))print("cost threshold, baseline day 1's 99th percentile per message:", fmt_usd(expensive))print("messages on the incident day:", fmt_int(len(messages)))print("detached roots, traces of their own with no message, incident day:", fmt_int(len(traces) - len(messages)))print("messages with an error, of all messages:", fmt_int(len(failed)))print("share of messages with an error:", fmt_share(len(failed), len(messages)))print(f"messages with an error kept by a 10% head sample, of {len(failed)}:", fmt_int(sum(t.error for t in head)))print("share of messages with an error kept by a 10% head sample:", fmt_share(sum(t.error for t in head), len(failed)))print(f"messages with an error kept by the tail rule, of {len(failed)}:", fmt_int(sum(t.seq in kept for t in failed)))print("share of messages with an error kept by the tail rule:", fmt_share(sum(t.seq in kept for t in failed), len(failed)))assert all(t.seq in kept for t in failed)           # the tail rule keeps every failed messageassert sum(t.error for t in head) < len(failed)     # the head sample loses most of themassert all(max(r["end_ns"] for r in t.rows if r["parent_span_id"] is None) == max(r["end_ns"] for r in t.rows)           for t in traces)                         # the root ends last, so a trace is whole when its root arrives (B-83)
출력python tail-rule-keeps-errors.py
latency threshold, the 20 s objective: 20,000.0 ms
cost threshold, baseline day 1's 99th percentile per message: $0.000115
messages on the incident day: 60
detached roots, traces of their own with no message, incident day: 4
messages with an error, of all messages: 17
share of messages with an error: 28.3%
messages with an error kept by a 10% head sample, of 17: 2
share of messages with an error kept by a 10% head sample: 11.8%
messages with an error kept by the tail rule, of 17: 17
share of messages with an error kept by the tail rule: 100.0%
연습문제 11.2

헤드 샘플이 실패 대부분을 놓치는 이유

+10 증명

22번째 줄은 10% 헤드 샘플을 추출하고, 30번째 줄은 그 샘플이 실패한 메시지를 몇 개나 유지하는지 보고한다. 헤드 샘플이 실패한 메시지를 소수만 유지하는 이유를 설명하는 것은 무엇인가?

헤드 샘플이 실패 대부분을 놓치는 이유: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

The incident day has 60 messages, and 17 of them have an error.

The head sample loses most of those errors. It keeps 2 of them, which is 11.8%. The guess of about a tenth came close here, but the head sample had no way to aim at the errors, so its count was a matter of chance.

The tail rule loses none. It keeps all 17 of them.

A rule that keeps every error can still cost too much, so the book's rule also takes a budget of spans for the day. Spans are what the backend stores, and a trace with many model calls holds many of them. Next, the rule is given a budget that the incident day cannot fit whole: 120 spans against a day of 276.

tail-rule-span-budget.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 통과
"""The tail rule under a span budget on the incident day: errors first, then the slowest messages, then the costliest, eachkept whole until the budget is spent. The budget of 120 spans is below the 127 the rule would keep with none, so it hasto drop something; the point rests on every error being kept and the slow message with no error being dropped."""from lib.clock import NS_PER_SECONDfrom lib.dayrun import run_day_tracedfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.sampling import TailRule, message_traces, only_messages, retained_bytesfrom lib.stats import nearest_rankMODEL = "Qwen3-4B-Instruct-2507"BASE, INCIDENT = "2026-12-08", "2026-12-09"BUDGET, SLOW_NS = 120, 20 * NS_PER_SECONDprice = PriceTable()base = only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))expensive = nearest_rank([t.cost for t in base], 99)  # the baseline day's 99th percentile of cost, as in the last examplelive = run_day_traced(INCIDENT)                     # live: the contacts server runs the injected faults over stdiotraces = message_traces(live.spans + live.server, INCIDENT, MODEL, price)  # each trace whole, the server's rows includedmessages = only_messages(traces)spans = sum(len(t.rows) for t in messages)kept = TailRule(True, SLOW_NS, expensive, BUDGET).keep(traces)no_budget = TailRule(True, SLOW_NS, expensive, sum(len(t.rows) for t in traces)).keep(traces)kept_spans = sum(len(t.rows) for t in traces if t.seq in kept)dropped = [t for t in messages if t.duration_ns > SLOW_NS and not t.error and t.seq not in kept]print("spans in the incident day's messages:", fmt_int(spans))print("spans in messages with an error:", fmt_int(sum(len(t.rows) for t in messages if t.error)))print("span budget:", fmt_int(BUDGET))print("spans the tail rule keeps with no budget, incident day:", fmt_int(sum(len(t.rows) for t in traces if t.seq in no_budget)))print("spans kept under the budget, of all spans:", fmt_int(kept_spans))print("share of spans kept under the budget:", fmt_share(kept_spans, spans))for reason in ("error", "slow", "expensive"):    print(f"messages kept for {reason}, under the budget:", fmt_int(sum(v == reason for v in kept.values())))print("slow messages with no error, dropped for the budget:", fmt_int(len(dropped)))print("time of the slowest message dropped for the budget:", fmt_ms(max(t.duration_ns for t in dropped)))print("messages over the expensive threshold with no error or slow time, incident day:",      fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in messages)))print("messages over the expensive threshold with no error or slow time, baseline day 1:",      fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in base)))# Retention: bytes per message without content, in the JSON-lines export (capture is off until chapter 12).per_message, kept_bytes, day_bytes = retained_bytes(base, messages, kept)print("bytes per message without content, baseline day 1:", fmt_int(per_message))print("bytes kept under the budget, of the incident day's bytes:", fmt_share(kept_bytes, day_bytes))assert all(t.seq in kept for t in messages if t.error)  # the budget leaves every error inassert kept_spans <= BUDGETassert sum(len(t.rows) for t in traces if t.seq in no_budget) > BUDGET
출력python tail-rule-span-budget.py
spans in the incident day's messages: 276
spans in messages with an error: 116
span budget: 120
spans the tail rule keeps with no budget, incident day: 127
spans kept under the budget, of all spans: 116
share of spans kept under the budget: 42.0%
messages kept for error, under the budget: 17
messages kept for slow, under the budget: 0
messages kept for expensive, under the budget: 0
slow messages with no error, dropped for the budget: 1
time of the slowest message dropped for the budget: 22,622.1 ms
messages over the expensive threshold with no error or slow time, incident day: 0
messages over the expensive threshold with no error or slow time, baseline day 1: 0
bytes per message without content, baseline day 1: 2,831
bytes kept under the budget, of the incident day's bytes: 42.6%
연습문제 11.3

스팬 예산을 예산 없음일 때의 스팬 수보다 약간 작게 잡기

+10 증명

13번째 줄이 스팬 예산을 정한다. 예제가 아래 출력을 내도록 이 줄을 고쳐라. 책의 출력과 다른 부분은 스팬 예산을 보고하는 줄뿐이다. spans in the incident day's messages: 276 spans in messages with an error: 116 span budget: 126 spans the tail rule keeps with no budget, incident day: 127 spans kept under the budget, of all spans: 116 share of spans kept under the budget: 42.0% messages kept for error, under the budget: 17 messages kept for slow, under the budget: 0 messages kept for expensive, under the budget: 0 slow messages with no error, dropped for the budget: 1 time of the slowest message dropped for the budget: 22,622.1 ms messages over the expensive threshold with no error or slow time, incident day: 0 messages over the expensive threshold with no error or slow time, baseline day 1: 0 bytes per message without content, baseline day 1: 2,831 bytes kept under the budget, of the incident day's bytes: 42.6%

MODEL = "Qwen3-4B-Instruct-2507"BASE, INCIDENT = "2026-12-08", "2026-12-09"price = PriceTable()base = only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))expensive = nearest_rank([t.cost for t in base], 99)  # the baseline day's 99th percentile of cost, as in the last example

얻어야 할 출력

spans in the incident day's messages: 276
spans in messages with an error: 116
span budget: 126
spans the tail rule keeps with no budget, incident day: 127
spans kept under the budget, of all spans: 116
share of spans kept under the budget: 42.0%
messages kept for error, under the budget: 17
messages kept for slow, under the budget: 0
messages kept for expensive, under the budget: 0
slow messages with no error, dropped for the budget: 1
time of the slowest message dropped for the budget: 22,622.1 ms
messages over the expensive threshold with no error or slow time, incident day: 0
messages over the expensive threshold with no error or slow time, baseline day 1: 0
bytes per message without content, baseline day 1: 2,831
bytes kept under the budget, of the incident day's bytes: 42.6%
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에서 실행된다

The budget keeps 116 spans, which is 42.0% of the day's. Those are the spans of the 17 messages with an error, and the rule keeps no slow message and no costly one.

Errors are ranked first, so they take their spans before anything else is considered, and the remainder of the budget is what is left for a slow message. The slow message without an error, which took 22,622.1 ms, holds more spans than that remainder, so the budget drops it. Two assertions in the code hold the rule to this: every error is kept, and the budget binds, since with no budget the rule keeps 127 spans, more than the budget allows.

The budget of 120 spans is the book's choice, not a rule of the method. It is above the spans that the errors take, so every error survives. The messages with an error hold 116 spans between them, so a budget below that would drop one of them, and the rule exists to keep them. A larger budget would also keep the slow message, at the cost of its spans.

The expensive class keeps nothing extra on either day. The number of messages above the expensive threshold with neither an error nor a slow time is 0 on the incident day and 0 on baseline day 1. Every costly message on both recorded days was also an error or a slow message, so the class does no work on them. We keep it in the rule because a costly message with neither mark is possible, and the rule should keep it when one comes. Neither recorded day shows one. The errors this rule keeps are also the traces that chapter 12 scans for personal data, so the rule also decides what that scan reads.

Working rule: Keep errors first, and set the budget above the spans they take on a day you have measured, not from a guess. Count the messages that are costly but neither erroneous nor slow before you trust a cost class, and say what a smaller budget would drop.

표본으로 하루의 총계 추정하기

샘플링은 스팬을 솎아 내므로, 남은 스팬을 합한 총계는 실제 하루의 총계보다 작다. 반면 샘플링은 카운터를 솎아 내지 않는다. 6장에서 스팬을 합하면 이중 집계가 생긴다는 점을 보았으므로, 이 책은 총계를 카운터에서 읽는다. 카운터는 어시스턴트의 계량기가 모델 호출이 끝날 때마다 값을 더해 간다. 9장도 같은 계량기에서 경보를 읽으므로, 샘플링은 총계나 경보를 솎아 내지 않는다. 표본에서 얻은 추정치는 카운터로는 나눌 수 없는 구분을 위한 것이며, 구분의 정확도는 각 부분에 남은 개수만큼만 좋다.

헤드 표본의 총계에 비율의 역수를 곱하면 전체를 추정할 수 있다. 모든 트레이스가 남을 확률이 같기 때문이다. 즉 남은 총계에 비율의 역수를 곱한 값이 하루의 추정치이다. 구간은 추정치에 표준오차의 1.96배를 더하고 뺀 값이며, 표준오차는 표본으로 뽑힌 트레이스만으로 구한다. 테일 규칙은 비율과 상관없이 일부 트레이스를 남기므로, 그 규칙이 남긴 집합은 하루의 일정한 몫이 아니다. 헤드 비율과 테일 규칙을 함께 적용하면(아래의 결정들) 백엔드에는 둘의 합집합이 남는데, 이는 헤드 표본이 아니다. 따라서 각 트레이스에 남은 이유를 표시하고 헤드 표본의 트레이스만 스케일해야 한다. 이 절에서는 헤드 표본만 스케일한다.

기준일 1의 10% 표본 하나에 10을 곱하면 추정치가 나오며, 이 추정치를 하루의 전체 개수 및 토큰 카운터와 견줄 수 있다.

estimate-totals-error.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 통과
"""Estimate baseline day 1's total tokens and cost from a 10 percent head sample, scaled by one over the ratio, with the 95percent interval (the estimate plus or minus 1.96 standard errors). The estimate is set against the full count, summed overevery message, and against the token counter's total for the day. The point is coverage: over 2,000 independent samples theinterval holds the full count in only some of them, and the printed count says how many."""from decimal import Decimalfrom opentelemetry.sdk.metrics.export import InMemoryMetricReaderfrom lib.dayrun import RELEASE, run_day_tracedfrom lib.metrics import USAGE, make_meter_provider, totalsfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_share, fmt_usdfrom lib.sampling import draws_holding, estimate_total, head_sample, message_traces, only_messagesMODEL = "Qwen3-4B-Instruct-2507"DAY, RATIO, DRAWS, SEED = "2026-12-08", 0.1, 2000, 20261207  # SEED is PL-6's; each draw salts the trace IDs with its numberreader = InMemoryMetricReader()provider = make_meter_provider(reader, service_instance_id=f"{DAY}-metrics", service_version=RELEASE.service_version)traced = run_day_traced(DAY, live=False, meter_provider=provider)  # the assistant's live meter counts each call's tokenstraces = only_messages(message_traces(traced.spans, DAY, MODEL, PriceTable()))counter = totals(reader)counter_tokens = int(counter[USAGE["input"]]["sum"]) + int(counter[USAGE["output"]]["sum"])sample = head_sample(traces, RATIO)full_tokens = sum(t.tokens for t in traces)full_cost = sum((t.cost for t in traces), Decimal(0))print(f"messages kept at ratio {RATIO}, of {len(traces)}:", fmt_int(len(sample)))tokens, tokens_interval = estimate_total([t.tokens for t in sample], RATIO)print("full count of tokens, all messages:", fmt_int(full_tokens))print("token counter total for the day, input plus output:", fmt_int(counter_tokens))print(f"estimated tokens, ratio {RATIO}:", fmt_int(int(tokens)))print("estimate as a share of the full count, tokens:", fmt_share(tokens, full_tokens))print("interval as shares of the full count, tokens, low end:", fmt_share(tokens_interval[0], full_tokens))print("interval as shares of the full count, tokens, high end:", fmt_share(tokens_interval[1], full_tokens))cost, cost_interval = estimate_total([t.cost for t in sample], RATIO)print("full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates:", fmt_usd(full_cost))print(f"estimated cost, ratio {RATIO}:", fmt_usd(cost))print("estimate as a share of the full cost:", fmt_share(cost, full_cost))print("interval as shares of the full cost, low end:", fmt_share(cost_interval[0], full_cost))print("interval as shares of the full cost, high end:", fmt_share(cost_interval[1], full_cost))assert counter_tokens == full_tokens          # the counter reads each call once, so it matches the root spansprint("samples of the same day, drawn independently:", fmt_int(DRAWS))held_tokens, held_cost = draws_holding(traces, RATIO, DRAWS, SEED)print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, tokens:", fmt_int(held_tokens))print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, cost:", fmt_int(held_cost))
출력python estimate-totals-error.py
messages kept at ratio 0.1, of 200: 21
full count of tokens, all messages: 109,807
token counter total for the day, input plus output: 109,807
estimated tokens, ratio 0.1: 98,090
estimate as a share of the full count, tokens: 89.3%
interval as shares of the full count, tokens, low end: 38.7%
interval as shares of the full count, tokens, high end: 140.0%
full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates: $0.007563
estimated cost, ratio 0.1: $0.005524
estimate as a share of the full cost: 73.0%
interval as shares of the full cost, low end: 29.6%
interval as shares of the full cost, high end: 116.5%
samples of the same day, drawn independently: 2,000
intervals that hold the full count, of 2,000 samples at ratio 0.1, tokens: 1,843
intervals that hold the full count, of 2,000 samples at ratio 0.1, cost: 1,854
연습문제 11.4

모든 메시지에 대해 합산한 전체 개수

+10 증명

24행은 보존된 메시지의 토큰을 합산하므로, 전체 개수가 하루 전체의 값이 아니라 표본의 합계가 된다. 전체 개수가 그날의 모든 메시지의 토큰이 되도록 24행을 고쳐라.

counter = totals(reader)counter_tokens = int(counter[USAGE["input"]]["sum"]) + int(counter[USAGE["output"]]["sum"])sample = head_sample(traces, RATIO)full_cost = sum((t.cost for t in traces), Decimal(0))print(f"messages kept at ratio {RATIO}, of {len(traces)}:", fmt_int(len(sample)))tokens, tokens_interval = estimate_total([t.tokens for t in sample], RATIO)
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의 10% 헤드 표본에서 시작한다. 이 표본은 그날 메시지 중 21개를 남기며, 그 토큰에 10을 곱한다. 전체 개수는 109,807 토큰이고, 6장에서 총계를 읽는 하루의 토큰 카운터도 같은 값인 109,807로 합산된다.

표본 하나는 추정치 하나를 주며, 구간은 표본을 뽑은 방식을 고려할 때 하루의 전체 개수가 어디에 놓일 수 있는지를 보여 준다. 이 구간은 표본 자체의 표준오차로 만든 것이며, 7장의 부트스트랩 구간이 아니다. 이 표본 하나에서 얻은 토큰 추정치는 98,090 토큰이다.

95% 구간은 전체 개수의 38.7%에서 140.0%까지이며, 이는 행동의 근거로 삼기에는 너무 넓다. 메시지 21개의 표본으로는 총계가 그 범위 어디에든 놓일 수 있다.

구간은 표기된 수준에도 못 미친다. 같은 날을 독립적으로 뽑은 표본 2,000개 가운데 1,843개의 구간만 전체 개수를 포함하며, 구간이 목표로 하는 값은 95%이다.

비용 추정은 같은 표본에 대한 별도의 합이다. 추정 비용은 $0.005524이고, 책의 표 book-2026-11-02로 가격을 매긴 그날의 전체 비용은 $0.007563이다.

그 구간은 전체 비용의 29.6%에서 116.5%까지이며, 같은 표본 중 1,854개가 이를 포함한다.

비율을 바꾸면 오차가 얼마나 많이 남기느냐에 따라 어떻게 달라지는지 알 수 있다.

figure-sampling-error-by-ratio.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 the error of a head sample's estimate of baseline day 1's total tokens against the sampling ratio, with the 95 percentinterval (chapter 11, `estimating-totals-from-a-sample`). The interval narrows as the ratio rises, and at ratio 1.0 every messageis kept, so the interval has no width. The points the prose names are printed, so a reader can read them off the lines."""import mathfrom lib.dayrun import run_day_tracedfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_sharefrom lib.sampling import estimate_total, head_sample, message_traces, only_messagesMODEL = "Qwen3-4B-Instruct-2507"DAY = "2026-12-08"RATIOS = (0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 1.0)traces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))full = sum(t.tokens for t in traces)points = []                                         # (ratio, estimate share, interval low share, interval high share)for ratio in RATIOS:    sample = head_sample(traces, ratio)    estimate, (low, high) = estimate_total([t.tokens for t in sample], ratio)    points.append((ratio, 100 * estimate / full, 100 * low / full, 100 * high / full))    if ratio in (0.01, 0.1, 0.5):        print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(sample)))        print(f"estimate as a share of the full count, ratio {ratio}:", fmt_share(estimate, full))        print(f"interval low end as a share of the full count, ratio {ratio}:", fmt_share(low, full))        print(f"interval high end as a share of the full count, ratio {ratio}:", fmt_share(high, full))print("full count of tokens, all messages:", fmt_int(full))xs, estimate_share, low, high = zip(*points)fig, ax = new_figure(height=2.8)ax.fill_between(xs, low, high, color=MUTED, alpha=0.35, linewidth=0, label="95% interval")ax.plot(xs, estimate_share, color=ACCENT, linewidth=1.8, marker="o", markersize=3, label="estimate, head sample")ax.axhline(100, color=INK, linewidth=1, linestyle=":", label="full count")ax.set_xscale("log")ax.set_xticks(RATIOS, [f"{r:g}" for r in RATIOS])ax.set_xlabel("sampling ratio (log scale)")ax.set_ylabel("estimate, % of full count")bottom, top = float(min(low)), float(max(high))      # the axis starts at the lowest interval end, not at zeropad = 0.1 * (top - bottom)ax.set_ylim(bottom - pad, top + 2 * pad)            # headroom above the widest interval, where the legend sitsax.legend(loc="upper right", ncol=3, frameon=False)save(fig, "sampling-error-by-ratio")assert all(math.isclose(p[1], 100) for p in points if p[0] == 1.0)   # at ratio 1 every message is kept, so no errorassert all(math.isclose(p[2], p[3]) for p in points if p[0] == 1.0)  # and the interval has no width
출력python figure-sampling-error-by-ratio.py
messages kept at ratio 0.01, of 200: 5
estimate as a share of the full count, ratio 0.01: 251.5%
interval low end as a share of the full count, ratio 0.01: -4.4%
interval high end as a share of the full count, ratio 0.01: 507.5%
messages kept at ratio 0.1, of 200: 21
estimate as a share of the full count, ratio 0.1: 89.3%
interval low end as a share of the full count, ratio 0.1: 38.7%
interval high end as a share of the full count, ratio 0.1: 140.0%
messages kept at ratio 0.5, of 200: 96
estimate as a share of the full count, ratio 0.5: 97.5%
interval low end as a share of the full count, ratio 0.5: 79.4%
interval high end as a share of the full count, ratio 0.5: 115.5%
full count of tokens, all messages: 109,807
figure: figures/sampling-error-by-ratio.svg

그림 11.1은 같은 추정치를 여덟 가지 비율로 그린 것이며, 비율이 1.0에 이르면 띠가 닫힌다. 왼쪽 끝에서는 메시지 5개가 남고, 추정치는 전체 개수의 251.5%이다. 구간은 -4.4%에서 507.5%까지이므로 아래쪽 끝이 0 아래로 내려가는데, 남은 트레이스가 너무 적어 정규 근사가 맞지 않기 때문이다.

0.1에서는 메시지 21개가 남고, 추정치는 전체 개수의 89.3%이며, 구간은 38.7%에서 140.0%까지이다.

비율 0.5에서는 메시지 96개가 남고, 추정치는 전체 개수의 97.5%이며, 구간은 79.4%에서 115.5%까지이다. 비율 1.0에서는 모든 메시지가 남으므로 추정치가 정확하고 구간의 너비가 없으며, 예제가 이를 단언한다.

0.010.020.050.10.20.30.51sampling ratio (log scale)0100200300400500600estimate, % of full count95% intervalestimate, head samplefull count
그림 11.1 여덟 가지 샘플링 비율에서 헤드 표본의 토큰 추정치를 전체 개수 대비 비율로 나타내고 95% 구간을 함께 표시한 그림

이 구간은 이 하루에 대한 샘플링의 우연을 측정한다. 다른 날에도 같은 총계가 나오는지는 다른 질문이며, 이 구간은 그에 답하지 않는다.

작업 규칙: 헤드 비율이 남긴 트레이스만 그 비율의 역수로 스케일하고, 추정치 옆에 구간을 함께 출력하며, 같은 날의 카운터 총계가 있으면 추정치를 그것과 대조한다. 표본 추정치는 카운터로 나눌 수 없는 구분에만 쓰고, 카운터가 이미 가진 총계에는 쓰지 않는다.

보존된 트레이스를 보관하는 데 드는 비용

보존 기간(retention)은 백엔드가 각 종류의 텔레메트리를 얼마나 오래 보관하는지를 뜻한다. Data Governance as Code는 플랫폼의 데이터에 대해 같은 개념, 곧 각 종류의 데이터를 얼마나 오래 보관하는지를 다룬다. 이 장은 이 개념을 텔레메트리에만 적용하며, 기간은 정하지 않는다. 기간은 사고가 난 뒤 엔지니어가 얼마나 오래전까지 거슬러 살펴봐야 하는지와 저장 비용에 달려 있고, 둘 다 백엔드를 운영하는 팀이 판단할 몫이다.

기간의 비용은 바이트로 치르므로, 보존 비율을 출력하는 테일 규칙 예제는 메시지 하나의 트레이스가 차지하는 크기도 함께 측정한다. 기준일 1일에 캡처를 끈 상태에서 메시지 하나의 스팬 행은 JSON-lines 내보내기에서 2,831바이트를 차지하며, 이 수치는 스팬 행만 센 값이다. 사고일에 보존된 트레이스는 그날 바이트의 42.6%를 차지하고, 스팬 기준으로는 42.0%를 차지한다. 여기서는 바이트가 스팬을 가깝게 따르므로, 이날에 한해서는 스팬의 보존 비율이 바이트의 보존 비율을 가늠하는 데 적절한 지표가 된다.

이 수치에는 콘텐츠가 빠져 있다. 캡처는 12장에서 켤 때까지 꺼져 있으며, 12장은 하나의 명시된 목적을 위해 캡처를 켜고 프롬프트와 응답이 같은 내보내기 경로에 얼마나 더하는지 측정한다. 따라서 이 바이트 수는 메시지 하나의 트레이스 크기에 대한 하한이다. 또한 샘플링은 어떤 스팬이 백엔드에 도달하는지만 정한다. 버려진 스팬을 프로세스가 어떻게 처리하는지는 샘플링이 정하지 않으며, 12장은 업로드 훅이 그 스팬 안의 콘텐츠를 어떻게 다루는지 보여 준다.

작업 규칙: 기간을 정하기 전에 자신의 내보내기에서 메시지당 바이트를 측정하라. 먼저 콘텐츠 없이, 그다음 보관할 계획인 콘텐츠를 포함해서 측정한다. 기간은 그것이 곱해지는 바이트 옆에 두고, 그 바이트가 무엇을 빠뜨렸는지 밝혀 둔다.

운영 환경에서 샘플링이 잘못되는 경우

헤드 비율은 정해진 비율만큼만 유지하며, 그 이상은 하지 않는다. 헤드 비율의 결정은 메시지를 읽지 않으므로, 한가한 날에도 새로운 장애가 생긴 날에도 기대 유지 비율은 같다. 테일 규칙이 유지하는 집합은 장애에 따라 움직이며, 이 장에서 둘을 함께 쓰는 이유가 여기에 있다. 헤드 샘플에도 쓸모는 있다. 헤드 샘플은 평범한 트레이스의 표본을 남기므로 일반적인 메시지를 읽어 볼 수 있고, 그 결정에는 메시지를 들여다볼 필요가 없다.

테일 규칙의 두 임계값은 이 책의 다른 부분에서 가져온 것이며, 이 값은 변한다. 지연 시간 기준선은 9장의 목표값이다. 비용이 큰 메시지의 기준선은 기준일 비용의 99번째 백분위수인데, 비용을 바꾸는 릴리스가 나가면 이 값도 함께 움직인다. 따라서 비용이 큰 메시지의 기준선은 처음 잡은 기준값을 그대로 두지 않고, 메시지 비용을 바꾸는 릴리스가 나갈 때마다 다시 읽는다.

이 규칙은 온전한 트레이스를 필요로 하며, 가지고 있는 트레이스만을 판단한다. 분리된 루트는 자기만의 트레이스를 시작하고, 규칙은 그 트레이스가 담고 있는 내용으로 판단한다. 장애가 발생한 날 예제는 이런 트레이스를 4 센다. 각각은 현재 컨텍스트가 없는 상태에서 시간 초과된 조회 뒤에 전송된 MCP notifications/cancelled 스팬이며, 각각 따로 판단된다. 해당 메시지의 나머지는 다른 트레이스에 있고, 규칙은 다른 근거로 그 트레이스를 유지하거나 버릴 수 있다. 이 검사는 이 책의 트레이스 형태만 다루며, 운영 환경에는 여기에 나타나지 않은 다른 형태가 있을 수 있다.

작업 규칙: 규칙은 한가한 날이 아니라 문제가 생긴 날에 무엇을 유지하는지로 판단하고, 임계값이 재는 대상을 바꾸는 릴리스가 나가면 각 임계값을 다시 읽는다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

The decisions this chapter made

The decisions below follow from one fact the examples show: a sampler's share is set before the message is known, so keeping the messages an engineer needs takes a rule that reads each whole trace.

  • We keep the head ratio and the tail rule together. The head sample alone kept 2 of the 17 messages with an error, and the tail rule keeps all of them.
  • The tail rule keeps errors first, then slow messages, then costly ones, under a budget of 120 spans. The budget sits above the spans the errors take, and one below them would drop an error.
  • Every service samples with parent-based sampling, and only the root's service makes the decision. The contacts server follows the assistant's flag and runs no ratio of its own.
  • Chapter 6's rule for totals holds here. A sampled estimate, printed with its interval, is for a split the counters cannot make, and it is only as good as each part's kept count.
  • The retention period belongs to the team. We measure the bytes per message first, without content, and chapter 12 adds what content costs.

Two of these are judgements that the examples cannot settle. The budget of 120 spans is one, because it is the book's number and not a measured limit. Parent-based sampling is the other. The probe checks the SDK's default sampler on one server, and it says nothing about services that this book does not run. A reader who copies the rule should measure their own day first: the spans their errors take, the bytes per message, and the messages that are costly but neither erroneous nor slow. Only then should any number in this chapter become a setting.

What the chapter learned is narrower than a rule about sampling. A head sampler's share is fixed by the trace ID before the message runs, so only a rule that reads each whole trace keeps the messages an engineer needs. A total from the kept traces is an estimate, and it carries its interval wherever it is printed.

Working rule: Before you copy a sampling setting, run its example on a day you have recorded yourself, and keep each setting with the example that tests it.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 236 of 6개 예제 in this chapter pass

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

Labs 시작

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

요금 보기

이 절 인용

형식

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

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

이 페이지의 내용

12장 중 11장: 보존할 트레이스 선택하기

  1. Head sampling decides before the trace runs
  2. 자식 스팬은 루트의 결정을 따른다
  3. Tail sampling reads the whole trace
  4. 표본으로 하루의 총계 추정하기
  5. 보존된 트레이스를 보관하는 데 드는 비용
  6. 운영 환경에서 샘플링이 잘못되는 경우
  7. The decisions this chapter made

맨 위로 돌아가기전체 장