You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Service Worker缓存异常:CloudFront/S3资源缓存体积过大求助

Service Worker Cache API 缓存体积异常问题排查思路

问题现象

  • 自有源或localhost环境下,缓存mui.css文件体积正常(约8KB)
  • 将文件迁移至CloudFront/S3后,该文件缓存体积异常波动,在3MB-12MB之间
  • 缓存全部资源时,总缓存体积甚至达到600MB-1GB

对应的Service Worker fetch逻辑代码:

self.addEventListener('fetch', (event) => {

  if (event.request.url === 'https://MyCloudfront.cloudfront.net/api_uploads/vmRevolution/css/mui.css') {  
  // ---> Cache size will be 3MB -12MB
  // if (event.request.url === 'https://myDomain.example/api_uploads/vmRevolution/css/mui.css') {  
  // ---> cache size will be 8Kb
  // if (event.request.url === 'https://localhost/api_uploads/vmRevolution/css/mui.css') {  
  // ---> cache size will be 8Kb
    showLog('file cache');  
    event.respondWith(  
      caches.match(event.request).then((cachedResponse) => {  
        if (cachedResponse) {  
          return cachedResponse;  
        }  
        return caches.open(RUNTIME).then((cache) => fetch(event.request).then((response) =>  
        
          // Put a copy of the response in the runtime cache.  
          cache.put(event.request, response.clone()).then(() => response)));  
      })  
    );  
  }  
})

解决思路

1. 验证CloudFront/S3返回的响应内容与编码

  • 对比自有源和CloudFront返回的响应:使用curl分别请求两个地址,保存响应文件后对比大小和内容,确认CloudFront是否返回了重复内容、错误页或额外数据
  • 检查响应头的Content-Encoding和Content-Length:确认CloudFront是否正确处理了压缩(比如gzip/brotli),避免缓存未解码的原始流或未压缩的大体积内容

2. 排查Service Worker缓存逻辑

  • 增加日志记录response.headers.get('Content-Length'),对比不同环境下的响应长度,确认是响应本身异常还是缓存过程出问题
  • 检查response.clone()的调用是否正常:在异常场景下,是否存在缓存不完整响应流的情况
  • 测试多次请求CloudFront资源的返回大小:如果每次大小都不同,说明CDN/S3的资源本身存在动态生成或配置错误的问题

3. 检查CloudFront配置

  • 禁用分段传输(Range Requests):若开启分段传输,Service Worker可能缓存多个分段响应导致体积膨胀,可在CloudFront行为设置中关闭该选项,或调整SW逻辑处理分段响应
  • 验证缓存策略:确认CloudFront没有缓存异常响应(如5xx错误页、重定向内容),这些内容体积通常远大于正常资源
  • 检查S3对象元数据:确保Content-Type设置为text/css,没有额外的附属元数据或错误配置

4. 调试缓存的实际内容

  • 使用Chrome DevTools的Application > Cache Storage,查看缓存的mui.css内容,确认是否为正常的CSS文件,而非错误页或重复内容
  • 通过代码打印缓存内容:调用caches.open(RUNTIME).then(cache => cache.match('https://MyCloudfront.cloudfront.net/api_uploads/vmRevolution/css/mui.css').then(res => res.text())),对比正常源的内容差异

内容的提问来源于stack exchange,提问作者Gugu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:05:07