メインコンテンツまでスキップ

Yabanin 本番ランブック

アーキテクチャ概要​

┌─────────────────────────────────────────┐
│ Internet / CDN │
└────────────────┬────────────────────────┘
│
┌────────────────▼────────────────────────┐
│ Gateway (:8082) │
│ - Auth middleware (API key → org/team) │
│ - Cache lookup (Redis + pgvector) │
│ - Classifier routing (ML + rule-tier) │
│ - Budget enforcement │
│ - Upstream proxy (OpenAI/Anthropic) │
└──┬──────┬──────┬──────┬──────────────────┘
│ │ │ │
┌──────────▼┐ ┌──▼──┐ ┌▼────────┐ ┌──────────────┐
│ PostgreSQL │ │Redis│ │Classifier│ │ BGE Embedder │
│ (:5432) │ │(:6379)│ (:8080) │ │ (:6006) │
│ pgvector │ │ │ │ ML V1 │ │ │
└─────┬─────┘ └──┬──┘ └─────────┘ └──────────────┘
│ │
┌─────▼─────┐ │ Redis Stream: events:queue
│ Admin ─│ │
│ (:8086) │◄───┘
│ Dashboard │ ┌──────────────┐
│ (:3000) │ │ Loggerd │
└───────────┘ │ (:8085) │
│ DB writer │
└──────────────┘

サービス​

サービスポート目的ヘルスチェック
ゲートウェイ8082メイン API プロキシ(OpenAI 互換)GET /healthz
Admin8086管理パネル + REST APIGET /health
Loggerd8085Redis ストリーム → PostgreSQL ライターGET /healthz
PostgreSQL5432プライマリデータベース(pgvector)pg_isready
Redis6379キャッシュ + イベントストリームredis-cli ping
Classifier8080ML タスクの複雑度(bge-small)GET /health
BGE Embedder6006セマンティックキャッシュ向けの埋め込みサービスGET /health
Dashboard3000React のコスト利用分析ダッシュボードHTTP 200

導入​

初回導入​

# 1. Create secrets (one-time setup)
cd deploy/secrets
echo "postgresql://yabanin:SECRET@postgres:5432/yabanin?sslmode=disable" > pg_uri
openssl rand -hex 32 > session_key
openssl rand -hex 32 > cache_hmac

# 2. Build and start all services
cd deploy/
docker compose up -d

# 3. Verify migrations ran
docker compose logs migrate | tail -20

# 4. Verify all services healthy
docker compose ps
curl http://localhost:8082/healthz
curl http://localhost:8086/health

サービスの更新​

# Rebuild and restart a single service
docker compose up -d --build gateway

# Zero-downtime rolling restart (for config-only changes)
docker compose restart gateway

ロールバック​

# Roll back to previous image
docker compose down gateway
docker tag yabanin-gateway:latest yabanin-gateway:rollback
docker tag yabanin-gateway:previous yabanin-gateway:latest
docker compose up -d gateway

# Database rollback (if migration caused issues)
# CAUTION: only run .down.sql if you understand the consequences
psql -h localhost -U yabanin -d yabanin -f migrations/0029_team_budgets.down.sql

環境変数​

ゲートウェイ​

変数必須説明
YABANIN_GATEWAY_LISTENはい待受アドレス(:8082)
YABANIN_PG_URI_FILEはいPG 接続文字列シークレットへのパス
YABANIN_REDIS_ADDRはいRedis アドレス(redis:6379)
YABANIN_EVENT_STREAMはいRedis ストリーム名(events:queue)
YABANIN_CACHE_HMAC_SECRET_FILEはいHMAC 署名シークレットへのパス
YABANIN_EMBEDDER_BASE_URLいいえ埋め込みサービスの URL
YABANIN_EMBEDDER_ENABLEDいいえセマンティックキャッシュを有効にします(true/false)

Admin​

変数必須説明
YABANIN_PG_URI_FILEはいPG 接続文字列へのパス
YABANIN_SESSION_KEY_FILEはいセッション署名キーへのパス
YABANIN_ADMIN_LISTENはい待受アドレス(:8086)
YABANIN_ADMIN_DOMAINはいCookie のドメイン(localhost)
YABANIN_ADMIN_API_KEYいいえ読み取り専用の /internal サービス API を有効にします(下記を参照)

Admin: 内部サービス API​

  • デフォルトでは無効です。YABANIN_ADMIN_API_KEY がない場合、独立した /internal の公開面はありません。
  • エンドポイント: GET /internal/api-keys?org_id=<id>&page=1&page_size=50、GET /internal/analytics/savings?org_id=<id>&days=7。
  • 認証: 定数時間でのヘッダー検査です。キーは X-Admin-Key: <value> として送ります(trcli は --api-key を使います)。
  • 読み取り専用かつ組織スコープです。両方のルートは org_id を必須とし、変更操作は公開しません。

スケーリング​

垂直(CPU/メモリの増加)​

# In docker-compose.yml, under deploy.resources:
deploy:
resources:
limits:
memory: 512M # was 256M
cpus: "2.0" # was 1.0

水平(レプリカの追加)​

ゲートウェイと loggerd はステートレスなので、水平にスケールしても安全です。

docker compose up -d --scale gateway=3 --scale loggerd=2

ゲートウェイのレプリカの前に、ロードバランサ(nginx/HAProxy)を置きます。

Redis のスケーリング​

  • 読み取りレプリカ: 読み取りが多いワークロード(キャッシュの参照)向けに Redis レプリカを追加します
  • メモリ: used_memory を監視します。OOM の前にコンテナのメモリ上限を上げてください
  • 永続化: 耐久性のため appendonly yes が有効です。AOF の書き換え頻度を監視します

PostgreSQL のスケーリング​

  • コネクションプーリング: ゲートウェイの接続が max_connections を超える場合は PgBouncer を使います
  • pgvector: HNSW インデックスのサイズを監視します。クエリのレイテンシが悪化したら再インデックスします
  • 読み取りレプリカ: 利用分析やダッシュボードのクエリ(admin サービス)向けに追加します

インシデント対応​

P0: ゲートウェイ停止(すべてのリクエストが失敗)​

# 1. Check gateway health
curl http://localhost:8082/healthz

# 2. Check recent logs
docker compose logs gateway --tail=100

# 3. Check dependencies
docker compose ps # Are postgres/redis/classifier healthy?

# 4. Quick restart
docker compose restart gateway

# 5. If still failing, check DB connectivity
docker compose exec gateway wget -qO- http://postgres:5432 || echo "DB unreachable"

# 6. If Redis is down, gateway can still serve (cache miss fallback)
# but loggerd cannot write to DB. Fix Redis first.

P1: 高レイテンシ(p95 > 2s)​

# 1. Check upstream provider latency
docker compose logs gateway --tail=50 | grep "duration"

# 2. Check Redis latency
docker compose exec redis redis-cli --latency

# 3. Check DB connection pool
docker compose exec postgres psql -U yabanin -c \
"SELECT count(*), state FROM pg_stat_activity GROUP BY state;"

# 4. Check if classifier is slow (>100ms timeout)
docker compose logs gateway --tail=50 | grep "classifier"

# 5. Mitigation: disable classifier temporarily (fallback to rule-tier)
curl -X PATCH -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8086/api/organizations/$ORG_ID/routing \
-d '{"routing_mode": "always_cheap"}'

P1: Classifier サービスの停止​

# Gateway automatically falls back to rule-tier classifier (circuit breaker)
# Verify fallback is working:
docker compose logs gateway --tail=50 | grep "circuit.*open"

# Check classifier health
curl http://localhost:8080/health

# Restart classifier
docker compose restart classifier

# Verify recovery
docker compose logs gateway --tail=50 | grep "circuit.*closed"

P1: データベース接続の枯渇​

# Check active connections
docker compose exec postgres psql -U yabanin -c \
"SELECT count(*), state, application_name FROM pg_stat_activity GROUP BY state, application_name;"

# If idle connections are high, restart services to release them
docker compose restart gateway admin

# Increase max_connections if needed
docker compose exec postgres psql -U yabanin -c "SHOW max_connections;"
# Edit postgresql.conf or set in docker-compose env

P2: Redis のメモリ不足​

# Check memory usage
docker compose exec redis redis-cli INFO memory | grep used_memory_human

# Check evicted keys
docker compose exec redis redis-cli INFO stats | grep evicted_keys

# Flush cache if needed (will cause temporary cache miss spike)
docker compose exec redis redis-cli FLUSHDB
# Or flush specific patterns:
docker compose exec redis redis-cli --scan --pattern "cache:*" | xargs redis-cli DEL

P2: Loggerd の遅延(ストリームのバックログ)​

# Check stream length
docker compose exec redis redis-cli XLEN events:queue

# Check consumer group lag
docker compose exec redis redis-cli XINFO GROUPS events:queue

# Scale loggerd
docker compose up -d --scale loggerd=3

# If backlog is huge, trim old messages
docker compose exec redis redis-cli XTRIM events:queue MAXLEN 100000

監視​

主要メトリクス(:2112 の Prometheus)​

メトリクスアラートしきい値
http_request_duration_seconds{quantile="0.95"}5 分間 2s 超
cache_hits_total{type="miss"} のレート15 分間 80% 超
circuit_breaker_state5 分間 1(open)
redis_stream_length10,000 超
pg_connections_active最大の 80% 超

Grafana ダッシュボード​

deploy/grafana/dashboards/ にあります。Grafana UI からインポートします。

主要パネル:

  • リクエスト量とレイテンシのパーセンタイル
  • キャッシュヒット率(完全一致 vs セマンティック vs ミス)
  • Classifier の分布(簡単(easy)/ 中程度(medium)/ 難しい(hard))
  • コスト削減(実績 vs 反事実)
  • プロバイダ別の上流エラー率

アラートの注意(必読)​

deploy/alertmanager/alertmanager.yml は、レシーバーがコメントアウトされた状態で配布されます(SMTP/Slack/PagerDuty は TODO のプレースホルダーです)。実際のレシーバーまたは Webhook を設定するまで、アラートは誰にも配信されません。Alertmanager はルールを評価し、ファイルログのレシーバーにのみ経路付けします。本番でアラートに頼る前に、少なくとも 1 つの実際のレシーバーを接続してください。

メトリクス公開の注意​

metrics_enabled: true は、admin リスナー(:9090)で /metrics を提供します。デフォルトでは認証はありません。Prometheus がスクレイプできるようにするための意図的なトレードオフです。代わりに Authorization: Bearer <key> を必須にするには、metrics_bearer_key(環境変数 YABANIN_METRICS_BEARER_KEY)を設定します。検査対象は Bearer トークンのみで、localhost 制限はない点に注意してください。スクレイパーは通常、別の Pod またはホストにいるためです。admin ポートをネットワークで完全に制限できない場合は、キーの使用を優先してください。メトリクスにはモデル名、組織 ID、経路ごとのトラフィック量が含まれます。これは、そのポートに到達できるセグメントへ公開したくない運用データである場合があります。本番ではネットワークレベルで制限してください。Kubernetes の NetworkPolicy、またはクラスタの Prometheus Pod / メトリクス範囲にスコープしたファイアウォールルールを使い、compose の導入では、ホスト上に admin ポートを決して公開しないでください。スクレイプはクラスタ内(PodMonitor / ServiceMonitor)に留め、クラスタの外からは決して行わないでください。

ゲート付き pprof​

debug_pprof: true のとき、ゲートウェイの admin リスナーは 5 つのプロファイルを公開します。対象は /debug/pprof/(インデックス)、cmdline、profile、symbol、trace で、すべて /debug/vars と同じゲートの背後にあります。localhost からの呼び出しのみであり、Authorization: Bearer <YABANIN_API_KEY> が必要です。30 秒の CPU プロファイルを取得します。

curl -H "Authorization: Bearer $YABANIN_API_KEY"

"http://127.0.0.1:9090/debug/pprof/profile?seconds=30" -o cpu.pprof go tool pprof cpu.pprof

名前付きプロファイルのエンドポイント(goroutine、heap、block、mutex、threadcreate)は、admin リスナーには意図的に公開していません。何が使えるかはインデックスページで選び、ヒープや goroutine のデータが必要なら SIGQUIT ダンプまたはサイドカーから取得してください。すべての拒否は、スタックトレースなしで 403 を返します(localhost 以外からの呼び出しと、不正な Bearer トークンの両方です)。


バックアップと復旧​

データベースのバックアップ​

# Full backup (run daily via cron)
docker compose exec postgres pg_dump -U yabanin yabanin | gzip > backup_$(date +%Y%m%d).sql.gz

# Restore
gunzip -c backup_20260723.sql.gz | docker compose exec -T postgres psql -U yabanin yabanin

Redis のバックアップ​

# AOF persistence is enabled (appendonly yes)
# Manual snapshot:
docker compose exec redis redis-cli BGSAVE
# Copy dump.rdb from volume
docker compose cp redis:/data/dump.rdb ./redis_backup_$(date +%Y%m%d).rdb

モデルチェックポイントのバックアップ​

# Classifier checkpoint
cp artifacts/classifier-v1.pt backups/classifier-v1-$(date +%Y%m%d).pt

ソースのバックアップ(git bundle)​

# Local bundle of ALL branches + tags into .backups/ (default retention: last 5)
make backup
# Options: BACKUP_DIR=/other/path RETAIN=10 make backup
# Restore/clone from a bundle:
git clone .backups/yabanin-<stamp>.bundle

リモートも資格情報も使いません。バンドルは gitignore 対象です(.backups/)。本当のマシン外バックアップにするには、バンドルをマシンの外(例: 暗号化ストレージ)へコピーしてください。


一般的な操作​

新しい組織の追加​

curl -X POST -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8086/api/organizations \
-d '{"name": "Acme Corp", "slug": "acme"}'

API キーのローテーション​

curl -X POST -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8086/api/api-keys/{id}/rotate

支出アラートの設定​

curl -X PATCH -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8086/api/organizations/{id}/spend-alert \
-d '{"threshold_usd": 100.0, "webhook_url": "https://hooks.slack.com/..."}'

チーム予算の設定​

curl -X PUT -H "Authorization: Bearer $ADMIN_TOKEN" \
http://localhost:8086/api/teams/{team_id}/budget \
-d '{"monthly_limit_usd": 500.0, "hard_limit": true}'

Classifier の再学習​

# 1. Generate new dataset
docker run --rm -v $(pwd)/datasets:/app/datasets yabanin-train \
python scripts/build_dataset.py --output /app/datasets/classifier/

# 2. Train
docker run --rm \
-v $(pwd)/datasets:/app/datasets \
-v $(pwd)/artifacts:/output \
yabanin-train \
--train /app/datasets/classifier/prompts_train.jsonl \
--test /app/datasets/classifier/prompts_test.jsonl \
--output /output/classifier-v2.pt \
--epochs 5

# 3. Evaluate
docker run --rm --entrypoint python \
-v $(pwd)/artifacts:/app/artifacts \
-v $(pwd)/datasets:/app/datasets \
-v $(pwd)/scripts:/app/scripts \
yabanin-train \
/app/scripts/evaluate_classifier.py \
--checkpoint /app/artifacts/classifier-v2.pt

# 4. Deploy new model
docker compose build classifier
docker compose up -d classifier

オンコール早見表​

症状最初の対応エスカレーションする条件
5xx エラーが急増しているゲートウェイのログを確認し、必要なら再起動します5 分を超えて続く場合
レイテンシの p95 が 2s を超える上流と Redis のレイテンシを確認します10 分を超えて続く場合
キャッシュヒット率が 25% 未満キャッシュのランブック を参照してください30 分を超えて続く場合
Classifier のエラーサーキットブレーカーが自動でフォールバックしますすべての Classifier が停止している場合
予算による拒否が急増している上限の設定ミスがないか確認します組織がロックアウトされている場合
DB ディスクが満杯古いログを Vacuum してアーカイブします空き容量が 10% 未満の場合
Redis の OOMキャッシュをフラッシュし、メモリを追加します再発する場合