Chapter 12 / 12 · AI Engineering

In production: monitoring, fallbacks and feedback

Trace every turn, hold cost and latency to a budget, survive a provider outage, and turn what customers do next into new eval cases.

Running the assistant in production means four jobs: seeing what it does for real customers, holding its cost and latency inside budgets set in advance, deciding what happens when something it depends on fails, and feeding what we learn back into the eval suite. This chapter works through each of them for the support assistant, on an ordinary day and on a bad one.

The traffic has a shape that matters. The assistant handles about 30,000 conversations a day, about 70% of them during market hours, with a sharp peak at the 9:15 open and larger ones on days when prices move a lot. Those are the days when customers most need answers about orders and funds, and also the days when every system the assistant depends on, including the model provider, is busiest. The design has to assume that the worst load and the worst reliability arrive together.

Trace every turn, and keep enough to replay it

A complaint in production usually arrives as a screenshot: “the assistant told me my money would arrive today, and it didn’t.” To act on it, we need to see exactly what the assistant saw. So every turn produces a trace, a tree of timed spans with the details attached. The retrieval span records which documents came back and their scores. Each model span records the model version, the prompt version, input and output tokens, time to first token and why generation stopped. Each tool span records the arguments, a summary of the result, its latency and any error. Guardrail spans record their verdicts. The trace carries the conversation id and the prompt and eval-suite versions that were live.

With that, a complaint becomes reproducible. We replay the turn with the same retrieved passages and the same tool results as fixtures, see the bad answer again, and save it as a new eval case, often within an hour of the complaint. The redaction rules from the security chapter apply to all of it, because a trace store with full prompts is the largest collection of customer conversations the company has.

one turn · “where is my sell order ORD-88213?” · spans on a time axis0 s1 s2 s3 s4 s5 s6 s7 sinput checksretrievaldecision callget_order_statusreply calloutput checksfirst visible token · 2.73 sthe customer waits for everything left of the line · the stream hides what is right of it
One traced turn for an order question: the customer waits for everything before the first visible token, and the stream covers the rest

Set the latency and cost budgets before launch

The trace above is a typical order question: “where is my sell order ORD-88213?” Input checks take 80 ms. Retrieval, with the context chapter’s query rewrite, two searches and reranker, takes 400 ms. The decision call, which returns the JSON saying lookup_order, takes 1.1 seconds. The order service answers in 250 ms. The reply call takes 900 ms to produce its first token and then streams about 250 tokens at roughly 60 a second, for another four seconds or so. The customer sees the first word at 80 + 400 + 1,100 + 250 + 900 = 2,730 ms.

Our budget is a first visible token under 2 seconds at the median and under 4 seconds at the 95th percentile. The trace shows where to cut. The decision call waits for retrieval, yet what it decides (this customer gave an order id and wants its status) depends on the message, not on the articles. So it runs in parallel with retrieval, and on a small, fast model, since it chooses among three actions and its output is validated by code anyway; that brings it to about 400 ms. The lookup then starts at 80 + max(400, 400) = 480 ms, and the first token arrives at 480 + 250 + 900 = 1,630 ms. The rare decision that does depend on the articles (whether they answer the question at all) is still caught by the reply call, which can offer a ticket.

The 95th percentile is set by the tails of the dependencies. The order service’s p95 is about 900 ms, and the model’s time to first token stretches under load. Each span gets its own timeout, chosen from its measured percentiles, so that a slow lookup produces a clear “I couldn’t reach the order system just now” instead of a frozen chat.

Cost gets the same treatment. A typical conversation costs about $0.0191 with the inference chapter’s prompt ordering, about $573 a day. We chart cost per conversation by prompt version and alert on the daily total and on the 99th percentile per conversation, which is where runaway agent loops show up. The per-version chart catches quieter changes too. Someone adds a line to the top of the system prompt, “Current time: 09:16:03”, so the assistant can talk sensibly about market hours. Every call’s prefix now differs from the last, nothing is read from the cache, and a conversation costs the uncached $0.0275: 44% more, about $250 a day, from a line that looks harmless in review. The fix is to put the time after the stable prefix, next to the question.

Guardrails, and the answers they wrongly block

Guardrails are checks that run outside the model, on what goes in and what comes out. On input we redact personal data before anything is logged, reject absurdly long messages, and flag known injection patterns. On output we check that the answer does not read as investment advice, that every link and image is on the allow-list from the security chapter, that every cited document was actually retrieved, and that no PAN or account number appears. Each check catches something real, and each one also stops some good answers.

GuardrailWhat it catchesWhat it costs
No-advice classifieranswers that recommend a tradeat a 2% false-positive rate, 600 good replies a day held for a reviewer while the customer waits
Link and image allow-listthe exfiltration channela legitimate exchange or regulator link is shown as plain text
Citation checkcitations to documents that were never retrievedalmost nothing; it is a set lookup
Full-answer holdanything, before the customer sees itthe whole generation time added to the wait

The last row is the tension with streaming. Most output checks want the whole answer, and streaming shows the answer as it is produced. Showing tokens and then retracting the message when a check fails is the worst of both: the customer has already read it, and for compliance purposes it has been said. We split by route. For questions the router marks as advice-shaped, we hold the full answer, check it and then show it, accepting about four extra seconds on a small share of traffic. Everywhere else we stream sentence by sentence, holding back one sentence at a time and checking it before release, which adds a few hundred milliseconds.

A held reply is a product decision too. While it waits for the reviewer the prompting chapter put behind this check, the customer sees a short message saying a colleague is checking the answer, links to the relevant articles and an offer to raise a ticket. We sample held replies every week, because a rising hold rate is as likely to be a check problem as a model problem, and every false hold costs a reviewer’s minute and a customer’s patience.

Predict first

At 9:20 one morning the model provider starts failing 30% of calls. Retries already use backoff and a budget, and each failed call is retried once. A conversation is four turns, each with a decision call and a reply call. What fraction of conversations get through without a visible failure?

Show the worked answer

With one retry, a call fails only if both attempts fail: 0.3 × 0.3 = 0.09, so each call succeeds with probability 0.91, assuming the failures are independent. A conversation needs eight calls to succeed: 0.918 ≈ 0.47. Fewer than half the conversations finish cleanly, even though nine calls in ten succeed.

And the independence assumption is generous. A provider failing at 30% is usually overloaded, so the retry fails more often than the first attempt did. Per-call error rates understate what customers experience, because a conversation multiplies them.

The morning the model provider went down

The inference chapter’s bad morning was about our own limits: a traffic spike hit the provider’s rate limit, and retries made it worse. Out of it came backoff, a retry budget, a token-usage cutoff that shows new customers a ticket button instead of the assistant, and a path that sends fraud reports to the fraud desk without touching the model. This morning is different. The traffic is ordinary for a falling market, and the provider itself is failing.

At 9:20 the provider’s error rate rises to 30% and its p95 latency goes from about 3 seconds to 25. Our client uses a generous 60-second timeout, so worker slots sit waiting on slow calls and new turns queue behind them. The retry budget stops retries from multiplying load, which is the lesson already learned, but it cannot make the provider answer. As the prediction shows, more than half the conversations hit a failure somewhere, often halfway through: the decision call succeeded and looked up the order, and the reply call timed out, so the customer saw “Something went wrong” after a long wait. Nothing in our code is broken. We have one model dependency and only one plan for it, which is to stop using the assistant.

The fix comes in layers, each with a cost. First, timeouts that match the budget: a 4-second limit on time to first token, so a failing call fails fast instead of holding a slot for a minute. Second, a circuit breaker: when the error rate stays above 20% for thirty seconds, we stop sending to the primary provider for a minute and send occasional probe requests to see when it recovers.

Third, a fallback model, either from a second provider or self-hosted. It must be in the eval suite like the primary, with its own adapted prompt, because tool-call formats and instruction-following differ between models. Suppose it scores 71% on the core set against the primary’s 79%. That is a known, measured degradation, which is far better than an unknown one. The cost is a second contract, a second prompt to keep in sync and every eval run done twice.

Fourth, a mode with no model at all. Retrieval is our own service, so we can still show the top three help articles for the customer’s question. The order lookup is ours, so we can show the order’s status formatted by ordinary code. And the ticket form works without a model. That mode answers a good share of questions on a bad morning, and it is the only layer that survives every provider failing at once. We test the breaker and the fallbacks every month by forcing them open in staging, and once a quarter in production during quiet hours, because a fallback that has never run will not work when it is needed.

One more dependency failure is quieter. If we call the model through an alias that the provider updates, a new model version can arrive on a Tuesday with no change on our side. We pin exact model versions, upgrade deliberately through the eval suite, and re-run the suite on a schedule anyway, because pinned versions are eventually retired.

What customers tell us without being asked

Thumbs-up and thumbs-down buttons get used on about 2% of conversations, mostly by customers who are unhappy, and mostly about outcomes the assistant does not control (“why is settlement so slow?”). They are worth keeping and nearly useless as a quality metric. The behaviour customers show afterwards is far more informative, and it covers every conversation. The strongest signal is re-contact: the same customer coming back about the same topic within 72 hours, through any channel. Others are a human ticket on an issue the assistant marked as resolved, the customer rephrasing the same question, asking for a person, or leaving straight after an answer.

We define a conversation as resolved when there is no re-contact within 72 hours and no human ticket, and that becomes the headline outcome. Then, each week, an engineer and a senior support agent read about a hundred conversations from the suspicious slices: re-contacts, low judge scores, blocked answers, budget hand-offs, unusually long conversations. Each confirmed failure becomes an eval case within the week, built from its trace. This is slow work, and it is where most real improvements come from. The suite grows towards the questions customers actually ask, and the next change is tested against them.

Testing a change on real traffic

An offline gain is a prediction. To confirm it, we ship the change to a share of customers and compare outcomes. Say the baseline re-contact rate is 18%, and we want to detect a drop to 16.5%. With the usual 5% significance level and 80% power, the sample needed per arm is about (1.96 + 0.84)² × (0.18 × 0.82 + 0.165 × 0.835) / 0.015², which works out to roughly 10,000 conversations per arm.

At 30,000 conversations a day split evenly, that is about two-thirds of a day of traffic, and we still run for two weeks. Traffic differs across the week, around derivative expiry days and around salary dates, and a test that saw only a calm Tuesday morning measures a calm Tuesday morning. We randomise by customer rather than by conversation, so one customer does not see both versions and blur the re-contact measure. The change goes first to a 2% canary for a day, and the test has stopping rules on the guardrail metrics: cost per conversation, p95 latency, block rate and the rate of hand-offs to humans.

Drift: what moves under a system nobody changed

Even with no deploys, three things move. Questions change, as customers arrive with new products and new events. Knowledge changes, as documents are updated or should have been. And the model can change under an alias, as described above. Each has a signal we can watch.

SignalWhat it suggestsFirst thing to check
Share of questions with no strong retrieval match risescustomers are asking about something the docs do not covercluster those questions by embedding and read the largest new cluster
Newest document in the index is days oldthe index refresh has stoppedthe ingestion job, before blaming the model
Scheduled eval run drops with no deploya dependency changed: model, judge or fixturesmodel version in the traces, then the flipped cases
Re-contact rises in one categorya real change in the product or the marketrecent policy changes and announcements in that category

The first row is how a product launch looks from the inside. The broker launches a new product on a Monday. By Wednesday, the share of questions whose best retrieval match is weak has gone from 6% to 14%. Clustering those questions shows one large new group, all about the new product, which the help centre covers in a single short page. The assistant has been answering them from general knowledge, which is exactly what we do not want. The docs team writes three articles, we add twenty eval cases from the real questions, and the signal falls back within a week. Without the signal, we would have learned about it from re-contacts a week later.

How much of this a smaller system needs

All of this is sized for 30,000 conversations a day and a regulated business. A pilot with 200 conversations a day needs less: traces, a cost alert, a kill switch that turns the assistant off and shows the help centre search instead, and someone reading every conversation that went badly. Dashboards and drift detection add little when a person can read the whole day’s failures in an hour. A/B tests need volume too; at 2,000 conversations a day, the test above needs ten days of all traffic just to reach its sample, and for low-risk changes a canary with close reading may be the better tool. The investment should grow when reading every failure stops being possible, which is also the point at which failures start reaching customers unseen.

This is the last chapter of the AI Engineering pathway. The support assistant started as a model call, gained retrieval, a tuned model, tools, a security design and an eval suite, and now has a loop that keeps it honest in production. A useful exercise is to take one AI feature you work on and write down four things: which of the trifecta’s legs it holds, how many real cases its eval suite has, what its cost per request is, and what a customer sees when its model provider is down. Any of the four you cannot answer is the next piece of work.