Video in progress
In this code a span is opened by hand with the OpenTelemetry API. What mistakes does it have, and how do they show up in the trace?
public Invoice generate(long orderId) {
Span span = tracer.spanBuilder("invoice.generate").startSpan();
span.setAttribute("order.id", orderId);
Invoice invoice = repository.load(orderId); // JDBC span
pdfClient.render(invoice); // HTTP span
span.end();
return invoice;
}
The span is never end()ed (not even on an exception), makeCurrent() is never called so the HTTP and SQL spans inside don't become its children, and the exception is not recorded on the span. As a result the span is never exported or you get orphan spans, and the error shows up in the trace as "OK".
📖 Answer
There are three problems.
The most visible one: span.end() is called only on the success path. If pdfClient.render throws, the span never ends. A span that hasn't ended is not exported, so the very part that failed is missing from the trace.
Next, the span is opened but not made current. The instrumentation of repository.load and pdfClient.render takes the span in the current context as the parent, and that is still the controller span. In the trace, the JDBC and HTTP spans show up next to invoice.generate, not inside it, and you can't tell which work belongs to whom.
And the error is not recorded on the span, so the status stays UNSET. A tail-sampling rule like "keep only ERRORs" will throw such a trace away.
The correct version:
public Invoice generate(long orderId) {
Span span = tracer.spanBuilder("invoice.generate").startSpan();
try (Scope ignored = span.makeCurrent()) { // spans inside become children
span.setAttribute("order.id", orderId);
Invoice invoice = repository.load(orderId);
pdfClient.render(invoice);
return invoice;
} catch (RuntimeException e) {
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
throw e;
} finally {
span.end(); // in every case
}
}
If you use Spring Boot 3 and Micrometer, Observation.createNotStarted(...).observe(...) does all of this for you, and I only manage spans by hand when I really have to. One more note: high-cardinality values like order.id are fine as a span attribute, but they must not turn into a metric tag.
Sign up to mark studied questions and save your progress.