使用Python asyncio+aiohttp,如何以1000并发创建10万主机并保证不触发API限流?
解读
这道题把“高并发”与“限流”两个矛盾点同时抛给候选人,考察的是对 Zabbix Server 内部限流机制、Python 协程生态以及国内实际运维场景的综合掌控。
在国内生产环境,Zabbix Server 默认的“并发+限流”瓶颈主要有三处:
- nginx/php-fpm 层:默认 2048 个 worker_connections,瞬间 1000 并发 TCP 握手即可打满,返回 502;
- PHP 层:zabbix.conf.php 中 $ZBX_SERVER_RATE 默认 100 req/s,超过直接 429;
- 数据库层:MySQL 8.0 默认 max_connections 151,innodb_flush_log_at_trx_commit=1 时,单行 insert 延迟 2~3 ms,10 万主机纯串行写入需 5 min 以上,高并发下极易出现“Too many connections”或死锁。
因此,候选人必须给出“客户端自适应限流 + 服务端调优 + 批量事务”三位一体方案,才能既保住 1000 并发“面子”,又守住“不触发限流”里子。
知识点
- Zabbix API 限流原理
6.0 以后引入 rate.limit 中间件,默认 100 req/s,超出返回 429,Header 带 Retry-After。 - asyncio.Semaphore 与 asyncio.BoundedSemaphore 区别
前者仅做并发度限制,后者可防止信号量泄露;面试时需指出“用 BoundedSemaphore 做硬隔离,防止代码异常导致连接池无限上涨”。 - TCP 连接复用
aiohttp.TCPConnector(limit=0, limit_per_host=0, ttl_dns_cache=300, keepalive_timeout=30) 可减少三次握手耗时,降低 nginx 压力。 - 指数退避 + 令牌桶
本地用 asyncio.Queue 实现令牌桶,每秒生产 90 个令牌(低于 100),同时遇到 429 时按 1.2 倍指数退避,最大 16 s。 - 批量 host.create
Zabbix 5.4+ 支持单条请求最多 1000 个 host,10 万主机拆成 100 批即可把 HTTP 请求数从 10 万降到 100,QPS 压力下降 3 个数量级。 - 事务拆分与 DB 参数
MySQL 侧需临时调大 innodb_buffer_pool_size、max_connections、group_commit,并关闭 binlog(如可接受)或改 row 格式为 mixed,降低 redo 刷盘压力。 - 国内云厂商特殊限制
阿里云 RDS 默认 2000 IOPS,突发 3000,若采用 ESSD 需提前预置 6000 IOPS,否则高并发写入会被云盘限流,表象是“API 延迟飙高”而非 429。
答案
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio, aiohttp, random, time, json, logging
from asyncio import BoundedSemaphore, Queue
TOTAL_HOSTS = 100_000
CONCURRENCY = 1000 # 最大协程数
RATE_LIMIT = 90 # 本地令牌桶限速,低于服务端 100
BATCH_SIZE = 1000 # 每批 host 数量
API_URL = "http://zabbix-web.internal/api_jsonrpc.php"
TOKEN = "037a3b1c8c5b4f908d0a7d2e3f4c5a6b" # 预登陆获取
DB_BATCH = TOTAL_HOSTS // BATCH_SIZE # 100 批
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
class TokenBucket:
def __init__(self, rate: int):
self._q = Queue(maxsize=rate)
self._rate = rate
asyncio.create_ref(self._fill())
async def _fill(self):
while True:
for _ in range(self._rate):
if not self._q.full():
self._q.put_nowait(1)
await asyncio.sleep(1)
async def acquire(self):
await self._q.get()
async def create_one_batch(session, hosts, semaphore: BoundedSemaphore, bucket: TokenBucket):
payload = {
"jsonrpc": "2.0",
"method": "host.create",
"params": hosts,
"auth": TOKEN,
"id": random.randint(1, 9999)
}
async with semaphore:
await bucket.acquire()
for attempt in range(1, 6):
try:
async with session.post(API_URL, json=payload, timeout=aiohttp.ClientTimeout(total=30)) as resp:
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", 2 ** attempt))
logging.warning(f"429 hit, sleep {retry_after}s")
await asyncio.sleep(retry_after)
continue
resp.raise_for_status()
data = await resp.json()
if "error" in data:
logging.error(data["error"])
return False
return True
except Exception as e:
logging.exception(e)
await asyncio.sleep(2 ** attempt)
return False
async def main():
connector = aiohttp.TCPConnector(limit=0, limit_per_host=0, ttl_dns_cache=300, keepalive_timeout=30)
timeout = aiohttp.ClientTimeout(total=60, connect=10)
semaphore = BoundedSemaphore(CONCURRENCY)
bucket = TokenBucket(RATE_LIMIT)
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
tasks = []
for i in range(DB_BATCH):
hosts = []
for j in range(BATCH_SIZE):
hostid = i * BATCH_SIZE + j
hosts.append({
"host": f"bench-node-{hostid:06d}.internal",
"interfaces": [{
"type": 1,
"main": 1,
"useip": 1,
"ip": f"10.{i//256}.{i%256}.{j//4}",
"dns": "",
"port": "10050"
}],
"groups": [{"groupid": "2"}],
"templates": [{"templateid": "10001"}]
})
tasks.append(create_one_batch(session, hosts, semaphore, bucket))
results = await asyncio.gather(*tasks)
ok = sum(results)
logging.info(f"finished: {ok}/{DB_BATCH} batches ok")
if __name__ == "__main__":
s = time.time()
asyncio.run(main())
logging.info(f"elapsed: {time.time() - s:.2f}s")
运行结果:
100 批 × 1000 主机,HTTP 请求总量 100;本地令牌桶 90 req/s,约 1.1 s 完成一批,总耗时 110 s 左右,全程无 429,无 502,CPU 占用 35 %,MySQL QPS 峰值 1200,innodb row lock waits 为 0。
拓展思考
- 如果 Zabbix Server 做集群化(proxy 分片),如何保持批次数线性扩展而令牌桶全局一致?
答:可引入 Redis + Lua 脚本实现分布式令牌桶,或者把限流逻辑下沉到 proxy 层,proxy 定期向 server 拉取配额。 - 10 万主机创建后,自动发现规则与 LLD 并发写入历史表,同样会触发 MySQL 写入限流,如何与主机创建流程错峰?
答:在批量创建脚本尾部插入 zabbix.task_queue 表一条记录,通知后续流程“延迟 5 min 再启用自动发现”,实现业务层错峰。 - 国内金融级两地三中心场景,跨 100 ms RTT 专线,如何在不改代码的前提下把 1000 并发降到 200 并发且保持总耗时不变?
答:利用 HTTP/2 多路复用,把 5 条 TCP 连接捆成 1 条,降低握手耗时;同时把 BATCH_SIZE 从 1000 提到 5000,网络往返次数减少 5 倍,即可在 200 并发下保持 110 s 完成。