← Inference From First Principles

From Inference Loop to API

Putting the engine behind an HTTP interface and measuring what the boundary has to decide: where a request's time goes, how a character limit fails as a token budget, which errors a client can act on, how a schema may change, and what a shared backend does to concurrent callers.

A deliberately lenient HTTP service was sent twenty-nine awkward requests, including malformed JSON, an empty prompt, an unknown option, a non-finite temperature, and a prompt containing 4,000 emoji. Eight requests received HTTP 200. Four of these successes silently changed what the caller specified: the string "5", float 5.0, and Boolean true were coerced into integer token limits, while the unknown field max_tokens: 2 was ignored and the existing field’s default produced sixteen tokens. Four other requests produced HTTP 500. None of the twenty-one errors followed a service-defined envelope; the framework returned detail objects in differing shapes. These are observations from the Chapter 25 probe list, not a general FastAPI failure rate.

The hardened variant used the same underlying inference engine. On the same twenty-nine probes it returned HTTP 200 four times, including one accepted request that carried a warning about an ineffective parameter. The remaining twenty-five received a consistent service-defined error envelope containing a request id, an error type, a message, and (when meaningful) the offending parameter. None returned HTTP 500. The comparison isolates the consequences of API validation and error policy for this test set; it does not establish that an unauthenticated, single-worker laboratory service is production-ready.

The difference is architectural: between an inference loop that produces tokens and a client on a network, the service must decide how to interpret inputs, enforce budgets, preserve model and sampler identity, report failures, and safely share state. This chapter measures those decisions rather than treating HTTP as a thin wrapper. The resulting design provides a working foundation for Part 5, but security, timeouts, cancellation, overload control, and streaming remain explicit exclusions.

The question

Chapter 6 defined Request, Result, and the backend boundary; Chapter 24 built a rule-based admission example for model and runtime capabilities. Neither directly addresses a remote client that can send malformed or contradictory JSON, an oversized body, or several requests sharing state. The API needs both checks: schema validation establishes whether the request is well-formed, and admission establishes whether the selected backend can execute the requested work. This chapter implements strict schema and token-budget checks for one GPT-2 backend; it does not yet incorporate the full Chapter 24 capability policy.

There are five questions. What portion of a real HTTP request belongs to parsing, tokenisation, inference, and transport? Can a character cap enforce a model’s token limit? How do errors become predictable enough for a client to handle? Which schema changes preserve old-client behaviour? And can the service preserve the engine’s tokens, usage, and identity when it crosses a process boundary or shares a cached backend? Each requires a different measurement; a fast success response alone answers none of them.

Where this sits

Part 5 starts at the network boundary. The Chapter 6 engine and Chapter 10 cached backend supply the computation; Chapter 24 supplies the principle that unsupported or ineffective options must not be silently accepted. This chapter supplies request parsing, an independent token budget, response provenance, stable errors, and a simple serialised engine call. The actual service is implemented in examples/ch25/service_lab.py; examples/ch25/api.py remains the starter example. This is the bridge to Chapter 26’s admission under load and Chapter 27’s incremental streaming protocol.

Chapter 9 measured prefill time from the start of the model call and reserved network-visible time to first token for a later service chapter. Here the experiment times a complete, non-streaming request that generates exactly one token, and records the engine’s prefill separately. That is a useful latency surrogate, but it is not the streaming time-to-first-byte or time-to-first-token of a longer response: the response is only sent after generation is complete. The service uses one process and a lock around one cached backend. Its single-client lifecycle experiment has negligible queueing; it does not characterise admission or fairness when many callers arrive.

The scope is deliberately controlled: GPT-2 small (124M parameters), a Chapter 10 cached backend, a FastAPI/uvicorn process, loopback HTTP, and no authentication or TLS. GPU experiments used the local RTX 2060; selected error and body-size probes ran on one CPU thread. Results describe this specified environment. No command in this chapter should be interpreted as a publicly deployable service configuration.

A request’s life

The path is: receive HTTP headers and body, parse and validate JSON, tokenise the prompt, check budgets, acquire the engine lock, run inference, construct the typed response, and serialise it to the wire. The request id is generated when the ASGI request enters the middleware. The Lab’s timing object reports parse/validate, tokenisation, lock wait, engine prefill, engine decode, and response-building time. Its Server-Timing: total value is attached when the response-start header is sent, rather than after the last response byte, so it is best read as server time to response headers, not complete server connection time.

I measured the route from a separate client process over a persistent loopback HTTP connection: twenty requests per output-length row, after three warm-ups. The server ran GPT-2 small on the RTX 2060. Values below are independent medians in milliseconds; medians of stages are not required to add exactly to a median round trip. The transport column is derived from client round-trip and server-header timings, so it also includes any uninstrumented server tail and client processing, not just network propagation.

Generated tokens Client round trip Parse and validate Tokenise Engine prefill Engine decode Build response Unattributed client/server difference
1 22.7 0.38 0.21 19.0 0.74 0.05 about 1.3
8 153.2 0.33 0.19 17.8 131.9 0.05 about 1.2
32 620.8 0.35 0.19 18.3 600.7 0.05 about 1.1
128 2,460.4 0.36 0.18 18.0 2,438.9 0.05 about 1.2

The measurements have three implications. First, the measured service boundary is small under these conditions. Parse/validation, tokenisation, and building the response each take fractions of a millisecond; the difference between HTTP round trip and the Server-Timing measurement is about 1–1.3 ms. Treating all of this as “network overhead” would be inaccurate, and the claim applies only to loopback, a persistent connection, a small prompt, and a single caller. Second, generation length dominates. Engine decode rises from 0.74 ms for the one-token case to roughly 2.44 s for 128 generated tokens; the cached backend’s short prefill remains around 18–19 ms. Third, the ratio is not an end-to-end service SLA. The result excludes congestion, remote transport, TLS, prompt variation, and queued work. On this shared card an earlier otherwise clean 128-token run had a 2.89 s median rather than 2.46 s. That variation is large compared with the measured sub-millisecond parsing stage, so a latency report should retain both the stage definition and the workload context.

The one-token request finished at the client in 22.7 ms, while the engine’s recorded prefill took 19.0 ms and its remaining decode stage 0.74 ms. The gap contains validation, tokenisation, framework and response work, and transport. It is the closest measurement here to a client-observed first-token latency, but it is still the latency of a complete non-streaming one-token response. A streaming endpoint must separately measure when the first token becomes available, when bytes are flushed, and when the client receives them; Chapter 27 takes up that experiment.

Request lifecycle

Connecting is not free, and the name matters

Connection setup can overwhelm these sub-millisecond stages. On the tested Windows host, raw TCP connect to 127.0.0.1 had a 0.64 ms median, while localhost had a 2,036 ms median. An HTTP /health request using a new connection showed a similar 2,047 ms versus 1.61 ms contrast. On already established keep-alive connections, the medians were only 1.15 and 1.36 ms respectively. These are unusual host-specific measurements, not a general rule that localhost is slow.

The supporting observations narrow the hypothesis. The host’s resolver listed ::1 before 127.0.0.1; the service was bound only to IPv4; and attempts to connect to an unused port took about two seconds on either address. An IPv6-first attempt followed by IPv4 fallback is consistent with the observed delay, but no socket trace established that exact sequence. Binding both address families or changing the resolver/client configuration may alter the result. For reproducibility, the lab commands use 127.0.0.1, and anyone applying the lesson should first measure DNS resolution, connection attempts, and keep-alive behaviour on their own deployment.

The event loop and the health check

A service must respond to health checks while generations are active. FastAPI ordinarily runs a plain def endpoint in a worker thread, whereas an async def endpoint runs on the event loop. Calling the same blocking generation code directly from an async def handler prevents that loop from processing unrelated requests. The Lab exposes both implementations solely for comparison. During three generations of 256 tokens per route, a second client issued /health requests with a short delay between polls; the table measures their observed responses, not real load-balancer decisions.

Route Generation Health checks answered Median Worst
plain def 5.8 to 6.1 s 266 to 277 2.1 to 2.2 ms 4.8 to 5.9 ms
async def calling the same code 4.9 to 5.6 s 9 to 12 1.8 to 2.0 ms 4.9 to 5.6 s

When the handler executed blocking generation directly on the event loop, a health request sometimes waited almost the entire 4.9–5.6-second generation. The low median of roughly 2 ms is misleading: only 9–12 checks completed during each such run, compared with 266–277 for the worker-thread route. A real orchestrator with a shorter probe timeout could therefore mark a responsive-but-busy process as unhealthy. The Lab separates /health (ASGI process responds) from /ready (backend loaded; otherwise 503 with Retry-After) and uses a plain def generation handler. This prevents the demonstrated event-loop blockage; it does not make a locked single backend concurrent, guarantee health under threadpool saturation, or prove the service is ready to accept work within a latency budget.

The contract

Requests

The first service contract is about the exact JSON types and allowed fields. Pydantic’s ordinary coercions and treatment of unknown fields can be useful in application code but are hazardous when the values control GPU work or billing. The hardened request model sets strict=True and extra="forbid", bounds strings and numeric values, and declares stop strings explicitly. The example is the actual request schema in service_lab.py (the following code remains unchanged), rather than a generic sketch.

class GenerateRequest(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    prompt: str = Field(min_length=1, max_length=4000)
    max_new_tokens: int = Field(16, ge=1, le=256)
    temperature: float = Field(0.0, ge=0.0, le=2.0)   # 0 means greedy
    top_k: Optional[int] = Field(None, ge=1, le=1000)
    top_p: Optional[float] = Field(None, gt=0.0, le=1.0)
    seed: int = Field(0, ge=0, lt=2**31)
    stop: List[Annotated[str, StringConstraints(min_length=1, max_length=32)]] = Field(default_factory=list, max_length=4)

The lenient variant deliberately restores coercion and ignores unknown fields. It accepted string "5", float 5.0, and Boolean true in a field intended to be an integer; it also interpreted { "max_tokens": 2 } as though that field had never been sent, generating the default sixteen tokens. The hardened request refused each with HTTP 422 and a named parameter. This is the HTTP-level analogue of Chapter 24’s rule about silent setting changes. The lesson is not that every coercion is always wrong; it is that an inference API must choose, document, and test which coercions it permits, rather than inherit those choices accidentally.

Strict input types are necessary but not sufficient validation. Pydantic accepts a JSON integer as a valid float for temperature; that deliberate compatibility is different from accepting a Boolean as a token count. A whitespace-only prompt or a NUL-containing string is permitted by this laboratory policy because it passes the declared checks and the toy input path can process it. Neither should be inferred to be safe or useful for every provider, tokenizer, log sink, or downstream client. Input encoding, control characters, content policies, request-size limits, and special-token semantics require their own contract tests.

For this API, temperature: 0 explicitly selects greedy decoding. In that mode top_k, top_p, and a non-zero random seed cannot affect sampling; the implementation returns a warning rather than silently ignoring these otherwise valid fields. For example, a request with top_k at temperature zero receives a warning naming the ineffective option. A stricter provider could reject the combination instead. The invariant to preserve is that a requested feature either has a defined effect or is identified as ineffective in a machine-readable or documented response—not that this one warning policy is universal.

Responses

A generation response includes both the model’s output and the evidence needed to reproduce or audit it: an id that matches the X-Request-Id header; a backend manifest digest, model name, and optional snapshot; text and the emitted token_ids; a finish_reason (length, stop, or eos); prompt, completion, and total token usage; warnings; and the version 1.1 timing object. A SHA-256 hash of the manifest identifies that manifest’s contents; it is only an artefact-integrity guarantee if the manifest itself binds trustworthy weight, tokenizer, configuration, and template digests. The Server-Timing response header uses W3C-defined syntax, but the current total metric stops at HTTP response start, not at the final byte. The W3C document consulted was a Working Draft in April 2026.

token_ids is not decorative. The engine emits token ids; the server decodes them to text for convenience. Re-tokenising that text may not reproduce the original sequence, as the later fidelity experiment shows. A client needing exact continuation should preserve the token ids and the associated tokenizer/version—not assume that decoded text uniquely identifies the model’s output tokens. Including ids increases response size, a trade-off the service has not benchmarked at scale.

Changing the contract

“Adding fields is safer than removing them” is only true after specifying who must stay compatible. An old caller needs its formerly valid request to remain valid and to retain its meaning. An old response reader needs every new response to remain intelligible under its rules. Those are different directions of schema containment, and an unknown-field-intolerant reader can be broken by an added response field. The following classifier is a small test of these principles rather than a proof of compatibility for arbitrary JSON Schema or OpenAPI documents.

For requests, the new server must continue to accept the old clients’ values, omitted optional fields, and defaults with the same semantics: raising a maximum or adding an optional field can be safe, whereas lowering a maximum, requiring a new field, or silently changing a default is not. For responses, the values a new server may emit must fit the old reader’s domain: adding an enum member can break a client with exhaustive handling, while deleting a possible enum member need not. diff_schemas implements selected structural checks—types, bounds, required fields, defaults, enum domains, and some nested object fields—over the JSON Schema generated by Pydantic. It does not exhaustively decide the semantics of all schema constructs, optionality conventions, security changes, or behavioural dependencies.

I compared the classifier with a small behavioural harness: eleven request edits and eight response edits built from miniature schemas, then representative old requests were submitted to the changed models and new responses to old readers. The classifier agreed with the harness on 19 of 19 constructed changes. This establishes agreement for the chosen cases. It does not turn a finite sample of requests into a proof that every value accepted by the old schema remains valid, or establish complete handling of arbitrary nested arrays, oneOf, union discriminators, and application-level invariants.

Request change Old requests still work and mean the same?
optional field added yes
max_new_tokens limit 256 to 512 yes
prompt maximum 4,000 to 8,000 yes
required field added no
max_new_tokens limit lowered to 128 no
prompt renamed to input no
temperature changed from number to string no
temperature default 0.0 to 1.0 no (the request is accepted and means something different)
max_new_tokens made required no
prompt minimum raised to 10 no
temperature removed no
Response change A tolerant v1 client reads it? A v1 client that rejects unknown fields reads it?
a field added yes no
a value removed from finish_reason yes yes
a value added to finish_reason no no
a field removed no no
text renamed to output no no
completion_tokens made a float no no
completion_tokens made optional no no
id changed to an integer no no

The response-field example is decisive: a client that ignores fields it does not know accepts an added timing object, but a client configured to forbid unknown fields rejects it. The Lab’s actual response v1-to-v1.1 change adds just that one field and is compatible under the tolerant-reader assumption used in the test. A producer cannot declare this compatible for all imaginable clients. Versioning policy therefore needs to state what consumers must tolerate, which fields are optional, and whether extra enum values or changed defaults count as breaking changes.

Anthropic’s API error documentation similarly warns clients that new error type values may be introduced. That is a provider’s contract statement, not evidence about its scheduler, backend, or implementation. It illustrates the general point: clients must reserve an unknown-type branch if the producer documents an expandable vocabulary. The Lab’s schema classifier does not inspect another provider’s response models; it only tests its own simplified request and response schemas.

Budgets

A request should be rejected before generation when its prompt plus reserved completion cannot fit the backend’s limits. But counting characters does not count tokens, and a schema that bounds prompt to 4,000 characters only bounds a Unicode string’s length under that convention. I measured token counts with the GPT-2 byte-level BPE tokenizer for samples of exactly 1,000 Python string characters. The source run retained four qualifying English-prose samples and twenty-nine Python-source samples, not forty of each as the initial prose suggested. Other rows are one repeated-character or constructed-symbol sample each.

1,000 characters of GPT-2 token count Samples
English prose from this book 217–243 4
Python source from this repository 260–528 29
One repeated letter 250 1
Newlines 500 1
Spaces 1,000 1
Repeated é 1,000 1
Repeated Cyrillic character 2,000 1
Repeated emoji 2,000 1
Repeated CJK character 3,000 1
Constructed mixed rare symbols 2,486 1

A 4,000-character limit admits very different GPT-2 token counts: 972 for one repeated prose example, 1,532 for the selected source-code example, 4,000 spaces, 8,000 instances of the tested Cyrillic character or emoji, and 12,000 instances of the tested CJK character. GPT-2 can represent only 1,024 positions. If the largest tested rate (three tokens per character) were treated as a fixed bound and 256 positions reserved for the answer, a conservative cap would be 256 characters. That would reject much ordinary prose that otherwise fits. The three-tokens-per-character number is the maximum among these test strings, not a proven upper bound for all Unicode text or tokenizers. The operational rule is to enforce bytes for transport protection and actual tokens for model context and compute protection; neither substitutes for the other.

Character vs token budget

The hardened service therefore tokenises before calling the engine and uses check_budget(prompt_tokens, max_new_tokens, limits). Its Limits deliberately distinguish a prompt-token cap (1,000 in this laboratory) from a total-position cap (1,024). A prompt of 901 tokens plus 256 reserved new tokens exceeds the latter by 133; the error names max_new_tokens and gives the arithmetic. These are reservation checks, not a promise that every generation reaches the maximum. The pure helper checks the prompt limit first, then the total; an earlier default of 768 prompt tokens would have made the second branch unreachable for any allowed completion length, which the probes exposed. For multiple models, the context and other limits should be derived from a versioned model/runner capability record rather than hand-entered in an HTTP route.

The danger of missing that check was measured in one CPU run, with the Chapter 10 cached GPT-2 backend. The lenient service accepted a 901-token prompt requesting another 256 tokens, generated until the learned positional embedding reached position 1,024, then raised IndexError; the client saw HTTP 500 after 12.06 seconds. The hardened service returned HTTP 422 context_length_exceeded after 9.3 ms without entering generation. This is a single-run CPU case, not a speed-up benchmark or general rejection-latency SLA. The failure has a distinct root cause from a body that is too large to read; that earlier protection happens in middleware, before JSON decoding.

In this laboratory, Limits.context_window is configured manually for GPT-2. The next step is to connect it to Chapter 24’s model fingerprint and runtime facts, accounting for the actual input tokenisation, cache policy, reserved completion, and per-request memory estimate. Rejecting overlong requests without allocating GPU state should be a tested property. This chapter’s existing check_budget is a useful but deliberately narrow implementation of that policy.

Errors

What a client can act on

A useful error contract answers three questions: can the caller retry, what can the caller change, and how can an operator find the event? HTTP status and retry guidance address the first; a stable error type and param address the second; the request id connects the client response to server-side diagnostics. The Lab uses a single error envelope for its controlled failures. An example of the actual structure is shown below. Clients must not depend on prose message wording alone as a stable interface.

{"error": {"type": "context_length_exceeded", "message": "901 prompt tokens plus 256 new tokens is 1157; the context window is 1024", "param": "max_new_tokens", "request_id": "gen-..."}}

Error envelope

The Lab maps parse failure to 400 (malformed_json), excessive request body to 413 (payload_too_large), unsupported content type to 415, and semantically invalid/unsupported inputs to 422 (invalid_request, unsupported_input, or context_length_exceeded). It returns 404 and 405 for path and method mistakes, 503 with Retry-After while the model is not ready, and a sanitised 500 (internal_error) for unanticipated exceptions. These rules are choices made by this API. The request id is attached to every response the outer middleware can reach; an exception before the middleware runs, a crashed worker, or a closed socket is not guaranteed to produce an envelope.

RFC 9110 defines the semantics of these HTTP statuses: 413 for content too large to process, 415 for an unsupported representation format, 422 for syntactically understood content whose instructions cannot be processed, and 503 for temporary service unavailability (which may carry Retry-After). Choosing 422 for schema validation follows FastAPI’s convention, not a unique mandate of HTTP; another documented API can consistently choose 400. Anthropic’s published interface illustrates that alternative, using invalid_request_error for many 400s, a documented request id, and a 413 size limit for its Messages API. These are statements of external interface behaviour, not claims about Anthropic’s internal implementation or about a universally prescribed error taxonomy. A client should branch on the documented provider contract rather than assume the Lab’s mapping is universal.

What the defaults did

The same twenty-nine malformed, contradictory, and edge-case requests were sent to both services. The following table shows selected cases; the full probe list and status counts are recorded in research/ch25/results.json. The baseline was deliberately lenient rather than an otherwise identical production-quality FastAPI implementation.

Probe First-draft service Hardened service
malformed JSON 422, detail list 400 malformed_json
valid JSON as text/plain 422, “valid dictionary” 415 unsupported_media_type
max_new_tokens is "5", 5.0 or true 200, coerced 422 invalid_request, param max_new_tokens
misspelt option max_tokens 200, 16 tokens not 2 422, param max_tokens
top_k with temperature 0 200, silent 200 with a warning
temperature NaN 500 422, param temperature
prompt with a lone surrogate 500 422, param prompt
prompt over the character cap 422, 4,152 bytes 422, 144 bytes
4,000 emoji 500 (IndexError) 422 context_length_exceeded
901-token prompt, 256 new tokens 500 after 12 s 422 in 9 ms
GET on the POST route 405, a bare detail string 405 method_not_allowed, with Allow

Across the twenty-nine awkward requests, excluding the additional valid control request, the lenient service produced eight 200s, fourteen 422s, four 500s, one 404, and two 405s; its twenty-one error responses did not share the Lab’s envelope. The hardened service produced four 200s, twenty 422s, one 400, one 404, two 405s, and one 415; all twenty-five errors used the same envelope. The absence of 500s in twenty-nine probes is evidence about this test set only, not proof that the application cannot return 500 under novel inputs or hardware failures. Neither service exposed a traceback or filesystem path in the tested client-visible bodies.

Two lenient-service 500s came from its error-reporting path. In this measured FastAPI/Pydantic version, an invalid non-finite number was included in the default validation error object, and attempting to JSON-serialise that object failed. A lone Unicode surrogate likewise entered an error representation that failed UTF-8 encoding. The framework had identified invalid input, but the default 422 response could not be sent. The hardened handler builds a small envelope from a controlled message and parameter name without echoing the submitted value, so these inputs produced 422 instead. The result is a reproducible property of the measured stack (FastAPI 0.136.3), not a claim about every framework release. Raw validation objects and request bodies may also contain sensitive data, another reason to keep them out of client-visible error bodies.

Large bodies

Field-size validation takes place after an HTTP request body has been read and parsed. To show the distinction, I submitted bodies from 100 KiB to 100 MiB to the lenient service in a separate CPU process. With no early body limit, both Content-Length and chunked framing were fully ingested, then rejected with a large 422 error that echoed the input. At 100 MiB the HTTP response was about 104,857,751 bytes, server resident memory grew by roughly 400 MiB, and the round trip took about 1.4–1.5 seconds. At 20 MiB the response was about 20,971,671 bytes and the process grew 76–82 MiB. This demonstrates amplification through validation error formatting—not through generation or the GPU.

The hardened service adds an ASGI BodyLimit middleware with a 64 KiB cap. It checks a declared Content-Length before parsing and counts received chunks when no length is available. A 100 KiB body yielded a compact 413 with either framing, and measured server RSS did not grow. For bodies of 1 MiB or more, however, the test client did not receive the 413 at all: httpx reported ReadError while the service still avoided measurable memory growth. Thus the implementation establishes a bounded server-ingestion path for these probes, not reliable client-visible error delivery for arbitrarily large uploads or all transport behaviours.

An early server response while the client is still sending data is a plausible explanation for those connection resets, and RFC 9110 allows a server to close a connection when it rejects oversized content. The packet-level sequence was not captured, so the mechanism remains a hypothesis. The operational conclusion is firmer: enforce upload limits at the reverse proxy or ingress as well as inside the app; test both declared and streaming bodies; define what callers should do on a connection reset; and never rely on a request-model max_length as a memory safety limit. This service has no reverse proxy, multipart handling, backpressure policy, or client-disconnect test.

What crosses the boundary

Is the answer the engine’s answer?

“The engine succeeded” does not imply “the client received the same artefact”. I compared forty book-derived prompts through loopback HTTP with calls to the same GPT-2 engine in another process, generating up to 32 tokens each, once greedily and once with seeded sampling. The service and direct path used the same model, tokenizer and sampling scheme. This isolates the serialization and service boundary for those requests, but it is not a test of distributed replicas, different library builds, or long-lived streaming clients.

All 40/40 greedy and 40/40 sampled HTTP results matched the direct engine in token ids and decoded text. Prompt-token, completion-token, and total-token usage also matched an independently computed count in all eighty responses. One sampled response stopped with eos; the rest stopped by length. The result supports fidelity of this API wrapper on this input set and with the same model and seed semantics, rather than a general guarantee that independently configured inference systems will produce identical sampled traces.

Text and token ids are not interchangeable records. When the returned text was tokenised again, its ids matched the generated sequence in 39/40 greedy cases and 33/40 sampled cases. The same match counts held when the original prompt and returned text were concatenated and re-tokenised. Because a tokenizer can admit multiple token sequences that decode to the same string, non-canonical encodings are one plausible explanation; the failing sequences were not examined, so that mechanism remains unverified here. The direct consequence does not depend on it: if a client needs an exact token continuation, it must preserve the emitted ids and tokenizer identity. Re-sending only text can lead to a different token sequence even though the visible characters look identical. The API does not yet test whether the seven sampled mismatches affect a multi-turn model output or whether stop-string trimming introduces additional differences.

One engine, many callers

This service exposes one worker process with threaded synchronous routes and a single stateful cached backend. The Chapter 10 backend’s next_logits(ids) contract checks whether the current cache corresponds to the supplied prefix, then extends or resets it. The calculation is correct for serial calls, but the underlying cache and engine are mutable shared state. Threadpool concurrency means two HTTP handlers can enter the same backend unless the service serialises the engine call. The Lab therefore places a lock around engine.generate; this protects correctness locally but creates a whole-request critical section.

The hazard was measured directly against the backend, not via HTTP. Four threads each issued a different 24-token greedy generation over twelve rounds (48 requests), and the outputs were compared with solo runs. Without a lock, every request either threw RuntimeError or produced the wrong token sequence in each of three recorded runs: the wrong-without-error counts were 4, 13, and 15 of 48, with the remainder raising exceptions. With the lock, all 48 requests matched the solo result in each run. These are observations for one cached backend and deterministic workload; they should not be generalised to every backend or scheduler.

The experiment justifies serialising calls to this shared backend and quantifies the danger of unsynchronised cache mutation. It does not validate the HTTP lock under real concurrent clients, measure queue time, or establish that one global lock is the best serving design. With a whole-generation lock, requests wait behind the entire prompt-and-decode operation. Chapter 26 must replace or refine that arrangement with explicit scheduling, admission and fairness while preserving isolation of request-specific KV state. The fact that the earlier single-client lifecycle rows show near-zero queue time says nothing about this concurrent workload.

What the numbers do not show

  • One backend and one worker. The system under test is GPT-2 small with a shared cached engine. Its per-token cost, and hence the apparent share of HTTP overhead, will vary with model size, batch size and output length. The observed interface stages are not an environment-independent 2 ms ceiling.
  • Loopback on Windows 11. Transport, IPv4/IPv6 resolution, the localhost anomaly, and resets on oversized bodies may differ on Linux, cloud networks, proxies, TLS and other client libraries.
  • A narrow schema classifier. Nineteen chosen changes agreed with a miniature client harness. The classifier is not a sound general-purpose JSON Schema compatibility checker and does not establish semantic invariants or arbitrary oneOf/array/union rules.
  • A finite fault sample. Twenty-nine awkward requests exposed lenient-service weaknesses. No result proves the hardened service has zero unhandled errors outside those requests.
  • Small and partially repeated tokenisation samples. Four book-prose and 29 source-code cases generated the measured ranges; individual non-ASCII rows are synthetic repeated strings, not universal maximum tokens-per-character guarantees.
  • An unstable shared GPU. An earlier clean lifecycle run showed about 15% timing variation at 128 tokens; stage results must include environment and collection conditions.
  • Header-start timing. The Server-Timing total value is stamped at response start, so client round trip minus that metric is not a pure network time.
  • No load experiment through HTTP. The lifecycle used one client. Concurrency failures and their lock-based correction were measured directly on backend threads, not through multiple HTTP requests.
  • Not a network-hardened service. Authentication, TLS, request cancellation and disconnects, reverse proxies, rate limiting, bounded queues, retries/idempotency, streaming and multi-worker state isolation were neither implemented nor qualified.

Inference Lab increment

The Inference Lab now has a real HTTP service for one backend. build_app(backend, limits, hardened=True) produces a FastAPI application; hardened=False deliberately restores selected first-draft behaviours for comparison. The production-facing interpretation is limited: no authentication, TLS, bounded request queue, timeout/cancellation contract, or independent per-request cache state has been established. The following components are actually implemented and unit-tested to the extent stated:

  • GenerateRequest and GenerateResponse / GenerateResponseV1_1: strict request and versioned response models, including usage, manifest-based provenance, token ids, warnings and stage timings.
  • check_budget and ignored_parameter_warnings: prompt and total-token preflight checks, plus disclosure of ineffective sampling settings.
  • ApiError, envelope and exception handlers: a defined error taxonomy that avoids echoing invalid input; the envelope covers errors the middleware and handlers can reach.
  • Stamp and BodyLimit: request ids and response-start Server-Timing; a declared-or-counted request-body cap, with client connection resets observed for large uploads.
  • diff_schemas: a limited Pydantic JSON Schema compatibility classifier, exercised against nineteen hand-selected request/response changes.
  • ServerProc: a real subprocess/server harness so measured HTTP requests traverse a socket.
  • Commands: budget, errors, compat, body, fidelity, lifecycle, blocking, race, and serve.

Run the service on local loopback only, with cached GPT-2 weights and the Chapter 25 example dependencies installed. The endpoint below is an unauthenticated laboratory service, not an instruction to expose port 8000 to the public internet. On the measured Windows machine 127.0.0.1 avoids the observed localhost connection anomaly.

python examples/ch25/service_lab.py serve --device cuda --port 8000
curl -s http://127.0.0.1:8000/v1/generate -H "content-type: application/json" -d '{"prompt": "The capital of France is", "max_new_tokens": 8}'

The principle this chapter adds is an HTTP success must mean the engine executed a defined request, within a verified budget, and returned an auditable result. A malformed, oversized, unsupported or ineffective request must be handled by an explicit rule; the response carries token usage, provenance, ids and documented status; and compatibility depends on both producer and consumer obligations. This laboratory demonstrates those ideas with a single-thread-safe-by-lock backend and measured probes. Chapter 26 adds work admission under contention, and Chapter 27 adds streaming—which requires a separate first-token timing and cancellation contract.

What you should now be able to do

  • Break down client-observed request latency into parsing, tokenisation, lock wait, prefill, decode, response construction, and an uninstrumented client/server remainder; explain why a response-start timer is not a complete round trip.
  • Measure actual token counts, not character length, and enforce separate prompt, total-context, and body-size budgets before inference work starts.
  • Specify a stable HTTP status/error envelope, including parameter names, request ids, non-echoing validation, retry guidance and readiness handling.
  • Decide which request/response schema changes are compatible for a named kind of client, and identify cases a small schema comparator cannot prove safe.
  • Compare serialized token ids, text, usage and model provenance with a direct engine call; explain why decoding and re-tokenising need not round-trip.
  • Demonstrate why a shared stateful KV backend needs request isolation, and explain why a whole-request lock is a correctness baseline rather than a concurrent-serving architecture.

Key terms

  • Request lifecycle: the stages from receiving bytes through validation, execution and response delivery; distinguish server-header timing from the full client round trip.
  • Token budget: prompt and reserved-completion limits expressed in the actual tokenizer’s units, alongside separate byte/body limits.
  • Error envelope: a documented JSON shape for recognised failures, with stable type, message, optional parameter and request id.
  • Liveness versus readiness: the process can answer health checks versus the backend has loaded; neither alone proves available capacity.
  • Tolerant reader: a client that accepts additional, unknown response fields or error types under an explicit compatibility policy.
  • Schema containment: old valid requests must remain accepted with the same meaning; new server responses must fit old clients’ expected domains.
  • Request id: the correlation value in response body, headers and diagnostics, where available.
  • Canonical tokenisation: the tokenizer’s preferred encoding of decoded text; generated ids need not equal that re-encoding.
  • Whole-request lock: serialises access to shared mutable inference state, preserving correctness at the cost of blocking other generations.

Reader exercises

  1. Integrate Chapter 24’s ModelSpec into Limits, including generation reservation, actual tokenizer, supported attention backend and available KV memory; reject a model mismatch before generation.
  2. Add a bounded work queue, a 429 rate_limit_exceeded response, and a Retry-After policy. Measure the change in request queue time under two or more real HTTP clients (Chapter 26).
  3. Design an Idempotency-Key contract: which request fields, model identity, output token ids, expiry and status must be stored so a retry cannot accidentally regenerate a different sampled answer?
  4. Strengthen diff_schemas against nested oneOf, discriminated unions, numeric coercion, missing-vs-null fields and changes to semantic validation; document any undecidable cases as requiring human review.
  5. Expose {token_id, text_fragment} streaming events. Decide how stop-string holdback, partial UTF-8 sequences, late errors and cancellation affect the meaning of a token event (Chapter 27).
  6. Repeat the request-probe suite against a different backend and client library; compare both the status codes and error envelope, not just the number of failures.
  7. Inspect the one greedy and seven sampled non-round-tripping outputs, record their raw ids and UTF-8 text, and distinguish tokenizer recanonicalisation from trimming or implementation defects.
  8. Test a reverse proxy body limit and Expect: 100-continue for streaming uploads of 100 KiB to 100 MiB; capture connection traces to confirm what the client sees on early rejection.

References

  • RFC 9110: HTTP Semantics — IETF Internet Standard, especially statuses 400, 413, 415, 422 and 503 plus Retry-After; protocol semantics, not a mandate to use one error taxonomy for every application.
  • FastAPI: Handling Errors — framework documentation of RequestValidationError and replacement handlers; the input-echo and serialisation failures here are measured behaviour of FastAPI 0.136.3, not universal defaults.
  • Server Timing — W3C Working Draft as consulted on 22 October 2026; the header syntax used in this Lab. Its total metric is measured only until response start.
  • Claude API Errors and Messages API — Anthropic’s documented public API error fields and status conventions; provider interface claims, not experimental evidence about its servers.
  • OpenAPI Specification — industry specification; not independently analysed in the recorded chapter experiment; diff_schemas runs on Pydantic’s generated JSON Schema, not on all OpenAPI features.
  • Orca: A Distributed Serving System for Transformer-Based Generative Models — Yu et al., OSDI 2022. Its iteration-level scheduling motivates the shift from a whole-generation lock to Chapter 26’s scheduler; no Orca benchmarks are reproduced here.
  • Efficient Memory Management for Large Language Model Serving with PagedAttention — Kwon et al., SOSP 2023. Reported KV-cache management and throughput improvements provide research context for independent request-state management; this service does not implement vLLM.
  • The Tail at Scale — Dean and Barroso, Communications of the ACM 56 (2013). Motivation for observing latency distributions and slow outliers rather than relying on medians alone; the Lab measures small-sample distributions and does not test the paper’s mitigation techniques.

Evidence in this chapter

Claim Evidence category and boundary
GPT-2 token counts differ markedly by character class; 4,000 chars gave 972 prose tokens versus 12,000 repeated CJK tokens Local GPT-2 tokenizer result: 4 English and 29 Python 1,000-character samples; most other classes use one constructed string, not a universal maximum
Lenient service: 8/29 HTTP 200 (four altered requests), four HTTP 500, no common error envelope; hardened: four HTTP 200 and 25 uniformly enveloped errors, no HTTP 500 Local CPU fault probes on one finite list; not evidence that hardened errors are impossible
Non-finite temperature and lone-surrogate prompt triggered error-serialization 500s in the lenient variant Locally reproduced with FastAPI 0.136.3; hardened response avoided echoing the invalid value
A 100 MiB request could inflate the unbounded validation response to approximately 100 MiB and process RSS by about 400 MiB Local single-server CPU experiment; middleware cap avoided this measured growth
Client received a 413 for a 100 KiB body but ReadError for bodies of at least 1 MiB Local httpx result on Windows; early-response/connection-close mechanism not packet-traced
diff_schemas agreed with client-model behaviour on 19/19 constructed schema changes Miniature Pydantic model harness; not a general proof of JSON Schema or semantic compatibility
40/40 greedy and 40/40 sampled HTTP outputs matched the direct engine ids, text and usage Local fidelity experiment with one model, tokenizer and sampler; no cross-provider guarantee
Text re-tokenised to original ids in 39/40 greedy and 33/40 sampled responses Local result; causes not investigated, exact continuation requires retaining token ids
Loopback RTT 22.7–2,460 ms and sub-millisecond parse/response stages One-client RTX 2060 measurements, independent stage medians; Server-Timing stamped at response start
localhost TCP connect median 2,036 ms versus 0.64 ms for IPv4 address Windows local observation; IPv6-first fallback a hypothesis, not traced
Blocking async def exposed /health latencies up to 5.6 s versus under 6 ms in the threaded route Three local generations per route, not a load-balancer trial
Unlocked shared cached backend: 48/48 mismatches or exceptions in three runs; with lock 48/48 matched In-process four-thread race, not concurrent HTTP-load evaluation
RFC 9110 HTTP statuses and selected FastAPI/Anthropic interface conventions Protocol/first-party documentation; not evidence for undocumented service internals
Authentication, TLS, proxy front door, streaming, cancellation, fairness and other serving stacks Not implemented or evaluated in this chapter

Implementation status

  • Manuscript: content/books/inference/25-chapter.md
  • Runnable examples: examples/ch25/api.py (original toy service, unchanged) and examples/ch25/service_lab.py (the hardened/lenient service, schema comparator, ASGI middleware, subprocess server and experiment commands).
  • Tests: tests/test_ch25_api.py, tests/test_ch25_service_lab.py (27 Chapter 25 service tests covering budgets, response identity/usage, input error envelopes, body limits, readiness, ignored parameter warnings, stop strings and selected schema-compatibility rules; CPU with the Chapter 1 table backend).
  • Recorded experiments: research/ch25/results.json, with supporting method/source notes in research/ch25/sources.md and research/evidence-register.md. GPU and network results are recorded runs, not rerun for this editorial revision.
  • Recorded commands: python examples/ch25/service_lab.py budget, errors, compat, body, fidelity, lifecycle, blocking, and race (the latter commands require the saved local model, dependencies and appropriate hardware).
  • Repository test entry point: python -m unittest discover -s tests -v.

The chapter is marked draft = false in the repository front matter, but this is a qualified teaching service, not a certified deployment endpoint. Its value is the evidence that strict input interpretation, early token and body budgets, response identity, stable errors and shared-state isolation can be tested separately from model mathematics. The tests do not cover public-network security, concurrent HTTP admission, reliable 413 delivery on large uploads, long-generation streaming, or retry/cancellation semantics. Chapter 26 takes up multi-request scheduling and overload, where the request boundary must become a resource-allocation decision rather than just a validation decision.