apisix icon indicating copy to clipboard operation
apisix copied to clipboard

help request: How to gracefully implement token quota limiting to block access once exceeding quota

Open RGZingYang opened this issue 4 months ago • 2 comments

Description

I want to enable token quota control on Apache APISIX. Limits can be set per user or per user-route pair. After a user exhausts their total request quota, all follow-up requests initiated by the user are blocked, with no traffic forwarded to the target upstream LLM service.

Environment

  • APISIX version (run apisix version):
  • Operating system (run uname -a):
  • OpenResty / Nginx version (run openresty -V or nginx -V):
  • etcd version, if relevant (run curl http://127.0.0.1:9090/v1/server_info):
  • APISIX Dashboard version, if relevant:
  • Plugin runner version, for issues related to plugin runners:
  • LuaRocks version, for installation issues (run luarocks --version):

RGZingYang avatar Jul 29 '26 02:07 RGZingYang

Hi @RGZingYang, this can be achieved using the ai-rate-limiting plugin. It counts the tokens from the LLM response usage field against a quota, and once the quota is exhausted it rejects follow-up requests at the gateway without forwarding them to the upstream LLM.

Key the quota per user with the rules option (APISIX >= 3.16.0) plus an authentication plugin so $consumer_name resolves:

{
  "uri": "/chat",
  "plugins": {
    "key-auth": {},
    "ai-proxy": { ... },
    "ai-rate-limiting": {
      "rules": [
        { "key": "$consumer_name", "count": 100000, "time_window": 2592000 }
      ],
      "rejected_code": 429,
      "rejected_msg": "token quota exhausted"
    }
  }
}

Counters are scoped to the resource the plugin is attached to:

  • On a route: one counter per user per route (your "user-route pair" case).
  • On a shared service: one counter per user across all its routes (your "per user" case).

Notes:

  • It only works together with ai-proxy / ai-proxy-multi.
  • Accounting is post-paid (cost is known only after the response), so the request that crosses the quota still completes; everything after it is blocked.
  • For streaming, make sure the provider returns usage in the stream (OpenAI: "stream_options": {"include_usage": true}).

For more detailed reference you can read this documentation: https://apisix.apache.org/docs/apisix/plugins/ai-rate-limiting/

janiussyafiq avatar Aug 13 '26 03:08 janiussyafiq

thinks

RGZingYang avatar Aug 14 '26 07:08 RGZingYang