Sub topic 6
Correlating calls with request IDs
This chapter assumes you can call an LLM API from Python, know how logging and JSON log lines work, and have read the earlier chapters on metadata-first logging. Here you add the piece that links log lines together: a request ID.
Why one log line is not enough
A single user action often produces several LLM calls. A support chat might run a classification call, a retrieval-query rewrite, and a final answer call. A timeout in the middle can trigger a retry. If every call logs its own line with no shared key, you can't answer basic questions:
- Which calls belonged to the same user action?
- Did the slow answer come from one slow call or from three retries?
- Which log line matches the error the user reported?
A correlation ID is a short identifier written into every log line that belongs to the same unit of work. Searching your log store for that one value returns the whole story, in order.
Correlation also supports the logging policy from earlier chapters. Because you can reconstruct a failed request from metadata alone, you rarely need to turn on content logging to debug it.
The three kinds of ID
Use three separate identifiers. They answer different questions.
| ID | Created by | Scope | Answers |
|---|---|---|---|
| `request_id` | Your service, at the entry point | One inbound user action | What happened during this action? |
| `call_id` | Your LLM wrapper | One attempt against the provider | Which attempt failed or was slow? |
| `provider_request_id` | The LLM provider, returned in a response header or field | One provider-side request | What do I quote to provider support? |
Some systems also carry a trace_id from a distributed tracing system such as OpenTelemetry. If you already have one, reuse it as your request_id instead of inventing a second value. Two competing IDs for the same action defeat the purpose.
Creating and accepting IDs
Create the request ID once, at the edge of your service, and never inside the LLM wrapper. If the wrapper generated it, two calls in the same user action would get different IDs.
Callers can also send an ID in a header such as X-Request-ID. Accepting it lets you correlate across services, but it is untrusted input. A client could send a 5 MB string, a value with newlines that forges log lines, or an email address that puts personal data into every log line. So validate the value against a strict pattern and fall back to a fresh UUID if it fails.
import re
import uuid
SAFE_ID = re.compile(r"[A-Za-z0-9._-]{8,64}")
def accept_or_create_id(incoming):
"""Return the caller's ID if it looks safe, otherwise a new one."""
if incoming and SAFE_ID.fullmatch(incoming):
return incoming
return str(uuid.uuid4())
print(accept_or_create_id("req-2026-abc123"))
print(accept_or_create_id("[email protected]") != "[email protected]")
print(accept_or_create_id("abc12345\nFAKE LOG LINE") != "abc12345\nFAKE LOG LINE")The pattern rejects @, spaces, and newlines, so an email address or a forged line can't pass through as an ID.
An ID should be random or sequential. Don't build it from a user's email, name, or account number. An ID derived from personal data is personal data, and it sits in every line.
Propagating the ID without passing it everywhere
You could pass request_id as an argument through every function. That works until someone forgets. Python's contextvars module is the usual alternative. A context variable holds a value that is local to the current thread or asyncio task, so concurrent requests don't see each other's IDs.
The next example sets the ID once, then logs from a wrapper that never receives it as a parameter. It includes retries, each with its own call_id, and runs as written.
import contextvars
import json
import logging
import time
import uuid
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("llm")
request_id_var = contextvars.ContextVar("request_id", default=None)
def log_event(event, **fields):
record = {"event": event, "request_id": request_id_var.get(), **fields}
logger.info(json.dumps(record))
def call_with_retries(client_call, model, prompt, max_attempts=3):
for attempt in range(1, max_attempts + 1):
call_id = uuid.uuid4().hex[:12]
start = time.perf_counter()
try:
response = client_call(model=model, prompt=prompt)
except ConnectionError as exc:
log_event(
"llm_call",
call_id=call_id,
attempt=attempt,
status="error",
error_type=type(exc).__name__,
latency_ms=round((time.perf_counter() - start) * 1000),
)
if attempt == max_attempts:
raise
continue
log_event(
"llm_call",
call_id=call_id,
attempt=attempt,
status="ok",
response_chars=len(response),
latency_ms=round((time.perf_counter() - start) * 1000),
)
return response
attempts = {"n": 0}
def flaky_client(model, prompt):
attempts["n"] += 1
if attempts["n"] == 1:
raise ConnectionError("timeout")
return "Hello!"
request_id_var.set("req-demo-0001")
call_with_retries(flaky_client, "demo-model", "Say hello")Running it prints two JSON lines. Both show "request_id": "req-demo-0001". The first has "status": "error" and "attempt": 1. The second has "status": "ok" and "attempt": 2. A search on the request ID returns both, and the call_id tells you which line is which.
json.dumps still does the escaping here, so the log-injection protection from the structured logging chapter applies to these fields too.
Context variables across threads and tasks
A context variable follows the flow of execution, with some exceptions you need to know.
- asyncio tasks copy the current context when they are created. A task started after you set the ID sees it. Setting the ID inside a child task does not change it for the parent.
asyncio.to_threadcopies the context into the worker thread.loop.run_in_executorand a plainThreadPoolExecutor.submitdo not. Calls made that way logrequest_id: null.- Background jobs and queues lose the context entirely. Put the ID in the job payload and set it again when the worker picks the job up.
- Web frameworks that reuse worker threads can leak an ID from one request into the next if you set it and never reset it.
For the thread pool case, copy the context explicitly:
import contextvars
from concurrent.futures import ThreadPoolExecutor
request_id_var = contextvars.ContextVar("request_id", default=None)
def work():
return request_id_var.get()
request_id_var.set("req-demo-0002")
ctx = contextvars.copy_context()
with ThreadPoolExecutor() as pool:
print(pool.submit(work).result()) # None
print(pool.submit(ctx.run, work).result()) # req-demo-0002To avoid the leak between requests, keep the token that set returns and reset it when the request ends:
token = request_id_var.set("req-demo-0003")
try:
pass # handle the request
finally:
request_id_var.reset(token)Recording the provider's request ID
Most providers return their own request identifier in a response header or response field. The name varies, so check your provider's documentation. Log it as provider_request_id. When you open a support ticket about a bad or missing response, this is the value the provider can look up on their side.
Treat it as external input, like the incoming header. Run it through the same SAFE_ID check, or cap its length, before you log it. If the call fails before a response arrives, there is no provider ID. Log null and rely on your own call_id.
Common mistakes
- Generating the ID inside the wrapper. Each call gets a different value, and nothing links them.
- Reusing one ID for retries and treating it as a call ID. You can no longer tell which attempt failed. Keep both.
- Logging the raw inbound header. Validate it first.
- Forgetting streams. The
stream_loggedgenerator runs when the consumer iterates, which may be after the handler returns. Readrequest_id_var.get()when the stream starts, store it in the generator, and include it in the final record. - Putting the ID in the prompt. Don't do this to make the model "know" the ID. It adds noise, it may leak into the response, and the model can repeat or alter it. Correlation belongs in logs and headers, not in prompt text.
Exercise
Exercise
Your wrapper logs one line per attempt. A user reports a slow answer. You search for their request ID and find three lines, each with a different call_id, where the first two have status "error" and the third has status "ok". Name two things the IDs let you conclude, and say why a single call-level UUID alone would not have been enough.
Show answer
You can conclude that the one user action triggered three attempts, and that the slowness came from two failed attempts plus a retry, not from one slow provider response. You can also see which callid to quote (together with its providerrequest_id, if one was returned) when contacting the provider. A call-level UUID alone would give three unrelated lines. Nothing would show they belonged to the same user action, so you couldn't group them or see the retry pattern.