Observability at scale: sampling, cardinality and telemetry cost
Keep SLO signals complete while the rest of the telemetry is sampled: compare head and tail trace sampling on seeded synthetic traces, count the series a histogram exposes with the Prometheus Python client, and build a daily telemetry budget for logs, traces and metrics.
Contentsand lesson path
On this page
- Why it matters
- Keep the SLO signals complete and cheap
- Traces: head and tail sampling
- Metric cardinality: count the series before they cost you
- A daily telemetry budget
- Check your understanding
- Apply it
- Review prompt
Lessons of Availability & Disaster Recovery
- Availability math: nines, dependencies and redundancy Worked example · 25 min
- Redundancy, failover and hidden single points of failure Concept · 20 min
- Multi-region designs, deployment stamps and their consistency cost Concept · 20 min
- RTO, RPO and choosing a recovery strategy Concept · 20 min
- Observability at scale: sampling, cardinality and telemetry cost Concept · 20 min
- Availability design check Knowledge check · 8 questions
What you will learn
- Plan telemetry that stays useful and affordable at high volume: SLO-based alerting, trace sampling, metric cardinality and log volume budgets.
01. Why it matters
Suppose an API serves 12,000 requests a second on average, and every request writes two log lines and nine trace spans. The budget script later in this lesson puts that at about 726 GB of logs and 5.6 TB of traces a day. Depending on your vendor, storing all of it can cost more than the servers that produce it.
Cutting blindly is risky too. Availability needs two things from telemetry: to notice quickly that users are failing, and to find the cause while the error budget burns. Which telemetry must stay complete for the first job, which can be sampled for the second, and what does the rest cost? It assumes you know SLOs and burn-rate alerts from SLOs, black-box probes and alerts; designing the platform that stores the data is the job of telemetry platform design.
02. Keep the SLO signals complete and cheap
The signals behind an availability SLO are counts: requests, and requests that failed. Count them in the service with metrics counters before any sampling happens. A counter is one time series per label set whether it counts ten requests a second or ten thousand, so it sees every request at a cost that does not grow with traffic. Multi-window burn-rate alerts run on those counters: they page when the budget burns fast over both a long window, proving the loss matters, and a short one, proving it is still happening.
Two consequences follow. Never compute an SLI from sampled traces or logs unless you weight each kept item by how often it was kept; the next section shows how wrong the shortcut is. And alert when the counters stop arriving, because a missing signal looks like a perfect one.
Counting has its own limit at low traffic. The Google SRE workbook gives the example of a service with 10 requests an hour: one failure is a 10% error rate, a burn rate of 1,000 against a 99.9% SLO, and pages at once. Its remedies include synthetic traffic, combining small services into one for monitoring, client retries, and a lower target or longer window, which is a product decision.
03. Traces: head and tail sampling
A trace records one request's path through the services as a tree of spans. Sampling keeps some traces whole and drops the rest, in one of two ways.
- Head sampling decides as early as possible, usually when the root span starts. An SDK sampler decides from a hash of the trace ID, so every service reaches the same decision (the specification calls the classic one
TraceIdRatioBasedand is replacing it with a composableProbabilitySampler), and aParentBasedwrapper makes child spans follow their parent. It is cheap, but it decides before anyone knows whether the request will fail. - Tail sampling decides after the trace is complete, so it can keep every trace with an error, every slow one, and a small share of the rest. The price is state. In the OpenTelemetry Collector's tail sampling processor (beta for traces in late 2026), all spans of one trace must reach the same collector instance, so the README recommends a first layer of collectors with the load-balancing exporter, which sends all spans of a trace to the same sampler. The processor holds spans in memory while it waits, 30 seconds by default (
decision_wait) for up to 50,000 traces (num_traces), and spans arriving after the decision can be sampled differently from the rest of their trace.
The two can combine: head sampling protects the pipeline from the busiest services, tail sampling then chooses what to keep. The script compares them on 200,000 synthetic traces with 0.4% errors.
"""Head versus tail sampling on synthetic traces (fixed seed)."""
import random
rng = random.Random(2026)
N = 200_000
ERROR_RATE = 0.004
traces = []
for _ in range(N):
error = rng.random() < ERROR_RATE
latency = rng.lognormvariate(-2.3, 0.6) * (8 if error else 1) # seconds
traces.append((error, latency))
errors = sum(e for e, _ in traces)
slow = sum(1 for _, lat in traces if lat > 1.0)
print(f"{N:,} traces: {errors} with errors, {slow} slower than 1 s")
# Head sampling: decide at the root, before the outcome is known.
head = [t for t in traces if rng.random() < 0.01]
print(f"head 1%: kept {len(head):,}, errors {sum(e for e, _ in head)}")
# Tail sampling: decide after the trace ends. Keep all errors and slow traces,
# plus 1% of the rest. Remember each kept trace's weight (1 / probability).
tail = []
for error, latency in traces:
if error or latency > 1.0:
tail.append((error, 1))
elif rng.random() < 0.01:
tail.append((error, 100))
kept_errors = sum(e for e, _ in tail)
print(f"tail policy: kept {len(tail):,}, errors {kept_errors}")
print(f"\ntrue error rate: {errors / N:.3%}")
print(f"error rate of kept traces: {kept_errors / len(tail):.3%}")
print(f"weighted by 1/probability: "
f"{sum(e * w for e, w in tail) / sum(w for _, w in tail):.3%}")200,000 traces: 827 with errors, 317 slower than 1 s
head 1%: kept 1,936, errors 5
tail policy: kept 2,725, errors 827
true error rate: 0.413%
error rate of kept traces: 30.349%
weighted by 1/probability: 0.437%Head sampling at 1% kept 1,936 traces but only 5 of the 827 failed requests: almost nothing to debug an incident with. The tail policy kept 2,725 traces, not many more, and all 827 errors. Now the last three lines: among the kept traces, 30% have errors, against a true rate of 0.41%, because errors were kept a hundred times more often than successes. Weighting each kept trace by 1 / probability brings the estimate back to 0.44%. Any count taken from sampled data needs those weights, which is why the SLO comes from counters.
Sampling is not always worth it. The OpenTelemetry docs suggest not sampling when you generate very little data (tens of small traces a second or fewer), when you only use the data in aggregate and can pre-aggregate it, or when rules forbid dropping data and you cannot route it to cheap storage instead.
04. Metric cardinality: count the series before they cost you
Metrics stay cheap only while the number of time series stays bounded. In Prometheus, every unique combination of label values is a separate series, and its documentation warns against labels with many values, such as user IDs or email addresses. A classic histogram multiplies the count again: it exposes one _bucket series per bucket bound (the +Inf bucket included), plus _sum and _count. The script below counts what the official Python client (prometheus-client 0.26.0, installed with pip install prometheus-client==0.26.0) actually exposes. It turns off the client's extra _created series so the output matches the Prometheus documentation.
"""Count the time series one latency histogram exposes for a set of label values."""
from itertools import product
from prometheus_client import CollectorRegistry, Histogram, generate_latest
from prometheus_client import disable_created_metrics
disable_created_metrics() # keep only _bucket, _sum and _count, as in Prometheus docs
BUCKETS = (0.05, 0.1, 0.25, 0.5, 1, 2.5, 5) # 7 bounds + the +Inf bucket = 8
def exposed_series(labels):
registry = CollectorRegistry()
hist = Histogram("http_request_duration_seconds", "Request latency",
list(labels), buckets=BUCKETS, registry=registry)
for values in product(*labels.values()): # every combination occurs once
hist.labels(*values).observe(0.2)
text = generate_latest(registry).decode()
return sum(1 for line in text.splitlines() if not line.startswith("#"))
base = {
"method": ["GET", "POST", "PUT", "DELETE"],
"route": [f"/api/r{i}" for i in range(20)],
"status_class": ["2xx", "3xx", "4xx", "5xx"],
}
print("per label set:", exposed_series({"method": ["GET"]}), "series")
print("method x route x status_class:", exposed_series(base))
with_region = {**base, "region": ["a", "b", "c"]}
print("... plus region (3 values):", exposed_series(with_region))
per_set = len(BUCKETS) + 1 + 2 # buckets incl. +Inf, then _sum and _count
for extra, values in (("pod", 60), ("customer_id", 50_000)):
print(f"... plus {extra} ({values:,} values), by formula: "
f"{4 * 20 * 4 * values * per_set:,}")per label set: 10 series
method x route x status_class: 3200
... plus region (3 values): 9600
... plus pod (60 values), by formula: 192,000
... plus customer_id (50,000 values), by formula: 160,000,000Each label set costs 10 series: 8 buckets, a sum and a count. Four methods × 20 routes × 4 status classes is 320 label sets, so 3,200 series, and a 3-value region label triples that. Labels multiply; they do not add. A pod label with 60 values makes 192,000 series, and pod names change at every deploy, so each deploy adds a fresh set while the old ones linger until they age out. A customer_id label would need 160 million. The product is the worst case: only combinations that occur create series, so a new route quietly raises the count later.
The rule of thumb: a label is safe when its values are few and known in advance (method, route template, status class, region). Identifiers of users, customers, requests or sessions belong in traces and logs, where one record per request is expected. Set a series budget per service and check it in review; enforcing limits at ingestion is a platform concern covered in telemetry platform design. Prometheus also offers native histograms, whose samples each carry all the buckets, so one label set is one series; check that your client library and server support them first.
05. A daily telemetry budget
The script prices logs and traces per ingested GB and metrics per active series, at assumed rates; check which unit your own vendor or platform bills by. The metrics size uses the 1 to 2 bytes per stored sample that Prometheus documents for its own disk, not for what is sent over the network.
"""A daily telemetry budget for one service. Every input is an assumption."""
RPS = 12_000 # average requests per second
ERROR_RATE = 0.003
LOG_LINES, LOG_BYTES = 2, 350 # per request, uncompressed
SPANS, SPAN_BYTES = 9, 600 # per trace, uncompressed
SERIES, SCRAPE_S, BYTES_PER_SAMPLE = 40_000, 15, 2 # metrics, Prometheus disk
PRICE_PER_GB = 0.50 # assumed price per ingested GB of logs or traces
PRICE_PER_1K_SERIES = 2.00 # assumed monthly price per 1,000 active series
DAY = 86_400
GB = 1e9
def logs_gb(keep_ok_share):
per_req = LOG_LINES * LOG_BYTES
kept = RPS * ((1 - ERROR_RATE) * keep_ok_share + ERROR_RATE)
return kept * per_req * DAY / GB
def traces_gb(kept_share):
return RPS * kept_share * SPANS * SPAN_BYTES * DAY / GB
print("logs and traces: GB ingested per day, priced per GB")
rows = {
"logs, every request": logs_gb(1.0),
"logs, 5% of OK + all errors": logs_gb(0.05),
"traces, every request": traces_gb(1.0),
"traces, 1% + all errors": traces_gb(0.01 + ERROR_RATE),
}
for name, gb in rows.items():
print(f" {name:<28}{gb:>8.1f} GB/day {gb * 30 * PRICE_PER_GB:>9,.0f} per month")
print("metrics: priced per active series, not per byte")
stored_gb = SERIES * DAY / SCRAPE_S * BYTES_PER_SAMPLE / GB
print(f" {SERIES:,} series: {stored_gb:.1f} GB/day on a Prometheus disk, "
f"{SERIES / 1000 * PRICE_PER_1K_SERIES:,.0f} per month")logs and traces: GB ingested per day, priced per GB
logs, every request 725.8 GB/day 10,886 per month
logs, 5% of OK + all errors 38.4 GB/day 575 per month
traces, every request 5598.7 GB/day 83,981 per month
traces, 1% + all errors 72.8 GB/day 1,092 per month
metrics: priced per active series, not per byte
40,000 series: 0.5 GB/day on a Prometheus disk, 80 per monthLogs and traces scale with traffic; metrics scale with series. If you change the request rate from 12,000 to 24,000 a second, the log and trace lines double while the metrics line does not move, as long as no label grows with traffic. Keeping all errors and 5% of successful requests cuts logs from about 726 to 38 GB a day; keeping errors plus 1% of traces cuts 5.6 TB to 73 GB. Other levers: no debug logs in production, none for health checks, short structured lines, and raw data kept for days while aggregates live longer.
Write the result down as a budget per service, for example 50 GB of logs and 100,000 series, and alert when a service exceeds it, so growth becomes a decision, not a surprise.
Cuts have limits. During an incident you may raise sampling for the affected service. Audit and security logs that rules require should not be sampled at all. And rare but important paths, such as a payment refund handled a few times a day, may need a policy that keeps all of their traces.
06. Check your understanding
07. Apply it
Finish the skill project with a telemetry budget for the checkout journey:
- Name the counters behind each SLI and confirm they are counted before any sampling.
- Choose a sampling design: head ratio, tail policies (errors, latency above a threshold, a baseline share) and the collector layout they need.
- List the labels on your main latency histogram, compute its series count, and set a series limit per service.
- Adapt
telemetry_budget.pyto your traffic and write the daily log, trace and metrics budget. - Inject the region or DNS failure from earlier lessons: does the telemetry pipeline itself survive it, and would you still see the SLO burn?
08. Review prompt
Without looking back: explain why SLIs should come from counters taken before sampling, and what goes wrong at very low traffic. Contrast head and tail sampling: when each decides, what each can keep, and what tail sampling needs in the collector layer. Show how to count the series of a classic histogram from its buckets and label values, and name three ways to cut log volume without losing error logs.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.