翻译 API 失败降级策略

解读

在国内一线互联网公司的 Lua 面试中,这道题表面问“翻译 API 失败降级”,实则考察候选人三点:

  1. 对“外部依赖失败”的敏感度和防御式编程习惯;
  2. 能否在 Lua 运行时(通常是宿主 C/C++ 程序)里用最小成本做“可观测、可回滚、可灰度”的兜底;
  3. 对性能、内存、GC 压力、热更兼容性的权衡。
    面试官期望你给出一条“从触发条件→探测→降级→恢复→灰度→监控”的完整闭环,而不是简单 try-catch 返回默认值。

知识点

  1. Lua 错误模型:pcall/xpcall 的栈保护、traceback 钩子、lightfunction 与 C closure 的差异。
  2. 同步/异步边界:Lua 协程 yield 不能跨 C 阻塞调用,翻译 API 如果是 HTTP 必须拆成“异步 IO + 协程轮询”或“C 线程池 + 消息队列”。
  3. 失败探测:超时(毫秒级)、异常(http code≥500)、内容质量(空译文、语种识别置信度 <阈值)、限流(429)。
  4. 降级策略:
    4.1 缓存降级:LRU+TTL 本地表、共享内存(ngx.shared.dict)、Redis 二级缓存、版本号防脏读。
    4.2 规则降级:拼音直译、语种同源透传(en→en)、占位符模板(“[EN]hello[/EN]”)。
    4.3 静默降级:用户无感切换,不弹错误 toast,埋点仅日志。
  5. 恢复机制:指数退避重试、熔断器(失败率 50%→open→half-open→close)、版本号熔断(新 Lua 脚本异常率升高自动回滚到老版本)。
  6. 灰度与热更:使用 skynet sharedata 或 ngx lua 的 lua_code_cache off 做秒级回滚;通过 Consul/Nacos 配置中心下发“降级开关+白名单”。
  7. 可观测:统一日志格式(时间戳|uid|scene|src_lang|dst_lang|api_latency|http_code|降级类型|回包大小),对接阿里云 SLS/Prometheus,关键指标:降级率、缓存命中率、GC 停顿。
  8. 性能红线:降级路径必须 100% 避免内存泄漏(循环引用、closure upvalue)、避免在热路径创建新 table;单次降级查询平均耗时 <5 ms,P99 <20 ms。

答案

下面给出一套可直接落地到“基于 OpenResty 的 Lua 网关层”的参考实现,兼顾“失败判定→缓存→降级→熔断→监控”全链路。

-- translate_api.lua
local http = require "resty.http"
local cjson = require "cjson"
local lock = require "resty.lock"
local ffi = require "ffi"

-- 1. 配置项(可从 Nacos 实时拉取)
local CONF = {
    timeout_ms     = 300,
    max_retry      = 2,
    fail_rate_threshold = 0.5,   -- 熔断阈值
    cache_ttl      = 300,        -- 5 分钟
    circuit_open_seconds = 30,
    degrade_phrase = "[翻译服务维护中]",
}

-- 2. 熔断器状态(进程级共享)
local circuit = {
    state = "close",               -- close/open/half
    fail_count = 0,
    total_count = 0,
    last_fail_time = 0,
}

-- 3. 本地 LRU 缓存(每个 worker 一份,避免竞争)
local lrucache = require "resty.lrucache"
local cache, err = lrucache.new(10000)  -- 1 万 key
if not cache then
    ngx.log(ngx.ERR, "create cache failed: ", err)
end

-- 4. 统一日志
local function log_metric(success, latency, degrade_type, src, dst, uid)
    local msg = string.format("%d|%s|%s|%s|%d|%s|%s|%s",
                              ngx.time(), uid or "-", src, dst,
                              latency, success and "1" or "0",
                              degrade_type or "-", ngx.var.bytes_sent or "0")
    ngx.log(ngx.INFO, "translate_metric:", msg)
end

-- 5. 探测+真正调用翻译云 API
local function call_translate_api(text, src, dst)
    local hc = http.new()
    hc:set_timeout(CONF.timeout_ms)
    local ok, err = hc:connect("translate.cloud.api", 443, true)
    if not ok then return nil, "connect:"..err end
    local res, err = hc:request{
        path = "/v2/translate",
        query = {q=text, source=src, target=dst},
        headers = {["Authorization"] = "Bearer " .. os.getenv("TRANSLATE_TOKEN")}
    }
    if not res then return nil, "request:"..err end
    if res.status ~= 200 then return nil, "http"..res.status end
    local body = res:read_body()
    local ok, json = pcall(cjson.decode, body)
    if not ok or not json.data or #json.data == 0 then
        return nil, "invalid_body"
    end
    return json.data[1].translatedText, nil
end

-- 6. 缓存封装(带互斥锁,防止雪崩)
local function get_with_cache(key, func, ...)
    local val = cache:get(key)
    if val ~= nil then return val, "hit" end
    local lock_obj, err = lock:new("translate_lock", {timeout=0.1, exptime=1})
    local elapsed, err = lock_obj:lock(key)
    if not elapsed then
        -- 拿不到锁直接降级,避免堆积
        return nil, "lock_fail"
    end
    val = cache:get(key)  -- 双检
    if val ~= nil then
        lock_obj:unlock()
        return val, "hit"
    end
    val, err = func(...)
    if val then
        cache:set(key, val, CONF.cache_ttl)
    end
    lock_obj:unlock()
    return val, err
end

-- 7. 熔断器判断
local function allow_pass()
    local now = ngx.time()
    if circuit.state == "close" then
        return true
    elseif circuit.state == "open" then
        if now - circuit.last_fail_time > CONF.circuit_open_seconds then
            circuit.state = "half"
            circuit.total_count = 0
            circuit.fail_count = 0
            return true
        end
        return false
    else -- half
        return true
    end
end

local function record_result(success)
    circuit.total_count = circuit.total_count + 1
    if not success then
        circuit.fail_count = circuit.fail_count + 1
        circuit.last_fail_time = ngx.time()
    end
    if circuit.state == "half" and circuit.total_count >= 10 then
        local rate = circuit.fail_count / circuit.total_count
        circuit.state = rate > CONF.fail_rate_threshold and "open" or "close"
    elseif circuit.state == "close" and circuit.total_count >= 50 then
        local rate = circuit.fail_count / circuit.total_count
        if rate > CONF.fail_rate_threshold then
            circuit.state = "open"
        end
        circuit.total_count = 0
        circuit.fail_count = 0
    end
end

-- 8. 对外唯一入口
function _M.translate(text, src, dst, uid)
    local key = table.concat({src, dst, ngx.md5(text)}, ":")
    local start = ngx.now()
    local degrade_type = nil
    local result, err

    -- 8.1 熔断检查
    if not allow_pass() then
        degrade_type = "circuit_open"
        result = CONF.degrade_phrase
        goto DONE
    end

    -- 8.2 缓存+API 调用
    result, err = get_with_cache(key, function()
        local ok, translated
        ok, translated = pcall(call_translate_api, text, src, dst)
        if not ok or not translated then
            return nil, translated or "unknown"
        end
        return translated
    end)

    -- 8.3 失败降级
    if not result then
        degrade_type = "api_fail"
        -- 同源透传
        if src == dst then
            result = text
        else
            result = CONF.degrade_phrase
        end
        record_result(false)
    else
        record_result(true)
    end

    ::DONE::
    local latency = (ngx.now() - start) * 1000
    log_metric(result ~= CONF.degrade_type, latency, degrade_type, src, dst, uid)
    return result, degrade_type
end

要点说明

  1. 全程使用 pcall 保护 C 边界,防止任何异常穿透到 nginx worker。
  2. 采用“本地 LRU + 分布式锁”二级策略,既防止缓存雪崩,又保证同一 key 在并发场景下只穿透一次。
  3. 熔断器状态放在 Lua 模块级 table,天然 worker 间隔离,避免共享内存锁竞争;对绝大多数场景已够用,如需跨机器可改 Redis sliding window。
  4. 降级文案可动态配置,支持同源透传、拼音、模板等多种策略,通过 Nacos 监听秒级生效,满足国内游戏发版“白天高峰不敢重启”的痛点。
  5. 日志格式与阿里 SLS 索引对齐,方便后续做 Grafana 大盘;同时把“降级类型”字段透出,可快速定位是网络超时还是云厂商限流。

拓展思考

  1. 多活架构:如果翻译云厂商在上海和深圳均有 endpoint,如何在 Lua 里做“地域亲和 + 失败切换”?提示:用 dns 轮询表+health check 协程,把结果写入 ngx.shared.health,每次 translate 优先选 healthy 节点。
  2. 质量降级:当 API 返回的译文置信度低于阈值,可触发“半自动降级”——先给用户展示,后台异步重新翻译并替换缓存;需要协程+定时器+版本号 CAS。
  3. 大文本切片:游戏公告经常一次 2 k 汉字,翻译 API 有 500 字符上限。如何在 Lua 里做“按句子切片→并发翻译→合并回包”,同时保证失败只重试失败段?
  4. 合规场景:国内出海游戏必须满足 GDPR 和 PIPL,翻译文本可能含 uid/手机号。降级路径里若走本地缓存,需先做“脱敏哈希”,如何设计不可逆加盐哈希且保证同一原文同一 salt?
  5. 性能极限:在 8 核 OpenResty 上,目标 5 w qps,降级路径 P99 20 ms。压测发现即使 LRU hit 也偶发 30 ms+,经 perf 发现是 GC 标记阶段 stw。如何针对 Lua GC 调优?(提示:减少 table 创建、重用 closure、把热点 key 预置在模块表,降低 mark 阶段工作量。)

把以上五点想透,基本可以在国内任意大厂或游戏公司的 Lua 面试中拿到“超出预期”评级。