When you orchestrate multiple agents working together, you’re dancing on the edge of complexity. One agent times out, and suddenly your whole pipeline falls apart. Another one runs out of context mid-task. A third tries to modify a file that another agent is already writing to. Welcome to the chaos of multi-agent orchestration—where things fail in ways that single-agent systems never do.
This is where error handling becomes architecture. You can’t just wrap things in try-catch blocks and hope for the best. You need patterns. You need visibility. You need strategies that let your agents recover, adapt, and keep moving forward even when things go sideways.
In this guide, we’re going to walk through the real failure modes you’ll encounter in multi-agent Claude Code workflows, the battle-tested patterns for handling them, and how to build systems that don’t just fail gracefully but actually learn from their failures.
Why Multi-Agent Systems Fail Differently
Before we talk about solutions, let’s understand the problem space. A single agent running a task fails in predictable ways: it runs out of context, times out, or encounters a permission error. Done. You know what went wrong.
But when you have agents working together—especially when they’re touching shared state—things get gnarly fast.
Cascading failures are the silent killer. Agent A modifies a file. Agent B tries to read that file while A is still writing. Agent C depends on both A and B finishing correctly. If A fails, B’s input is corrupted, and now C has garbage data. Your whole system cascades down from there. Imagine you’re building a story. The architect agent creates an outline, the character agent reads that outline, the world-builder reads both. If the architect produces a malformed outline, every downstream agent gets bad input. The character agent might create inconsistent profiles. The world-builder might design a world that contradicts the plot. You’ve wasted tokens and now you’re stuck fixing inconsistencies that shouldn’t have existed in the first place.
Context overflow happens differently too. In a single agent, you know roughly how much context you’re using. In a multi-agent workflow, you might have five agents each building up their own context, passing results between them. Suddenly, Agent D’s input from Agent C contains 50,000 tokens of accumulated history, and Agent D explodes. This is particularly nasty because it’s silent. Agent C succeeds. It just returns a massive output. Agent D takes it as input and quietly produces garbage because the context is so polluted. You won’t know it happened until you review the output.
Timeout cascades are brutal. Agent A takes 30 seconds (still within limits). Agent B waits for A, adds another 30 seconds. Agent C waits for both. Now you’re at 90+ seconds, and your orchestrator timeout kicks in, killing the whole run. Meanwhile you’ve burned tokens on Agent A and Agent B for nothing. The cascading timeouts aren’t just failures—they’re expensive failures.
Tool permission conflicts are insidious. Two agents try to write to the same file. One succeeds, one fails. Which one? The one that went first. The one with better luck. Your system is now non-deterministic and unreliable. You run the pipeline twice and get different results. That’s a nightmare to debug.
Model degradation happens silently. You spin up three agents: Opus for the hard thinking, Sonnet for the fast work, Haiku for the trivial stuff. But Opus hits a rate limit. Now Sonnet is running the hard thinking work and failing quietly because it doesn’t have the reasoning power. The output looks reasonable but it’s missing nuance. It’s incomplete. Users trust it and make decisions based on bad information.
These aren’t bugs in the traditional sense. They’re the cost of parallelism, shared state, and complexity. The good news? They’re all patterns you can handle if you know what to look for. That’s what the rest of this article covers.
Pattern 1: Retry with Exponential Backoff
The simplest and most effective error handling pattern is the retry loop. But vanilla retries are amateur hour. You need exponential backoff—increasingly long waits between retry attempts—to give your system time to recover from transient failures without hammering it into submission.
Here’s what a basic retry handler looks like in a Claude Code workflow:
#!/bin/bash
# Retry with exponential backoff
retry_agent() {
local agent_name="$1"
local task="$2"
local max_attempts=5
local initial_delay=2 # seconds
local attempt=1
while [ $attempt -le $max_attempts ]; do
echo "[ATTEMPT $attempt/$max_attempts] Running $agent_name: $task"
# Run the agent and capture both output and exit code
agent_output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
# Success case
if [ $exit_code -eq 0 ]; then
echo "[SUCCESS] $agent_name completed on attempt $attempt"
echo "$agent_output"
return 0
fi
# Check if it's a retryable error
if echo "$agent_output" | grep -qE "timeout|rate.limit|temporary"; then
delay=$((initial_delay * (2 ** (attempt - 1))))
echo "[RETRYABLE] Waiting ${delay}s before retry..."
sleep "$delay"
((attempt++))
continue
fi
# Non-retryable error - fail fast
echo "[FATAL] Non-retryable error from $agent_name:"
echo "$agent_output"
return 1
done
echo "[EXHAUSTED] $agent_name failed after $max_attempts attempts"
return 1
}
# Usage: retry_agent "story-architect" "outline the three-act structure"
Why this works: Exponential backoff prevents you from DDOSing your own system. The delays grow exponentially—2s, 4s, 8s, 16s, 32s—giving transient failures time to clear without burning through all your retries in seconds. You’re being respectful of the rate limit. You’re also being smart about it. Each retry assumes the system might be recovering, so you give it progressively more time.
The key insight: Not all failures are retryable. Rate limits? Timeouts? Temporary API issues? Retry. Permission denied? File not found? Context overflow? These are permanent failures—retrying is just wasting time and money. You need to classify errors properly.
In production systems, the cost of retries adds up quickly. Every failed attempt burns tokens, consumes API quota, and delays your users. The real sophistication in error handling comes from knowing which errors to retry and when to fail fast instead.
Here’s how you classify errors:
is_retryable_error() {
local error_message="$1"
case "$error_message" in
*"timeout"*)
return 0 # retryable
;;
*"rate.limit"*)
return 0
;;
*"temporarily unavailable"*)
return 0
;;
*"connection reset"*)
return 0
;;
*"Permission denied"*)
return 1 # not retryable
;;
*"File not found"*)
return 1
;;
*"context.*overflow"*)
return 1 # need to reduce context, not retry
;;
*)
return 1 # default to not retryable
;;
esac
}
# Enhanced retry with error classification
retry_agent_smart() {
local agent_name="$1"
local task="$2"
local max_attempts=3
local attempt=1
while [ $attempt -le $max_attempts ]; do
agent_output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
return 0
fi
if is_retryable_error "$agent_output"; then
delay=$((2 ** (attempt - 1)))
echo "[RETRYABLE] Waiting $((delay))s..."
sleep "$delay"
((attempt++))
else
echo "[FATAL] Non-retryable error"
return 1
fi
done
return 1
}
The pitfall: Exponential backoff can lull you into a false sense of security. You retry, it succeeds, life is good. But if the underlying condition that caused the failure isn’t fixed, you’re just delaying the inevitable crash. Use retries for transient failures only. If an agent consistently fails even with retries, that’s a permanent problem and you need a different strategy.
Real scenario: Your API is under load. You get a rate limit. You wait 2 seconds, retry, it succeeds. You’ve handled a transient condition gracefully. Compare that to just failing immediately—you’d break your user’s workflow unnecessarily. But also, if rate limits are constant (happening on every invocation), retrying isn’t the solution—you need to reduce load or upgrade your API tier.
Pattern 2: Fallback Agents and Graceful Degradation
Here’s a scenario that happens constantly in production: you design your workflow around Opus because it’s the most capable. But Opus hits a rate limit. Your entire workflow stalls.
This is where fallback agents come in. When your primary agent fails, you don’t fail the whole task—you degrade gracefully to a simpler, faster model that might not be perfect but is better than nothing.
The sophistication here is understanding when degradation is acceptable. You can’t degrade from a specialized financial analysis agent to Haiku and expect the same quality. But for exploratory work, brainstorming, or basic refactoring, Haiku might be perfectly adequate. The key is matching degradation strategies to task requirements.
#!/bin/bash
# Fallback chain: try Opus first, then Sonnet, then Haiku
execute_with_fallback() {
local task="$1"
local agent_chain=("story-architect-opus" "story-architect-sonnet" "story-architect-haiku")
for agent in "${agent_chain[@]}"; do
echo "[TRY] Attempting with $agent"
output=$(dispatch "$agent" "$task" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo "[SUCCESS] Completed with $agent"
echo "$output"
return 0
fi
# Check if this is a rate limit (try next agent)
if echo "$output" | grep -q "rate.limit"; then
echo "[FALLBACK] $agent rate-limited, trying next"
continue
fi
# Other errors: log and try next
echo "[ERROR] $agent failed, trying next"
done
echo "[FAILED] All fallback agents exhausted"
return 1
}
Why this works: You’re not just hoping for recovery—you’re actively managing degradation. Your system can still make progress, even if it’s with a less powerful model. The user gets a working result instead of a timeout error. This is crucial for user experience. A slightly worse answer is better than no answer at all.
Real-world example: Imagine you’re building an outline. Opus is ideal—it understands story structure deeply, can balance multiple plot threads, understands pacing and narrative momentum. But it’s rate-limited. Sonnet can still create a workable outline; it just might miss some of the nuance. It might oversimplify subplots or miss opportunities for foreshadowing. Haiku can create a basic outline—worse quality, but something. Your workflow completes instead of failing. The user gets content, even if it’s not optimal.
The trick is knowing what quality is acceptable at each level. This isn’t arbitrary—it’s based on your domain expertise and user expectations. For critical tasks, you might only accept Opus output. For utility tasks, Haiku is fine. Build quality thresholds into your fallback logic:
execute_with_fallback_and_quality_check() {
local task="$1"
# Try Opus
echo "[1] Attempting with Opus (best quality)"
opus_output=$(dispatch "story-architect-opus" "$task" 2>&1)
opus_exit=$?
if [ $opus_exit -eq 0 ] && validate_quality "$opus_output" "high"; then
echo "$opus_output"
return 0
fi
# Opus failed or quality is poor, try Sonnet
echo "[2] Falling back to Sonnet (medium quality)"
sonnet_output=$(dispatch "story-architect-sonnet" "$task" 2>&1)
sonnet_exit=$?
if [ $sonnet_exit -eq 0 ] && validate_quality "$sonnet_output" "medium"; then
echo "$sonnet_output"
return 0
fi
# Sonnet failed, try Haiku
echo "[3] Falling back to Haiku (basic quality)"
haiku_output=$(dispatch "story-architect-haiku" "$task" 2>&1)
haiku_exit=$?
if [ $haiku_exit -eq 0 ] && validate_quality "$haiku_output" "basic"; then
echo "$haiku_output"
return 0
fi
return 1
}
# Validate that output meets minimum quality threshold
validate_quality() {
local output="$1"
local threshold="$2"
# Count non-empty lines as a basic quality metric
local line_count=$(echo "$output" | wc -l)
case "$threshold" in
"high")
[ "$line_count" -gt 50 ] && return 0
;;
"medium")
[ "$line_count" -gt 25 ] && return 0
;;
"basic")
[ "$line_count" -gt 5 ] && return 0
;;
esac
return 1
}
The pitfall: Don’t fall back to cheaper models without tracking it. If you’re always falling back to Haiku, you’ve got a deeper problem—maybe your task is too complex for cheaper models, maybe your rate limits are too low. Log every fallback so you can see patterns. You should be investigating why Opus is hitting limits so consistently.
Pattern 3: Circuit Breaker Pattern
Imagine an agent starts failing consistently. Not temporarily—permanently. You could keep retrying, burning through your token budget with each attempt. Or you could use a circuit breaker.
A circuit breaker is simple: after a certain number of consecutive failures, you stop trying and fail fast. You’ve opened the circuit. Nothing gets through. Only after a cooldown period do you try again. The circuit breaker pattern is borrowed from electrical engineering, where circuit breakers prevent damage to systems by interrupting current flow. In software, it prevents damage to your rate limits and token budget by interrupting failed calls.
#!/bin/bash
# Circuit breaker implementation
# Tracks failure counts and enforces "open" state
CIRCUIT_BREAKER_DIR="${HOME}/.claude/circuit-breakers"
mkdir -p "$CIRCUIT_BREAKER_DIR"
get_circuit_file() {
local agent_name="$1"
echo "${CIRCUIT_BREAKER_DIR}/${agent_name}.state"
}
get_circuit_state() {
local agent_name="$1"
local circuit_file=$(get_circuit_file "$agent_name")
if [ ! -f "$circuit_file" ]; then
echo "closed:0:0" # state:consecutive_failures:last_failure_timestamp
return
fi
cat "$circuit_file"
}
set_circuit_state() {
local agent_name="$1"
local state="$2"
local failures="$3"
local timestamp="$4"
local circuit_file=$(get_circuit_file "$agent_name")
echo "${state}:${failures}:${timestamp}" > "$circuit_file"
}
record_failure() {
local agent_name="$1"
local current_state=$(get_circuit_state "$agent_name")
IFS=':' read -r state failures timestamp <<< "$current_state"
failures=$((failures + 1))
# Open circuit after 5 consecutive failures
if [ "$failures" -ge 5 ]; then
set_circuit_state "$agent_name" "open" "$failures" "$(date +%s)"
echo "CIRCUIT OPENED for $agent_name after $failures failures"
return 1
fi
set_circuit_state "$agent_name" "closed" "$failures" "$(date +%s)"
return 0
}
record_success() {
local agent_name="$1"
set_circuit_state "$agent_name" "closed" "0" "0"
}
can_execute() {
local agent_name="$1"
local current_state=$(get_circuit_state "$agent_name")
local cooldown_period=300 # 5 minutes
IFS=':' read -r state failures timestamp <<< "$current_state"
if [ "$state" = "closed" ]; then
return 0 # Circuit is closed, execute
fi
if [ "$state" = "open" ]; then
local now=$(date +%s)
local elapsed=$((now - timestamp))
if [ "$elapsed" -ge "$cooldown_period" ]; then
# Cooldown expired, try half-open state
set_circuit_state "$agent_name" "half-open" "$failures" "$timestamp"
echo "Circuit half-open for $agent_name, attempting single execution"
return 0
else
local remaining=$((cooldown_period - elapsed))
echo "Circuit open for $agent_name, rejecting call ($remaining seconds remaining)"
return 1
fi
fi
if [ "$state" = "half-open" ]; then
# In half-open state, allow execution
return 0
fi
return 1
}
# Execute with circuit breaker
execute_with_circuit_breaker() {
local agent_name="$1"
local task="$2"
if ! can_execute "$agent_name"; then
echo "[CIRCUIT BREAKER] $agent_name is unavailable"
return 1
fi
output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
record_success "$agent_name"
echo "$output"
return 0
else
record_failure "$agent_name"
echo "[FAILURE] $agent_name failed (recorded)"
return 1
fi
}
# Usage: execute_with_circuit_breaker "prose-generator" "write the opening scene"
Why this works: You’re protecting your system from death by a thousand cuts. If an agent is broken, you stop calling it immediately rather than burning tokens on failed retries. The half-open state gives it a chance to recover without flooding it with requests. Think of it like this: if something fails 5 times in a row, it’s probably not a transient issue. Maybe there’s a bug in the agent. Maybe its configuration is wrong. Trying a 6th time won’t fix it—you’re just wasting tokens.
The three states deserve explanation. Closed means the circuit is working normally—calls go through. Open means too many failures, so calls are blocked immediately. Half-open is the recovery state—after a cooldown period, you try one request to see if the problem is fixed. If it succeeds, you close the circuit and resume normal operation. If it fails, you open again.
Real scenario: Your API hits rate limits hard. Every call to your primary agent times out. Without a circuit breaker, you keep retrying, burning through your entire budget in minutes. With a circuit breaker, you fail fast, use your fallback, and preserve tokens for tasks that can actually complete. Your system doesn’t degrade gracefully—it fails loud and early, allowing human operators to notice and respond.
The pitfall: Circuit breakers are reactive. They only help after you’ve already failed multiple times. For expensive operations, you might want to be more proactive—check known conditions (rate limit status, API health) before executing.
Pattern 4: Structured Logging for Debugging Failed Chains
When an agent chain fails, your job is to figure out why. Was it the first agent? The second? Did data corruption happen when Agent A passed results to Agent B? Structured logging is your flashlight in the dark. Good logging isn’t just about capturing what happened—it’s about making that information searchable, queryable, and actionable.
#!/bin/bash
# Structured logging for agent chains
LOG_FILE="${HOME}/.claude/agent-chain.log"
JSON_LOG_FILE="${HOME}/.claude/agent-chain.jsonl"
log_agent_execution() {
local agent_name="$1"
local task="$2"
local status="$3" # START, SUCCESS, FAILURE
local output="$4"
local duration="$5"
local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
local log_entry=$(cat <<EOF
{
"timestamp": "$timestamp",
"agent": "$agent_name",
"task": "$task",
"status": "$status",
"output_length": ${#output},
"duration_seconds": $duration,
"output": $(echo "$output" | jq -Rs .)
}
EOF
)
echo "$log_entry" >> "$JSON_LOG_FILE"
echo "[$timestamp] [$agent_name] $status (${duration}s, ${#output} chars)" >> "$LOG_FILE"
}
# Execute with comprehensive logging
execute_with_logging() {
local agent_name="$1"
local task="$2"
local start_time=$(date +%s)
echo "[START] $agent_name: $task" >> "$LOG_FILE"
output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
local end_time=$(date +%s)
local duration=$((end_time - start_time))
if [ $exit_code -eq 0 ]; then
log_agent_execution "$agent_name" "$task" "SUCCESS" "$output" "$duration"
return 0
else
log_agent_execution "$agent_name" "$task" "FAILURE" "$output" "$duration"
return 1
fi
}
# Trace a full chain execution
trace_agent_chain() {
local chain_id="chain-$(date +%s)"
echo "CHAIN_ID: $chain_id" >> "$LOG_FILE"
# Agent 1: Architect
if ! execute_with_logging "story-architect" "outline plot"; then
echo "[CHAIN $chain_id] Failed at story-architect" >> "$LOG_FILE"
return 1
fi
# Agent 2: Character Forge
if ! execute_with_logging "character-forge" "develop protagonist"; then
echo "[CHAIN $chain_id] Failed at character-forge" >> "$LOG_FILE"
return 1
fi
# Agent 3: World Builder
if ! execute_with_logging "world-builder" "establish setting"; then
echo "[CHAIN $chain_id] Failed at world-builder" >> "$LOG_FILE"
return 1
fi
echo "[CHAIN $chain_id] Complete" >> "$LOG_FILE"
}
# Query the log for debugging
analyze_chain_failures() {
echo "=== Agent Failures (last 24h) ==="
grep "FAILURE" "$LOG_FILE" | tail -20
echo ""
echo "=== Average Duration by Agent ==="
jq -s 'group_by(.agent) |
map({agent: .[0].agent,
avg_duration: (map(.duration_seconds) | add / length)}) |
.[]' "$JSON_LOG_FILE" | column -t
echo ""
echo "=== Failure Rate by Agent ==="
jq -s 'group_by(.agent) |
map({agent: .[0].agent,
failures: map(select(.status == "FAILURE")) | length,
total: length}) |
map({agent: .agent,
failure_rate: (.failures / .total * 100 | round)}) |
.[]' "$JSON_LOG_FILE" | column -t
}
Why this works: When things fail, you have a complete record of what happened, not just “it didn’t work.” You can see which agent failed, how long it took, what the output was. For chain debugging, you can see exactly where the problem started. If Agent 2 gets bad input from Agent 1, you can see that in the logs. Did Agent 1 produce incomplete output? Was it truncated? Did it hang?
The key insight: JSON structured logs are your friend. They’re parseable, queryable, and you can build dashboards on top of them. A plain text log makes you grep through files. JSON logs let you ask questions like “which agents have a failure rate above 5%?” or “what’s the 95th percentile duration for the character-forge agent?”
Understanding your agent behavior through data is the foundation of reliable systems. You’ll discover patterns you never anticipated—certain agents taking longer during off-peak hours, certain task types consistently failing, certain error patterns indicating systematic problems.
The pitfall: Don’t log raw outputs for sensitive data. Truncate long outputs, redact credentials, strip personally identifiable information. A log file that contains secrets is worse than no log at all. Also, be careful about disk space. Append-only logs grow indefinitely. Implement log rotation—archive old logs and delete them after a certain retention period.
Pattern 4b: Context Overflow Detection
Context overflow is a silent killer. Agent C complains that the input from Agent B is too long. You don’t know this happened because Agent B succeeded—it just returned 40,000 tokens of output. Agent C fails quietly.
#!/bin/bash
# Detect and handle context overflow
check_context_size() {
local output="$1"
local max_tokens=50000 # Conservative estimate: 4 chars ≈ 1 token
local char_count=${#output}
local estimated_tokens=$((char_count / 4))
if [ "$estimated_tokens" -gt "$max_tokens" ]; then
return 1 # Overflow detected
fi
return 0
}
# Truncate output if it's too large
execute_with_context_check() {
local agent_name="$1"
local task="$2"
local max_tokens=40000
output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
if [ $exit_code -ne 0 ]; then
return 1
fi
# Check size
local char_count=${#output}
local estimated_tokens=$((char_count / 4))
if [ "$estimated_tokens" -gt "$max_tokens" ]; then
echo "[WARNING] $agent_name output is $estimated_tokens tokens (truncating)" >> "$LOG_FILE"
# Truncate to safe size
local safe_char_limit=$((max_tokens * 4))
output="${output:0:$safe_char_limit}"
output+="... [TRUNCATED] ..."
fi
echo "$output"
return 0
}
Why this matters: Context overflow doesn’t always fail visibly. Sometimes downstream agents just silently produce garbage because their input was incomplete. Detecting and truncating proactively prevents cascading failures. It’s like checking your input before passing it to the next person in line—better to acknowledge the limit upfront than have someone fail because they got too much information.
Pattern 5: Concurrent Agent Execution with Atomic File Locking
When multiple agents modify shared files, chaos ensues. Agent A writes to outline.md. Agent B reads outline.md and gets a partial file. Agent C tries to write and corrupts Agent A’s work. The solution is file locking, a classic concurrency control mechanism that ensures only one agent can modify a file at a time.
#!/bin/bash
# File locking for atomic agent operations
LOCK_DIR="${HOME}/.claude/locks"
mkdir -p "$LOCK_DIR"
acquire_lock() {
local file_path="$1"
local timeout=${2:-30} # seconds
local lock_file="${LOCK_DIR}/$(echo "$file_path" | md5sum | awk '{print $1}').lock"
local start_time=$(date +%s)
while [ -f "$lock_file" ]; do
local current_time=$(date +%s)
local elapsed=$((current_time - start_time))
if [ "$elapsed" -gt "$timeout" ]; then
echo "FATAL: Could not acquire lock on $file_path after ${timeout}s"
return 1
fi
echo "[WAITING] Lock held on $file_path"
sleep 1
done
# Create lock file with PID and timestamp
echo "$$:$(date +%s)" > "$lock_file"
return 0
}
release_lock() {
local file_path="$1"
local lock_file="${LOCK_DIR}/$(echo "$file_path" | md5sum | awk '{print $1}').lock"
rm -f "$lock_file"
}
# Execute agent with file locking
execute_with_lock() {
local agent_name="$1"
local task="$2"
local target_file="$3"
if ! acquire_lock "$target_file"; then
return 1
fi
# Perform the operation
output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
# Always release the lock
release_lock "$target_file"
if [ $exit_code -eq 0 ]; then
echo "$output"
return 0
else
return 1
fi
}
# Usage: execute_with_lock "story-architect" "outline plot" "./story/plot.md"
Why this works: Only one agent can hold the lock at a time. Writers and readers queue up. No more data corruption from concurrent modifications. No more partial reads. This is essential when you have multiple agents working in parallel. The lock acts as a synchronization primitive that serializes access to critical resources.
The pitfall: Locks can deadlock if not managed carefully. Agent A locks File X while waiting for Agent B. Agent B locks File Y while waiting for Agent A. Nobody makes progress. Always acquire locks in the same order across your system. If you need two files, always lock them in alphabetical order, or by some other deterministic ordering.
Pattern 6: Validation Gates Between Agents
Agents are supposed to produce valid output. Supposed to. In reality, they sometimes produce garbage—malformed JSON, incomplete lists, nonsensical content. A validation gate catches this before it propagates downstream.
#!/bin/bash
# Validation gates between agents
validate_outline() {
local outline="$1"
# Check: Has required sections
if ! echo "$outline" | grep -q "ACT I"; then
return 1
fi
if ! echo "$outline" | grep -q "ACT II"; then
return 1
fi
if ! echo "$outline" | grep -q "ACT III"; then
return 1
fi
# Check: Not too short
local line_count=$(echo "$outline" | wc -l)
if [ "$line_count" -lt 10 ]; then
return 1
fi
return 0
}
validate_character_profile() {
local profile="$1"
# Must have name, motivation, arc
if ! echo "$profile" | grep -q "Name:"; then
return 1
fi
if ! echo "$profile" | grep -q "Core Motivation"; then
return 1
fi
if ! echo "$profile" | grep -q "Character Arc"; then
return 1
fi
return 0
}
# Execute with validation
execute_with_validation() {
local agent_name="$1"
local task="$2"
local validator="$3" # Function name
output=$(dispatch "$agent_name" "$task" 2>&1)
exit_code=$?
if [ $exit_code -ne 0 ]; then
return 1
fi
# Run validator
if ! $validator "$output"; then
echo "[VALIDATION FAILED] Output from $agent_name did not pass $validator"
echo "[RETRYING] Asking $agent_name to fix the output"
# Ask agent to fix it
output=$(dispatch "$agent_name" "Fix the output to ensure it has: [requirements]" 2>&1)
if ! $validator "$output"; then
echo "[FATAL] Could not fix output after retry"
return 1
fi
fi
echo "$output"
return 0
}
# Usage: execute_with_validation "story-architect" "create outline" validate_outline
Why this works: You catch garbage before it becomes a problem. An invalid outline detected at the architect level doesn’t cascade through the entire workflow. You ask the agent to fix it right away. This is cheap—you’re fixing it at the source where the agent still has full context.
The pitfall: Don’t validate too strictly. Your validation rules should check for structural integrity, not subjective quality. “Has ACT I, II, III” is valid. “The dialogue is engaging” is not. Structural checks are objective and reliable. Subjective quality is fragile and depends on perspective.
Putting It All Together: A Complete Multi-Agent Pipeline
Here’s how all these patterns work together in a real story development pipeline:
#!/bin/bash
set -e
CHAIN_LOG="chain-execution-$(date +%Y%m%d-%H%M%S).log"
{
echo "=== Story Development Pipeline ==="
echo "Start time: $(date)"
# Step 1: Create outline with fallback and circuit breaker
echo ""
echo "Step 1: Creating story outline"
if ! outline=$(execute_with_circuit_breaker "story-architect" "create three-act outline for a cyberpunk thriller"); then
echo "Outline creation failed"
exit 1
fi
if ! validate_outline "$outline"; then
echo "Invalid outline, retrying"
outline=$(execute_with_fallback "story-architect" "create outline with acts, key beats, and turning points")
fi
# Step 2: Develop protagonist with timeout protection
echo ""
echo "Step 2: Developing protagonist"
if ! protagonist=$(execute_with_lock "character-forge" "create detailed protagonist profile" "./characters/protagonist.md"); then
echo "Character creation failed"
exit 1
fi
if ! validate_character_profile "$protagonist"; then
echo "Invalid character profile"
exit 1
fi
# Step 3: World building
echo ""
echo "Step 3: Building world"
if ! world=$(execute_with_context_check "world-builder" "establish cyberpunk setting with tech, culture, and politics"); then
echo "World building failed"
exit 1
fi
# Step 4: Write opening chapter
echo ""
echo "Step 4: Writing opening chapter"
if ! chapter=$(retry_agent_smart "prose-generator" "write the opening scene, setting the tone and introducing the protagonist within the established world"); then
echo "Chapter writing failed"
exit 1
fi
# Step 5: Validate everything
echo ""
echo "Step 5: Final validation"
if ! validate_chapter "$chapter"; then
echo "Chapter validation failed"
exit 1
fi
echo ""
echo "=== Pipeline Complete ==="
echo "End time: $(date)"
} | tee "$CHAIN_LOG"
echo "Chain log saved to: $CHAIN_LOG"
This pipeline combines circuit breakers to prevent hammering broken agents, fallbacks to degrade gracefully when primary agents fail, locks to prevent concurrent file corruption, context checking to catch overflow before it happens, validation gates to ensure output quality, retries with exponential backoff for transient failures, and structured logging for debugging. The result is a system that’s resilient, debuggable, and actually works when things go wrong.
Recovery Strategies Beyond Retries and Fallbacks
The patterns we’ve covered so far are defensive—preventing failures or recovering from transient ones. But production multi-agent systems need proactive recovery strategies. The moment you detect that something is degraded, you want active recovery mechanisms that restore system health without human intervention.
Graceful degradation strategies go beyond simple fallbacks. You’re not just switching to a slower model—you’re actively reducing scope. If your prose generator is timing out on long chapters, don’t just retry. Split the chapter into smaller scenes and generate them independently. Stitch them together. The output quality is slightly worse (less context for each scene), but you complete the task instead of timing out. This is intelligent degradation—understanding what your agents can handle and adjusting the work to fit their capacity.
State reconstruction is critical for agent chains. When Agent C fails midway, what state does it leave behind? Did it write a partial output file? Did it allocate resources? Your recovery strategy needs to know how to undo work-in-progress. The solution is declarative state—each agent writes to a well-known location with a well-known format. If an agent crashes, the next attempt can see what partial work exists and either clean it up or resume from it. This transforms a crash from a disaster into a resumable operation.
Backpressure and rate limiting are underrated recovery mechanisms. When your agents are overloaded, don’t keep throwing more work at them. Implement backpressure—queue incoming work, process it at a rate your agents can sustain. This prevents the cascading slowdown where each agent backs up waiting for the previous one. With backpressure, you handle load smoothly. Your agents run at sustainable speed. Everything completes, even if more slowly.
The strategic insight: recovery isn’t just about fixing failures. It’s about designing systems that degrade smoothly under load, resume from partial failures, and actively reduce scope when needed. These proactive mechanisms prevent crises before they happen.
Monitoring and Observability
Once you have error handling patterns in place, you need visibility into what’s actually happening:
#!/bin/bash
# Daily failure report
generate_failure_report() {
echo "=== Agent Failure Report (last 24 hours) ==="
echo ""
echo "Failures by agent:"
grep "FAILURE" "$LOG_FILE" | cut -d']' -f2 | sort | uniq -c | sort -rn
echo ""
echo "Failures by type:"
grep "FAILURE" "$LOG_FILE" | grep -oP "(?<=\().*(?=\))" | sort | uniq -c | sort -rn
echo ""
echo "Most common retryable errors:"
grep "RETRYABLE" "$LOG_FILE" | tail -10
echo ""
echo "Circuit breaker events:"
grep "CIRCUIT" "$LOG_FILE"
}
# Alert on critical patterns
check_health() {
# Alert if any agent has failure rate > 20%
jq -s 'group_by(.agent) |
map({agent: .[0].agent,
failures: map(select(.status == "FAILURE")) | length,
total: length}) |
map(select((.failures / .total) > 0.2))' "$JSON_LOG_FILE" |
while read -r line; do
echo "ALERT: High failure rate detected - $line"
done
}
# Monitor in real-time
tail -f "$LOG_FILE" | while read line; do
if echo "$line" | grep -q "FAILURE"; then
echo "[ALERT] $line"
fi
done
Monitoring and Learning from Failures
The final piece of the puzzle is continuous monitoring and improvement. You can’t just implement error handling and move on. You need to actively monitor your systems, learn from failures, and continuously refine your strategies.
Create a dashboard that tracks these key metrics across your agent network:
Failure patterns over time: Are certain agents failing more often? Are failures clustered at specific times (indicating external dependency issues)? Are certain failure categories appearing more frequently (suggesting systematic problems)? By tracking this longitudinally, you can spot trends before they become crises. If your authentication agent starts failing at 2% rate and climbs to 5% over a week, that’s a signal. Something is degrading. You want to know before it hits 20%.
Retry effectiveness: What percentage of retries actually succeed? If 80% of retries succeed, retries are working—transient failures are being handled gracefully. If only 5% of retries succeed, something deeper is broken. That difference tells you whether you’re fighting transient issues or permanent problems.
Fallback frequency: How often are you falling back to lower-tier models? Fallbacks should be rare if your system is healthy. If you’re falling back to Haiku 30% of the time, your rate limits are too aggressive or your primary model is undersized. This is data telling you where to invest.
Circuit breaker triggers: When and why do circuit breakers open? Are they protecting you from real problems, or are you adjusting thresholds too aggressively? Circuit breaker activity is a leading indicator that something needs attention.
Error category distribution: Are most errors transient (retryable) or permanent? Are most security-related or availability-related? This tells you where to focus your infrastructure improvements.
The System Complexity Tradeoff
Here’s an honest conversation you need to have with yourself: error handling adds complexity. Each pattern introduces new moving parts, new state to track, new configurations to tune. At some point, you’re building an error handling system instead of a feature system.
The answer isn’t “build everything perfectly.” It’s understanding your risk tolerance. A story development pipeline is different from a payment processing pipeline. A story development system that fails can be restarted. A payment system that loses data is a catastrophe. These warrant different investment levels in error handling.
Start with the essentials:
Minimal version (good for internal tools, experimentation, low-risk systems): Retry with exponential backoff. Structured logging. That’s it. If it fails, you restart it. You learn from the logs. You iterate.
Intermediate version (good for production supporting services): Add validation gates and circuit breakers. Add fallback options where available. Now you have reasonable resilience without massive complexity.
Advanced version (for critical systems): Everything we’ve discussed. Full monitoring. File locking. Context checking. Comprehensive validation. The complexity is justified because the consequences of failure are severe.
The danger is either extreme: under-engineering error handling and living with constant firefighting, or over-engineering and building a system so complex that nobody understands it. The right approach is right-sizing. If your system is failing once a week, add error handling. If it’s failing once a year, you’re probably over-engineered already.
Understanding Failure Modes in Real Production Systems
The theoretical patterns are important, but understanding how they actually fail in production is where real expertise develops. Multi-agent systems exhibit failure modes that seem impossible until you encounter them. A cascade failure might take 30 minutes to manifest fully—Agent A fails silently, passing degraded output to Agent B, which produces questionable results that Agent C consumes and amplifies. By the time you notice something is wrong, three levels of downstream work is built on corrupted data.
The insidious nature of cascade failures is that each individual agent might report success. Agent B didn’t crash. It processed input and returned output. The output just happened to be subtly wrong because it was built on Agent A’s compromised data. Your monitoring sees three successful operations. Meanwhile, the quality of your story outline is degrading silently.
Real production systems add another dimension: partial failures. Agent A partially succeeds—it completes the main task but fails on an optional subtask. Do you treat this as success or failure? If you treat it as success, downstream agents might expect data that isn’t there. If you treat it as failure, you’re overly pessimistic. The answer is structured validation—know what “success” actually means. Success isn’t binary. It’s success-with-all-features or success-with-degradation. Your validation gates need to distinguish between them.
The timing aspect is often overlooked. Agent A completes in 2 seconds. Agent B waits for A, then takes 5 seconds. Agent C is waiting for B. Your orchestrator has a 30-second timeout. If this sequence runs 10 times (maybe processing 10 chapters), you’re at 70 seconds total—your timeout fires. But you’ve already burned tokens on agents A and B. The orchestrator timeout didn’t protect you; it wasted your budget.
Production teams solve this by setting per-agent timeouts, not just orchestrator timeouts. Agent A: 5 seconds max. Agent B: 10 seconds max. Agent C: 10 seconds max. If Agent A hits the timeout, fail immediately. Don’t wait for the orchestrator timeout. This prevents cascading delays and preserves tokens for operations that have a chance of completing.
Building Observability That Actually Works
Logging is necessary but insufficient. The real power comes from observability—the ability to ask questions about your system’s behavior and get answers. Logs are data. Observability is your ability to extract meaning from that data.
A team implementing multi-agent error handling with just logs spends half their time parsing files with grep. A team with observability can ask: “Which agent types have failure rates above 5% in the last hour? How many failures were transient vs. permanent? What’s the P95 latency for the story-architect agent?” The answers come instantly.
Build observability by treating your logs as a time-series database. Structure them as JSON. Ship them to a queryable system (ELK stack, DataDog, Honeycomb, whatever). Now you can ask sophisticated questions. “Show me all failures from the character-forge agent where the output was under 100 tokens.” This might reveal that the agent is quietly outputting garbage—valid JSON, non-erroring, but undersized and worthless. Your monitoring would have missed this because the agent didn’t fail.
Observability also helps with capacity planning. You notice that prose-generator is consistently taking longer on Fridays—probably because your shared infrastructure is under heavier load. You can adjust scheduling or allocate more capacity preventively. Without observability, you just see Friday failures and wonder why.
The deepest benefit of observability is learning. Your logs become a dataset. Analyze it. What patterns precede failures? Do certain combinations of agents always fail together? Are certain time-of-day patterns correlated with failures? Machine learning on your operational data reveals patterns humans miss.
The Bottom Line
Multi-agent workflows fail in unique, complex ways. But these failures are patterns—repeatable, predictable patterns that you can handle with the right strategies:
- Retry with exponential backoff for transient failures
- Fallback agents for graceful degradation
- Circuit breakers to fail fast when agents are broken
- Structured logging for visibility and debugging
- Context size checking to prevent overflow cascades
- File locking to prevent concurrent corruption
- Validation gates to catch bad output early
- Continuous monitoring to learn and improve
Build these patterns into your Claude Code workflows, and you’ll spend less time firefighting and more time building systems that actually work. The investment in error handling infrastructure pays dividends immediately—your pipelines become more reliable, easier to debug, and faster to recover from problems. You’re not just patching failures; you’re architecting for resilience.
The key insight is that error handling isn’t a feature you bolt on at the end. It’s an architectural decision made upfront about how your system behaves when reality doesn’t cooperate with your assumptions. Every production system encounters failures. The question is whether you handle them gracefully or spectacularly. By investing in these patterns early, you’re choosing grace over spectacle. Your team gets sleep. Your users get stable service. Your system stays standing even when individual components fall over.
And when things do fail, your logs tell you exactly what happened. You’re not left wondering. You’re not guessing. You’re investigating facts. You’re iterating based on real data. That’s the difference between chaos and control.
-iNet