在连接级别统一设置 `retry_strategy` 的 `urllib3` 参数

解读

国内互联网公司普遍把 Airflow 部署在私有 Kubernetes 集群或阿里云 ACK 上,任务里大量用到 HttpOperator、SimpleHttpOperator 或自研的 PythonOperator 去回调内部 REST 网关。一旦网关做了灰度发布或弹性缩容,瞬时 502/503 非常常见,因此必须在“连接”层面统一做重试,而不是每个 DAG 里写一堆 retry 代码。
面试时,面试官真正想考察的是:

  1. 你知不知道 Airflow 的 Connection 对象只能存 extra 这一坨 JSON;
  2. 你能否把 urllib3.Retry 的构造参数序列化成可 JSON 序列化的字典;
  3. 你是否理解 requests 的 HTTPAdapter 初始化时机,并能在 Hook 里把重试策略注入进去;
  4. 你是否能把这套方案做成插件化,让全公司 200+ 团队无感使用。

知识点

  • Airflow Connection 的 extra 字段本质是一个 TEXT 列,Airflow 2.3+ 以后支持 JSON 校验,但不会自动反序列化复杂 Python 对象。
  • urllib3.Retry 构造参数里 method_whitelist 在 1.26+ 改名为 allowed_methods,写错会直接抛 TypeError,导致任务失败。
  • HttpHook 在 get_conn() 时才会实例化 requests.Session,因此必须在 HttpHook.__init__ 或自定义的 BaseHook.get_connection 返回之前把 Retry 策略塞进 adapters['http'] 与 adapters['https']。
  • 国内云厂商的内网 SLB 对并发连接数有限制,如果 total 重试次数过大,会把 SLB 的会话表打爆,因此需要把 backoff_factor 设成 0.3~0.6 之间,并加 respect_retry_after_header=True。
  • 从 Airflow 2.5 开始,extra 里允许使用 jinja2 宏(如 {{ conn.conn_id }}),但 Retry 参数必须是静态可 JSON 序列化的,不能出现 Python 的 set 或 tuple。

答案

  1. 在 Airflow WebUI → Admin → Connections 里新建一条 http 类型连接,
    Conn Id 填 internal_gateway,
    Host 填 http://gateway.company.local,
    Extra 字段写:

    {
      "retry_strategy": {
        "total": 5,
        "backoff_factor": 0.4,
        "status_forcelist": [502, 503, 504],
        "allowed_methods": ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE", "POST"],
        "respect_retry_after_header": true
      }
    }
    
  2. 自定义一个 InternalHttpHook,继承 HttpHook,重写 get_conn:

    from airflow.providers.http.hooks.http import HttpHook
    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    import json
    
    class InternalHttpHook(HttpHook):
        def get_conn(self, headers=None):
            session = super().get_conn(headers)
            extra = self.get_connection(self.http_conn_id).extra_dejson
            retry_cfg = extra.get("retry_strategy", {})
            if retry_cfg:
                retry = Retry(**retry_cfg)
                adapter = HTTPAdapter(max_retries=retry)
                session.mount("http://", adapter)
                session.mount("https://", adapter)
            return session
    
  3. 在 DAG 里使用:

    from airflow.providers.http.operators.http import SimpleHttpOperator
    from internal_hooks import InternalHttpHook
    
    task = SimpleHttpOperator(
        task_id='call_gateway',
        method='POST',
        endpoint='/api/v1/etl/callback',
        http_conn_id='internal_gateway',
        hook=InternalHttpHook(http_conn_id='internal_gateway'),
        data=json.dumps({"batch_id": "{{ ds_nodash }}"}),
        headers={"Content-Type": "application/json"},
        dag=dag
    )
    
  4. 上线前用 airflow tasks test 把网关 Pod 手动缩容到 0,确认任务日志里出现
    Retrying (Retry(total=4, connect=5, read=5, redirect=5, status=4))
    即证明重试策略生效。

拓展思考

  • 如果公司同时存在内网 http 与外网 https 两种出口,可以把 retry_strategy 拆成 retry_strategy_internal 与 retry_strategy_external,在 Hook 里根据 self.base_url 的 hostname 后缀自动选择,避免把外网 429 误当成 503 重试。
  • 对于** MLOps 场景中调用 Kubeflow Pipelines API,可以把 total 调到 8,并加 raise_on_status=False,让 404 也重试,因为 KFP 的缓存控制器偶尔会出现最终一致性**延迟。
  • 在金融公司里,审计要求所有外部调用必须记录 request_id 与 retry_count,可以在 InternalHttpHook 里重写 send_and_receive,把 urllib3.util.retry.history 里的元数据打印到 task log,再通过公司的 ELK 采集,方便后续监管报表回溯。