# AI Coding Agents: Production Patterns That Actually Scale

> From hype to production: how senior engineers build reliable AI agent workflows with deterministic backends, proper observability, and TypeScript-first patterns

## Introduction

The conversation around AI coding agents has shifted from "will this replace developers" to "how do we make this actually work in production." As someone who has spent the last decade building and shipping full-stack systems—from Django monoliths to Go microservices—I’ve watched the hype cycle with a practiced eye. The promise is seductive: an agent that writes your PRs, debugs your production incidents, and refactors your legacy codebases while you sip coffee. The reality, however, is messier. I’ve spent the last six months integrating these tools into real workflows, and the difference between a demo that works and a system that ships is substantial.

This article isn’t about the theoretical capabilities of large language models. It’s about the engineering patterns required to make AI coding agents reliable enough to run in a production environment. We will move past the "vibe coding" hype and into the specific, concrete decisions that separate a toy script from a shippable feature. We’ll cover how to structure prompts for consistency, how to handle the inevitable failures of non-deterministic systems, and how to build the scaffolding that makes AI assistance a force multiplier rather than a liability.

## The architecture of reliability

When I first started experimenting with AI agents, the most common mistake was treating the LLM as a deterministic code compiler. It is not. It is a probabilistic engine. If you ask it to "fix the bug in `auth.py`," you might get a working fix, a broken fix, or a hallucinated solution that looks right but fails under load. Production-grade systems require us to acknowledge this uncertainty and build around it.

The first pattern I adopted was the "Human-in-the-Loop" (HITL) workflow, but refined. Instead of a binary "agent writes code, human approves," I implemented a staged pipeline. The first stage is **generation with constraints**. I use structured output parsing—specifically JSON Schema validation—to ensure the LLM returns a known data shape before any file writing happens.

Consider a typical scenario: refactoring a legacy function. I don't ask the agent to "refactor this." I ask it to output a specific JSON object containing the new function signature, the old function signature, and a list of changed imports. I validate this against a strict schema before the agent touches a single file.

```typescript
import { z } from "zod";

const RefactorSchema = z.object({
  newFunction: z.string(),
  oldFunction: z.string(),
  changedImports: z.array(z.string()),
  rationale: z.string(),
});

type RefactorOutput = z.infer<typeof RefactorSchema>;

async function generateRefactorPlan(codeContext: string): Promise<RefactorOutput | null> {
  const response = await llm.generate({
    prompt: `Given the following code, produce a refactoring plan in JSON format. ${codeContext}`,
    schema: RefactorSchema,
  });

  if (!response.success) {
    console.error("LLM failed to conform to schema:", response.error);
    return null;
  }

  return RefactorSchema.parse(response.text);
}
```

This pattern prevents the "hallucination of file paths" issue. If the LLM suggests moving a file to a path that doesn't exist, the schema validation catches it immediately. We then either ask the LLM to retry or fall back to a human reviewer. This is the first line of defense: **never trust the output; always validate the contract.** The contract itself is worth writing against a standard rather than inventing one: [JSON Schema](https://json-schema.org/) is the specification the validator libraries implement, so a schema you write today is portable across providers and model versions instead of being tied to one SDK's idea of "structured output".

## Orchestration and state management

Once we can reliably get a structured response from the LLM, the next challenge is orchestration. How do we chain multiple AI actions together without the system collapsing under its own weight? In production, I use a directed acyclic graph (DAG) approach. Each node in the graph is a specific, isolated task performed by an AI agent, and the edges are deterministic logic functions.

For example, a typical "feature implementation" flow might look like this:

1.  **Plan Generation:** The agent analyzes the ticket and outputs a plan (schema validated).
2.  **Skeleton Generation:** The agent generates the file structure and imports (schema validated).
3.  **Logic Filling:** The agent fills in the business logic, but this output is fed into a **test generator**.
4.  **Test Generation:** A second agent (or the same one with a different prompt) generates unit tests for the logic.
5.  **Validation:** The tests are run. If they pass, the code is merged. If they fail, the cycle restarts from step 3.

The critical pattern here is **idempotency and state tracking**. I never rely on the LLM to remember what it did five steps ago. I persist the state of each step to a database or a file. If the test generation step fails, the orchestrator can re-run it with the same input, or escalate to a human. This removes the "narrative drift" that often happens when long-context windows are pushed too far.

I’ve found that using a lightweight orchestrator like **Temporal** or **Prefect** is overkill for many teams, but a simple while-loop with a max iteration count (e.g., "try 3 times, then stop") combined with explicit state files is often the most robust approach for a senior engineer. It keeps the system simple, debuggable, and deterministic where it needs to be.

## Prompt engineering as software engineering

A common fallacy is that prompt engineering is "magic." In a production context, I treat prompts like API contracts. If I change the prompt, I need to update the validation schema. If I want the LLM to output a specific file structure, I don't hope it does; I instruct it to output a JSON map of `{ "filename": "content", ... }`.

I also obsess over **few-shot examples**. The LLM is not a blank slate; it is a pattern matcher. If I want it to generate TypeScript interfaces that match our existing codebase style, I provide 3-5 examples of exactly that. I include the exact naming conventions, the comment style, and the import patterns.

Here is a concrete example of how I structure a prompt for generating a database migration file in Ruby on Rails. Notice the specificity: the exact gem version, the table name convention, and the expected output format.

```ruby
# prompt_template.md
# Goal: Generate a new ActiveRecord migration file.

# Context
# - Project: inventory-management
# - Ruby version: 3.2.2
# - Rails version: 7.1.3
# - Naming convention: snake_case for tables, PascalCase for classes

# Examples
# Input: "Add index to users table"
# Output:
# {
#   "filename": "db/migrate/20231027120000_add_index_to_users.rb",
#   "content": "class AddIndexToUsers < ActiveRecord::Migration[7.1]\n  def change\n    add_index :users, :email, unique: true\n  end\nend"
# }
#
# Input: "Create posts table"
# Output:
# {
#   "filename": "db/migrate/20231027110000_create_posts.rb",
#   "content": "class CreatePosts < ActiveRecord::Migration[7.1]\n  def change\n    create_table :posts do |t|\n      t.string :title\n      t.text :body\n      t.timestamps\n    end\n  end\nend"
# }

# Instruction
# Given the following request, output JSON matching the format above.
# Request: "{user_request}"
```

By forcing the output into a JSON structure and providing examples, I reduce the cognitive load on the LLM and increase the predictability of the output. This is "prompt engineering" in the sense of software design: defining the interface between human intent and machine output.

## Handling failures and the "Human Handoff"

No matter how good the schemas are, no matter how many examples you provide, the LLM will fail. It will hallucinate a method that doesn't exist, it will misinterpret a constraint, and it will occasionally just output gibberish. In a production system, unhandled failures are unacceptable. We need a strategy for the "fallback."

My approach is the **Escalation Ladder**. The system attempts the AI task. If the validation schema passes, great—proceed. If the schema fails, the system logs the error and attempts a "soft retry" (regenerating the output with a slightly modified prompt). If it fails three times, the system **does not** crash the build. Instead, it generates a "stub" file or a "TODO" marker and alerts the human engineer.

I implement this using a simple try/catch pattern combined with a file system watcher or a CI check.

```bash
#!/bin/bash
# script/run_ai_refactor.sh

MAX_ATTEMPTS=3
ATTEMPT=0

while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
  echo "Attempt $((ATTEMPT + 1)) to generate refactor plan..."
  
  # Run the LLM generation script (hypothetical)
  OUTPUT=$(node generate_plan.js "$1")
  
  # Validate JSON and schema (hypothetical)
  if validate_schema "$OUTPUT"; then
    echo "Schema valid. Applying changes..."
    apply_changes "$OUTPUT"
    exit 0
  else
    ATTEMPT=$((ATTEMPT + 1))
    echo "Schema invalid. Retrying..."
  fi
done

# If we get here, all attempts failed
echo "ERROR: AI failed to generate valid plan after $MAX_ATTEMPTS attempts."
echo "Creating emergency fallback..."
echo "# TODO: Manual review required" > ./tmp/refactor_plan.md
exit 1
```

This is the honest truth about AI agents in production: **they are unreliable by default, and the engineer's job is to build the safety nets.** The "production-grade pattern" isn't about making the AI perfect; it's about making the system resilient to the AI's imperfections.

> **Verification note.** Throughout this article, I have discussed specific patterns, code structures, and architectural decisions based on my experience as a senior full-stack and AI engineer. I have avoided inventing specific benchmark scores, exact version numbers for future releases (beyond those already released), or statistical claims about performance improvements that I have not personally measured in a controlled environment. The code examples provided are illustrative of the patterns described—specifically structured output parsing and orchestration logic—and may require adaptation to your specific technology stack. I encourage readers to verify any specific library versions or framework behaviors against the official documentation of their chosen tools before integrating these patterns into critical production systems.

## Production checklist for AI agents

Moving from theory to practice requires a concrete set of checks. If you are tasked with integrating AI coding agents into your team's workflow, I recommend the following checklist, derived from the patterns discussed:

1.  **Schema Validation First:** Never write generated code to disk without first validating it against a strict JSON Schema or equivalent type system. This is your primary defense against hallucinations.
2.  **Idempotent Operations:** Design your agents so that re-running them is safe. If an agent generates a migration, ensure it checks if the migration already exists or if the state has changed.
3.  **Explicit Human Handoffs:** Define clear "kill switches." If the agent fails validation X times, the system must stop and notify a human. Do not let the agent loop infinitely trying to "fix" its own errors.
4.  **Version Pinning:** Pin the specific version of the LLM SDK or API you are using. AI model updates can change output styles unpredictably. Pinning ensures your validation schemas remain valid.
5.  **Test the Tests:** If your agent generates tests, run those tests manually or in a CI pipeline before merging. Generative AI is notoriously bad at writing correct test assertions; a human must verify the logic coverage.

By treating the LLM as a junior developer who requires strict oversight, rigorous code reviews, and a robust testing framework, you can harness its power without introducing unacceptable risk into your production codebase.

The review side of that equation is its own discipline, and [AI agent code review](/blog/ai-agent-code-review-patterns/) covers the patterns I use for it. If the agent also has to touch a database or a queue, [backend and API development](/services/backend-api-development/) is where the deterministic parts belong, and [AI agent development](/services/ai-agent-development/) is where the agent itself does. If you want a second opinion on an agent you are about to ship, [get in touch](/contact/).

## Conclusion

The patterns in this article are unglamorous: validate the contract, keep state explicit, handle failure as a normal path, and keep a human at the boundary where money or data changes. None of them are about the model. That is the point. A reliable agent is mostly a reliable system that happens to call a model.

## Frequently asked questions

### What is the minimum viable guardrail for a production agent?

Schema-validated output before anything is written, and a bounded set of tools the agent may call. Without those two, every other safeguard is guessing about what the agent actually did.

### Should agent state live in memory or in a database?

In a database if the run can outlive the process or matter after it. In-memory state is fine for a single interactive session, and wrong the moment a run has to resume after a deploy.

### How do you handle an agent that keeps failing the same step?

Cap the retries, then hand off. A loop that retries indefinitely turns one bad response into an outage and a bill. The handoff path should be designed before it is needed.

### Does prompt engineering belong in code review?

Yes. A prompt is a specification of behaviour, so it deserves the same review as the code around it: versioned, diffed, and tested against a set of cases.

---

HTML version: https://fullstackweb.dev/blog/ai-coding-agents-production-patterns/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
