Natural language processing
Production NLP Systems and Monitoring
Design production NLP systems that preserve preprocessing, retrieval, decision policy, observability, security, and recovery across change.
By the end you can
- Describe the runtime architecture of classification, extraction, retrieval, and generation services
- Balance latency, throughput, quality, cost, freshness, and privacy requirements
- Monitor language-specific inputs, outputs, components, and delayed outcomes
- Plan safe deployment, rollback, incident response, and corpus or index refresh
Comparison
Two models with the same score can be different production systems
The surrounding architecture determines whether measured model quality survives contact with real traffic. An offline document pipeline, an online prediction service, a search and retrieval service and a generative language application can run identical weights and still be four different systems. Each answers to a different contract with the clock, the index and the reviewer.
That contract is itself a versioned artifact, published and revised like the model. MLCommons released MLPerf Inference v5.0 on 2 April 2025 with a new Llama 2 70B Interactive serving benchmark. One of the submitters described it this way: “This workload is based on the same Llama 2 70B model that was first introduced in MLPerf Inference v4.0, but features more stringent latency constraints of 450 ms TTFT and 40 ms TPOT (25 tokens per second per user).” MLCommons's own writeup records what the earlier budget had been: the v4.0 server latencies “were set … at 2s TTFT and 200 ms TPOT”.
Between v4.0 and v5.0 the model did not change. The 99th-percentile time-to-first-token allowance fell from 2 s to 450 ms, and the 99th-percentile time-per-output-token allowance from 200 ms to 40 ms. A "tight latency budget" is therefore not a property of a model at all. It is a number that someone published, that carries a version, and that can be tightened underneath a service which never redeployed a single weight.
Offline document pipeline
Processes files on a schedule and writes durable results.
- High throughput
- Minutes or hours of latency
- Replay and backfill support
- Example: nightly contract extraction
Online prediction service
Returns a label, span, or score during an interactive request.
- Tight latency budget
- Versioned preprocessing
- Load shedding and fallback
- Example: live intent routing
Search and retrieval service
Maintains an index and returns ranked evidence.
- Freshness pipeline
- Candidate and reranker stages
- Query and document logging
- Example: policy search
Generative language application
Combines context assembly, model inference, controls, and post-processing.
- Variable latency and cost
- Support and safety checks
- Conversation state
- Example: grounded answer drafting
Visual
A production NLP request crosses several contracts
Observability should follow the request across components rather than stopping at the model endpoint.
Each stage owns its own versions, timeouts and failure modes. An incident is diagnosed by naming which stage broke. That is only possible if a single trace carries identifiers from all five: ingress and policy, text preparation, evidence and inference, decision and response, telemetry and feedback.
1. Ingress and policy
Authentication, quotas, consent, locale, document limits, and request validation.
2. Text preparation
Decoding, normalization, language detection, segmentation, and tokenization.
3. Evidence and inference
Indexes, rules, models, caches, external tools, and versioned prompts or schemas.
4. Decision and response
Thresholds, abstention, formatting, citations, routing, and human escalation.
5. Telemetry and feedback
Traces, metrics, sampled artifacts, user corrections, labels, and incident evidence.
Version the whole language contract, not only the weights
A tokenizer change can alter sequence length, offsets, truncation, and unknown-token behavior while the model file remains identical. An index refresh can change answers without a model deployment. A label-policy change can invalidate an old threshold.
Record versions for normalization, tokenization, label schema, model, index, prompt or template, post-processing, threshold, and fallback. A release identifier should reconstruct the complete path from request to response.
The unknown-token problem is not hypothetical, and its size has been measured. Sander Land and Max Bartolo searched tokenizer vocabularies for entries the model was never meaningfully trained on, and published the result at EMNLP in 2024. What they found is a prevalence rather than an anecdote: “we detect the presence of such tokens across all tested models, with typically around 0.1–1% of the vocabulary consisting of severely under-trained tokens, although their prevalence varies significantly.” On the open OLMo v1.7 model, 191 of 49,575 tokens passed their verification threshold. A separate 2024 study, AnomaLLMy, reached the same phenomenon from outside a closed system. It reported 413 major and 65 minor anomalous tokens in GPT-4's vocabulary — the cl100k_base token set — through API access alone, for $24.39 in credits. A vocabulary is a component with its own defect rate. A defect rate is something you version and re-audit, not something you assume away.
One tokenizer was built around exactly this obligation. SentencePiece, published in 2018, guarantees that decoding inverts encoding: “Decode(Encode(Normalize(text))) = Normalize(text)”. Its authors, Taku Kudo and John Richardson, call that “lossless tokenization, in which all the information to reproduce the normalized text is preserved in the encoder’s output”. The decision that matters for a release identifier is the next one. “The model file of SentencePiece is designed to be self-contained to guarantee perfect reproducibility of the normalization and subword segmentation.” The tokenizer is a versioned artefact because its authors made it one.
Reproducibility requires the serving graph, not merely a model checksum.
Example
Signals that reveal NLP-specific degradation
Generic CPU and error-rate dashboards are necessary, but they do not show whether language behavior remains useful.
The size of that blind spot is on the record for shipped products. Magesh, Surani, Dahl, Suzgun, Manning and Ho ran a preregistered benchmark of 202 legal queries against shipped, retrieval-augmented commercial products between 22 March and 22 April 2024. Twenty of the queries were taken verbatim from LegalBench's Rule QA task, twenty verbatim from BARBRI bar-exam prep questions, and 162 were hand-written or adapted. Despite vendor claims of "hallucination-free" citations, the tools hallucinated more than 17% of the time. The two systems failed in opposite directions: “Lexis+ AI provides accurate (i.e., correct and grounded) responses on 65% of queries, while Ask Practical Law AI refuses to answer queries 62% of the time and responds accurately just 18% of the time.”
Note where Thomson Reuters' Ask Practical Law AI lost its accuracy. The study attributes its failures to the narrow document universe it retrieves over, not to the generator sitting on top of it. A refusal rate of 62% and an accuracy of 18% would both look like model behavior on a dashboard that only watched the model. Retrieval-side signals have to be monitored as their own population.
- Input composition: language, locale, script, channel, document length, token count, encoding errors, and truncation rate.
- Classification behavior: label prevalence, confidence, abstention, threshold crossings, disagreement, and slice-level correction rates.
- Extraction behavior: entity density, span length, invalid offsets, schema violations, and downstream reconciliation failures.
- Retrieval behavior: zero-result rate, candidate recall proxies, rank distribution, stale-document hits, and query reformulation — the layer that drove Ask Practical Law AI's 18% accuracy rather than its generator.
- Generation behavior: refusal, unsupported claim, citation mismatch, repair request, token usage, and human edit distance; a 62% refusal rate is a product outcome, not only a safety setting.
- Outcome behavior: task completion, escalation, complaint, reversal, reviewer workload, and delayed correctness labels.
Analogy
A restaurant service rather than a recipe
A restaurant depends on ingredient sourcing, storage, preparation, timing, serving, allergy controls, and customer feedback. A good recipe cannot compensate for spoiled ingredients or a missing safety process.
Software can reproduce an identical artifact, while language traffic and external knowledge keep changing. Model quality is still only one dependency in the delivered experience.
Operate the complete service chain, not an isolated model benchmark.
Key idea
Language telemetry can become a second privacy incident
Raw prompts, messages, transcripts, retrieved passages, and generated replies may contain personal or confidential information. Logging everything for debugging can create a larger, less controlled copy of the original risk.
Use purpose-specific sampling, field minimization, access control, encryption, retention limits, redaction where appropriate, and secure incident capture. Preserve enough evidence to debug without treating unrestricted text retention as observability.
European law states the ceiling as a principle rather than a practice. Personal data must be “adequate, relevant and limited to what is necessary”. That is Article 5(1)(c) of the GDPR, and the limit is set “in relation to the purposes for which they are processed (‘data minimisation’)”. Article 5(1)(e) requires it to be “kept in a form which permits identification of data subjects for no longer than is necessary”. Again the yardstick is “the purposes for which the personal data are processed … (‘storage limitation’)”. Article 5(2) closes the loop. The controller “shall be responsible for, and be able to demonstrate compliance with” those principles. A debugging archive of raw transcripts is a processing purpose. It has to be declared, bounded and defended like any other.
The same body of law sets a floor pointing the other way. The AI Act, Regulation (EU) 2024/1689, was published in the Official Journal on 12 July 2024. Article 12(1) requires high-risk AI systems to “technically allow for the automatic recording of events (logs) over the lifetime of the system”. Article 19(1) says how long those logs then live: “Without prejudice to applicable Union or national law, the logs shall be kept for a period appropriate to the intended purpose of the high-risk AI system, of at least six months, unless provided otherwise in the applicable Union or national law, in particular in Union law on the protection of personal data.” A team running a high-risk language system has a minimum it must keep and a maximum it must not exceed. The design work is deciding which fields can satisfy both at once.
What the ceiling looks like when the default is wrong is a matter of public record. On 31 May 2023 the FTC and DOJ charged Amazon with violating the COPPA Rule over Alexa. The complaint alleged that Amazon retained children's voice recordings indefinitely by default, kept transcripts of what children said even after parents requested deletion, and used the retained data to help improve its Alexa algorithm. Samuel Levine, Director of the FTC's Bureau of Consumer Protection, put it this way: “Amazon's history of misleading parents, keeping children's recordings indefinitely, and flouting parents' deletion requests violated COPPA and sacrificed privacy for profits”. Amazon agreed to a permanent injunction and a $25 million civil penalty.
Amazon's own response describes the controls a retention policy is actually made of. Customers can choose not to have recordings and transcripts saved at all, or to auto-delete on a three- or 18-month cycle, and child profiles inactive for more than 18 months would be removed. "Retention limits" is not a value. It is a named period, an owner, and a default — and the default is the part that was charged.
Log retention has a legal floor and a legal ceiling, and observability has to be designed to live between them.
Steps
Release a language-system change safely
A change may involve code, model, tokenizer, labels, corpus, index, prompt, or policy.
For a whole class of systems, the last step of this sequence is not a good habit but a documented obligation that outlives the release. Article 72 of the AI Act requires providers of high-risk AI systems to establish and document a post-market monitoring system running throughout the system's lifetime, based on a written plan that forms part of the technical documentation under Annex IV. Article 72(2) says what that system has to do: “The post-market monitoring system shall actively and systematically collect, document and analyse relevant data which may be provided by deployers or which may be collected through other sources on the performance of high-risk AI systems throughout their lifetime, and which allow the provider to evaluate the continuous compliance of AI systems with the requirements set out in Chapter III, Section 2.”
The template is still being drafted. Regulation (EU) 2026/1744 of 8 July 2026, the Digital Omnibus on AI, replaced Article 72(3) and applies from 27 July 2026. The provision now in force gives the Commission until 2 September 2027 to adopt guidance, including a template for the post-market monitoring plan, taking utmost account of the opinion of the Board. The five steps below are the shape of the evidence such a plan has to produce, whether or not the template has arrived.
1. Rebuild a comparable evaluation
Use representative traffic, fixed regressions, challenge suites, and newly affected slices.
2. Verify artifact compatibility
Check schemas, offsets, token limits, index versions, and fallback behavior.
3. Run shadow or replay tests
Compare candidate behavior without exposing users to its decisions.
4. Limit initial exposure
Use canary traffic, protected cohorts, quotas, and clear rollback triggers.
5. Review outcomes and incidents
Inspect examples and delayed labels before expanding or retiring the prior version.
Indexes, labels, and language policies age at different rates
A retrieval system may have to ingest documents hourly while its encoder changes quarterly. A classifier can remain statistically stable even though a policy redefinition makes its labels obsolete.
Assign separate freshness objectives and ownership to source documents, annotations, features, indexes, models, thresholds, and evaluation sets. Rebuild only the components that the evidence justifies.
Freshness is a set of component obligations, not one timestamp on the application.
Steps
Respond to an NLP incident with evidence preservation
The immediate goal is containment. The lasting goal is a safer system and a test that would have caught the failure.
Containment is measured with a clock and a blast radius, and there is a canonical measurement of both. Microsoft released the Tay chat bot on Twitter on 23 March 2016. Gina Neff and Peter Nagy date the end of it precisely: “Sixteen hours after Tay started interacting with and learning from Twitter users, Microsoft took Tay offline.” Inside that window Tay had already posted more than 93,000 tweets. A reactivation seven days later failed as well.
Sixteen hours is not slow by the standards of 2016. The point is that the blast radius was 93,000 outputs wide before the first containment action, and that the system had been tested. Peter Lee, Corporate Vice President of Microsoft Research, wrote on 25 March 2016: "We stress-tested Tay under a variety of conditions, specifically to make interacting with Tay a positive experience". He also wrote: "Unfortunately, in the first 24 hours of coming online, a coordinated attack by a subset of people exploited a vulnerability in Tay". Pre-release testing had happened. It did not cover the case that mattered. His closing commitment is the sentence an NLP runbook should be able to produce on demand: "Tay is now offline and we'll look to bring Tay back only when we are confident we can better anticipate malicious intent that conflicts with our principles and values." Containment first. Restoration only against a named, testable condition.
1. Contain consequence
Disable the affected action, route to fallback, narrow traffic, or restore the previous release.
2. Preserve a minimal evidence set
Capture versions, trace identifiers, inputs under policy, outputs, and downstream decisions.
3. Locate the failing contract
Separate source, preprocessing, index, model, policy, interface, and human-review causes.
4. Repair and replay
Test the smallest defensible change against incident examples and ordinary traffic.
5. Add durable prevention
Update regression suites, monitoring, documentation, ownership, and runbooks.
Draw the serving graph for one NLP feature
Include every transformation and decision from ingress to final action. Label versioned artifacts, timeouts, caches, external dependencies, logs, privacy boundaries, fallback, and human handoff.
Then choose six quality signals and six operational signals. For each, define its population, aggregation window, alert threshold, likely false alarm, and incident owner. Finish by writing down two numbers your diagram does not yet contain: the latency budget the service is held to, and the retention period each logged field is kept for.
A production diagram is complete only when it shows how the system fails and recovers.
Key takeaways
- Production NLP systems combine ingress policy, preprocessing, evidence, inference, decision logic, response construction, telemetry, and fallback — and even the latency budget is a published artifact, tightened from 2 s to 450 ms p99 TTFT between MLPerf Inference v4.0 and v5.0 with no change to the model.
- Release reproducibility requires versions for tokenizers, schemas, indexes, prompts, thresholds, post-processing, and models; Land and Bartolo found severely under-trained tokens in every model they tested, typically 0.1–1% of the vocabulary, and 191 of 49,575 on OLMo v1.7.
- Language-quality monitoring should measure input composition, component behavior, downstream decisions, user corrections, and delayed outcomes: shipped legal RAG products hallucinated more than 17% of the time, with one refusing 62% of queries and answering accurately on 18%.
- Raw-text telemetry sits between the GDPR Article 5 storage-limitation ceiling and the AI Act Article 19(1) floor of at least six months; the FTC and DOJ complaint over indefinitely retained children's Alexa recordings ended in a $25 million civil penalty.
- Safe deployment uses comparable evaluation, compatibility checks, replay or shadowing, limited exposure, rollback triggers, and outcome review — which Article 72 of the AI Act turns into a documented post-market monitoring plan filed under Annex IV.
- An incident process should contain harm, preserve minimal evidence, locate the failing contract, replay the repair, and add durable prevention; Tay was offline sixteen hours after launch, after more than 93,000 tweets, despite having been stress-tested.