On this page · 13 sections

The support assistant from “RAG Explained: How AI Systems Work With Your Data (opens in a new tab)” passes its retrieval test: for all 24 answerable questions, an article that answers it is among the three it retrieves. Before it goes in front of customers, someone asks three questions it can’t answer.

What does a customer see if the embedding model hangs? The demo waits 60 seconds for the embedding call before it gives up, and up to two minutes for the chat call.

Billing raises the Pro plan from $25 to $30, as in “RAG vs Fine-Tuning: When Should You Use Which? (opens in a new tab)”, and someone edits the article tonight. What does the assistant do between the edit and the re-index? The demo refuses to answer anything until someone rebuilds the whole index.

And it answered three questions the help center doesn’t cover, from articles that only looked related. In production, how would anyone find out, short of reading every reply?

None of these is about the model. The prompt, the model, and the output checks can stay exactly as they are. They’re about the pipeline around the model, and that’s what this article builds: the same assistant, with a versioned index, one deadline per request, a way to say “nothing relevant here”, and a trace of every request. Then we break it on purpose and measure what each piece does, and what it doesn’t.

Try to Understand It This Way

Go back to the new support agent and the binder. During training week, a desk with a binder is enough. A desk that’s open to customers needs a few rules nobody needed in training:

  • A time limit. If the records system is down, tell the customer within ten seconds. Don’t leave them on hold for two minutes and then say the same thing.
  • A way to replace pages. Print the new pages, swap them in all at once, and keep the old binder on the desk until the new one is complete. And know which pages are out of date.
  • A rule for questions the binder doesn’t cover. If nothing in it even looks related, say so, instead of reading out the closest page.
  • A log book. For every call: which pages were pulled, how long each step took, and what the customer was told.

None of these makes the agent smarter. They make the desk something you can run, change, and debug. That’s the difference between a RAG demo and a RAG pipeline.

Two Pipelines, Not One

A RAG system has two pipelines that run at different times, and production concerns show up in both:

Index time (whenever articles change)
  help center ──► fingerprint each article ──► embed only new or changed ones ──► new index version
              ──► write it to a temporary file, then rename it over the old index

Query time (every question, one deadline for the whole request)
  validate ──► retrieve ──► relevance gate ──► generate ──► check ──► reply

    retrieve         the embedding call, then a cosine search over the index
    relevance gate   decline without calling the model if even the best match is weak
    generate         the chat call, with a JSON schema

  every step adds to one trace: index version and staleness, timings,
  retrieval scores, the gate decision, token counts, the outcome

Each stage has a contract: what it takes, what it returns, how it can fail, and what it records. The rest of this article is about those contracts.

The Experiment

The demo, 03-production-rag-pipeline, uses the same 50-article help center, the same 30 test questions (24 answerable, 6 the help center doesn’t answer), the same prompt, and the same two local models as Article #12: llama3.2:3b to answer and nomic-embed-text to embed.

One codebase has two profiles:

basic        Article #12's behavior: a 60-second timeout for the embedding call, 120 seconds
             for the chat call, and no relevance gate
production   one 10-second deadline for the whole request, and a relevance gate

Whenever the gate lets a question through, both profiles send the model a byte-identical request. That’s what makes the comparison clean: any difference comes from the pipeline, not from the model. It held in the runs: the basic profile’s 30 replies were identical to Article #12’s saved run, and the production profile’s 27 replies that passed the gate were identical to the basic ones.

Three experiments then test the three new pieces. An update scenario changes five articles and watches the index. A fault injector, a small stand-in server between the assistant and Ollama, makes the model calls hang, fail, or return garbage. And a relevance threshold is chosen on a separate set of development questions, then applied to the test questions.

Implementation note: the exact setup
Machine:       Apple M4 Pro (24 GB), macOS 26.6, on AC power
Runtime:       Ollama 0.40.16, /api/embed and /api/chat
Chat model:    llama3.2:3b, ID a80c4f17acd5 (Q4_K_M), temperature 0, seed 1,
               at most 300 output tokens, JSON schema in `format`, default context (4,096)
Embeddings:    nomic-embed-text, ID 0a109f422b47, 768 dimensions,
               prefixes "search_query: " / "search_document: "
Pipeline:      top 3 articles; production: 10-second deadline, relevance threshold 0.65
Languages:     Python 3.12.13 (requests 2.34.2) and Node.js 24.16.0, identical output apart from timings
Runs:          evaluation, faults, and update twice in each language, 2026-11-13
Grading:       every answer to an answerable test question read and labeled by hand;
               each label stored with a hash of the exact reply. Replies to the six
               questions the help center doesn't answer: counted as declined or answered
               (any answer is a failure there), and every reply read

Across the four evaluation runs, every reply, retrieval score, and token count was identical; only timings differed. Expect the same shape with other models or versions, not the same digits.

Index Time: Treat the Index as a Build

Article #12 already recorded the embedding model, the prefixes, and a fingerprint of every article with its index, and refused to serve from an index that didn’t match. That’s safe, but it has a cost: after any edit, the assistant answers nothing until someone rebuilds everything.

The production version treats the index like any other build artifact:

  • Incremental. Each article’s fingerprint is a SHA-256 of exactly the text that gets embedded: its title and body. Fingerprint everything that affects retrieval or the prompt; a field left out could change without changing the version. Only new or changed articles are embedded again; the others keep their vectors. A different embedding model or different prefixes mean a full rebuild, because vectors from different settings can’t be compared.
  • Versioned. The version is a hash of the settings and every fingerprint, so the same content always gets the same version, and every trace records which version answered.
  • Swapped in one step. The new index is written to a temporary file and renamed over the old one. On one file system, a rename replaces the file in one step, so a reader sees the old index or the new one, never half of one. That makes replacing the file atomic; it doesn’t switch running processes over. The demo’s assistant checks the file on every request and loads a new version when there is one. With several workers, each has to do the same, and for a while different workers can answer from different versions, which the index version in every trace makes visible.
  • A snapshot of what was embedded. The index stores the article text it embedded, and the prompt is built from that text. So the text the model reads always matches the vectors that retrieved it.

Here is the update scenario, with the same five fact changes as Article #13:

1. Build the index
   from scratch: embedded 50, reused 0, removed 0 -> version eae26b6c1519
   again, nothing changed: embedded 0, reused 50, removed 0 -> version eae26b6c1519 (unchanged)

2. Billing changes 5 articles (6 edits). Articles changed since the index was built: 5

3. Before re-indexing, the running assistant still serves the old version:
  a02 [index eae26b6c1519, 5 stale] 'How much is the Pro plan?'
      The Pro plan costs $25 per month and $250 per year.

4. Re-index: embedded 5, reused 45, removed 0 -> version f701f0419d49
   The same assistant, on its next requests:
  a02 [index f701f0419d49, 0 stale] 'How much is the Pro plan?'
      The Pro plan costs $30 per month and $300 per year.

5. The 'sso' article is removed. Re-index: embedded 0, reused 49, removed 1 -> version 367ec836ebce

(The scenario asks all five affected questions; the other four behaved the same way. All ten replies were read: the five before the re-index had the old values, the five after had the new ones, and none said anything else that was false.)

Step 3 is a decision, not a bug. Between the edit and the re-index, the assistant told a customer $25 while the help center said $30. Article #12’s version would have refused to answer at all. Neither is right for every system:

  • For most support content, serving the last complete version is the better failure, if staleness is short and visible. Every trace here records one count, index_stale_articles: the articles added, changed, or removed since the index was built, so a monitor can alert on it. And re-indexing can be part of publishing an article, so the window lasts seconds instead of “until someone notices”.
  • For content where an old answer is worse than no answer, such as prices you’re bound by, or legal and safety text, you might decline any question whose retrieved articles have changed since indexing. This demo doesn’t implement that; it’s a design option.

Step 5 matters just as much. A deleted article must stop being retrievable. An index that only adds and updates keeps serving a withdrawn policy for as long as nobody rebuilds it from scratch.

Query Time: One Deadline, Named Failures

The assistant from “Building Your First LLM-Powered Application (opens in a new tab)” already turned every model failure into one error type and a polite message. What it didn’t control was how long a customer waited for that message, or which call had failed.

The production profile gives the whole request one deadline, 10 seconds, and each model call gets whatever time is left. In JavaScript, that’s a hard limit on each call. In Python, requests limits how long each wait for data can take, not the whole call. That’s enough for the calls that stop responding below, but it isn’t a wall-clock cap in general (details in the box further down). The fault injector then puts a stand-in server between the assistant and Ollama: it forwards requests to the real server, or breaks one endpoint on purpose. The same question went through both profiles in each scenario:

scenario                          profile       waited  status  outcome      failed call
healthy                           basic          0.4 s     200  answered
healthy                           production     0.4 s     200  answered
Ollama not running                basic          0.0 s     503  unavailable  retrieve: unavailable
Ollama not running                production     0.0 s     503  unavailable  retrieve: unavailable
embedding call hangs              basic         60.0 s     503  unavailable  retrieve: timeout
embedding call hangs              production    10.0 s     503  unavailable  retrieve: timeout
embedding call returns HTTP 500   basic          0.0 s     503  unavailable  retrieve: http_error
embedding call returns HTTP 500   production     0.0 s     503  unavailable  retrieve: http_error
chat call hangs                   basic        120.0 s     503  unavailable  generate: timeout
chat call hangs                   production    10.0 s     503  unavailable  generate: timeout
chat call takes 12 s              basic         12.4 s     200  answered
chat call takes 12 s              production    10.0 s     503  unavailable  generate: timeout
chat call returns HTML, not JSON  basic          0.0 s     503  unavailable  generate: invalid_response
chat call returns HTML, not JSON  production     0.0 s     503  unavailable  generate: invalid_response
chat connection closed, no reply  basic          0.0 s     503  unavailable  generate: unavailable
chat connection closed, no reply  production     0.0 s     503  unavailable  generate: unavailable

(Timings from one Python run; the other three fault runs matched to within 0.1 s.)

Three things stand out.

Fast failures were already fine. A refused connection, an HTTP 500, or a garbage response fails in milliseconds in both profiles, and the customer gets the same message. Error handling isn’t the hard part. Waiting is.

Hangs are where a deadline pays off. A hung embedding call kept the customer waiting 60 seconds; a hung chat call, 120. With the deadline, both were 10. And because each failure is named by call and kind (retrieve: timeout, generate: invalid_response), whoever reads the trace knows where to look.

A deadline turns slow successes into failures. When the chat call took 12 seconds, the basic profile answered after 12.4 seconds, and the production profile gave up at 10. That’s the trade-off you’re choosing when you pick a deadline. Google’s SRE book describes both sides: “High deadlines can result in resource consumption in higher levels of the stack” when the lower levels are having problems, and “Short deadlines can cause some more expensive requests to fail consistently.” In these runs, the slowest answered request in the production profile, including loading both models from cold, took under 2 seconds, so 10 seconds left plenty of room. Measure your own slow path, especially cold starts, before you pick the number.

Why one deadline instead of a timeout per call? Because the customer experiences the total. If the embedding call takes 8 seconds, the chat call should get 2, not a fresh 120. The SRE book calls the general version of this deadline propagation: “The tree of RPCs emanating from an initial request will all have the same absolute deadline.”

Under the hood: what a timeout actually limits

The two languages enforce the deadline differently, and it matters at the edges.

In Python, requests applies its timeout to connecting and to each wait for data. One number applies separately to each, so a slow connection and a slow reply can add up. Its documentation says it’s “the number of seconds that the client will wait between bytes sent from the server”, and that “Neither the connect nor read timeouts are wall clock.” A server that sends a reply slowly, a few bytes at a time, could keep a request alive past the deadline. With stream: false, Ollama sends its reply once generation has finished, so here the timeout works as a limit on the wait for the reply. A hard wall-clock limit in Python needs something on top of requests’ timeouts.

In JavaScript, the demo passes AbortSignal.timeout() to fetch, which returns a signal “that will automatically abort after a specified time” (MDN). That limits the whole request, including reading the body.

If the deadline has already passed before a call starts, the pipeline doesn’t make the call at all; the failure is recorded with kind deadline.

There’s a second lesson in this experiment, and it came from a bug in the demo. The first version of the stand-in server kept sleeping after the production profile had given up on the 12-second chat call, then forwarded the request to Ollama anyway. That reloaded the chat model after the script had already unloaded it. A timed-out request isn’t a cancelled request: the client stopped waiting, but the work it started kept going. The gRPC documentation says the same about its own deadlines: “the server application is responsible for stopping any activity it has spawned to service the RPC.” Whether a model server stops generating when the client disconnects depends on the server. Check yours, because abandoned requests still use GPU time.

The production profile has no retries. A retry inside a 10-second budget only helps if there’s time left for it, and retrying a hung call can double the load on a struggling server. Retries, backoff, and circuit breakers are their own topic, later in the series.

“Nothing Relevant Found”: The Relevance Gate

Article #12 ended with an open problem: this implementation always hands the model the closest articles, even when none of them is relevant, and for half the questions the help center doesn’t answer, the model answered anyway.

The simplest fix is a gate between retrieval and generation. If even the best article scores below a threshold, decline without calling the model.

The threshold can’t be chosen on the test questions; then the test would only measure how well we fit them. So it was chosen on separate development questions: 123 answerable ones, the questions Article #13 fine-tuned and validated on (112 training and 11 validation questions, which word help-center facts differently from the test questions), and 19 the help center doesn’t answer (9 from Article #13’s data, 10 written for this demo). The rule was fixed before any test question went through the gate: the highest threshold, rounded down to 0.01, that blocks at most 1% of the answerable development questions. That gave 0.65:

development questions      top-1 similarity       blocked at 0.65
answerable (123)           0.6059 to 0.8727          1 of 123
not in docs (19)           0.4950 to 0.7508         16 of 19

That looks promising. Here is what it did on the test questions:

                     answerable (24)                         not in docs (6)          chat
profile        correct  partly  wrong  declined            declined  answered         calls
basic               22       0      1         1                 3/6         3            30
production          22       0      1         1                 3/6         3            27

The gate blocked three of the six questions the help center doesn’t answer: a phone number (0.6452), a nonprofit discount (0.5925), and a Windows app (0.6381). The model had declined all three anyway. The three it answered all scored above the threshold, and each reply says something the help center doesn’t:

'How many days does it take for a refund to arrive?'   0.8508
   A refund is returned to the original payment method within 30 days of the request.
'What is the maximum number of tasks in one project?'  0.7109
   There is no limit on the number of tasks in a project, but the board view can become cluttered...
'Can I pay in euros?'                                  0.6545
   We do not currently accept euros as a payment method. We accept Visa, Mastercard, ...

The refunds article says a refund can be requested within 30 days of purchase; the reply turned that window into a delivery time. No article mentions a limit on tasks or which currencies are accepted.

So on the test set, the gate changed nothing the customer saw. It saved three chat calls.

The reason is in what a similarity score measures: how much the question and the article are about the same thing. “How many days does it take for a refund to arrive?” is about refunds, and the refunds article is about refunds. It just doesn’t contain the answer. That’s the hardest kind of out-of-scope question, and a similarity threshold can’t see it.

What the gate catches is questions whose best match is weak, and that isn’t the same as off-topic. All three blocked test questions are about this product: reaching support, pricing, and apps. No article answers them, and their best matches scored below 0.65; the closest article to the nonprofit-discount question was the one about guests (0.5925). A similarity score can say that nothing in the help center is close to a question. It can’t say that the closest article lacks the answer.

Under the hood: the threshold on the development questions
threshold   answerable blocked   not in docs caught
     0.55                0/123                 2/19
     0.60                0/123                 4/19
     0.62                1/123                 8/19
     0.64                1/123                14/19
     0.65                1/123                16/19
     0.66                3/123                16/19
     0.68                7/123                17/19
     0.70               19/123                17/19

The margin is thin: the highest out-of-scope score below 0.65 was 0.6492, and the lowest answerable score above it 0.6536. The one answerable question it blocks is “Do you support SAML?” (0.6059): a short question that is mostly one acronym. The three out-of-scope questions that pass are topic-adjacent: task dependencies (0.6685), printing a task list (0.7140), and a browser extension (0.7508), which scores high against the article about supported browsers.

Two caveats. Some development questions cover the same facts as test questions in other words, so the two sets are related, not independent. And the test questions’ score ranges had already been published with Article #12; the rule doesn’t use them, but they weren’t hidden either.

The threshold belongs to this embedding model, these prefixes, and this help center. Change any of them, and it has to be chosen again: scores from different embedding models aren’t comparable.

Is the gate still worth having? As a stage, yes: it’s cheap, it fails closed when even the best match is weak, and it saves model calls on exactly those questions. As a solution to “the model answers from near-miss articles”, no. It’s a place in the pipeline where a better relevance signal can go later: keyword and hybrid scores, reranker scores, or a retrieval evaluator like the one in Corrective RAG (Yan et al., 2024), “designed to assess the overall quality of retrieved documents for a query”. The next articles in this phase work on those signals. Whatever you plug in, choose its threshold on development data and measure it on test data, as here.

Traces: What Happened, Not Whether It Was Right

Every request produces one trace. Here is the one for the phone-number question, which the gate blocked:

{"profile": "production", "prompt_version": "support-v1", "chat_model": "llama3.2:3b",
 "embedding_model": "nomic-embed-text", "index_version": "eae26b6c1519", "index_stale_articles": 0,
 "k": 3, "deadline_seconds": 10, "relevance_threshold": 0.65, "input_chars": 38,
 "stages": {"retrieve": 552},
 "retrieved": [{"id": "support-hours", "score": 0.6452}, {"id": "billing", "score": 0.5957},
               {"id": "webhooks", "score": 0.5828}],
 "gate": {"top_score": 0.6452, "threshold": 0.65, "passed": false},
 "prompt_tokens": null, "error": null, "status": 200, "outcome": "no_relevant_article", "latency_ms": 552}

(Abridged: the request id and three empty fields are left out. The 552 ms includes loading the embedding model, which wasn’t in memory yet.)

A small report reads nothing but traces, the way an operator would, without the test questions or the hand labels. Over all saved runs, it answered most of the operational questions directly:

  • Which call failed, and how? Every failure in the fault runs, by call and kind, with the longest wait: 60 and 120 seconds in the basic profile, 10 in production.
  • Where does the time go? In answered requests, retrieval took a median of about 0.01 seconds and generation about 0.75. If this assistant gets slow, the chat call is where to look first.
  • What answered? The prompt version, both models, and the index version for every request, including the five requests answered from an index with five changed articles.
  • What did the gate do? Blocked requests and their scores, and the answered requests that scored close to the threshold.

What the traces can’t tell you is whether an answer was right. The wrong answer about the deleted project (“No, after 30 days…”, top score 0.7367) and the refund answer (0.8508) look like any healthy request: normal scores, normal latency, outcome answered, with a schema-valid reply that passed the value check. The report’s list of answers near the threshold flagged three in the test run: two correct (getting a refund, 0.6619; the member limit, 0.6535) and one unsupported (euros, 0.6545). A review band, not a detector.

So traces and evaluation do different jobs. Traces tell you what happened to each request, which you need the moment something goes wrong. Evaluation, with labeled questions and people reading replies, tells you whether the answers are good. A production pipeline needs both, and neither replaces the other.

What Breaks

  • Deadlines cut both ways. A deadline that’s too long keeps customers waiting on a dead dependency; one that’s too short fails slow but valid requests, and cold starts first.
  • Abandoned work. A client timeout doesn’t stop the server. Without cancellation, timed-out requests still consume GPU time.
  • The stale window. Between an edit and the re-index, the assistant gives the old answer. Make the window short and visible, or decline for changed articles.
  • Near-miss questions pass a similarity gate. Every out-of-scope question that got past the gate and was answered was close to a real topic: refunds, payment methods, tasks.
  • Thresholds that drift. A threshold chosen for one embedding model, prefix set, or help center is wrong for the next one, and nothing in the score says so.
  • Citations nobody checks. One correct answer cited an article that doesn’t mention its topic; the application only checks that a cited id was retrieved.
  • Traces that look healthy. A wrong answer produces a normal-looking trace. Only evaluation finds it.

Engineering Decisions

1. Give each request one deadline, and pass on what’s left

Pick it from your measured slow path, including cold starts, and give every downstream call the remaining time, not a fresh timeout of its own.

2. Name every failure by stage and kind

retrieve: timeout and generate: invalid_response lead to different fixes. Decide in code what the customer sees for each, and keep it the same across failures they can’t do anything about.

3. Build the index like an artifact

Fingerprint the documents, re-embed only what changed, version the result, swap it in atomically, and record the version in every trace.

4. Decide what “stale” means for your content

Serve the last complete version and alert on staleness, or decline for changed documents. Either way, make removal a first-class change.

5. Gate on relevance, but measure what it catches

Choose the threshold on development data, report it on test data, and expect a similarity threshold to catch weak matches, not near misses.

6. Trace every request, and evaluate separately

Traces explain individual requests. Labeled questions and read replies tell you whether the system is good. You need both.

7. Keep a profile that reproduces the old behavior

The basic profile made every comparison here controlled: identical requests, so every difference came from the pipeline. That’s worth keeping for every future change.

What to Take Away

  • Production concerns live in the pipeline, not the model. Here the prompt and model didn’t change; the deadline, index, gate, and traces did.
  • In these runs, one deadline turned 60- and 120-second waits into 10. It also turned a 12-second success into a failure. Choose that trade-off with measurements, and check what your client actually enforces: here, Python’s limit is on each wait, not the whole call.
  • The index is a build artifact. Incremental, versioned, swapped atomically; serving a stale version is a decision to make explicitly.
  • A similarity threshold isn’t an answerability check. On the test questions it caught only what the model already declined, and missed every near-miss.
  • Traces say what happened, evaluation says whether it was right.

Think About These Use Cases

  • An internal policy assistant: HR updates the leave policy. Would you serve the old version until re-indexing finishes, or decline questions about leave? What decides it?

  • A voice assistant on a phone line: The caller hears silence while the pipeline runs. What deadline would you set, and what should the caller hear when it expires?

  • A multi-step RAG pipeline: Query rewriting, retrieval, reranking, and generation each call a model. How would you split one deadline across four calls?

  • A help center in five languages: Each language has its own articles. Would one relevance threshold work for all of them? How would you find out?

  • A weekly quality review: You can read 50 replies a week. Which requests would you pick from the traces, and which would you sample at random?

If you want to work through one of these, take it to GPT along with this article. Ask GPT ↗️

  • 03-production-rag-pipeline: The companion demo for this article: the versioned index, the deadline, the relevance gate, the fault injector, traces, and the hand labels (Python and JavaScript).
  • Addressing Cascading Failures (Site Reliability Engineering, Google): Deadlines, deadline propagation, and what happens when they’re too long or too short.
  • Deadlines (gRPC documentation): Deadlines versus timeouts, propagation, and why the server must stop its own work.
  • Corrective Retrieval Augmented Generation (Yan et al., 2024): A retrieval evaluator that judges retrieved documents before generation.
  • Ollama API reference: The /api/embed and /api/chat endpoints used by the demo, including JSON-schema output with format.
  • Requests: Timeouts: What a timeout in Python’s requests does and doesn’t limit.

What’s Next?

This pipeline treats each article as one piece of text, because the help center’s articles are short. Real documents aren’t: they’re manuals, contracts, and wikis, and they have to be split before they’re embedded.

In the next article, we’ll look at Chunking Strategies for RAG: What Actually Matters?: how splitting documents changes what retrieval can find, and how to measure it.

← All articles