Sub topic 13
Recording errors, retries and timeouts
This chapter assumes you can create spans with start_as_current_span, set attributes, and export traces through the SDK and Collector setup from earlier chapters. It covers how to make failures visible in a trace: which span gets the error, how to show each retry attempt, and how to tell a timeout from other failures.
Why failures need care in LLM traces
LLM calls fail often and in different ways. Providers return rate-limit errors (HTTP 429), servers return 5xx errors, networks drop connections, and requests time out. Agents add another layer: a tool can fail, and the model can respond with output your code cannot parse.
Many of these failures are handled by a retry. If the trace shows only the final success, you lose the information that the call took three attempts and 40 seconds. If the trace marks a span as an error even though a retry recovered, your error dashboards become noisy. The goal is for the trace to describe what actually happened at each level.
Span status: the rules
A span has one of three statuses: Unset, Ok and Error. Follow these rules:
- Leave the status
Unsetwhen the operation succeeded. Backends treatUnsetas success. - Set
Errorwhen the operation this span represents failed. - Avoid setting
Okunless you have a reason to override an error status. An explicitOkis final, and later code can no longer change it.
The Error status takes an optional description. Keep it short and free of user content, because the description appears in many views.
For GenAI spans, the semantic conventions also define the error.type attribute. Set it to a low-cardinality value, such as an exception class name (RateLimitError) or an HTTP status code as a string ("429"). Low cardinality matters because you will group and count by this attribute. Do not put full error messages in it.
Recording an exception
The record_exception method adds an event named exception to the span. The event carries exception.type, exception.message and exception.stacktrace. It does not change the status. You must set the status yourself.
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
def call_model(messages):
# Stand-in for a real LLM client call.
raise TimeoutError("model did not respond in 30s")
def traced_chat(messages, model="example-model"):
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model)
try:
return call_model(messages)
except Exception as exc:
span.record_exception(exc)
span.set_attribute("error.type", type(exc).__name__)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raiseRe-raise the exception after recording it. Swallowing it hides the failure from the caller, and the caller may need to retry or report it.
The start_as_current_span context manager can also record exceptions and set the error status for you. Its record_exception and set_status_on_exception parameters both default to True. Using the explicit try block, as above, is still useful when you want to add error.type or choose a different description.
Modeling retries
There are two common ways to show retries, and they answer different questions.
- One span per attempt. Each attempt is its own client span, and all attempts sit under a parent span for the logical operation. The trace shows every attempt's duration and error.
- One span with events. A single span covers the whole operation, and each failed attempt adds an event. This is lighter, but you lose per-attempt timing and attributes.
For model calls, prefer one span per attempt. Attempts differ in latency and in the error they return, and that is what you want to look at when debugging. Put a parent span around the retry loop and record the attempt number on each child.
import time
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
class RateLimitError(Exception):
pass
_calls = {"n": 0}
def call_model(messages):
# Fails twice, then succeeds, to demonstrate retries.
_calls["n"] += 1
if _calls["n"] < 3:
raise RateLimitError("429 too many requests")
return "Hello!"
def chat_with_retry(messages, model="example-model", max_attempts=3):
with tracer.start_as_current_span(f"chat_with_retry {model}") as parent:
parent.set_attribute("app.retry.max_attempts", max_attempts)
for attempt in range(1, max_attempts + 1):
with tracer.start_as_current_span(
f"chat {model}", kind=SpanKind.CLIENT
) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model)
span.set_attribute("app.retry.attempt", attempt)
try:
text = call_model(messages)
parent.set_attribute("app.retry.attempts_used", attempt)
return text
except Exception as exc:
span.record_exception(exc)
span.set_attribute("error.type", type(exc).__name__)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
if attempt == max_attempts:
parent.set_status(Status(StatusCode.ERROR, "retries exhausted"))
parent.set_attribute("app.retry.attempts_used", attempt)
raise
time.sleep(0.1 * 2 ** (attempt - 1))The names with the app. prefix are custom attributes. The GenAI conventions do not define retry attributes, so use your own namespace to avoid clashing with standard names. Pick the names once and use them everywhere.
In this example, the first two attempt spans end with Error, and the third has Unset status. The parent ends with Unset because the operation as a whole succeeded. If all attempts fail, the parent is marked Error.
The sleep happens after the attempt span closes. Backoff time then appears as a gap between sibling spans under the parent. That gap is useful: it shows how much of the total latency came from waiting rather than from the model.
Client libraries that retry internally
Many LLM SDKs retry on their own. If you wrap the SDK call in one span, you see a single long span and no detail about the internal attempts. Options:
- Disable the SDK's retries and run your own loop, as above.
- Keep the SDK's retries and record the configured maximum on the span. The slow span still tells you that something took long.
- Use an instrumentation library that traces at the HTTP layer. Each HTTP request then gets its own span.
Pick one place to retry. Retrying in both the SDK and your code multiplies attempts, and a single failure can turn into nine requests.
Timeouts
A timeout is a failure with a known cause, so mark it as one. Set error.type to a consistent value such as timeout, and record the limit you configured as an attribute (for example app.timeout_seconds). When you review a slow trace, you can then compare the span's duration with the limit.
Be clear about which timeout fired. These are different problems:
- A connect timeout means the server could not be reached.
- A read timeout means the connection was open but the response was slow.
- An overall deadline in your own code means the agent gave up on the step.
Use different error.type values or an extra attribute for each. A streaming response adds another case: the first token may arrive quickly and the stream may stall later. A span that ended with Error after a long duration and partial output looks very different from one that failed immediately.
Errors that are not exceptions
Not every failure raises. Common cases in LLM apps:
- The model returns output that fails validation, such as invalid JSON when you expected a tool argument.
- The response finishes with a reason like
length, meaning it was cut off by the token limit. - A tool returns an error result that the agent passes back to the model.
Decide whether each case is a failure of the span's own operation. A cut-off response from a successful HTTP call is usually not an error on the chat span. Record the finish reason in gen_ai.response.finish_reasons and let the code that validates the output mark its own span as Error. A tool that returns an error to the model is a failed tool span, even though the agent continues. Mark the tool span Error, and the agent span stays Unset if the agent recovers.
Errors and the parent span
Status does not propagate from child to parent. If a child fails and the parent code catches the exception, the parent stays Unset. This is correct when the error was handled. If the error was not handled, the exception propagates and the parent records it the same way.
In a trace viewer, an error deep in the tree can be easy to miss. Make the parent span carry a summary attribute when it matters, such as the retry count above, so that you can filter on the parent without opening every child.
Common mistakes
- Setting
Erroron a span that a retry recovered, which inflates error rates. - Calling
record_exceptionwithoutset_status, which leaves a span that looks healthy but carries an exception event. - Putting the full error message or user input in
error.type, which creates high-cardinality values. - Swallowing the exception after recording it, so the caller never retries.
- Retrying in both the SDK and your own loop.
- Sleeping inside the attempt span, which counts backoff as model latency.
Exercises
Exercise
A request fails twice with a 429 error and then succeeds on the third attempt. You use one span per attempt under a parent span. Which spans should have Error status, and why?
Show answer
Only the first two attempt spans should be Error, because those operations failed. The third attempt and the parent stay Unset, because the logical operation succeeded. Marking the parent as an error would count a recovered request as a failure.
Exercise
A span has an exception event with a stack trace, but your dashboard shows the span as successful. What is the most likely cause, and how do you fix it?
Show answer
The code called record_exception but never set the status. record_exception only adds an event. Call span.set_status(Status(StatusCode.ERROR, ...)) as well, or rely on start_as_current_span defaults when the exception propagates out of the with block.
Exercise
Why is sleeping for backoff outside the attempt span better than sleeping inside it?
Show answer
The attempt span should measure only the model call. Sleeping outside it keeps attempt latency accurate and shows backoff as a visible gap between sibling spans under the parent.