← Back to Guides
GuideFor: AI Engineers, ML Engineers, Platform Engineers, AI Systems Architects

Harness Engineering: The Missing Layer Between LLMs and Production Systems

Why AI systems don't fail at the model layer - and how designing the right execution harness turns brittle prompts into reliable infrastructure

Updated
#harness-engineering#llm-reliability#production-ai-systems#ai-system-design#prompt-engineering#llm-orchestration

The Demo That Lied

This is Part 1 of the Harness Engineering series - a deep dive into the production infrastructure layer that sits between your LLM and your users. This article covers the architecture. Parts 2-8 go deep on each layer.

This series grew into a book: Harness Engineering for Production AI Systems. What is inside is at the end of this article.

14 November 2026: updated for provider-native structured outputs and for "agent harness" as a vendor product category, corrected the end-to-end failure rate in The Reliability Math, and gave every layer its own diagram.

You've shipped "production-ready" LLM features before. You know the feeling.

The playground worked perfectly. You tested 20 edge cases, the model handled all of them. You showed the demo to stakeholders, it was flawless. You deployed.

And then - at 2am on a Tuesday - your on-call phone fires. The agent is stuck in a loop. It's been apologizing for "the confusion" for 47 minutes, burning tokens on every retry, and your users are getting back nothing but a spinner.

You dig into the logs. The model returned a valid-looking response. But it wrapped a number in quotes. One field. One wrong type. And your downstream system - which trusted the model completely - fell over.

Same model, two runs. Read the two columns side by side: nothing changed between them except the inputs.

d2
grid-rows: 1
grid-gap: 48
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
demo: "The demo" {
  label.near: top-center
  a: "20 curated inputs" {class: grey}
  m: "Model" {class: yellow}
  r: "Every answer\nlooks right" {class: green}
  a -> m -> r
}
prod: "2am, real traffic" {
  label.near: top-center
  a: "Real users" {class: grey}
  m: "Same model" {class: yellow}
  q: "One number\nwrapped in quotes" {class: orange}
  d: "Downstream system\nfalls over" {class: red}
  a -> m -> q -> d
}

One extra box on the right, and that box is the whole story. Nothing between the model and the downstream system was there to catch it.

Here's what nobody told you when you started building with LLMs: the model worked fine. Your system didn't.

That's the gap this article is about. Not prompt engineering. Not model selection. The layer between the LLM and your production system - the layer most teams skip entirely - that's where real AI reliability is built or broken.

By now the field has a name for it: Harness Engineering. OpenAI's Codex team used it for their account of building software with agents, and Anthropic's engineering blog writes about harnesses for long-running agents in the same terms.


What Harness Engineering Actually Is

Most teams treat the LLM as the system. They spend weeks perfecting prompts, evaluating models, and benchmarking output quality. Then they wire the model directly to their application code and ship.

This is the wrong mental model.

An LLM is not a reliable software component. It's a probabilistic engine - volatile, stateful in unexpected ways, and capable of producing output that is syntactically valid but semantically broken. You wouldn't wire raw mains voltage directly into your laptop. You'd use a converter, a regulator, a fuse. The harness is exactly that - a deterministic wrapper around a probabilistic engine.

Picture it as containment. The model sits inside the box, and nothing reaches it or leaves it except through a check.

d2
direction: down
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
req: "Request" {class: grey}
harness: "Harness" {
  label.near: top-left
  in: "Checks on the way in" {class: violet}
  llm: "LLM\nprobabilistic engine" {class: yellow}
  out: "Checks on the way out" {class: green}
  in -> llm -> out
}
sys: "Your system" {class: blue}
req -> harness.in
harness.out -> sys

Your system never talks to the yellow box directly. Every path from the request to your system runs through a deterministic check first.

Harness Engineering is the discipline of designing that wrapper. Not talking to the model better. Containing the model so it cannot break your system, regardless of what it outputs.

The goal is not to make the model smarter. The goal is to reduce the space in which it can be wrong.

Prompt engineering is local optimization. You tune the inputs and hope the output cooperates — or measure whether the tuning actually helped instead of hoping. Harness engineering is systems design. You assume the output will eventually break your assumptions - and you build for that.


Harness vs. Framework: A Critical Distinction

Before going further, one confusion worth clearing up - because you will run into it.

A framework is not a harness. And "harness" now means two different things.

LangChain, LangGraph, CrewAI, AutoGen - these are frameworks. They give you components: agent loops, tool abstractions, prompt templates, memory interfaces. They're blueprints and building materials. You use them to assemble an agent architecture.

Since this article first ran, "harness" has also become a product category. LangChain now describes its own packages as three tiers: LangChain an agent framework, LangGraph an agent runtime, Deep Agents an agent harness, and it admits the lines between them are murky. Anthropic calls the Claude Agent SDK a general-purpose agent harness. A vendor harness ships the generic loop: planning, a filesystem, subagents, context management.

What a vendor harness can't ship is your risk surface. It doesn't know that your refund tool has no undo, that an extracted damage cap must match the clause it came from, or which actions need a human at 2am. The Harness Architecture this series describes is that part - the outer harness: the runtime controls that decide what context your model sees, which tools it can reach, what output is accepted, what it may act on, how state is checkpointed, and how failure is handled.

Stack them up and the ownership line shows. Everything below the green layer can be bought; the green layer can't.

d2
grid-columns: 1
grid-gap: 10
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
yours: "Your harness (you build it)\nvalidators, gate, constraints, budgets, checkpoints" {class: green}
vendor: "Vendor agent harness\nplanning, filesystem, subagents (Deep Agents, Claude Agent SDK)" {class: violet}
runtime: "Agent runtime\ndurable execution (LangGraph)" {class: blue}
fw: "Agent framework\nabstractions (LangChain, CrewAI)" {class: teal}
model: "Model" {class: yellow}

You can build a framework-based agent, even on top of a vendor harness, without ever building the top layer. Teams do it constantly. It's why agents that demo well fail in production - the framework got them to a working prototype, but the controls that make it survive real users were never built.

FrameworkVendor agent harnessYour harness
What it isBuild-time componentsA packaged agent loopRuntime controls for your risk surface
ExamplesLangChain, CrewAIDeep Agents, Claude Agent SDKYour validators, gate, repair loop
Knows your domainNoNoYes
Without itYou write more glueYou write the loop yourselfYou can't ship the agent safely

The relationship is complementary. Use a framework to build, adopt a vendor harness if its loop fits, and build your own harness to ship. Most teams are excellent at the first two and skip the third entirely.


Why Prompt Engineering Hits a Wall in LLM Orchestration

Prompt engineering assumes that if you phrase things clearly enough, the model will behave. I call this Linguistic Optimism - and it doesn't scale to production.

Here's the specific failure mode: prompts are brittle at the edges. The center of your input distribution? The model handles it beautifully. The edges - unusual user phrasing, unexpected input length, missing fields, multilingual inputs, adversarial content - that's where prompt-only systems crack. Intent classification is a textbook case for this failure mode - a confident label on a paraphrase the model never saw in training.

Picture the input distribution as a grid. The prompt was tuned on the middle cell.

d2
grid-rows: 3
grid-columns: 3
grid-gap: 10
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
e1: "Unusual phrasing" {class: red}
e2: "Very long input" {class: red}
e3: "Missing fields" {class: red}
e4: "Multilingual input" {class: red}
c: "Center of the distribution:\nthe prompt handles it" {class: green}
e5: "Adversarial content" {class: red}
e6: "Paraphrased intent" {class: red}
e7: "Very short input" {class: red}
e8: "OCR or encoding noise" {class: red}

Eight cells out of nine are the edges. A demo samples the middle one; production samples all of them.

And in production, edge cases aren't edge cases anymore. They're just users.

Consider the difference:

DimensionPrompt EngineeringHarness Engineering
PhilosophyTell the model what to doBuild a system where it can't do wrong
Failure modeSilent failure / hallucinationCaught exception / controlled retry
PredictabilityProbabilisticDeterministic at the system level
ScalabilityDegrades at the edgesHolds at scale
Debuggability"Why did it say that?"Structured logs, clear failure paths

The shift in mental model is this: a good prompt makes a demo work. A good harness makes a product survive.


The Seven Layers of a Production Harness

A production harness isn't a single module. It's a layered execution pipeline - each layer absorbing a specific failure mode before it propagates downstream.

This layered system is what I call a Harness Architecture. The diagram below is its core execution loop - the mental model for everything that follows:

d2
direction: down
classes: {
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
}
req: "User request" {class: blue}
pre: "Before the model sees it" {
  label.near: top-left
  grid-rows: 1
  l1: "Layer 1:\nNormalization" {class: violet}
  l2: "Layer 2:\nContext orchestration" {class: violet}
  l3: "Layer 3:\nConstraint layer" {class: violet}
}
llm: "LLM reasoning" {class: yellow}
cb: "Layer 6: Circuit breaker" {class: red}
st: "Layer 7: State management" {class: orange}
l5: "Layer 5: Validation" {class: green}
rep: "Repair loop" {class: red}
l4: "Layer 4: Gated execution" {class: teal}
out: "Final output" {class: blue}
req -> pre
pre -> llm
llm -> cb: "provider fails"
cb -> llm: "retry or fallback"
llm -> st: "checkpoint"
st -> llm: "resume"
llm -> l5
l5 -> rep: "fails"
rep -> llm: "error stated"
l5 -> l4: "passes"
l4 -> out

This diagram represents the core execution loop of a production Harness Architecture - all seven layers. Every node exists because a real production system failed without it. Note the two red nodes: the Repair Loop (exception path when model output fails validation) and the Circuit Breaker (exception path when the LLM provider itself fails). Both are recovery branches. Both are non-optional. Let's go through each layer at the level of what actually breaks when you skip it.


Layer 1: The Normalization Layer

This is the first thing the request touches before the model sees it.

Normalization does two things: it strips input noise and it enforces prompt consistency. Input noise is everything that shouldn't reach the model - trailing whitespace, OCR artifacts, HTML entities, user-injected role overrides ("Ignore all previous instructions..."), metadata from UI components that the user didn't intend to send.

Without normalization, your prompt becomes a surface area. Every unexpected character is a potential exploit or a reasoning failure.

What breaks without it: prompt injections, confused reasoning caused by UI metadata, inconsistent behavior across different client surfaces (mobile sends the request differently than desktop, and the model behaves differently because of it).

What it looks like in practice: a preprocessing function that runs before context assembly. The order matters, so the diagram numbers it.

d2
direction: down
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
raw: "Raw input" {
  label.near: top-left
  grid-rows: 1
  n1: "OCR artifacts" {class: grey}
  n2: "HTML entities" {class: grey}
  n3: "\"Ignore all previous\ninstructions...\"" {class: red}
  n4: "UI metadata" {class: grey}
}
norm: "Normalizer, in order" {
  label.near: top-left
  grid-rows: 1
  s1: "1. Sanitize" {class: violet}
  s2: "2. Truncate" {class: violet}
  s3: "3. Check fields" {class: violet}
  s4: "4. Detect\ninjection" {class: violet}
  s5: "5. Normalize\nwhitespace" {class: violet}
}
clean: "Clean request, to context orchestration" {class: green}
raw -> norm
norm -> clean

Only what comes out of the bottom box is allowed to reach the next layer. The red cell is the reason the injection check sits inside the normalizer rather than somewhere downstream: by the time context is assembled, the override is already part of the prompt.

Normalization patterns, prompt injection defense, and multi-surface input consistency will be covered in full in Part 2 of this series.


Layer 2: Context Orchestration

This is the layer most teams get wrong even when they know it exists.

Context orchestration is not "put everything in the prompt."

It's assembling exactly the right context for the current task - no more, no less.

The "Lost in the Middle" problem is real. LLMs perform worse on content buried in long contexts. Dump 40 RAG chunks into the prompt, and the model reasons well on the first few and the last few - and poorly on everything between.

That's not a model failure. That's a context design failure.

Context orchestration means: retrieve, filter, rank, compress, assemble. Follow the 40 chunks down the pipeline:

d2
direction: down
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
cand: "40 retrieved chunks" {class: grey}
pipe: "Context pipeline, in order" {
  label.near: top-left
  grid-rows: 1
  f: "1. Filter:\ndrop off-task" {class: violet}
  r: "2. Rank:\nmost relevant first" {class: violet}
  c: "3. Compress\nboilerplate" {class: violet}
  a: "4. Assemble under\nthe token budget" {class: violet}
}
ctx: "Focused context: the chunks that\nmatter are not buried in the middle" {class: green}
cand -> pipe
pipe -> ctx

Each step shrinks what the model has to read, so the chunks that carry the answer stop competing with the ones that don't. Budget your context window the way you budget compute.

Without this layer: you're paying for tokens the model ignores, while the tokens that matter get buried.

I'll do a full deep dive into Context Engineering - memory architectures, retrieval strategies, context compression - in Part 3 of this series.


Layer 3: The Constraint Layer

The model can only do what you permit it to do. The constraint layer enforces that.

In agentic systems, this is where action scope is defined. What tools can the model call? What APIs are in scope? What can it read? What can it write?

Without explicit constraints, you get hallucinated actions - the model tries to call an API that doesn't exist, references a UI element it invented, or takes an action that was never in scope. This isn't rare. In any sufficiently complex tool-calling setup, it happens.

Concretely: your tool registry, your action schema, your permission model. The model sees only what you expose. Nothing else is reachable, regardless of what the model thinks it can do. When tools reach the model through MCP servers, the same rule applies one level up: the constraint layer is the allowlist of servers and tools the agent may connect to, plus per-tool authorization, not whatever a connected server happens to advertise.

Think of the registry as a fork with two exits, only one of which leads anywhere:

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
model: "Model proposes tool calls" {class: yellow}
reg: "Tool registry + permission model\n(and MCP server allowlist)" {class: violet}
ok: "Registered, in scope" {
  label.near: top-left
  grid-rows: 1
  t1: "read_contract" {class: green}
  t2: "search_clauses" {class: green}
}
no: "Unreachable" {
  label.near: top-left
  grid-rows: 1
  x1: "Invented API" {class: red}
  x2: "Out-of-scope write" {class: red}
}
model -> reg
reg -> ok: "dispatched"
reg -> no: "rejected"

Nothing in a red cell is blocked by a rule that says "don't". They have no route to execution at all, which is a stronger guarantee than any instruction in the prompt.

Without this layer: the model's imagination becomes your attack surface.

We'll get into deterministic constraint design - tool registries, action manifests, scope enforcement - in Part 8 of this series.


Layer 4: Gated Execution

The validator tells you the output is structurally correct. Gated execution decides whether to actually run it.

The model proposes. The gate decides. That's the whole principle.

This is the firewall between model intent and real-world side effects. LLM output - even valid, schema-compliant output - can carry parameters that are dangerous to execute. A deletion query with a WHERE clause that matches everything. An API call with a dollar amount of -$10,000. A SQL statement that's syntactically valid but semantically destructive.

Gated execution adds a semantic check before any action with side effects runs. High-risk actions escalate to a human approval step. Lower-risk actions run automated policy checks.

A gate has more than two answers. Read the bottom row left to right as rising cost if the action turns out to be wrong:

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
p: "Proposed action (schema-valid)" {class: yellow}
g: "Policy engine: what does this cost if it is wrong?" {class: teal}
o: "Gate decision" {
  label.near: top-left
  grid-rows: 1
  a: "Low risk:\nrun, inside budget\nand rate guards" {class: green}
  b: "Unclear effect:\ndry-run preview\nfirst" {class: orange}
  c: "Irreversible:\nescalate to\na human" {class: violet}
  d: "Violates policy:\nrefuse" {class: red}
}
p -> g -> o

In practice this looks like: a policy engine that evaluates proposed actions against a ruleset before dispatch. Budget guards. Rate limiters. Dry-run modes that preview side effects before committing. Human-in-the-loop escalation paths for irreversible actions. This series grew into a book: Harness Engineering for Production AI Systems. Chapter 9, "Gated Execution," builds this gate's policy end to end around a refund tool that has no undo.

Without this layer: structurally valid output causes real-world damage. The model didn't hallucinate. The system just didn't check before it acted.

Policy engine design, human-in-the-loop escalation patterns, and budget guards for agentic systems will be covered in Part 4 of this series.


Layer 5: The Validation and Repair Layer

This is the layer that makes the difference between a flaky demo and a production system.

The model will produce wrong output. Not occasionally - regularly. Especially under load, with unusual inputs, or when the prompt has drifted from what the model was fine-tuned on. The validation layer catches this before it reaches your application code.

At minimum: schema validation. Is the JSON well-formed? Are required fields present? Are types correct? Does the structure match what downstream expects?

That part can now move into the provider. Anthropic's structured outputs constrain a response to a JSON schema (output_config.format), and strict tool use (strict: true) does the same for tool inputs; OpenAI has offered strict structured outputs since 2024. With strict mode on, the quoted number from the opening story can't come back: the decoder won't emit a string where the schema says number. Use it where the provider supports your schema. It removes a class of failure instead of catching it.

What strict mode can't tell you is whether a well-typed answer is right. A damage cap of 5000000 is a perfectly valid number. So good validation goes further:

Semantic validation - does the content make sense given the task?

Range validation - are numeric values in plausible bounds?

Consistency validation - do interdependent fields agree with each other?

Put together, the shape check and your own checks sit in sequence, and only the second stage needs a repair path:

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
model: "Model" {class: yellow}
strict: "Provider strict mode:\nshape and types enforced at decode time" {class: blue}
v: "Your validators" {
  label.near: top-left
  grid-rows: 1
  s: "Semantic" {class: green}
  r: "Range" {class: green}
  c: "Consistency" {class: green}
}
acc: "Accepted output" {class: teal}
rep: "Repair loop:\nerror stated back" {class: red}
ff: "Fail fast" {class: red}
model -> strict -> v
v -> acc: "passes"
v -> rep: "fails"
rep -> model: "retry"
rep -> ff: "retries exhausted"

When validation fails, you have two options: fail fast, or repair. Fail fast is appropriate when the failure is unrecoverable or when retrying is expensive. Repair loops are appropriate when the failure is deterministic and correctable - send the error back to the model with the violation explicitly stated and ask it to try again.

In practice, many teams implement this with Pydantic for schema definition and validation, and Instructor (built on top of Pydantic) for structured LLM output that retries automatically on validation failure. Pair either one with native structured outputs where the provider supports your schema: the provider guarantees the shape, and your validators check the meaning. Chapter 7 of the book, "Validation and Repair," turns this into a repair ladder you can copy into a repository.

Here's the pattern in plain Python to show what's happening under the hood:

python
def validated_call(prompt: str, schema: dict, max_retries: int = 3) -> dict:    for attempt in range(max_retries):        raw = llm.call(prompt, schema=schema)  # strict mode where supported        try:            result = parse_and_validate(raw, schema)            return result        except ValidationError as e:            if attempt == max_retries - 1:                raise            prompt = build_repair_prompt(prompt, raw, e)    # unreachable, but explicit    raise MaxRetriesExceeded()

The model doesn't need to be perfect. It needs to be correctable. That's a much lower bar - and the harness is what makes it achievable.

I'll cover advanced Validation Layer design - including semantic validators, repair prompt patterns, and when to fail fast vs. retry - in Part 5 of this series.


Layer 6: Graceful Degradation

The model goes down. Rate limits hit. Latency spikes to 30 seconds. Your third-party LLM provider has an incident.

Graceful degradation is how your system behaves when the probabilistic engine is unavailable or unreliable.

Without this layer, a model outage becomes a system outage. Your users get a 500 error with a stack trace. Your application is completely non-functional until the model recovers.

With graceful degradation, you have: circuit breakers that stop hammering a degraded endpoint, fallback models that step in at reduced capability, cached responses for common queries, and user-facing messaging that's honest about reduced functionality without being alarming.

Those four pieces form a ladder. Each question on the left is asked only if the one above it went badly:

d2
grid-rows: 4
grid-columns: 2
grid-gap: 24
classes: {
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
q1: "1. Is the primary model healthy?" {class: violet}
a1: "Breaker closed: call it" {class: green}
q2: "2. Has the breaker tripped open?" {class: violet}
a2: "Stop calling it; route to\na fallback model" {class: orange}
q3: "3. Is the fallback down too?" {class: violet}
a3: "Serve a cached response\nfor common queries" {class: orange}
q4: "4. Nothing cached?" {class: violet}
a4: "Say so honestly:\nreduced functionality" {class: red}
q1 -> q2
q2 -> q3
q3 -> q4

Every rung still answers the user. A 500 with a stack trace is the only outcome the ladder has no row for.

The pattern is familiar from distributed systems. LLMs just need it applied explicitly, because most teams don't think of the model as an external dependency that can fail - they think of it as the application itself.

Retry strategies, fallback model selection, and circuit breaker patterns for LLM systems will be the focus of Part 6 of this series.


Layer 7: State Management

This layer only becomes visible when your agents start running for more than a few seconds. Which, in production, they will.

A simple request-response LLM call has no state problem. But an agentic workflow - one that runs 20 steps, calls multiple tools, processes intermediate results, and might take 5 minutes to complete - is a long-running process. And long-running processes fail mid-execution.

What breaks without it: the agent crashes at step 14 of 20. Without state management, it restarts from step 1. Your user waits another 5 minutes. Worse, some of those first 14 steps had side effects - files written, APIs called, records updated. Now you're replaying them. Duplicate records. Double-charged transactions. Corrupted state.

State management gives the harness checkpoint-resume capability. At each meaningful step, the harness serializes current state - what has been done, what the intermediate results are, what still needs to happen. If the agent fails or the process dies, it resumes from the last checkpoint, not from scratch.

Same crash, two harnesses. The columns diverge at the third box:

d2
grid-rows: 1
grid-gap: 48
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
no: "No checkpoints" {
  label.near: top-center
  a: "Steps 1-13 run:\nrecords written, APIs called" {class: grey}
  b: "Crash at step 14" {class: red}
  c: "Restart from step 1" {class: orange}
  d: "Steps 1-13 replayed:\nduplicates, double charges" {class: red}
  a -> b -> c -> d
}
yes: "With checkpoints" {
  label.near: top-center
  a: "Steps 1-13 run:\nstate saved after each" {class: grey}
  b: "Crash at step 14" {class: red}
  c: "Load the checkpoint\nfrom step 13" {class: teal}
  d: "Resume at step 14:\nnothing replayed" {class: green}
  a -> b -> c -> d
}

On the left, every side effect already caused gets paid for twice. On the right, you pay only for the step that was in flight, which is why that step's tool calls still need to be idempotent.

It also covers cross-session memory for agents that span multiple interactions. When a user picks up a task tomorrow that they started today, what does the agent remember? How is prior context structured and compressed so the next session doesn't start blind?

In practice this looks like: checkpointing state to a durable store (Redis, Postgres, or a purpose-built agent memory layer) after each tool call or reasoning step. Structured scratchpad files the agent maintains itself. Summarization of prior steps before injecting into the next session's context.

Without this layer: every long-running agentic task is a gamble. You're betting the process completes before something goes wrong. At production scale, that bet loses constantly.

State management architectures for long-running agents - including checkpoint strategies, memory compression, and cross-session context design - will be covered in depth in Part 7 of this series.


A Full Harness in Action

Let's make this concrete. A user submits a 50-page contract: "Summarize this and extract all liability risks."

Without a harness, you dump the contract into the prompt, call the model, and pray the output JSON is parseable.

With a Harness Architecture, every layer has a job. Here is the run end to end, including the one time it goes wrong:

d2
direction: down
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
doc: "50-page contract" {class: grey}
n: "Normalization: strip OCR, detect a legal document" {class: violet}
c: "Context: liability, indemnification,\ndamages and termination sections only" {class: violet}
k: "Constraint: read-only, no write actions" {class: violet}
m: "LLM call with a strict schema" {class: yellow}
v: "Validator: does each damage_cap\nappear in its clause text?" {class: green}
r: "Repair: the clause says \$500,000,\nnot 5000000" {class: red}
out: "Validated JSON, to downstream" {class: blue}
doc -> n -> c -> k -> m -> v
v -> r: "no"
r -> m: "retry"
v -> out: "yes"

Without that loop on the left, a human would have had to step in. Walking the layers one at a time:

Normalization: Strip OCR artifacts. Detect the document type and jurisdiction. Clean encoding issues. Identify that this is a legal document, not a general query - route accordingly.

Context Orchestration: Don't send the full 50 pages. Use a chunked retrieval strategy - pull only the sections semantically close to "liability," "indemnification," "limitation of damages," and "termination." Compress boilerplate. Assemble a focused context under the token budget.

Constraint Layer: The task is extraction only. The model is not permitted to call external APIs, modify any records, or take any write actions. The action scope is read-only, output-only.

LLM Call (Structured Output): Call the model with strict structured output against this schema: [{clause: string, risk_type: string, severity: "low" | "medium" | "high", damage_cap: number | null}]. Strict mode guarantees the shape: severity is one of the three values, and damage_cap comes back as a number or null, never a string like "$500,000".

Validation: Parse the response. Check that every damage_cap figure actually appears in the clause it was extracted from. Check that every quoted clause exists in the contract. Check that no required fields are missing.

Repair Loop: The model returned "damage_cap": 5000000 for a clause that caps liability at $500,000 - a valid number, off by a factor of ten. Strict mode can't catch that; the consistency check does. The harness sends back: "Validation error: damage_cap 5000000 does not appear in the clause text, which states $500,000. Re-read the clause and retry." The model corrects on the next attempt.

Gated Execution: This is a read-only extraction task, so no gate check needed. For a task that would write to a database, this is where the policy check runs.

Final Output: A validated, schema-compliant JSON object, ready for the downstream system. Zero manual intervention. Zero crashes. The model made a mistake and the harness absorbed it.

That's Harness Engineering working as designed.


The Reliability Math

Here's the framing that changes how you think about this:

Your LLM might be 85% accurate on your task. That means roughly 1 in 7 calls produces output that is wrong or malformed in some way. At 10 calls/second, that's over 129,000 failures per day. Without a harness, each of those is a user-facing failure.

Now make it agentic. Say each step in your multi-step pipeline succeeds 95% of the time - which sounds solid. Chain 20 steps together, and your end-to-end task completion rate drops to 36%. This is the compounding failure problem. The math predicts that agents which look reliable at the step level will fail nearly two out of three real end-to-end tasks.

Watch the middle column fall as the chain gets longer:

d2
grid-rows: 5
grid-columns: 3
grid-gap: 8
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#F87171"; stroke: "#DC2626"; font-color: "#2C2C2A"}}
}
h1: "Steps chained\n(95% each)" {class: grey}
h2: "End-to-end success" {class: grey}
h3: "What it feels like" {class: grey}
r1a: "1" {class: grey}
r1b: "95%" {class: green}
r1c: "The demo" {class: green}
r2a: "5" {class: grey}
r2b: "77%" {class: yellow}
r2c: "Fine in testing" {class: yellow}
r3a: "10" {class: grey}
r3b: "60%" {class: orange}
r3c: "Four in ten tasks fail" {class: orange}
r4a: "20" {class: grey}
r4b: "36%" {class: red}
r4c: "Nearly two in three fail" {class: red}

No row changes the model. Only the chain length changes, and that gap between "it works" and "it ships" is exactly what the harness closes.

Two different failure modes. Same root cause: no harness.

With a harness - specifically with validation, repair loops, and state management - a large fraction of those failures become self-correcting. The model is wrong at step 14, the harness catches it, repairs or retries, and the user sees nothing. Your system reliability can be 99%+ even with an 85% accurate model underneath.

This is engineering. Not hoping the model performs better. Building a system that absorbs model failures and maintains reliability guarantees despite them.

The metric that matters is not model accuracy. It's system reliability. And system reliability is a property of the harness, not the model.

A good prompt makes a demo work. A good harness makes a product survive.


The Discipline Shift: From Prompt Whispering to Systems Engineering

The industry is making a transition right now, and most teams are behind it.

Early LLM adoption was dominated by prompt engineers - people who were skilled at getting good outputs from models through careful instruction. This skill is real and it matters. But it's not sufficient for production systems.

Production LLM systems need AI systems engineers - people who think in terms of failure modes, reliability guarantees, fallback behavior, observability, and system-level correctness. People who instrument their harness, not just their prompts.

The metrics change. You stop tracking ROUGE scores and start tracking:

  • Validation failure rate - what fraction of model outputs fail schema checks?
  • Repair loop success rate - of those failures, how many does the harness self-correct?
  • Circuit breaker trip count - how often is the model endpoint degraded enough to trigger fallback?

Set the two dashboards next to each other. The left one tells you about the model's output; the right one tells you about the system's behavior.

d2
grid-rows: 1
grid-gap: 48
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
old: "Prompt-era metrics" {
  label.near: top-center
  grid-columns: 1
  a: "ROUGE score" {class: grey}
  b: "Outputs that looked\ngood in review" {class: grey}
  c: "\"Why did it say that?\"" {class: grey}
}
new: "Harness metrics" {
  label.near: top-center
  grid-columns: 1
  a: "Validation failure rate" {class: green}
  b: "Repair loop success rate" {class: green}
  c: "Circuit breaker trip count" {class: green}
}

These are harness metrics. They're how you know whether your system is reliable, independent of how "smart" the model is. If you export them as OpenTelemetry traces, the GenAI semantic conventions already define agent and tool-execution spans. They are still marked Development, so pin the attribute names you build dashboards on.

LLMs don't fail gracefully. Systems must.

The mental shift is from "how do I make the model do the right thing" to "how do I build a system that produces the right outcome even when the model does the wrong thing."

These are not the same question. The second one is harder. It's also the one that matters in production.


What to Build First in Your Agentic Workflow

If you're starting from a system with no harness, don't try to build all seven layers at once. The order falls into three tiers:

d2
direction: down
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  orange: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
t1: "Hours of work, biggest win" {
  label.near: top-left
  grid-rows: 1
  a: "1. Validation" {class: green}
  b: "2. Repair loop" {class: green}
}
t2: "Before untrusted input or write actions" {
  label.near: top-left
  grid-rows: 1
  a: "3. Normalization" {class: violet}
  b: "4. Gated execution" {class: violet}
}
t3: "Once the basics hold" {
  label.near: top-left
  grid-rows: 1
  a: "5. Graceful degradation" {class: orange}
  b: "6. State management" {class: orange}
  c: "7. Context orchestration" {class: orange}
}
t1 -> t2
t2 -> t3

Each tier assumes the one above it. Context tuning in the bottom row is worth little while malformed output from the top row still reaches your code.

First: Validation. If you're doing structured output today with no schema validation, you have a reliability bomb. Turn on the provider's strict mode if it supports your schema, and add your own validators now. It takes hours and immediately eliminates the most common failure mode.

Second: The Repair Loop. Wire your validator to send structured error messages back to the model. This alone will recover a significant fraction of your failures without any human intervention.

Third: Normalization. Clean your inputs before they hit the model. Especially if you're taking user input from the web - sanitize for injection patterns and normalize encoding.

Fourth: Gated Execution. If your system has any write operations triggered by model output, add a policy gate before execution. This is non-negotiable for any agentic system.

Fifth: Graceful Degradation. Add fallback behavior and circuit breakers. Your LLM provider will have an incident eventually. How does your system behave when that happens?

Sixth: State Management. Once your agents run for more than a few seconds, add checkpointing. This only becomes critical when you go agentic - but when it matters, it matters immediately.

Seventh: Context Orchestration. Optimize once the basic reliability mechanisms are in place. Don't over-engineer your context pipeline before you've fixed your validation.


The Containment Principle

LLMs are not software components in the traditional sense. They are volatile, high-energy systems that produce probabilistic outputs. In every other engineering domain, volatile components are not trusted - they are contained. The containment layer is what makes the system predictable.

The harness is that containment layer.

You don't ship prompts. You ship systems that survive bad prompts. The model is the least reliable component in your stack - and good systems engineers don't trust their least reliable component. They design around it.

The model gets the credit when the demo works. The harness is the reason the product is still running.


What's Next in This Series

This article introduced the architecture. The next articles go deep on each layer:


Going deeper: the book, layer by layer

This series grew into Harness Engineering for Production AI Systems. The seven layers above are all in it, organised around one question, the Role Test: is this component a sensor that observes, a comparator that checks against a standard, a gate that decides whether a proposal becomes an action, or a bound that caps how far the system can go? A component that is none of the four is application code.

One running example carries the whole book: a billing support agent that reads tickets, looks up invoices, applies credits, and issues refunds, with a human reviewing every reply by day and nobody there overnight. Its refund tool moves money and has no undo, which is what makes the gate design concrete.

Part I - The Harness Is a Control System. The demo cliff, the trust boundary, and the four roles.

Part II - The Four Roles. Input defence, context assembly, signals, validation and repair, resilience, gated execution, deterministic constraints, checkpoints, ceilings, and authority bands. Parts 2 to 8 of this series each became one of these chapters.

Part III - Constructing the Oracle. Testing the harness with no model and with a hostile one, and attributing a failure to the model, the harness, or their interaction.

Part IV - When the Harness Fails. Failure modes of the control layer itself.

Every numbered chapter ships one artifact you can copy into a repository, and every control appears as a plain Python object, as the artifact it reads, and as the LangGraph node that wires it in. The companion code is on GitHub under the MIT License, and its tests run with no API key, no network, and no model: harness-engineering-code.

Each layer in this article has a chapter in the book, and each chapter ends in an artifact you can copy:

  • Layer 1, Normalization - Chapter 4, "Input Defense and Normalisation": the input policy
  • Layer 2, Context orchestration - Chapter 5, "Context Assembly as Managed Infrastructure": the context budget spec
  • Layer 3, Constraints - Chapter 10, "Deterministic Constraint Systems": the tool-safety matrix
  • Layer 4, Gated execution - Chapter 9, "Gated Execution": the gate policy
  • Layer 5, Validation and repair - Chapter 7, "Validation and Repair": the repair ladder
  • Layer 6, Graceful degradation - Chapter 8, "Retry, Fallback, Circuit Breaking": the resilience config
  • Layer 7, State management - Chapter 12, "State, Checkpoints, Resume": the checkpoint spec
  • Harness metrics - Chapter 6, "Signals, and What the Harness Must Emit": the signal schema

For the book one chapter at a time on this blog, starting with Harness Engineering Without an Oracle: What Transfers, see the chapter-by-chapter guide to the book.


References

  1. Liu, N. F., Lin, K., Hewitt, J., et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. Transactions of the Association for Computational Linguistics, 12, 157-173. https://doi.org/10.1162/tacl_a_00638

  2. Ouyang, L., Wu, J., Jiang, X., et al. (2022). Training language models to follow instructions with human feedback. arXiv:2203.02155. https://arxiv.org/abs/2203.02155

  3. Shinn, N., Cassano, F., Labash, B., et al. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. arXiv:2303.11366. https://arxiv.org/abs/2303.11366

  4. Yao, S., Zhao, J., Yu, D., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023. https://arxiv.org/abs/2210.03629

  5. Chase, H. (2022). LangChain: Building applications with LLMs through composability. https://github.com/langchain-ai/langchain

  6. Liu, J. (2023). Instructor: Structured outputs for LLMs. https://github.com/567-labs/instructor

  7. Fowler, M. (2018). Circuit Breaker. martinfowler.com. https://martinfowler.com/bliki/CircuitBreaker.html

  8. Chen, S. (2026). The Complete Guide to Agent Harness: What It Is and Why It Matters. harness-engineering.ai. https://harness-engineering.ai/blog/agent-harness-complete-guide/

  9. Kumar, R. (2026). Harness Engineering for Production AI Systems. Part I, "The Harness Is a Control System" (Chapters 1-3); Chapter 7, "Validation and Repair"; Chapter 9, "Gated Execution." https://harness.ranjankumar.in/

  10. Lopopolo, R. (2026). Harness engineering: leveraging Codex in an agent-first world. OpenAI. https://openai.com/index/harness-engineering/

  11. Anthropic (2025). Effective harnesses for long-running agents. Anthropic Engineering. https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents

  12. LangChain (2025). Agent Frameworks, Runtimes, and Harnesses - oh my! LangChain Blog. https://blog.langchain.com/agent-frameworks-runtimes-and-harnesses-oh-my

  13. Anthropic. Structured outputs. Claude Developer Platform documentation. https://platform.claude.com/docs/en/build-with-claude/structured-outputs

  14. OpenAI. Structured Outputs. OpenAI API documentation. https://platform.openai.com/docs/guides/structured-outputs

  15. OpenTelemetry. GenAI semantic conventions. https://github.com/open-telemetry/semantic-conventions-genai


Systems Design

Follow for more technical deep dives on AI/ML systems, production engineering, and building real-world applications:


Books by Ranjan Kumar

Federated AI Agents cover

Federated AI Agents

Right-Sized AI cover

Right-Sized AI

Harness Engineering for Production AI Systems cover

Harness Engineering

The 7 GenAI Architectures cover

The 7 GenAI Architectures

Building Real-World Agentic AI Systems with LangGraph cover

Building Real-World Agentic AI Systems

The ChatML Handbook cover

The ChatML Handbook

The Chat Templates Handbook cover

The Chat Templates Handbook

Comments