Limit Req
limit-req 插件使用漏桶算法,按键执行持续请求速率限制。它可以立即拒绝超出的请求,或在配置的突发额度内延迟处理。
本地限速与基于 Redis 的限速
limit-req 插件支持两种限速模式:
- 本地限速:每个网关实例独立实施限速。每个实例维护自己的计数器,因此当流量分散到多个实例时,实际限额约为“限额 × 实例数”。未设置
policy或将其设置为local时,这是默认模式。 - 基于 Redis 的限速:所有网关实例通过 Redis 共享限额,因此配置的限额会应用到所有网关实例。
理解突发请求和请求间隔
rate 决定累积的超额请求量以多快的速度持续消减,burst 是限流器允许累积的超额量。这两个参数不会为实际时间的每一秒设定固定的 rate + burst 配额。
对于尚无请求的键,假设 rate: 2、burst: 3,且请求完全按照下表所示的时间到达限流器:
| 到达方式 | 结果 |
|---|---|
| 五个请求同时到达 | 第一个请求启动漏桶。接着三个请求占用突发配额,第五个请求被拒绝。 |
| 五个请求依次到达,间隔 0.5 秒 | 累积的超额量以每秒两个请求的速率消减,因此五个请求均可通过。 |
| 同时到达的这批请求之后 0.5 秒,又来一个请求 | 超额量已经减少一个单位,因此可以再放行一个请求。 |
当 nodelay: false 时,这批同时到达且获准通过的三个超额请求分别等待约 0.5、1 和 1.5 秒。当 nodelay: true 时,这些请求立即继续处理,但仍会占用突发配额。此设置不会提高持续请求速率,也不会清空漏桶。
按照实现 API 节流配置漏桶,并比较同时发送的请求与按配置速率间隔发送的请求。每轮测试之间等待漏桶排空,并记录时间戳和延迟,因为客户端进程只能近似模拟请求同时到达。
示例
以下示例演示了如何在不同场景下配置 limit-req。
基于远程地址进行速率限制
以下示例演示了如何通过单个变量 remote_addr 对 HTTP 请求进行速率限制。
创建一个启用了 limit-req 插件的路由,配置为每个远程地址允许 1 QPS:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '
{
"id": "limit-req-route",
"uri": "/get",
"plugins": {
"limit-req": {
"rate": 1,
"burst": 0,
"key": "remote_addr",
"key_type": "var",
"rejected_code": 429,
"policy": "local",
"nodelay": true
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
services:
- name: httpbin
labels:
docs-example: limit-req
routes:
- uris:
- /get
name: limit-req-route
plugins:
limit-req:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
预览变更,并确认变更仅影响本指南使用的资源:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
将配置同步到网关:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: limit-req-plugin-config
spec:
plugins:
- name: limit-req
config:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: limit-req-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: limit-req-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: limit-req-route
spec:
ingressClassName: apisix
http:
- name: limit-req-route
match:
paths:
- /get
methods:
- GET
upstreams:
- name: httpbin-external-domain
plugins:
- name: limit-req
config:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
应用配置:
kubectl apply -f limit-req-ic.yaml
❶ rate:将 QPS 限制为 1。
❷ key:设置为 remote_addr,以根据远程地址和消费者应用速率限制配额。
❸ key_type:设置为 var,以将 key 解释为变量。
发送请求进行验证:
curl -i "http://127.0.0.1:9080/get"
你应该会看到一个 HTTP/1.1 200 OK 响应。
该请求已消耗了时间窗口内允许的所有配额。如果你在同一秒内再次发送请求,应该会收到一个 HTTP/1.1 429 Too Many Requests 响应,表明请求超过了配额阈值。
实现 API 流量整形
以下示例演示了如何配置 burst 以允许超过速率限制阈值的请求按配置值进行排队,从而实现请求流量整形。你还将看到与未实施流量整形时的比较。
创建一个启用了 limit-req 插件的路由,配置为每个远程地址允许 1 QPS,burst 为 1:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "limit-req-route",
"uri": "/get",
"plugins": {
"limit-req": {
"rate": 1,
"burst": 1,
"key": "remote_addr",
"rejected_code": 429,
"policy": "local"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
services:
- name: httpbin
labels:
docs-example: limit-req
routes:
- uris:
- /get
name: limit-req-route
plugins:
limit-req:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
预览变更,并确认变更仅影响本指南使用的资源:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
将配置同步到网关:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
- Gateway API
- APISIX CRD
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: limit-req-plugin-config
spec:
plugins:
- name: limit-req
config:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: limit-req-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: limit-req-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: limit-req-route
spec:
ingressClassName: apisix
http:
- name: limit-req-route
match:
paths:
- /get
methods:
- GET
upstreams:
- name: httpbin-external-domain
plugins:
- name: limit-req
config:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
应用配置:
kubectl apply -f limit-req-ic.yaml
❶ burst:允许 1 个超过配置速率的请求延迟处理。该值的单位为请求数,而非每秒请求数。
生成三个请求到该路由:
resp=$(seq 3 | xargs -I{} curl -i "http://127.0.0.1:9080/get" -o /dev/null -s -w "%{http_code}\n") && \
count_200=$(echo "$resp" | grep "200" | wc -l) && \
count_429=$(echo "$resp" | grep "429" | wc -l) && \
echo "200 responses: $count_200 ; 429 responses: $count_429"
你可能会看到所有三个请求都成功:
200 responses: 3 ; 429 responses: 0
设置 nodelay: true 后,允许的突发请求会立即通过而无需等待,并且仍会保留突发容量;若设置 burst: 0,则会移除该容量。以下示例继续使用 rate: 1 和 burst: 1:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes/limit-req-route" -X PATCH \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"plugins": {
"limit-req": {
"nodelay": true
}
}
}'
在 ADC YAML 中设置 nodelay: true:
services:
- name: httpbin
labels:
docs-example: limit-req
routes:
- uris:
- /get
name: limit-req-route
plugins:
limit-req:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
nodelay: true
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
预览变更,并确认变更仅影响本指南使用的资源:
adc diff -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
将更新后的插件配置同步到网关:
adc sync -f adc.yaml \
--include-resource-type service \
--label-selector docs-example=limit-req
按如下方式更新清单文件:
- Gateway API
- APISIX CRD
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: limit-req-plugin-config
spec:
plugins:
- name: limit-req
config:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
nodelay: true
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: limit-req-route
spec:
ingressClassName: apisix
http:
- name: limit-req-route
match:
paths:
- /get
methods:
- GET
upstreams:
- name: httpbin-external-domain
plugins:
- name: limit-req
config:
rate: 1
burst: 1
key: remote_addr
rejected_code: 429
policy: local
nodelay: true
应用更新后的配置:
kubectl apply -f limit-req-ic.yaml
再次生成三个请求到该路由:
resp=$(seq 3 | xargs -I{} curl -i "http://127.0.0.1:9080/get" -o /dev/null -s -w "%{http_code}\n") && \
count_200=$(echo "$resp" | grep "200" | wc -l) && \
count_429=$(echo "$resp" | grep "429" | wc -l) && \
echo "200 responses: $count_200 ; 429 responses: $count_429"
在计数器刚创建且请求间隔足够短、能够彼此重叠时,一个示例结果如下:
200 responses: 2 ; 429 responses: 1
基于远程地址和消费者名称进行速率限制
以下示例演示了如何通过变量组合 remote_addr 和 consumer_name 对请求进行速率限制。
- Admin API
- ADC
- Ingress Controller
创建消费者 john:
curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "john"
}'
为该消费者创建 key-auth 凭证:
curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "cred-john-key-auth",
"plugins": {
"key-auth": {
"key": "john-key"
}
}
}'
创建第二个消费者 jane:
curl "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"username": "jane"
}'
为该消费者创建 key-auth 凭证:
curl "http://127.0.0.1:9180/apisix/admin/consumers/jane/credentials" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "cred-jane-key-auth",
"plugins": {
"key-auth": {
"key": "jane-key"
}
}
}'
创建一个启用了 key-auth 和 limit-req 插件的路由:
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "limit-req-route",
"uri": "/get",
"plugins": {
"key-auth": {},
"limit-req": {
"rate": 1,
"burst": 0,
"key": "$remote_addr $consumer_name",
"key_type": "var_combination",
"rejected_code": 429,
"policy": "local"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
创建两个消费者和一个按消费者启用限速的路由:
consumers:
- username: john
labels:
docs-example: limit-req
credentials:
- name: key-auth
type: key-auth
config:
key: john-key
- username: jane
labels:
docs-example: limit-req
credentials:
- name: key-auth
type: key-auth
config:
key: jane-key
services:
- name: limit-req-service
labels:
docs-example: limit-req
routes:
- name: limit-req-route
uris:
- /get
plugins:
key-auth: {}
limit-req:
rate: 1
burst: 0
key: "$remote_addr $consumer_name"
key_type: var_combination
rejected_code: 429
policy: local
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
预览变更,并确认变更仅影响本指南使用的资源:
adc diff -f adc.yaml \
--include-resource-type consumer \
--include-resource-type service \
--label-selector docs-example=limit-req
将配置同步到网关:
adc sync -f adc.yaml \
--include-resource-type consumer \
--include-resource-type service \
--label-selector docs-example=limit-req
创建两个消费者和一个按消费者启用限速的路由:
- Gateway API
- APISIX CRD
apiVersion: apisix.apache.org/v1alpha1
kind: Consumer
metadata:
namespace: aic
name: john
spec:
gatewayRef:
name: apisix
credentials:
- type: key-auth
name: primary-key
config:
key: john-key
---
apiVersion: apisix.apache.org/v1alpha1
kind: Consumer
metadata:
namespace: aic
name: jane
spec:
gatewayRef:
name: apisix
credentials:
- type: key-auth
name: primary-key
config:
key: jane-key
---
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: limit-req-plugin-config
spec:
plugins:
- name: key-auth
config:
_meta:
disable: false
- name: limit-req
config:
rate: 1
burst: 0
key: "$remote_addr $consumer_name"
key_type: var_combination
rejected_code: 429
policy: local
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: limit-req-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: limit-req-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
apiVersion: apisix.apache.org/v2
kind: ApisixConsumer
metadata:
namespace: aic
name: john
spec:
ingressClassName: apisix
authParameter:
keyAuth:
value:
key: john-key
---
apiVersion: apisix.apache.org/v2
kind: ApisixConsumer
metadata:
namespace: aic
name: jane
spec:
ingressClassName: apisix
authParameter:
keyAuth:
value:
key: jane-key
---
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: limit-req-route
spec:
ingressClassName: apisix
http:
- name: limit-req-route
match:
paths:
- /get
methods:
- GET
upstreams:
- name: httpbin-external-domain
plugins:
- name: key-auth
config:
_meta:
disable: false
- name: limit-req
config:
rate: 1
burst: 0
key: "$remote_addr $consumer_name"
key_type: var_combination
rejected_code: 429
policy: local
应用配置:
kubectl apply -f limit-req-ic.yaml
❶ key-auth:在路由上启用密钥认证。
❷ key:设置为 $remote_addr $consumer_name,以根据远程地址和消费者应用速率限制配额。
❸ key_type:设置为 var_combination,将 key 解释为变量组合。
同时发送两个请求,每个消费者一个:
curl -i "http://127.0.0.1:9080/get" -H 'apikey: jane-key' & \
curl -i "http://127.0.0.1:9080/get" -H 'apikey: john-key' &
你应该收到两个请求的 HTTP/1.1 200 OK 响应,表明每个消费者的请求均未超过阈值。
如果你在同一秒内作为任一消费者发送更多请求,你应该会收到一个 HTTP/1.1 429 Too Many Requests 响应。
这验证了插件是根据变量组合 remote_addr 和 consumer_name 进行速率限制的。
在 Redis 中存储漏桶状态
以下示例展示如何在 Redis 中存储 limit-req 漏桶状态,并查看已存储的哈希和 TTL。
本示例使用 Docker,将运行中的网关容器连接到受密码保护的 Redis 服务器。该容器应在本地主机上公开 Admin API 端口 9180 和代理端口 9080。开始之前,导出网关容器名和 Admin API Key:
export GATEWAY_CONTAINER="replace-with-gateway-container-name"
export ADMIN_API_KEY="replace-with-admin-api-key"
export REDIS_PASSWORD="redis-password"
export REDIS_DATABASE=1
创建专用网络,连接网关并启动 Redis:
docker network create limit-req-net
docker network connect limit-req-net "$GATEWAY_CONTAINER"
docker run -d \
--name limit-req-redis \
--network limit-req-net \
redis:8.10.2-alpine \
redis-server --requirepass "$REDIS_PASSWORD"
验证 Redis 连接:
docker exec \
-e REDISCLI_AUTH="$REDIS_PASSWORD" \
limit-req-redis \
redis-cli ping
命令应返回 PONG。如果 Redis 仍在启动,请稍等片刻后重复执行。
创建使用 Redis 存储漏桶状态的路由:
curl "http://127.0.0.1:9180/apisix/admin/routes/limit-req-redis" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"uri": "/redis-rate-limit",
"plugins": {
"proxy-rewrite": {
"uri": "/get"
},
"limit-req": {
"rate": 0.1,
"burst": 6,
"key": "remote_addr",
"rejected_code": 429,
"nodelay": true,
"policy": "redis",
"redis_host": "limit-req-redis",
"redis_port": 6379,
"redis_password": "${REDIS_PASSWORD}",
"redis_database": ${REDIS_DATABASE}
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}
EOF
❶ 允许突发七次请求,然后以每十秒一次请求的速率排空漏桶。
❷ 在 Redis 中存储漏桶状态,使其他网关实例可以使用相同状态。
❸ 连接 Redis 容器并选择数据库 1。
使用一个空漏桶,在十秒内从同一地址发送八次请求。七次通过限流器,一次返回 HTTP 429。
for i in 1 2 3 4 5 6 7 8; do
curl -sS -o /dev/null -w '%{http_code}\n' "http://127.0.0.1:9080/redis-rate-limit" &
done
wait
当网关实例使用相同的 Redis 数据库、路由和插件配置,以及相同的解析后客户端键时,它们会共享漏桶。
查看 Redis 漏桶
这项可选验证使用 API7 企业版 3.10.10 和 APISIX 3.21.0 在 info 级别记录的 limit key: 消息。
在生效的 config.yaml 中将 nginx_config.error_log_level 设为 info,然后重新加载 Docker 网关:
docker exec "$GATEWAY_CONTAINER" apisix reload
如果容器使用不同的配置或重载流程,请先按该部署方式应用日志级别改动,再继续。重复请求测试,然后在容器日志中查找最新的键:
docker logs "$GATEWAY_CONTAINER" 2>&1 \
| grep "limit key:" \
| tail -1
复制 limit key: 后面的完整值,只查看对应的 Redis 哈希:
export LIMIT_KEY='COPY_THE_LOGGED_LIMIT_KEY'
docker exec \
-e REDISCLI_AUTH="$REDIS_PASSWORD" \
limit-req-redis \
redis-cli -n "$REDIS_DATABASE" HGETALL "limit_req:${LIMIT_KEY}"
docker exec \
-e REDISCLI_AUTH="$REDIS_PASSWORD" \
limit-req-redis \
redis-cli -n "$REDIS_DATABASE" TTL "limit_req:${LIMIT_KEY}"
哈希包含 excess 和 last。每次获准通过的请求都会将 TTL 刷新为 61 秒。被拒绝的请求不会改变过期时间。要重复测试,请等到 TTL 返回 -2。
如需清除过时的键,先确认部署、网关版本和 Redis 数据库,再删除该确切键。
对于 ADC 或 Ingress Controller,将相同的插件字段应用到远程地址示例,并使用每个网关实例均可访问的 Redis 地址。
测试完成后,在 config.yaml 中恢复之前的 nginx_config.error_log_level 值,并重新加载网关:
docker exec "$GATEWAY_CONTAINER" apisix reload
然后删除路由、Redis 容器和专用网络:
curl "http://127.0.0.1:9180/apisix/admin/routes/limit-req-redis" -X DELETE \
-H "X-API-KEY: ${ADMIN_API_KEY}"
docker rm -f limit-req-redis
docker network disconnect limit-req-net "$GATEWAY_CONTAINER"
docker network rm limit-req-net