设计一个可重试的 HTTP 客户端异常层次结构
解读
在国内一线互联网公司的 Ruby 面试中,这道题表面问“异常层次”,实则考察对网络不可靠性的建模能力、对 Ruby 异常系统的深度理解以及可观测性/可运维性的落地经验。
面试官希望听到:
- 能把“该不该重试”这一业务语义固化到异常类本身,而不是散落在 if/else。
- 能区分瞬态失败(重试有用)与持久态失败(重试浪费钱),并给出可扩展的基类设计。
- 能结合 Ruby 的
Exception#cause链与Net::HTTP原生异常,做到不丢失原始堆栈即可包装。 - 能给出可配置的退避策略(线性、指数、全抖动),并说明如何在异常元数据里携带“已重试次数/下次等待时间”,方便接入公司统一的监控大盘(如 Falcon、Prometheus)。
知识点
- Ruby 异常继承体系:必须继承自
StandardError,避免rescue时误捕获SystemExit。 Net::HTTP异常映射:Net::OpenTimeout、Net::ReadTimeout、SocketError、EOFError、Errno::ECONNRESET等需分别归类。- 可重试语义标记:用
module Retriable作为** mixin**,而非硬编码在基类,避免菱形继承。 - 退避算法:线性退避
delay = base * attempt;指数退避delay = base * 2 ** attempt;全抖动delay = rand(0..base * 2 ** attempt)。 - 可观测性:异常对象携带
request_id、attempt、max_attempts、next_delay,方便日志与监控对齐。 - 线程安全:异常本身无状态,但重试器(RetryHandler)需支持并发场景,如 Sidekiq 多线程。
答案
# 统一命名空间,避免与公司其他 gem 冲突
module HttpClient
# 1. 可重试语义标记
module Retriable
def retriable? = true
end
# 2. 永久失败标记
module NonRetriable
def retriable? = false
end
# 3. 基类,强制携带原始 cause
class HttpError < StandardError
attr_reader :request_info, :attempt, :max_attempts, :next_delay
def initialize(msg = nil, request_info: {}, attempt: 1, max_attempts: 3, next_delay: 0, cause: nil)
super(msg)
@request_info = request_info
@attempt = attempt
@max_attempts = max_attempts
@next_delay = next_delay
@cause = cause
set_backtrace(cause.backtrace) if cause && backtrace.empty?
end
end
# 4. 瞬态网络失败,可重试
class TimeoutError < HttpError
include Retriable
end
class ConnectionFailed < HttpError
include Retriable
end
# 5. 业务语义失败,永久不重试
class ClientError < HttpError
include NonRetriable # 4xx
end
class ServerError < HttpError
include Retriable # 5xx,但可细化
end
# 6. 重试器,与异常层次解耦
class RetryHandler
DEFAULT_STRATEGY = ->(attempt) { 2 ** attempt }
def initialize(max_attempts: 3, strategy: DEFAULT_STRATEGY)
@max_attempts = max_attempts
@strategy = strategy
end
def with_retry(request_info = {})
attempt = 0
begin
attempt += 1
yield
rescue HttpError => e
raise e unless e.retriable? && attempt < @max_attempts
delay = @strategy.call(attempt)
e.next_delay = delay
sleep delay
retry
end
end
end
end
# 7. 使用示例
client = HttpClient::RetryHandler.new(max_attempts: 5, strategy: ->(n){ rand(0..2**n) })
client.with_retry(path: "/payments") do
Net::HTTP.get(URI("https://api.xxx.com/payments"))
rescue Net::OpenTimeout => e
raise HttpClient::TimeoutError.new("open timeout", request_info: {path: "/payments"}, cause: e)
end
拓展思考
-
如何与 Rails 自动加载机制共存?
把异常文件放在app/errors/http_client/目录,并遵循 Zeitwerk 命名约定,可避免生产环境autoload失败。 -
如何支持熔断?
在RetryHandler里注入CircuitBreaker实例,当连续失败次数超过阈值,直接抛出CircuitOpenError(标记为NonRetriable),防止雪崩。 -
如何对接国内监控?
在HttpError#initialize里发送一条带标签的指标:
StatsD.increment("http_client.error", tags: ["retriable:#{retriable?}", "code:#{response_code}"])
这样 Falcon 可以直接配置告警规则:若retriable: false错误率 > 1%,立即报警。 -
如何支持 GRPC/Thrift?
把HttpError升级为RpcError,再派生GrpcUnavailable(可重试)、GrpcInvalidArgument(不可重试),同一套RetryHandler无需改动。 -
如何防止重试风暴?
在异常元数据里加入jitter_ratio,并在全链路网关(如 Envoy)侧验证x-request-id的退避时间一致性,确保重试漏斗收敛。