High-cardinality, wide events and the Honeycomb model
One rich event per request per service, every field you might ask about, aggregated when you ask rather than when you write: answer 'which version, which customers, which order size' with one query
After a release, gateway checkout p99 is 40 ms on version 1.0.0 and 55 ms on 1.1.0, over a few thousand requests each. 1% of requests come from VIP users whose orders are three times larger. What can you conclude about VIP users on 1.1.0?
The previous chapters built three signals and a way to correlate them. Each was shaped by its cost. Metrics are cheap because they pre-aggregate, and pre-aggregation throws away every dimension you did not choose in advance. Traces keep the request’s structure, but their query languages are built for finding traces, not for computing p99 over a slice of millions of them. Logs keep detail but scatter one request’s facts across many lines.
The wide event is the response: one record per request per service, carrying every fact about that request you might later want to slice by, with aggregation done at query time. It is the canonical log line from the structured-logging chapter taken seriously. This chapter is about what goes in it, where to store it, and how to ask it a question no dashboard anticipated.
Cardinality and dimensionality
Two words do most of the work here, and they are often confused.
Cardinality is the number of distinct values a field takes. vip has 2. service.version has a handful. items in the demo app has about ten. user has 1,000 and in a real shop millions. order_id and trace_id are unique per request.
Dimensionality is the number of fields an event carries. The demo app’s request log line has four (method, route, status, ms). Stripe’s canonical lines carry dozens. Wide-event advocates aim for hundreds.
Metrics punish both. A Prometheus series is one combination of label values, and a histogram is one series per bucket per combination. The demo’s http_request_duration_seconds has 13 buckets plus +Inf, _sum and _count, so 16 series per combination. Add service_version (2 values during a release), vip (2) and an items_bucket (5): 16 × 2 × 2 × 5 = 320 series per route and status, which is fine. Add user (1,000): 320,000 series for one histogram on one service. The metrics-101 chapter showed what that does to Prometheus. The cost of a metric grows with the product of its label cardinalities and not at all with traffic, which is exactly backwards for a high-cardinality question.
A wide event costs the opposite way: one record per request, whatever it contains. A thousand users or a million cost the same per event. Adding a field costs bytes, not a multiplication. You pay by volume, and you can choose to answer any combination of fields later, including ones nobody thought of when the event was designed.
The useful questions in a debugging session are almost all high-cardinality, high-dimensionality questions. Which customer? Which build? Which shard? Which feature flag combination? Which order size on which version? Each of those is a group-by over fields a metric could not afford.
The Honeycomb model
Charity Majors and the Honeycomb team gave this approach its current shape, drawing on Facebook’s Scuba. The model has four parts.
- Emit one wide event per unit of work per service. For an HTTP service, one per request, written when the request ends, carrying everything known about it: identity (user, tenant, plan), request (route, parameters, sizes), build (version, commit, feature flags), downstream work (time in the database, number of queries, cache hits), outcome (status, error class), and the trace id and span id.
- Store raw events in a column store. No pre-aggregation. A columnar layout means a query that touches four fields reads four columns, however many hundreds the events carry.
- Aggregate at read time.
p99(duration) GROUP BY version, vip, items_bucketover the last hour is a scan of three or four columns. Any field can be a group-by or a filter, and the question decides which. - Let the tool find the dimension. Honeycomb’s BubbleUp takes a selection (draw a box around the slow region of a latency heatmap) and compares it with everything else, field by field: for each field, which values are over-represented among the selected events. It is the automation of the loop you would otherwise do by hand, trying one group-by after another until a field separates slow from fast.
In Honeycomb a trace is a set of wide events that share a trace id, each with a duration and a parent id. The span and the event are the same record. That is why OpenTelemetry spans with rich attributes and canonical log lines carrying the trace id end up interchangeable for these questions: both are wide events, one with tree structure.
Sampling fits the model in its own way. Each kept event carries a sample rate (keep 1 in 20 healthy requests, every error), and the query engine weights each event by it, so counts and percentiles stay unbiased estimates. A sample rate field on every event is cheap and lets you drop most of the boring volume without losing the ability to count.
Building on the canonical line
The demo app already writes one line per request per service from the request_log middleware in services/common/app.py. The structured-logging chapter turned it into a canonical line: msg="canonical", the HTTP fields, a duration string with a unit, and a request.state.fields dict that handlers fill. Over OTLP, every field becomes structured metadata in Loki with dots turned to underscores (http.route to http_route), and the line itself is the message canonical.
To make that line a wide event, three things change.
Handlers add fields as soon as they know them, not at the end. If the gateway records user, items and vip before calling orders, a request that fails in orders still carries them. A field added only on the happy path vanishes from exactly the events you need.
The middleware adds derived fields once. An items_bucket (1, 2-3, 4-7, 8-15, 16+) turns a continuous field into a small set you can group by. Keep the raw items too: the bucket is for grouping, the raw value for filtering. Computing the bucket in one place in common/app.py keeps every service’s buckets identical, which matters when you compare across services. LogQL can compute buckets at query time with label_format, but its template functions have no numeric comparison, so the result is unreadable; do it at write time.
Every service writes its own event. The gateway knows the user and the overall latency. Orders knows the item count, the amount and the number of statements. Payments knows whether the charge was a replay. Each writes the fields it has, and the trace id joins them when you need more than one service’s view.
The fields that earn their place in the demo app:
| service | fields | why you will group or filter by it |
|---|---|---|
| all | http_route, http_response_status_code, duration, service_version (stream label), trace_id |
the RED questions, and the pivot to the trace |
| gateway | user, vip, items, items_bucket, order_id, orders_ms, upstream_status |
who, how big, how much of the time was downstream |
| orders | user, items, items_bucket, amount_cents, order_id, n_plus_one |
which orders, and whether a fault flag was on |
| payments | order_id, amount_cents, cached |
replays versus real charges |
What does not belong: the request body, the card holder’s name (the PII fault from the structured-logging chapter), anything multi-kilobyte, and anything already a stream label. Wide is not the same as dumped.
Asking wide events questions in Loki
The lab stack has no column store. It has Loki 3.4.2, which keeps OTLP log attributes as structured metadata: key-value pairs stored with each line, not part of the stream’s identity, and available after the stream selector as if they were labels. That gives you most of the Honeycomb query model in LogQL:
quantile_over_time(0.9,
{service_name="gateway"} |= "canonical" | http_route="/checkout"
| unwrap duration(duration) | __error__="" [20m]
) by (service_version, vip, items_bucket)
Read it left to right. The stream selector picks gateway’s streams (one per service_version, since that is an indexed resource attribute). The line filter |= "canonical" keeps the wide events. The label filter on http_route uses structured metadata without a parser. unwrap duration(duration) turns the string "212.3ms" into seconds as the sample value; __error__="" discards any line whose value did not convert. quantile_over_time computes the 90th percentile over each 20-minute window, and by (...) groups by a stream label and two structured-metadata fields at once. One query, and the answer is a small table.
The other questions you will want:
sum by (items_bucket) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" | duration > 150ms [20m]))
/
sum by (items_bucket) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" [20m]))
That is a manual BubbleUp for one field: the share of each bucket’s requests that are slow. Repeat it with by (vip) or by (http_response_status_code) and the field whose values separate is the one to follow. And the pivot back to individual requests is a log query, not a metric query: {service_name="gateway"} |= "canonical" | vip="true" | duration > 150ms lists the matching events, each with a trace id that opens the trace.
Where Loki stops being the right tool:
- Every query scans. Structured metadata is not indexed. A query decompresses every chunk of the selected streams in the time range and evaluates the filters line by line. Loki parallelises this by splitting the range and sharding, but the bytes read are the bytes stored for those streams. On the demo app’s few megabytes an hour that is instant. At 10,000 requests per second with 1 KB events, one service writes 36 GB an hour, and every ad hoc group-by over an hour reads all 36 GB.
- Group-bys on high-cardinality fields hit limits. A metric query returning more than
max_query_seriesseries (500 by default in 3.4) fails.by (order_id)is not a question Loki’s metric queries can answer; the log query that lists the top events is. The lab’s break shows the error. - No comparison engine. There is no BubbleUp. You write the ratio above once per field.
Do you need ClickHouse?
ClickHouse (or Honeycomb’s own store, or any column store with SQL) changes the cost of one thing: a query that touches a few fields of very wide events over a long range. It reads only the referenced columns, each compressed on its own, and it can GROUP BY user ORDER BY p99 DESC LIMIT 10 over millions of distinct users. The same question in Loki reads every byte of every line.
For the demo app, it does not earn its place. The traffic is 5 to 20 requests per second, the events are a few hundred bytes, and Loki answers the lab’s questions in well under a second. Adding ClickHouse would add a stateful service, an ingest path from the Collector (its clickhouse exporter), a schema to manage, and a second place logs live, for no question you cannot already answer. The rule of thumb that falls out of the numbers above: when the common incident query window is more than a few gigabytes per service and people wait more than a few seconds for group-bys, or when you need high-cardinality group-bys with ORDER BY ... LIMIT, a column store pays for itself. The trace storage chapter in module four puts spans in ClickHouse and measures exactly that.
The honest alternative to running one is buying one. Honeycomb has a free tier with a monthly event cap, and the OTel Collector can send the same traces to it alongside Tempo. Check the arithmetic first: the demo app at its default 5 requests per second makes ten spans per checkout, about 4.3 million spans a day, so send it for a few hours or sample. That is the cheapest way to try BubbleUp on your own data.
Where wide events go wrong
- PII by default. A wide event is the easiest place to leak a name or an email, because adding fields is encouraged. Keep an allow-list of field names per service and scrub in the Collector, as the O2 pipeline project did.
- Name drift.
user,user_id,userIdandcustomerin four services make every cross-service query wrong. Use one vocabulary: OpenTelemetry semantic conventions where they exist, a team-owned list for the rest. - Fields only on success. Covered above, and the most common mistake.
- Sampling without weights. If you drop 95% of healthy events and keep every error, a count without the sample rate overstates errors twenty-fold.
- Wide events instead of metrics for alerting. A burn-rate alert evaluated every 30 s over a log store is a scan every 30 s. Alert on cheap pre-aggregated metrics, debug with wide events. They answer different questions.
You will widen the canonical line in all three services, ship a release that regresses only some requests, and find the slice with one LogQL query. If you completed the structured-logging lab, parts of steps 2 and 3 are already in place; apply the full versions below anyway.
1. Start the stack at version 1.0.0 with more load.
cd labs/observability
printf 'OTEL_SDK_DISABLED=false\nLOG_FORMAT=json\nOTEL_SEMCONV_STABILITY_OPT_IN=http/dup\nLOADGEN_RPS=20\n' > .env
docker compose --profile telemetry up -d --build2. Make the request line a wide event. In services/common/app.py, add this function above create_app:
def items_bucket(n: int) -> str:
"""Power-of-two buckets so every service groups order sizes the same way."""
for upper, name in ((1, "1"), (3, "2-3"), (7, "4-7"), (15, "8-15")):
if n <= upper:
return name
return "16+"and replace the whole request_log middleware with:
@app.middleware("http")
async def request_log(request: Request, call_next):
start = time.perf_counter()
request.state.fields = {} # handlers add fields here as soon as they know them
status = 500
try:
response = await call_next(request)
status = response.status_code
return response
finally:
if request.url.path not in ("/health", "/metrics"):
route = getattr(request.scope.get("route"), "path", request.url.path)
fields = request.state.fields
if isinstance(fields.get("items"), int):
fields["items_bucket"] = items_bucket(fields["items"])
log.info("canonical", extra={
"http.request.method": request.method,
"http.route": route,
"http.response.status_code": status,
"duration": f"{(time.perf_counter() - start) * 1000:.1f}ms",
**fields,
})create_app, where the OpenTelemetry middleware wraps it, so the span is current and every event carries trace_id and span_id.3. Add fields where they are known. In services/gateway/app.py, import Request (from fastapi import FastAPI, Query, Request), add request: Request as the first parameter of checkout, delete the log.info("checkout done", ...) line if the structured-logging lab left one, and add, directly after effective_items = ...:
request.state.fields.update(user=user, items=effective_items, vip=vip)and directly after order_id = body.get("order_id"):
request.state.fields.update(order_id=order_id, orders_ms=ms, upstream_status=resp.status_code)In services/orders/app.py, import Request (from fastapi import FastAPI, Request), change the handler signature to async def create_order(order: OrderIn, request: Request):, and add after n_plus_one = n_plus_one_enabled():
request.state.fields.update(user=order.user, items=order.items, amount_cents=amount, n_plus_one=n_plus_one)and after span.set_attribute("order.id", order_id):
request.state.fields["order_id"] = order_idIn services/payments/app.py, import Request (from fastapi import FastAPI, HTTPException, Request), change the signature to async def charge(req: ChargeIn, request: Request):, and add after the fields = {...} line:
request.state.fields.update(order_id=req.order_id, amount_cents=req.amount, cached=False)and inside if existing:, before return result:
request.state.fields["cached"] = TrueRebuild and look at one event of each kind:
docker compose --profile telemetry up -d --build gateway orders payments
sleep 30
docker compose logs --since 20s gateway | grep '"canonical"' | tail -n 1
docker compose logs --since 20s orders | grep '"canonical"' | tail -n 1http.route, http.response.status_code, duration, user, items, vip, items_bucket, order_id, orders_ms, upstream_status, trace_id and span_id; an orders line with user, items, items_bucket, amount_cents, n_plus_one and order_id. In Grafana Explore on Loki, {service_name="gateway"} |= "canonical" shows the same fields as structured metadata, with dots turned to underscores.4. Plant a release that regresses only some requests. Release 1.1.0 adds a stock check: one query per item against order_items, which has no index on sku. The lab has one image, so the new code is gated on the version string. In services/orders/app.py, inside async with conn.transaction():, after the if n_plus_one: ... else: ... block and at the same indentation as it, add:
if os.getenv("SERVICE_VERSION") == "1.1.0":
# release 1.1.0: check stock for every item (no index on order_items.sku)
for i in range(order.items):
await conn.execute("SELECT count(*) FROM order_items WHERE sku = %s", (sku(order.user, i),))
DB_OPS.labels(operation="SELECT").inc()Give the table a realistic size, about 20 MB, so a scan costs something:
docker compose exec -T db psql -U atlas orders -c "
INSERT INTO order_items (order_id, sku, qty, unit_price_cents)
SELECT (SELECT min(id) FROM orders), 'SKU-' || lpad((g % 500)::text, 4, '0'), 0, 1000
FROM generate_series(1, 300000) g;
ANALYZE order_items;"
docker compose --profile telemetry up -d --build ordersNote the time, let 1.0.0 run for 10 more minutes, then ship 1.1.0 to all three services and let it run for 10 minutes:
date -u +%H:%M:%S
sleep 600
SERVICE_VERSION=1.1.0 docker compose --profile telemetry up -d gateway orders payments
date -u +%H:%M:%S
sleep 600INSERT 0 300000 and ANALYZE. The filler rows have qty = 0, which no real order writes, so you can remove them at the end. After the release, every new orders statement for an order runs one sequential scan per item, a few milliseconds to tens of milliseconds each depending on your machine. One-item orders gain one scan; a 15-item VIP order gains fifteen.5. Ask the aggregate first.
lq() { curl -sG localhost:3100/loki/api/v1/query --data-urlencode "query=$1" \
| jq -r '.data.result[] | "\([.metric.service_version, .metric.vip, .metric.items_bucket] | map(select(. != null)) | join(" "))\t\(.value[1])"' | sort; }
lq 'quantile_over_time(0.99, {service_name="gateway"} |= "canonical" | http_route="/checkout"
| unwrap duration(duration) | __error__="" [20m]) by (service_version)'6. Now the one query.
lq 'quantile_over_time(0.9, {service_name="gateway"} |= "canonical" | http_route="/checkout"
| unwrap duration(duration) | __error__="" [20m]) by (service_version, vip, items_bucket)'1.1.0 true 8-15, VIP orders of 9 to 15 items, is several times slower than the 1.1.0 false 1 row and many times its own 1.0.0 value. That is the escalation from the top of the chapter, found in one query with no new metric, no new label and no deploy. Run the same query in Grafana Explore as a table for a view you can share.7. Confirm it like BubbleUp, then pivot to a trace. The share of slow requests by bucket on 1.1.0, then the same by VIP:
lq 'sum by (items_bucket) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" | duration > 150ms [10m]))
/ sum by (items_bucket) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" [10m]))'
lq 'sum by (vip) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" | duration > 150ms [10m]))
/ sum by (vip) (count_over_time({service_name="gateway", service_version="1.1.0"} |= "canonical" [10m]))'Then in Grafana Explore, Loki: {service_name="gateway", service_version="1.1.0"} |= "canonical" | vip="true" | items_bucket="8-15", expand a line and follow its trace_id link to Tempo.
8-15 if your scans are slow enough to cross 150 ms; adjust the threshold to your machine’s numbers from step 6. By VIP the split is as sharp, but VIP is only a proxy: curl 'localhost:8080/checkout?user=42&items=15' is a non-VIP order of 15 items and is as slow, which the bucket predicts and the VIP flag does not. The trace has 9 to 15 SELECT spans under POST /orders, one per item, and the critical-path script from the previous chapter puts most of the time on them. Wide event to find the slice, trace to see the mechanism.by (service_version, vip, items_bucket) in step 6 with by (order_id). Loki answers with an error that the maximum of series (500) was reached for a single query, because max_query_series defaults to 500 and the window holds about 24,000 orders. Structured metadata let you store a unique field per event for free; grouping by it in a metric query is still capped. The question you meant (which orders were slowest) is a log query: {service_name="gateway"} |= "canonical" | duration > 500ms. A column store answers GROUP BY order_id ORDER BY duration DESC LIMIT 10 without the cap, which is the strongest argument for one. Reset with docker compose --profile telemetry up -d gateway orders payments (back to 1.0.0), then remove the filler rows with docker compose exec -T db psql -U atlas orders -c "DELETE FROM order_items WHERE qty = 0; VACUUM FULL order_items;". Keep the code changes: the canonical line is what later chapters query, and the 1.1.0 stock check only runs when orders is started with SERVICE_VERSION=1.1.0.Your company runs 60 services at a combined 15,000 requests per second. You have Prometheus, Loki and Tempo. You want engineers to answer 'which customer, version and region is slow' during incidents. Canonical lines average 1.2 KB. Options are on the table; pick one for the next year.
- BOOK Observability Engineering Charity Majors, Liz Fong-Jones, George Miranda, 2022
The Honeycomb model from the people who built it: why events and not metrics, how traces are events, and how a column store makes arbitrary group-bys affordable. Skip the vendor-flavoured adoption chapters on a first read. Read: chapters 5 (structured events), 6 (stitching events into traces) and 16 (efficient data storage, the column-store argument).
- PAPER Scuba: Diving into Data at Facebook Abraham et al., 2013
The system the wide-event model descends from. Shows the trade Facebook made: raw sampled events in memory, any group-by in under a second, at the cost of retention. Read: VLDB 2013: the introduction and the use-case and data-model sections; skim the architecture.
- POST Logs vs Structured Events Charity Majors, 2019
The short argument for replacing many log lines per request with one rich event per request per service. Read it for the field list and the reasoning about levels.
- POST All you need is Wide Events, not 'Metrics, Logs and Traces' Ivan Burmistrov, 2024
An engineer who used Scuba at Meta explains, with a worked investigation, why the three-pillar split is a storage artefact. A good counterweight to the course's three-signal framing.
- DOC Identify outliers with BubbleUp Honeycomb
How the selection-versus-baseline comparison works field by field. Read it to see what the lab's ratio queries are approximating by hand.
- DOC What is structured metadata (Loki) Grafana Labs
The rules for high-cardinality fields in Loki: limits per line, how to filter, and the series-limit warning for metric queries that the lab's break triggers.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.