---

title: Cache-Control 扩展:stale-while-revalidate 与 stale-if-error 的容错与性能

keywords:

  • stale-while-revalidate
  • stale-if-error
  • Cache-Control
  • CDN
  • TTL

description: 介绍 Cache-Control 的扩展指令 stale-while-revalidate/stale-if-error 的语义与部署策略,结合

CDN 与客户端缓存实现更好的可用性与性能,并给出示例与参考。

categories:

  • 文章资讯
  • 技术教程

---

概述

stale-while-revalidate 允许在资源过期后的一段时间内继续使用过期副本,同时后台刷新;stale-if-error 允许在源站错误时回退到过期副本。两者与标准 max-age/s-maxage 协作,提升稳定性与用户体验。

示例与用法

Cache-Control: public, max-age=300, stale-while-revalidate=600, stale-if-error=86400

CDN 配置(示意)

# 源站响应头携带 SWR/SIE;CDN 遵循并在边缘刷新

Service Worker 模式(简化 SWR)

self.addEventListener('fetch', event => {
  event.respondWith((async () => {
    const cache = await caches.open('v1')
    const cached = await cache.match(event.request)
    const networkPromise = fetch(event.request).then(resp => {
      cache.put(event.request, resp.clone()); return resp
    }).catch(() => cached)
    return cached || networkPromise
  })())
})

工程建议

  • 端到端一致:在源站与 CDN 保持一致策略;对动态资源谨慎使用。
  • TTL 选择:根据资源变更频率确定合理窗口;监控回退命中率与错误率。
  • 兼容与观察:不是所有中间层都支持扩展指令;通过 Cache-Status 观察缓存行为。

参考与验证

  • RFC 5861 HTTP Cache-Control Extensions:https://www.rfc-editor.org/rfc/rfc5861
  • MDN Cache-Control 扩展文档:https://developer.mozilla.org/docs/Web/HTTP/Headers/Cache-Control#extensions
  • Fastly/Cloudflare 文档(SWR/SIE 支持):https://developer.fastly.com/;https://developers.cloudflare.com/cache/

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部