In this post
What this post covers
How this was tested
2 vCPU GitHub runner (CPU only), Python 3.12.16, fastapi 0.165.0, httpx 0.29.0, in-process TestClient (no network). BM25 retrieval over 7,298 paragraph chunks from the FastAPI English docs. 2,000 requests per mode from a fixed workload (23 distinct queries, 80% answerable, 20% unanswerable). The LLM call is a stub, so timings cover retrieval plus logging only. Not tested: a real LLM call, multiple workers or log shipping, a log backend, concurrency, real user traffic.
When a RAG answer is wrong, what do you need in the log to find out why? And what does that logging cost?
Short answer: log one JSON line per request with the retrieved chunk IDs and scores, the outcome, per-stage timings and the index version. In my test that added 0.106 ms per request (1.8%) and 553 bytes per line. Storing the full chunk text and prompt too cost +0.153 ms (2.6%) but made lines 3.4 times larger. The log also exposed a bug I had not planned for: my score gate was answering most questions it should have refused.
For the background on tracing and metrics, see the free guide Why observability. The refusal gate used here is the idea from Make your RAG say “I don’t know”.
Setup
- A small FastAPI app with one endpoint,
/ask?q=.... Retrieval is BM25 over 7,298 paragraph chunks of the FastAPI docs. Generation is a stub that returns a fixed string. No LLM was called, so I make no latency claim about generation. - Refusal gate: if the top-1 BM25 score is below 8.0, return “I don’t know”. I picked 8.0 by eye for this test; it is not calibrated.
- Workload: 2,000 requests per mode, drawn at random (fixed seed) from 15 answerable and 8 unanswerable questions, 80/20.
- Three modes:
off(no logging),ids(the schema below),text(schema plus the query, all 5 chunk texts and the full prompt). - Timed in-process with FastAPI’s TestClient, after a 100-request warmup. This measures the middleware cost, not network or server cost.
The schema
{"ts":1796265609.9,"request_id":"7b95f5c467ab","route":"/ask",
"index_version":"fastapi-docs-2026-12-03",
"query_sha1":"bd449c2387","query_len":28,
"retrieval":{"k":5,"n_hits":5,"top1":16.98,"scores":[16.98,15.2,12.1,11.8,9.4],
"chunk_ids":["deployment_docker.md#3","..."]},
"stages_ms":{"retrieve":2.38},
"generation":{"model":"stub","prompt_chars":3120,"completion_chars":40},
"outcome":"answered","status":200,"latency_ms":5.9}
Why each field is there:
request_id: accept it from an incoming header so a log line joins your API gateway and tracing.index_version: a quality drop after a re-index is invisible without it.chunk_ids+scores: lets you replay “what did it retrieve” without storing text. IDs are stable; text can be fetched from the index later.outcome:answered,refused_low_score, or an error class. This is the field you will filter on most.stages_ms: per-stage timings, so “slow” can be pinned on retrieval, rerank or the model.query_sha1andquery_len: a hash counts repeats and lets you join to an eval set without storing user text. Store the raw query only if your privacy policy allows it.- In production also add the model name, real token counts, and cache hit or miss. My stub has no tokens, so I log characters instead.
Results
| Mode | Median ms/request | p95 ms | Overhead vs off (median) | Bytes per line |
|---|---|---|---|---|
| off | 5.932 | 7.531 | n/a | n/a |
| ids | 6.038 | 7.615 | +0.106 ms (1.8%) | 553 |
| text | 6.085 | 7.909 | +0.153 ms (2.6%) | 1,858 |
The full-text mode produced 3,715,785 bytes for 2,000 requests, 3.4 times the 1,105,187 bytes of the ID-only mode. At 553 bytes a line, a million requests is about 553 MB of log.
What the logs answered
I ran these questions over the ids log, using only json and collections:
- Refusal rate: 107 of 2,000 requests (5.4%) were refused. The workload is 20% unanswerable, so that is already suspicious.
- Score by outcome: answered requests had a median top-1 score of 16.98 (range 8.36 to 39.69). Refused ones had a median of 0.00 (so at least half had no hits at all) and a maximum of 7.48.
- Stage timing: retrieval was p50 2.38 ms, p95 3.98 ms, p99 4.11 ms, with one outlier at 23.6 ms. Retrieval was a median 86% of request time here, which will not hold once a real LLM call is in the path.
- Gate failures: I hashed my 8 unanswerable questions and matched them against
query_sha1. Only 2 were refused (Prometheus histogram buckets, Selenium browser automation). The other 6, including “How do I boil an egg”, were answered. Of 439 unanswerable requests, 332 (75.6%) got an answer.
That last result is the point. Status was 200 on every request and latency looked healthy; only outcome plus top1 showed that the gate was close to useless. Common words like “how” and “do” give BM25 a high score for any English question. This matches what I measured earlier in the refusal post: raw BM25 scores make a poor gate. Cosine scores separated the groups much better there.
Caveats
- Everything is single-process and in-process. Under real load, a log line written through a blocking file handle can cost more; ship logs through your platform’s stdout and collector.
- The 0.1 ms figures are small because the stub is fast. A real LLM call takes far longer, so the relative cost would be smaller, but I did not measure that.
- 23 distinct queries is a small workload. Treat the gate numbers as a demonstration of what the log shows, not a benchmark of BM25 gating.
- Hashing a query is not anonymization. Short or repeated queries can be guessed.
- The score threshold of 8.0 was arbitrary, so 75.6% is a property of this setup only.
Copyable middleware
import contextvars, json, time, uuid
from fastapi import FastAPI, Request
ctx = contextvars.ContextVar("rec", default=None)
app = FastAPI()
@app.middleware("http")
async def log_request(request: Request, call_next):
rec = {"ts": time.time(),
"request_id": request.headers.get("x-request-id") or uuid.uuid4().hex[:12],
"route": request.url.path, "stages_ms": {}}
token = ctx.set(rec)
t0 = time.perf_counter()
try:
resp = await call_next(request)
rec["status"] = resp.status_code
return resp
except Exception as e:
rec["status"], rec["error"] = 500, type(e).__name__
raise
finally:
rec["latency_ms"] = round((time.perf_counter() - t0) * 1000, 3)
print(json.dumps(rec, separators=(",", ":")), flush=True)
ctx.reset(token)
Inside your handler, call ctx.get() and add retrieval, stages_ms, generation and outcome. The full runnable version is bench_logging.py in the Experiment files box below.
Rule of thumb
Log IDs and scores on every request, and keep text only for a sampled slice or behind a short retention window. Add outcome and index_version on day one. Then, each week, query the log for refusal rate, answered-with-low-score requests and the slowest stage. For turning those into a regression test, see a golden set in CI.
Experiment files
Get the free RAG production checklist
25 checks to run before real users see your RAG feature: exact-match misses, invented citations, prompt injection through documents, quality that slips after a prompt change. Confirm your email and the PDF comes with the welcome email, plus each new experiment.