How to Reduce Model Costs with an AI Router, and Failover Design for External AI API Outages
公開日 2026-08-13 · 更新日 2026-08-13 · 最終検証日 2026-08-13
結論
The core of cost reduction is not sending everything to a large model. Route routine work like classification and extraction to smaller models, and route design judgment or long-form reasoning to larger models, while combining prompt caching, output token limits, result caching, and batching. Validate the output of cheaper models through a quality gate, and only retry with a higher-tier model when it fails. As a failure countermeasure, abstract the providers and prepare health checks and circuit breakers, a distinction between 429 and 5xx handling, and a definition of degraded mode.
この文書の適用条件
| 対象製品 | AI Router (a relay layer that bundles multiple LLM providers) |
|---|---|
| 確認バージョン | A design-level explanation independent of product version (pricing and latency constantly change, so this article does not cover them) |
| 適用環境 | AWS, Azure, on-premises |
| 必要権限 | Read access to each provider's API key, and access to the Router host |
| 実行影響 | Read-only (health checks run on a path separate from production traffic) |
| 再起動 | Not required (when the routing policy is loaded dynamically) |
| 最終検証日 | 2026-08-13 |
そのまま実行できるコマンド
- 対象
- Your organization's AI Router routing policy definition
- 権限
- Edit access to the policy definition
- 変更作業
- None (example definition only)
- Production実行
- Not applicable (design sample)
# 対象: 自組織のAI Routerのルーティングポリシー定義
# 権限: ポリシー定義の編集権限
# 変更作業: なし(定義の記述例)
# Production 実行: 該当なし(設計サンプル)
# 「小 / 中 / 大」は自組織で採用しているモデルの相対的な区分を指す。
# 具体的なモデル名と価格は変動するため、ここでは書かずに定義側で解決する。
タスク種別 | 既定の割り当て | 出力上限 | 品質ゲート | 不合格時の扱い
----------------------|----------------|----------|------------------------------|----------------------------
分類・ラベル付け | 小 | 短 | 許可ラベル集合に含まれるか | 中へ1回だけ再試行
構造化抽出(JSON) | 小 | 中 | JSONスキーマ検証 | 中へ1回だけ再試行
要約(短文) | 小 | 中 | 入力に無い固有名詞が無いか | 中へ1回だけ再試行
要約(長文・横断) | 中 | 長 | 参照元の提示があるか | 大へ1回だけ再試行
コード生成(定型) | 中 | 中 | 構文解析とテスト実行 | 大へ1回だけ再試行
設計判断・長文推論 | 大 | 長 | 人間のレビュー | 再試行しない(人へ回す)
自由入力の対話 | 中 | 中 | 出力フィルタ | 中で再試行(上位へ上げない)
共通の制御:
timeout: タスク種別ごとに設定。長文推論だけ長くする
max_retries: 2 まで。ジッタ付き指数バックオフ
prompt_cache: システムプロンプトと共通コンテキストは前方固定にして再利用する
result_cache: 入力のハッシュをキーにする。ただし個人情報を含む入力は対象外
batching: 即時性が不要なタスクのみ。締切のあるタスクは対象外
budget_guard: 日次・月次の上限に対する消費割合を監視し、しきい値で通知する
計測の前提:
- 振り分けの妥当性は、自組織の利用ログ(タスク種別ごとの件数・入出力量・
品質ゲートの合格率・上位モデルへの再試行率)で判断する
- 単価と提供モデルは変わるため、各プロバイダの現行の価格ページを定期的に確認するRouting to cheaper models without a quality gate increases the time humans spend manually fixing failed output. Record the gate pass rate and the retry rate to higher-tier models, and raise the default allocation for task types that retry frequently. The basis for judgment is your own usage logs.
- 対象
- Your organization's AI Router (a relay layer bundling multiple providers)
- 権限
- Read access to each provider's API key and shell access to the Router host
- 変更作業
- None (only connectivity checks and reading/writing state files)
- Production実行
- Allowed (health checks run on a path separate from production traffic)
# 対象: 自組織のAI Router(複数プロバイダを束ねる中継層)
# 権限: 各プロバイダのAPIキー参照権限とRouterホストへのシェルアクセス
# 変更作業: なし(疎通確認と状態ファイルの読み書きのみ)
# Production 実行: 可能(本番トラフィックとは別経路のヘルスチェック)
STATE_DIR=/var/lib/ai-router/breaker
FAIL_THRESHOLD=5 # 連続失敗がこの回数に達したら OPEN にする
mkdir -p "$STATE_DIR"
for p in provider-a provider-b; do
# 軽量なエンドポイントを使う。本番の推論リクエストで死活を測らない
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "https://$p.example.com/v1/models")
fails=$(cat "$STATE_DIR/$p.fails" 2>/dev/null || echo 0)
case "$code" in
200)
fails=0
;;
429)
# レート制限は「プロバイダは生きている」。切り離さずバックオフとキューイングで受ける
echo "$p: 429 rate limited -> backoff, do not open breaker"
;;
5*|000)
# 5xx と接続不能は障害として数える(000 は curl が到達できなかった場合)
fails=$((fails + 1))
;;
4*)
# 429 以外の 4xx はこちらのリクエストの問題。切り離しても直らない
echo "$p: client error $code -> check request, do not open breaker"
;;
esac
echo "$fails" > "$STATE_DIR/$p.fails"
if [ "$fails" -ge "$FAIL_THRESHOLD" ]; then
echo "$p: OPEN -> 新規ルーティングを停止し、次候補へ退避。一定時間後に HALF_OPEN で試行"
else
echo "$p: CLOSED (http=$code consecutive_fails=$fails)"
fi
doneUse a lightweight endpoint for health checks rather than a production inference request. Measuring liveness with inference generates cost and load from the check itself. When recovering from OPEN, don't restore full volume at once — route through a HALF_OPEN state that sends only a portion first.
結果の読み方
| 列 | 意味 | 確認するポイント |
|---|---|---|
| Task-difficulty-based routing | Route routine work to small models and judgment-heavy work to large models | Are per-task-type counts and input/output volume tracked in usage logs? |
| Quality gate | A mechanism that validates a cheap model's output before accepting it | Are the pass rate and the retry-to-higher-model rate being recorded? |
| Prompt caching | Reusing a common prefix to reduce duplicated input | Is the common portion fixed at the front with variable portions placed after it? |
| Output token limit | Capping output length per task type | Is the design such that truncated output doesn't break downstream? |
| Result caching | Reusing results for identical input | Is input containing personal data excluded from caching? |
| Batching | Grouping non-urgent work for execution together | Are deadline-bound tasks mistakenly included in a batch? |
| Retry and timeout policy | Policy for retry count and wait time on failure | Are retries inflating cost and wait time? Is there a cap? |
| Abstraction layer | A structure where the calling side is unaware of provider-specific differences | Can the app switch away from a failed provider without code changes? |
| Circuit breaker | A mechanism that stops sending to a path after consecutive failures | Are OPEN and recovery conditions defined, and does recovery restore traffic gradually? |
| Distinguishing 429 from 5xx | Treating rate limiting and outages differently | Is a 429 NOT triggering a path cutoff (is it instead absorbed with backoff)? |
| Queuing and backpressure | Absorbing inflow and making upstream wait once capacity is reached | Are the queue limit and overflow behavior defined? |
| Degraded mode | A state that keeps only core functions rather than all functions | Is it decided in advance which functions to stop and which to keep? |
| Output-variance acceptance criteria | The tolerance for output changing when the provider changes | Is downstream processing structured to absorb this via schema validation? |
| Cost-cap alerting | A mechanism for noticing unexpected spend | Is it monitored both daily and monthly? Is the notification target active? |
こういう状況で使います
- AI usage costs are rising more than expected, but it's unclear which tasks are driving it
- All processing is routed through the same large model
- When the external AI API becomes unstable, the entire app stops responding
- A 429 response is being treated the same as an outage, cutting off the path
- Switching providers changed the output format and broke downstream processing
- Frequent retries are increasing both wait time and cost
考えられる原因(可能性の高い順)
01
The same model is used regardless of task difficulty
Routing routine work like classification or extraction through the same path as reasoning like design judgment means the routine work also pays for the expensive path. Separating task types first is the prerequisite.
02
There is no cap on output length
Without an output token limit, unnecessarily long output can be generated. Set the cap based on the length that downstream processing actually uses.
03
There is no retry policy
Unlimited retries on every failure increase cost and wait time. Decide on a retry-count cap, backoff, and conditions under which retrying stops.
04
Provider-specific calls are scattered across the entire app
Without an abstraction layer, switching during an outage requires a code change. Consolidating calls into one place means switching is just a configuration change.
05
Rate limiting is not distinguished from outages
A 429 indicates the provider is operating. Treating it as an outage and cutting off the path can divert requests that would have succeeded with waiting onto another path, worsening the situation.
06
What to stop during degradation is undecided
Trying to keep all functions running slows everything down. Deciding priorities in advance lets you keep only the core functions running.
確認手順
- 1
Aggregate usage by task type
参照のみAggregate counts, input volume, output volume, and failure rate by task type from your usage logs. This is the starting point for routing design.
- 2
Check the distribution of output tokens
参照のみLook at actual output length as a distribution to judge where to set the cap. An average alone cannot determine the cap.
- 3
Separate retry rate by cause
参照のみAggregate separately whether retries are due to timeouts, 429s, 5xxs, or quality-gate failures. The response differs for each.
- 4
Check each provider's current pricing and available models
参照のみReference each provider's pricing page and apply it to your own aggregated figures. Since pricing changes, review it periodically.
- 5
Verify operation with one provider disabled
中Disable one path in a test environment and confirm the app keeps working without any code changes.
対応方法
すぐに実施できる低リスクの対応
Start tagging calls by task type
低Attach a task-type label to every call and record it in usage logs. This first resolves the lack of data needed for routing decisions.
Set an output token limit
低Set a cap per task type. Confirm that downstream processing can safely handle output truncated at the cap.
Set cost-cap alerts
低Set thresholds for both daily and monthly spend, and confirm the notification target is active.
Separate handling of 429 and 5xx
低Absorb 429 with backoff, and count only 5xx and connection failures as circuit-breaker failures.
事前検討が必要な変更
Consolidate calls into an abstraction layer
中Gather provider-specific implementation into one place and have the app call a common interface. Switching then becomes just a configuration change.
Implement a quality gate
中Add validation appropriate to the task type — schema validation, allowed-value matching, syntax parsing, test execution — and only accept the result when it passes.
Introduce prompt caching and result caching
中Fix the common prefix at the front and reuse results for identical input. Exclude input containing personal data from caching.
Add a circuit breaker and health checks
中Measure liveness with a lightweight endpoint, implement a transition to OPEN on consecutive failures, and to HALF_OPEN after a set time to restore a portion of traffic.
Define the content of degraded mode
中Decide in advance which functions to stop and which to keep, and prepare the switchover procedure.
専門家のレビューが必要な作業
Change the default model allocation
専門家レビュー必須Lowering the allocation for key tasks reduces cost but may raise the quality-gate failure rate. Apply it gradually and observe the pass rate before expanding.
Introduce queuing and backpressure
専門家レビュー必須A design that absorbs inflow affects upstream wait time and perceived responsiveness. Decide the cap and overflow behavior together with business requirements.
!注意事項
- This article does not cover model pricing, per-token cost, response time, or cost-reduction figures. These change at the provider's discretion and would be outdated as soon as they were written. Base your decisions on your own usage logs and each provider's current pricing page.
- Introduce a design that favors cheaper models together with a quality gate. Without a gate, the time humans spend fixing failed output increases, and overall it stops being a saving.
- Do not cut off a path on a 429. Rate limiting indicates the provider is operating, and the correct response is backoff and queuing.
- Switching providers changes output details. If downstream isn't structured to absorb this via schema validation, failover creates a different outage.
- Do not put input containing personal data into the cache target. Depending on the cache-key design, results could be returned to a different user.
- Do not use production inference requests for health checks. The check itself generates cost and load.
バージョン・環境による違い
これで解決しない場合に確認すること
Identify which task types are driving up cost
Look separately at high-volume tasks and tasks with large per-call input/output volume. The response differs for each.
Review quality-gate failure rates by task type
For types with high failure rates, raising the default allocation may end up being cheaper overall.
Check cache hit rates
If hits are low, the cause lies in key design or variance in input.
Actually trigger a failover
Bring down one provider in a test environment and confirm the switchover and degraded mode behave as expected.
Decide when to check each provider's current pricing page
Pricing and available models change. Include a review cadence in your operating procedures.
この文書の根拠と限界
一般的な技術説明
The routing and failover design applies general availability-design and caching techniques to AI APIs. Model pricing, per-token cost, response time, and cost-reduction rates fluctuate and cannot be verified, so this article does not state any of them. Only the "GIIP's scope" paragraph describes GIIP's own operating practice.
よくある質問
Which tasks are safe to route to a smaller model?
Tasks whose output correctness can be judged mechanically. Classification can be judged by matching against an allowed label set, structured extraction by JSON schema validation, and code generation by syntax parsing and test execution. Tasks with no judging mechanism cannot have their quality guaranteed even if routed to a cheaper path.
How much does cost actually go down?
This article gives no figures. The effect depends on the mix of task types, input/output length, and quality-gate pass rate, and provider pricing also fluctuates. Aggregate input/output volume by task type from your own usage logs and apply it to each provider's current pricing page to estimate.
Should I switch to a different provider when I get a 429?
In principle, absorb it with backoff and queuing. A 429 indicates the provider is operating, so cutting it off does not improve the situation. Only consider falling back to another path if the wait time is not acceptable for the business.
When should the circuit breaker go OPEN?
When 5xx responses and connection failures occur consecutively. Set the threshold from your own measured failure rate. Recovery should go to HALF_OPEN after a set time, sending only a portion, and return to CLOSED once that succeeds.
Switching providers changes the output. How should I handle that?
Make downstream processing absorb it via schema validation, and set the acceptance criterion to "the format is correct and required fields are present." Any processing that assumes exact text matches will break with every failover.
What should be stopped in degraded mode?
This must be decided in advance. Generally, stop non-urgent auxiliary functions (recommendations, summarization, auto-tagging) first and keep the core business flow running. Deciding the order during an actual incident delays the response.
この文書がカバーする質問
- How do you design failover for external AI API outages?
- Where should you start to reduce LLM usage costs?
- How do you build a setup that can switch between multiple AI providers?
リスク表示の意味
- 参照のみデータと設定を変更しません。
- 低影響は限定的ですが、権限と負荷の確認が必要です。
- 中性能・ロック・コストに影響する可能性があります。
- 高障害・データ損失・復旧作業が発生する可能性があります。
- 専門家レビュー必須本番適用前に別途レビューが必須です。
GIIPの対応範囲
Everything above can be implemented without a specific product. GIIP uses a configuration that switches among multiple AI models depending on the use case, and includes path switching and degraded mode in its operating procedures so that processing doesn't stop when an external API misbehaves. Which model is actually applied to which category depends on the type of task and quality requirements, so it must be decided based on your own usage logs. If you'd like help organizing how to aggregate that decision data, you can reach out for a consultation.
執筆・技術検証
GIIP プロダクション運用チーム
大規模Webサービス、SQL Server、Oracle、AWS、Azureの設計・移行・運用に約30年従事。x12largeクラスのAWS RDS for SQL Server環境12セット、約12万テーブルのOracle環境、約3TBのTiDBからAurora MySQLへの移行を経験。現在も複数のクラウドデータベースと約30のWebサービスを、AIエージェントと人間の専門家が継続的に監視・運用しています。
Why AI automated execution needs approval and rollback, and how to design for it
Design elements for automated execution — snapshots, approval gates, dry-run separation, allowlists, idempotency, audit logs, staged rollout, and a kill switch — are summarized, along with where to draw the line on what can run without approval.
ai-operationsWhat it takes to bring an AI-generated application to production
We organize the remaining work between "the code works" and "it can run in production" into 14 items, with commands for detecting hardcoded keys and auditing dependency vulnerabilities.
awsWhat to Check When Reviewing AWS Database Costs
A checklist for reviewing AWS database spend in order of increasing impact: stop what is unused → right-size → storage → backups → non-production → commitments.
giipWhat is the difference between a coding agent and GIIP FDE Ops?
Coding agents and operations services differ in their "unit of work." We compare the boundary between the two across nine dimensions, with commands you can run to check your own organization.
関連サービス
Visualize the cost structure of your AI usage
同じ確認を複数の環境で継続する必要がある場合は、運用体制ごと相談できます。
Visualize the cost structure of your AI usage