giip
SES Proposal
AI運用参照のみモデルコストフェイルオーバーコスト監視自動化

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

そのまま実行できるコマンド

Routing policy definition (per-task-type allocation and quality gates)参照のみ
対象
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.

Provider health checks and circuit breaker state transitions参照のみ
対象
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
done

Use 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 routingRoute routine work to small models and judgment-heavy work to large modelsAre per-task-type counts and input/output volume tracked in usage logs?
Quality gateA mechanism that validates a cheap model's output before accepting itAre the pass rate and the retry-to-higher-model rate being recorded?
Prompt cachingReusing a common prefix to reduce duplicated inputIs the common portion fixed at the front with variable portions placed after it?
Output token limitCapping output length per task typeIs the design such that truncated output doesn't break downstream?
Result cachingReusing results for identical inputIs input containing personal data excluded from caching?
BatchingGrouping non-urgent work for execution togetherAre deadline-bound tasks mistakenly included in a batch?
Retry and timeout policyPolicy for retry count and wait time on failureAre retries inflating cost and wait time? Is there a cap?
Abstraction layerA structure where the calling side is unaware of provider-specific differencesCan the app switch away from a failed provider without code changes?
Circuit breakerA mechanism that stops sending to a path after consecutive failuresAre OPEN and recovery conditions defined, and does recovery restore traffic gradually?
Distinguishing 429 from 5xxTreating rate limiting and outages differentlyIs a 429 NOT triggering a path cutoff (is it instead absorbed with backoff)?
Queuing and backpressureAbsorbing inflow and making upstream wait once capacity is reachedAre the queue limit and overflow behavior defined?
Degraded modeA state that keeps only core functions rather than all functionsIs it decided in advance which functions to stop and which to keep?
Output-variance acceptance criteriaThe tolerance for output changing when the provider changesIs downstream processing structured to absorb this via schema validation?
Cost-cap alertingA mechanism for noticing unexpected spendIs 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

考えられる原因(可能性の高い順)

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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. 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. 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. 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. 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. 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.

バージョン・環境による違い

When depending on a provider's SDKDefault retry behavior can differ across SDK versions. Control retries at the abstraction-layer level so they don't duplicate the SDK's automatic retries.
When using a managed inference platformThe unit of rate limiting (token-based or request-based) differs by platform. Align your backoff design with that unit.
When combining with a self-hosted modelThis can serve as a fallback when an external API is unavailable, but capability differences will show in the output. Define in advance the range acceptable as degraded mode.

これで解決しない場合に確認すること

  • 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エージェントと人間の専門家が継続的に監視・運用しています。

関連するナレッジ

関連サービス

Visualize the cost structure of your AI usage

同じ確認を複数の環境で継続する必要がある場合は、運用体制ごと相談できます。

Visualize the cost structure of your AI usage

ナレッジベース一覧へ