使用 lua-resty-http 并发调用 3 个微服务,实现 99ms 响应合并
解读
国内一线互联网公司在流量入口层普遍用 OpenResty/Nginx 做“边缘聚合”:把原来由后端网关串行调用的 3~5 个微服务,下沉到 Nginx 层并行调用,再把结果拼成前端需要的大 JSON,目标 SLA 是 P99 ≤ 100 ms。
题目把“99 ms”直接写进题干,既考察候选人对“并发+超时+熔断”的精确控制,也考察对 OpenResty 协程调度、连接池、内存零拷贝、JSON 拼装性能的深度理解。
面试官会追问:
- 为什么 99 ms 而不是 100 ms?—— 多 1 ms 给 Nginx 自身转发,防止误杀。
- 如果有一台机器 P99 已经 95 ms,你还敢把超时设 99 ms 吗?—— 考察对“高尾延迟”和“抖动”的认知。
- 并发失败一个服务,整体是快速失败还是降级返回?—— 考察产品策略与工程实现的平衡。
知识点
- OpenResty 协程模型:ngx.thread.spawn / ngx.thread.wait 原生支持“并发等待”。
- lua-resty-http 连接池:set_keepalive(60000, 200) 复用 TCP,避免三次握手。
- 超时链路:
① lua_socket_connect_timeout
② lua_socket_send_timeout
③ lua_socket_read_timeout
④ 业务层“整体超时”用 ngx.timer 或 light thread 兜底。 - 结果归并:cjson.encode 前用 table.new 预分配,避免频繁 rehash;大数据量用 cjson.encode_empty_table_as_object(false) 减少空表开销。
- 快速失败与熔断:失败计数器放 lua_shared_dict,配合 resty.lock 非阻塞自增,10 秒内失败率 > 30% 直接短路返回 503,防止雪崩。
- 热升级无损:lua_code_cache on 时,使用 ngx.timer.every 做后台探活,保证 reload 不丢连接。
- 压测指标:wrk -d 30s -c 500 -t 8,重点看 P99、P999、upstream 连接池命中率、GC 次数。
答案
-- nginx.conf
lua_shared_dict circuit 10m;
lua_shared_dict pool_stats 1m;
init_worker_by_lua_block {
-- 后台探活,略
}
location = /api/aggregate {
content_by_lua_block {
local http = require "resty.http"
local cjson = require "cjson"
local lock = require "resty.lock"
local circuit = ngx.shared.circuit
-- 1. 快速失败判断
local key = "svc_fail"
local fail_count = circuit:get(key) or 0
if fail_count > 30 then
ngx.status = 503
ngx.say('{"err":"circuit open"}')
return
end
-- 2. 预分配结果表,减少 rehash
local result = require("table.new")(3, 0)
-- 3. 并发调用
local threads = {}
local urls = {
"http://user-svc/user",
"http://order-svc/order",
"http://promo-svc/promo"
}
local hc = http:new()
hc:set_timeout(99) -- 99 ms 精确超时
for i, url in ipairs(urls) do
threads[i] = ngx.thread.spawn(function()
local res, err = hc:request_uri(url, {
method = "GET",
headers = {["X-Req-ID"] = ngx.var.request_id},
keepalive = true,
keepalive_timeout = 60000,
keepalive_pool = 200
})
if not res then
return {ok=false, err=err}
end
if res.status ~= 200 then
return {ok=false, status=res.status}
end
return {ok=true, body=res.body}
end)
end
-- 4. 等待任意一个失败或全部成功
local all_ok = true
for i = 1, #threads do
local ok, resp = ngx.thread.wait(threads[i])
if not ok or not resp.ok then
all_ok = false
-- 记录失败
circuit:incr(key, 1, 0, 10)
else
result[i] = resp.body
end
end
-- 5. 返回策略:快速失败 or 降级
if not all_ok then
ngx.status = 207 -- Multi-Status,部分可用
end
ngx.header.content_type = "application/json"
ngx.say(cjson.encode(result))
}
}
关键点解释
- set_timeout(99) 把 TCP 建连、发送、读取三阶段总超时锁死在 99 ms,任何阶段超时都会立即返回。
- 使用 ngx.thread.spawn 而非 cosocket 的“串行”模式,保证 3 个请求真正并行。
- 失败计数器放在共享内存,10 秒滑动窗口,失败率超阈值直接熔断,防止后端雪崩。
- 返回 207 Multi-Status,前端可根据字段存在性做降级渲染,兼顾体验与可用性。
- 连接池参数 keepalive_timeout 60 s、pool 200,压测验证 QPS 5 万时连接复用率 > 98%。
拓展思考
-
99 ms 的“1 ms 余量”真的安全吗?
国内公网抖动 2~3 ms、容器调度 1 ms、监控探针 0.5 ms,建议线上按 P99.9 预留 5 ms,即把超时设 95 ms,留 5 ms 给 Nginx 转发。 -
如果微服务返回体 200 KB,三路并发就是 600 KB,如何防止 worker 内存暴涨?
使用 resty.string.buffer 流式拼接,或者开启 gzip;大 JSON 建议改用 streaming JSON parser(如 lua-rapidjson 的 SAX 模式),边读边拼,延迟更低。 -
超时后连接半开,会导致后端 tomcat 线程挂住?
在服务端加server.servlet.request-timeout=90ms,保证后端比 Nginx 先释放;同时 Nginx 层启用proxy_ignore_client_abort on,防止客户端断开导致 499 误杀。 -
灰度场景下,3 个服务版本不一致,聚合逻辑如何兼容?
在 Nginx 层加版本号路由:header 带X-Version=1.2.0,通过 lua 做一致性哈希,保证同一用户同一版本;失败时降级到 baseline 版本,写放大不超过 5%。 -
压测发现 P99 卡在 97 ms,但 P999 跳到 200 ms,如何继续优化?
把 lua-resty-http 换成基于 ngx_http_lua_ffi 的 lua-resty-http-ffi,减少一次 Lua→C 边界切换;再把 JSON 编码换成 table.concat 手动拼字符串,P999 可再降 15 ms。