feat(gateway): add configurable daily usage limits - #714
Open
YorhaL wants to merge 1 commit into
Open
Conversation
YorhaL
force-pushed
the
feat/daily-usage-limits
branch
from
August 6, 2026 11:34
7ae5049 to
2ae9763
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
需求背景
在上游 Token 资源或整体服务容量有限的情况下,仅使用 RPM 无法限制单个用户在一天内消耗的资源总量。部分用户即使请求频率不高,也可能通过大上下文或高价格模型占用大量额度,从而影响其他用户的可用性。
因此需要提供一个按日累计的最高使用量限制,用于控制单个用户或 API Key 每天最多能够使用多少资源,避免少数用户持续占用过多 Token,并确保有限 Token 资源能够在用户之间得到相对公平的分配。
该功能关注的是网关层面的资源使用控制,与现有机制关注的维度不同:
因此,即使用户钱包余额充足、余额无限或仍有套餐额度,管理员也可以单独通过每日使用限额限制其当天的最高使用量。该限制不会增加余额、抵扣费用或改变现有计费结果。
功能概述
本 PR 增加了以美元计价的每日使用限额,作为一项独立的网关限流策略。
该功能与钱包余额、套餐额度相互独立。当用户当天已完成请求的累计用量达到配置上限后,后续正成本或无法确定成本的请求将返回 HTTP 429;能够明确证明为零成本的请求仍然允许执行。
默认不开启限制,因此升级后不会改变现有用户行为。
限额策略
系统设置
daily_usage_limit_usd。0表示默认不限额。用户组
inherit、system和custom三种模式。0时,该用户不限额。普通 API Key
0或null时,不增加 Key 级限制。独立 API Key
null:跟随系统默认额度。0:明确不限额。绕过规则
每日窗口按照
APP_TIMEZONE的自然日计算,默认时区为Asia/Shanghai。执行与计量
actual_total_cost_usd累计当天用量。达限响应包括:
daily_usage_limit_exceeded。Retry-After。性能设计
请求热路径完全基于 Redis,不会查询数据库。
Redis 状态恢复
项目默认不启用 Redis 持久化,因此增加了 Redis 状态丢失后的数据库懒恢复:
background_data。管理接口与前端
本 PR 补充了以下管理能力:
/api/monitoring/rate-limit-status保持原字段兼容,并为每个 Key 增加嵌套的daily_usage状态,包括:数据库兼容性
包含以下数据库的迁移:
同时更新了:
新增字段均为可空或默认继承配置。升级后,现有用户和 API Key 默认不会受到限制。
验证情况
cargo fmt --all -- --check通过。git diff --check通过。