Home / AI Architecture & System Design / AI System Design
How do you get reliable JSON out of an LLM?
30-second answer
Use the provider's structured output or tool-calling mode with a JSON schema where available. Give a clear schema and examples. Validate every response with a schema validator; on failure, retry with the validation error included. Keep schemas simple, and design downstream code to handle a final failure gracefully.
Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.
New to these terms? 9 terms on this page are explained in the glossary
0–5 min Functional requirements
"Get JSON out of an LLM" becomes a real design question once you ask where the JSON goes and what happens when it's wrong. Turn it into a concrete service.
You What feeds on this JSON: a UI, a database, another service?
Interviewer Support tickets come in as free text. We extract a category, a priority, an order ID and a short summary, and write them to the ticketing database, which routes the ticket.
You What happens today when extraction goes wrong?
Interviewer About 2% fail to parse, and sometimes the model invents an order ID, so tickets get routed to the wrong team.
You Can a person fix the ones the system can't handle?
Interviewer Yes, there's a small triage team.
You Will the schema change over time?
Interviewer Definitely. New categories get added every quarter.
| # | Functional requirement | Why it matters |
|---|---|---|
| F1 | Turn ticket text into JSON that matches a versioned schema | Downstream code needs a stable contract |
| F2 | Never write invalid or invented values downstream; use null when information is missing |
A fabricated order ID is worse than a missing one |
| F3 | Validate meaning, not just syntax: order IDs exist, enums are valid, cross-field rules hold | Valid JSON can still be wrong |
| F4 | Retry with the validation error, then send unresolved items to human review | Some inputs are genuinely ambiguous |
| F5 | Support schema versions: add categories without breaking old consumers | Stated requirement |
| F6 | Record attempts, errors and final status for every item | Debugging and quality measurement |
5–10 min Non-functional requirements and estimates
You What volume and latency are we talking about?
Interviewer About a million tickets a day. Routing should happen within a couple of seconds.
| Requirement | Target | What it forces in the design |
|---|---|---|
| Downstream validity | 100% of written records pass schema and semantic checks | Validation is a hard gate, not best effort |
| Field accuracy | ≥ 97% per field on the labelled evaluation set | Good schema design, examples, evaluation per field |
| Invented values | ≤ 0.1% of records with a non-null value that isn't in the text | Nullable fields, "null if absent" instructions, lookups |
| Latency | ≤ 2 s p95 including any retry | Small model, low temperature, at most 2 retries |
| Human review | ≤ 0.3% of tickets | Determines triage staffing |
| Throughput | ~35 tickets/s at peak | Stateless workers, rate-limit aware |
Back-of-envelope estimates:
- Traffic: 1M tickets/day ≈ 12/s on average, ~35/s at peak.
- Tokens: ~800 input tokens (instructions, schema, ticket) and ~150 output tokens. With a 1% retry rate, cost rises ~1%; retries are cheap insurance.
- Human review load: 0.3% of 1M is 3,000 tickets/day. At ~1 minute each, that's 50 hours of work a day, about 6–7 full-time reviewers. Each 0.1% of fallback rate is roughly two people, which is why the fallback rate is a design target and not an afterthought.
- Order ID lookups: ~60% of tickets mention an order → ~21 lookups/s at peak against the order service; cache recent orders.
10–18 min High-level design
You The core is a validate-and-repair loop around a schema-constrained model call. Nothing reaches the database until it passes both schema validation and semantic checks.
Scroll sideways to see the whole diagram.
Components:
- Extraction API: receives the ticket, selects the schema version, builds the prompt.
- LLM call in structured-output mode: the provider constrains the output to the JSON Schema, so it always parses and has the right shape.
- Schema validation: a strict validator (Pydantic, Zod or a JSON Schema validator) as a second line of defence.
- Semantic checks: business rules in code: the order ID exists and belongs to this customer, the priority is allowed for this category, the summary is under 200 characters.
- Repair prompt: on failure, a retry that includes the specific error.
- Fallback: after two failed retries, the ticket goes to the triage queue with the partial result and errors.
- Results store: final record, schema version, attempts, model, prompt version.
API sketch:
POST /v1/extract
{ schema: "ticket", version: 3, text: "...", customer_id: "c_123" }
→ { status: "ok" | "needs_review",
data: { category, priority, order_id | null, summary },
errors: [], attempts: 1, schema_version: 3 }
Schema (version 3):
class Ticket(BaseModel):
category: Literal["billing", "shipping", "bug", "account", "other"]
priority: Literal["low", "normal", "high", "urgent"]
order_id: str | None = Field(None, pattern=r"^ORD-\d{8}$",
description="Only if written in the ticket; otherwise null")
summary: str = Field(max_length=200)
How it works: a worked example
A study aid: two tickets traced through the extraction service, one that succeeds first time and one that needs a repair, with the actual JSON at each step.
Ticket A (customer_id=c_123): "Hi, I was charged twice for order ORD-20481193 last week, please refund one of them asap!!"
- The worker builds the prompt: instructions, the
Ticketv3 JSON Schema, two short examples, and the ticket text (~800 tokens). It calls a small model withtemperature=0in structured-output mode, so decoding can only produce JSON matching the schema. - Model output:
{ "category": "billing", "priority": "high", "order_id": "ORD-20481193",
"summary": "Customer was charged twice for one order and requests a refund of the duplicate." }
- Schema validation (Pydantic) passes. Semantic checks in code:
order_idexists in the order service and belongs toc_123✓ (cache hit, 3 ms)- priority
highis allowed forbilling✓ - the order ID string appears verbatim in the ticket text ✓ (guards against invented IDs)
- The record is written with
attempts=1, schema_version=3, model=small-v2, prompt=extract-v7and published to the routing queue. Total ~700 ms.
Ticket B: "my order 2048119 never arrived, where is it"
- Model output:
{"category": "shipping", "priority": "normal", "order_id": "ORD-02048119", ...} - Schema validation passes (it matches the pattern), but the semantic check fails:
ORD-02048119isn't in the text verbatim and doesn't exist for this customer. - Repair attempt: the worker retries with the specific error appended:
Your previous output set order_id to "ORD-02048119", which does not appear in the
ticket and does not match any order for this customer. If the ticket does not
contain a valid order ID in the format ORD-XXXXXXXX, set order_id to null.
- Second output:
"order_id": null. All checks pass. A separate lookup tool later searches the customer's recent orders for2048119and attaches the match for the agent, with a "suggested" label rather than as fact. - If the second attempt had also failed, the ticket would go to the human triage queue with the partial result and the errors, so routing never waits on a broken record.
Where each piece runs:
| Component | Runs as | Example technology | Sizing (35 tickets/s peak) | If it fails |
|---|---|---|---|---|
| Intake queue | Managed queue | SQS/Kafka topic tickets.new |
Buffers spikes; consumers scale on lag | Messages wait; nothing is lost |
| Extraction workers | Stateless containers | Python + Pydantic, or C# + System.Text.Json schema validation | ~10 workers × 4 concurrent calls | Crash → message redelivered (idempotent by ticket ID) |
| Model | Small model via model gateway | Structured-output mode | ~35 calls/s; ~28k input tokens/s | Fail over to second provider; after timeouts, send to triage |
| Order lookup | Internal API with a cache | Redis cache in front of the order service | ~21 lookups/s | Treat as "unverified": null the field rather than guess |
| Results store | Database table | Postgres extractions(ticket_id, data jsonb, attempts, schema_version, …) |
1M rows/day; partitioned | — |
| Triage queue | Ticketing tool view | Existing support tooling | ~3,000/day at 0.3% | Alert if the rate rises above target |
18–32 min Deep dive
You I'd cover how constrained generation works and its limits, schema design, and the repair loop with semantic validation.
Interviewer Start with constrained generation. Doesn't structured-output mode solve this?
Deep dive 1 · Constraining the output
How it works. At each step the model produces probabilities for every token. Constrained decoding masks out tokens that would make the output invalid under the schema or grammar, so the model can only produce output that parses and matches the shape. Providers expose this as "structured outputs" or as tool calling with a strict schema; self-hosted stacks support it with JSON Schema or grammar files.
What it doesn't solve:
- Correct values.
"order_id": "ORD-12345678"is perfectly valid and may be invented. - Semantic rules across fields or against your data.
- Quality on complex schemas. Deeply nested schemas with many optional fields lower accuracy. Forcing JSON from the first token also leaves no room for the model to reason before answering; for hard extractions, let the model reason first (or use a model with built-in reasoning), then produce the structured output.
So constrained decoding removes parse failures, and validation still has to catch wrong values.
Interviewer How would you design the schema to reduce wrong values?
Deep dive 2 · Schema design
- Enums over free text for anything with a fixed set of values.
- Nullable fields with explicit instructions: "null if the ticket doesn't contain an order number". Without a legal "I don't know", the model fills the field with something plausible.
- Field descriptions in the schema are part of the prompt; write them carefully.
- Flat and small: split large schemas into steps rather than one giant extraction.
- Examples: two or three examples, including one with nulls, teach the "leave it empty" behaviour.
- Low temperature (0–0.2) for extraction.
For documents with many types (invoices, contracts, receipts), classify first, then extract with a type-specific schema:
Scroll sideways to see the whole diagram.
Deep dive 3 · Validation and the repair loop
Scroll sideways to see the whole diagram.
- Layer 1, schema: types, enums, patterns, lengths. With structured outputs this almost never fails, but keep it as a guard against provider or schema mismatches.
- Layer 2, semantics: the order ID exists in the order service and belongs to this customer;
urgentpriority only for outage categories; the summary doesn't contain PII. - Repair: send the original input, the previous output and the specific error ("order_id ORD-12345678 not found for this customer; use null if no valid order ID appears in the text"). Specific errors fix most failures in one retry.
- Bounded retries: at most two, then fallback. Unbounded retries waste money on genuinely ambiguous tickets.
- Fallback with context: the triage queue receives the ticket, the best partial result and the errors, so reviewers start from something useful. Their corrections become new evaluation and few-shot examples.
Deep dive 4 · Measuring and evolving (if time allows)
- Field-level metrics on a labelled set of ~500 tickets: accuracy per field, null precision (null when it should be), and the invented-value rate.
- Production signals: schema and semantic failure rates per error type, retry rate, fallback rate, and reviewer corrections per field.
- Schema evolution: additive changes (new enum value, new optional field) get a new minor version; consumers ignore unknown fields. Breaking changes get a new major version, run in parallel until consumers migrate. Re-run the evaluation set on every schema change.
32–37 min Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Output control | Structured outputs + validation | "Please reply in JSON" + regex parsing | Parse failures disappear; validation still catches wrong values |
| Missing data | Nullable fields, "null if absent" | Required fields | Required fields push the model to invent values |
| Complex documents | Classify, then type-specific schema | One huge schema | Accuracy and maintainability |
| Retries | Up to 2, with the specific error | Unlimited, or none | Most fixes come on the first retry; limits cap cost |
| Fallback | Human triage queue | Write best guess | Wrong routing is costly; staffing sized from the fallback rate |
| Reasoning | Reason first for hard cases, then structured output | Force JSON from the first token | Better accuracy on ambiguous inputs |
Build first: structured outputs with the Pydantic schema, semantic checks for order IDs, two retries and the triage fallback, plus the labelled evaluation set.
37–40 min Wrap-up and likely follow-ups
Close with: "Constrained decoding guarantees the shape, so parse failures go away, but values still need checking. I'd design a small, nullable schema, validate types and business rules in code, retry with the specific error up to twice, and send the rest to human review with context. The fallback rate is a key metric because it sets review staffing."
Likely follow-ups:
- What if the provider doesn't support structured outputs? Use tool calling with a strict schema, or a self-hosted model with grammar-constrained decoding, and keep the same validation loop.
- How do you stream structured output? Wait for completion before validating, or use an incremental parser and only act on fields once they're complete.
- How do you handle very long documents? Extract per section and merge with rules, or retrieve the relevant sections first.
What interviewers listen for
- Knowing what structured outputs guarantee (shape) and what they don't (correct values).
- Nullable fields to prevent invented values.
- A bounded repair loop with semantic validation and a human fallback.
- Field-level evaluation and schema versioning.
Red flags
- "Ask nicely for JSON and parse it with a regex."
- Treating valid JSON as correct JSON.
- Unlimited retries, or no plan for items that never validate.
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.