Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0050

One daily AI token budget in Redis, per ICT day; per-process fallback when Redis is down

Trạng thái
accepted
Ngày
2026-11-22
Người quyết định
SmartLearn team (#164)

Context

AI_DAILY_TOKEN_BUDGET was counted by a MemoryBudgetStore in every process, and the api even built one store per (provider, model) client. With the api and the worker as separate processes, and across restarts, nobody could say what the real daily ceiling was. The research measured the default (1M) at about 150 tutor answers a day, below the expected ~200.

Decision

  • One counter in Redis per ICT day. RedisBudgetStore (packages/ai) implements BudgetStore with two Lua scripts: reserve = GET, compare with the limit, INCRBY, PEXPIRE in one atomic step; record = INCRBY (negative to settle a reservation down), clamped at 0. Keys stay ai:budget:<bucket>:<window>; BudgetOptions.windowOffsetMs = ICT_UTC_OFFSET_MS makes the window an ICT day, so the budget resets at 00:00 Asia/Ho_Chi_Minh (17:00 UTC), the same calendar as the monthly quota. The package takes any client with eval (ioredis), so it still has no Redis dependency.
  • Every client in a process shares one store. The api's AiService and the worker's runtime each pass one store to every createAiClient call (overrides.budgetStore). Both use their own fail-fast connection (no offline queue, one retry): BullMQ's connection queues commands while disconnected, which would make an AI call wait instead of fall back.
  • Redis down: fall back to the per-process in-memory budget, with a warning. A FailoverBudgetStore sends every operation to Redis and, when that throws, to a MemoryBudgetStore with the same limit, logging at most once a minute. We chose this over both plain options: - _Fail closed_ (refuse every call) would take the tutor down for every student on a Redis blip (Upstash free tier), although each answer is already paid for from the student's monthly quota in Postgres (ADR-0044). The budget is a last cash stop, not the main control. - _Fail open_ (no limit) would leave nothing between a bug or abuse and the bill. - The fallback keeps a limit: the most an outage day can cost is (processes × limit). Today that is 2 (api + embedded worker, ADR-0039), so ≤ 4M tokens ≈ 8.3 USD at the 2027 Flash rate.
  • Without REDIS_URL (local dev, unit tests) the store is in memory only, as before.
  • Refusal is explicit. A call the budget refuses is never sent. AiService turns it into a 503 AI_DAILY_BUDGET_EXCEEDED with a Vietnamese message, and skips the fallback provider (the budget is shared, it would be refused too); the tutor answers that message as a DEGRADED reply and refunds the credit.
  • Default 2,000,000 tokens per ICT day for the whole platform, from the research: ~200 typical tutor answers ≈ 1.3M tokens, plus ~0.7M for quiz generation, grading and embeddings, which now share the budget. At the blended 2027 tutor rate ($2.07 / 1M) that is ≈ 108,000 đ a day, ≈ 3.2M đ a month at most. Formula and reasoning are in .env.example.

Consequences

Proven on a real Postgres and Redis by apps/api/test/integration/ai-daily-budget.int-spec.ts: 12 concurrent tutor questions split across two app instances never push the shared counter past the limit, the tokens the provider was asked for equal the counter, refused questions made no provider call and were refunded, and a restarted instance sees the day's spend. Unit tests cover the ICT-midnight rollover, 20 concurrent calls at the edge, and the failover. A reservation and its settlement can land in different stores if Redis comes back between them; the error is at most one call's worst case and is accepted. Per-course budgets (budgetKey: course:<id>) use the same store.