Sub topic 6
Correlating calls with request IDs
This chapter assumes you know basic Python, have called an LLM API, and understand log levels and JSON logging. You should also have seen the metadata-first wrapper from the earlier chapters.
Why one ID per call is not enough
A single user action often triggers several LLM calls. A support bot might classify the message, retrieve documents, draft a reply, and then run a safety check. Each call writes its own log record. If the records share no identifier, you cannot tell which ones belong together. Without that link you end up reading prompts to guess the connection, and that pushes you toward logging content you would rather not store.
Correlation IDs solve this. They let you follow a request through your logs using only metadata.
Two kinds of ID
| ID | Scope | Created | Purpose |
|---|---|---|---|
| `request_id` | One LLM call | Inside the wrapper | Find one record, match a provider error to your log |
| `trace_id` | One user action or job | At the edge (HTTP handler, queue consumer) | Group every call and log line from that action |
The wrapper from the previous chapters already creates a request_id per call. A trace_id must come from outside the wrapper, because the wrapper does not know what started the work.
Carrying the trace ID with contextvars
Passing trace_id through every function signature is tedious and easy to forget. Python's contextvars module stores a value per task or thread of execution. It works with asyncio, where a plain global would mix up concurrent requests.
import contextvars
import json
import logging
import uuid
logger = logging.getLogger("llm")
trace_id_var = contextvars.ContextVar("trace_id", default=None)
def start_trace(incoming: str | None = None) -> str:
"""Call once at the edge. Reuses an upstream ID only if it looks safe."""
candidate = incoming if incoming and len(incoming) <= 64 and incoming.isalnum() else None
trace_id = candidate or uuid.uuid4().hex
trace_id_var.set(trace_id)
return trace_id
def log_call(model: str, status: str) -> None:
record = {
"event": "llm_call",
"request_id": uuid.uuid4().hex,
"trace_id": trace_id_var.get(),
"model": model,
"status": status,
}
logger.info(json.dumps(record))
logging.basicConfig(level=logging.INFO, format="%(message)s")
start_trace()
log_call("example-model", "ok")
log_call("example-model", "error")Both records print the same trace_id and different request_id values. In the real wrapper, read trace_id_var.get() when you build the record, as shown above.
Choosing and accepting IDs
- Generate IDs randomly, for example with
uuid.uuid4().hex. Do not build them from user emails, names, or prompt text. An ID derived from personal data is personal data. - Treat an incoming ID, such as an
X-Request-IDheader, as untrusted input. It could contain newlines or huge strings. Thestart_tracefunction above accepts only short alphanumeric values and otherwise makes a new one. - Log IDs as fields in the JSON record, not by string concatenation. JSON escaping then protects the log format.
Pass the ID onward
Correlation works across services only if each service forwards the trace ID. Send it in a header on outgoing calls to your own services. Some LLM providers return their own request ID in a response header. Log that value as provider_request_id. Support teams at the provider can use it to look up a failed call, which is far better than sending them your prompt.
Common errors
- Setting the trace ID in one thread or task and reading it in another. A new thread does not inherit the value unless you copy the context.
- Never calling
start_trace, which leavestrace_idasnullin every record. Alert on a high share of null values. - Reusing one
request_idfor retries. Give each attempt its ownrequest_idand keep one sharedtrace_id, so you can count retries.
Exercise
A retry loop calls the model three times after timeouts. Which IDs should be the same across the three log records, and which should differ? Why does an ID built from a hash of the user's email fail as a trace ID?
Show answer
The traceid stays the same, since all attempts belong to one user action. The requestid differs for each attempt, so each attempt can be found and counted. An ID derived from the email is personal data, can be reversed by guessing common emails, and would link different actions by the same user, so IDs should be random.