When an LLM-powered feature fails in production, the difference between a minor hiccup and a major outage often comes down to whether the system was designed to degrade gracefully. This post walks through practical patterns for building resilience into LLM applications so that partial failures don't cascade into complete outages.
The Degradation Mindset
LLM applications have unique failure modes: model providers experience outages, rate limits get hit, context windows overflow, and outputs fail validation. Traditional circuit breakers and retries help, but they don't address what happens when a feature simply can't work as intended. Graceful degradation means the system continues providing value even when individual components fail.
The goal isn't to eliminate failures — it's to make them survivable. A chat application that loses its RAG retrieval can still answer from training data. An image analysis feature that loses its vision model can ask users to describe images in text. A code generation tool that hits rate limits can queue requests with transparent wait estimates.
Feature Tiering: Categorize by Criticality
Not all features are equally important. Before implementing degradation logic, categorize your LLM features into tiers:
Tier 1: Core — never disable. The fundamental user interaction (chat, search, basic completion). These features must remain available even if degraded.
Tier 2: Enhanced — degrade with messaging. Features that improve the experience but aren't essential (RAG-enhanced answers, code formatting, image analysis). When these fail, the core experience continues with a clear message to the user.
Tier 3: Experimental — disable first. New features, beta capabilities, or high-cost operations. These are the first to go under pressure.
Fallback Model Routing
The most direct degradation pattern is maintaining a model portfolio with automatic fallback. When the primary model fails or exceeds latency/cost thresholds, route to the next available model:
class ModelRouter:
def __init__(self):
self.models = [
{"name": "primary", "model": "claude-3.5-sonnet", "cost_per_1k": 3.0, "latency_p50": 1.5},
{"name": "fallback_1", "model": "claude-3.5-haiku", "cost_per_1k": 0.25, "latency_p50": 0.5},
{"name": "fallback_2", "model": "gpt-4o-mini", "cost_per_1k": 0.15, "latency_p50": 0.8},
]
self.current_index = 0
async def route(self, request, max_cost=None, max_latency=None):
for i, model_config in enumerate(self.models):
if max_cost and model_config["cost_per_1k"] > max_cost:
continue
if max_latency and model_config["latency_p50"] > max_latency:
continue
try:
return await self.call_model(model_config, request)
except Exception as e:
if i == len(self.models) - 1:
raise # No more fallbacks
logging.warning(f"Model {model_config['name']} failed, trying next: {e}")
raise Exception("All models exhausted")
Key practices:
- Test fallback models against your golden dataset to ensure quality remains acceptable
- Route based on request type — simple classification can use cheaper models; complex reasoning needs premium ones
- Track which model served each request for debugging and cost attribution
Feature Gates with User-Facing Messages
Feature gates control capability availability and provide fallback messaging. Instead of returning errors, return structured responses that explain the limitation and offer alternatives:
class FeatureGate:
def __init__(self):
self.gates = {
"rag_enhancement": {"enabled": True, "tier": 2},
"vision_analysis": {"enabled": True, "tier": 2},
"code_generation": {"enabled": True, "tier": 1},
"beta_features": {"enabled": True, "tier": 3},
}
def check_and_respond(self, feature, request_context):
gate = self.gates.get(feature)
if not gate or not gate["enabled"]:
return {
"degraded": True,
"feature": feature,
"message": self.get_fallback_message(feature),
"alternatives": self.get_alternatives(feature),
}
return {"degraded": False}
def get_fallback_message(self, feature):
messages = {
"rag_enhancement": "Knowledge base temporarily unavailable. Answering from training data.",
"vision_analysis": "Image analysis offline. Please describe your image in detail.",
"code_generation": "Code generation at capacity. Please try again in a moment.",
}
return messages.get(feature, "Feature temporarily unavailable.")
Circuit Breakers for External Dependencies
LLM applications often depend on external services — vector databases, embedding APIs, knowledge bases, and model providers. Each dependency should have its own circuit breaker:
from circuitbreaker import circuit
@circuit(failure_threshold=5, expected_exception=Exception, recovery_timeout=30)
async def call_embedding_service(texts):
return await embedding_client.embed(texts)
@circuit(failure_threshold=3, expected_exception=Exception, recovery_timeout=60)
async def call_vector_db(query_vector):
return await vector_client.search(query_vector)
When a circuit opens, the degradation logic activates immediately rather than retrying and timing out. The response includes a user-facing message about the specific degraded capability.
Context Window Management as Degradation
Context overflow is a common failure mode. Implement tiered context strategies that automatically reduce context when tokens exceed budgets:
class TieredContextManager:
def __init__(self, max_tokens=8000):
self.max_tokens = max_tokens
def prepare(self, conversation, request_type="standard"):
tokens = estimate_tokens(conversation)
if tokens <= self.max_tokens:
return conversation
if request_type == "latency_critical":
# Minimal: key facts + last 3 messages
return self.minimal_context(conversation)
elif request_type == "standard":
# Medium: summary + last 10 messages
return self.summarized_context(conversation)
else:
# Full: hierarchical summarization
return self.hierarchical_context(conversation)
def minimal_context(self, history):
key_facts = extract_key_facts(history) # User name, decisions, preferences
recent = history[-3:]
return [{"role": "system", "content": key_facts}] + recent
This prevents hard failures and keeps the conversation functional, albeit with reduced history.
Rate Limit Graceful Handling
When rate limits are hit, avoid generic "too many requests" errors. Instead:
- Queue requests with position updates: "Your request is #3 in queue. Estimated wait: 45 seconds."
- Offer synchronous alternatives: "High demand detected. Switching to faster model — response coming shortly."
- Implement priority tiers: paying users get queue priority; free users see wait estimates.
Monitoring Degradation Impact
Track how degradation affects user behavior to prioritize fixes:
async def log_degradation_event(request_id, feature, degradation_type, user_outcome):
await analytics.track({
"event": "degradation_impact",
"request_id": request_id,
"feature": feature,
"degradation_type": degradation_type, # fallback_model, feature_disabled, context_reduced
"user_outcome": user_outcome, # continued, retried, abandoned, gave_feedback
"timestamp": datetime.utcnow().isoformat()
})
Key metrics:
- Continuation rate: Percentage of users who continue after seeing a degradation message
- Retry rate: How often users retry immediately vs. waiting
- Session abandonment: Sessions ending within 2 minutes of a degradation event
- Explicit feedback: Thumbs up/down on degraded responses
Testing Degradation Paths
Degradation logic is only useful if it works. Include failure scenario testing in your CI/CD:
# .github/workflows/degradation-test.yml
name: Degradation Tests
on: [pull_request]
jobs:
test-failures:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Test model fallback
run: python -m pytest tests/test_model_fallback.py
- name: Test feature gates
run: python -m pytest tests/test_feature_gates.py
- name: Test circuit breakers
run: python -m pytest tests/test_circuit_breakers.py
- name: Test context reduction
run: python -m pytest tests/test_context_reduction.py
Run chaos engineering exercises monthly: disable the knowledge base, throttle the primary model, simulate vector DB outages. Observe system behavior and user experience.
Summary Checklist
- Categorize all LLM features into tiers (core/enhanced/experimental)
- Implement model fallback routing with quality-validated alternatives
- Add feature gates with user-facing fallback messages for each enhanced feature
- Deploy circuit breakers on every external dependency
- Build tiered context management that reduces history before hitting limits
- Design rate limit responses with queue position and alternatives
- Instrument degradation events with user outcome tracking
- Add degradation scenario tests to CI/CD
- Schedule monthly chaos engineering exercises
Graceful degradation transforms LLM application failures from outages into managed experiences. The patterns above are practical starting points — adapt them to your architecture, user expectations, and business requirements. The key principle: every failure path should have a designed user experience, not a generic error.
For broader system resilience patterns including model failover, context reduction, and circuit breaking, see the related guide Graceful Degradation Strategies for Production LLMs.