Observability
Telemetry for an API with one endpoint: OpenTelemetry on both stacks, a span per resolver and per source call, errors by code and deprecated-field usage as metrics, span metrics, logs found by trace id, and what to leave out.
Learning objectives
By the end of this chapter you can:
- Join a server-side trace to the callerâs own trace via the W3C
traceparentheader, with no application code on either stack. - Instrument a span per resolver and per source call (
opentelemetry-graphql-java-20.0, StrawberryâsOpenTelemetryExtension) and read the result back from Tempo by trace id. - Derive RED metrics per GraphQL operation from Tempoâs span-metrics generator instead of a per-URL histogram that canât tell
FanOutapart fromTrackCargo. - Record
graphql.errorsbyerror.codeandgraphql.field.deprecated.usagebyclient.nameas engine-level counters that no resolver can forget to call. - Decide what belongs in a span attribute or a metric label (operation name, field coordinate, error code) and what must never appear there (variable values, tokens, owner lists).
Why this matters
Every GraphQL request hits one route, and a response with errors still answers 200. A server that answers every question the same way at the HTTP layer has to be observed at the GraphQL layer: by operation, by field and by error code.
Three signals answer different questions. Traces say where the time of one request went. Metrics say how often and how slow across many requests, and which errors by code. Logs hold the detail of one failure that a response must not carry. They are useful together only if one id joins them, and the trace id is that id.
One endpoint, every operation
An access log and a latency histogram keyed by URL and status describe POST /graphql and nothing finer. A fan-out page and a single cargo lookup share the route, the status and the histogram. A response that carries SERVICE_UNAVAILABLE at one edge is a 200 like all the others, so a dashboard built from those two labels cannot tell a healthy service from one that fails a field in every response.
The operation name restores the distinction. query TrackCargo is a name a person can read in a trace and a team can own, and it comes from the clientâs own document. A span or metric keyed by operation name, and an error counted by extensions.code, sees the same traffic as separate things.
Operation names are not free. An anonymous operation is named anonymous in these metrics, and a client that omits names loses the split. The server cannot enforce naming without rejecting documents, so it belongs in the clientâs code generation or lint step.
Three signals, one collector
OpenTelemetry is the vendor-neutral API, SDK and wire protocol for telemetry. An application records traces, metrics and logs through the API and exports them over OTLP to a collector, which routes each signal to a store. The stack runs grafana/otel-lgtm, an open source image that bundles a collector with Tempo for traces, Prometheus for metrics, Loki for logs and Grafana in front of them. Both stacks export to the collector on port 4317 inside the compose network. Grafana is on 8292, Tempo on 8293, Prometheus on 8294 and Loki on 8295, apart from the usual 3000, 9090 and 3200 so the lab can run beside an observability stack of your own.
A trace belongs to the caller when the caller says so. The W3C Trace Context traceparent header carries a version, a 16-byte trace id, an 8-byte parent span id and flags. A server that honors it starts its HTTP span as a child of the callerâs span, in the callerâs trace. Both stacks do that without code, because the HTTP instrumentation reads the header. A gateway in front of several subgraphs works the same way once its OpenTelemetry integration is on (Hive Gateway has one): it propagates traceparent to each, so one trace holds the gatewayâs plan and every subgraphâs operation span.
Sampling decides which traces are kept. The lab runs parentbased_always_on, the default: keep every trace whose parent was sampled and start a sampled trace when there is no parent. A busy service samples a fraction, and the percentage is a cost choice that belongs to configuration, not to the schema.
A trace per request, a span per resolver
One request produces one tree: the HTTP server span, an operation span below it, a span for each resolver that does work, and a span for each call into a source. The HTTP span comes from the web frameworkâs instrumentation. The other layers come from the GraphQL engine, and each stack gets them from its own ready-made component.
Quarkus adds quarkus-opentelemetry for the SDK, the exporter and the HTTP span, and the OpenTelemetry projectâs opentelemetry-graphql-java-20.0, which instruments graphql-java and produces the operation span and a span per data fetcher. SmallRye fires a GraphQL.Builder event before it builds the engine, and that is the seam for appending the instrumentation:
void instrument(@Observes GraphQL.Builder builder) {
Instrumentation smallrye = builder.build().getInstrumentation();
Instrumentation spans = GraphQLTelemetry.builder(openTelemetry)
.setDataFetcherInstrumentationEnabled(true)
.setQuerySanitizationEnabled(true)
.setOperationNameInSpanNameEnabled(true)
.build()
.createInstrumentation();
builder.instrumentation(new ChainedInstrumentation(List.of(smallrye, spans, tracking)));
}
schema = strawberry.Schema(
query=Query,
mutation=Mutation,
config=StrawberryConfig(scalar_map=SCALAR_MAP),
extensions=[
partial(MaskErrors, should_mask_error=should_mask, error_message="Internal server error."),
partial(OpenTelemetryExtension, arg_filter=drop_arguments),
OperationMetrics,
],
)
SmallRye has an operation span of its own, turned off with quarkus.smallrye-graphql.tracing.enabled=false, so each request has one operation span, from the OpenTelemetry instrumentation.
Python gets the HTTP span from opentelemetry-instrument, the zero-code wrapper in the Containerfileâs entrypoint, and the rest from Strawberryâs OpenTelemetryExtension. Strawberry builds one extension per request, so the schema lists a class or a factory such as partial. The instrumentation skips introspection fields and plain attribute reads, so a trivial field costs nothing.
The stacks name their spans differently:
| Layer | Quarkus | Python |
|---|---|---|
| HTTP | POST /graphql |
POST /graphql |
| Operation | query FanOut |
GraphQL Query: FanOut |
| Resolver | itinerary, with graphql.field.path |
GraphQL Resolving: itinerary, with graphql.path |
| Source | source.call |
source.call |
The source.call span is the same on both. It wraps the one place every source read goes through, SourceCalls, and carries source.name and source.operation. On Quarkus the @WithSpan annotation creates it, and the span ends when the returned Uni completes:
@WithSpan("source.call")
public <T> Uni<T> call(
String request,
@SpanAttribute("source.name") String source,
@SpanAttribute("source.operation") String op,
String key,
Supplier<T> lookup) {
return Uni.createFrom().deferred(() -> {
long startMs = nowMs();
return afterLatency(Uni.createFrom().item(lookup))
.eventually(() -> calls.add(new SourceCall(request, source, op, key, startMs, nowMs())));
});
}
On Python the tracer from the OpenTelemetry API opens it around the lookup:
# One span per source call: the OpenTelemetry API's manual-instrumentation
# idiom. It is a child of whichever resolver span is current.
with _TRACER.start_as_current_span(
"source.call",
attributes={"source.name": source, "source.operation": op},
):
try:
await asyncio.sleep(self._latency)
return lookup()
finally:
self._calls.append(SourceCall(request, source, op, key, start_ms, _now_ms()))
Reading the trace
The trace of the batched fan-out below was read back from Tempo by the id the script sent. The query pages four cargos with each cargoâs itinerary legs and delivery. It has four levels, and each level is one tick of the DataLoader machinery.
In Grafana, Explore with the Tempo data source takes a trace id and draws the same waterfall. The slowest resolver span is rarely the answer. The question is which level the time sits in and whether the batch below it served many resolvers or one. Here every level costs one source latency, so the query is as slow as its depth: four levels, about a second. Fewer calls would not make it faster. A shallower selection would.
Both stacks produce 25 resolver spans for this query: cargos once, then node, itinerary, delivery, voyage, loadLocation and unloadLocation four times each. trackingId, number, unLocode, transportStatus, edges and legs have none. The resolver spans of a level overlap, because the resolvers start together and wait for the same batch, and end when the value arrives, 250 ms later with the latency compose sets.
The batch is the visible part. Python has six source.call spans, one per bulk call, and one is a getLocations span under eight location resolvers. Quarkus has eight, with two getLocations spans, because SmallRye batches per field and the two location fields have separate loaders. The trace shows that 8-against-6 difference without the call log.
A batched source.call serves many resolvers, so it has no single resolver to hang under. On Python it is a child of the resolver span whose turn dispatched the batch. On Quarkus it is a child of whichever context was current when the engine dispatched it. In both it belongs to the requestâs trace, descends from the HTTP span, and overlaps in time the resolvers it serves.
Errors in a trace
GHI345 is the cargo whose booking load fails. The page cargos(last: 2), named CargoPage, reaches it. The response carries SERVICE_UNAVAILABLE at the failing edge, the message booking service unavailable, and no class name or stack frame. The trace holds the rest.
On both stacks the span of the failing resolver ends in status ERROR with an exception event holding the type, message and stack trace. On Quarkus both node spans of the failed batch end in ERROR, and so does the operation span, since SmallRye fails the whole batch. On Python only the span for GHI345âs edge does. The source.call span for the bulk read is not an error on either stack: the call returned, and one key in it failed.
Metrics from spans
Tempoâs metrics generator turns the spans it receives into Prometheus series without application code: traces_spanmetrics_calls_total and a latency histogram, labelled by service, span_name, span_kind and status_code. Because operation spans carry the operation name, the series are RED metrics per operation: rate, errors and duration.
Generated metrics count spans by name and status. An error carried inside a 200 response is counted where it is recorded, by code, which is what the next two metrics do.
Metrics the spans cannot give
Two counters answer questions spans do not: how often each error code occurs, and which clients still select a deprecated field. Both are recorded once per request at the operation level, through the engineâs own hook: a graphql-java Instrumentation on Quarkus and a Strawberry SchemaExtension on Python. No resolver changes, and no field can forget to count.
graphql.errorscounts each error of an executed operation, witherror.codeandgraphql.operation.name. A document that fails to parse or validate never executes and is not counted. An error without a declared code, such as a masked one, counts asunclassified, so unexpected failures are visible as their own bucket. On Quarkus the instrumentation reads the code through the same provider that writesextensions.code, so metric and response agree.graphql.field.deprecated.usagecounts requests that select a deprecated field, once per field coordinate per request, withgraphql.field.coordinate,graphql.operation.nameandclient.name. Both stacks find the fields by walking the selected operation against the schema, with graphql-javaâsQueryTraverserand graphql-coreâsTypeInfo, so aliases, fragments and variables resolve the way execution resolves them. The client name is theX-Client-Nameheader, orunknown. It is read when execution starts, on the thread that holds the HTTP request, and carried to later callbacks in the instrumentationâs per-request state.
Prometheus translates the OTLP names: graphql.errors becomes graphql_errors_total and error.code becomes error_code. When the count for a deprecated field stays at zero for a release cycle, the field can be removed, and a breaking-change gate will then agree.
The error counter also shows the DataLoader blast radius as a number. One failed key produces one error on Python and two on Quarkus, so graphql_errors_total{error_code="SERVICE_UNAVAILABLE"} is 1 and 2 for the same request.
Logs that point at traces
A log record written while a span is current carries that spanâs trace id and span id. Both stacks export logs over OTLP: Quarkus with quarkus.otel.logs.enabled=true and Python through the logging instrumentation that opentelemetry-instrument enables. Loki stores the trace id as structured metadata, so a query can select by it:
{service_name="ch19-observability-python"} | trace_id="<the id the script sent>" | exception_type=~".*SourceUnavailable.*"
The record for CargoPage holds the exception that the response masked down to a code and a message, with its stack. An operator with the trace id from a trace or a support ticket reaches it in one query. The record does not carry the GraphQL path or a request id, so the trace id is the join key.
What to record
Telemetry leaves the process and lives longer than the request. Record the shape of a request and keep its values out. Authentication kept the token out of the context for the same reason: the subject is an identity a span may carry, and the token and owner list stay out.
Span names follow the same rule as labels. The operation span is named for the operation, query TrackCargo, not for the document, so the span metrics have one series per operation. That is why the Quarkus instrumentation is configured with the operation name in the span name: without it every operation would share the name query and the generated metrics would be as blind as the URL dashboard.
Variable values never reach a span. The operation spanâs document attribute shows query TrackCargo($id: TrackingId!) for a request sent with {"id": "ABC123"}. A literal written into the document is part of the document. The OpenTelemetry instrumentation replaces literals with ? when it records the document, giving query TrackLiteral{cargo(trackingId:?){trackingId}}, and the Python extension records the document as sent. The convention that serves both is the one clients already follow: send values as variables. Pythonâs arg_filter is drop_arguments, which returns an empty dict, so no span has a graphql.param.* attribute. The field coordinate says which resolver ran, and the argument would say for whom.
Metric labels have a stricter rule, because every distinct label value becomes its own time series in Prometheus:
| Value | As a label | Why |
|---|---|---|
| Operation name | yes | a client has tens, and they change by deployment |
| Field coordinate, error code | yes | bounded by the schema |
client.name |
with care | set by a client header; keep it to issued names and map the rest to unknown |
| Tracking id, document | no | unbounded; at most a span attribute, and generated documents multiply the series count without limit |
| Credential | never | the HTTP instrumentation records no Authorization header |
Decision
When every client writes its own selection, the only stable units are the operation name, the field coordinate and the error code. One document fans out to several owners, so a span per resolver and per source call is worth its cost: a total latency alone cannot say which source was slow. Export OpenTelemetry over OTLP, join the callerâs trace, record the operation, the field and the code and never a value, count errors by code and deprecated usage by client, and find a failureâs log record by trace id.
đ¤ Explore with your agent
âIn examples/19-observability, add a counter
graphql.operationswith the attributesgraphql.operation.nameandclient.nameto the QuarkusTelemetrybean and the PythonOperationMetricsextension, recorded once per executed operation next to graphql.errors. Follow the rule that metric labels are bounded names and never values: leave out variables, tracking ids and the document.âCheck: run
bash examples/19-observability/verify.sh, sendTrackCargotwice withX-Client-Name: web, and query Prometheus on 8294 forgraphql_operations_totalbyclient_name.
Build, run, observe
bash examples/19-observability/verify.sh runs the whole sequence on both stacks and prints PASS only when both hold. To explore by hand, start the stack. Quarkus is on 8290, Python on 8291, and the stores on 8292 to 8295.
docker compose -f examples/19-observability/compose.yaml up -d --build
TID=$(python3 -I -c 'import secrets; print(secrets.token_hex(16))')
curl -s localhost:8291/graphql -H 'Content-Type: application/json' \
-H "traceparent: 00-$TID-00f067aa0ba902b7-01" \
-d '{"query":"query TrackCargo($id: TrackingId!) { cargo(trackingId: $id) { trackingId delivery { transportStatus } } }","variables":{"id":"ABC123"}}'
{"data":{"cargo":{"trackingId":"ABC123","delivery":{"transportStatus":"ONBOARD_CARRIER"}}}}
Read the trace by the id you sent. Tempo answers a few seconds after the request:
curl -s localhost:8293/api/traces/$TID | python3 -I -c 'import json,sys; d=json.load(sys.stdin); print(sorted({s["name"] for b in d["batches"] for ss in b["scopeSpans"] for s in ss["spans"]}))'
['GraphQL Parsing', 'GraphQL Query: TrackCargo', 'GraphQL Resolving: cargo', 'GraphQL Resolving: delivery', 'GraphQL Validation', 'POST /graphql', 'POST /graphql http receive', 'POST /graphql http send', 'source.call']
Count the errors by code and the deprecated field by client from Prometheus:
curl -sG localhost:8294/api/v1/query --data-urlencode 'query=sum by (error_code) (graphql_errors_total)'
curl -sG localhost:8294/api/v1/query --data-urlencode 'query=sum by (client_name) (graphql_field_deprecated_usage_total{graphql_field_coordinate="Itinerary.finalArrivalDate"})'
Send the failing page under a trace id of its own, then find the failureâs log record by that id in Loki:
FID=$(python3 -I -c 'import secrets; print(secrets.token_hex(16))')
curl -s localhost:8291/graphql -H 'Content-Type: application/json' \
-H "traceparent: 00-$FID-00f067aa0ba902b7-01" \
-d '{"query":"query CargoPage { cargos(last: 2) { edges { node { trackingId } } } }"}'
curl -sG localhost:8295/loki/api/v1/query_range \
--data-urlencode "query={service_name=\"ch19-observability-python\"} | trace_id=\"$FID\""
Stop the stack when done:
docker compose -f examples/19-observability/compose.yaml down -v
The table lists what verify.sh asserts on each stack.
| Check | Quarkus | Python |
|---|---|---|
FanOut data and source calls |
DataLoader batchingâs data, 8 calls | DataLoader batchingâs data, 6 calls |
| HTTP span | one POST /graphql, child of the callerâs span |
the same |
| operation span | one query FanOut, descends from the HTTP span |
one GraphQL Query: FanOut |
| resolver spans | cargos 1; node, itinerary, delivery, voyage, loadLocation, unloadLocation 4 each; all descend from the operation span |
the same, named GraphQL Resolving: <field> |
| trivial fields | no span for trackingId, edges, legs, number, unLocode, transportStatus |
the same |
source.call spans |
8, equal to the call log; 2 for getLocations |
6; 1 for getLocations |
TrackCargo |
ONBOARD_CARRIER; the document attribute lacks ABC123; no graphql.param.* |
the same |
TrackLiteral |
the document attribute is query TrackLiteral{cargo(trackingId:?){trackingId}} |
the document is recorded as sent |
CargoPage |
SERVICE_UNAVAILABLE at the edge; both node spans and the operation span in ERROR; no class name or frame in the response |
the edgeâs node span in ERROR, the other UNSET |
| span metrics | 3 calls and a latency count of 3 for query TrackCargo |
the same for GraphQL Query: TrackCargo |
graphql_errors_total |
SERVICE_UNAVAILABLE on CargoPage: 2 |
1 |
graphql_field_deprecated_usage_total |
Itinerary.finalArrivalDate: legacy-app 2, unknown 1, total 3 |
the same |
| log record | found by the trace id, exception type and message | the same |
| schema | conforms; finalArrivalDate deprecated; only Subscription unserved |
the same |
- Send
TrackCargowith the id as a literal in the document instead of a variable: Quarkus records?in its place, and Python records the document as sent. - Run without a collector: set
OTEL_SDK_DISABLED=truefor Python andQUARKUS_OTEL_SDK_DISABLED=truefor Quarkus. The other examples in the series keep telemetry off by default and add the collector withcompose.observability.yaml; here the collector is a default service and the apps wait for it to be healthy.
For deeper coverage
- Charity Majors, Liz Fong-Jones & George Miranda, Observability Engineering (OâReilly, 2022): the three-signal model (traces, metrics, logs) for a single-route API.
- Cloud Native Design Patterns, chapter âObservabilityâ: the broader tracing, metrics and log-correlation patterns, applied here to a GraphQL engine.
- W3C Trace Context recommendation: the
traceparentheader that joins traces. - OpenTelemetry specificationâs âTrace Contextâ overview and its semantic conventions for GraphQL spans (
graphql.operation.name,graphql.operation.type,graphql.document). - Grafana Tempo documentation, âMetrics-generatorâ: the span-metrics mechanism behind the RED metrics.
- Quarkus guides âUsing OpenTelemetryâ, âUsing OpenTelemetry Tracingâ and âUsing OpenTelemetry Metricsâ, and the OpenTelemetry Java instrumentationâs graphql-java library page.
- Strawberryâs OpenTelemetry extension page and the OpenTelemetry Python zero-code instrumentation page.