CLAUDE LABJP
COWORK — Claude Cowork expands to web and mobile with remote sessions, synced files, and a shared Chat and Cowork home across devicesM365 — Claude Cowork adds Microsoft 365 write tools to draft and send email, manage calendars, and update OneDrive and SharePoint filesMCP — Admins can provision MCP connectors org-wide through their identity provider, starting with Okta, with access granted on first loginCODE — Claude Code fixes SessionStart hook streaming in headless sessions so remote workers are not idle-reaped mid-hookGOV — Claude Code and Claude Cowork are in public beta in Claude for Government Desktop on a FedRAMP High authorized environmentLIMITS — Claude Code weekly usage limits are increased by 50% through July 13COWORK — Claude Cowork expands to web and mobile with remote sessions, synced files, and a shared Chat and Cowork home across devicesM365 — Claude Cowork adds Microsoft 365 write tools to draft and send email, manage calendars, and update OneDrive and SharePoint filesMCP — Admins can provision MCP connectors org-wide through their identity provider, starting with Okta, with access granted on first loginCODE — Claude Code fixes SessionStart hook streaming in headless sessions so remote workers are not idle-reaped mid-hookGOV — Claude Code and Claude Cowork are in public beta in Claude for Government Desktop on a FedRAMP High authorized environmentLIMITS — Claude Code weekly usage limits are increased by 50% through July 13
Articles/API & SDK
API & SDK/2026-03-31Advanced

Building Self-Healing AI Agents with Claude API — Error Detection, Auto-Recovery, and Graceful Degradation Patterns for Production

Learn how to build production-grade AI agents that automatically detect failures and self-heal using Claude API. Covers retry strategies, fallback chains, Supervisor patterns, and observability pipelines.

claude-api78agent12self-healingerror-handling11production109resilience9typescript11

Premium Article

The Night I Finally Took Self-Healing Seriously

As an indie developer running my own apps and services, the thing that keeps me up at night isn't writing new features — it's what happens when something quietly breaks at 3 a.m. Billing validation, outbound API calls, automated responses — when any of these stall, the morning's revenue and reputation take the hit.

When I first started building agents with Claude API, I fell into the classic trap of writing demo code for the happy path. Rate limits, tool timeouts, model hallucinations — I wasn't designing under the assumption that they will happen.

Running an agent in production teaches you that AI-system failures are qualitatively different from ordinary server failures. A single 429 response doesn't just need a retry — it forces a four-way decision: retry as-is, switch to a different model, compress the context, or escalate to a human. Wrapping everything in a circuit breaker isn't enough.

A self-healing agent is one that classifies these AI-specific failures on its own and picks the right recovery strategy. The patterns I describe here come from running Dolice Labs (Claude Lab, Gemini Lab, Antigravity Lab, Rork Lab) in parallel as an indie operator, so the focus is operational rather than theoretical. Working TypeScript is included throughout.

Six Operational Gotchas Apple's, AWS's, and Anthropic's Docs Don't Mention

Before the patterns themselves, here are six things I had to learn the hard way running Claude API against real traffic. The SDK reference doesn't say these out loud, but you'll hit every one of them once you go past demo scale.

1. You'll see 529 (overloaded), not just 429

When classifying Anthropic.APIError, expect 529 "regional overload" in addition to rate-limit 429s. 529 usually arrives without a retry-after header, so reusing your 429 back-off logic isn't enough. In my experience, 529s tend to clear within a few minutes, so my rule is: exponential back-off up to 60 seconds, then switch to a different model if it still hasn't recovered.

2. On tool timeouts, return an error string — never an empty one

If you abort a tool call with AbortController, Claude assumes the call completed and waits for the next message. I learned the hard way that returning an empty string in tool_result triggers parsing crashes downstream. I now always return something like "ERROR: tool timed out after 30s, please proceed without this data". English error strings get interpreted by Claude more reliably than localized ones.

3. To resume a broken stream, preserve tool_use_id

If a stream: true request is cut off mid-stop_reason: tool_use, you have to rebuild the request with the matching tool_use_id in the next tool_result, or Claude loses track of context. I store these snapshots in a local SQLite table and replay them on reconnect.

4. A Sonnet Supervisor is more expensive than you'd expect

I initially built the Supervisor with Sonnet because "smart monitoring sounds good." Measured cost was around 3,000 tokens per incident, roughly ¥1.5 (about $0.01). At 1,000 incidents per day — easily reachable at small production scale — that's ¥1,500 daily, ¥45,000 monthly. Swapping the Supervisor to Haiku kept quality steady and cut the cost by roughly 75%. The Supervisor is doing classification, not creative work; Haiku is enough.

5. Context-compression summaries hallucinate

Asking a separate Claude call to summarize a long context works, but the summary itself hallucinates. I once shipped a system that swapped "succeeded" and "failed" tool results during summarization. The fix that worked: temperature: 0, plus a system prompt that says "summarize facts only, no inference, mark anything unclear as 'unknown'." Hallucinations dropped sharply.

6. Cloudflare Workers is a bad host for the agent loop

Dolice Labs runs on Cloudflare Workers + OpenNext, but Workers' CPU time limits (50 ms free, 30 s paid) don't accommodate long agent loops. Three self-healing retries alone will blow past it. I now run the agent body on Lambda, Cloud Run, or a small VM. Workers is great for result storage and lightweight state transitions, but the loop itself wants somewhere it can sit and breathe.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
Classify 7 categories of AI-agent-specific errors and assign the optimal recovery strategy to each — full production implementation
Working TypeScript code for the Supervisor pattern, fallback chains, and graceful degradation that you can drop into a real system
Hard-won indie-developer lessons distilled into observability and cost-vs-reliability trade-offs that keep you from getting paged at night
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

API & SDK2026-06-19
When Your Claude × Playwright Browser Agent Fails While Reporting Success — Verifying Actions and Catching UI Drift
A vision-driven Claude + Playwright browser agent fails quietly: it reports success while nothing actually changed. Here is how to stop trusting self-reports, verify each action against the goal, and detect UI drift before it breaks you.
API & SDK2026-03-27
Claude API Production Resilience Patterns — Model Routing, Circuit Breakers, and Fallback Strategies for Indie Teams
Production resilience patterns for Claude API: circuit breakers, intelligent model routing, fallback chains, exponential backoff with jitter, and disaster recovery — with TypeScript implementations and operational lessons from running Dolice Labs across four sites as an indie developer.
API & SDK2026-06-28
A Silent Drop to a Weaker Model Is Scarier Than an Error: Designing a Capability Floor for Claude API Fallback
When a model becomes unavailable in an unattended pipeline, automatically dropping to a weaker model is dangerous. Drawing on years of running automated indie pipelines, this is how to use per-task capability contracts and a degradation budget to decide where to stop.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →