Skip to content
Structured output is stable, but every step pays a latency cost

Structured output is stable, but every step pays a latency cost

Turning on JSON output pushed the endpoint’s p95 from a few hundred milliseconds to one or two seconds. The format errors did disappear, but the complaints switched to timeouts. This trade-off happens in many teams: structured output looks like it just adds a format constraint to the model, but it actually moves uncertainty from the parsing layer to the latency layer. Constrained decoding is not free; it does masking at every step and occasionally has to backtrack.

What constrained decoding does extra at each step

Ordinary generation does only one thing: the model produces logits over the vocabulary (the raw score for each candidate token), and one token is sampled. Constrained decoding adds a step before sampling: it maintains a grammar state, computes the set of currently allowed tokens, masks out the logits of disallowed ones, and then samples. The JSON schema is compiled into a finite state machine or a context-free grammar, and each generated token advances the state by one step.

The cost of this mechanism is not how large a single computation is, but that it happens on every token. The vocabulary is on the order of tens of thousands to over a hundred thousand, and masking requires filtering the entire vocabulary once; if the grammar is a context-free grammar (CFG) rather than a simple regex, state transitions and allowed-set computation are heavier. Compiling the schema when a request arrives also costs money; compiling a complex schema once in tens of milliseconds is not surprising, so in production the compiled result is usually cached by schema hash rather than compiled fresh for every request.

More insidious is batching. A batch in an online service usually mixes different requests, each with a different grammar state, and the mask matrix has to be expanded per batch. Masks are computed on the CPU and logits on the GPU, and a single synchronization in between can leave the GPU idle. When QPS is high, the throughput drop may not be because the model can’t compute fast enough, but because the scheduler is waiting on masks.

A constrained decoding loop roughly looks like this, and a dead end triggers backtracking.

flowchart TD
  A[模型输出 logits] --> B[语法状态求允许集]
  B --> C{有可用 token}
  C -- 是 --> D[掩码采样并推进状态]
  D --> E{到达终止态}
  E -- 否 --> A
  E -- 是 --> F[返回结构化结果]
  C -- 否 --> G[回退并禁用该 token]
  G --> A

Backtracking is the real source of tail latency

If the grammar only does local validation, the model may pick a token that is currently legal but from which no terminating state can be reached later. In that case, either backtrack to the previous branch point, disable this token, and resample, or fail the whole request and retry. The former requires truncating the KV cache (inference cache) and re-prefilling the prefix after the backtrack point; the latter is more expensive, as all previously generated tokens are discarded.

Backtracking depth is a latency multiplier. Backtrack one level, and one more prefix segment is recomputed; backtrack three levels, and tail latency may multiply several times. In the worst case, using depth-first search to find a feasible path explodes in complexity, so production systems do not do unbounded backtracking; they usually keep only one or a few levels, and fail if that is not enough.

Another kind of backtracking comes from the tokenizer and grammar boundaries not coinciding. A character-level grammar may see a token that spans several grammar nodes; if masking only judges character by character, it will wrongly allow or forbid a token, and by the time the parser notices, it can only backtrack. Token-level grammars must map the vocabulary onto state transitions; if this part is not done carefully, the more complex the format, the more likely problems are.

A good compiler precomputes reachability and, when masking, only allows tokens that can still reach a terminating state; this eliminates most backtracking. The cost is heavier compilation and more states, and everything must be recomputed whenever the schema changes. If the engine only does local validation, the backtracking rate will be high, and latency will have to pay for it in the end.

So I treat backtracking as a fallback, not the main path. When launching, first measure the backtracking rate; if it is not a very small number, fix the schema or grammar first rather than brute-forcing it by adding more backtracking levels.

Look at p95 first, not just p50

The latency of structured output consists of four parts: prefill, per-token decoding, constraint overhead, and failure retries. Constrained decoding mainly adds to the second and third parts, while backtracking and retries add to the fourth. p50 may rise only a little, because most requests take the short path; p95 (95th percentile latency) is stretched by backtracking and retries. An endpoint’s average latency barely changes, but users occasionally wait two or three seconds; that is usually where the problem is.

Also look at throughput. If the downstream is a synchronous endpoint, p95 is the user experience; if it is batch processing, look at tokens/s and GPU utilization. The same approach may be acceptable in offline batch processing but unusable in online chat. Do not use a single average-latency curve to make decisions for both scenarios.

Four approaches: don’t treat structured output as an on/off switch

Approach Format determinism Main latency source Suitable boundary
Post-validation plus retry Low to medium, relies on retries Normal requests unchanged, failed requests doubled Low format error rate, simple schema
JSON mode Only guarantees JSON syntax Few states, usually cheaper than a full schema Downstream can tolerate missing fields, internal logs
Constrained decoding High, grammar-level determinism Per-token masking, backtracking stretches the tail Machine-to-machine, short output, high cost of format failure
Two-stage Medium to high, depends on the second stage One extra call Long text, content quality first

If JSON mode is also grammar-constrained underneath, it is not zero-cost; it just has weaker constraints and fewer states. Post-validation plus retry adds almost no latency on the normal path and doubles it on the failure path, making it suitable for scenarios with a low format error rate and a simple schema. Constrained decoding raises format determinism to the grammar level, at the cost of per-step masking and backtracking. The two-stage approach first generates content freely, then extracts it into a structure using a template or a second small model; it adds one extra call but is friendlier to long text.

If function calling or tool calling is also constrained decoding underneath, the accounting is the same; don’t assume it is free just because the name changed.

How the schema is written directly determines the latency ceiling

The latency of constrained decoding is not determined only by the engine; the schema itself also determines the state space.

Flatten where possible. Each additional level of nesting adds a level of grammar state; oneOf and anyOf introduce branches and raise the backtracking probability. If a field can be expressed with one object, don’t wrap it in three layers.

Enums need boundaries. Using enums for classification fields is more stable than free text, but stuffing thousands of values into one field enlarges both the allowed set and the token prefix tree, and makes it easier for the model to pick the wrong one among similar enum values.

Set upper limits for arrays and strings. maxItems and maxLength are not formalism; they give the grammar a termination condition and prevent the model from writing indefinitely. Specifying ranges for numeric fields also reduces the probability of hitting a dead end and backtracking.

Fix field order where possible. Object key order does not matter for JSON semantics, but it matters for grammar branches; a fixed order removes a layer of permutations, provided the downstream does not depend on order.

Don’t have too many required fields. If a default value can express it, don’t force the model to generate it; the more required fields, the more dead ends.

When not to use constrained decoding

If the bulk of the output is long natural language with just a JSON wrapper around it, I usually do not recommend constraining the whole thing. Long text inside JSON also has to handle quote and newline escaping, the token count increases, and the grammar state becomes more complex. Freely generating the body first and then wrapping it with a template or a second small step is often more stable.

If the cost of format errors is low and retries are cheap, post-validation is the better deal. Constrained decoding suits machine-to-machine scenarios where format failures are expensive, the downstream has no fault tolerance, and output length is controllable—not every JSON output is worth it.

If the latency budget is a hard constraint and the schema is complex, consider asynchronous tasks, offline batch processing, or splitting the structured part into a post-processing step. Forcing a synchronous interface to meet low latency usually ends with timeouts and retries dragging the system down.

Constrained decoding guarantees shape, not judgment. When a field is restricted by an enum, the model may pick a syntactically valid but semantically wrong value; a 100% format validity rate does not mean a 100% field accuracy rate.

Measure three numbers before launch

Before launch, measure at least three numbers: format validity rate, field semantic accuracy rate, and p95 latency and fallback rate. Format validity and semantic accuracy must be tracked separately; otherwise constrained decoding will make the first number look great while the second doesn’t move.

When stress testing, don’t test only with the simplest schema. Take the most complex business schema, fix the output length, and record the per-step masking overhead, the number of fallbacks, and the retry rate. If p95 exceeds budget, cut schema branches first, then consider fallback strategies.

My default approach is to keep fallback depth to one layer only; beyond that, fail and retry. Keep schema nesting within what the business actually requires, and set upper bounds on both arrays and strings. This isn’t theoretically optimal—it’s about locking down tail latency.

Don’t ask whether to enable structured output first. Ask how long the longest output path for this schema is, how many dead ends there are, and how much p95 budget is left. If you can’t answer those three numbers, enabling it just moves the errors somewhere else.

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Constrained Decoding #Inference Latency #Structured Output

Comments