Photo by Lalada . from Pexels

When a user's chat request hits your LLM API call, they don't care whether it went to OpenAI, Anthropic, or OpenRouter, they care about how fast the first token arrives. A 200 ms TTFB (time to first byte) feels snappy; a 2-second wait feels broken. In production, latency isn't uniform: regional geography, network load, and provider capacity all shift response times minute by minute. Smart routing and automated failover based on measured latency, not guesswork, can mean the difference between a seamless user experience and support tickets piling up.

This article walks through how to build latency-aware failover: what metrics to track, how to detect degradation across regions, and when to automatically switch providers to keep your LLM features fast.

Key takeaway: Implement regional, latency-driven failover using automated synthetic probes, percentile-based thresholds, and real-time routing decisions. This transforms reactive incident response into proactive traffic management, ensuring users consistently experience fast responses even when individual providers degrade.

TL;DR

0core principles
Latency Failover Essentials
  • Track TTFB (time to first byte) and TTFT (time to first token) separately; average latency masks regional spikes.
  • Set up synthetic probes from multiple regions to measure each provider's actual performance, not their advertised SLOs.
  • Implement provider failover on a per-region basis: if OpenRouter US-East degrades, switch to OpenAI for that region, not globally.
  • Use latency percentiles (p95, p99) to catch tail latency before it reaches your users.
  • Automate alerts when latency crosses thresholds; manual incident response is too slow.
Article Progress: Core Concepts Established
0%

Why Latency Variance Matters for Production LLM Services

global network map
Photo by Nothing Ahead from Pexels

Most SaaS APIs quote a single global latency number: "99% of requests complete in under 500 ms." That hides a critical truth: latency is not distributed evenly. A request from São Paulo to an OpenAI endpoint in the US East region will round-trip differently than one from Tokyo to the same endpoint. Network hops, BGP routing, datacenter congestion, and regional traffic patterns all introduce variance.

In practice:
  • Regional baseline shifts. OpenRouter's endpoint in Singapore might average 180 ms from Sydney but degrade to 450 ms during peak hours.
  • Provider performance is asymmetric. OpenAI may be faster from Europe, while Claude via Anthropic's direct API is faster from Asia-Pacific.
  • Aggregate metrics hide the tail. Averaging 10,000 requests across all regions and time windows masks the fact that 5% of requests hit 3-second latency.
For chat applications, slow responses trigger user frustration fast. A 1-second TTFB on a completion endpoint kills perceived responsiveness. Streaming endpoints (where TTFT matters more than TTFB) are even more sensitive: a 3-second wait before the first token appears feels like the system is hung.

The failover insight: If you know latency by provider and region in near-real-time, you can route requests to the fastest available option before users experience a slowdown. This requires continuous measurement and rapid decision logic.

Setting Up Latency Measurement Across Regions

server room data
Photo by Brett Sayles from Pexels

Before you can route intelligently, you need data. The gold standard is synthetic probes: automated requests sent to each provider from multiple regions on a fixed schedule, measuring both TTFB and TTFT.

Key Metrics to Track

  • TTFB (Time to First Byte)
    • Elapsed time from request sent to first byte of response received.
    • Measures network latency + provider queue time + initial processing.
    • Targets: < 300 ms for chat, < 500 ms for complex reasoning tasks.
  • TTFT (Time to First Token)
    • For streaming endpoints, the time until the first token appears in the stream.
    • More relevant for user experience than TTFB on streaming models.
    • Targets: < 1,000 ms (1 second) for real-time chat feel.
  • Percentile Latencies (p50, p95, p99)
    • Median (p50) tells you typical performance.
    • p95 and p99 tell you how often users hit slow requests.
    • A provider with p50=200ms and p99=4s is less reliable than one with p50=400ms and p99=600ms.
  • Provider Response Time
    • Total time from request sent to response complete (useful for batch workloads).
    • Less critical for interactive chat but important for capacity planning.

Probe Frequency and Coverage

Recommended setup:
  • Probe each provider (OpenAI, Anthropic, OpenRouter) every 60 seconds from at least 5 key regions.
  • Distribute regions geographically: US East, US West, Europe, Asia-Pacific, South America.
  • Use a fixed prompt to ensure fair comparison (e.g., "Say 'ok'" to avoid variable token generation time).
  • Log raw latencies, not just aggregates, so you can detect anomalies later.
Observinio runs probes from 21 global regions and publishes daily summaries and per-region breakdowns. For smaller teams, starting with 5 regions (covering major user demographics) is practical and scales as you grow.

Aggregation Without Losing Signal

Store measurements at high granularity: one data point per probe per provider per region. Then roll up:
  • 5-minute window: average + percentiles for real-time routing logic.
  • 1-hour window: rolling average to detect gradual degradation.
  • Daily summary: understand which time-of-day or day-of-week patterns emerge.
Avoid throwing away raw data. When an incident occurs, you'll want to revisit the raw probe logs to understand what happened.

Implementing Regional Failover Logic

dashboard analytics
Photo by Negative Space from Pexels

Once you have latency data flowing, the next step is to use it in your routing layer. The key principle: failover decisions are regional and metric-driven, not reactive.

Step-by-Step Failover Implementation

Failover Between LLM Providers Based on Latency process
Figure 1: Failover Between LLM Providers Based on Latency at a glance.
  • Define latency thresholds per region and model.
    • For GPT-4 completions: TTFB threshold 400 ms, TTFT threshold 1,500 ms.
    • For fast models (GPT-3.5, Claude Instant): TTFB threshold 250 ms, TTFT threshold 800 ms.
    • Thresholds should reflect your user experience targets, not provider SLOs.
  • Build a provider preference list per region.
    • Primary: OpenRouter (good availability, cost-effective).
    • Secondary: OpenAI direct (low latency from US, higher latency internationally).
    • Tertiary: Anthropic direct (good latency from some regions, variable from others).
    • List should reflect your testing; adjust based on your actual probe data.
  • Measure the 5-minute p95 latency for each provider-region pair.
    • Every 60 seconds, recompute: "What is the p95 TTFB for OpenRouter in EU-West over the last 5 minutes?"
    • If p95 exceeds threshold, mark that provider as "degraded" in that region.
  1. Route new requests to the best available option.
   FOR each new request:
     GET user's region (from IP or client header)
     FOR each provider in preference_list[region]:
       IF latency_status[provider][region] == "healthy":
         ROUTE request to provider
         BREAK
     IF no provider is healthy:
       ROUTE to primary (failsafe) and alert on-call
   
  • Automatically recover degraded providers.
    • Once a provider's p95 latency falls below 80% of threshold for 10 minutes, mark it healthy again.
    • Prevents flapping: if a provider oscillates around the threshold, you'd thrash failovers.

Example: A Concrete Failover Scenario

Your SLO for chat responses in Europe is TTFB < 350 ms. You run probes every minute from Frankfurt. The last 5 minutes of data show:

  • OpenRouter p95 TTFB: 320 ms (healthy)
  • OpenAI p95 TTFB: 280 ms (healthy)
  • Anthropic p95 TTFB: 410 ms (degraded)
A user in Berlin sends a chat request. Your router:
  1. Detects region = "EU-West"
  2. Tries OpenRouter first (primary in your setup), sees p95 = 320 ms, which is < 350 ms threshold.
  3. Routes to OpenRouter.
  4. Request completes in 310 ms. User sees fast response. ✓
Five minutes later, OpenRouter's probe latencies spike to p95 = 380 ms (maybe a brief capacity crunch). The router:
  1. On the next request, detects OpenRouter is degraded.
  2. Falls back to OpenAI (p95 = 280 ms), which is well under threshold.
  3. Routes to OpenAI instead.
  4. Traffic automatically diverts away from the slow provider without human intervention.
When OpenRouter recovers (p95 drops back to 320 ms for 10 minutes), the router automatically re-enables it as an option.
"The right gateway for Claude Code must preserve the protocol and interaction the client expects."
>, Blog

Detecting and Alerting on Latency Degradation

Measurement and routing are half the story. The other half is observability: knowing when latency degrades before your users complain.

Alert Conditions

Set up alerts for:

  • Absolute threshold breaches
    • p95 TTFB in region X exceeds 400 ms for 3 consecutive probes.
    • Severity: warning if one provider, critical if all providers degraded in a region.
  • Sudden spikes
    • p95 TTFB increases > 50% compared to the last hour.
    • Catches rapid degradation that might not hit an absolute threshold yet.
  • Provider unavailability
    • Probe fails (HTTP 5xx, timeout, no response).
    • After 2 consecutive failures from a region, page on-call.
  • Regional isolation
    • A provider is degraded in one region but not globally.
    • May indicate regional network or datacenter issue, not a provider outage.
  • Tail latency explosion
    • p99 latency is 5x higher than p50.
    • Signals that percentile requests are hitting pathological slowness.

Alert Delivery

  • Email digests: Daily or weekly summaries for trending latency analysis (good for Sam the SRE).
  • Slack/PagerDuty: Real-time alerts for threshold breaches and unavailability (good for on-call rotations).
  • Dashboard: Observinio's status page shows live latency heatmaps by region and provider so Alex (the platform engineer) can see degradation as it happens.

Practical Checklist for Alert Setup

Your progress is saved automatically in your browser.

Article Progress: Implementation Guide Complete
0%

Common Failover Pitfalls and How to Avoid Them

Pitfall 1: Failover flapping
  • Problem: Latency oscillates around your threshold; router switches providers every few minutes.
  • Solution: Use hysteresis. Degrade at 400 ms; recover only when it drops to 320 ms. Require 10 minutes of stable good latency before re-enabling.
Pitfall 2: Ignoring cost in failover decisions
  • Problem: You route all traffic to the "fastest" provider, which happens to be 3x more expensive.
  • Solution: Incorporate cost into routing: if Provider A is 15 ms slower but 50% cheaper, prefer it unless latency is critical (e.g., real-time user chat). Set a "cost ceiling" and only use expensive providers as failover.
Pitfall 3: Probe overhead and self-induced latency
  • Problem: Your probes add load to providers, which increases latency for real users.
  • Solution: Keep probe frequency reasonable (every 60 seconds) and use a tiny test prompt (5–10 tokens). Use a low-priority queue or account if the provider supports it.
Pitfall 4: Blindly trusting averages
  • Problem: A provider's average latency looks good, but p99 is terrible.
  • Solution: Always route based on percentiles, not averages. p95 is a good baseline for most use cases.
Pitfall 5: Not accounting for user geography
  • Problem: Your probes run from 5 fixed regions, but your users are spread globally.
  • Solution: Use geoIP to map requests to the nearest probe region. If a user in Mexico hits a request, treat latency from Miami or São Paulo probes as representative.

Monitoring and Tuning Failover Over Time

Article Progress: Monitoring & Optimization Strategies
0%

Failover isn't set-and-forget. You should review and adjust monthly.

Weekly Latency Reports

  • Which provider is fastest in each region?
  • Which time windows have the highest latency variance?
  • Are there any recurring degradation patterns (e.g., every Friday at 5 PM UTC)?
  • Did failover trigger? How often? Was it justified by the latency data?

Monthly Tuning

  • Adjust thresholds based on what you've learned. If p95 routinely hits 380 ms and users are happy, your 350 ms threshold is too aggressive.
  • Test adding or removing providers. If a new provider consistently outperforms, promote it in your preference list.
  • Review alert fatigue. Too many alerts = on-call ignores them. Too few = you miss real issues.
  • Update your probe setup if you've added new user regions or model types.
For teams using Observinio, the weekly digest email includes regional latency trends and a summary of any threshold breaches or failovers, so tuning decisions are informed by real data.
Pro Tip: Establish a monthly "Latency Review" meeting where you examine failover events, adjust thresholds, and discuss changes to your provider preference lists. Use Observinio reports and production traffic patterns as the basis for decisions. This systematic approach prevents threshold drift and ensures your failover logic stays aligned with your actual infrastructure performance and business priorities.

FAQ

Frequently Asked Questions

Every 60 seconds is a good baseline for most services. Faster updates (e.g., every 15 seconds) add probe overhead but catch rapid degradation sooner. Slower updates (every 5 minutes) reduce overhead but may delay failover by a few minutes. Start at 60 seconds; adjust based on your incident response SLA.
Use p95 for routing decisions. It represents the experience most users see while being sensitive to tail latency anomalies. p50 (median) is too optimistic and can mask real degradation. p99 is useful for understanding worst-case scenarios but too volatile for real-time routing.
Always per-region. A provider can be fast in the US but slow in Asia. Regional failover prevents unnecessary switches and lets you maintain diversity: maybe OpenRouter is best for US traffic, OpenAI for EU, and Anthropic for APAC. This also reduces blast radius if a single provider has a global outage.
Define a "cost-aware latency budget." For example: if Provider A is 10 ms slower but 40% cheaper, prefer Provider A unless latency urgently needs to drop. Use Observinio's alerts to notify you when a cheaper provider crosses your latency threshold, so you can consciously decide to pay more for speed if necessary.
Set a fallback: route to your primary provider (the one with the best reliability track record) and page on-call. Log this decision so you can investigate during the postmortem. You might also set a circuit breaker: if all providers fail 3 times in 5 minutes, return a cached response or friendly error rather than hammering a broken backend.
Compare probe latency to actual production traffic latency (if you're already logging it). If probes show p95 TTFB = 320 ms but real traffic shows 280 ms, your probes may be hitting a different code path or network path than production. Adjust probe setup (use different test prompts, vary concurrency, route from different ISPs) until they correlate with real traffic.
Partially. APM tools excel at tracing requests within your stack but are less equipped to monitor third-party API latency across multiple regions in near-real-time. Observinio and similar synthetic monitoring tools are purpose-built for this. You can integrate: APM for your stack, Observinio (or equivalent) for provider latency, and route failover based on Observinio alerts + data.

Next Steps

Article Progress: Final Recommendations
0%

Latency-aware failover is a multiplier for reliability. It transforms your LLM infrastructure from reactive (detecting slowdowns via support tickets) to proactive (automatically routing around degradation). Start by setting up probes from 3–5 key regions, measure your current baseline, define thresholds based on your SLO targets, and implement a simple preference list + degradation detection.

If you'd like real-time visibility into latency across OpenAI, Anthropic, and OpenRouter from 21 global regions, Observinio's status page shows live data and daily probe summaries. Set up email degradation alerts to be notified before your users are, and use weekly reports to tune your failover thresholds.

The goal isn't perfection, it's consistency. Fast and reliable beats spectacular and unpredictable. By implementing the practices outlined in this article, you'll build a resilient LLM infrastructure that maintains consistent performance across regions and adapts automatically to real-world conditions.

Additional Resources