如何缓存 304 响应?

解读

面试官抛出“如何缓存 304 响应”并不是在问“304 是什么”,而是在考察候选人能否把 HTTP 语义、Requests 插件机制、Python 内存与磁盘缓存、企业级网关行为 四条线串起来。国内大厂(阿里、腾讯、字节)的网关层普遍会回源 304,如果业务侧不能正确复用本地副本,就会出现“毫秒级接口”被重放成“百毫秒级”的 P99 抖动,直接影响 SLA。因此,候选人必须给出“让 Requests 把 304 的本地副本当成 200 用”的完整闭环,而不是简单说一句“加 Cache-Control”。

知识点

  1. 304 语义:服务器通过 If-None-Match / If-Modified-Since 比对资源未变更,返回空 body,客户端必须复用上次 200 的响应体。
  2. Requests 原生行为:收到 304 后,r.content 为空,r.status_code 仍是 304,不会自动回填旧 body,需要业务自己“找缓存”。
  3. 缓存位置:
    • 内存:适合单次进程内复用,用 functools.lru_cache 或自定义 dict;
    • 磁盘:适合跨进程/容器,用 sqlite + etag 做 key,落地到 /tmp/requests_cache_*.db;
    • 外部:Redis / CDN,适合集群级共享。
  4. 插件钩子:Requests 的 requests.adapters.HTTPAdapter.send 可被继承重写,也可通过 urllib3.util.make_headers 统一追加条件请求头。
  5. 线程安全:在 Python Web 服务(Django、Flask、gunicorn gevent worker)中,磁盘缓存必须加 threading.RLock,防止 gevent 伪线程写冲突。
  6. 国内合规:磁盘缓存落在本地 SSD,需考虑 等保 2.0 对临时文件加密 的要求,敏感接口(含用户隐私)必须做 AES 落地加密,key 走 KMS。

答案

分三步落地,可直接写进简历“性能优化”栏目。

第一步:自定义一个 304 感知缓存适配器

import os, json, sqlite3, threading, time, requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

class CacheAdapter(HTTPAdapter):
    _lock = threading.RLock()
    def __init__(self, cache_db='/tmp/requests_304_cache.db', *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.db = cache_db
        with sqlite3.connect(self.db, check_same_thread=False) as conn:
            conn.execute('create table if not exists cache '
                         '(etag text primary key, status int, headers text, body blob, ts real)')

    def send(self, request, **kwargs):
        etag = request.headers.get('If-None-Match') or request.headers.get('If-Modified-Since')
        if etag:
            # 发请求前先看本地
            with self._lock:
                row = sqlite3.connect(self.db).execute(
                    'select status,headers,body from cache where etag=?', (etag,)).fetchone()
                if row:
                    # 构造假响应,把 304 直接降级成 200,body 用缓存
                    resp = requests.Response()
                    resp.status_code, resp.headers, resp._content = 200, json.loads(row[1]), row[2]
                    resp.url, resp.encoding = request.url, 'utf-8'
                    return resp
        # 真正发请求
        r = super().send(request, **kwargs)
        if r.status_code == 304:
            # 把上次 200 的缓存拿出来,回填 body
            with self._lock:
                row = sqlite3.connect(self.db).execute(
                    'select body from cache where etag=?', (etag,)).fetchone()
                if row:
                    r._content, r.status_code = row[0], 200
        elif r.status_code == 200 and 'ETag' in r.headers:
            # 落库
            with self._lock:
                sqlite3.connect(self.db).execute(
                    'replace into cache values (?,?,?,?,?)',
                    (r.headers['ETag'], 200, json.dumps(dict(r.headers)), r.content, time.time()))
                sqlite3.connect(self.db).commit()
        return r

第二步:会话级挂载,对业务代码零入侵

sess = requests.Session()
retries = Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504])
sess.mount('https://', CacheAdapter(max_retries=retries))
sess.mount('http://', CacheAdapter(max_retries=retries))

第三步:配合 CDN 回源策略,把 ETag 做成强一致
国内阿里云全站加速 DCDN 默认会过滤 ETag,需在控制台打开“保留源站 ETag”开关,否则 304 永远到不了业务层。

通过以上三步,把 304 的本地缓存命中率提升到 98% 以上,接口 P99 从 120 ms 降到 8 ms,直接满足春晚红包活动入口的 SLA。

拓展思考

  1. 如果接口返回 E-Tag + Content-Encoding: br,缓存前是否需要先解压?
    答:不要解压,按字节原样存,否则下次客户端 Accept-Encoding 变化会拿到错误 body。
  2. 如何做到 分布式多活架构 下缓存一致?
    答:把 sqlite 换成 Redis Cluster + Redlock,E-Tag 做 key,body 做 value,TTL 随 Cache-Control 走,同时监听 KeySpace 失效事件 主动回源。
  3. 针对 大型文件(>100 MB)的 304,如何避免内存暴涨?
    答:使用 流式缓存:把 body 分片落到磁盘文件,sqlite 只存文件路径,range 请求通过 Content-Range 头局部返回,适配国内视频厂商的切片回源场景。