Trace an AI request end to end
Correlate browser, API, worker, retrieval and model activity with traces, privacy-aware logs and key metrics.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.
In short
One question to the Q&A service touches the browser, the API, sometimes a queued job and worker, the retrieval query and a model call. Tracing gives every step the same trace ID so you can see the whole path, how long each part took and where it failed. Structured logs without secrets and a few key metrics, such as token usage, queue lag, error rate and latency percentiles, complete the picture.
Think of it like this: A trace is a parcel tracking number: every depot scans it, so you can see where the parcel waited and where it got lost.
Explained simply
When a user says the answer was slow, you need to know where the time went. Was it the search? The model? A job stuck in the queue? Observability means collecting enough signals from the running system to answer questions like these without adding new code first.
There are three main signals. A trace follows one request through every service it touches. A metric is a number tracked over time, like requests per second or error rate. A log is a written record of one event. Each answers different questions, and they work best when they share the same IDs.
OpenTelemetry is an open standard and set of libraries for producing traces, metrics and logs. Its FastAPI instrumentation creates a span for every request automatically. You add your own spans for retrieval and model calls, and send everything to a backend such as Jaeger locally or a cloud monitoring service.
Be careful what you record. Prompts and documents may contain personal or customer data, and logs are often kept longer and read by more people than the database. Record IDs, counts, sizes and durations instead of content. Token counts are especially useful because they drive cost.
Press Play on a diagram to walk through it one step at a time.
- Browser to API: POST /chat with traceparent header1POST /chat with traceparent header
- API to Postgres: Span: tenant-filtered vector search2Span: tenant-filtered vector search
- Postgres to API: Top 5 chunks, 38 ms3Top 5 chunks, 38 ms
- API to Model: Span: model call, same trace ID4Span: model call, same trace ID
- Model to API: Tokens streamed, usage counted5Tokens streamed, usage counted
- API to Browser: Stream ends; X-Request-ID returned6Stream ends; X-Request-ID returned
- One request end to end
- Where did time go?
- Sampled to control volume
- Span per step
- Numbers over time
- Is it getting worse?
- Cheap to keep for months
- Drive alerts
- One event in detail
- What exactly happened?
- Structured JSON with IDs
- Never contain secrets or content
In depth
Propagating trace and job IDs
Inside one process, OpenTelemetry keeps the current span in context, so child spans attach automatically. Across a network hop, the context travels in the W3C traceparent header, which instrumented HTTP clients such as HTTPX add for you. A browser can start the trace too if you add OpenTelemetry's web SDK; otherwise the trace starts at the API.
Queues are where traces usually break, because a job message is not an HTTP request. Fix this by hand: when the API enqueues a job, call opentelemetry.propagate.inject on a dictionary and store it in the message as trace_context. The worker calls extract on that dictionary and starts its span with the result as context. Now the upload request and the ingestion hours later share one trace. Also put the job ID and document ID on spans and log lines, and return a request ID in the X-Request-ID response header so support staff can find the trace from a user report.
- HTTP: traceparent header, added by instrumentation
- Queue: inject into the message, extract in the worker
- Add job_id, document_id and tenant_id as span attributes
- Return a request ID to the client
- API to Queue: Enqueue job with trace_context1Enqueue job with trace_context
- Queue to Worker: Deliver message2Deliver message
- 3extract(trace_context), start spanWorker to Worker: extract(trace_context), start span
- Worker to Postgres: Insert chunks, child span4Insert chunks, child span
- Worker to Postgres: Job status done, span ends5Job status done, span ends
Structured logs without secrets
Write logs as JSON with fixed field names: timestamp, level, event, request_id, trace_id, span_id, tenant_id, job_id and duration_ms. The OpenTelemetry logging instrumentation can add trace and span IDs to standard Python logging records, which lets your log tool jump from a log line to its trace.
Decide what never goes into logs: authorization headers, cookies, API keys, database URLs with passwords, prompts, model output and document text. Enforce it in code with a logging filter that drops or masks known keys, rather than trusting every developer to remember. Log the shape of data instead: prompt_tokens=812, chunks=5, document_bytes=48213. If you truly need content to debug a case, use a separate, short-retention store with tighter access, and note it in your data retention plan.
- One event name per log line, such as chat_completed
- IDs and numbers, not content
- A filter that masks secrets by key name
- Same trace_id in logs and traces
Recording token usage and model metrics
Most model APIs return usage with each response: input tokens and output tokens. For streams, usage often arrives in the final event. Record it in three places. As span attributes on the model span; OpenTelemetry's generative AI semantic conventions name these gen_ai.usage.input_tokens and gen_ai.usage.output_tokens, though those conventions are still marked as in development and may change. As metrics, for example a counter of tokens labelled by model and token type. And in your own usage table keyed by tenant, because quotas and invoices need exact per-tenant numbers that metrics are not designed to give.
Keep metric labels low in cardinality: model name, route and status are fine; tenant ID is fine only if you have a handful of tenants; user ID or question text never is. Also record time to first token for streams, since that is what makes a chat feel fast or slow.
Queue lag, error rate and latency percentiles
Four metrics catch most problems. Request rate and error rate per route show whether something broke; count 5xx responses and your own error codes such as provider_timeout. Latency as a histogram, read as p50, p95 and p99: p50 is the typical request, p99 is the worst one in a hundred. Queue lag, measured as the age of the oldest waiting job, shows the worker falling behind long before users complain; queue length alone can mislead when jobs vary in size. And saturation: database pool usage, in-flight model calls and worker busy time.
Set alerts on symptoms users feel, such as p95 chat latency above 8 seconds for 10 minutes or queue lag above 5 minutes, not on every internal number. When an alert fires, open an example trace from that period to see which span grew.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Propagate trace and job IDs~40m
- 2Write structured logs without secrets~40m
- 3Record token usage~40m
- 4Watch queue lag and error rate~40m
- 5Read latency percentiles~40m
Key points
- Traces show one request's path; metrics show trends across all requests; logs give detail at one moment.
- Copy the trace context into every job message so worker spans join the request that created them.
- Log IDs, counts and durations, not prompts, document text, tokens or passwords.
- Record input and output tokens per request with tenant and model, because tokens are your main cost.
- Watch p95 and p99 latency, error rate and queue lag; averages hide the slow requests users notice.
Key terms
Tap a card to flip it. 0/6 known
Examples
from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
tracer = trace.get_tracer("qa.chat")
async def answer(question: str, tenant_id: str):
with tracer.start_as_current_span("retrieve") as span:
span.set_attribute("app.tenant_id", tenant_id)
chunks = await search(tenant_id, question, k=5)
span.set_attribute("app.chunks_found", len(chunks))
return chunksAutomatic spans for each route plus one manual span for retrieval.
Continuing the trace in the worker
Prerequisites: opentelemetry-api and opentelemetry-sdk installed and a local Jaeger or OTLP collector running. Step 1: the API injects the current context into a dictionary and stores it in the job message. Step 2: the worker extracts it and starts its span as a child. Expected evidence: in the trace viewer, the POST /documents span and the ingest_document span appear in one trace, with chunking and embedding spans under the worker span.
from opentelemetry import trace
from opentelemetry.propagate import inject, extract
tracer = trace.get_tracer("qa.ingest")
# API side
def build_job(doc_id: str, tenant_id: str) -> dict:
carrier: dict[str, str] = {}
inject(carrier)
return {"doc_id": doc_id, "tenant_id": tenant_id, "trace_context": carrier}
# Worker side
async def handle(job: dict):
ctx = extract(job["trace_context"])
with tracer.start_as_current_span("ingest_document", context=ctx) as span:
span.set_attribute("app.document_id", job["doc_id"])
await ingest(job)Finding a slow answer from a user report
A contoso user reports a slow answer and gives the request ID shown in the UI. Step 1: search logs for that request_id and read its trace_id. Step 2: open the trace: total 14.2 seconds. Step 3: the retrieve span took 40 ms and the model span 2.1 seconds, but a span waiting for a database connection took 11.8 seconds. Step 4: the pool metric shows the pool at 100 percent for that period. Conclusion: the pool is too small for current concurrency or a slow query is holding connections, not the model. Next step: the sizing checks in the scaling topic.
Quick reference
- FastAPIInstrumentor.instrument_app(app) creates a span for every request.
- traceparent is the W3C header that carries trace context between services.
- For queues: inject(carrier) when enqueuing, extract(carrier) in the worker.
- Log IDs, counts and durations; never prompts, output, documents or secrets.
- Store tokens per tenant in your own table; metrics are for trends, not invoices.
- Queue lag = age of the oldest waiting job; alert on it before queue length.
- Read p50, p95 and p99; alert on symptoms users feel.
- Keep metric labels low-cardinality: no user IDs or free text.
Common mistakes
- Logging the full prompt or retrieved text, which copies customer data into a system with different access rules and retention.
- Starting a new trace in the worker instead of continuing the one from the API, which breaks the story in two.
- Putting user IDs or free text into metric labels, which creates millions of time series.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a logging.Filter that replaces the value of any record attribute named authorization, api_key or password with REDACTED.
- Exercise 2medium
Wrap a model call in a span named model.complete and record the model name and input and output tokens as attributes.
- Exercise 3hard
Write a SQL query that reports queue lag in seconds from a jobs table with columns status and created_at, and say what alert you would set on it.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a paid monitoring service to learn this?
- No. Run Jaeger or the OpenTelemetry Collector locally in Docker and send traces there. Cloud monitoring services are optional and usually charge by data volume.
- Should I trace every request?
- Locally, yes. In production, sampling a share of requests, while keeping all errors if your setup supports it, controls cost and volume.
- What is the difference between a request ID and a trace ID?
- A trace ID is created by tracing and links spans. A request ID is a value you return to the client for support. Many teams log both, or use the trace ID as the request ID.