5.4 Production Reliability: Rate Limits, Retries & Observability
Key Takeaways
Distinguish transient 429 rate/ramp limits, 529 overload and retryable server faults from persistent spend limits, malformed requests, missing resources, oversized HTTP bodies and authorization failures.
Honor Retry-After and x-should-retry when applicable, use jittered bounded backoff, and include SDK retries in the end-to-end budget; reconcile side effects before replay.
Circuit breakers prevent repeated calls during dependency outages; durable failed-job queues support controlled, authorized, idempotent replay.
Propagate W3C trace context and correlate child spans with provider request IDs; monitor duration, cache usage, tool errors and attributable model cost without logging secrets.
Production Reliability: Rate Limits, Retries & Observability
Production enterprise AI systems operate under explicit availability and latency objectives, multi-dimensional token quotas, and volatile downstream dependencies. Reliability engineering ensures transient hiccups recover automatically without triggering retry storms, exhausting latency budgets, or obscuring root causes.
Anthropic API Error Taxonomy & Retry Policy
Blindly retrying every failed API call wastes quota, spikes tail latency, and masks client bugs. Classify responses strictly before scheduling retries:
| Status / Failure | Category | Retry? | Root Cause & Production Action |
|---|---|---|---|
429 Too Many Requests | Rate/ramp or spend limit | Conditional | Inspect error details; rate/ramp may recover, persistent spend limits require authorized intervention |
529 Overloaded | Transient Capacity | Yes | Temporary Anthropic capacity saturation; bounded backoff or tested/authorized fallback |
500 / 502 / 503 / Timeout | Transient Server | Yes | Retryable upstream fault; follow retry headers and remaining deadline; reconcile side effects |
400 / 422 | Permanent Client | No | Malformed JSON, invalid tool_use/tool_result pairing; fail fast and alert |
401 / 403 | Permanent Auth | No | Invalid API key or insufficient permission; stop unchanged retries; resolve credentials/permissions through approved processes |
404 / 413 | Permanent Request | No | Unknown resource (404) or request byte limit (413); correct request before retrying; context token limit is separate |
Remember that rate limits govern three independent dimensions—Requests Per Minute (RPM), Input Tokens Per Minute (ITPM), and Output Tokens Per Minute (OTPM)—and the direct Messages API excludes cache-read tokens from default ITPM accounting. Check surface/model quotas, ramp limits and spend caps separately.
Jittered Exponential Backoff, Retry-After & Circuit Breakers
Stopping Synchronized Retry Storms
When 400 concurrent workers hit a 429 at t = 0 and execute deterministic exponential backoff (1s, 2s, 4s), all 400 workers wake up together at t = 1s, hammering the endpoint again and prolonging the outage. For client-controlled transient retries, consider full jitter:
sleep_ms = random(0, min(max_delay_ms, base_delay_ms * 2^attempt))
Whenever the Anthropic API includes a Retry-After header (for example, 12 seconds), do not retry earlier than that delay. With your own retry policy, a small additional randomized delay after the required minimum can help avoid simultaneous wakeups, if permitted by the deadline. The provider SDK already handles retries; include its attempts and delays instead of independently multiplying retries at each layer.
Bounding Retry Budgets to Caller SLOs
Retry policies must respect the caller's latency budget. Suppose an interactive customer-support UI enforces a p95 end-to-end latency SLO of 6.0 seconds. Performing five retries totaling 45 seconds violates the SLO and holds open upstream worker threads until gateways return 504. For this hypothetical six-second path, cap attempts within the actual remaining deadline before degrading gracefully—such as returning a deterministic fallback message or routing to a human queue. Background workers may tolerate longer backoff; when a timed-out operation may have changed state, reconcile or deduplicate using a stable operation ID rather than replaying blindly.
Circuit Breakers & Dead-Letter Queues (DLQs)
If a downstream MCP server or legacy CRM experiences a prolonged outage (for instance, >50% failure rate across a 30-second sliding window), continuing to invoke Claude only to fail inside tool loops wastes thousands of tokens per minute. Wrap external tool executors in a circuit breaker:
- CLOSED: Normal traffic flows while failure rates are tracked.
- OPEN: Trips after threshold breach (e.g., 60-second cooldown), immediately returning a structured non-retryable fallback so Claude stops calling the broken dependency.
- HALF-OPEN: Allows limited probe calls after cooldown to verify recovery before restoring full traffic.
For asynchronous pipelines, retain failed jobs in a durable quarantine or dead-letter queue (DLQ) after the retry limit. Store only permitted payload or a reference to it, tenant and correlation context, secure access and retention, and alert an owner. Reconcile and safely replay after diagnosis; ordering-sensitive workloads need special care.
End-to-End Observability & Production SLOs
A typical enterprise Claude request may cross several subsystems: API Gateway, RAG vector store, MCP tool servers, Claude inference, and output/guardrail validators. Without correlated telemetry, distinguishing slow vector search, an ERP lock, and model latency becomes difficult.
OpenTelemetry Distributed Tracing
Create or extract trace context at ingress, honoring trust and privacy boundaries; W3C traceparent carries a trace identifier and parent identifier. Propagate supported context through HTTP/queue boundaries and generate child spans. Correlate provider request IDs where the provider does not expose internal spans. Emit child spans for:
- Gateway AuthN/OBO token exchange
- RAG embedding and hybrid retrieval
- Each MCP or REST tool call (recording
tool_name,is_error, and duration—never raw secrets or unredacted PII) - Claude Messages API inference (recording model ID,
stop_reason, and token usage fields) - Deterministic schema/policy validation
Five Core Enterprise SLIs
| Metric / SLI | Target Example | Operational Signal |
|---|---|---|
| Time to First Token (TTFT) | < 800 ms (p95) | Measures time until the defined first token/event; distinguish first visible text from thinking and tool events |
Total Latency (p50 / p95 / p99) | p95 < 5.5 s | Captures full multi-turn agent loop duration including tool round-trips |
| Token Spend per Tenant | Budget alerts at 80% / 100% | Attributes uncached input, cache writes/reads and generated output at applicable rates by tenant for chargeback and noisy-neighbor throttling |
| Prompt Cache Hit Ratio | > 75% on multi-turn agents | Drops can indicate changed prefixes, expiration or configuration (e.g., placing dynamic timestamps before static system prompts) |
| Tool Error Rate | < 2% steady state | Spikes indicate upstream API schema drift, authorization failures, or prompt regressions |
Combining error-aware backoff, SLO-bounded retry budgets, circuit breakers, and end-to-end OpenTelemetry traces turns fragile LLM prototypes into auditable, resilient enterprise services.
Detect failures that a successful HTTP status hides
The Claude API can return a stream error after HTTP 200; monitor the terminal event and stop reason rather than counting every status-200 response as successful. Current SDK documentation says it normally retries twice (three attempts total), with behavior governed by x-should-retry and retry-after when present; connection errors, timeouts, 408, 409, 429 and 5xx are default retry candidates, with SDK-specific exceptions. Resolve conflicts and persistent caps rather than treating them as transient. HTTP 413 reports the request size in bytes, not the context-token count. For the first-party API, use the request ID in diagnostics, and inspect model usage and validated outcome even for a successful HTTP response.
Official references
An integration worker calling the Anthropic Messages API encounters a burst of HTTP 400 (malformed tool_result pairing), HTTP 413 (HTTP request body exceeds byte limit), HTTP 429 (ITPM rate limit), and HTTP 529 (overloaded) responses. Which response types are candidates for bounded automatic retry, assuming provider headers permit and the failure is transient?
Retry 429 and 529 with backoff; fail fast immediately on 400 and 413 without retrying
Retry all four status codes up to 5 times with exponential backoff
Retry 400 and 413 with jitter; fail fast on 429 and 529
Retry only 400 after waiting for the Retry-After header
During a morning traffic spike, 300 microservices receive HTTP 429 responses simultaneously and execute fixed exponential backoff (1s, 2s, 4s). Each retry collides with the others, extending the outage, while interactive users experience 40-second hangs before gateway timeouts. Which two fixes resolve these issues?
Disabling retries altogether and increasing the API gateway timeout to 120 seconds
Adding full jitter while honoring Retry-After headers, and capping interactive retries to a strict budget bounded by the caller's latency SLO
Switching from streaming Messages API calls to synchronous polling loops
Removing Retry-After inspection so workers poll every 100 milliseconds
An enterprise order-processing pipeline uses an asynchronous Kafka consumer running Claude tool loops against a legacy warehouse API. The warehouse API suffers a 20-minute outage, causing consumers to burn Claude tokens on repeated failed tool calls and eventually drop messages after max retries. What architecture prevents both wasted inference and silent data loss?
Increasing max retries on the Kafka consumer to 500 attempts per message
Moving the warehouse integration to a synchronous browser-initiated call
Suppressing tool errors inside the warehouse adapter so Claude receives empty success payloads
Placing a circuit breaker around the warehouse tool executor to short-circuit calls during outages, and routing exhausted Kafka messages to a Dead-Letter Queue (DLQ) for replay
A multi-tenant agent platform reports that p99 latency tripled from 4s to 12s and daily token spend doubled overnight, even though request volume remained flat. Which observability practice pinpoints both root causes most effectively?
Logging raw user prompts and bearer tokens to console stdout across all pods
Increasing max_tokens across all endpoints and disabling streaming
Correlating W3C OpenTelemetry trace_id spans across gateway, RAG, MCP tools, and inference while tracking prompt cache hit ratio and per-tenant token metrics
Monitoring only HTTP 200 vs HTTP 500 counts at the outer load balancer
Sections you finish are checked off in the contents.