← All writing

Your agent demo worked. Here's why it dies in production

· Muaaz Ahmad

Picture a familiar story (illustrative, not a specific client): the demo goes well. The agent reads the ticket, calls three tools, writes a clean reply, and the room nods. Two weeks into the pilot it double-books a shipment, stalls for 40 seconds on a provider outage, and keeps answering a customer who has been asking for a human for ten minutes.

None of that is a model problem. A demo runs on the happy path: one user, warm caches, no rate limits, tools that never time out. Production runs on everything else.

The numbers back this up. Datadog's State of AI Engineering 2026, built from production telemetry, found that about 5% of AI model requests fail in production, and nearly 60% of those failures come from capacity limits. McKinsey's 2026 State of AI survey shows 40% of large organizations now scaling agents, up from 27% a year earlier, while smaller organizations sit flat at 22%. And Gartner still forecasts that over 40% of agentic AI projects will be cancelled by the end of 2027, citing cost, unclear value and weak risk controls.

The gap between "it works" and "it works on Tuesday at peak" is mostly engineering you can list, check off, and test. Here are six failure modes, each with the fix and a check you can run today.

Diagram: six checks (retries, rate limits, fallbacks, idempotent tools, human handoff, kill switch) between an agent demo and real traffic

1. Retries that make things worse

The failure. The demo either has no retries or a bare while True: try again. In production, a provider hiccup turns into a retry storm: every worker retries at once, you burn your rate limit faster, and requests that could never succeed (a bad payload, an expired key) loop until the user gives up.

The fix. Retry only what is retryable, back off exponentially with jitter, honour retry-after, and cap total attempts. For the Claude API specifically: 429 (rate limit), 500, 504 and 529 (overloaded) are worth retrying; 400, 401, 403 and 413 will fail the same way every time. Anthropic's docs also note that a spend-cap 429 has no retry-after header and keeps failing until access resumes, so treat it as fatal, not transient. The official SDKs already retry twice by default with backoff; know that before you wrap them in a second retry loop and multiply your attempts.

import random, time

RETRYABLE = {429, 500, 502, 503, 504, 529}

def call_with_backoff(fn, max_attempts=4, base=0.5, cap=20.0):
    for attempt in range(max_attempts):
        try:
            return fn()
        except ApiError as e:            # your client's error type
            status = e.status_code
            if status not in RETRYABLE or attempt == max_attempts - 1:
                raise
            if status == 429 and not e.headers.get("retry-after"):
                raise                    # spend cap: retrying won't help
            wait = float(e.headers.get("retry-after") or 0) or \
                   random.uniform(0, min(cap, base * 2 ** attempt))  # full jitter
            time.sleep(wait)

Check today: grep your agent for retry logic. Count the layers (SDK + your wrapper + framework + queue). If the product of their attempt limits is above ~6, you have a retry storm waiting to happen.

2. Rate limits you only meet at scale

The failure. One tester never hits tokens-per-minute limits. Fifty concurrent users running multi-step agents do, and since Datadog also reports tokens per request more than doubling year over year for median teams, your headroom shrinks even if traffic doesn't grow.

The fix. Treat model capacity like a database connection pool. Put a concurrency limit (a semaphore) in front of every provider, queue work instead of firing it, and set a per-tenant token budget so one heavy customer can't starve the rest. Read the rate-limit headers on every response and log remaining capacity alongside latency.

Check today: run a load test at 3x your expected peak concurrency for ten minutes. Record the 429 rate. If it's above zero, decide now whether those requests queue, degrade, or fail fast.

3. No plan for when the model is down

The failure. The agent has one model, one region, one provider. When it's overloaded, your product is down, even though the task was a simple classification any smaller model could handle.

The fix. Write a fallback chain per task, not per app. A routing step might fall back from your primary model to a smaller one; a high-stakes drafting step might fall back to "save the draft and tell the user it will be ready shortly." Datadog found 69% of companies already use three or more models, so the plumbing usually exists; the decision table usually doesn't.

Step typePrimary fails →Then
Classification / routingSmaller model, same providerRules-based default route
Retrieval answerSecond provider"I couldn't answer that right now" + handoff
Irreversible actionDon't fall backQueue for retry or human approval

Check today: for each agent step, fill in the right two columns. Any blank cell is an outage you haven't designed yet.

4. Tools that do things twice

The failure. The agent calls create_booking, the request times out, the framework retries, and now there are two bookings. Timeouts don't tell you whether the first call landed. This is the failure that loses clients, because it shows up in their data, not your logs.

The fix. Every tool with a side effect gets an idempotency key, and the key is derived from the run, not generated fresh on each attempt. Stripe's API is the reference pattern: the server stores the result of the first request for a key and returns it on retries. If the downstream system has no idempotency support, keep a small ledger yourself.

import hashlib

def idem_key(run_id: str, step: int, tool: str, args: dict) -> str:
    raw = f"{run_id}:{step}:{tool}:{sorted(args.items())}"
    return hashlib.sha256(raw.encode()).hexdigest()[:32]

def call_tool_once(ledger, run_id, step, tool, args, fn):
    key = idem_key(run_id, step, tool, args)
    if (hit := ledger.get(key)) is not None:
        return hit                      # replay, don't re-execute
    result = fn(**args, idempotency_key=key)
    ledger.put(key, result, ttl_hours=24)
    return result

LangGraph's durable execution docs make the same point: if you resume from checkpoints, your steps need to be deterministic and idempotent, with side effects wrapped so they don't re-run on replay.

Check today: list every tool your agent can call. Mark each one read-only or side-effecting. Every side-effecting tool without an idempotency key is a bug.

5. No way out to a human

The failure. The user types "let me talk to someone" and the agent apologises and tries again. Or the agent is 60% confident about a refund and issues it anyway.

The fix. Define handoff triggers before launch, in code, not in the prompt alone: the user explicitly asks; the same intent fails twice; a tool returns an error the agent can't classify; an action crosses a money or risk threshold. When a trigger fires, pause the run and preserve state so the human sees the whole context and can resume or cancel. In LangGraph that's interrupt() with a durable (database-backed) checkpointer and a thread_id; the docs are explicit that the in-memory saver is for development only.

Check today: write your handoff triggers as a list of four or five conditions. If any of them only exists as a sentence in the system prompt, move it into code.

6. No kill switch

The failure. Something goes wrong at 2 a.m. (a prompt regression, a tool hammering a client API, a loop spending tokens) and the only way to stop it is a redeploy.

The fix. Three switches, all controllable without a deploy:

  • Global off: a feature flag that routes all traffic to the non-agent path or a holding message.
  • Per-tool off: disable one tool (say, send_email) while the rest keep working.
  • Hard caps per run: max steps, max tokens, max wall-clock time. When a cap trips, end the run and log it as an incident, not a success.

Check today: ask the person on call how they'd stop the agent from sending emails right now. If the answer involves a pull request, build the switch first.

The go-live checklist

Copy this into your launch ticket. Every line needs an owner and a "tested on" date, not just a tick.

  • Retries: retryable codes only, jittered backoff, retry-after honoured, total attempts across all layers ≤ 6
  • Rate limits: concurrency limit per provider, per-tenant token budget, 3x-peak load test passed
  • Fallbacks: decision table filled for every step, irreversible actions never fall back silently
  • Idempotency: every side-effecting tool keyed by run + step, ledger with TTL
  • Human handoff: triggers in code, durable checkpointer, handoff tested end to end with a real person
  • Kill switch: global flag, per-tool flags, step/token/time caps per run
  • Observability: every run traced with request IDs, tool calls, retries and fallbacks visible
  • Failure drill: one hour of injected 429s, timeouts and tool errors in staging before launch

That last line is the one teams skip. Pick an hour, point a fault-injection proxy at staging, and return a 429 on one call in ten and a timeout on one in twenty. Watch what the agent does. Whatever surprises you there would have surprised your client in production.

The real job

Building the agent is the part that demos well. Making it boring under load is the part that gets it renewed. If you're the engineer deployed inside a customer's stack, this checklist is the work: it's what turns a promising pilot into something the ops team stops worrying about.

Sources

Originally published on Substack.

Newsletter

Get the next post by email

Production AI engineering, three times a week. Free, on Substack.

Need this built for real?

I take systems like this into production. Email me or download the CV.